function ToggleDisplay(id, allowPrint)
{	
	var idArray = id.split(",");
	for(i = 0; i < idArray.length; i++)
	{
		var curDisplayState = document.getElementById(idArray[i]).style.display;
		var curClassState = document.getElementById(idArray[i]).className
		if(curDisplayState == "none" || (allowPrint && curClassState == "printonly"))
		{		
			if(!allowPrint)
			    document.getElementById(idArray[i]).style.display = "";
			else
			    document.getElementById(idArray[i]).className = "";
	    }
		else
		{
		    if(!allowPrint)
			    document.getElementById(idArray[i]).style.display = "none";
			else			
			    document.getElementById(idArray[i]).className = "printonly";
		}
	}
}

function ToggleText(id,txt1,txt2)
{
	var text = document.getElementById(id).innerText;
	if(text == txt1 || text != txt2)
		document.getElementById(id).innerText = txt2;
	else
		document.getElementById(id).innerText = txt1;
}

function ToggleColumns(tableId,columnNumbers) 
{
	var tbl  = document.getElementById(tableId);
	var rows = tbl.getElementsByTagName('tr');
	var columnArray = columnNumbers.split(",");
	
	for (var row=0; row < rows.length; row++) 
	{
		var cells = rows[row].getElementsByTagName('td')
		for(i = 0; i < columnArray.length; i++)
		{			
			var curState =cells[columnArray[i]].style.display;
			if(curState == "none")
				cells[columnArray[i]].style.display = "";
			else
				cells[columnArray[i]].style.display = "none";;
		}
	}
}

function ShowOverlay(layerID)
{
    //TODO: add cross browser support
    var theSrc = window.event.srcElement;
    var theLayer = document.getElementById(layerID);        
    
    theLayer.style.left = theSrc.style.left;
    theLayer.style.top = theSrc.style.top;
    theLayer.style.display = ""; 
}

function HideOverlay(layerID)
{
    var theLayer = document.getElementById(layerID);        
    theLayer.style.display = "none";
}

///To show div by jQuery animation
///divName - Name of div object to work with
///speed - [slow,fast] the speed to show/hide animation
function jQueryShowDiv(divName, speed) {
    var div = document.getElementById(divName);
    if (div != null) {
        $(div).show(speed);
    }
}

///To hide div by jQuery animation
///divName - Name of div object to work with
///speed - [slow,fast] the speed to show/hide animation
function jQueryHideDiv(divName, speed) {
    var div = document.getElementById(divName);
    if (div != null) {
        $(div).hide(speed);
    }
}

///This will show/hide html element.
function ShowHideHtmlElement(id, show) {
	var htmlElement = document.getElementById(id);

	if (htmlElement != null) {
		if (show == true) {
			htmlElement.style.display = 'block';
		} else {
			htmlElement.style.display = 'none';
		}
	}
}

function ParseParameterString() {
	var searchParamsString = document.location.search.substring(1);
	var params = {};
	if (searchParamsString.length > 0) {
		var parameterPairs = searchParamsString.split("&");
		for (var pairIndex in parameterPairs) {
			var kvp = parameterPairs[pairIndex];
			var sp = kvp.split("=");
			if (sp.length == 1) {
				params[sp[0].toLowerCase()] = true;
			}
			else if (sp.length == 2) {
				params[sp[0].toLowerCase()] = sp[1];
			}
		}
	}
	return params;
}

function JQInitTabs(tabsRoot, tabContentRoot, showTab, tabChecklist, animate) {
	animate = typeof (animate) == 'undefined' ? false : animate; //don't animate on initialize
	tabChecklist = typeof (tabChecklist) == 'undefined' ? new Array() : tabChecklist;

	if (tabChecklist.length > 0) {
		var tabs = $("#" + tabsRoot + " li");
		var content = $("#" + tabContentRoot + " .tabContent");
		var nextTab, nextContent, tab;
		for (var i = 0; i < tabChecklist.length; i++) {
			tab = tabChecklist[i];
			nextTab = tabs.filter(".active, .current").filter("." + tab + "_tab");
			nextContent = content.filter("." + tab + "_tabContent");
			if (nextTab.length > 0) {
				if (nextContent.length <= 0) {
					nextTab.removeClass("active current").addClass("disabled");
				}
			}

		}
	}


	JQShowTabFrom(tabsRoot, tabContentRoot, showTab, false);
}

