﻿//this functions are required for cross browser

//=======================================EVENTS RELATED==================================================
///PARAMETERS:
///         objEle:     document element
///         objEvent:   name of event [click/dblclick/contextmenu/mouseout/mousemove not onclick or ondblclick]
///         objFunction:reference of any function which is invoke my event
///         captuer:    true/false
///RETURN:
///         boolean value true or false
function addEvent(objEle,objEvent,objFunction,Capture)
{
    if(typeof objFunction != 'function')
    {
        return false;
    }
    if(objEle.addEventListener)
    {
        objEle.addEventListener(objEvent, objFunction, Capture);
        return true;
    }
    else if(objEle.attachEvent)
    {
        objEle.attachEvent('on' + objEvent, objFunction);
        return true;
    }
    return false;
}
//-------------------------------------------------------------------------------------------------------
function getEventObject(e)
{
    if(!e)
        return window.event;
    else
        return e;
    
}
//-------------------------------------------------------------------------------------------------------
function cancelEventBubbling(e)
{
	if (e.cancelBubble) e.e.cancelBubble=true;
	if (e.preventDefault) e.preventDefault();
	if (e.stopPropagation) e.stopPropagation();
	
	e.returnValue=false;
}
//======================================POSITION RELATED=================================================
///PARAMETERS:
///         obj:     document element
///RETURN:
///         1-dim. Array of integer
///         arr[0]=left position of input object 
///         arr[1]=top position of input object
function findAbsPos(obj)
{
    var curLeft=curTop=0;
    if(obj.offsetParent)
    {
        curLeft=parseInt(obj.offsetLeft);
        curTop=parseInt(obj.offsetTop);
        while(obj=obj.offsetParent)
        {
            curLeft+=parseInt(obj.offsetLeft);
            curTop+=parseInt(obj.offsetTop);
        }
    }
    return [curLeft,curTop];
}
//-------------------------------------------------------------------------------------------------------
function setIFrameHeight(ele)
{
    ele.style.height=parseInt(ele.document.body.offsetHeight) + parseInt(ele.document.body.scrollHeight) + 10 + "px";
}
//======================================ELEMENTS RELATED=================================================
///PARAMETERS:
///         obj:     document element
///         flag:    true for disabled all child controls, false for enabled all child controls
function disableElement(obj,flag){
    var childs=obj.childNodes;
    obj.disabled=flag;
    for(var index=0;index<childs.length;index++){
        if(typeof childs[index].disabled!="undefined"){
            childs[index].disabled=flag;
        }
    }
}
//=======================================EMAIL RELATED===================================================
///PARAMETERS:
///         email:   email address
///         subject: subject of mail [optional] 
///         body:    email body[optional]
function mailTo(email,subject,body){
    
    var reqString="mailto:" + email;
    var param="";
    
    if(subject!=null) param+="subject=" + subject;
    if(body!=null) param+=(param==""?"":"&") + "body=" + subject;
    
    document.location=reqString + (param!=""?("?" + param):"");
}

//=====================================URL PATH RESOLVE============================
function resolveClientUrl(urlPath){
    
    if(urlPath.indexOf("~")<0) return urlPath;
    
    var commonPath=document.location.protocol + "//" + document.location.host;
    
    if(ROOT_DIRECTORY && ROOT_DIRECTORY!="/")
        commonPath=commonPath + ROOT_DIRECTORY;
    
    urlPath=urlPath.replace("~",commonPath);
    
    return urlPath;
}

function ShowLargeImage(ele)
{   
    if(ele)
    {   
        CommonDialogManager.ShowPage ('PupupImage', resolveClientUrl("~/ShowImage.aspx?img=") + ele.id,null,null,null);
    }
}
///---------------------Dialog Box------------------------

/*
var dialogsSetting=new Array();
dialogsSetting["FirstDialog"]={Height:"auto", 
                               Width:"auto",
                               Title:"Test Dialog"};
*/

