var __sysPostBack;
function HijackPostBack() {
    if (__sysPostBack == null && typeof(__doPostBack) != "undefined") {
        __sysPostBack = __doPostBack;
        __doPostBack = safePostBack;
    }
}
function safePostBack(eventTarget, eventArgument) {
    try {
        return __sysPostBack(eventTarget,eventArgument);
    } catch(ex) {
        if (ex.message.indexOf('Unspecified')==-1) {throw ex;}
    }
}
HijackPostBack();

String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g,"");}
String.prototype.ltrim=function(){return this.replace(/^\s+/,"");}
String.prototype.rtrim=function(){return this.replace(/\s+$/,"");}
// Safely handles opening windows.
function showWindow(url, title, targetfield, callback, width, height, centered, resizeable, scrollable, showmodal) {

    var returnValue = "";
    var parentIsModal = (!self.opener);
    var features = "";

    if (!showmodal && !parentIsModal) {
        if (centered == 'null' || centered == 'undefined') { centered = false; }
    
        // Build the features.
        features += "location=no,menubar=no,status=no,titlebar=no,toolbar=no,fullscreen=no";
        if (width != 'null' || width != 'undefined') {
            features += ",width:" + width;
            if (centered) { features += ",left:" + (screen.width - width) / 2; }
        }
        if (height != 'null' || height != 'undefined') {
            features += ",height:" + height;
            if (centered) { features += ",top:" + (screen.height - height) / 2; }
        }
        if (resizeable != 'null' || resizeable != 'undefined') {
            if (resizeable) { resizeable = "yes"; } else { resizeable = "no"; }
            features += ",resizable:" + resizeable;
        }
        if (scrollable != 'null' || scrollable != 'undefined') {
            if (scrollable) { scrollable = "yes"; } else { scrollable = "no"; }
            features += ",scrollbars:" + scrollable;
        }
  
        // Show standard window.
        returnValue = window.open(url, title, features, false);
        
    } else { // Show Modal
        // Build the features.
        features += "edge:raised,status:no,unadorned:no";
        if (width != 'null' || width != 'undefined') {
            features += ",dialogWidth:" + width;
        }
        if (height != 'null' || height != 'undefined') {
            features += ",dialogHeight:" + height;
        }
        if (centered != 'null' || centered != 'undefined') {
            if (centered) { centered = "yes"; } else { centered = "no"; }
            features += ",center:" + centered;
        }
        if (resizeable != 'null' || resizeable != 'undefined') {
            if (resizeable) { resizeable = "yes"; } else { resizeable = "no"; }
            features += ",resizable:" + resizeable;
        }
        if (scrollable != 'null' || scrollable != 'undefined') {
            if (scrollable) { scrollable = "yes"; } else { scrollable = "no"; }
            features += ",scroll:" + scrollable;
        }

        // Show the window in a modal dialog.
        returnValue = window.showModalDialog(url, null, features);
    }
    if (boundfield) { // Check for bound field.
        boundfield.value = returnValue;
    }
    if (callback) { // Check for callback.
        callback(returnValue);
    }
    // Send the return value.
    if (returnValue == "1") { returnValue = true; } else { returnValue = false; }
    return returnValue;
}

