
isDOM=document.getElementById //DOM1 browser (MSIE 5+, Netscape 6, Opera 5+)
isOpera=isOpera5=window.opera && isDOM //Opera 5+
isOpera6=isOpera && window.print //Opera 6+
isOpera7=isOpera && document.readyState //Opera 7+
isMSIE=document.all && document.all.item && !isOpera //Microsoft Internet Explorer 4+
isMSIE5=isDOM && isMSIE //MSIE 5+
isNetscape4=document.layers //Netscape 4.*
isMozilla=isDOM && navigator.appName=="Netscape" //Mozilla или Netscape 6.*
/* End code */


/* Div scroll by Pimenov Dmitriy */
var timer;
var divWidth = 300;
var divHeight = 90;
var scrollWidth = 0;
var scrollHeight = 0;
var scrollSpeed = 2;
var scrollStep = 10;

if(isNetscape4 || isMozilla)
{
        scrollWidth = 18;
        scrollHeight = 18;
}
else
{
        scrollWidth = 16;
        scrollHeight = 16;
}

/*function myScrollStart(dir)
{
        if(dir == 'up')
        {
                timer=setInterval('myScrollUp()', scrollStep);
        }
        else
        {
                timer=setInterval('myScrollDown()', scrollStep);
        }
}*/

function myScrollStartu(dir)
{
        if(dir == 'left')
        {
                timer=setInterval('myScrollleft()', scrollStep);
        }
        else
        {
                timer=setInterval('myScrollright()', scrollStep);
        }
}
/*
function myScrollUp()
{
        document.getElementById('divscroll').style.width = (divWidth+scrollWidth)+'px';
        document.getElementById('divscroll').style.overflow='auto';
        document.getElementById('divscroll').scrollTop-=scrollSpeed;
}

function myScrollDown()
{
        document.getElementById('divscroll').style.width = (divWidth+scrollWidth)+'px';
        document.getElementById('divscroll').style.overflow='auto';
        document.getElementById('divscroll').scrollTop+=scrollSpeed;
}

function myScrollTop()
{
        document.getElementById('divscroll').style.width = (divWidth+scrollWidth)+'px';
        document.getElementById('divscroll').style.overflow='auto';
        document.getElementById('divscroll').scrollTop=0;
}

function myScrollBottom()
{
        document.getElementById('divscroll').style.width = (divWidth+scrollWidth)+'px';
        document.getElementById('divscroll').style.overflow='auto';
        document.getElementById('divscroll').scrollTop=10000;
}
*/
function myScrollleft()
{
        document.getElementById('divscroll').style.height = (divWidth+scrollHeight)+'px';
       // document.getElementById('divscroll').style.overflow='auto';
        document.getElementById('divscroll').scrollLeft-=scrollSpeed;
}

function myScrollright()
{
        document.getElementById('divscroll').style.height = (divWidth+scrollHeight)+'px';
       // document.getElementById('divscroll').style.overflow='auto';
        document.getElementById('divscroll').scrollLeft+=scrollSpeed;
}

function myScrollLeft()
{
        document.getElementById('divscroll').style.height = (divWidth+scrollHeight)+'px';
       // document.getElementById('divscroll').style.overflow='auto';
        document.getElementById('divscroll').scrollLeft=0;
}

function myScrollRight()
{
        document.getElementById('divscroll').style.height = (divWidth+scrollHeight)+'px';
       // document.getElementById('divscroll').style.overflow='auto';
        document.getElementById('divscroll').scrollLeft=10000;
}

function myScrollClear()
{
        clearInterval(timer);
}
/* End code */














function Changeimg(n){
myimg = new Array("<img src='images/lim1.jpg' alt='' border='0'>","<img src='images/lim1.jpg' alt='' border='0'>","<img src='images/lim2.jpg' alt='' border='0'>","<img src='images/lim3.jpg' alt='' border='0'>","<img src='images/lim4.jpg' alt='' border='0'>","<img src='images/lim5.jpg' alt='' border='0'>","<img src='images/lim6.jpg' alt='' border='0'>","<img src='images/lim7.jpg' alt='' border='0'>","<img src='images/lim8.jpg' alt='' border='0'>","<img src='images/lim9.jpg' alt='' border='0'>");

document.all.imgg.innerHTML=myimg[n];

}


function del_img_tov(){
var oForm = document.forms.formedittov;
if(confirm("Вы уверены что хотите удалить эту картинку?")){
				oForm.submit();
			}
			return false;
		}

