// описываем пользовательский объект и его методы //
function valid(){
	this.msgBox = function (str){
		alert(str);
	};
	this.trim = function(str){
		return str.replace(/(^\s+)|(\s+$)/g,"");
	};
	this.validMail = function(str){
		return str.match(/\b(^([\.0-9a-zA-Z_-]+@[0-9a-zA-Z_\.-]+(\.[a-zA-Z]{2,4}){1,2})$)\b/gi);
	};
	this.validNumber = function(str){
		return str.match(/\b(^([0-9]+)$)\b/gi);
	};
	this.openWindow = function(){
		var left= (screen.width / 2) - (arguments[1] / 2);
		var top = (screen.height / 2) - (arguments[2] / 2);
		return window.open(arguments[0], "newWindow","left=" + left + ",top=" + top + ",width=" + arguments[1] + ",height=" + arguments[2] + ",resizable=" + arguments[3] + ",scrollbars=" + arguments[4]);
	};
	this.validInputBox = function(form){
		var count = form.elements.length;
		var bool = false;
		for (i=0; i<count; i++){
			if (form.elements[i].type=='checkbox' && form.elements[i].getAttribute("novalidate")!='1')
				if (form.elements[i].checked)
					bool = true;
		}
		if (bool == false){
			return false;
		}
		return true;
	};
}

	
function getTreeTools(sec_id){
	var obj = new valid();
	obj.openWindow('?mod=tree&action=viewAllUsers&sec_id=' + sec_id,600,600,1,1);
}

function getAddUsers(form){
	var obj = new valid();
	var users = new Array("");
	var i,j = 0;
	if(!obj.validInputBox(form)){
		obj.msgBox("Выберите пользователя");
		return false;
	}
	for (i=0; i<form.elements.length;i++){
		if (form.elements[i].type=='checkbox' && form.elements[i].checked){
			users[j] = form.elements[i].value;
			j++;
		}
	}
	window.opener.document.getElementById("users_list").value = users.join(",");
	window.opener.document.getElementById("label").innerHTML = '(изменен, требуется пересохранение)';
	self.window.close();
}

function getForumReadUsers(forum_id){
	var obj = new valid();
	obj.openWindow('?mod=forum&action=viewAllUsers&sec_id=' + forum_id,600,600,1,1);
}

function getAddForumReadUsers(form){
	var obj = new valid();
	var users = new Array("");
	var i,j = 0;
	if(!obj.validInputBox(form)){
		obj.msgBox("Выберите пользователя");
		return false;
	}
	for (i=0; i<form.elements.length;i++){
		if (form.elements[i].type=='checkbox' && form.elements[i].checked){
			users[j] = form.elements[i].value;
			j++;
		}
	}
	window.opener.document.getElementById("users_read_list").value = users.join(",");
	window.opener.document.getElementById("label").innerHTML = '(изменен, требуется пересохранение)';
	self.window.close();
}

function validateAlNumUnder(e) {
      var re = /[1-9\x0D\x08]/i;
      if (!e || !e.which) {
        var code = event.keyCode;
      }
      else {
        var code = e.which;
      }
      if (!re.test(String.fromCharCode(code))) {
        //alert('Допустим ввод только символом латинского алфавита,\n цифр и знаков: _@.');
        return false;
      }
}


function validateAlNumUnder2(e) {
      var re = /[0-9_a-zA-Z.@\x0D\x08]/i;
      if (!e || !e.which) {
        var code = event.keyCode;
      }
      else {
        var code = e.which;
      }
      if (!re.test(String.fromCharCode(code))) {
        //alert('Допустим ввод только символом латинского алфавита,\n цифр и знаков: _@.');
        return false;
      }
}
function validateBasket(form){
  //var countElem = form['edit_number'].length;
  var countElem = form.length;
  for (i=0; i<countElem; i++){
    //if (form.elements[i].id)
    if((typeof(form.elements[i].id) != "undefined")  && (trim(form.elements[i].id)=='edit_number')){
        if (form.elements[i].value <= 0 || (!form.elements[i].value.match(/\b(^([0-9]+)$)\b/gi))){
          alert('Количество продукта должно быть более нуля');
          return false;
        }
    }
  }
  return true;
}

