var nLine = "\n";
var eLang = "heb";
var eDir = "rtl";
var eDirMirr = "ltr";
var eAlign = "right";
var eAlignMirr = "left";

var cell_arr = new Array(new Array("1", "GSM"), new Array("2", "CDMA"), new Array("3", "TDMA"));
var coin_arr = new Array(new Array("1", "$"), new Array("2", "&#8364;"), new Array("3", "&#163;"), new Array("3", "р"));
var viewtype_arr = new Array(new Array("0", "Все"), new Array("1", "Оригинальные"));
var status_usr_arr = new Array(new Array("1", "Удален."), new Array("2", "Новый"), new Array("3", "Не Активир."), new Array("4", "Активир."), new Array("5", "Админ"));
var status_deal_arr = new Array(new Array("1", "Удален."), new Array("2", "Новый"), new Array("3", "Не Активир."), new Array("4", "Активир."), new Array("5", "Горяч."));
var status_arr = new Array(new Array("1", "Удален."), new Array("2", "Не Активир."), new Array("3", "Активир."));

var sortMsgTxt = "";
var dataMsgTxt = "";

var ErrLog = false;
function errorHandler(errMsg, errUrl, errLine) {
  alert("JavaScript Error:------------\n Msg: ["+errMsg+"]\n Line: ["+errLine+"]\n Url: ["+errUrl+"]\n\n-------------\n\n");
  if(ErrLog) addLog("<b>JavaScript Error:</b> "+(new Date())+"<br>Msg: [<b>"+errMsg+"</b>]<br>Line: [<b>"+errLine+"</b>]<br>Url: [<b>"+errUrl+"</b>]");
  return true;
}
window.onerror = errorHandler;

function DebugRun() {
}

function sortMsg() {
  smsg(sortMsgTxt);
}

function dataMsg() {
	smsg(dataMsgTxt);
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}

function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}

function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

function checkemail(emailStr){
	var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
	if (filter.test(emailStr))
		return true;
	return false;
}

function makeHex(n) { // only works on 0 to 256
	var Digits="0123456789ABCDEF";
	return Digits.charAt(n / 16) + Digits.charAt(n % 16);
}

function setLang(strLang) {
	eLang = strLang;
	eDir = (eLang == "heb")?"rtl":"ltr";
	eDirMirr = (eLang == "heb")?"ltr":"rtl";
	eAlign = (eLang == "heb")?"right":"left";
	eAlignMirr = (eLang == "heb")?"left":"right";
}

function addLog(logMsg) {
	if(divDebugLog) {
		divDebugLog.style.display="block";
		divDebugLog.innerHTML=logMsg+"<br>"+divDebugLog.innerHTML;
	}
}

function setCookie(c_name, value, expiredays)
{
	var exdate=new Date();
	exdate.setDate(expiredays);
	document.cookie=c_name+ "=" +escape(value)+((expiredays==null)?"":";expires="+exdate);
}

function getCookie(c_name)
{
	if (document.cookie.length>0) {
	  var c_start=document.cookie.indexOf(c_name + "=")
	  if (c_start!=-1) {
	    c_start=c_start + c_name.length+1;
	    var c_end=document.cookie.indexOf(";",c_start);
	    if (c_end==-1) c_end=document.cookie.length;
	    return unescape(document.cookie.substring(c_start,c_end));
	  }
	}
	return null;
}

function getDateSQL(tmpDate) {
  return tmpDate.getFullYear()+"-"+add0(tmpDate.getMonth()+1)+"-"+add0(tmpDate.getDate());
}

function getSQLDate(tmpDate) {
  return new Date(1*tmpDate.substring(0, 4), 1*tmpDate.substring(5, 7)-1, 1*tmpDate.substring(8, 10));
}

function add0(strNumber) {
	strNumber = "" + strNumber;
  if(strNumber.length == 1) return "0"+strNumber;
  return strNumber;
}

function copyObject(obj2copy) {
	for(var x in obj2copy)
		this[x] = obj2copy[x];
  return this;
}

function addLoadEvent(func) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {
    window.onload = function() {
      oldonload();
      func();
    }
  }
}

