﻿/* ----------------------------------------------
 *  Made For HooshCo Neccessary Ajax Functions
 *  By Foad Attar Olyaee 87/08/07
 * ----------------------------------------------
 */

/* return document.getElementById(ElementId) */
function gel(objId)
{
    return document.getElementById ? document.getElementById(objId) : null
}

/* Make a new Http object and Send-Receive via Ajax Request
 * getFromHttpRequest(method[get:post], Responser Url, formId[form:null] , onSucceedFunction name, array of arguments [OPTIONAL])
 * SAMPLE-1: getFromHttpRequest('get','Res.htm',null,func,[1,2]);
 * SAMPLE-2: getFromHttpRequest('post','Res.htm','f1',func);
 */
function getFromHttpRequest(method,url,formId,func,args)
{
    formBody=(formId!=null)?setBody(formId):null;
    var AjaxObj=getXmlHttpObject();
    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;
                                    if(args!=undefined)
                                    {
                                        args.push(result);
                                        func.apply(document,args);
                                    }
                                    else
                                    {
                                        func(result);
                                    }
                                    applyScript(result);
                                    //applyStyle(result);
                                }
                                else
                                {
                                    if(AjaxObj.status!=0)
                                        showError(AjaxObj,url);
                                    result= "Error";
                                }
                           }
    AjaxObj.send(formBody);
}

/* Use one Http object (if object exists -> reset) and Send-Receive via Ajax Request
 * reGetFromHttpRequest(method[get:post], Responser Url, formId[form:null] , onSucceedFunction name, [OPTIONAL] array of arguments)
 */
function reGetFromHttpRequest(method,url,formId,func,args)
{
    formBody=(formId!=null)?setBody(formId):null;
    AjaxObj=resetXmlHttpObject();
    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;
                                    if(args!=undefined)
                                    {
                                        args.push(result);
                                        func.apply(document,args);
                                    }
                                    else
                                    {
                                        func(result);
                                    }
                                    applyScript(result);
                                    //applyStyle(result);
                                }
                                else
                                {
                                    if(AjaxObj.status!=0)
                                        showError(AjaxObj,url);
                                    result= "Error";
                                }
                           }
    AjaxObj.send(formBody);
}

/* return a new Http Object */
function getXmlHttpObject()
{
    if(window.ActiveXObject)
    {
        HttpRequest=new ActiveXObject("Msxml2.XMLHTTP");
        HttpRequest||(HttpRequest=new ActiveXObject("Microsoft.XMLHTTP"))
    }
    else if(window.XMLHttpRequest)
        HttpRequest=new XMLHttpRequest;

    return HttpRequest;
}

var HttpRequest=null; // an Http Object
/* return a new Http Object OR reset(abort) an existung Http object */
function resetXmlHttpObject()
{
    if (HttpRequest==null)
    {
        if(window.ActiveXObject)
        {
            HttpRequest=new ActiveXObject("Msxml2.XMLHTTP");
            HttpRequest||(HttpRequest=new ActiveXObject("Microsoft.XMLHTTP"))
        }
        else if(window.XMLHttpRequest)
            HttpRequest=new XMLHttpRequest;
    }
    else if(HttpRequest.readyState!= 0)
    {
        HttpRequest.abort();
    }
    return HttpRequest;
}

/* make a ParameterStr(URIComponent) from the elements of the form 
 * to send via Ajax when using 'POST' methd
 */
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;
		else 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 and apply the scripts of the Ajax responseText in the current page */
function applyScript(result)
{
    var HiddenDIV=document.createElement('Div');
    HiddenDIV.innerHTML=result;
    var scriptArr = HiddenDIV.getElementsByTagName('SCRIPT');
    for(var i=0; i<scriptArr.length; i++)
    {
        /* eval(scriptObj[i].text); //---OR the bottom script: */
        var scriptText = scriptArr[i].text;
        var scriptSrc = scriptArr[i].src
        var scriptTag = document.createElement('SCRIPT');
        if ((scriptSrc != null) && (scriptSrc != ''))
            scriptTag.src = scriptSrc;
        scriptTag.text = scriptText;
        if (!document.getElementsByTagName('HEAD')[0])
            document.createElement('HEAD').appendChild(scriptTag)
        else
            document.getElementsByTagName('HEAD')[0].appendChild(scriptTag);
    }
}

/* if error occured, alert server error (ONLY FOR ASPX ERRORS) */
function showError(obj,url)
{
    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: `No Specific Line`";
    url=url.substring(0,url.lastIndexOf('.aspx')+5);
    alert("\nError:"+obj.status+"\nخطا در دریافت اطلاعات از سرور\n"+url+"\n\n"+erMsg);
}