//animate requires jquery-ui
function JQShowTabFrom(tabsRoot, tabContentRoot, tab, animate) {
	animate = typeof (animate) == 'undefined' ? true : animate;
	var tabs = $("#" + tabsRoot + " li");
	var content = $("#" + tabContentRoot + " .tabContent");
	var nextTab = tabs.filter(".active, .current").filter("." + tab + "_tab");
	var nextContent = content.filter("." + tab + "_tabContent");
	if (nextTab.length > 0 && nextContent.length > 0) {
		//remove current active links
		tabs.filter(".current").removeClass("current").addClass("active");
		content.hide();
		nextTab.removeClass("active").addClass("current");
		if (animate) {
			//nextContent.show("blind", {}, "slow");
			//todo: find out how to get jquery-ui animations to not trigger the ready event
			nextContent.show();
			$(document).trigger('tabChanged', [tab]);
		} else {
			nextContent.show();
			$(document).trigger('tabChanged', [tab]);
		}
	}
};

function JQDatePickerOptions(moreOptions) {
	var options = {
		showOtherMonths: true,
		selectOtherMonths: true,
		changeMonth: true,
		changeYear: true,
		//showButtonPanel: true
		showAndim: 'slideDown',
		duration: 0//'fast'
	};
	if(moreOptions) {
		for(var key in moreOptions) {
			options[key] = moreOptions[key];
		}
	} 
	return options;
}


//NOTE: depends on 		jquery.bgiframe plugin and jquery for ie6 to work properly, be sure to include it on pages that may have z-index issues with select boxes
//JQUIDialogPopup(control, triggerControl, optionOverrides, hideTitle, anchor)
//control - the control to turn into a dialog popup
//triggerControl - the control that gets the click events applied to it to open the dialog
//optionOverrides -optional- additional options to send to initialize the dialog
//  offsetAdjustLeft & offsetAdjustTop -optional- will offset where the dialog appears from relative to the anchor(or triggerControl)
//hideTitle -optional- whether to add the style to make this a more minimal dialog box
//anchor -optional- what the dialog positions itself against when opening
//
//all controls/anchors should be JQuery objects
function JQUIDialogPopup(control, triggerControl, optionOverrides, hideTitle, anchor) {
	if (typeof (hideTitle) == "undefined") {
		hideTitle = false;
	}
	if (typeof (anchor) == "undefined") {
		anchor = triggerControl;
	}
	var options = {
		resizable: false,
		draggable: false,
		autoOpen: false,
		open: function(event, ui) { control.data("dialog_showing", true) },
		close: function(event, ui) { control.data("dialog_showing", false) },
		show: "blind",
		dialogClass: "dropDownDialog",
		offsetAdjustLeft: 0,
		offsetAdjustTop: 0
	};
	if (hideTitle) {
		options["dialogClass"] = "dropDownDialog minimalMenuPopup";
	}
	if (optionOverrides) {
		for (var key in optionOverrides) {
			if(key == "dialogClass") {
				options[key] = options[key] + ' ' + optionOverrides[key];
			} else {
				options[key] = optionOverrides[key];
			}
		}
	}
	control.dialog(options);
	triggerControl.click(function(e) {
		if (control.data("dialog_showing")) {
			control.dialog('close');
		} else {
			var offset = anchor.offset();
			var offsetTop = options.offsetAdjustTop;
			if(typeof(offsetTop) == "object") {
				offsetTop = offsetTop.outerHeight();
			}
			var offsetLeft = options.offsetAdjustLeft;
			if(typeof(offsetLeft) == "object") {
				offsetLeft = offsetLeft.outerWidth();
			}
			control.dialog("option", "position", [offset.left + offsetLeft, offset.top + offsetTop - $(document).scrollTop()]);
			control.dialog('open');
		}
		return false;
	});
	$(document.body).bind('click', function(e) {
		if (control.data("dialog_showing")) {
			if (!$.contains(control.dialog('widget')[0], e.target)) {
				control.dialog('close');
			}
		}
	});
}

