var waitImage = null;
var activeComboOption = null;

function isNumeric(str) 
{
    return (!str.length || !isNaN(str.replace(/\s/,"z")/1)); 
}

function isString(a) {
    return typeof(a) == 'string';
}

function isUndefined(a) {
    return typeof(a) == 'undefined';
} 

function isNumber(a) {
    return typeof(a) == 'number' && isFinite(a);
}

function isNull(a) {
    return typeof(a) == 'object' && !a;
}
function isNullOrUndefined(a) {
    return isUndefined(a) || isNull(a);  
}

function SessionAlert() {  
  alert("Your Session will time out in 5 minutes");
}

function BodyKeyDownTrap()
{
    if (window.event.keyCode != 13) return true;
    
    var element = document.activeElement;
    
    if (element == null || isUndefined(element) || isUndefined(element.tagName)) return false;

    var tagName = element.tagName;

    switch(tagName.toUpperCase())
	    {

		    case "INPUT":
			    switch (element.type.toUpperCase())
			    {
				    case "IMAGE":
				    case "BUTTON":
					    return true;
    			    default:
    			       if (element.onkeypress !=null) return true;
    			        return false;    	
			    }
			    
		    case "A":
		    case "SELECT":
			    return true;

		    default:
			    return false;
	    }
}



function OnAbstractTextBoxClick(keyCode, objName, onBlurCode, event) 
{

    if (event.keyCode == 13) 
    {
        if (!eval(onBlurCode)) return false;
        return _AbstractTextBoxKeyPress(event, 13, objName);
      
    }

    return true; 
}


function bodyOnFocus(e) 
{
    document.body.onfocus = null;
    if (!isNullOrUndefined(document.activeEl))
    {
        document.activeEl.onblur = document.activeEl.onBlurCode;
        document.activeEl = null;
    }
}

function OnLoadDialog() 
{
    //for IE 
    try 
    {   
        var activeEl = document.activeElement;
        switch (activeEl.tagName.toUpperCase())
        {
            case "SELECT":
            case "INPUT":
                activeEl.onBlurCode = activeEl.onblur;
                activeEl.onblur = null;
                document.activeEl = activeEl;
                document.body.onfocus = bodyOnFocus;
                document.body.focus();    
                break;
        }

       
        
    }
    catch (e) {}

    InitGrid();
   
    if (!window.opener) 
    {
        BrowserDetect.init();

        if (BrowserDetect.browser == "Explorer")
        {


            if (BrowserDetect.version <= 6) 
            {
                try {


                    var minHeight = getQueryString("minHeight", 0);
                    var windowHeight = parseInt(window.dialogHeight.replace("px", ""));
                    window.dialogHeight = windowHeight + (minHeight - document.body.offsetHeight) + "px";

                    //alert(document.body.offsetHeight + ":" + window.dialogHeight); 
                }
                catch (e) { }
            }

            var modWidth = getQueryString("modWidth", 0);

            if (modWidth > 0) {
                window.dialogWidth = modWidth + "px";
                //fix horizontal bar issue
                if (document.body.offsetWidth > document.body.clientWidth &&
                        document.body.offsetWidth - document.body.clientWidth < 20)
                    window.dialogWidth = parseInt(window.dialogWidth) + (document.body.offsetWidth - document.body.clientWidth) + "px";

            }
        }
    }
}

function PostBackCombo(obj)
{
    //alert(obj.name);
    document.getElementById("lblPleaseWait").style.display="block";    
   
    for(var i = 0;i<document.forms[0].elements.length;i++)
    {   
        var element = document.forms[0].elements[i];
        if (element !=null)
        {
            var tagName =document.forms[0].elements[i].tagName;
            if (!isNull(tagName) && !isUndefined(tagName))
            {
                switch(tagName.toUpperCase())
	            {

		            case "INPUT":
		                if (element.type!="hidden") 
		                     if (element.name!= obj.id) element.setAttribute("disabled","true");
		                break; 
		            case "SELECT":
		                if (element.name!= obj.id) element.setAttribute("disabled","true");
		                break;
    			        
    			        /*        
			            switch (element.type.toUpperCase())
			            {
				            case "IMAGE":
				            case "BUTTON":				                					
				                break;
    			            default:
    			                if (element.name != obj.id) element.setAttribute("disabled","true");
    			                break;
			            } 
			            */  
			     }
			 }
	    }
	 }
  
    document.body.style.cursor="wait";
   __doPostBack(obj.name,'');

}


