var isKeysChekOn = true;
var arrLastKeys = new Array();
var timeOutInterval = 1;
var myWidth = 0, myHeight = 0;
var isJsObjLoaded =false;
var isNN = document.layers ? true : false;
var isIE = document.all ? true : false;
var cy = null;


loadContent('js/xml/draganddrop.js');

function getCyId(){
	var oldDiv = document.getElementById('bodyDiv');
	if(oldDiv){
		var tmpcy = oldDiv.getAttribute('cy');
		cy = tmpcy;
	}
	setTimeout("getCyId();",500);
}
getCyId();

function isRightClick(e)
{
	var rightclick;
	if (!e) var e = window.event;
	if (e.which) rightclick = (e.which == 3);
	else if (e.button) rightclick = (e.button == 2);
	return rightclick; // true or false
}

function updateWindowSize() {
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  //window.alert( 'Width = ' + myWidth );
  //window.alert( 'Height = ' + myHeight );
}

function waitJsToExecute(fun,connTry,paramKey){
	if(connTry==undefined){
		connTry = 6;
	}
	connTry--;
	if(connTry==0){
		setSysStat(connMsg('Unable To Load Library','error'));
		setTimeout("setSysStat(null,0);",2000);
		return false;
	}
	eval('var check = typeof('+fun+');');
	//window.status=fun;
	if(check=='function'){
		isJsObjLoaded = 1;
		var z = fun+"('"+paramKey+"');"
		//window.status = 'Object Loaded';
		setSysStat(null,0);
		
		//if(typeof(paramKey)=='object'){
			//alert(z);
			//alert(paramKey['name']);
		//}
		eval(z);
		return true;
	}else{
		isJsObjLoaded = 0;
	}
	//window.status = 'Loading Object ...' ;
	setSysStat(connMsg('Waiting For Library '+connTry+' sec.'));
	setTimeout("waitJsToExecute('"+fun+"',"+connTry+",'"+paramKey+"')",1000);//? check
	
}

function setSysStat(msg,isOn){
	divName = 'sysStat';
	var newdiv = document.getElementById(divName);
	if(isOn==0){
		if(newdiv!=null){
			document.body.removeChild(newdiv);
		}
		return true;
	}
	updateWindowSize();
	if(newdiv!=null){
		newdiv.innerHTML  = '';
	}else{
		var newdiv = document.createElement('div');
	}
	var divH = 20;
	var endF = 'alert';
	var divW = 99;
	var stepW = 1;//sec
	var stepH = 3;//sec
	newdiv.setAttribute('id',divName);
	newdiv.setAttribute('class',divName);
	newdiv.style.width = divW;
	newdiv.style.height = divH;
	newdiv.style.left = (myWidth-divW)/2;
	newdiv.style.top = (myHeight-divH)/2;
	newdiv.style.position = "absolute";
	newdiv.style.textAlign = "center";
	newdiv.style.background = "#6C7F9E";
	newdiv.style.border = "1px solid #3E403F";
	newdiv.innerHTML = msg;
	newdiv.style.visibility='visible';
	document.body.appendChild(newdiv);
	//setTimeout("resizeDiv('"+divName+"',"+divW+","+0+","+divW+","+divH+","+stepW+","+stepH+",'"+endF+"')",0);
}


function print_r(theObj){
	if(theObj.constructor == Array ||
     theObj.constructor == Object){
    document.write("<ul>")
    for(var p in theObj){
      if(theObj[p].constructor == Array||
         theObj[p].constructor == Object){
document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
        document.write("<ul>")
        print_r(theObj[p]);
        document.write("</ul>")
      } else {
document.write("<li>["+p+"] => "+theObj[p]+"</li>");
      }
    }
    document.write("</ul>")
  }
}


function grepXMLElements(obj,key){
	if(obj.responseXML.getElementsByTagName(key)[0]==undefined){
		return 0;
	}
	return obj.responseXML.getElementsByTagName(key);	
}

function dumpXML(xml){
	alert(xml.responseText);
}

function grepXML(obj,key){
	if(obj.responseXML.getElementsByTagName(key)[0]==undefined){
		return 'Data Transfer Failure';
	}
	return obj.responseXML.getElementsByTagName(key)[0].firstChild.data;
}


