// utility JavaScript Document

//global variables
// lets define the browser we have instead of multiple calls throughout the file
var userAgent = navigator.userAgent.toLowerCase();
var is_opera  = (userAgent.indexOf('opera') != -1);
var is_saf    = ((userAgent.indexOf('applewebkit') != -1) || (navigator.vendor == "Apple Computer, Inc."));
var is_webtv  = (userAgent.indexOf('webtv') != -1);
var is_moz    = ((navigator.product == 'Gecko') && (!is_saf));
var is_ie     = ((userAgent.indexOf('msie') != -1) && (!is_opera) && (!is_saf) && (!is_webtv) && (!is_moz));
var is_ie4    = ((is_ie) && (userAgent.indexOf("msie 4.") != -1));
var is_kon    = (userAgent.indexOf('konqueror') != -1);
var is_ns     = ((userAgent.indexOf('compatible') == -1) && (userAgent.indexOf('mozilla') != -1) && (!is_opera) && (!is_webtv) && (!is_saf));
var is_ns4    = ((is_ns) && (parseInt(navigator.appVersion) == 4));
var tmp
/*used modified global varibale */

function initPage() {
	if(document.getElementById) {	
	    document.onkeydown = 
	    	function(evt) {oKey.keyevent(evt);}
	}
	init();
}

function trim(str) {
	var resultStr = "";
	var firstChar = false;
	var i=0;
	while( i<str.length && str.charAt(i)==" " )i++;
	var j=str.length-1;
	while( j>=0 && str.charAt(j)==" " )j--;
	return str.substring(i,j+1);
}

function saveCurVal(Obj) { //just for input and textarea
	if(Obj.nodeName == "INPUT")
		switch(Obj.type) {
			case "password" :
			case "text" : tmp = Obj.value; break;
			case "radio" :
			case "checkbox" : tmp = Obj.checked; break;
		}
	else if (Obj.nodeName == "textarea")
		tmp = Obj.innerText;
}

function testForChange(Obj) { //just for input and textarea
	if(Obj.nodeName == "INPUT")
		switch(Obj.type) {
			case "password" :
			case "text" : if( tmp != Obj.value )
							 modified = true;
						  break;
			case "radio" :
			case "checkbox" : if(tmp != Obj.checked )
								modified = true;
							  break;
		}
	else if (Obj.nodeName == "textarea" && tmp != Obj.innerText)
		modified = true;
}