function DelGroup(){
			if(confirm("Вы уверены что хотите удалить эту рубрику?")){
				return true;
			}
			return false;
		}

function DelAttrib(){
			if(confirm("Вы уверены что хотите удалить этот атрибут?")){
				return true;
			}
			return false;
		}	
		
function show_podkat(){
var oForm = document.forms.formgroup;
if (oForm.maingroup.value!=''){
	alert("Рубрики нет");
				//return false;
				//document.all.show_podkat.innerHTML='fgbfg'
				}
//oForm.submit();
}


   function openContact(url,name,width,height)
    {
      if (!width) width = 500;
      if (!height) height = 550;
      var w=window.open(url,name,"width="+width+",height="+height+",resizable=1,toolbar=0,location=0,status=0,menubar=0,directories=0,scrollbars=yes,top=0,left=0");
      w.focus();
    };

	function DelTov(){
			if(confirm("Вы уверены что хотите удалить этот товар?")){
				return true;
			}
			return false;
		}	
		
	function CheckFormAddTov(){
				//var oForm = document.forms.formaddtov;	
						
				if (document.getElementById("zag_add_tov").value==''){
					alert("Введите название товара !");
					document.getElementById("zag_add_tov").focus();
					return false;
				}
				/*else if (document.getElementById("anons_tov").value==''){
					alert("Введите анонс товара !");
					document.getElementById("anons_tov").focus();
					return false;
				}*/
				else if (document.getElementById("descr_tov").value==''){
					alert("Введите описание товара !");
					//document.getElementById("descr_tov").focus();
					return false;
				}
		
				return true;
		}		
		
	function CheckFormEditTov(){
				var oForm = document.forms.formedittov;	
						
				if (oForm.zag_edit_tov.value==""){
					alert("Введите название товара !");
					oForm.zag_edit_tov.focus();
					return false;
				}
				/*else if (oForm.anons_edit_tov.value==""){
					alert("Введите анонс товара !");
					oForm.anons_edit_tov.focus();
					return false;
				}*/
				else if (oForm.descr_edit_tov.value==""){
					alert("Введите описание товара !");
					oForm.descr_edit_tov.focus();
					return false;
				}
		
				return true;
		}		


function Save_prav_group_kat(){
     var oForm = document.forms.formgroup;
          oForm.submit();
    }
	

		
		//каталог товаров
		
function AddAtribRub(){
		var n=parseInt(document.all.skolkoatr.value)+1;
		document.all.skolkoatr.value=n;
		//var p=document.all.name[].value;
		//alert(p);
		
		if(n<11){
		
		for (var i = 0; i < n; i++){
d=document.all.Names.innerHTML+"<input style='width:100%;height:18px;' type='text' name='name[]'>";
     
		}
		document.all.Names.innerHTML=d;
		}
		else { 
		alert('Бууу!!!');
		}
		
}
		
		
function DelAtribRub(){
		var n=parseInt(document.all.skolkoatr.value)-1;
		if(n>0){
		document.all.skolkoatr.value=n;
		//alert(document.all.skolkofot.value);
		
		
		document.all.Names.innerHTML="";
		for (var i = 0; i < n; i++){
d=document.all.Names.innerHTML+"<input style='width:100%;height:18px;' type='text' name='name[]'>";
     document.all.Names.innerHTML=d;
		}
		}
		else{
		alert('Бууу!!!');
		}
		
}


function Proverka(){
//var d=document.all.mybody.innerHTML;
//document.all.proverka.innerHTML=d;
//alert(d);
//document.all.proverka.value=d;
//var d=document.getElementById("descr_tov").value;

var d=document.getElementById("wysiwygpole_edit").contentWindow.document.body.innerHTML;
document.all.descr_edit_tov.value=d;
var a=document.all.descr_edit_tov.value;
//alert(a);
document.all.proverka.value=a;
}

function WysiwygAdd(){
var d=document.getElementById("wysiwygpole").contentWindow.document.body.innerHTML;
document.all.descr_tov.value=d;
}

function WysiwygEdit(){
var d=document.getElementById("wysiwygpole_edit").contentWindow.document.body.innerHTML;
document.all.descr_edit_tov.value=d;
}