var BrowserDetect = {
    init: function() {
        this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
        this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
        this.OS = this.searchString(this.dataOS) || "an unknown OS";
    },
    searchString: function(data) {
        for (var i = 0; i < data.length; i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function(dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index + this.versionSearchString.length + 1));
    },
    dataBrowser: [
		{ string: navigator.userAgent,
		    subString: "OmniWeb",
		    versionSearch: "OmniWeb/",
		    identity: "OmniWeb"
		},
		{
		    string: navigator.vendor,
		    subString: "Apple",
		    identity: "Safari"
		},
		{
		    prop: window.opera,
		    identity: "Opera"
		},
		{
		    string: navigator.vendor,
		    subString: "iCab",
		    identity: "iCab"
		},
		{
		    string: navigator.vendor,
		    subString: "KDE",
		    identity: "Konqueror"
		},
		{
		    string: navigator.userAgent,
		    subString: "Firefox",
		    identity: "Firefox"
		},
		{
		    string: navigator.vendor,
		    subString: "Camino",
		    identity: "Camino"
		},
		{		// for newer Netscapes (6+)
		    string: navigator.userAgent,
		    subString: "Netscape",
		    identity: "Netscape"
		},
		{
		    string: navigator.userAgent,
		    subString: "MSIE",
		    identity: "Explorer",
		    versionSearch: "MSIE"
		},
		{
		    string: navigator.userAgent,
		    subString: "Gecko",
		    identity: "Mozilla",
		    versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
		    string: navigator.userAgent,
		    subString: "Mozilla",
		    identity: "Netscape",
		    versionSearch: "Mozilla"
		}
	],
    dataOS: [
		{
		    string: navigator.platform,
		    subString: "Win",
		    identity: "Windows"
		},
		{
		    string: navigator.platform,
		    subString: "Mac",
		    identity: "Mac"
		},
		{
		    string: navigator.platform,
		    subString: "Linux",
		    identity: "Linux"
		}
	]

};

function supportModalDialog() 
{
    return (!isNullOrUndefined(window.showModalDialog));
}