function openCenterWindow(sURL, title, width, height, resizeable){
    var ID
    var wleft = (screen.width - width) / 2;
    var wtop = (screen.height - height) / 2;
    ID = window.open(sURL, title, 'fullscreen=no,height=' + height + ',left=0,location=no,menubar=no,resizable=' + resizeable + ',scrollbars=no,status=no,titlebar=no,toolbar=no,top=' + wtop + ',left=' + wleft + ',width=' + width + '');
    if (ID == "1") {
		return true;
	} else {
		return false;
	}
}
function openWindow(sURL,Width,Height) {
	var ID
	ID = window.showModalDialog(sURL,null,'dialogHeight:' + Height + 'px;dialogWidth:' + Width + 'px;status:no;scroll:no;');
	if (ID == "1") {
		return true;
	} else {
		return false;
	}
}
function openWindowScroll(sURL,Width,Height) {
	var ID
	ID = window.showModalDialog(sURL,null,'resizable:yes;dialogHeight:' + Height + 'px;dialogWidth:' + Width + 'px;status:no;scroll:yes;');
	if (ID == "1") {
		return true;
	} else {
		return false;
	}
}
function openWindowResizable(url, width, height) {
	var  id = window.showModalDialog(url, null, 'resizable:yes;dialogHeight:' + height + 'px;dialogWidth:' + width + 'px;status:no;scroll:no;');
	if (id == "1") {
		return true;
	} else {
		return false;
	}
}
function openReturnWindow(sURL,Width,Height,boundField) {
	var returnedValue;
	
	returnedValue = window.showModalDialog(sURL,null,'dialogHeight:' + Height + 'px;dialogWidth:' + Width + 'px;status:no;scroll:no;');
	if ((returnedValue == "") || (returnedValue == null)) {
	} else {
		boundField.value = returnedValue;
	}
}
function openReturnWindowCallback(sURL,Width,Height,callback) {
	var returnedValue;
	
	returnedValue = window.showModalDialog(sURL,null,'dialogHeight:' + Height + 'px;dialogWidth:' + Width + 'px;status:no;scroll:no;');
		
	if ((returnedValue == "") || (returnedValue == null)) {		
	} else {
		callback(returnedValue);
	}
}
function openReturnWindowFieldCallback(sURL,Width,Height,boundField,callback) {
	var returnedValue;
	
	returnedValue = window.showModalDialog(sURL,null,'dialogHeight:' + Height + 'px;dialogWidth:' + Width + 'px;status:no;scroll:no;');
		
	if ((returnedValue == "") || (returnedValue == null)) {		
	} else{
		boundField.value = returnedValue;
		callback(returnedValue);
	}
}
function changeDate(dropdown,element) {
	if (dropdown.options[dropdown.selectedIndex].value=="CUSTOM") {
		element.style.display='';
	} else {
		element.style.display='none';
	}
}
function Set(sClassName) {
	window.event.srcElement.className = sClassName;
}
function Focus(oElement) {
	if (oElement) {
	    try { oElement.focus(); } 
	    catch (e) {}
	}
}
function AdjustEditor() {
	oContainer.style.height='100%';
	document.all.item('Editor1_Div').style.padding='5px';
	Editor1.style.height='100%';
	Editor1.rows(2).cells(0).style.height='100%';
}
function openCalendar(oTextField,sURL,Width,Height) {
	var Date;
	Date = window.showModalDialog(sURL + '?startdate=' + oTextField.value,null,'dialogHeight:' + Height + 'px;dialogWidth:' + Width + 'px;status:no;scroll:no;');
	
	if ((Date == "") || (Date == null)) {
		oTextField.focus();
	} else {
		oTextField.value = Date;
		oTextField.focus();
	}
}
function openConversion(oAmount,oCurrencyID,sURL,Width,Height) {
	openWindow(sURL + "?SELECTEDID=CURRENCY&MENUID=CURRENCY&CURRENCYID=" + oCurrencyID.value + "&AMOUNT=" + oAmount.value,Width,Height);
}
function GridKey() {
	// page left (left arrow or page up)
	if (event.keyCode == 37 || event.keyCode == 33) {
		if (document.all.item('DataPaging1:_ctl2') != null) {
			if (!document.all.item('DataPaging1:_ctl2').disabled) __doPostBack('DataPaging1$_ctl2','');
		}
	}
	// page right (right arrow or page down)
	if (event.keyCode == 39 || event.keyCode == 34) {
		if (document.all.item('DataPaging1:_ctl3') != null) {
			if (!document.all.item('DataPaging1:_ctl3').disabled) __doPostBack('DataPaging1$_ctl3','');
		}
	}
	// page first
	if (event.keyCode == 36) {
		if (document.all.item('DataPaging1:_ctl1') != null) {
			if (!document.all.item('DataPaging1:_ctl1').disabled) __doPostBack('DataPaging1$_ctl1','');
		}
	}
	// page last
	if (event.keyCode == 35) {
		if (document.all.item('DataPaging1:_ctl4') != null) {
			if (!document.all.item('DataPaging1:_ctl4').disabled) __doPostBack('DataPaging1$_ctl4','');
		}
	}
		// insert record
	if (event.keyCode == 45) {
		if (document.all.item('btnAdd') != null) {
			if (!document.all.item('btnAdd').disabled) __doPostBack('btnAdd','');
		}	
	}
	// delete record
	if (event.keyCode == 46) 
		if (window.event.srcElement.type != "text") {
			if (document.all.item('btnDelete') != null) {
				if (!document.all.item('btnDelete').disabled) {
					if (openWindow("/shared/components/global/confirm.aspx?TITLE=Confirm Delete&MESSAGE=You are about to delete the selected record(s).  Once this operation has been performed, it cannot be undone.  Are you sure you want to delete these records?",400,200) == false){ 
						window.event.cancelBubble=true; 
						return false; 
					} else {
						__doPostBack('btnDelete','');	
					}
				}
			}
		}
	// exit page
	if (event.keyCode == 27){if (typeof(Page_ClientValidate) != 'function' ||  Page_ClientValidate()) __doPostBack('btnClose','')}
	// copy
	if (event.keyCode == 67) {
		// check to see if the control key is down when the c is pressed
		if (event.ctrlKey) {
			if (document.all.item('btnCopy') != null) {
				if (!document.all.item('btnCopy').disabled) __doPostBack('btnCopy','');
			}
		}
	}
}
function FormKey() {
	// exit page
	if (event.keyCode == 27){if (typeof(Page_ClientValidate) != 'function' ||  Page_ClientValidate()) __doPostBack('btnClose','')}
}
function WindowKey() {
	// exit page
	if (event.keyCode == 27) window.close();
}
function Show(oElement) {
	if (oElement.style.display=="") {
		oElement.style.display="none";
	} else {
		oElement.style.display="";
	}
}
function OpenList(oLabelField,oHiddenField,sURL,Width,Height) {
	var ID
	ID = window.showModalDialog(sURL,null,'dialogHeight:' + Height + 'px;dialogWidth:' + Width + 'px;status:no;scroll:no;');
	if (typeof(ID) != "undefined") {
		var arrItems;
		arrItems = ID.split("~");
		if (arrItems.length == 2) {
			oHiddenField.value = arrItems[0];
			oLabelField.innerHTML = decodeURI(arrItems[1].replace("+"," "));
		}
	}
}