/* make a new Effect Object and apply to the objId  
 * runEffect(objectId,effectType[fade:expand],flag[true,false],[OPTIONAL] array of arguments)
 *
 * flag:true -> effect in
 * flag:false -> effect out
 * 
 * args: some effect settings (eg. speed, ExpandHeight, FadeRange , ...) 
 * ! these settings are different according to each effect type
 *
 * SAMPLE-1: runEffect('div01','fade',true)
 */
function runEffect(objId,effectType,flag,args)
{
    if(Effect.initEffect(objId,effectType))
    {
        Effect.flag = flag;
        switch(effectType.toLowerCase())
        {
            case 'expand': 
                try{Effect.speed=parseInt(args[0])}
                catch(e){Effect.speed=30}
                
                try{Effect.lastLength=parseInt(args[1])}
                catch(e){Effect.lastLength=(flag?200:0)}
                
                break;
            case 'fade':
                try{Effect.speed=parseInt(args[0])}
                catch(e){Effect.speed=50}
                
                try{Effect.lastLength=parseInt(args[1])}
                catch(e){Effect.lastLength=(flag?1:0)}
                
                break;
        }
        //eval("Effect."+effectType+".apply(effect.obj,args)";
        eval("Effect."+effectType+"();");
    }
}

/* effect class: */
var Effect={
        obj:null,
        effectType:null,
        lastLength:null,
        flag:null,
        speed:null,
        timer:null,
        initEffect:function(obj,type)
        {
            if(gel(obj))
                Effect.obj=gel(obj);
            else
            {   alert("Object "+obj+" Not Found"); return false;  }
            var arrEffects=['fade','expand'];
            for(i=0;i<arrEffects.length;i++)
                if(type.toLowerCase()==arrEffects[i])
                    {Effect.effectType=type;return true;}
            if(Effect.effectType==null)
                {alert("Effect Not Supported!!!");return false;}
            clearTimeout(Effect.timer);
            //effect.lastLength = arguments[0];
            return true;
        },
        fade:function()
        {
            //--------IE
            if(Effect.obj.filters)
            {
                if(Effect.obj.style.filter)
                    opc = parseFloat(Effect.obj.filters["alpha"].opacity / 100);
                else
                {
                    Effect.obj.style.filter="alpha(opacity=100)";
                    opc = 1;
                }
            }
            //--------FF
            else if(Effect.obj.style.opacity)
                opc = parseFloat(Effect.obj.style.opacity);
            else
            {
                Effect.obj.style.opacity=1;
                opc = 1;
            }
            
            if(Effect.flag) // fade In
            {
                if(opc<(Effect.lastLength/100))
                {
                    opc+=0.1;
                    if(Effect.obj.filters)
                        Effect.obj.filters["alpha"].opacity = opc*100;
                    else
                        Effect.obj.style.opacity=opc;

                    Effect.timer = setTimeout(Effect.fade,Effect.speed);
                }
                else
                {
                    if(Effect.obj.filters)
                        Effect.obj.filters["alpha"].opacity = 100;
                    else
                        Effect.obj.style.opacity = 1;
                }
            }
            else // fade Out
            {
                if(opc>(Effect.lastLength/100))
                {
                    opc-=0.1;
                    if(Effect.obj.filters)
                        Effect.obj.filters["alpha"].opacity = opc*100;
                    else
                        Effect.obj.style.opacity=opc;
                    Effect.timer = setTimeout(Effect.fade,Effect.speed);
                }
                else
                {
                    if(Effect.obj.filters)
                        Effect.obj.filters["alpha"].opacity = Effect.lastLength;
                    else
                        Effect.obj.style.opacity = Effect.lastLength/100;
                }
            }
        },
        expand:function()
        {
            if(Effect.flag) // Expand
            {
                Hi = parseInt(Effect.obj.style.height);
                if(Hi<Effect.lastLength)
                {
                    Hi+=10;
                    Effect.obj.style.height=Hi+"px";
                    Effect.timer = setTimeout(Effect.expand,Effect.speed);
                    Effect.speed+=2;
                }
                else
                    Effect.obj.style.height=Effect.lastLength+"px";
            }
            else // Collapse
            {
                Hi = parseInt(Effect.obj.style.height);
                if(Hi>Effect.lastLength)
                {
                    try{Hi-=10;}
                    catch(e){Effect.obj.style.height=Effect.lastLength+"px";return}
                    Effect.obj.style.height=Hi+"px";
                    Effect.timer = setTimeout(Effect.expand,Effect.speed);
                    Effect.speed+=2;
                }
                else
                    Effect.obj.style.height=Effect.lastLength+"px";
            }
        }
        
};