function removeAllByObj(selectObj) {
  if(typeof(document.forms[formName]) == 'undefined' ||
    typeof(document.forms[formName].elements[selectName]) == 'undefined' ||
    !document.forms[formName].elements[selectName].options[0]) return;
  while(document.forms[formName].elements[selectName].options[0] != null)
    document.forms[formName].elements[selectName].options[0] = null;
}

function removeAll(formName, selectName) {
  if(typeof(document.forms[formName]) == 'undefined' ||
    typeof(document.forms[formName].elements[selectName]) == 'undefined' ||
    !document.forms[formName].elements[selectName].options[0]) return;
  while(document.forms[formName].elements[selectName].options[0] != null)
    document.forms[formName].elements[selectName].options[0] = null;
}

function addOption(formName, selectName, value1, value2, optionNumb) {
  if(typeof(document.forms[formName]) == 'undefined' ||
    typeof(document.forms[formName].elements[selectName]) == 'undefined') return;
  document.forms[formName].elements[selectName].options[optionNumb] = new Option(value2, value1);
}

function updateHidden(formName, array_id, dataName, newValue) {
  if (typeof(document.forms[formName].elements[dataName+"_arr[]"].length) == 'undefined')
    document.forms[formName].elements[dataName+"_arr[]"].value = newValue;
  else
    document.forms[formName].elements[dataName+"_arr[]"][array_id].value = newValue;
}

function showDataDiv(formName, checkBoxName, array_id, dataName) {
  h();
  divObj = document.all(dataName+'_'+array_id);
  divObj.onclick = null;
  divObj.onmouseover = null;
  divObj.onmouseout = null;
  if (typeof(document.forms[formName].elements[dataName+"_arr[]"].length) == 'undefined')
    tmpCurr = document.forms[formName].elements[dataName+"_arr[]"].value;
  else
    tmpCurr = document.forms[formName].elements[dataName+"_arr[]"][array_id].value;
  tmpString = "<select name=\"tmpSelect\" onchange=\"changeDiv('"+formName+"', '"+checkBoxName+"', "+array_id+", '"+dataName+"', this.value, this[this.selectedIndex].text);\">";
  for (i=0; i < window[dataName+"_arr"].length; i++) {
    tmpString = tmpString+"<option value=\""+window[dataName+"_arr"][i][0]+"\""+((tmpCurr == window[dataName+"_arr"][i][0])?" selected":"")+">"+window[dataName+"_arr"][i][1]+"</option>";
  }
  divObj.innerHTML = tmpString + "</select>";
}

function changeDiv(formName, checkBoxName, array_id, dataName, selectedValue, selectedText) {
  setCheckbox(formName, checkBoxName, array_id, true);
  if (typeof(document.forms[formName].elements[dataName+"_arr[]"].length) == 'undefined')
    document.forms[formName].elements[dataName+"_arr[]"].value = selectedValue;
  else
    document.forms[formName].elements[dataName+"_arr[]"][array_id].value = selectedValue;
  divObj = document.all(dataName+'_'+array_id);
  divObj.innerHTML = selectedText;
  divObj.onclick = new Function("showDataDiv('"+formName+"', '"+checkBoxName+"', "+array_id+", '"+dataName+"');");
  divObj.onmouseover = new Function("dataMsg();");
  divObj.onmouseout = new Function("hDiv(dataDiv);");
}

function showElements(objPath, inWindow, justNames, justType) {
	var showObj = eval(objPath);
	var txtMsg = "";
	var i = 0;
	var curType = "";
	var curVal = "";

  txtMsg = "<font color=blue><b>"+objPath+"</b></font> <i>("+typeof(showObj)+")</i>";
  if(inWindow) {
  	wID = window.open("javascript:'<html><title>"+objPath+"</title><body></body></html>';")
  	wID.document.writeln(txtMsg+"<pre>");
  } else
  	addLog(txtMsg);

  for(showVar in showObj) {
    i++;
    curType = typeof(showObj[showVar]);
    curVal = showObj[showVar];
    if(justNames && (justType == "" || justType == curType)) {
   		txtMsg = "\t"+i+")\t<font color=blue>"+showVar+"</font>";
   	} else if(curType == "object" && (curVal == "[object]" || curVal == "[object Object]") && (justType == "" || justType == curType)) {
   		txtMsg = "\t"+i+")\t<font color=blue>"+showVar+"</font>\t= <a href=\"javascript:opener.showElements('"+objPath+"."+showVar+"', "+inWindow+", "+justNames+", '"+justType+"');\"><font color=red><b>"+curVal+"</b></font></a>";
    } else if(curType == "object" && curVal == null && (justType == "" || justType == curType)) {
   		txtMsg = "\t"+i+")\t<font color=blue>"+showVar+"</font>\t= "+curVal+"\t <font color=green><i>("+curType+")</i></font>";
    } else if(justType == "" || justType == curType) {
   		txtMsg = "\t"+i+")\t<font color=blue>"+showVar+"</font>\t= <font color=red><b>"+curVal+"</b></font>\t <font color=green><i>("+curType+")</i></font>";
    }
    if(justType == "" || justType == curType) {
		  if(inWindow)
		  	wID.document.writeln(txtMsg);
		  else
		  	addLog(txtMsg);
	  }
  }

  if(inWindow)
  	wID.document.writeln("</pre>");
}