var defaultDialogSetting={Height:"300px", 
                       Width:"300px",
                       CssClass:"dialog",
                       HeaderCssClass:"dialogHeader",
                       ContentAreaCssClass:"grayBox",
                       Title:"Dialog Box",
                       CloseImageUrl:"~/Images/winClose.gif"};
                       



var CommonDialogManager={
    GetValue:function(dialogSetting,key){
        return (dialogSetting[key]?dialogSetting[key]:defaultDialogSetting[key]);
    },
    
    ShowPage:function(dialogName, pageUrl, parentDialog, startupFunction, onDialogClose){
        
        if(parentDialog && (typeof parentDialog=="string"))
            parentDialog=document.getElementById("dlg_" + parentDialog);
        
        
        var currParent=(!parentDialog)?document.body:parentDialog;
        
        var dialogSetting=dialogSettings[dialogName];
        
        if(!dialogSetting){
            alert("Invalid Dialog Name - " + dialogName);
            return;
        }
        var dialogContainer=this.GetDialogContainer(dialogName, dialogSetting, currParent);
        
        openModalDialog(dialogContainer.Element.id, dialogSetting.Title, currParent, onDialogClose);
        
        if(pageUrl)
            updateContainer(dialogContainer.ContentArea.id,resolveClientUrl(pageUrl),function(){resetDialogPosition(dialogContainer.Element.id); if(startupFunction) startupFunction();});
        
        return dialogContainer.Element;
    },//end show page
    
    Show:function(dialogSetting, contentContainerID, parent, startupFunction, onDialogClose){
        if(!dialogSetting) dialogSetting=defaultDialogSetting;
        
        if(parent!=null && parent.id.indexOf("dlg_")<0){
            
            while(parent.parentNode!=null){
                if(parent.id.indexOf("dlg_")>=0 || parent.tagName.toLowerCase()=="body") break;
                parent=parent.parentNode;
            }
        }
        
        var currParent=(!parent)?document.body:parent;
        
        var contentContainer=document.getElementById(contentContainerID);
        
        if(!contentContainer) {alert("Content container not found");return};
        
        var dialogContainer=this.GetDialogContainer(contentContainerID, dialogSetting, currParent);
    
        if(dialogContainer.ContentArea.childNodes.length==0){
            dialogContainer.ContentArea.appendChild(contentContainer.cloneNode(true));
            contentContainer.parentNode.removeChild(contentContainer);
        }
        
        //if(dialogContainer.ContentArea.childNodes.length==0) contentContainer.parentElement=dialogContainer.ContentArea;
        
        openModalDialog(dialogContainer.Element.id, dialogSetting.Title, parent, onDialogClose);
        
        if(startupFunction) startupFunction();
        
        return dialogContainer.Element;
    },//end show
    
    GetDialogContainer:function(dialogName, dialogSetting, currParent){
        var dialogContainer=document.getElementById("dlg_" + dialogName);
        var titleBar, contentArea;
        
        if(dialogContainer){
            titleBar=document.getElementById("dlgtitle_" + dialogName);
            contentArea=document.getElementById("dlgcontentarea_" + dialogName);
        }
        else{//If dilog box not found then create new one
            var cssClass=this.GetValue(dialogSetting,"CssClass");;
            var headerCssClass=this.GetValue(dialogSetting,"HeaderCssClass");
            var contentAreaCssClass=this.GetValue(dialogSetting,"ContentAreaCssClass");
            var areaHeight=this.GetValue(dialogSetting,"Height");
            var areaWidth=this.GetValue(dialogSetting,"Width"); 
            var closeImageUrl=this.GetValue(dialogSetting,"CloseImageUrl"); 
            
            dialogContainer=document.createElement("div");
            dialogContainer.id="dlg_" + dialogName;
            dialogContainer.className=cssClass;
            
            dialogContainer.style.width=areaWidth;
            
            titleBar=document.createElement("div");
            titleBar.className=headerCssClass;
            titleBar.id="dlgtitle_" + dialogName;
            titleBar.innerHTML="<span class=\"float-left\">" + dialogSetting.Title + "</span>" + 
                                "<img src=\"" + resolveClientUrl(closeImageUrl) + "\" class=\"float-right\" onclick=\"javascript:closeModalDialog(this)\" alt=\"Close\" />";
            
            contentArea=document.createElement("div");
            contentArea.className=contentAreaCssClass;
            contentArea.id="dlgcontentarea_" + dialogName;
            
                                
            dialogContainer.appendChild(titleBar);
            dialogContainer.appendChild(contentArea);
            currParent.appendChild(dialogContainer);
            
            if(areaHeight!="auto"){
                contentArea.style.height=areaHeight;
                dialogContainer.style.height=(parseInt(titleBar.offsetHeight) + parseInt(contentArea.offsetHeight)) + "px";
            }
        }
        
        return {Element:dialogContainer, TitleBar:titleBar, ContentArea:contentArea};
    }
};