////////НОВОЕ ДОБАВЛЕНИЕ////////////////////////////////////////////////////////////
var countOfFields = 1; // Текущее число полей
var curFieldNameId = 1; // Уникальное значение для атрибута name
var maxFieldLimit = 5; // Максимальное число возможных полей
function deleteField(a) {
// Получаем доступ к ДИВу, содержащему поле
var contDiv = a.parentNode;
// Удаляем этот ДИВ из DOM-дерева
contDiv.parentNode.removeChild(contDiv);
// Уменьшаем значение текущего числа полей
countOfFields--;
// Возвращаем false, чтобы не было перехода по сслыке
return false;
}
function addField() {
// Проверяем, не достигло ли число полей максимума
if (countOfFields >= maxFieldLimit) {
alert("Число полей достигло своего максимума = " + maxFieldLimit);
return false;
}
// Увеличиваем текущее значение числа полей
countOfFields++;
// Увеличиваем ID
curFieldNameId++;
// Создаем элемент ДИВ
var div = document.createElement("div");
// Добавляем HTML-контент с пом. свойства innerHTML
div.innerHTML = "<input  style=\"width:200px;height:18px;\" name=\"name_" + curFieldNameId + "\" type=\"text\" /> <a onclick=\"return deleteField(this)\" href=\"#\">[X]</a>";
// Добавляем новый узел в конец списка полей
document.getElementById("parentId").appendChild(div);
// Возвращаем false, чтобы не было перехода по сслыке
return false;
} 
///////////////////////////////////////////////////////////////////////////////////

//////////////////////////////////////

var max_files='5';
var h;
var warn_exist_file="Вы уже добавили этот файл!";
function chServer(obj)
{
    document.myform.action=js_server_id[obj.options[obj.selectedIndex].value]+'/index.php';
}
function getexpirydate( nodays){
   var UTCstring;
   Today = new Date();
   nomilli=Date.parse(Today);
   Today.setTime(nomilli+nodays*24*60*60*1000);
   UTCstring = Today.toUTCString();
   return UTCstring;
}
function getcookie(cookiename) {
   var cookiestring=""+document.cookie;
   var index1=cookiestring.indexOf(cookiename);
   if (index1==-1 || cookiename=="") return "";
   var index2=cookiestring.indexOf(';',index1);
   if (index2==-1) index2=cookiestring.length;
   return unescape(cookiestring.substring(index1+cookiename.length+1,index2));
}
function setcookie(name,value)
{
   duration=30;

   cookiestring=name+"="+escape(value)+";EXPIRES="+getexpirydate(duration);
   document.cookie=cookiestring;

}
function delcookie(name)
{
   cookiestring=name+"="+escape('')+";EXPIRES="+getexpirydate(-1);
   document.cookie=cookiestring;
}
function checkUploadFile(obj)
{
   sfile=obj.value;
   sfile=sfile.toLowerCase();
   last=sfile.lastIndexOf('.');
   ext=sfile.substring(last+1);
   filetype="jpg,zip,tif,bmp,jpeg,gif,png,swf,tiff,avi,wmv,mpg,mpeg";
   filetype=filetype.toLowerCase();
   ok=filetype.search(ext.toLowerCase())
   if(ok==-1)
   {
       alert("please upload file with extensions:jpg,zip,tif,bmp,jpeg,gif,png,swf,tiff,avi,wmv,mpg,mpeg!");
       if(obj.type=='file') canContinue=false;
       delInput('idfilespan',obj.id.substring(8));
       return false;
   }
   else
   {
       if(obj.type=='file')
       canContinue=true;
       //return true;
   }
   exist(obj.id,obj.type);
}
function checkUploadZipFile()
{
   var sfile=document.myform.uploadfile.value;
   sfile=sfile.toLowerCase();
   last=sfile.lastIndexOf('.');
   ext=sfile.substring(last+1);
   if(ext!='zip')
   {
      alert("please upload file with extensions:.zip!");
      return false;
   }
   else
   {
      document.myform.submit();
      document.myform.done.disabled=true;
      return true;
   }
}
function calsize(obj,str)
{
    var size=obj.value;
    var unit = 'Байт';
    if(size=='') size=0;
    if(size>1024) { size=size/1024; unit='&#1050;&#1080;&#1083;&#1086;&#1073;&#1072;&#1081;&#1090;'; }
    if(size>1024) { size=size/1024; unit='&#1052;&#1077;&#1075;&#1072;&#1073;&#1072;&#1081;&#1090;'; }
    if(size>1024) { size=size/1024; unit='&#1043;&#1080;&#1075;&#1072;&#1073;&#1072;&#1081;&#1090;'; }
    size = Math.round(size*100)/100;

    document.all[str].innerHTML=size+' '+unit;
}