function MM_jumpMenu(targ,selObj,restore){  //for jum menu
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function deleteConfirm(msg) {
	idTextObj = document.getElementById("idText");
	idText = idTextObj.value
	idOpObj = document.getElementById("idOperation");
	if( idText == "" ) {
		alert("اين فيلد نبايد خالي باشد!");
		idTextObj.focus();
		return false;
	}
	if ( idOpObj.selectedIndex == 2 )
		return window.confirm("آيا از حذف " + msg + " '" + idText + "' مطمئن هستيد؟");
}

function itemsGroupCtrl(groupId,defState) {
	var groupObj = document.getElementById(groupId);
	if(defState == "COLLAPSE") {
		var state1 = document.getElementById(groupId+"Pic_before");
		var state2 = document.getElementById(groupId+"Pic_after");
	}
	else {
		var state1 = document.getElementById(groupId+"Pic_after");
		var state2 = document.getElementById(groupId+"Pic_before");
	}
		
	if (groupObj.style.display == "none") {
		groupObj.style.display = "";
		state1.style.display = "none";
		state2.style.display = "";
	}	
	else {
		groupObj.style.display = "none";
		state1.style.display = "";
		state2.style.display = "none";
	}	
}

function formSubmit(obj) {
	obj.form.submit();
}

function focusForm(obj) {
	if (_documentActiveForm != null && typeof _documentActiveForm.onblur == "function")
		_documentActiveForm.onblur();
	_documentActiveForm = obj;
	for(var index = 0; index < obj.elements.length; index++)
		if (obj.elements[index].type == 'submit') {
			obj.elements[index].oldClassName = obj.elements[index].className;			
			obj.elements[index].className = 'active_button';
			break;
		}	
}

function blurFrom(obj) {
	_documentActiveForm = obj;
	for(var index = 0; index < obj.elements.length; index++)
		if (obj.elements[index].type == 'submit' && obj.elements[index].oldClassName)
			obj.elements[index].className = obj.elements[index].oldClassName;
}

function mousedownForm(obj) {
  if (obj != _documentActiveForm) {
	focusForm(obj);
  }
}

function keydownForm(obj) {
  if (obj != _documentActiveForm) {
	focusForm(obj);
  }
}

function prepareStartRow(preName,offset) {
	hiddenObj = document.getElementById(preName+"startRow");
	hiddenObj.value = offset;
}

function detailRefresh(masterObj, detailId) {
	if( detailId == "") return;
	detail = document.getElementById(detailId);
	detail_hide = document.getElementById(detailId + "_hide");
	var mm = masterObj.options[masterObj.selectedIndex].getAttribute('master');
	var mv = masterObj.options[masterObj.selectedIndex].value;
	if( mm != "")
		var key = mm + "_" + mv;
	else
		var key = mv;

	comboRemoveAll(detail);
	var i=0, optionNumber=0;
	while( i < detail_hide.options.length ) {
		if( detail_hide.options[i].getAttribute('master') == key  || detail_hide.options[i].getAttribute('master') == "" ) {
			if (optionNumber == 0 && detail.getAttribute("blankItem") == "true") {
		    	newElem = document.createElement("option");
		        newElem.innerText = "";
		        newElem.text = "";
		    	newElem.value = "";
		 		detail.appendChild(newElem);				
			}
			optionNumber++;
			newElem = document.createElement("option");
			newElem.text = detail_hide.options[i].text;
			newElem.innerText = detail_hide.options[i].text;
			newElem.setAttribute('master', detail_hide.options[i].getAttribute('master'));
			newElem.value = detail_hide.options[i].value;
 			//detail.add(newElem, -1);
 			detail.appendChild(newElem);
			newElem.selected = detail_hide.options[i].choice;
		}
		i++;
	}
    if(optionNumber==0){
    	newElem = document.createElement("option");
        newElem.innerText = "";
        newElem.text = "";
    	newElem.value = "";
 		//detail.add(newElem, -1);
 		detail.appendChild(newElem);
    }
	detail.onchange();
}

function comboRemoveAll(combo) {
	var i=0;
	while( i < combo.options.length )
		combo.remove(0);
}

function callComboOnChange(topId) {
	var topCombo = document.getElementById(topId);
	if(topCombo && topCombo.options.length > 0) { //NULL if mode is view
		topCombo.onchange();
		modified = false;
	}
}

function autoComplete(dateObj, type) {
	if(type == null ) type = 'JALALIDATE';
	if( dateObj.value == "" ) return false;
	var dateAry = dateObj.value.split("/");
	var day = dateAry[0];
	var month = dateAry[1];
	var year = dateAry[2];
	if( day && month && year && 1<=day && day<=31 && 1<=month && month<=12) {
		if (year.length == 1)
			preYear = (type == 'JALALIDATE') ? '130' : '200';
		else
			preYear = (type == 'JALALIDATE') ? '13' : '20';
		if ( day.length < 2 )
			day = '0' + day;
		if ( month.length < 2 )
			month = '0' + month;
		if ( year.length < 3 )
			year = preYear + year;
		else if(year.length < 4)	
			year = preYear.charAt(0) + year;
		dateObj.value = day + '/' + month + '/' + year;
	}
	else
		dateObj.value = '';
}

function timeAutoComplete(timeObj) {
	if (timeObj.value == "") return false;
	var timeAry = timeObj.value.split(":");
	switch (timeAry.length) {
		case 1:
				hour = timeAry[0];
				minute = '0';
				second = '0';
				break;
		case 2:
				second = '0';
				hour = timeAry[0];
				minute= timeAry[1];
				break;
		case 3:
				hour = timeAry[0];
				minute = timeAry[1];
				second = timeAry[2];
				break;				
	}

	if (second > 59 || minute > 59 || hour > 23) {
		timeObj.value = '';
		return false;
	}	
	if (second && minute && hour) {
		if ( second.length < 2 )
			second = '0' + second;
		if ( minute.length < 2 )
			minute = '0' + minute;
		if ( hour.length < 2 )
			hour = '0' + hour;
		timeObj.value = hour + ':' + minute + ':' + second;	
	}
	else
		timeObj.value = '';
}

function toggleFrame(outerFsetId,outerMinSize,innerFsetId,innerMinSize) {
	var outerFset = parent.document.getElementById(outerFsetId);
	var innerFset = parent.document.getElementById(innerFsetId);	
	var before = document.getElementById("toggle_before");
	var after = document.getElementById("toggle_after");
	if( outerFset.rows == outerMinSize + ",*" ) {
		outerFset.rows = outerFset.oldRows;
		innerFset.cols = innerFset.oldCols;
		before.style.display = "";
		after.style.display = "none";
	}	
	else {
		outerFset.oldRows = outerFset.rows;			
		outerFset.rows = outerMinSize + ",*" ;
		innerFset.oldCols = innerFset.cols;			
		innerFset.cols = "*," + innerMinSize;
		before.style.display = "none";
		after.style.display = "";
	}	
}

var sctim = 0
var noScroll = true
function moveUp() {
	var frm = parent.frames['menu'];
	if (!noScroll){
		frm.scrollBy(0, -5)
		sctim = setTimeout("moveUp()")
	}	
}
function moveDown() {
	var frm = parent.frames['menu'];	
	if (!noScroll){
		frm.scrollBy(0, +5)
		sctim = setTimeout("moveDown()")
	}	
}
function noMove(){
	clearTimeout(sctim);
	noScroll = true;
}
function setImage(preImgId, action) {
	img1 = 	document.getElementById(preImgId+"__normal");
	img2 = 	document.getElementById(preImgId+"__over");
	img3 = 	document.getElementById(preImgId+"__down");
	switch(action) {
		case "over" : newImg = img2; break;
		case "normal" : newImg = img1; break;
		case "down" : newImg = img3; break;
	}	
	if(img1) img1.style.display = "none";
	if(img2) img2.style.display = "none";
	if(img3) img3.style.display = "none";
	newImg.style.display = "";
}
function checkDetails(sibling) {
	var counter = 0;
	var obj = sibling.id+"_"+counter;
	obj = document.getElementById(obj);
	while (obj) {
		obj.checked = sibling.checked;	
		counter ++;
		obj = sibling.id+"_"+counter;
		obj = document.getElementById(obj);
	}
}
function checkAll_checklist(sibling) {
	var counter = 0;
	var obj = sibling.id+counter;
	obj = document.getElementById(obj);
	while (obj) {
		obj.checked = sibling.checked;	
		checkDetails(obj);
		counter ++;
		obj = sibling.id+counter;
		obj = document.getElementById(obj);
	}
}

var lookupIframeObj =null, targetObj=null;
function Lookup(module, targetId, jparams, rowIndex){
    lookupIframeObj = document.getElementById('_lookupIframeId'); //this name is fixed	
    targetObj = document.getElementById(targetId);
	var src = sisLOOKUPPATH_HTTP + module + jparams + "&ownapp=" + sisOWNAPP + "&exeapp=" + sisEXEAPP + "&RepeatLoopCounter=" + rowIndex;
    window.open(src,lookupIframeObj.name);
    lookupIframeObj.Document.body.innerHTML = '';
    transferHTML();
    return true;
}

function transferHTML() {
    t = null;
    if(( !lookupIframeObj || !lookupIframeObj.Document || !lookupIframeObj.Document.body || !lookupIframeObj.Document.body.innerHTML) ||
       ( lookupIframeObj.Document.body.innerHTML == ''))
       	t = setTimeout("transferHTML()", 100);
    else {
        clearTimeout(t);
        targetObj.innerHTML = lookupIframeObj.Document.body.innerHTML;
    }
}

function showLOV(lovName, lovTargetObj, lov_url_params, dialogWidth, dialogHeight) {
	var h = ( dialogHeight / 100 ) * screen.availHeight + 'px';
    var w = ( dialogWidth / 100 ) * screen.availWidth + 'px';
    var feature = "help:no;status:no;center:yes;resizable:yes;dialogHeight:" +h+ ";dialogWidth:" +w;
    var lovSrc = "";
	try
	{
    	//##RR
	    if (sisLIBWRAPPER_URL != "sisLIBWRAPPER_URL")
			lovSrc = sisLIBWRAPPER_URL + sisLoadLOV + "&lovname=" + lovName + "&ownapp=" + sisOWNAPP + "&exeapp=" + sisEXEAPP + lov_url_params;
		else	
	    	lovSrc = sisLoadLOV + "?lovname=" + lovName + "&ownapp=" + sisOWNAPP + "&exeapp=" + sisEXEAPP + lov_url_params;	

	    var val = showModalDialog(lovSrc, "", feature);
	    
	    if (val) {
	    	var retValues = val.split("_:_");
	    	for(var i=0; i < retValues.length; i++) {
	    		if (lovTargetObj[i].tagName == "SPAN" || lovTargetObj[i].tagName == "DIV")
	    			lovTargetObj[i].innerHTML = retValues[i];
	    		else if (lovTargetObj[i].tagName == "IMG")
	    			lovTargetObj[i].src = sisLIBWRAPPER_URL + sisLoadClientImage + "&image=" + retValues[i];
	    		else	
					lovTargetObj[i].value = retValues[i];    		
	    	}
	    	//alert(retValues.length);
	    }
	}
	catch(ex) {}
	//##RR    	    
    /*if (val)
      lovTargetObj.value = val;*/
}

//##RR
function showWizard(wizardName, targetElements, wparams, dialogWidth, dialogHeight)
{
	var h = ( dialogHeight / 100 ) * screen.availHeight + 'px';
    var w = ( dialogWidth / 100 ) * screen.availWidth + 'px';
    var feature = "scroll:off;help:no;status:no;center:yes;resizable:yes;dialogHeight:" +h+ ";dialogWidth:" +w;
    var wizardSrc = "";

	wizardSrc = sisLIBWRAPPER_URL + sisLoadWizard  + "&wizardname=" + wizardName +"&"+ wparams;

    var val = showModalDialog(wizardSrc, "", feature);
    //var val = open(wizardSrc, "", feature);

    
    if (val) {
		for(var i=0; i<targetElements.length; i++)
			for(var j=0; j<val.length; j++) {
				if (targetElements[i].name == val[j].name) {
		    		if (targetElements[i].element.tagName == "SPAN" || targetElements[i].element.tagName == "DIV")
		    			targetElements[i].element.innerHTML = val[j].value;
		    		else	
						targetElements[i].element.value = val[j].value;    		
					break;					
				}
			}
    }
}
//##RR

function showDialog(path, targetObj, params, dialogWidth, dialogHeight) {
	var h = ( dialogHeight / 100 ) * screen.availHeight + 'px';
    var w = ( dialogWidth / 100 ) * screen.availWidth + 'px';
    var feature = "help:no;status:no;center:yes;resizable:yes;dialogHeight:" +h+ ";dialogWidth:" +w;
    var windowLoc = path + "&ownapp=" + sisOWNAPP + "&exeapp=" + sisEXEAPP + params;
    var val = showModalDialog(windowLoc, "", feature);
    if (val && targetObj != null)
      document.getElementById(targetObj).value = val;
    return val;
}

function sisOpenCenteredWindow(url, width, height, target, menubar) {
    var height = ( height / 100 ) * screen.availHeight ;
	var width = ( width / 100 ) * screen.availWidth ;
    var left = parseInt((screen.availWidth/2) - (width/2));
    var top = parseInt((screen.availHeight/2) - (height/2));
    var windowFeatures = "width=" + width + ",height=" + height + 
    	",directories=0,location=0,menubar=" + menubar + 
    	",status=0,toolbar=0,scrollbars,resizable=true" +
        ",left=" + left + ",top=" + top + 
        ",screenX=" + left + ",screenY=" + top;    
    return window.open(url, target, windowFeatures);
}

function sisOpenWindow(url, width, height, left, top, target, menubar) {
    var height = ( height / 100 ) * screen.availHeight ;
	var width = ( width / 100 ) * screen.availWidth ;
    var windowFeatures = "width=" + width + ",height=" + height + 
    	",directories=0,location=0,menubar=" + menubar + 
    	",status=0,toolbar=0,scrollbars,resizable=true" +
        ",left=" + left + ",top=" + top + 
        ",screenX=" + left + ",screenY=" + top;    
    return window.open(url, target, windowFeatures);
}

var firstColor;
function color4(id) {
	var obj = document.getElementById(id);
	obj.style.backgroundColor = FIELD_COLOR4;
}
function color3(id) {
	var obj = document.getElementById(id);
	obj.style.backgroundColor = FIELD_COLOR3;
	setTimeout("color4('"+id+"')",100);
}
function color2(id) {
	var obj = document.getElementById(id);
	obj.style.backgroundColor = FIELD_COLOR2;
	setTimeout("color3('"+id+"')",100);
}
function color1(id) {
	var obj = document.getElementById(id);
	obj.style.backgroundColor = FIELD_COLOR1;
	setTimeout("color2('"+id+"')",100);
}
function activeMe(obj) {
	firstColor = obj.style.backgroundColor;
	try{
		obj.select();
	}catch(Exp){}
	setTimeout("color1('"+obj.id+"')",100);
}


function deactiveMe(obj) {
	setTimeout("deColor4('"+obj.id+"')",100);
}
function deColor4(id) {
	var obj = document.getElementById(id);
	obj.style.backgroundColor = FIELD_COLOR4;
	setTimeout("deColor3('"+id+"')",100);
}
function deColor3(id) {
	var obj = document.getElementById(id);
	obj.style.backgroundColor = FIELD_COLOR3;
	setTimeout("deColor2('"+id+"')",100);
}
function deColor2(id) {
	var obj = document.getElementById(id);
	obj.style.backgroundColor = FIELD_COLOR2;
	setTimeout("deColor1('"+id+"')",100);
}
function deColor1(id) {
	var obj = document.getElementById(id);
	obj.style.backgroundColor = FIELD_COLOR1;
	setTimeout("deColor0('"+id+"')",100);
}
function deColor0(id) {
	var obj = document.getElementById(id);
	obj.style.backgroundColor = firstColor;
}
	
//sisInfoButton assistance api
function ValidateItems(InputArray) {
	var index;
	var regexp = / /g;						
	for (index=0; index < InputArray.length; index++) {
		if ( InputArray[index].replace(regexp, "") == "") {
			alert("لطفا فيلدهاي مورد نظر را وارد نماييد.");
			return false;
		}
	}
	return true;
}

function ShowInfoWindow(url, target, wWidth, wHeight) {
	var he,wi,top,left;
	wi=(screen.width*wWidth/100);
	he=(screen.height*wHeight/100);
	left=(screen.width/2)-wi/2;
	top=(screen.height/2)-he/2;
	window.open(url, target,"scrollbars,resizable,status,menubar=false,height="+he+",width="+wi+",top="+top+",left="+left);
}

// get left position of elm
function fetch_object_posleft(elm) {
	var left = elm.offsetLeft;
	while((elm = elm.offsetParent) != null)
	{
		left += elm.offsetLeft;
	}
	return left;
}

// get top position of elm
function fetch_object_postop(elm) {
	var top = elm.offsetTop;
	while((elm = elm.offsetParent) != null)
	{
		top += elm.offsetTop;
	}
	return top;
}

// detect if selectobj overlaps m
function menu_overlap(selectobj, m) {
	s = new Array();
	s['L'] = fetch_object_posleft(selectobj);
	s['T'] = fetch_object_postop(selectobj);	
	s['R'] = s['L'] + selectobj.offsetWidth;
	s['B'] = s['T'] + selectobj.offsetHeight;
	
	if (s['L'] >= m['L'] && s['L'] <= m['R'] && ((s['T'] >= m['T'] && s['T'] <= m['B']) || (s['B'] >= m['T'] && s['B'] <= m['B']))) { return true; }
	else if (s['R'] >= m['L'] && s['R'] <= m['R'] && ((s['T'] >= m['T'] && s['T'] <= m['B']) || (s['B'] >= m['T'] && s['B'] <= m['B']))) { return true; }
	else if (s['B'] >= m['T'] && s['T'] <= m['B'] && ((s['L'] >= m['L'] && s['L'] <= m['R']) || (s['R'] >= m['R'] && s['R'] <= m['R']))) { return true; }
	else if (m['B'] >= s['T'] && m['T'] <= s['B'] && ((m['L'] >= s['L'] && m['L'] <= s['R']) || (m['R'] >= s['R'] && m['R'] <= s['R']))) { return true; }
	else { return false; }
}

// get element correct value
function getElementValue(obj) {
	for(var i = 0; i < obj.length; i++) {
		switch (obj[i].type) {
		case 'radio' :
			  	if(obj[i].checked)
			  		return obj[i].value;
			  	break;
		case 'hidden': break;
		default: 
			try{
				return obj[i].value;
			}catch(e) {
				return obj[i].innerText;				
			}
		}
	}
}

function autoFillElementValue(obj1,obj2) {
  if(!obj1 || !obj2) return true; //if not exist object
  var orgObj1 = GetMainObject(obj1);
  var orgObj2 = GetMainObject(obj2);
  orgObj2.value = orgObj1.value;	
}

function SimpleAjax(url, method, postData, callbackMethod) {				        
    if (document.xmlRequest && document.xmlRequest.readyState != 4) {
		window.setTimeout(function() { SimpleAjax(url, method, postData, callbackMethod)}, 100);
		return;
	}						
    var xmlRequest,e;					    
    try {
	    xmlRequest = new XMLHttpRequest();
    }
    catch(e) {
	    try {
            xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
        }
	    catch(e) {
    	    return false;            
        }
    }
	document.xmlRequest = xmlRequest;            
    xmlRequest.open(method, url, true);
    xmlRequest.setRequestHeader("Content-Type", "text/html;charset=UTF-8");
    xmlRequest.onreadystatechange = callbackMethod;
        
    if (method == "POST")
    	xmlRequest.send(postData);
    else    
        xmlRequest.send(null);	    
        
    return true;
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
				curleft += obj.offsetLeft
				curtop += obj.offsetTop
		}
	}
	return [curtop,curleft];
}