///onDialogClose is a function pointer 
function openModalDialog(WINDOWid, strWinTitle, parent, onDialogClose)
{
    var WINDOW=document.getElementById(WINDOWid);
    //set parent window
    Object.extend(WINDOW,{PARENT:parent});
    
    if(parent==null) parent=document.body;
    
    var objLockDiv=document.getElementById(WINDOWid + "_LockDiv");
    if(objLockDiv!=null) return;
    
    objLockDiv=document.createElement("div");
    objLockDiv.className="LockDiv";
    objLockDiv.id=WINDOWid+ "_LockDiv";
    //objLockDiv.style.cssText="opacity: .30;background-color:red;filter: alpha(opacity=30);-moz-opacity: 0.3;z-index: 100;left: 0px;position: absolute;top: 0px;background-color: #000;";
        
    //SHOW THE DIV
    objLockDiv.style.height=parseInt(parent.height || parent.offsetHeight) + "px";
    objLockDiv.style.width=parseInt(parent.width || parent.offsetWidth) + "px";
    
    parent.appendChild(objLockDiv);
    objLockDiv.style.display='';
    
    
   //the Title
        
        WINDOW.getElementsByTagName("span")[0].innerHTML=strWinTitle;
        WINDOW.style.display='block';
        var top=(parseInt(parent.height ||parent.offsetHeight)/2 - parseInt(WINDOW.offsetHeight)/2) + document.documentElement.scrollTop;
        WINDOW.style.top=((top<0)?1:top) +  "px";
        WINDOW.style.left=(parseInt(parent.width || parent.offsetWidth)/2 - parseInt(WINDOW.offsetWidth)/2) + "px";
  
  //set dialogclose function
  if(typeof onDialogClose!="undefined"){
        Object.extend(WINDOW,{dialogClose:onDialogClose});
  }  
  
   resetDialogPosition(WINDOWid); 
}


///===============================================================================
function closeModalDialog(dialogBox,result){
    try{
        
        while(dialogBox.className!="dialog" && dialogBox!=null) {
            dialogBox=dialogBox.parentNode;
        }
        if(dialogBox!=null && dialogBox.className=="dialog"){
            dialogBox.style.display='none';
            
            var objLockDiv=document.getElementById(dialogBox.id + "_LockDiv");
            if(objLockDiv!=null) {
                objLockDiv.style.display='none';
                objLockDiv.parentNode.removeChild(objLockDiv);
            }
            
            if(dialogBox.dialogClose && typeof dialogBox.dialogClose!="undefined"){
                dialogBox.dialogClose(result);
            }
        }
   }
   catch(e){
        alert(e.message);
   }
}

function cleanContainer(eleId){
    document.getElementById(eleId).innerHTML='';
}