function ClipBoard(id)
{
	var ccc = MM_findObj(id);
    if (document.all){
	ccc.value = ccc.innerText;
	Copied = ccc.createTextRange();
	Copied.execCommand("Copy");
    }
    else
    {
        alert('Close this box and press \'CTL-c\' to copy');
        ccc.focus();
        ccc.select();
    }
}

function MM_findObj(n, d) { //v4.01
    var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
    if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
    for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
    if(!x && d.getElementById) x=d.getElementById(n); return x;
}
function highlight(id) {
    var field = MM_findObj(id);
	field.focus();
  	field.select();
}
function checkBeforeEmail()
{
   semail=document.emailform.email.value;
   if(semail==''||semail.indexOf('@')==-1)
   {
      alert('please enter a valid email!');
      return false;
   }
   for (var i=0;i<document.emailform.elements.length;i++)
   {
      var e = document.emailform.elements[i];
      if (e.type == 'checkbox' && e.name != 'allbox'&& !e.disabled)
      if(e.checked ==true) return true;
   }
   alert('Please select a image to email!');
   return false;
}

function checkAll()
{
   for (var i=0;i<document.myform.elements.length;i++)
   {
      var e = document.myform.elements[i];
      if (e.type == 'checkbox' && e.name != 'allbox'&& !e.disabled)
      e.checked = document.myform.allbox.checked;
   }
}

function checkAll2()
{
   for (var i=0;i<document.emailform.elements.length;i++)
   {
      var e = document.emailform.elements[i];
      if (e.type == 'checkbox' && e.name != 'allbox'&& !e.disabled)
      e.checked = document.emailform.allbox.checked;
   }
}


function opConfirm(text, conf)
{
    for (var i=0;i<document.myform.elements.length;i++)
    {
       var e = document.myform.elements[i];
       if (e.type == 'checkbox' && e.name != 'allbox' && e.checked == 1 ) {
          if (conf) {
             return confirm(text);
          } else {
             return 1;
          }
       }
    }
    return false;
}
/**
* below is the add/delete unlimited fields
*/

attaIdx=1;
attaNum=1;
IsIE=IsIEBrowser();
canContinue=true;
function IsIEBrowser() {
	if (navigator.userAgent.indexOf("MSIE") != -1 && navigator.userAgent.indexOf("Opera") == -1) {
		return true;
		} else {
		return false;
		}
}
function addItem(pareId,type) {
    if(max_files<=attaNum)
    {
        alert('Max files you can upload in one time is '+max_files);
        return true;
    }
    attaNum++;
    //var upload = document.getElementById("uploadbtn");
    //upload.style.display='block';

       
    var strIndex = "" + attaIdx;
    var attachId = "attachId"+ strIndex;
    var brId = "idAttachBr" + strIndex;
    var delId = "idAttachOper"+ strIndex;

    var jsCode={'event':'onchange','handler':'checkUploadFile(this);'};
    addInputField(pareId,attachId,type,'',jsCode);
    //if(type=='file' && IsIE)
    //document.getElementById( attachId ).click();
    
    if(canContinue==false) {canContinue=true;return false;}

    if(IsIE)
    var jsCode={'event':'onclick','handler': '"'+"return delInput('" + pareId + "',"+strIndex+");"+'"'};
    else
    var jsCode={'event':'onclick','handler': "return delInput('" + pareId + "',"+strIndex+");"};
    addInputField(pareId,delId,'button','del',jsCode);

    addbr(pareId,brId);

    var span = document.getElementById(pareId);
    //alert(span.innerHTML);

    attaIdx++;
	return false;
}


function checkUploadFile1(obj)
{
    sfile=obj.value;
    sfile=sfile.toLowerCase();
    last=sfile.lastIndexOf('.');
    ext=sfile.substring(last+1);
    filetype="jpg";
    filetype=filetype.toLowerCase();
    ok=filetype.search(ext.toLowerCase())
    if(ok==-1)
    {
        alert("please upload file with extensions:"+filetype+"!");
        obj.focus();
        delInput('idfilespan',obj.id.substring(8));
        return false;
    }
    exist(obj.id,obj.type);
}
//----------------------------------------fileexist()----------------------------------------------------------
//edited by alun
function exist(fileId,filetype) {
      var file = document.getElementById(fileId);
	  var result = false;
	  if ( file !=null ) {
			if ( file.value != null && file.value != "") {
				result = existFile( file,filetype);
			}//if
	  }
	  if( result != -1)
	  {
		  alert(warn_exist_file);
          //if(IsIE&&filetype=='file') canContinue=false;
          delInput('idfilespan',result);
	  }
      else
      {
          canContinue=true;
      }
}//end of function
//added by alun
function getfilename( attaName ) {
	var s = attaName.lastIndexOf( '\\' );
	return attaName.substr(s+1, attaName.length - s -1);
}
//added by alun
function existFile( file,filetype )
{
	var form = document.formedittov;
	for ( var i= 0 ; i < form.elements.length ; i ++ ) {
		if ( form.elements[i].type == filetype && form.elements[i].name != file.name && form.elements[i].name.substring(0,7) == 'uploads' ) {
			if ( file.value == form.elements[i].value ) {
                delId=file.name.substring(16);
                if(filetype=='text')
                {
                   lpos=delId.indexOf(']');
                   delId=delId.substring(0,lpos);
                }
				return delId;
			}
		}
	}//for

	return -1;
}