// EBA ComboBox utility methods
function selectEvent(comboID, txtBoxID, fieldIndex) 
{ 
    selectEvent(comboID, txtBoxID, fieldIndex, false);
}

// EBA ComboBox utility methods
function selectEvent(comboID, txtBoxID, fieldIndex, postback) 
{ 
    var selectedValue = document.getElementById(comboID).object.GetSelectedRowValues()[fieldIndex];
    
    //only reselect and postback if the value has changed
    if(document.getElementById(txtBoxID).value != selectedValue)
    {
	    // copy selected value from list to the hidden .net TextBox control 	
	    document.getElementById(txtBoxID).value = selectedValue; 	

	    if(postback == true && selectedValue != '') 
	    {
	        __doPostBack(comboID + '$ebaCombo','Select');	 	        
	    }
	}
} 

var popup;
function ShowHelp(sender, applyFilters)
{				
	//if there are any other popups open close them now
	if(popup)
		HideHelp();
	else
	{
		var loc = getMouseLoc();
		//var loc = getObjLoc(sender);
	
		//get the help msg for this link
		popup = document.getElementById(sender.HelpPanelID);	
		
		if(!popup)
		    return;
		    
		//if(popup.parentElement.tagName == "LEGEND")		
		document.getElementsByTagName("body").item(0).appendChild(popup);
        popup.style.width = popup.width;
        
		if(applyFilters && popup.filters != null && popup.filters.length > 0)
			popup.filters[0].apply();
	
		popup.style.position = "absolute";		
		popup.style.top = loc.y;
		popup.style.left = loc.x;
		popup.style.display = "block";
		popup.style.visibility = "visible"
		
		if(applyFilters && popup.filters != null && popup.filters.length > 0)
			popup.filters[0].play();
	
	}
}

function HideHelp(applyFilters)
{	
	if(popup)
	{			
		if(applyFilters && popup.filters != null && popup.filters.length > 0)
			popup.filters[0].apply();

		popup.style.visibility = "hidden";

		if(applyFilters && popup.filters != null && popup.filters.length > 0 )
			popup.filters[0].play();				
		
		popup = null;
	}
}

function getScrollWidth() {
	var w = window.pageXOffset ||
           document.body.scrollLeft ||
           document.documentElement.scrollLeft;

	return w ? w : 0;
}

function getScrollHeight() {
	var h = window.pageYOffset ||
           document.body.scrollTop ||
           document.documentElement.scrollTop;

	return h ? h : 0;
}

function getMouseLoc() {
	var x;
	var y;

	// NOTE: document.body.scrollTop and document.body.scrollLeft always equal to 0 on the new quote page,
	// use these methods to get browser compatible scroll width and height
	x = event.clientX + getScrollWidth();
	y = event.clientY + getScrollHeight();

	var loc = new Object();
	loc.x = x + 12;
	loc.y = y + 10;
	return loc;
}

//not used but could be useful
function getCenter()
{
	var clientHeight;
	var clientWidth;
	var docTop;
	var docLeft;	

	clientHeight = document.body.clientHeight;
	clientWidth = document.body.clientWidth;
	docTop = document.body.scrollTop;
	docLeft = document.body.scrollLeft;
    
	var loc = new Object();
	loc.x = docLeft + clientWidth/2;
	loc.y = docTop + clientHeight/2;
	return loc;
}

