/* ----------------------------------------------
 *  Useful Java & Ajax Functions 
 *  |||
 *  By Foad Attar Olyaee 87-08-07
 *  lastUpdate: 1389-09-10 | 2010-12-01
 * ----------------------------------------------
 - gel(objId)
 - getDigit(number,lang)
 
 */
var _jax_sser = true; // Alerts server errors
var _catch_err = true; // Browser displays error warning if window.onerror happens

var usrAgent = window.navigator.userAgent;
var isIE = usrAgent.indexOf('MSIE')!=-1;
var IEversion = isIE ? usrAgent.substring(usrAgent.indexOf('MSIE')+5, usrAgent.indexOf('MSIE')+6) : null;
var isFF = usrAgent.indexOf('Firefox')!=-1;
var isChrome = usrAgent.indexOf('Chrome')!=-1;
var isNetscape = usrAgent.indexOf('Netscape')!=-1;
var isOpera = window.opera!=null;
var isSafari = usrAgent.indexOf('Safari')!=-1;
var isIPhone = usrAgent.indexOf('iPhone')!=-1;
var isIPod = usrAgent.indexOf('iPod')!=-1;
var isIPad = usrAgent.indexOf('iPad')!=-1;

//------------------------------- get browser Name
var agentBrowser = function()
{
    if(isIE) return "IE";
    else if(isFF) return "Firefox";
    else if(isChrome)return "Chrome";
    else if(isOpera) return "Opera";
    else if(isSafari) return "Safari";
    else if(isNetscape) return "Netscape";
    else return "";
}
//------------------------------- return document.getElementById(ElementId)
function gel(obj) {
    if(!obj || typeof(obj)!='string')
        return null;
    if (obj.charAt(0) == '#') return document.getElementById(obj.replace('#', ''));
    else if(obj.charAt(0)=='^') return document.getElementsByTagName(obj.replace('^',''),arguments[1]);
    else if (obj.charAt(0) == '.') return document.getElementsByAttributeValue(obj.replace('.', ''), (isIE && IEversion < 8 ? 'className' : 'class'), arguments[1]);
    else if (obj.charAt(0) == '$') return document.getElementsByAttributeValue(obj.replace('$', ''), 'name', arguments[1]);
    else if (obj.charAt(0) == '*') // keyword in (attrib,class,name,id,...)
    {
        if(obj.length==1)
            return document.getElementsByTagName('*');
        return document.getElementsByAttributeValue(obj.replace('*', ''), arguments[1]);
    }
    else if (obj.charAt(0) == '@') // @attribName:Value
    {
        attribName = (coll = obj.split(':'))[0].replace('@','');
        attribValue = coll[1];
        return document.getElementsByAttributeValue(attribValue, attribName, arguments[1]);
    }
    return document.getElementById ? document.getElementById(obj) : null;
}
//------------------------------- Get Elements By Attribute(value,[attrib]) or (null,attrib)
// (value): any obj with any attrib equal to the value
// (value,name): any obj with the name attrib equal to the value
// (~value,name): any obj with the name attrib similar to the value
// (null,name): any obj with the name attrib
// breakOnFirstMatch : break on first matched element
document.getElementsByAttributeValue = function (attrValue, attrName, breakOnFirstMatch) 
{
    var all = document.getElementsByTagName("*");
    var elem = new Array();
    var i = 0;
    while (all[i]) 
    {
        //--- search only in the specified AttribName
        if (attrName) 
        {
            //if ((all[i].hasAttribute && all[i].hasAttribute(attrName)) || (!all[i].hasAttribute && all[i].tagName != "!"))
            if ((val=all[i].getAttribute(attrName))!=null)
                if (attrValue == null || attrValue == '' 
                    || (attrValue.charAt(0) != '~' && val == attrValue)
                    || (attrValue.charAt(0) == '~' && val.indexOf(attrValue.replace('~', '')) != -1))
                    {
                        elem[elem.length] = all[i];
                        if (breakOnFirstMatch)
                            break;
                    }
        }
        //--- search in all attribs
        else if (all[i].tagName != "!")
        {
            for (var j = 0; j < all[i].attributes.length; j++)
                if (attrValue == ''
                    || (attrValue.charAt(0) != '~' && all[i].attributes[j].value == attrValue)
                    || (attrValue.charAt(0) == '~' && all[i].attributes[j].value.indexOf(attrValue.replace('~', '')) != -1))
                    elem[elem.length] = all[i];
        }
        i++;
    } // End While
    return elem;
}
//------------------------------- Get digit according to Language
function getDigit(number,lang)
{
    number=number.toString();

    if(lang.toUpperCase().trim()=='FA')
        number=number.replace(/0/g,'۰')
                     .replace(/1/g,'۱')
                     .replace(/2/g,'۲')
                     .replace(/3/g,'۳')
                     .replace(/4/g,'۴')
                     .replace(/5/g,'۵')
                     .replace(/6/g,'۶')
                     .replace(/7/g,'۷')
                     .replace(/8/g,'۸')
                     .replace(/9/g,'۹');
    else
        number=number.replace(/۰/g,'0')
                     .replace(/۱/g,'1')
                     .replace(/۲/g,'2')
                     .replace(/۳/g,'3')
                     .replace(/۴/g,'4')
                     .replace(/۵/g,'5')
                     .replace(/۶/g,'6')
                     .replace(/۷/g,'7')
                     .replace(/۸/g,'8')
                     .replace(/۹/g,'9');
	
	return number;
}
//------------------------------- Write in Cookie
function setCookie(sName, sValue, oExpires, sPath, sDomain, bSecure) 
{
    var sCookie = sName + "=" + encodeURIComponent(sValue)+";";
    if(oExpires)
    {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        sCookie += "expires=" + oExpires.toGMTString() + ";";
    }
    sPath && (sCookie += "path=" + sPath + ";");
    sDomain && (sCookie += "domain=" + sDomain + ";");
    bSecure && (sCookie += "secure" + ";");
    document.cookie = sCookie;
    return true;
}
//------------------------------- Read Cookie
function getCookie(sName)
{
    if(!document.cookie)
        return null;
    var sRE = "(?:; )?" + sName + "=([^;]*);?";
    var oRE = new RegExp(sRE);
    if (oRE.test(document.cookie))
        return decodeURIComponent(RegExp["$1"]);
    else
        return null;
}
//------------------------------- Delete Cookie
function deleteCookie(sName, sPath, sDomain)
{
    setCookie(sName, "", 0/*new Date(0)*/, sPath, sDomain);
    return true;
}
//------------------------------- Set Style of obj
function setStyle(obj,str)
{
	if(document.all && !window.opera) // IE
		obj.style.setAttribute("cssText",str);
	else 
		obj.setAttribute("style",str);
}
//-------------------------------  set the obj Opacity (0~1)
function setOpacity(obj,value)
{
    typeof(obj)=='string' && (obj=gel(obj));
    try
    {
        if(obj.filters!=undefined)
            obj.style.filter="alpha(opacity="+parseInt(value*100)+")";
        else
          obj.style.opacity=value;
    }
    catch(er) {obj.style.filter="alpha(opacity="+parseInt(value*100)+")"; }
}
//------------------------------- get Style of obj
function getStyle(obj)
{
	if(document.all && !window.opera) // IE
		return obj.style.getAttribute("cssText");
	else 
		return obj.getAttribute("style");
}
//-------------------------------  get the current style of obj (even if assigend by css class)
function getCurrentStyle(obj, attrib)
{
    typeof(obj)=='string' && (obj=gel(obj));
    
    if(obj.currentStyle) // IE, Op
        return eval("obj.currentStyle."+attrib);
        // return obj.currentStyle[obj.toCamelCase()];
    if(document.defaultView) // FF, Ch
        return document.defaultView.getComputedStyle(obj,'').getPropertyValue(attrib);
    return "";
}
//------------------------------- Remove click from anchor links which point to '#'
function disableSharpLinks()
{
  var anchors = document.gel('^a');
  for (var i=0; i<anchors.length; i++)
    if (anchors[i].href.match(/[^#]#$/))
      anchors[i].onclick = "void(0)";
      //addEvent(pageLinks[i], 'click', removeEvent, false);
}
//-------------------------------  Ajax Class
function XHR(formId, url, func, args)
{
    this.formId = formId;
    this.method = formId==null ? 'get' : 'post';
    this.url = url;
    this.func = func;
    this.funcArgs = args;
    this.ajaxObj = XmlHttpObject();
    this.async = true;
    this.responseText = null;
    this.responseXML = null;
    //this.readyState = -1;
    //this.status = 0;
    //this.statusText = '';
}
XHR.prototype.status = function(){ return this.ajaxObj.status; };
XHR.prototype.readyState = function(){ return this.ajaxObj.readyState; };
XHR.prototype.statusText = function(){ return this.ajaxObj.statusText; };

XHR.prototype.send = function()
{
    AjaxObj.open(this.method, this.url, this.async);
    if(this.method=='post')
        this.ajaxObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    this.ajaxObj.setRequestHeader("Cache-Control", "no-cache");
    var oAjax = this;
    this.ajaxObj.onreadystatechange=function()
    {
        if(this.ajaxObj.readyState==4)
            if(this.ajaxObj.status==200)
            {
	            var result = this.ajaxObj.responseText;
	            var resContentType = this.ajaxObj.getResponseHeader("Content-Type");
	            var resultXML = resContentType!=null && resContentType.indexOf("xml")>=0 ? this.ajaxObj.responseXML : null;
	            
	            if (resultXML!=null && resultXML.documentElement.nodeName === "parsererror" )
	            {
		            parseXmlError(resultXML);
		            return;
	            }
	            this.responseText = result;
	            this.responseXML = resultXML;
                if(this.funcArgs != null)
                {
		            this.funcArgs.push(result);
		            if(resultXML!=null)
			            this.funcArgs.push(resultXML);
                    this.func.apply(document, args);
                }
                else
                {
                    this.func();
                }
                if(resultXML==null)
		            applyScript(result);
            }
            else
            {
                result = "!RS!"; // !RESET!
                this.responseText = "!RS!";
                if(this.ajaxObj.status!=0)
                {
                    parseHttpError(this.ajaxObj, url);
                    result = "!ER!"; // !ERROR!
                    this.responseText = "!ER!";
                }
                this.func();
            }
    }
    var formBody= (this.formId!=null)? setBody(formId):null;
    this.ajaxObj.send(formBody);
}
XHR.prototype.responseHeader = function(header)
{
    this.ajaxObj.getResponseHeader(header);
}
XHR.prototype.abort = function()
{
    if(this.ajaxObj.readyState!= 0)
        GlobalXHRobj.abort();
}
//-------------------------------  Send\Receive via one (Shared) Ajax-obj (RESET-able)
function reGetFromHttpRequest(method,url,formId,func,args)
{
    getFromHttpRequest(method,url,formId,func,args,'reset');
}
//-------------------------------  
function getFromHttpRequest(method, url, formId, func, args)
{
    formBody=(formId!=null)?setBody(formId):null;
    var AjaxObj;
    if(arguments[5] && arguments[5]=='reset')
        AjaxObj= resetXmlHttpObject();
    else
        AjaxObj= XmlHttpObject();
    AjaxObj.open(method,url,true);
    if(method.toUpperCase()=='POST')
        AjaxObj.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    AjaxObj.setRequestHeader("Cache-Control", "no-cache");
    AjaxObj.onreadystatechange=function()
    {
        if(AjaxObj.readyState==4)
            if(AjaxObj.status==200)
            {
	            result = AjaxObj.responseText;
	            var resContentType = AjaxObj.getResponseHeader("Content-Type");
	            resultXML = resContentType!=null && resContentType.indexOf("xml")>=0 ? AjaxObj.responseXML : null;
	            
	            if (resultXML!=null && resultXML.documentElement.nodeName === "parsererror" )
	            {
		            parseXmlError(resultXML);
		            return;
	            }
                if(args!=undefined)
                {
		            args.push(result);
		            if(resultXML!=null)
			            args.push(resultXML);
                    func.apply(document,args);
                }
                else
                {
                    func(result,resultXML);
                }
                if(resultXML==null)
		            applyScript(result);
            }
            else
            {
                result= "!RS!"; // !RESET!
                if(AjaxObj.status!=0)
                {
                    parseHttpError(AjaxObj,url);
                    result= "!ER!"; // !ERROR!
                }
                func(result);
            }
    }
    AjaxObj.send(formBody);
}
//-------------------------------  create a new XML object with root -|OR|- from a string (strXML)
function createXmlObject(root, strXML)
{
	if(strXML) // create from a string
	{
		strXML = strXML.replace(/&/g,'%26');
		if (window.DOMParser) //Ns
		{
			parser=new DOMParser();
			xmlDoc=parser.parseFromString(strXML,"text/xml");
		}
		else // IE
		{
			xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
			xmlDoc.async="false";
			xmlDoc.loadXML(strXML);
			//xmlDoc.load("File.xml");
		}
	}
	else if(root) //  new XML object
	{
		if(window.ActiveXObject) // IE
		{
	        xmlDoc = new ActiveXObject("Msxml.DOMDocument");
			tmpRoot = xmlDoc.createElement(root);
			xmlDoc.appendChild(tmpRoot);
		}
		else if(document.implementation) // Ns
			xmlDoc = document.implementation.createDocument("",root,null);
	}
	if (xmlDoc==null)
	    return null;
	if((xmlDoc.parseError && xmlDoc.parseError.errorCode!=0) // IE
		|| (xmlDoc.documentElement && xmlDoc.documentElement.nodeName === "parsererror"))
	{
		// NOTE: in Chrome,xml error nodeName is still the original <documentElement.nodeName>, not <parsererror>
		parseXmlError(xmlDoc,strXML);
		return null;
	}
	return xmlDoc;
}
//-------------------------------  return a new Http Object
function XmlHttpObject()
{
    if(window.ActiveXObject)
    {
        HttpRequest=new ActiveXObject("Msxml2.XMLHTTP");
        HttpRequest||(HttpRequest=new ActiveXObject("Microsoft.XMLHTTP"))
    }
    else if(window.XMLHttpRequest)
        HttpRequest=new XMLHttpRequest;

    return HttpRequest;
}

var GlobalXHRobj=null; // Global XML HttpRequest Object
//-------------------------------  returns 'new' or 'reset' HttpObject
function resetXmlHttpObject()
{
    if (GlobalXHRobj==null)
    {
        if(window.ActiveXObject)
        {
            GlobalXHRobj=new ActiveXObject("Msxml2.XMLHTTP");
            GlobalXHRobj||(GlobalXHRobj=new ActiveXObject("Microsoft.XMLHTTP"))
        }
        else if(window.XMLHttpRequest)
            GlobalXHRobj=new XMLHttpRequest;
    }
    else if(GlobalXHRobj.readyState!= 0)
    {
        GlobalXHRobj.abort();
    }
    return GlobalXHRobj;
}
//-------------------------------  abort a 'RESETable' Ajax Action
function abortHttpRequest()
{
    try { GlobalXHRobj.abort(); }
    catch(e){}
}
//------------------------------- returns URIComponent from the form elements 
function setBody(form)
{
    frm=gel(form);
    FormElements = new Array();
    var ParameterStr;
    for(i=0; i<frm.elements.length; i++)
    {
        elm=frm.elements[i];
		if(elm.name=='')
			continue;
		if(elm.type=='checkbox' || elm.type=='radio')
			if(!elm.checked)
				continue;
 
		ParameterStr = encodeURIComponent(elm.name);
        ParameterStr += "=";
        ParameterStr += encodeURIComponent(elm.value);
        FormElements.push(ParameterStr);
    }
    //alert(FormElements.join("\n"));
    return FormElements.join("&");
}
//------------------------------- add Ajax-received scripts to current page
function applyScript(scriptSTR)
{
    var HiddenDIV = gel('HiddenDIV_ScriptSettler');
	if(!HiddenDIV)
	{
		HiddenDIV=document.createElement('div');
		HiddenDIV.id="HiddenDIV_ScriptSettler";
	}
    HiddenDIV.innerHTML = '.'+scriptSTR; // '.' is added 4 IE innerHTML problem
    var scriptsText = '';
    var scriptArr = HiddenDIV.getElementsByTagName('script');
    for(var i=0; i<scriptArr.length; i++)
    {
        var scriptSrc = scriptArr[i].src;
        if (scriptSrc != null && scriptSrc != '')
        {
            var scriptTag = document.createElement('script');
            scriptTag.type = 'text/javascript';
            scriptTag.src = scriptSrc;
            if (!document.getElementsByTagName('HEAD')[0])
                document.createElement('HEAD').appendChild(scriptTag)
            else
                document.getElementsByTagName('HEAD')[0].appendChild(scriptTag);
        }
        else
        {
            eval(scriptArr[i].text);
            //scriptsText = scriptArr[i].text;
        }
    }
    /*if(scriptsText.trim() != '')
    {
        var scriptTag = document.createElement('SCRIPT');
        scriptTag.type = 'text/javascript';
        scriptTag.text = scriptsText;
        if (!document.getElementsByTagName('HEAD')[0])
            document.createElement('HEAD').appendChild(scriptTag)
        else
            document.getElementsByTagName('HEAD')[0].appendChild(scriptTag);
    }*/
}
//------------------------------- (ONLY FOR ASPX SERVER ERRORS) alert occured error  */
function parseHttpError(obj,url)
{
    if(!_jax_sser) return;
	
	res=obj.responseText;
    if(res.indexOf("Compiler Error Message: </b>")!=-1)
    {
        a=res.indexOf("Compiler Error Message: </b>")+28;
        b=res.indexOf("Source Error:")-13;
    }
    else if(res.indexOf("<title>")!=-1)
    {
        a=res.toLowerCase().indexOf("<title>")+7;
        b=res.toLowerCase().indexOf("</title>");
    }
    else
    {
        a=0;
        b=1;
    }
    erMsg="Error Message:\n"+res.substring(a,b);
    
    if(res.lastIndexOf("=red>Line")!=-1)
    {
        c=res.lastIndexOf("=red>Line")+9;
        d=res.lastIndexOf("=red>Line")+19;
        erMsg+="\nLine: "+res.substring(c,d).replace(":","");
    }
    else
        erMsg+="\nLine: ---";
    url=url.substring(0,url.lastIndexOf('.aspx')+5);
    try
    { 
        openWin('text',"<img height='17' src='../Images/cancel.png' />&nbsp;<b>Connection Error:</b><br><b>Url:</b> "+url+"<br>"+erMsg.replace(/\n/g,'<br>'),'Connection Error', 300, 200); 
    }
    catch(er) 
    { 
        alert("\nError:"+obj.status+"\nConnection Error:\n"+url+"\n\n"+erMsg); 
    }
}
//-------------------------------  parse XML Error
function parseXmlError(objXML)
{
	if(!_jax_sser) return;
	
	if(typeof XMLSerializer=="function")
	{
		errText = new XMLSerializer().serializeToString(xmlDoc);
		var reError = /<parsererror ([\s\S]*?)>([\s\S]*?)Location:([\s\S]*?)Line Number (\d+), Column (\d+):<sourcetext>([\s\S]*?)(?:\-*\^)/;
		arrMatches = reError.exec(errText);
		/*arrMatches = reError.test(errText);
		gel("d2").innerHTML = "<b>"+ (arrMatches?"OK":"-") + "</b><br>" +errText +"<br>t: " + RegExp.$0;*/
	}
	try
	{
		errCode = (xmlDoc.parseError ? xmlDoc.parseError.errorCode : arrMatches[4]);
		errDesc = (xmlDoc.parseError ? xmlDoc.parseError.reason : arrMatches[2]);
		errLine = (xmlDoc.parseError ? xmlDoc.parseError.line : arrMatches[4]);
		errChar = (xmlDoc.parseError ? xmlDoc.parseError.linePos : arrMatches[5]);
		errFile = (xmlDoc.parseError ? xmlDoc.parseError.filePos : arrMatches[3]);
		errSrc = (xmlDoc.parseError ? xmlDoc.parseError.srcText : arrMatches[6]);
		errUrl = (xmlDoc.parseError ? xmlDoc.parseError.url : arrMatches[3]);
		errMsg = "<b>errCode:</b> "+errCode+"\n" +
				"<br><b>errDesc:</b> "+errDesc+"\n" +
				"<br><b>errLine:</b> "+errLine+"\n" +
				"<br><b>errChar:</b> "+errChar+"\n" +
				"<br><b>errFile:</b> "+errFile+"\n" +
				"<br><b>errSrc:</b> "+errSrc+"\n"+
				"<br><b>errUrl:</b> "+errUrl+"\n";
		openWin('text', "<img height='17' src='../Images/cancel.png' />&nbsp;<b>Xml parsing Error:</b><br>" + errMsg.replace(/\n/g,'') ,'Xml parsing Error', 400, 200);
	}
	catch(er)
	{
		alert("error:\n"+er.message+"\n\nXML error:\n" + errText.pureText());
	}
}
//-------------------------------  parse Json string
function parseJson(sData)
{
	if (!sData || typeof sData != "string" || sData=='!RS!' || sData=='!ER!') return null;
	try { return eval(sData); }
    catch(e) 
    { 
        if(_jax_sser)
        {
            errMsg = "<img height='17' src='../Images/cancel.png' />&nbsp;<b>Json parsing Error:</b><br>"
                  + "<b>Message:</b><br>"+e.message+"<br><b>sData:</b><br>"+sData;
            openWin('text', errMsg.replace(/\n/g,'') ,'Json parsing Error', 300, 200);
        }
        return null;
    }
}
//-------------------------------  Effect class:
function Effect(obj, effectType, flag, args)
{
    this.obj=obj;
    this.effectType=effectType;
    this.flag=flag;
    this.args=args;
    this.firstLength;
    this.lastLength;
    this.speed;
    this.timer=1;
    this.arrEffects=['fade','expand','animcolor','dropdown'];
    this.effectVars={
        totalframes:0,
        frameCounter:0
    }
    this.afterEffect=null; // a user function to define after an effect process
}
Effect.prototype.run= function()
{
    this.obj = typeof this.obj=='string'? gel(this.obj) : this.obj;
    if(!this.obj)
    {
        alert("Object "+this.obj+" Not Found!!!");
        return false;
    }
    if(!this.effectType)
    {
        alert("Effect Not Set!!!");
        return false;
    }
    this.effectType = this.effectType.toLowerCase();
    var _found=false;
    for(i=0;i<this.arrEffects.length;i++)
        if(this.effectType==this.arrEffects[i])
        {
            _found=true;
            break;
        }
    if(!_found)
    {
        alert("Effect Not Supported!!!");
        return false;
    }
    if(this.flag==null)
    {
        alert("flag Not set!!!");
        return false;
    }
    //this.timer = clearTimeout(this.timer);
    
    switch(this.effectType)
    {
        case 'expand': 
            this.speed= (this.args && this.args[0]) ? parseInt(this.args[0]) : 30;
            try{
                this.lastLength= (this.args && this.args[1]) ? parseInt(this.args[1]) : this.flag? this.obj.scrollHeight:0;
            }
            catch(er){this.lastLength=0;}
            this.firstLength= (this.args && this.args[2]) ? parseInt(this.args[2]) : this.flag? 1:this.obj.clientHeight;
            //!this.lastLength && (this.lastLength=0);
            with(this.obj.style)
            {
                overflow = 'hidden';
                height=this.firstLength+'px';
                display='';
            }
            // since if display=none -> obj.scrollHeight:0; below code must be after the obj.display='' 
            if(this.args && this.args[1] && this.args[1].toString().toLowerCase()=='auto')
                this.lastLength = this.obj.scrollHeight;
            break;
        case 'fade':
            this.speed= (this.args && this.args[0]) ? parseInt(this.args[0]) : 20;
            this.lastLength= (this.args && this.args[1]) ? parseFloat(this.args[1]) : this.flag? 1:0;
            this.firstLength = (this.args && this.args[2]) ? parseFloat(this.args[2]) : this.flag? 0:1;
            
            setOpacity(this.obj,this.firstLength);
            this.obj.style.display='';
            break;
		case 'animcolor':
			this.speed= (this.args && this.args[0]) ? parseInt(this.args[0]) : 50;
			this.lastLength = (this.args && this.args[1])? this.args[1] : '#ffffff';
            this.firstLength = (this.args && this.args[2])? this.args[2] : '#000000';
			this.effectVars.totalframes = Math.ceil(1000/this.speed); //default:20
		    break;
		case 'dropdown':
		    if(this.obj.getAttribute("Flag")==null)
		        this.obj.setAttribute("Flag",!this.flag);
		    else
		    {
		        var flag = this.obj.getAttribute("Flag");
	            if(flag=="true")
	            {
		            this.args = [5,'auto'];
		            this.flag=true;
	            }
	            else
	            {
		            this.args=[5,0];
		            this.flag=false;
	            }
	            this.obj.setAttribute("Flag",!this.flag);
	        }
	        //-------
		    this.speed= (this.args && this.args[0]) ? parseInt(this.args[0]) : 30;
            try
            {
                this.lastLength= (this.args && this.args[1]) ? parseInt(this.args[1]) : this.flag? this.obj.scrollHeight:0;
            }
            catch(er){this.lastLength=0;}
            this.firstLength= (this.args && this.args[2]) ? parseInt(this.args[2]) : this.flag? 1:this.obj.clientHeight;
            //!this.lastLength && (this.lastLength=0);
            with(this.obj.style)
            {
                overflow = 'hidden';
                height=this.firstLength+'px';
                display='';
            }
            // since if display=none -> obj.scrollHeight:0; below code must be after the obj.display='' 
            if(this.args && this.args[1] && this.args[1].toString().toLowerCase()=='auto')
                this.lastLength = this.obj.scrollHeight;
            break;
    }
    eval("this."+this.effectType+"();");
}
Effect.prototype.fade= function()
{
    var slf = this;
    clearInterval(slf.timer);
    slf.timer = setInterval(
        function()
        {
            //------IE
            if(slf.obj.filters)
            {
                a = slf.obj.style.filter? slf.obj.style.filter : slf.obj.style.filter="alpha(opacity=100)";
                opc = parseFloat(a.substring(14,a.length-1)/100);
            }
            //------FF
            else
            {
                a = slf.obj.style.opacity ? slf.obj.style.opacity : slf.obj.style.opacity=1;
                opc = parseFloat(a);
            }
            
            if(slf.flag) // fade In
            {
                opc+=0.3;
                if(slf.obj.filters)
                    slf.obj.style.filter="alpha(opacity="+parseInt(opc*100)+")";
                else
                    slf.obj.style.opacity=opc;
                if(opc>slf.lastLength)
                {
                    if(slf.obj.filters)
                        slf.obj.style.filter="alpha(opacity="+parseInt(slf.lastLength*100)+")";
                    else
                        slf.obj.style.opacity = slf.lastLength;
                    if(slf.lastLength==0)
                    {
                        slf.obj.style.display='none';
                        //slf.obj.style.visibility='hidden';
                    }
                    clearInterval(slf.timer);
                    if(typeof slf.afterEffect == 'function') slf.afterEffect(slf.obj);
                }
            }
            else // fade Out
            {
                opc-=0.1;
                if(slf.obj.filters)
                    slf.obj.style.filter="alpha(opacity="+parseInt(opc*100)+")";
                else
                    slf.obj.style.opacity=opc;
                if(opc<slf.lastLength)
                {
                    if(slf.obj.filters)
                        slf.obj.style.filter="alpha(opacity="+parseInt(slf.lastLength*100)+")";
                    else
                        slf.obj.style.opacity = slf.lastLength;
                    if(slf.lastLength==0)
                    {
                        slf.obj.style.display='none';
                        //slf.obj.style.visibility='hidden';
                    }
                    clearInterval(slf.timer);
                    if(typeof slf.afterEffect == 'function') slf.afterEffect(slf.obj);
                }
            }
        }
    ,slf.speed);
}
Effect.prototype.expand= function()
{
    var slf = this;
    clearInterval(slf.timer);
    slf.timer = setInterval(
        function()
        {
            if(slf.flag) // Expand
            {
                Hi = parseInt(slf.obj.style.height);
                Hi+=10;
                slf.obj.style.height=Hi+"px";
                if(Hi>slf.lastLength)
                {
                    slf.obj.style.height=slf.lastLength+"px";
                    clearInterval(slf.timer);
                    if(typeof slf.afterEffect == 'function') slf.afterEffect(slf.obj);
                }
            }
            else // Toggle
            {
                Hi = parseInt(slf.obj.style.height);
                Hi-=10;
                    slf.obj.style.height=(Hi>0 ? Hi : slf.lastLength+1)+"px";
                if(Hi<parseInt(slf.lastLength+1))
                {
                    slf.obj.style.height=slf.lastLength+1+"px";
                    slf.lastLength==0 && (slf.obj.style.display='none');
                    clearInterval(slf.timer);
                    if(typeof slf.afterEffect == 'function') slf.afterEffect(slf.obj);
                }
            }
        }
    ,slf.speed);
}
Effect.prototype.animcolor= function()
{
    var slf = this;
    var existStyles = getStyle(slf.obj);
    clearInterval(slf.timer);
    slf.timer = setInterval(
        function()
        {
            var b = color2rgb(slf.firstLength);
            var e = color2rgb(slf.lastLength);
            var change0=e[0]-b[0];
            var change1=e[1]-b[1];
            var change2=e[2]-b[2];
            var frame = slf.effectVars.frameCounter++;
            
            var inc0 = b[0]+change0*(frame/slf.effectVars.totalframes);
	        var inc1 = b[1]+change1*(frame/slf.effectVars.totalframes);
	        var inc2 = b[2]+change2*(frame/slf.effectVars.totalframes);
            setStyle(slf.obj, existStyles+';'+slf.flag+': rgb('+parseInt(inc0)+','+parseInt(inc1)+','+parseInt(inc2)+')');
            slf.effectVars.frameCounter++;

            if(parseInt(slf.effectVars.frameCounter) > parseInt(slf.effectVars.totalframes))
            {
                clearInterval(slf.timer);
                if(typeof slf.afterEffect == 'function') slf.afterEffect(slf.obj);
            }
        }
    ,slf.speed);
}
Effect.prototype.dropdown = function()
{
    /*----- if effect is for a related group:
    for(var i=1;i<=4;i++)
	{
		if(i!=id)
		{
			if(gel('Div_'+i).style.display!='none')
			{
				var efObj1 = new Effect('Div_'+i,'expand',false,[5,0]);
				efObj1.run();
			}
			gel('Title_'+i).setAttribute("Flag","false");
		}
	}
	efObj.obj = gel('Div_'+id);
	*/
	//-----------
	var slf = this;
    clearInterval(slf.timer);
    slf.timer = setInterval(
        function()
        {
            if(slf.flag) // Expand
            {
                Hi = parseInt(slf.obj.style.height);
                Hi+=10;
                slf.obj.style.height=Hi+"px";
                if(Hi>slf.lastLength)
                {
                    slf.obj.style.height=slf.lastLength+"px";
                    clearInterval(slf.timer);
                    if(typeof slf.afterEffect == 'function') slf.afterEffect(slf.obj);
                }
            }
            else // Toggle
            {
                Hi = parseInt(slf.obj.style.height);
                Hi-=10;
                    slf.obj.style.height=(Hi>0 ? Hi : slf.lastLength+1)+"px";
                if(Hi<parseInt(slf.lastLength+1))
                {
                    slf.obj.style.height=slf.lastLength+1+"px";
                    slf.lastLength==0 && (slf.obj.style.display='none');
                    clearInterval(slf.timer);
                    if(typeof slf.afterEffect == 'function') slf.afterEffect(slf.obj);
                }
            }
        }
    ,slf.speed);
	
}
//-------------------------------
function d2h(dec) { return dec.toString(16); }
function h2d(hex) { return parseInt(hex,16); }

function rgb2h(r,g,b) { return [d2h(r),d2h(g),d2h(b)]; }
function h2rgb(h,e,x) { return [h2d(h),h2d(e),h2d(x)]; }

//--- return [R,G,B] array
function color2rgb(color) 
{
    if(color.indexOf('rgb')<=-1) // need 4 IE if color format is hex (#------)
		return h2rgb(color.substring(1,3),color.substring(3,5),color.substring(5,7));
    return color.substring(4,color.length-1).split(',');
}
//------------------------------- initTooltip (obj:[obj,objId], tooltipDIV:[DIVobj,DIVid], type:[null,mobile], effect:[null,fade,expand], ajaxURL:[null,url], args[null,effectArgs])
function Tooltip(obj, tooltipDIV, type, effect, ajaxUrl, args)
{
    this.obj = typeof obj=='string'? gel(obj) : obj;
    this.tooltipDIV = typeof tooltipDIV=='string'? gel(tooltipDIV) : tooltipDIV;
    this.type = type;
    this.effect = effect;
    this.ajaxUrl = ajaxUrl;
    this.args = args;
    this._effectObj=null;
    this._tooltipDisplay = false; // if effect is 'expand'
    this._ajaxAlreadyReceived = false; // true if AjaxResponse was received
    this.init();
}
Tooltip.prototype.init = function()
{
    this.effect && (this.effect= this.effect.toLowerCase());
    this.tooltipDIV.style.position='absolute';
    this.tooltipDIV.style.display='none';
    //tooltipDIV.style.visibility='hidden';
    
    if(this.effect)
        switch(this.effect)
        {
            case 'fade' : setOpacity(this.tooltipDIV,0);break;
            case 'expand' : 
                this.tooltipDIV.style.overflow='hidden';
                //tooltipDIV.style.height='0px';
                break;
            case 'animcolor': ;break;
        }
    if(this.type && this.type.toLowerCase()=='mobile')
        this.type = 'mousemove';
    else this.type = 'mouseover';
    
    var slf = this;
    addEvent(this.obj,this.type,function(){ slf.show(arguments[0]) });
    addEvent(this.obj,'mouseout',function(){ slf.hide(arguments[0]) });
}
Tooltip.prototype.setPosition = function()
{
    var evt = new Evt(arguments[0]);
    var otop = 0;
    var oleft = 0;
    
    if(isIE)
    {
        /*
        alert("-----src:\noffsetTop:"+evt.source.offsetTop+"\nclientTop:"+evt.source.clientTop+"\noffsetHeight:"+evt.source.offsetHeight+"\nclientHeight:"+evt.source.clientHeight+"\nscrollTop:"+evt.source.scrollTop+"\nscrollHeight:"+evt.source.scrollHeight+"\n-----doc:\n"+
        "offsetTop:"+document.body.offsetTop+"\nclientTop:"+document.body.clientTop+"\noffsetHeight:"+document.body.offsetHeight+"\nclientHeight:"+document.body.clientHeight+"\nscrollTop:"+document.body.scrollTop+"\nscrollHeight:"+document.body.scrollHeight+"\n"+"\n-----div:\n"+
        "offsetTop:"+this.tooltipDIV.offsetTop+"\nclientTop:"+this.tooltipDIV.clientTop+"\noffsetHeight:"+this.tooltipDIV.offsetHeight+"\nclientHeight:"+this.tooltipDIV.clientHeight+"\nscrollTop:"+this.tooltipDIV.scrollTop+"\nscrollHeight:"+this.tooltipDIV.scrollHeight+"\n"+
        "-----mos:\nY:"+window.event.y+"\nclientY:"+window.event.clientY+"\noffsetY:"+window.event.offsetY+"\n");
        */
        //---set Y pos
        otop = window.event.offsetY + 25;
        if(window.event.y!=window.event.clientY)
        {
            oParents = evt.source;
            while((oParents = oParents.offsetParent) != null) otop += oParents.offsetTop;
        }
        //---set X pos
        oleft += window.event.offsetX + 10;
        oleft -= this.tooltipDIV.offsetWidth;
        if(window.event.y!=window.event.clientY)
        {
            oParents = evt.source;
            while((oParents = oParents.offsetParent) != null) oleft += oParents.offsetLeft;
        }
        else
          oleft +=25;  
    }
    else
    {
        otop = evt.pageY + 10;
        oleft = evt.pageX - this.tooltipDIV.offsetWidth;
    }
    if(otop + this.tooltipDIV.offsetHeight+25 > document.body.clientHeight)
    {
        //otop = otop - this.tooltipDIV.offsetHeight - (isIE? 3 : 13);
        otop<0 && (otop=0);
    }
    if(oleft + this.tooltipDIV.offsetWidth+10 > document.body.clientWidth)
    {
        //oleft = oleft - this.tooltipDIV.offsetWidth - (isIE? 12 : 15);
        oleft<0 && (oleft=0);
    }
    this.tooltipDIV.style.top = otop + 'px';
    this.tooltipDIV.style.left = oleft + 'px';
}
Tooltip.prototype.show = function()
{
    this.setPosition(arguments[0]);
    
    //--if Ajax
    if(this.ajaxUrl && this.ajaxUrl.trim()!='' && !this._ajaxAlreadyReceived)
    {
        this._ajaxAlreadyReceived=true;
        this.tooltipDIV.innerHTML = "<img src='Images/loader.gif' border='0' alt='loading...'>"; 
        var slf = this;
        reGetFromHttpRequest('get',this.ajaxUrl,null,function(){
            if(result != "!ER!" && result != "!RS!")
               slf.tooltipDIV.innerHTML = result;
               slf.tooltipDIV.style.height='auto';
        });
    }
    //--if effect
    if(this.effect)
    {
        if(!this._tooltipDisplay)
        {
            this._tooltipDisplay=true;
            if(this._effectObj==null)
            {
                this._effectObj = new Effect(this.tooltipDIV,this.effect,true,this.args);
                //this._effectObj = new Effect(this.tooltipDIV,this.effect,true);
            }
            else
            {
                this._effectObj.flag = true;
                this._effectObj.args = this.args;
                //this._effectObj.args = null;
            }
            this._effectObj.run();
        }
    }
    else
        this.tooltipDIV.style.display='';
    if(this.type == 'mouseover') // if DIV locates out of window
        this.setPosition(arguments[0]);
}
Tooltip.prototype.hide = function()
{
    if(this._tooltipDisplay) this._tooltipDisplay=false;
    var evt = new Evt(arguments[0]);
    if(this.effect)
    {
        if(this._effectObj==null)
        {
            this._effectObj = new Effect(this.tooltipDIV,this.effect,false);
            //this._effectObj = new Effect(this.tooltipDIV,'expand',false,[10,0]);
        }
        else
        {
            this._effectObj.flag = false;
            this._effectObj.args = [10,null];
            //this._effectObj.args = [2,null];
        }
        this._effectObj.run();
    }
    else
        this.tooltipDIV.style.display='none';
}
//------------------------------- Event class & methods:
function Evt(evt) 
{
    this.evt = evt ? evt : window.event;
    this.source = evt.target ? evt.target : evt.srcElement;
    this.dest = evt.relatedTarget ? evt.relatedTarget : evt.toElement;
    this.key = evt.which ? evt.which : evt.keyCode;
    this.x = evt.clientX;
    this.y = evt.clientY;
    this.pageX = evt.pageX ? evt.pageX : /*IE*/ evt.clientX+document.body.scrollLeft;
    this.pageY = evt.pageY ? evt.pageY : /*IE*/ evt.clientY+document.body.scrollTop;
    this.shift = evt.shiftKey;
    this.alt = evt.altKey;
    this.ctrl = evt.ctrlKey;
}
Evt.prototype.info = function () 
{
    return "key:"+this.key
       +(this.x!=null ? "\n[x="+this.x+", y="+this.y+"]":"")
       +(this.source!=null ? "\nsrc:"+this.source.tagName+" #"+this.source.id : "");
};
//-------------------------- Add Event to an object
function addEvent(elm, evType, fn, useCapture)
{
    var ret = 0;

    if (elm.addEventListener) //IE
        ret = elm.addEventListener(evType, fn, useCapture);
    else if (elm.attachEvent) //Ns
        ret = elm.attachEvent('on'+evType , fn);
    else
        elm['on'+evType] = fn;
    return ret;
}
//------------------------------- Remove Event from an object
function removeEvent(target,type,func,bubbles) 
{
    if (document.removeEventListener) {     target.removeEventListener(type,func,bubbles);    } 
    else if (document.detachEvent) {     target.detachEvent("on"+type,func,bubbles);    } 
    else {     target["on"+type] = null;    }
}
//------------------------------- Remove Event default action
function cancelEvent(evt)
{
    /// must be declared in "onkeypress" insteadof "onkeydown" (else !opera)
    !evt && (evt=window.event);
    if (evt.stopPropagation) evt.stopPropagation(); 
    if (evt.cancelBubble) evt.cancelBubble = true; 
    if (evt.preventDefault) evt.preventDefault(); 
    //if (window.event) window.event.returnValue = false;
    return false;
}
//-------------------------------  check if 'node2' is located inside 'node1'
function contains(node1, node2)
{
  if(node2 == node1) return true;
  if(node2 == null) return false; 
  else return contains(node1, node2.parentNode);
}
//-------------------------------  fill the dest-Combobox according to the refValue  <srcComboId>RelJson: ([{"text":"@1","value":"@2","pId":"@3"},{...}])
function resetComboBox(srcComboId, destComboId, firstOption) 
{
     while( gel(destComboId).options.length>0)
        gel(destComboId).options[0] = null;

     var index = 0;
     if(firstOption)
     {
         gel(destComboId).options[0] = new Option(firstOption[0], firstOption[1]);
         index++;
    }
    
    if(gel(srcComboId).value=='-1' || gel(srcComboId).value.trim()=='')
        return;

    var arrOpts = parseJson(eval(srcComboId + 'RelJson'));
    if (arrOpts)
        for (var i = 0; i < arrOpts.length; i++)
            if (arrOpts[i].pId == gel(srcComboId).value)
                gel(destComboId).options[index++] = new Option(arrOpts[i].text, arrOpts[i].value);

    if(index==0)
        gel(destCombo).options[0] = new Option('------', '-1');
}
//-------------------------------  fill the dest-Combobox according to the refValue - Json result: ([{"text":"@1","value":"@2"},{...}])
function setComboBox(destCombo, refValue, url, firstOption, func)
{
    var destCombo = typeof destCombo=='string' ? gel(destCombo) : destCombo;
    
    while(destCombo.options.length>0)
        destCombo.options[0] = null;
    
    if(refValue=='-1' || refValue.trim()=='')
    {
        if(firstOption)
            destCombo.options[0] = new Option(firstOption[0], firstOption[1]);
        else
            destCombo.options[0] = new Option('------',refValue);
        return;
    }
    var msg_Saving = 'درحال جستجو';
    destCombo.options[0] = new Option(msg_Saving+'...',(firstOption ? firstOption[1] : '-1'));
    
    var sign = url.indexOf('?')==-1 ? '?' : '&';
    url += sign+'Action=GetSubOptions&RefValue='+refValue;
    getFromHttpRequest('get',url,null,function(){
		if(result=='expired')
        {
            window.location.replace('Login.aspx?ex='+new Date().getTime());
            return;
        }
        if(result.indexOf('!ER!')!=-1 || result=='!RS!')
        {
            destCombo.options[0] = new Option((firstOption? firstOption[0] : '------'), (firstOption? firstOption[1] : '-1'));
            return;
        }
        var index = 0;
        if (firstOption)
		{
			destCombo.options[0] = new Option(firstOption[0], firstOption[1]);
			index++;
		}
		var arrOpts = parseJson(result);
		if(arrOpts)
		    for(var i=0;i<arrOpts.length;i++)
			    destCombo.options[index++] = new Option(arrOpts[i].text,arrOpts[i].value);
		//destCombo.disabled=false;
		if(func)
		    func(arrOpts);
    });
}
//-------------------------------  fill a Tbody(tbodyId) by parsing rowsStr
function fillTableList(tbodyId,rowsStr,appendFlag)
{
    var index = 0;
    if(gel(tbodyId))
    {
        tbd = gel(tbodyId);
        index = tbd.rows.length;
    }
    else
    {
        tbd = document.createElement('tbody');
        tbd.id = tbodyId;
        index = 0;
    }
    
    if(!appendFlag)
    {
        while(tbd.rows.length>0)
            tbd.deleteRow(0);
        index = 0;
    }
    var tbdParent = tbd.parentNode;
	var oFragment = document.createDocumentFragment();
	oFragment.appendChild(tbd);
	
    tblXml = createXmlObject(null,"<table>"+rowsStr+"</table>");
    //arrTr = parseJson(rowsStr); # if json was prefered in future
    for(i=0;i<tblXml.documentElement.childNodes.length;i++)
    {
		trChild = tblXml.documentElement.childNodes[i];
		oTr = tbd.insertRow(index);
        oTr.id = tbodyId+'_tr'+index; // ID of new TR row
        
		for(j=0;j<trChild.attributes.length;j++)
			oTr.setAttribute(trChild.attributes[j].name,trChild.attributes[j].value);
        
		for(j=0;j<trChild.childNodes.length;j++)
        {
            tdChild = trChild.childNodes[j];
			oTd = tbd.rows[index].insertCell(j);
            oTd.id= tbodyId+'_tr'+index+'_td'+j; // ID of new TD cell
			
			for(k=0;k<tdChild.attributes.length;k++)
				oTd.setAttribute(tdChild.attributes[k].name,tdChild.attributes[k].value);
			
            oTd.innerHTML = tdChild.textContent ? tdChild.textContent /*Ns*/ : tdChild.text /*IE*/;
        }
        index++;
    }
    if(tbdParent!=null)
        tbdParent.appendChild(oFragment);
    else
        return oFragment;
/*
object.colSpan [ = iCount ]
iCount Integer that specifies or receives the number of columns to span. 
This property can be changed only after the page has been loaded. 
---or----
object.setAttribute(sName, vValue [, iFlags])
sName Required. String that specifies the name of the attribute. 
vValue Required. Variant that specifies the string, number, or Boolean to assign to the attribute.  
iFlags Optional. Integer that specifies one the following flags: 
0 When the attribute is set, it overwrites any attributes with the same name, regardless of their case. 
1 Default. The case of the attribute that you set is respected when it is set on the object. 
---or----
object.setExpression("colspan","2");


<td colspan="n" style="width: auto;">...</td>

*/
}
//------------------------------  Sort list of the table by a specified column
function sortTable(tbodyId, iCol, dataType)
{
	var tbd = gel(tbodyId);
	var colDataRows = oTBody.rows;
	var aTRs = new Array();
	for (var i=0; i < colDataRows.length; i++)
		aTRs[i] = colDataRows[i];
		
	if (tbd.sortCol && tbd.sortCol == iCol)
		aTRs.reverse();
	else
		aTRs.sort(generateCompareTRs(iCol,dataType));
	
	var oFragment = document.createDocumentFragment();
	for (var i=0; i < aTRs.length; i++)
		oFragment.appendChild(aTRs[i]);
	
	tbd.appendChild(oFragment);
}
function generateCompareTRs(iCol,dataType) {
	return function compareTRs(oTR1,oTR2) 
	{
		var val1 = convert(oTR1.cells[iCol].firstChild.nodeValue, dataType);
		var val2 = convert(oTR2.cells[iCol].firstChild.nodeValue, dataType);
		if (val1 < val2) return -1;
		else if (val1 > val2) return 1;
		else return 0;
	};
}
function convert(val,dataType) 
{
	switch(dataType) 
	{
		case "int": return parseInt(val);
		case "float": return parseFloat(val);
		case "date": return new Date(Date.parse(val));
		default: return val.toString();
	}
}
//------------------------------ Popup window
function openWin(type, strContent ,title, width, height)
{
    if(window.parent)
        window.parent.window.openWinMain(type, strContent ,title, width, height)
    else
        openWinMain(type, strContent ,title, width, height)
}
//------------
function openWinMain(type, strContent ,title, width, height)
{
    var lightBoxSurf = gel('MyLightBoxSurface');
	if(!lightBoxSurf)
	{
		lightBoxSurf = document.createElement('div');
		lightBoxSurf.id = 'MyLightBoxSurface';
		lightBoxDIV = document.createElement('div');
		lightBoxDIV.id = "MyLightBoxDiv";
		lightBoxDIV.innerHTML = "<div id='MyLightBoxTitle'><span id='Sp_MyLightBoxTitle' onmousedown='dragPress(event)'>&nbsp;</span>\n"
		    + "<img id='MyLightBoxCloseBtn' src='../Images/close.gif' onclick=\"closeWin('"+type+"')\" /></div>\n";
		lightBoxContent = document.createElement('div');
		lightBoxContent.id = 'MyLightBoxContent';
		lightBoxDIV.appendChild(lightBoxContent);
	}
	switch(type)
	{
	    case 'iframe':
	        var iContent = gel('MyLightBoxContent_Iframe');
	        if(!iContent)
	        {
	            iContent = document.createElement('iframe');
	            iContent.id="MyLightBoxContent_Iframe";
	            iContent.frameBorder="0";
	            lightBoxContent.appendChild(iContent);
	        }
	        break;
	    case 'text':
	    case 'div':
	    case 'ajax':
	        var iContent = gel('MyLightBoxContent_Passage');
	        if(!iContent)
	        {
	            var iContent = document.createElement('p');
	            iContent.id="MyLightBoxContent_Passage";
	            lightBoxContent.appendChild(iContent);
	        }
	        break;
	}
	document.body.appendChild(lightBoxSurf);
	document.body.appendChild(lightBoxDIV);

	gel('Sp_MyLightBoxTitle').innerHTML = title;
	lightBoxDIV = gel('MyLightBoxDiv');
	
	//ScrWidth = parseInt(screen.availWidth);
    //ScrHeight = parseInt(screen.availHeight);
    width==null && (width = '600'/*parseInt(document.body.clientWidth) / 2*/);
    height==null && (height = '300'/*parseInt(document.body.clientHeight) / 2*/);
    var xPos=Math.round(parseInt(document.body.scrollLeft) + (parseInt(document.body.clientWidth) / 2 - parseInt(width) / 2));
	var yPos=Math.round(parseInt(document.body.scrollTop) + (parseInt(document.body.clientHeight) / 2 - parseInt(height) / 2));
	//alert("yPos:"+yPos + "\nscrollTop:" +document.body.scrollTop +"\nclientHeight:"+ document.body.clientHeight +"\nH:"+ height);
	if(xPos<0) xPos = 5;
	if(yPos<0) yPos = 5;
	lightBoxDIV.style.left=xPos+'px';
	lightBoxDIV.style.top=yPos+'px';
	lightBoxDIV.style.width=width+'px';
	lightBoxDIV.style.height=height+'px';
	
	gel('MyLightBoxContent_Iframe') && (gel('MyLightBoxContent_Iframe').style.display='none');
    gel('MyLightBoxContent_Passage') && (gel('MyLightBoxContent_Passage').style.display='none');
	switch(type)
	{
	    case 'iframe': 
	        gel('MyLightBoxContent_Iframe').style.display='';
	        gel('MyLightBoxContent_Iframe').src=strContent; break;
	    case 'text':
	        gel('MyLightBoxContent_Passage').innerHTML=strContent; 
	        gel('MyLightBoxContent_Passage').style.display=''; break;
	    case 'div':
	        if(typeof strContent=='string') strContent = gel(strContent);
	        var divContent = strContent.innerHTML;
			if(isIE)
			    divContent = "<table width='100%'><tr><td>"+divContent+"</td></tr></table>";
	        gel('MyLightBoxContent_Passage').innerHTML = divContent;
	        gel('MyLightBoxContent_Passage').style.display=''; break;
	    case 'ajax':
	        var preLoad = "<br><p width='100%' align='center'><img src='../Images/ajax_loader.gif'></p>";
			var tmpDiv = document.createElement('div');
			tmpDiv.innerHTML = preLoad;
			gel('MyLightBoxContent_Passage').appendChild(tmpDiv);
			gel('MyLightBoxContent_Passage').style.display='';
	        getFromHttpRequest('get',strContent,null,function() { 
	            if(result=='expired')
                {
                    window.location = 'Login.aspx?ex='+new Date().getTime();
                    return;
                }
                if(result!='!ER!' && result!='!RS!')
                {
	                var tmpDiv = document.createElement('div');
	                tmpDiv.innerHTML = result;
	                gel('MyLightBoxContent_Passage').innerHTML = '';
	                gel('MyLightBoxContent_Passage').appendChild(tmpDiv); 
	            }
	        }); break;
	}
	lightBoxSurf.style.display='';
	var effectObj = new Effect('MyLightBoxDiv','fade',true,[10,1,0]);
    effectObj.run();
    if(isIE)
    {
        gel('MyLightBoxSurface').style.height=document.body.clientHeight+'px';
        gel('MyLightBoxSurface').style.width=document.body.clientWidth+'px';
    }
    else
    {
        gel('MyLightBoxSurface').style.position='fixed';
    }
    //addEvent(document,'scroll',checkScroll);
    //window.open(strURL,(target ? target : ''), 'scrollbars=yes,toolbar=no,location=no,directories=no,status=no,menubar=yes,resizable=yes,copyhistory=no,width='+ width +',height='+ height +',left='+ left +', top='+ top);
}
//------------------------------ Close Popup window
function closeWin(type)
{
    gel('MyLightBoxDiv').style.display='none';
    gel('MyLightBoxSurface').style.display='none';
    switch(type)
	{
	    case 'iframe': gel('MyLightBoxContent_Iframe').src='empty.htm'; break;
	    case 'text':
	    case 'div':
	    case 'ajax':
	        gel('MyLightBoxContent_Passage').innerHTML='&nbsp;'; break;
	}
    removeEvent(document,'scroll',checkScroll);
}
var MyLightDeltaX, MyLightDeltaY;
//------------------------------ ready for draging
function dragPress(evtSrc) 
{
    var evt = new Evt(evtSrc);
    var dragbox = gel('MyLightBoxDiv');
    setOpacity(gel('MyLightBoxContent'),0.8);    
    MyLightDeltaX = evt.x - parseInt(dragbox.style.left);
    MyLightDeltaY = evt.y - parseInt(dragbox.style.top);
    addEvent(document,"mousemove",dragMove);
    addEvent(document,"mouseup",dragRelease);
}
//------------------------------ start draging
function dragMove(evtSrc)
{
    var evt = new Evt(evtSrc);
    var dragbox = gel('MyLightBoxDiv');
    dragbox.style.left = (evt.x - MyLightDeltaX)+'px';
    dragbox.style.top = (evt.y - MyLightDeltaY)+'px';
    if(parseInt(dragbox.style.left)<5) dragbox.style.left = '5px';
    if(parseInt(dragbox.style.top)<5) dragbox.style.top = '5px';
    cancelEvent(evtSrc);
}
//------------------------------ stop draging
function dragRelease(evtSrc) 
{
    var evt = new Evt(evtSrc);  
    var dragbox = gel('MyLightBoxDiv');  
    setOpacity(gel('MyLightBoxContent'), 1);    
    removeEvent(document,"mousemove", dragMove);    
    removeEvent(document,"mouseup", dragRelease);  
}
//------------------------------ move box while scrolling
function checkScroll()
{
    with(gel('MyLightBoxDiv').style)
    {
        left=MyLightOffsetX+document.body.scrollLeft+'px';
        top=MyLightOffsetY+document.body.scrollTop+'px';
    }
}
//------------------------------ use for paging list (not Ajax paging)
function goToPage(pageIndex ,frm)
{
    if(typeof(pageIndex)!='number')
    {
        var evt = new Evt(pageIndex);
        if(evt.key!=13)
            return;
        pageIndex=0;
    }
    var pageNo = gel('TxtTargetPage').value;
    if(!isInt(pageNo))
    {
        gel('TxtTargetPage').value = gel(frm).CurrPage.value;
        return;
    }
    nextPage = parseInt(pageNo) + parseInt(pageIndex);
    if(nextPage<1 || nextPage>gel(frm+"_TotalPageCount").value || nextPage==gel(frm).CurrPage.value)
    {
        gel('TxtTargetPage').value = gel(frm).CurrPage.value;
        return;
    }
    gel(frm).CurrPage.value = gel('TxtTargetPage').value = nextPage;
    gel(frm).Action.value='Search'; // ???
    gel(frm).submit();
}
//============================================ Tiny Form-Check ==========================================
//
// isEmpty(s) --empty||space
// isEmail(s)
// isInt(s)
// isFloat(s)
// ---STRING FUNCTIONS:
// trim()
// pureText(HTML text)
// toCamelCase(cssString)
// removeChars(chars)
// removeNotInChars(chars)
// removeSpace()
// contains(char)
// reformat(mask)
//
// ---DATE FUNCTIONS:
// isDate(year, month, day, [lang])
// cmpDate(y1, m1, d1, y2, m2, d2)
// fullCmpDate(y1, m1, d1, y2, m2, d2, nullable, [lang])

var emptyOK = false;
var Space = " \t\n\r";

var daysInMonth = new Array();
daysInMonth[1]  = 31;   daysInMonth[2]  = 29;// must programmatically check this
daysInMonth[3]  = 31;   daysInMonth[4]  = 30;
daysInMonth[5]  = 31;   daysInMonth[6]  = 30;
daysInMonth[7]  = 31;   daysInMonth[8]  = 31;
daysInMonth[9]  = 30;   daysInMonth[10] = 31;
daysInMonth[11] = 30;   daysInMonth[12] = 31;

var ShamsdaysInMonth = new Array();
ShamsdaysInMonth[1]  = 31;   ShamsdaysInMonth[2]  = 31;
ShamsdaysInMonth[3]  = 31;   ShamsdaysInMonth[4]  = 31;
ShamsdaysInMonth[5]  = 31;   ShamsdaysInMonth[6]  = 31;
ShamsdaysInMonth[7]  = 30;   ShamsdaysInMonth[8]  = 30;
ShamsdaysInMonth[9]  = 30;   ShamsdaysInMonth[10] = 30;
ShamsdaysInMonth[11] = 30;   ShamsdaysInMonth[12] = 30;// must programmatically check this

function isEmpty(s)
{   typeof(s)=='object' && (s=s.value);
    return (s == null || s.length == 0 || s.removeSpace().length == 0)
}

function isInt(s,nullable)
{   typeof(s)=='object' && (s=s.value);
    if(nullable && isEmpty(s)) return true;
    if(isNaN(parseInt(s))) return false;
    inx=0;
    if(s.charAt(0)=="-" || s.charAt(0)=="+")
        inx=1;
    for (var i=inx; i<s.length; i++)
        if(isNaN(parseInt(s.charAt(i))))
            return false;
    return true;
}

function isPositive(s,nullable)
{   if(s.charAt(0)=="-") return false;
    return isInt(s,nullable);
}

function isFloat(s,nullable)
{   typeof(s)=='object' && (s=s.value);
    if(nullable && isEmpty(s)) return true;
    return isNaN(parseFloat(s))? false : true;
}

function isEmail(s,nullable)
{   typeof(s)=='object' && (s=s.value);
    if(nullable && isEmpty(s)) return true;
    var reEmail = /^(?:\w+\.?)*\w+@(?:\w+\.?)*\w+\.(?:\w+\.?)*\w+$/i;
    return reEmail.test(s);
}

//=============================| String Functions |================================

String.prototype.trim = function () {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
};

// Remove HTML tags
String.prototype.pureText = function () 
{
    var reTag = /<(?:.|\s)*?>/g;
    return this.replace(reTag, '');
};

// CamelCase CSS-property names
String.prototype.toCamelCase = function() 
{
    var stringArray = this.toLowerCase().split('-');
    if (stringArray.length == 1)
        return stringArray[0];

    var ret = (this.indexOf("-") == 0)
              ? stringArray[0].charAt(0).toUpperCase() + stringArray[0].substring(1)
              : stringArray[0];
    for (var i = 1; i < stringArray.length; i++) {
        var s = stringArray[i];
        ret += s.charAt(0).toUpperCase() + s.substring(1);
    }
    return ret;
};

String.prototype.removeChars = function(chars)
{
    var reChars = eval("/["+chars+"]/g");
    return this.replace(reChars,'');
};

String.prototype.removeNotInChars = function(chars)
{
    var reChars = eval("/[^"+chars+"]/g");
    return this.replace(reChars,'');
};

String.prototype.removeSpace = function()
{   return this.replace(/\s/g,'');
    // return this.removeChars(Space);
};

String.prototype.contains = function(c){
    if(this.indexOf(c)==-1) return false;
    return true;
};

/// # reformat (str, int, str, int ... )       
// 
// NOTE:
//   arguments must be alternately string & integer
// * Must not be more characters than s.length
//
// EXAMPLE:
// * str = "1234567890" --> "(123) 456-7890"
//   str.reformat('(', 3, ') ', 3, '-', 4)
//
// HINT:
// * for already formatted strings:
//   i.  call removeNotInChars to remove the unwanted characters
//   ii. call reformat for the new format.
//   eg: str.removeNotInChars(digits).reformat('(', 3, ') ', 3, '-', 4)

String.prototype.reformat = function reformat()
{   var arg;
    var sPos = 0;
    var retStr = '';

    for (var i = 1; i < arguments.length; i++)
    {
       arg = arguments[i];
       if (i % 2 == 1) retStr += arg;
       else
       {
           retStr += this.substring(sPos, sPos + arg);
           sPos += arg;
       }
    }
    return retStr;
};

//=============================| Date Functions |================================

function daysInFebruary(year)
{   // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (  ((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0) ) ) ? 29 : 28 );
}

function daysInEsfand(year)
{   // Esfand has 29 days in any year+1 evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return ( (((year+1) % 4 == 0) && ( (!((year+1) % 100 == 0)) || ((year+1) % 400 == 0) ) ) ? 30 : 29 );
}

function isDate(year, month, day, lang, nullable)
{
    typeof(year)=='object' && (year=year.value);
    typeof(month)=='object' && (month=month.value);
    typeof(day)=='object' && (day=day.value);
    
    if(nullable && (isEmpty(year) && isEmpty(month) && isEmpty(day)))
       return true;
    else if(!nullable && (isEmpty(year) || isEmpty(month) || isEmpty(day)))
        return false; 
    dateStr = "/((0)?[1-9]|[12][0-9]|3[01])-((0)?[1-9]|1[0-2])-("
            + (lang && lang.toUpperCase()=='FA'?"13|14":"19|20") + "\d{2})/";
    reDate = eval(dateStr);
    if(!reDate.test(day+'-'+month+'-'+year))
        return false;
    
    var intYear = parseInt(year);
    var intMonth = parseInt(month);
    var intDay = parseInt(day);
    
    if(lang && lang.toUpperCase()=='FA')
    {
        if (intDay > ShamsdaysInMonth[intMonth]) return false;
        if ((intMonth == 12) && (intDay > daysInEsfand(intYear))) return false;
    }
    else
    {
        if (intDay > daysInMonth[intMonth]) return false;
        if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;
    }
    return true;
}

function cmpDate(d1_year, d1_month, d1_day, d2_year, d2_month, d2_day)
{
	if (d1_month.length == 1)
		d1_month = '0' + d1_month;
	if (d1_day.length == 1)
		d1_day = '0' + d1_day;
	if (d2_month.length == 1)
		d2_month = '0' + d2_month;
	if (d2_day.length == 1)
		d2_day = '0' + d2_day;
	var d1 = parseInt(d1_year +  d1_month + d1_day);
	var d2 = parseInt(d2_year +  d2_month + d2_day);
	if (d1 > d2)
		return 1;
	if (d1 < d2)
		return -1;
	return 0; // is equal
}

function fullCmpDate(d1_year, d1_month, d1_day, d2_year, d2_month, d2_day, nullable, lang)
{
    doCmp=true;
    if(d1_year=='' && d1_month=='' && d1_day=='')
    {
        if(!nullable)
            return -4;
        else
            doCmp=false;
    }
    else if(!isDate(d1_year,d1_month,d1_day, lang))
        return -1;
    
    if(d2_year=='' && d2_month=='' && d2_day=='')
    {
        if(!nullable)
            return -5;
        else
            doCmp=false;
    }
    else if(!isDate(d2_year,d2_month,d2_day, lang))
        return -2;
    
    if(doCmp)
    {
        if(cmpDate(d1_year,d1_month,d1_day, d2_year,d2_month,d2_day)==1)
            return -3;
    }
    return 1;
}
//-------------------------------------------------------------------------------
function setFocusEffectForIE7()
{
    var aArr = document.getElementsByTagName('input');
    for(i=0;i<aArr.length;i++)
    {
        var elObj = aArr[i];
        if(elObj.type && (elObj.type=='text' || elObj.type=='password'))
        {
            addEvent(elObj,'focus',function(){var srcElm = window.event.srcElement; srcElm.className=srcElm.className+' InputFocus'});
            addEvent(elObj,'blur',function(){var srcElm = window.event.srcElement; srcElm.className=srcElm.className.replace(' InputFocus','')});
        }
    }
    aArr = document.getElementsByTagName('textarea');
    for(i=0;i<aArr.length;i++)
    {
        addEvent(aArr[i],'focus',function(){var srcElm = window.event.srcElement; srcElm.className=srcElm.className+' InputFocus'});
        addEvent(aArr[i],'blur',function(){var srcElm = window.event.srcElement; srcElm.className=srcElm.className.replace(' InputFocus','')});
    }
    /*
    aArr = document.getElementsByTagName('select');
    for(i=0;i<aArr.length;i++)
    {
        addEvent(aArr[i],'focus',function(){window.event.srcElement.className='InputFocus'});
        addEvent(aArr[i],'blur',function(){window.event.srcElement.className=''});
    }
    */
}

//--- add focus effect on input & textarea Tags in case isIE & IEversion<8
if(isIE && parseInt(IEversion)<8)
    setFocusEffectForIE7();

if(!_catch_err)
{
    window.onerror = function(msg,url,line) {
        //alert('Msg'+msg+'\nUrl:'+url+'\nLine:'+line); 
        return true;
    };
}

//=================================
function tmpChangeStyle()
{
    var u = gel('MainStyleLink').href;
    if(u.indexOf('Yellow')==-1)
        gel('MainStyleLink').href='styles/YellowStyle.css';
    else
        gel('MainStyleLink').href='styles/style.css';
}