var allowapply = false;
var oldTitle = document.title;
var objDict = new ActiveXObject("Scripting.Dictionary");

function Reset() {
    if (typeof(Form1) == 'undefined') Form1 = document.forms[0]
    
	// only evaluate this method if btnSave exists on the page
	if (typeof(Form1.btnSave) != 'undefined') {
		objDict.RemoveAll();
		Form1.btnSave.disabled = true;
		document.title = oldTitle;	
	}
}

function Apply(e)
{
    if (typeof(Form1) == 'undefined') Form1 = document.forms[0]
    
    if (typeof(Apply.btnSave) == 'undefined') Apply.btnSave = Form1.btnSave
    
    if (typeof(Apply.btnSave) == 'undefined')
    {
        var formInputs = Form1.tags('input');
        
        for(var i = 0; i < formInputs.length; i++)
        {
            var elementId = new String(formInputs[i].id);
            if(elementId.indexOf("btnSave", 0) > 0)
            {
                Apply.btnSave = formInputs[i];
                break;
            }
        }
    }
    
	// only evaluate this method if btnSave exists on the page
	if (typeof(Apply.btnSave) != 'undefined') {
		var changedCount=0;
		var x,a,i;
		var currentValue;
		var defaultValue;
		var option;
		
		// Allow id Name to be passed in. 20060606/foltzp
		if (typeof(e) == "string")
			e = document.getElementById(e)
		
		
	    switch (e.type) {
		    case "checkbox":
			    currentValue=e.checked;
			    defaultValue=e.defaultChecked;
			    if (currentValue == defaultValue) {
				    if (objDict.Exists(e.id)){ objDict.Remove(e.id); }
				    objDict.Add(e.id,false);
			    } else {
				    if (objDict.Exists(e.id)){ objDict.Remove(e.id); }
				    objDict.Add(e.id,true);
			    }
			    break;
		    case "radiobutton":
			    currentValue=e.checked;
			    defaultValue=e.defaultChecked;
			    if (currentValue == defaultValue) {
				    if (objDict.Exists(e.id)){ objDict.Remove(e.id); }
				    objDict.Add(e.id,false);
			    } else {
				    if (objDict.Exists(e.id)){ objDict.Remove(e.id); }
				    objDict.Add(e.id,true);
			    }
			    break;
		    case "select-one":				
			    for (i=0;i<e.options.length;i++)  { 					
				    if (e.options[i].selected) {							
					    currentValue=e.options[i].selected;
					    defaultValue=e.options[i].defaultSelected;
				    }					
			    }
			    if (currentValue == defaultValue) {
				    if (objDict.Exists(e.id)){ objDict.Remove(e.id); }
				    objDict.Add(e.id,false);
			    } else {
				    if (objDict.Exists(e.id)){ objDict.Remove(e.id); }
				    objDict.Add(e.id,true);
			    }
			    break;
		    case "select-multiple":
			    for (i=0;i<e.options.length;i++) { 					
				    currentValue=e.options[i].selected;
				    defaultValue=e.options[i].defaultSelected;
					
				    if (currentValue == defaultValue) {
					    if (objDict.Exists(e.id + '_' + i)){ objDict.Remove(e.id + '_' + i); }
					    objDict.Add(e.id + '_' + i,false);
				    } else {
					    if (objDict.Exists(e.id + '_' + i)){ objDict.Remove(e.id + '_' + i); }
					    objDict.Add(e.id + '_' + i,true);
				    }
			    }
			    break;
		    default:
		        if(e.constructor == Array){
	                if (objDict.Exists(e[0])){ objDict.Remove(e[0]); }
		                objDict.Add(e[0],!e[1]);
	            }
	            else {
			        currentValue=e.value;
			        defaultValue=e.defaultValue;
			        if (currentValue == defaultValue) {
				        if (objDict.Exists(e.id)){ objDict.Remove(e.id); }
				        objDict.Add(e.id,false);
			        } else {
				        if (objDict.Exists(e.id)){ objDict.Remove(e.id); }
				        objDict.Add(e.id,true);
			        }
			    }
			    break;
	    }
						
		a = (new VBArray(objDict.Keys())).toArray();   // Get the keys.
		
		for (x in a) { 				
			if (objDict(a[x])==true){ changedCount++; }
		}
        
		if (changedCount > 0) {
			allowapply=true;					
			document.title = oldTitle + " *";
		} else {
			allowapply=false;
			document.title = oldTitle;
		}
		
		// Form1.btnSave.disabled = !allowapply;
		Apply.btnSave.disabled = !allowapply;
	}
}
function checkForChanges() {
    if (typeof(Form1) == 'undefined') Form1 = document.forms[0]

	// only evaluate this method if btnSave exists on the page
	if (typeof(Form1.btnSave) != 'undefined') {
		if (allowapply) {
			event.returnValue = "You have modified this form and not selected the Apply button.  Are you sure you want to exit?";
		}
	}
}
function enumerateProperties(object,maxvaluelength) {
	var prop;
	var message = "";
	for (prop in object) 
	{
		var value = "" + object[prop];		
		message += prop + "=" + value.substring(0,maxvaluelength) + "\n";					
	}
	return message;
}