function resetDialogPosition(WINDOWid)
{  
    var WINDOW=document.getElementById(WINDOWid);
    if(WINDOW!=null){
        var parent=WINDOW.PARENT;
        
        var lefttop;
        if(parent) lefttop=findAbsPos(parent);
        
        var docWindowHeight=(parent)?parent.offsetHeight:getWindowHeight();
        var windowHeight=parseInt(WINDOW.offsetHeight);
        
        var docWindowWidth=(parent)?parent.offsetWidth:getWindowWidth();
        var windowWidth=parseInt(WINDOW.offsetWidth);
        
        var top,left;

        if(windowHeight>docWindowHeight) top=(parent)?lefttop[1]:0;
        else top=(docWindowHeight-windowHeight)/2;
        
        if(windowWidth>docWindowWidth) left=(parent)?lefttop[0]:0;
        else left=(docWindowWidth-windowWidth)/2;
        
        
        //var top=(parseInt(document.height || document.body.offsetHeight) - parseInt(WINDOW.offsetHeight))/2 + document.documentElement.scrollTop;
        if(!parent || parent.tagName.toLowerCase()=="body"){
            WINDOW.style.top=100 + parseInt(document.documentElement.scrollTop) + "px";
            //WINDOW.style.top=parseInt(top) + document.documentElement.scrollTop + "px";
            WINDOW.style.left=parseInt(left) + document.documentElement.scrollLeft + "px";
        }
        else{
            WINDOW.style.top=parseInt(top) + "px";
            WINDOW.style.left=parseInt(left) + "px";
        }
    }
}
function getWindowHeight() {
    var windowHeight = 0;
 
    if (typeof(window.innerHeight) == 'number') {
        windowHeight = window.innerHeight;
        }
    else {
        if (document.documentElement && document.documentElement.clientHeight) 
            {windowHeight = document.documentElement.clientHeight;}
        else 
            {if (document.body && document.body.clientHeight) 
                {windowHeight = document.body.clientHeight;}
            }
    }
    
    return windowHeight;
}
function getWindowWidth() {
    var windowWidth = 0;
 
    if (typeof(window.innerWidth) == 'number') {
        windowWidth = window.innerWidth;
        }
    else {
        if (document.documentElement && document.documentElement.clientWidth) 
            {windowWidth = document.documentElement.clientWidth;}
        else 
            {if (document.body && document.body.clientWidth) 
                {windowWidth = document.body.clientWidth;}
            }
    }
    
    return windowWidth;
}

//===========================================================================================
function selectRows(ele, tableId, cellIndex){
    var table=document.getElementById(tableId);
    var rows=table.getElementsByTagName("tr");
    var checkbox;
    
    for(var index=0;index<rows.length;index++){
        checkbox=rows[index].getElementsByTagName("td")[cellIndex].getElementsByTagName("input")[0];
        if(!checkbox.disabled)
            checkbox.checked=ele.checked;
    }
}

//=======================================PRINT HTML==========================================
///PARAMETERS:
///         html:   html string
///         stylesheetLinks:    array of style sheets[optional]