function OpenModalForm(a, s, n, t, p,sysProp) {

    modalFormHasBeenOpened = true;
    var isCalculationPanel = (s.indexOf("CalculationPanel")!=-1);
    var oldModWidth;
    
    formlaunch_ac = a;
    formlaunch_sc = s;
   // var useModalDialog = false;
    var index = -1;
    var paramName,paramValue;
        
    if (!isNullOrUndefined(sysProp)) 
    {
        var sProp = (sysProp.toString() + ";").split(";");

        for (var i = 0; i < sProp.length - 1; i++)
        {
            index = sProp[i].indexOf("=");
            if (index != -1) 
            {
                paramName = sProp[i].substring(0, index);
                paramValue = sProp[i].substring(index + 1, sProp[i].length);

                switch (paramName.toLowerCase()) 
                {
                    case "usemodaldialog":
                        useModalDialog = (paramValue=="yes")?true:false;
                    
                        break;
                }
            }    
        }

    }

 //useModalDialog = false;

    if (supportModalDialog() && useModalDialog && !isCalculationPanel ) 
    {
        BrowserDetect.init();

        var modHeight, modWidth, isScroll;
        isScroll = true;
        
        p = p.replace("height", "dialogHeight");
        p = p.replace("width", "dialogWidth");
        p = p.replace(/,/g, ";");
        
        
        var sParams = (p + ";").split(";");

        for (var i = 0; i < sParams.length - 1; i++) {
            index = sParams[i].indexOf("=");
            if (index != -1) {
                paramName = sParams[i].substring(0, index);
                paramValue = sParams[i].substring(index + 1, sParams[i].length);

                switch (paramName.toLowerCase()) {

                    case "scrollbars":
                        p = p.replace(/scrollbars/, "scroll");
                        isScroll = (paramValue=="yes")?true:false;
                        break;
                    case "dialogheight":
                        modHeight = parseInt(paramValue);
                        //p = p.replace("dialogHeight=" + paramValue + ";", "dialogHeight=" + (parseInt(paramValue)+20) + "px;");
                        break;

                    case "dialogwidth":
                        modWidth = parseInt(paramValue);                     
                        
                        break;
                }
            }
        }

        oldModWidth = modWidth; 
        if (BrowserDetect.browser == "Explorer" ) {

            if (BrowserDetect.version <= 6) 
            {
               
                if (isCalculationPanel) modWidth= modWidth-13;
                p = p.replace("dialogWidth=" + oldModWidth + ";", "dialogWidth=" + ((isScroll) ? modWidth : modWidth + 5) + "px;");
                p = p.replace("dialogHeight=" + modHeight + ";", "dialogHeight=" + ((isScroll) ? modHeight +60 : modHeight +60) + "px;");
                n = n + "&minHeight=" + modHeight + "&modWidth=" + ((isScroll) ? modWidth : modWidth + 5);
            }
            else 
            {
                if (isCalculationPanel) modWidth= modWidth-19;
                p = p.replace("dialogWidth=" + oldModWidth + ";", "dialogWidth=" + (modWidth) + "px;");
                p = p.replace("dialogHeight=" + modHeight + ";", "dialogHeight=" + modHeight + "px;");
                n = n + "&minHeight=" + modHeight + "&modWidth=" + modWidth;

            }
        }
        else if (BrowserDetect.browser == "Firefox" && BrowserDetect.version >= 3) 
        {
            //if (isCalculationPanel) modWidth= modWidth-19;
            p = p.replace("dialogWidth=" + oldModWidth + ";", "dialogwidth=" + ((isScroll) ? modWidth : modWidth + 10) + "px;");
            p = p.replace("dialogHeight=" + modHeight + ";", "dialogheight=" + ((isScroll) ? modHeight : modHeight + 30) + "px;");
            //center it 
            p = p + ";dialogleft=" + ((screen.width - modWidth)/2);
            p = p + ";dialogtop=" + ((screen.height - modHeight) / 2);
            //n = n + "&minHeight=" + ((isScroll) ? modHeight : modHeight + 30) + "&modWidth=" + ((isScroll) ? modWidth : modWidth + 10);


        }
        p += ";center=yes;";
        
        // http://support.microsoft.com/kb/831678
        // The cookie may be lost when a window is opened from a modal dialog in IE. To work around this behavior, 
        // pass the window object of the parent of the dialog box into the dialog box, and then use that object to open the new window.
        var args = new Object;
	    args.window = window;
	    args.callerArgs = t;
        var result = showModalDialog(n, args, p);
        if (IsProcessingAsyncRequest())
        {            
            // Defer the postback in reponse to the closure of the dialog till after the current async request has completed. 
            Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function() { 
                                                                            Sys.WebForms.PageRequestManager.getInstance().remove_endRequest(arguments.callee); // remove this function as a handler for the event
                                                                            __doPostBack(formlaunch_sc, formlaunch_ac);                                                                                                                                                         
                                                                            });                
        }
        else
        {
           __doPostBack(formlaunch_sc, formlaunch_ac);
        }
    }
    else 
    {
        window.focus();          
        formlaunch_wnd = window.open(n, t, p);        
        if (formlaunch_wnd != null) 
        {
            if (formlaunch_wnd.opener == null)   formlaunch_wnd.opener = self;
           
            formlaunch_wnd.focus();
        }
        window.onfocus = KeepModal; 
    }
}
function KeepModal(e) {
    if (formlaunch_wnd != null) {
        var oldHandler = window.onerror;
        window.onerror = focus_errorHandler;
        if (formlaunch_wnd.closed == true) {
            focus_errorHandler(0, 0, 0);
        }
        else {
            formlaunch_wnd.focus();
            window.blur();
        }
        window.onerror = oldHandler;
    }
}
function TerminateModal(rp)
{
    formlaunch_wnd = null;  
    window.focus();   
    __doPostBack(formlaunch_sc, formlaunch_ac);
}

function focus_errorHandler(message, url, line) {
    TerminateModal(null);
}

function CloseWindow(param) 
{

    if ( !supportModalDialog() || (!isNullOrUndefined(window.opener)))
        window.opener.TerminateModal(param); 
    window.close();
}