function openPhoto(product_id) {

if (!parseInt(product_id)) return false;
var width=600;
var height=600;
var left= (screen.width / 2) - (width / 2);
var top = (screen.height / 2) - (height / 2);

if (width>screen.width || height>screen.height)
  wnd = window.open("/shop/photos/" + product_id, "imageWindow",
    "left=" + left + ",top=" + top + ",width=" + width + ",height=" + height +",scrollbars=yes");
else
  wnd = window.open("/shop/photos/" + product_id, "imageWindow",
    "left=" + left + ",top=" + top + ",width=" + width + ",height=" + height);

  return false;
}




function openType(type_id,base_url) {
var width=600;
var height=500;
var left= (screen.width / 2) - (width / 2);
var top = (screen.height / 2) - (height / 2);

if (width>screen.width || height>screen.height)
  wnd = window.open(base_url + "/shop/type/" + type_id, "imageWindow",
    "left=" + left + ",top=" + top + ",width=" + width + ",height=" + height +",scrollbars=yes");
else
  wnd = window.open(base_url + "/shop/type/" + type_id, "imageWindow",
    "left=" + left + ",top=" + top + ",width=" + width + ",height=" + height);

  return false;
}

function openImg(src,width,height) {
var left= (screen.width / 2) - (width / 2);
var top = (screen.height / 2) - (height / 2);

if (width>screen.width || height>screen.height)
  wnd = window.open("", "imageWindow",
    "left=" + left + ",top=" + top + ",width=" + width + ",height=" + height +",scrollbars=yes");
else
  wnd = window.open("", "imageWindow",
    "left=" + left + ",top=" + top + ",width=" + width + ",height=" + height);

  var doc = wnd.document;
  doc.open();
  doc.write('<html><head><title>Увеличенное изображение</title></head>' +
            '<body topmargin="0" leftmargin="0" marginheight="0" marginwidth="0">' +
            '<img onClick=window.close(); style="cursor: hand; cursor: pointer;" alt=Закрыть src="' + src + '" width="' + width + '" height="' + height +
            '">' +
            '<br></body></html>'
            );
  doc.close();
  wnd.focus();
  return false;
}


function sel(elem,url){
  location.href=url + "/shop/" + elem.value;
}

function validate(form){

                  var goodEmail = form['email'].value.match(/\b(^([\.0-9a-zA-Z_-]+@[0-9a-zA-Z_\.-]+(\.[a-zA-Z]{2,4}){1,2})$)\b/gi);

                  if (!goodEmail){
                        alert('Неправельный формат E-mail');
                        return false;
                  }
                  return true;
}

function trim(s){return s.replace(/(^\s+)|(\s+$)/g,"");}

function popup(file,width,height)
{
  window.open(file,"site_path","height="+height+",width="+width+",status=no,location=no,toolbar=no,directories=no,resizable=yes,scrollbars=yes,menubar=no,top=10,left=10");
}

function in_new_window(file,width,height)
{
  window.open(file,"site_path","height="+height+",width="+width+",status=no,location=no,toolbar=no,directories=no,resizable=yes,scrollbars=yes,menubar=no,top=10,left=10");
  return false;
}

function pop_up(file,width,height)
{
  window.open(file,"site_path","menubar=false,height="+height+",width="+width);
}

function makeSiteLink(name) {
  if (!window.js_base_url) {
    str = document.location.toString();
    js_base_url = str.replace("/javascript/editor/scripts/hyperlink.htm","");
    js_base_url = js_base_url.replace("/javascript/editor/scripts/moz/hyperlink.htm","");
  }
  popup(js_base_url+'/admin/index.php?mod=tree&action=mini_browser&returnname='+name,'600','400');
}

function retBack(obj, str) {
  window.close();
  obj.value = str;
}