function getRoot(sGetDomainUrl) {
var sRoot ;
    //alert(sGetDomainUrl);
   var iStart = sGetDomainUrl.indexOf('/');
		if (iStart == 0) {
		   var iEnd= sGetDomainUrl.substring(1,sGetDomainUrl.length).indexOf('/');
            sRoot = sGetDomainUrl.substring(iStart,iEnd+1);
		} else {
		   sRoot ='/';
		}
		//alert(sRoot);
    return sGetDomainUrl;
}

// A killer 2-line method of chaining window.onload function calls
// http://blog.firetree.net/2005/07/17/javascript-onload/
// To call a function w/parameters, wrap the call in another function that doesn’t take parameters:
// WindowOnload(function() { myFunction(param) });
function WindowOnload(f) {
    var prev=window.onload;
    window.onload=function(){ if(prev)prev(); f(); }
}

//PORTALS specific scripts

// this hides and shows the information panel attached to each portal. 
// First sibling is the Empty row and 2nd sibling is the row containing InfoPanelContent.
// "ingavals - 07/19/2007"
function collapseinfopanel(infobutton) {
    var panel;
    panel = infobutton.parentNode.parentNode.nextSibling.nextSibling;
    panel.style.display=panel.style.display=='block'?'none':'block';
}

// getElementById shortcut alias
var $ = function (el) {
    if (typeof el == 'string')
        return document.getElementById(el);
    return el
}