function CreateReportStyles(styleID, names, rules)
{    
	// If the style element already exists, remove it. 
	var cssNode = document.getElementById(styleID);
	if (cssNode !== null)
	{
	    cssNode.parentNode.removeChild(cssNode);
	    cssNode = null;	    
	}
	// Create a new style element
	cssNode = document.createElement('style');
	cssNode.id = styleID;
	cssNode.type = 'text/css';
	cssNode.rel = 'stylesheet';
	cssNode.media = 'screen';		
		
	// Create a single string which contains all the style rules
    var styleText = '';
    for (var i=0; i<names.length; i++) 
    {
		styleText += names[i] + " " + rules[i] + "\n";
	}
	
	if (!cssNode.styleSheet)
	{	
	    // W3C browsers, add the style text as a child node of 
	    // newly created script element
		var textNode = document.createTextNode(styleText);	
		cssNode.appendChild(textNode);
		textNode = null;
	}
	else
	{
	    // IE, set the the style text directly on the new 
	    // stylesheet
		cssNode.styleSheet.cssText = styleText;
	}
	
	document.getElementsByTagName("head")[0].appendChild(cssNode);
	cssNode = null;
}

function ExtendedReportButtonClick(id) 
{

 
    var obj = document.getElementById(id);
    if (obj != null)
    {
        //obj.focus();
        obj.click();
        return false;     
    }
    return true;
}

function ReportForDownloadButtonClick(id)
{
    var obj = document.getElementById(id);
    if (obj != null)
    {
        //obj.focus();
        obj.click();
        return false;
    }
    return true;
}


function ReportButtonClick() 
{
    var outerDiv = document.createElement("div");
    outerDiv.className = "divIndicatorOuter";
    document.body.style.overflow = "hidden";
    outerDiv.style.width = document.body.clientWidth + "px";
    outerDiv.style.height = document.body.clientHeight + "px";
    
    var innerDiv = document.createElement("div");
    var imageEl = document.createElement("img");
    var spanEl = document.createElement("span");
    imageEl.src = waitImage.src; //"images/test_1.bmp"; //indicator.gif";    
    spanEl.className = "reportPleaseWait";
    spanEl.innerHTML = "Please wait...";
    
    innerDiv.appendChild(imageEl);
    innerDiv.appendChild(spanEl);    
    innerDiv.className = "divIndicatorInner";    
    innerDiv.style.left = parseInt(document.body.clientWidth/2) - 50;
    innerDiv.style.top = parseInt(document.body.clientHeight / 2) - 10;
    
    document.body.appendChild(innerDiv);
    document.body.appendChild(outerDiv);

    var hiddenElement = document.createElement("input");
    hiddenElement.type = "hidden";
    hiddenElement.value = "1";
    hiddenElement.name = "hiddenDownload";
    hiddenElement.id = "hiddenDownload";
    document.forms[0].appendChild(hiddenElement);
    
}




function Trim(str) {
    return str.replace(/^\s*/, "").replace(/\s*$/, "");
}




function XBrowserAddHandler(target, eventName, handlerName) {
    if (target.addEventListener)
        target.addEventListener(eventName, handlerName, false);
    else if (target.attachEvent)
        target.attachEvent("on" + eventName, handlerName);
    else
        target["on" + eventName] = handlerName;
} 



function LoadReport(url,title,params) {

    

    var len = url.length;
    var fileType = url.substring(len, len - 3);
    var isAsyncRequest = IsProcessingAsyncRequest();
    //reportUrl = url;

    if (!isAsyncRequest && (fileType.toUpperCase() == "RTF" || fileType.toUpperCase() == "CSV")) 
    {
        XBrowserAddHandler(window, "load", function() { window.location.href = url; });
        //window.attachEvent("onload", function() { window.location.href = url; });
        return;
    }
    
    reportLoadFunc = function() {        
        var p;
        var wndOpenFunc;
        if (window.dialogArguments != null && window.dialogArguments.window != null)
        {
            // http://support.microsoft.com/kb/831678
            // The cookie may be lost when a window is opened from a modal dialog in IE. To work around this behavior, 
            // pass the window object of the parent of the dialog box into the dialog box, and then use that object to open the new window.
            wndOpenFunc = window.dialogArguments.window.open; 
        }
        else
        {
            wndOpenFunc = window.open;
        }
        
        p = wndOpenFunc(url, title, params);            
        if (p) 
        {        
            try 
            {
                p.focus();
            }
            catch (e)
            {
                // In IE, if window.open returned a reference to a previously opened window, that had been minimised,
                // then trying to give the window focus may fail,so catch the exception and continue. 
            }
        }
    }

    if (isAsyncRequest)
    {        
        reportLoadFunc();                
    }
    else
    {
        // Not using MS Ajax so open window when onload event fires
        window.onload =  reportLoadFunc;
    }
}