function doKeysChek(ev)	{
	if(!isKeysChekOn)return true;
	if(window.event.srcElement.tagName.toString().match(/INPUT/i))return true;;
	if(window.event.srcElement.tagName.toString().match(/TEXTAREA/i))return true;;
	var myKeyCode      = ev.keyCode;
	// 27=ESC
	if (myKeyCode==27){arrLastKeys= new Array();return true;}
	
	arrLastKeys.push(myKeyCode);
	
	if(arrLastKeys.length>5){
		arrLastKeys.shift();
	}
	
	//admin
	var admin = new String("65,68,77,73,78");
	var menu = new String("77,69,78,85");
	var jwords = new String(arrLastKeys.join(","));
	
	var checkAdmin = jwords.indexOf(admin);
	var checkMenu = jwords.indexOf(menu);
	
	if(checkMenu>-1){
		arrLastKeys = new Array();
		if(parseInt(is_a)==1)
			startMenu();


	}
	if(checkAdmin>-1){
		if(parseInt(is_l)!=1)
			doAdmin();
	}
}



function cE(typ){
	return document.createElement(typ);
}
function sA(obj,key,myVal){
	obj.setAttribute(key,myVal);
}
function aC(obj,subObj){
	obj.appendChild(subObj);
}
function cTN(myText){
	return document.createTextNode(myText);
}

function resizeDiv(divAdminName,sW,sH,eW,eH,stepW,stepH,fAtEnd){
	diffH = eH-sH;
	diffW = eW-sW;

	if(diffW>0){
		nsW = sW + stepW;
	}else{
		nsW = eW;
	}

	if(diffH>0){
		nsH = sH + stepH;
	}else{
		nsH = eH;
	}
	

	var obj = document.getElementById(divAdminName);
	obj.style.width = nsW;
	obj.style.height = nsH;
	var zaqvka = "resizeDiv('"+divAdminName+"',"+nsW+","+nsH+","+eW+","+eH+","+stepW+","+stepH+",'"+fAtEnd+"')";
	if ((diffW <= 0)&&(diffH <= 0)){
		if(fAtEnd!=undefined){
		 	setTimeout(""+fAtEnd+"()",1);
		}else{
			alert('no way');
		}
	}else{
		setTimeout(zaqvka, timeOutInterval);
	}
}


function moveDiv(divAdminName,sX,sY,eX,eY,step,fAtEnd){
/*	diffH = eH-sH;
	diffW = eW-sW;

	if(diffW>0){
		nsW = sW + stepW;
	}else{
		nsW = eW;
	}

	if(diffH>0){
		nsH = sH + stepH;
	}else{
		nsH = eH;
	}
	

	var obj = document.getElementById(divAdminName);
	obj.style.width = nsW;
	obj.style.height = nsH;
	var zaqvka = "resizeDiv('"+divAdminName+"',"+nsW+","+nsH+","+eW+","+eH+","+stepW+","+stepH+",'"+fAtEnd+"')";
	if ((diffW <= 0)&&(diffH <= 0)){
		 setTimeout(""+fAtEnd+"()",1);
	}else{
		setTimeout(zaqvka, timeOutInterval);
	}*/
}

function getStrippedName(name){
	//return name;
	var removeArr = new Array('\\:','\\/','\\.','\\@');
	var tmpStr = name;
	//alert(removeArr.length);
	for(i = 0; i < removeArr.length;i++){
		var z = "/"+removeArr[i]+"/gi";
		var tmpStr = tmpStr.replace(eval(z),"");
	}
	return tmpStr;
}

function loadContent(file){
  var nameToDeclare = getStrippedName(file);
  var z = 'var chek = typeof('+nameToDeclare+');';
  eval(z);
  if(chek=='undefined'){
  	//alert('loading '+file);

	  var head = document.getElementsByTagName('head').item(0)
	  var scriptTag = document.getElementById('loadScript');
	  if(scriptTag) head.removeChild(scriptTag);
	  script = document.createElement('script');
	  script.src = file;
		script.type = 'text/javascript';
		script.id = 'loadScript';
		head.appendChild(script);
		var z = ' '+nameToDeclare+'=1;';
		eval(z);  
  }else{
  	//alert('passing cont');
  }
}