var defaultPrintWinStyles=new Array();
var currentPrintStylesLink=new Array();
var currentPrintContent="";
function openPrintPreviewWindowHTML(title, html, stylesheetLinks, width, height){
    if(html){
        var tempStr="";
        currentPrintContent=html;
        currentPrintStylesLink=stylesheetLinks;
        
        if(!title) title="Print Preview";
        
        var printFunction="function printDocument(){\n" +
                                    "var pbar=document.getElementById(\"printBar\");\n" +
                                    "if(pbar){" +
                                        "var prnWin=document.getElementById(\"printContainer\");\n" +
                                        "prnWin.contentWindow.focus();\n" +
                                        "prnWin.contentWindow.print();\n" +
                                    "}\n" +
                                    "window.focus();" +
                                "}\n";
        
        var newWin=window.open("","printWindow","left=100, top=100, width=" + width + ", height=" + height);
        
        newWin.document.write("<html><head><title>" + title + "</title>");
        
        //insert default styles
        defaultPrintWinStyles=[
            "body{margin:0px;padding:0px;font-size:8pt;font-family:Arial}",
            "#printBar{text-align:right;background-color:#EAEAEA;height:25px}",
            "#printBar .button{margin:3px;background-color:#AAA;color:#FFF;border:1px solid #FFF}",
            "#printContainer{overflow:auto;width:100%;height:" + (height-26) + "px}",
            "#printContent{margin:0.5in;text-align:left;width:8in;height:11in}"
        ];
        
        newWin.document.write("<style type=\"text/css\" >" + defaultPrintWinStyles.join("") + "</style>");
             
        //insert script to print
        newWin.document.write("<script type=\"text/javascript\" >" + printFunction + " window.focus();</script>");
        
        //draw print bar
        tempStr="<div id=\"printBar\"><input onclick=\"javascript:printDocument();\" class=\"button\" type=\"button\" value=\"Print\" /></div>";
        
        newWin.document.write("</head><body>" + tempStr + "<iframe frameborder=\"no\" id=\"printContainer\"></iframe>");
        
        //register startup script
        newWin.document.write("<script type=\"text/javascript\" >window.opener.drawPrintPreviewContent(document.getElementById(\"printContainer\"));</script>");
        
        newWin.document.write("</body></html>");
        
        newWin.document.close();
    }
}

function drawPrintPreviewContent(cont){
    if(!cont) return;
    var odoc=(cont.contentWindow || cont.contentDocument);
    if(odoc.document) odoc=odoc.document;
    
    odoc.write("<html><head>");
    odoc.write("<style type=\"text/css\" >" + defaultPrintWinStyles.join("") + "</style>");
    
    //insert style sheets(if any)
    if(currentPrintStylesLink && currentPrintStylesLink.length){
        for(var sl=0;sl<currentPrintStylesLink.length;sl++){
            odoc.write("<link href=\"" + currentPrintStylesLink[sl] + "\" rel=\"stylesheet\" type=\"text/css\" />")
        }
    }
    odoc.write("</head><body><div id=\"printContent\">");
    odoc.write(currentPrintContent);
    odoc.write("</div></body></html>");
    
    odoc.close();
}

//--------------------------------------------------
var ValidateNumberInput=function(eve, ele, separator){
    if(!eve) eve=window.event;
    if(!ele) ele=eve.srcElement || eve.target;

    var espectedRange="0-9.,";

    if((typeof eve.charCode!="undefined") && eve.charCode==0) return true;
                            
    var code=eve.charCode || eve.keyCode;
            
    var values, totalQuantity=0;
    if(separator) values=ele.value.split(separator);
    else values=[ele.value];             


    if(separator && code==espectedRange.charCodeAt(4)) return true;
    var charIndex=1, charEnd=0;
    var caretPosition=GetTextboxCaretPosition(ele);

    if(code>=espectedRange.charCodeAt(0) && code<=espectedRange.charCodeAt(2)){
        return true;
    } else if(code==espectedRange.charCodeAt(3)){
        for(var i=0; i<values.length; i++){
            charEnd = charIndex + values[i].length;                
            if(caretPosition>=charIndex && caretPosition<=charEnd){                    
                    firstIndexDecChar = values[i].indexOf(".");
                    return firstIndexDecChar<0;                         
            }
            charIndex +=values[i].length + 1;
        }
    } else{
        return false;
    }
};

var GetTextboxCaretPosition=function(ele){            
    var sel, rng, r2, i=-1;

    if(typeof ele.selectionStart=="number") {
        i=ele.selectionStart;
    } else if(document.selection && ele.createTextRange) {
        sel=document.selection;
        if(sel){
            r2=sel.createRange();
            rng=ele.createTextRange();
            rng.setEndPoint("EndToStart", r2);
            i=rng.text.length;
        }
    } else {
        ele.onkeyup=null;
        ele.onclick=null;
    }
    return i;
};