function GetPosition(e, dir) {	            	
	var x, y;
	if (dir == "rtl") {  
		x = e.x -  ((__optionMenuFirstScroll * 1) - GetScroll()[1]) - 28;
		y = e.y + GetScroll()[0];
	}
	else {
    	x = e.x + GetScroll()[1];
    	y = e.y + GetScroll()[0];
	}
    return [y, x];
}				   

function GetScroll() {
    var dd = document.documentElement; db = document.body;
    if (dd && (dd.scrollTop || dd.scrollLeft)) {
        return [dd.scrollTop, dd.scrollLeft];
    } else if (db) {
        return [db.scrollTop, db.scrollLeft];
    } else {
        return [0, 0];
    }
}

function trim(s)
{
	return rtrim(ltrim(s));
}

function ltrim(s)
{
	var l=0;
	while(l < s.length && s[l] == ' ')
	{	l++; }
	return s.substring(l, s.length);
}

function rtrim(s)
{
	var r=s.length -1;
	while(r > 0 && s[r] == ' ')
	{	r-=1;	}
	return s.substring(0, r+1);
}

function urlencode(str) {
	str = escape(str);
	str = str.replace('+', '%2B');
	str = str.replace('%20', '+');
	str = str.replace('*', '%2A');
	str = str.replace('/', '%2F');
	str = str.replace('@', '%40');
	return str;
}

function urldecode(str) {
	str = str.replace('+', ' ');
	str = unescape(str);
	return str;
}