// Provide client-side method mirroring the server-side String.IsNullOrEmpty, to simplify string checks
String.IsNullOrEmpty = function(str){
    return ((typeof(str) != "string") || (str.length == 0));
}

// Find first active input field on the page and attempt to set focus
function setFocusToFirstInputField(){
    if (document.forms[0]){
        for (i = 0; i < document.forms[0].elements.length; i++){
            var oE=document.forms[0].elements[i];
	        if (oE.type != "hidden" && oE.disabled != true && oE.style.display != "none"){
		        Focus(oE);
		        return;
	        }
        }
    }	
}

//////////////////////////////////
// begin QueryManager helpers
// Purpose:
//      Help mange compound values representing aspects of query
// Format:
//      q:QUERY-NAME;v:VIEW-NAME;t:DATA-SOURCE-TYPE
// Todo:
//      Move out of global.js and objectify
//
// Placeholder for Datasource types:
//QueryManagement.DataSourceTypes = {
//        'RelationalDatabase': 0,
//        'EmbeddedSource': 1,
//        'SharePoint': 2,
//        'FileLibraryCSV': 3,
//        'FileLibraryXls': 4
//    };

// return "q:" part
function QM_ExtractQueryName( value)
{
    var parts = value.split(";")
    var max = parts.length
    for (var i=0;i<max;i++)
    {
        if (parts[i].charAt(0) == "q")
            return parts[i].substr(2);
    }
    return "";
}

// Return the "t:" part
function QM_ExtractQueryDataSourceType( value)
{
    var parts = value.split(";")
    var max = parts.length
    for (var i=0;i<max;i++)
    {
        if (parts[i].charAt(0) == "t")
            return parts[i].substr(2);
    }
    return "";
}
// End QueryManager helpers
//////////////////////////////////
function copyToClipboard(A){
  if(window.clipboardData){
    window.clipboardData.setData("text", A);
  } else {
    var flashCopier = $("flashcopier");
    if(flashCopier==null){
      flashCopier=document.createElement("div");
      flashCopier.id="flashcopier";
      document.getElementsByTagName("body")[0].appendChild(flashCopier);
    }
    flashCopier.innerHTML='<embed src="/Common/flash/clipboard.swf" FlashVars="clipboard='+encodeURIComponent(A)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
  }
}