function addInputField(pareId,fieldId,fieldType,fieldValue,fieldJs)
{
	  var pare = document.getElementById(pareId);
	  if ( pare !=null ) {
	                if ( !IsIE ) {
						var fieldObj = document.createElement("input");
						if ( fieldObj != null ) {
							fieldObj.type= fieldType;
                            if(fieldType=='file'){
							fieldObj.name = 'uploads_'+fieldId+'';
				            h=parseInt(document.all.skolkoaddfot.value);
		                    document.all.skolkoaddfot.value=h+1;
							}
                            else{
                            fieldObj.name = 'uploads['+fieldId+']';
							}
                            if(fieldType!='file')
                            fieldObj.value = fieldValue;
							fieldObj.id = fieldId;
							fieldObj.size="30";
                            if(fieldJs['event'])
							fieldObj.setAttribute(fieldJs['event'],fieldJs['handler'],0);
							pare.appendChild(fieldObj);
						}//if fieldObj
					}// !IsIE

					if ( IsIE ) {
                        var jsEvent = fieldJs['event'] + '=' + fieldJs['handler'];
                        if(jsEvent=='=') jsEvent='';
                        if(fieldType=='file'){
                        var fieldTag = "<input type='"+fieldType+"' id ='" + fieldId + "' name=uploads_" + fieldId + " value='" + fieldValue + "' size=30 " + jsEvent + ">";
                        h=parseInt(document.all.skolkoaddfot.value);
		                document.all.skolkoaddfot.value=h+1;
						}
                        else {
						var fieldTag = "<input type='"+fieldType+"' id ='" + fieldId + "' name=uploads[" + fieldId + "] value='" + fieldValue + "' size=30 " + jsEvent + ">";
                        }
						var fieldObj = document.createElement(fieldTag);
						pare.appendChild(fieldObj);
					}//IsIE if

	  }//if pare
}

function addbr(spanId,brId)
{
	  var span = document.getElementById(spanId);
	  if ( span !=null ) {
			var brObj = document.createElement("br");
			if ( brObj !=null ) {
				brObj.name = brId;
				brObj.id = brId;
				span.appendChild(brObj);
            }//if
     }//if
	 return;
}
//-------------------------------------------------------------------------------------------------------------


//---------------------------------------------delete input file-----------------------------------------------
function delInput(spanId,index)
{
       attaNum--;
       var attach = document.getElementById("attach");
       var upload = document.getElementById("uploadbtn");
       if(attaNum == 0)
       {
          attach.childNodes[0].nodeValue='Add Files';
          upload.style.display='none';
       }
    
	   var strIndex = "" + index;
	   var fileId = "attachId"+ strIndex;
	   var brId = "idAttachBr" + strIndex;
	   var delId = "idAttachOper" + strIndex;
	   //first,get the element
       var span = document.getElementById(spanId);
       //second,create the replace element
	   var temp= document.createElement("SPAN");

       if ( span == null ) return false;

       //third,replace it
	   var fileObj = document.getElementById(fileId);
	   if ( fileObj == null ) return false;
       span.replaceChild(temp,fileObj);
	   
	   var brObj = document.getElementById(brId);
	   if ( brObj ==null ) return false;
       span.replaceChild(temp,brObj);
        
	   var delObj = document.getElementById(delId );
	   if ( delObj == null ) return false;
       span.replaceChild(temp,delObj);
       h=parseInt(document.all.skolkoaddfot.value);
		  document.all.skolkoaddfot.value=h-1;

	   // Added by Harry, Repair Remove attached bug 2005/04/04
	   //span.removeChild(delObj.previousSibling);

	   return false;
}