function connMsg(msg,state){
	switch(state){
		case 'empty':
			var src =  '<table><tr><td style="color:#DBE1EA">'+msg+'</td><td> <img src="images/gri/empty.gif"/></td></tr></table>';
		break;
		case 'error':
			var src =  '<table><tr><td style="color:#DBE1EA">'+msg+'</td><td> <img src="images/gri/scroll_error.ico"/></td></tr></table>';
		break;
		default:
			var src =  '<table><tr><td style="color:#DBE1EA">'+msg+'</td><td> <img src="images/gri/loading1.gif"/></td></tr></table>';
		break;
	}
	return src;
}

function doAdmin(){
		setSysStat(connMsg('Initaling'));
		loadContent('/js/xml/loginPanel.js');
}

function startMenu(){
		setSysStat(connMsg('Initaling'));
		loadContent('/js/xml/mainMenu.js');
}



function addEvent(element, eventType, lamdaFunction, useCapture) {
    if (element.addEventListener) {
        element.addEventListener(eventType, lamdaFunction, useCapture);
        return true;
    } else if (element.attachEvent) {
        var r = element.attachEvent('on' + eventType, lamdaFunction);
        return r;
    } else {
        return false;
    }
}
/* 
 * Kills an event's propagation and default action
 */
function knackerEvent(eventObject) {
    if (eventObject && eventObject.stopPropagation) {
        eventObject.stopPropagation();
    }
    if (window.event && window.event.cancelBubble ) {
        window.event.cancelBubble = true;
    }
    
    if (eventObject && eventObject.preventDefault) {
        eventObject.preventDefault();
    }
    if (window.event) {
        window.event.returnValue = false;
    }
}

/* 
 * Safari doesn't support canceling events in the standard way, so we must
 * hard-code a return of false for it to work.
 */
function cancelEventSafari() {
    return false;        
}


/*function getMouseXY(e) {
  if (IE) { // grab the x-y pos.s if browser is IE
    tempX = event.clientX + document.body.scrollLeft
    tempY = event.clientY + document.body.scrollTop
  } else {  // grab the x-y pos.s if browser is NS
    tempX = e.pageX
    tempY = e.pageY
  }  
  // catch possible negative values in NS4
  if (tempX < 0){tempX = 0}
  if (tempY < 0){tempY = 0}  
  // show the position values in the form named Show
  // in the text fields named MouseX and MouseY
  document.Show.MouseX.value = tempX
  document.Show.MouseY.value = tempY
  return true
}*/


//addEvent(myForm, 'submit', submitLogin, false);
/* 
 * Cross-browser event handling, by Scott Andrew
 */
 
 function sendXML(url,sFun,sFunParam,kEvent,successFun,failureFun,dataToSend){
	//sFun - status function
	//sFunParam - text
	//kEvent - event to stop;
	//url
	//successFun
	//failureFun
	//dataToSend
		var z = sFun+"('"+sFunParam+"',1);";
   	eval(z);
    //knackerEvent(e);
    /* Set up the request */
    var xmlhttp =  new XMLHttpRequest();
    xmlhttp.open('POST', url, false);
    
    /* The callback function */
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200){
							var z = sFun+"('"+sFunParam+"',0);";eval(z);	
   						successFun(xmlhttp);
            }else{
              failureFun('damn');
            }
        }
    }
		    
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send(dataToSend);	
}

function initAjaxObj(obj,sParams,wParams){
		//wParams['sX'] = sX;
		//wParams['sY'] = sY;
		//wParams['sP'] = sP;
		//wParams['aD'] = aD;
		
		var kEvent 		= null;
		var dataToSend= '_obj='+obj+'&'+sParams['params'];
		var url  	 		= '/xml/xmlController.php'
		var sFun		  = wParams['sF'];
		var sFunParam = wParams['sFP'];
		var successFun = 'initFirstFunction';
		var failureFun = alert;
		
		sendXML(url,sFun,sFunParam,kEvent,successFun,failureFun,dataToSend);
	//alert(dump(wParams));
}



/* 
 * Cross-browser style extraction, from the JavaScript & DHTML Cookbook
 * <http://www.oreillynet.com/pub/a/javascript/excerpt/JSDHTMLCkbk_chap5/index5.html>
 */
function getElementStyle(elementID, CssStyleProperty) {
    var element = document.getElementById(elementID);
    if (element.currentStyle) {
        return element.currentStyle[toCamelCase(CssStyleProperty)];
    } else if (window.getComputedStyle) {
        var compStyle = window.getComputedStyle(element, '');
        return compStyle.getPropertyValue(CssStyleProperty);
    } else {
        return '';
    }
}