function getObjLoc(obj)
{
	var objTop = obj.offsetTop;
	var objLeft = obj.offsetLeft;
	var clientWidth= obj.offsetWidth;
	var clientHeight= obj.offsetHeight;		

	var loc = new Object();
	loc.x = objLeft + clientWidth;
	loc.y = objTop + clientHeight;
	return loc;
}

/* Returns the text value of a document element like <span> or <div>
   should be cross browser compliant. */
function SetElementText(element, text)
{
	if (element != null)
	{
		if (typeof(element.textContent) != "undefined")
			element.textContent = text;
		else if (typeof(element.innerText) != "undefined")
			element.innerText = text;
	}
}

/* Sets the text value of a document element like <span> or <div>
   should be cross browser compliant */
function GetElementText(element)
{
	if (element != null)
	{
		if (typeof(element.textContent) != "undefined")
			return element.textContent;
		else if (typeof(element.innerText) != "undefined")
			return element.innerText;
		else
			return "";
	}
}

/* Fires the specified elements onchange event should be cross browser compliant */
function FireOnChangeEvent(element)
{
	if(element != null)
	{
		if(document.createEvent)
		{
			var e = document.createEvent("HTMLEvents");
			e.initEvent("change", false, false);
			element.dispatchEvent(e);
		}
		else
		{
			element.fireEvent("onchange");
		}
	}
}

/* Returns the index of an item in an array */
function indexOf(array, item)
{
	for(var i = array.length; i-- && array[i] != item;);
		return i;
}

function readCookie(name, unescaped)
{
	var nameEQ = name + '=';
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++)
	{
		var c = ca[i];
		while (c.charAt(0) == ' ') 
			c = c.substring(1, c.length);
		
		if (c.indexOf(nameEQ) == 0) 
		{
			var escapedValue = c.substring(nameEQ.length, c.length);
			return unescaped ? unescape(escapedValue) : escapedValue;
		}
	}
	return null;
}

function setCookie(name, value, expires, path, domain, secure){
	var cookieString = name + "=" + escape(value) + "; ";
	
	if(expires){
		expires = setExpiration(expires);
		cookieString += "expires=" + expires + "; ";
	}
	if(path){
		cookieString += "path=" + path + "; ";
	}
	if(domain){
		cookieString += "domain=" + domain + "; ";
	}
	if(secure){
		cookieString += "secure; ";
	}
	document.cookie = cookieString;
}

// cookieLife in milliseconds
function setExpiration(cookieLife){
    var today = new Date();
    var expr = new Date(today.getTime() + cookieLife * 1000);
    return  expr.toGMTString();
}

function isNullOrUndefined(value) {
    /// <summary>
    ///     Determines if the provided value is null or undefined.
    /// </summary>
    /// <param name="value">The object to check.</param>
    /// <returns>
    ///     A bool value, true if value is null or undefined, false otherwise.
    /// </returns>
    return (value == null || value == undefined);
}

function UIString(value) {
    /// <summary>
    ///     Converts the value string object to a proper UI textnode (empty strings for null or undefined objects).
    /// </summary>
    /// <param name="value">Text string to check.</param>
    /// <returns>
    ///     The resulting textnode.
    /// </returns>
    var newString = isNullOrUndefined(value) ? "" : value;

    return document.createTextNode(newString);
}


function CreateSelectOptionTag(value, text, label, innerHTML) {
    /// <summary>
    ///     Add option item to select tag
    /// </summary>
    /// <param name="value">attribute value string</param>
    /// <param name="text">attribute text string</param>
    /// <param name="label">attribute label string (spcifically for IE)</param>
    /// <param name="innerHTML">text betweeen the open and close tag</param>
    /// <returns>
    ///     The resulting textnode.
    /// </returns>    
    optionObject = document.createElement('option');
    optionObject.value = value;
    optionObject.text = text;
    optionObject.label = label; //specificly for IE.
    optionObject.innerHTML = innerHTML;

    return optionObject;
}