var marked_row = new Array;

function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor)
{
    if ((thePointerColor == '' && theMarkColor == '')
        || typeof(theRow.style) == 'undefined') {
        return false;
    }

    var domDetect    = null;
    var currentColor = null;
    var newColor     = null;
    if (typeof(window.opera) == 'undefined'
        && typeof(theRow.getAttribute) != 'undefined') {
        currentColor = theRow.getAttribute('bgcolor');
        domDetect    = true;
    }
    else {
        currentColor = theRow.style.backgroundColor;
        domDetect    = false;
    }

    if (currentColor == ''
        || currentColor.toLowerCase() == theDefaultColor.toLowerCase()) {
        if (theAction == 'over' && thePointerColor != '') {
            newColor              = thePointerColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
        }
    }
    else if (currentColor.toLowerCase() == thePointerColor.toLowerCase()
             && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
        if (theAction == 'out') {
            newColor              = theDefaultColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
        }
    }
    else if (currentColor.toLowerCase() == theMarkColor.toLowerCase()) {
        if (theAction == 'click') {
            newColor              = (thePointerColor != '')
                                  ? thePointerColor
                                  : theDefaultColor;
            marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
                                  ? true
                                  : null;
        }
    }

    if (newColor) {
        if (domDetect) {
          theRow.setAttribute('bgcolor', newColor, 0);
        }
        else {
          theRow.style.backgroundColor = newColor;
        }
    }

    return true;
} // end of the 'setPointer()' function

function setCheckboxes(formName, elementName, do_check)
{
    if (typeof(document.forms[formName]) == 'undefined' || typeof(document.forms[formName].elements[elementName]) == 'undefined') return;
    var elts      = document.forms[formName].elements[elementName];
    var elts_cnt  = (typeof(elts.length) != 'undefined')
                  ? elts.length
                  : 0;

    if (elts_cnt) {
        for (var i = 0; i < elts_cnt; i++) {
            elts[i].checked = do_check;
        } // end for
    } else {
        elts.checked        = do_check;
    } // end if... else

    return true;
} // end of the 'setCheckboxes()' function

function setCheckbox(formName, elementName, array_id, do_check)
{
    if (typeof(document.forms[formName]) == 'undefined' || typeof(document.forms[formName].elements[elementName]) == 'undefined') return;
    var elts      = document.forms[formName].elements[elementName];
    var elts_cnt  = (typeof(elts.length) != 'undefined')
                  ? elts.length
                  : 0;

    if (elts_cnt) {
       elts[array_id].checked = do_check;
    } else {
       elts.checked        = do_check;
    } // end if... else

    return true;
} // end of the 'setCheckboxes()' function

function catalogUpdate(formName, flagAny) {
  if (typeof(document.forms[formName]) != 'undefined') {
    document.forms[formName].find.value = "";
    var cell = document.forms[formName].findcell.value;
    var brandid = document.forms[formName].findbrandid.value;
    removeAll(formName, "findmobileid");
    if (flagAny) addOption(formName, "findmobileid", "0", "Все", 0);
    if (brandid > 0) {
      document.forms[formName].findcell.disabled=true;
      document.forms[formName].findbrandid.disabled=true;
      document.forms[formName].findmobileid.disabled=true;
      smsg("Загрузка данных...<iframe frameborder=0 width=0 height=0 marginheight=0 marginwidth=0 scrolling=\"no\" name=\"catalog\" src=\"catalog_update.php?formname="+formName+"&cell="+cell+"&brandid="+brandid+"&startnumb="+((flagAny)?1:0)+"\"></iframe>");
    }
  }
}