function insertIntoWYSIWYG(str) {
  doc = "window.opener";
  for ( property in eval(doc) ) {
    fullPropertyName = "document." + property;

    if (fullPropertyName.indexOf("document.myStyle")!=-1) {
      objName = fullPropertyName.replace("document.myStyle", "");
      break;
    }
  }
  objName = eval(doc+".window."+objName);
  objName.insertCustomTag(str);
  self.window.close();
}

function check4compare(obj) {
  for(i=0; i<obj.elements.length; i++) if (obj.elements[i].type=="checkbox" && obj.elements[i].checked) return true;

  alert('Не выделено ни одного продукта для сравнения');
  return false;
}

function switch_loading_box (box_id) {

  if(document.getElementById(box_id).style.display!="none") {
    document.getElementById(box_id).style.display="none";
  }
  else {
    document.getElementById(box_id).style.display="";

    var ie=document.all;
    iebody=document.body;
    var scroll_top=(ie)? iebody.scrollTop : window.pageYOffset;
    var docwidth=(ie)? iebody.clientWidth : window.innerWidth;
    docheight=(ie)? iebody.clientHeight: window.innerHeight;
    var objwidth=document.getElementById(box_id).offsetWidth;
    objheight=document.getElementById(box_id).offsetHeight;
    var test=docwidth/2-objwidth/2+"px";

    document.getElementById(box_id).style.left=docwidth/2-objwidth/2+"px";
    document.getElementById(box_id).style.top=scroll_top+docheight/2-objheight/2+"px";
  }

  return false;

}
/* Navigation */
document.onkeydown = NavigateThrough;
function NavigateThrough (event)
{
	if (!document.getElementById) return;
	if (window.event) event = window.event;
	if (event.ctrlKey)
	{
		var link = null;
		var href = null;
		switch (event.keyCode ? event.keyCode : event.which ? event.which : null)
		{
			case 0x25:
				link = document.getElementById ('NextLink');
				break;
			case 0x27:
				link = document.getElementById ('PrevLink');
				break;
			case 0x26:
				link = document.getElementById ('UpLink');
				break;
			case 0x28:
				link = document.getElementById ('DownLink');
				break;
			case 0x24:
				href = '/';
				break;
		}

		if (link && link.href) document.location = link.href;
		if (href) document.location = href;
	}			
}

/* JS */
function showObject(num) {
  document.getElementById("div"+num).className = 'go_menu';
  document.getElementById("p"+num).className = 'mmm_1';
}

function showObject_01(num) {
    if (document.getElementById("f"+num).className != 'go') {
      document.getElementById("f"+num).className = 'go';
    }
    else {
      document.getElementById("f"+num).className = 'pop_sub';
    }
}

function hideObject(num) {
  document.getElementById("div"+num).className = 'pop_menu';
  document.getElementById("p"+num).className = 'mmm';
}

function subscriber(form) {
  var goodEmail = form['new_subscriber_mail'].value.match(/\b(^([\.0-9a-zA-Z_-]+@[0-9a-zA-Z_\.-]+(\.[a-zA-Z]{2,4}){1,2})$)\b/gi);

  //if (form.new_subscriber_mail.value == "" || form.new_subscriber_mail.value.indexOf('@', 0) == -1) {
    if (!goodEmail){
    document.getElementById("container").className = "mails";
    return false;
  }

  else {
    return true;
  }
}
function flatOver(cl, url)
{
  var i;
  var td;
  for(i=0;i<cl.childNodes.length;i++)
  {
    if(cl.childNodes[i].nodeName == 'TD')
    {
      td = cl.childNodes[i];
      td.style.color = '#333';  
      td.style.background = '#eee';
    }
  }
}
function shows_menu(name) {
	if(document.getElementById(name).style.display!="none")	document.getElementById(name).style.display="none";
	else document.getElementById(name).style.display="";
	return false;
}

function flatOut(cl)
{
  var i;
  var td;

  for(i=0;i<cl.childNodes.length;i++)
  {
    if(cl.childNodes[i].nodeName == 'TD')
    {
      td = cl.childNodes[i];
      td.style.color = '#333';
      td.style.background = 'none';
    }
  }
}
function flatOver(cl) {
	cl.className = 'act';
}
function flatOut(cl) {
	cl.className = '';
}