function IsInArray(array, searchValue) {
    for (var i = 0; i < array.length; i++) {
        if (array[i] === searchValue)
            return true;
    }
    return false;
}


function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g, '');
    if (isNaN(num)) {
        num = "0";
    }
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num * 100 + 0.50000000001);
    cents = num % 100;
    num = Math.floor(num / 100).toString();
    
    if (cents < 10) {
        cents = "0" + cents;
    }
    
    for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
        num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
    }
    
    return (((sign) ? '' : '-') + '$' + num + '.' + cents);
}

///<summary>
/// array of element type that can be used along with createElement
///</summary
elementTypes = { div: 'div', span: 'span', a: 'a', img: 'img', p: 'p', table: 'table', row: 'tr', column: 'td'
};

function createElement(type, parent, id, cssClass, appendChild) {
    ///<summary>
    ///     Creates a new element
    ///</summary>
    /// <param name="type">Type of the new element.</param>    
    /// <param name="parent">Parent div to add new element to.</param>
    /// <param name="id">ID of the new element.</param>
    /// <param name="cssClass">Css Class to add to the new element.</param>
    /// <param name="appendChild">First child element to add to the new element.</param>
    var divName = document.createElement(type);

    if (!isNullOrUndefined(id)) {
        divName.setAttribute('id', id);
    }
    if (!isNullOrUndefined(parent)) {
        parent.appendChild(divName);
    }

    if (!isNullOrUndefined(cssClass)) {
        Sys.UI.DomElement.addCssClass(divName, cssClass);
    }
    if (!isNullOrUndefined(appendChild)) {
        divName.appendChild(appendChild);
    }
    return divName;
}

function ConfirmationDialog(confirmationMsg) {
    if (confirm(confirmationMsg)) {
        return true;
    }
    return false;
   }

// Need to handler internation dollar separater in the future if we support that
String.prototype.trimRightZeros = function() {
   	var valueString = this.toString();
   	var lastIndexOfDot = valueString.lastIndexOf('.');
   	if (lastIndexOfDot > 0) {
   		for (var lastDigitNonZero = valueString.length - 1; lastDigitNonZero >= lastIndexOfDot; lastDigitNonZero--) {
   			if (valueString.charAt(lastDigitNonZero) != '0' && valueString.charAt(lastDigitNonZero) != '.') {
   				break;
   			}
   		}
   	}
   	return valueString.substring(0, lastDigitNonZero + 1);
}

/*
String.prototype.formatTrimZeros = function(formatString) {
	return this.format(formatString).trimRightZeros();
}
*/

//a common function used throughout quote and account pages. 
//ddlCoverageType - a dropdownlist object ClientID
function SetCancelTerms(ddlCoverageTypeClientID, ddlDaysToCancelClientID) {

	var ddlCoverageType = document.getElementById(ddlCoverageTypeClientID);
	var numberOfDaysToCancel = ddlCoverageType.options[ddlCoverageType.selectedIndex].attributes["NumberOfDaysToCancel"].value;
	var ddlDaysToCancel = document.getElementById(ddlDaysToCancelClientID);
	var Idx = undefined;


	for (i = 0; i < ddlDaysToCancel.length; i++) {
		//since coveragetype selected has change. we'll automatically remove additional item was added to the top
		if ((ddlDaysToCancel.options[i].attributes["enabled"].value == "false")) {
			ddlDaysToCancel.remove(i);
		}

		//get the top most available cancel terms
		if ((Idx == undefined) && (ddlDaysToCancel.options[i].attributes["enabled"].value == "true")) {
			Idx = i;
		}

		//compare to find the match default cancel terms
		if (numberOfDaysToCancel == ddlDaysToCancel.options(i).value) {
			Idx = i;
			break;
		}
	}


	//default it to top most val
	ddlDaysToCancel.selectedIndex = Idx;
}