function catalogShow(formName) {
  if (typeof(document.forms[formName]) != 'undefined') {
    document.forms[formName].find.value = "";
    document.forms[formName].findcell.disabled=false;
    document.forms[formName].findbrandid.disabled=false;
    document.forms[formName].findmobileid.disabled=false;
    h();
  }
}

function usersUpdate(formName, flagAny) {
  if (typeof(document.forms[formName]) != 'undefined') {
    var agentid = document.forms[formName].findagentid.value;
    removeAll(formName, "finduserid");
    if (flagAny) addOption(formName, "finduserid", "0", "Все", 0);
    if (agentid > 0) {
      document.forms[formName].findagentid.disabled=true;
      document.forms[formName].finduserid.disabled=true;
      smsg("Загрузка данных...<iframe frameborder=0 width=0 height=0 marginheight=0 marginwidth=0 scrolling=\"no\" name=\"users\" src=\"users_update.php?formname="+formName+"&agentid="+agentid+"&startnumb="+((flagAny)?1:0)+"\"></iframe>");
    }
  }
}

function usersShow(formName) {
  if (typeof(document.forms[formName]) != 'undefined') {
    document.forms[formName].findagentid.disabled=false;
    document.forms[formName].finduserid.disabled=false;
    h();
  }
}

function getNumb(Numb, Len) {
	var tmpStr = ''+Numb;
	var tmpInt = 0;
	var tmpAftDot = 0;
	var tmpAftLast = 0;
	var dotPlace = tmpStr.indexOf('.');
  if (dotPlace == -1)
    return tmpStr*1;
  else {
    tmpInt = parseInt(tmpStr);
    tmpAftDot = tmpStr.substring(dotPlace + 1, dotPlace + 1 + Len);
    tmpAftLast = tmpStr.substring(dotPlace + 1, dotPlace + 2);
    if ((tmpAftLast > 8 && Len > 0) || (tmpAftLast > 4 && Len == 0))
      return tmpInt + 1;
    else if (tmpAftLast > 1 && Len > 0)
      return  (tmpInt + '.' + tmpAftDot)*1;
  }
  return tmpInt*1;
}

function elem(val) {
	return gD(val);
}

function enableForm(frmObj) {
	for (i=0; i<frmObj.elements.length; i++)
		frmObj.elements[i].disabled = false;
}

function chDisp(dspObj, dspValue) {
	if(dspObj) {
		if(dspObj.style != undefined) {
			var tmpValue = dspObj.style.display;
			dspObj.style.display = (dspValue != '')?dspValue:(tmpValue == '' || tmpValue == 'block')?'none':'block';
		} else if(dspObj.length != undefined) {
		  for(var i=0;i<dspObj.length;i++) {
		  	chDisp(dspObj[i], dspValue);
		  }
	  }
	}
}

//DOM functions
function gD(elementId) {
	return document.getElementById(elementId);
}

function gH(elementId) {
	var tmpElement = gD(elementId);
	return (tmpElement)?tmpElement.innerHTML:"";
}

function sH(elementId, strHTML) {
	var tmpElement = gD(elementId);
	if(tmpElement) tmpElement.innerHTML = strHTML;
}

//XML functions
function gE(singleNode, strXQLQuery) {
	return (singleNode)?singleNode.getElementsByTagName(strXQLQuery):null;
}

function gN(singleNode, strXQLQuery) {
	return (singleNode)?singleNode.selectSingleNode(strXQLQuery):null;
}

function gT(singleNode, strXQLQuery) {
	var tmpNode = gN(singleNode, strXQLQuery);
	return (tmpNode)?tmpNode.text:"";
}


function confirma(msg,url)
{
	var agree=confirm(msg);
	if (agree)
		this.location = url ;
	else
		return false;
}

function checkForm(objForm, lstFildNames)
{
//"checkForm(this, {0:{name:'val[name]', dicName:'".getDict('agenstvo_'.$var_lang)."',msg:'Enter value',check:'e'}})"
//	alert(lstFildNames);
//	alert(lstFildNames[0]);
	return false;
}