function IsProcessingAsyncRequest()
{
    if (typeof(Sys) !== "undefined")
    {
        // MS Ajax functionality available
        prm = Sys.WebForms.PageRequestManager.getInstance();
        return prm != null && prm.get_isInAsyncPostBack();
    }
    else
    {    
        return false;
    }
}


function getQueryString(key, defValue)
{
    if (defValue == null) defValue = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return defValue;
    else
        return qs[1];
}


function LoadExportFile(url)
{   
    window.onload = function(evt)
    {
        //create frame
        var iFrame = document.createElement("iframe");
        iFrame.setAttribute("name", "frameExport");
        iFrame.setAttribute("id", "frameExport");
        iFrame.setAttribute("src", url);
        iFrame.style.display = "none";
        iFrame.style.width.value = "0px";
        iFrame.style.height.value = "0px";
        document.body.appendChild(iFrame);
    }
}

function PreloadWaitImage() 
{
    if (waitImage == null) 
    {
        waitImage = new Image();
        waitImage.src = "images/indicator.gif";
    }
}

function AbandonSession() {
    if (window.event.clientY < 0 || window.event.clientX < 0) {
        if (typeof (modalFormHasBeenOpened) == "undefined" || !modalFormHasBeenOpened) PageMethods.AbandonSession();
    }
}



function ComboOptionClick(parentDivId, txtComboId, comboBoxId, option, frameId) {

    $("#" + parentDivId).css("display", "none");
    $("#" + frameId).css("display", "none");
    $("#" + txtComboId).html(option).focus();
    var comboBox = $("#" + comboBoxId);
    if (typeof (comboBox.change) != "undefined" && comboBox.val() != option) {
        comboBox.val(option);
        __doPostBack(comboBox.attr("name"), '');
    }
}

function ChangeClass(obj, className) {

    obj.className = className;
}


function ComboClick(objId,ComboId,frameId, comboText) {
    
    if (activeComboOption != null) {
        ChangeClass(activeComboOption, 'OptionNormal');
        activeComboOption = null;
    }
    
    var divObj = $("#" + objId);

    if (divObj.css("display") == "none") {
        var selectedObj = document.getElementById(ComboId + "OptionPanel_" + $("#" + ComboId).val());
        //var obj = divObj.find("div>div:eq(" + selectedIndex + ")").get(0);
        selectedObj.className = "OptionOnMouseOver";
        activeComboOption = selectedObj;
        $("#" + frameId).css("display", "block");
        divObj.css("display", "block");
        selectedObj.focus();

    }
    else {

        //debugger;
        divObj.css("display", "none");
        $("#" + frameId).css("display", "none");
        if (comboText) comboText.focus();
        
    }
}

function ComboPanelOnBlur(obj, txtComboId, imgComboId,frameId) {

    var targetElement = window.event.toElement;
    
    if (targetElement == null || (targetElement.className != 'OptionOnMouseOver'
                        && targetElement.className != 'OptionNormal'
                        && targetElement.className != 'DivComboContent'
                        && targetElement.id != txtComboId
                        && targetElement.id != imgComboId)) {

        $(obj).css('display', 'none');
        $("#" + frameId).css('display', 'none');
        if (activeComboOption != null) {
            ChangeClass(activeComboOption, 'OptionNormal');
            activeComboOption = null;
        }
    }
}


function OptionOnMouseOver(obj, className) {

    if (activeComboOption != null)
            ChangeClass(activeComboOption, 'OptionNormal');      
    
    activeComboOption = obj;
    ChangeClass(obj, className);
    obj.focus();
}

function OptionOnMouseOut(obj, className)
{
    //ChangeClass(obj, className);
    //obj.blur();
}

function ComboTextOnBlur(obj) 
{
    obj.style.backgroundColor =  "#ffffff";
    obj.style.color = "#092869";	
}


function ComboTextOnFocus(obj) 
{
    obj.style.backgroundColor = "#08246B";
    obj.style.color = "#ffffff";
}


function ComboTextOnMouseDown(obj, objId, ComboId, frameId) {
    ComboClick(objId, ComboId, frameId,obj);   
}

function ComboImgOnMouseDown(obj, objId, ComboId, frameId,txtComboId) {
    ComboClick(objId, ComboId, frameId, $("#" + txtComboId).get(0))
}