/* Event class & methods: */
function Evt(evt) 
{
    this.evt = evt ? evt : window.event;
    this.source = evt.target ? evt.target : evt.srcElement; 
    this.key = evt.which ? evt.which : evt.keyCode;
    this.x = evt.pageX ? evt.pageX : evt.clientX;    
    this.y = evt.pageY ? evt.pageY : evt.clientY;
    try{
    this.shiftKey = evt.shiftKey;
    this.ctrlKey = evt.ctrlKey;
    this.altKey = evt.altKey;
    }
    catch(err){}
}
Evt.prototype.toString = function () { return "Evt [ x = " + this.x + ", y = " + this.y + " ]"; };      
Evt.prototype.consume = function () 
{ 
 if (this.evt.stopPropagation) {     
    this.evt.stopPropagation();
    this.evt.preventDefault();    
 } 
 else if (this.evt.cancelBubble) {
      this.evt.cancelBubble = true;     
      this.evt.returnValue  = false;
 }
};
Evt.addEventListener = function (target,type,func,bubbles) 
{
 if (document.addEventListener) {   target.addEventListener(type,func,bubbles);    } 
 else if (document.attachEvent) {   target.attachEvent("on"+type,func,bubbles);    } 
 else {     target["on"+type] = func;    }   
};     
Evt.removeEventListener = function (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;    }   
};
 
/* check if 'node1' is located inside 'node2' */
function contains(node1, node2)
{
  if(node2 == node1) return true;
  if(node2 == null) return false; 
  else return contains(node1, node2.parentNode);
}

/* fill a combobox according to the value
 * ! Responser page get this value from Request["ComboBoxFirstValue"]
 * ! Responser result must have '^' between options
 * ! and have '&' between each option's name&value
 * Response EXAMPLE: a&1^b&2^c&3 ...
 */
function setComboBox(comboId,firstValue,url,firstOption)
{
    combo = gel(comboId);
    while(combo.options.length>0)
        combo.options[0] = null;
    if(firstValue==-1)
    {
        if (firstOption != undefined)
            combo.options[0] = new Option(firstOption[0],firstOption[1]);
        else
            combo.options[0] = new Option('--------','-1');
        return;
    }
    combo.options[0] = new Option('درحال جستجو...','-1');
    sign =  url.indexOf('?')==-1 ? '?' : '&';
    url += sign+'ComboBoxFirstValue='+firstValue;
    getFromHttpRequest('get',url,null,function(){
            var index = 0;
            if (firstOption != undefined)
            {
                combo.options[0] = new Option(firstOption[0],firstOption[1]);
                index++;
            }
            
            arrOpts = result.split('^');
            for(i=0;i<arrOpts.length;i++)
            {
                if(arrOpts[i].indexOf('&')==-1)
                    continue;
                newOpt = arrOpts[i].split('&');
                combo.options[index++] = new Option(newOpt[0],newOpt[1]);
            }
    });
}

/* fill a Tbody(tbodyId) by parsing rowsStr
 * 
 * if tbodyId not exists -> new Tbody will be created whose Id is tbodyId
 *
 * rowStr: an string to make Rows & Cells of the Table:
 *     -> ^tr^: seprator between each ROW
 *     -> ^td^: seprator between each CELL
 *
 * appendFlag:true --> new rows will append the previous rows
 * appendFlag:false --> new rows will overwrite the previous rows
 */
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;
    }
    
    arrTr = rowsStr.split('^tr^');
    for(i=0;i<arrTr.length;i++)
    {
        if(arrTr[i].indexOf('^td^')==-1)
            continue;
        oTr = tbd.insertRow(index);
        oTr.id = tbodyId+'_tr'+index; // ID of new TR row
        //oTr.style.backgroundColor=(index%2==0)? 'white' : 'whiteSmoke';

        arrTd = arrTr[i].split('^td^');
        for(j=0;j<arrTd.length;j++)
        {
            oTd = tbd.rows[index].insertCell(j);
            oTd.id= tbodyId+'_tr'+index+'_td'+j; // ID of new TD cell
            oTd.innerHTML=arrTd[j];
        }
        index++;
    }
}

/* set the Opacity style of the objId with assigned value 
 * value is between (0~1)
 */
function setOpacity(objId,value) 
{
     node = gel(objId);
     if (node.filters)
     {    try { node.filters["alpha"].opacity = value*100; } catch(e) {}    } 
     else if (node.style.opacity)
     {  node.style.opacity = value;  }
}