// -------------------------------------------------------------------
// PrestoCommon.js
//   common JS functions for the presto.com web apps
//
// Requirements:
//   None
//
// Version: 
//   $Id: $
// -------------------------------------------------------------------


// -------------------------------------------------------------------
// Globals
// -------------------------------------------------------------------
//
var gDubug		= false;
var gDebugMsg	= "";
var gStartTime;
var gScreenX;
var gScreenY;

// -------------------------------------------------------------------
// PrestoCommon()
//   a mock constructor. 
// -------------------------------------------------------------------
//
function PrestoCommon() {
	// get the size of the window
	//
	if (document.body.scrollHeight > document.body.offsetHeight) {
		// all but Explorer Mac
		//
		gScreenX = document.body.scrollWidth;
		gScreenY = document.body.scrollHeight;
	} else {
		// Explorer Mac, but would also work in Explorer 6 Strict, 
		// Mozilla and Safari
		//
		gScreenX = document.body.offsetWidth;
		gScreenY = document.body.offsetHeight;
	}
	
	//This is to get the size of the viewport of the browser
	//
    var viewPortY;
    if( typeof( window.innerHeight ) == 'number' ) {
        //Non-IE
        viewPortY = window.innerHeight;
    } else if( document.documentElement && document.documentElement.clientHeight ) {
        //IE 6+ in 'standards compliant mode'
        viewPortY = document.documentElement.clientHeight;
    } else if( document.body && document.body.clientHeight ) {
        //IE 4 compatible
        viewPortY = document.body.clientHeight;
    }
	
	//Check to see if the view port is larger than the body of the html document
    //
    if (gScreenY < viewPortY){
        _DEBUG("PrestoCommon: Viewport is larger than the document body");
        gScreenY = viewPortY;
    }
	
	// if the curtain is down, let's be sure to resize it. 
	//
	if (gCurtainCurrentOpacity > 1) {
		var curtain = new getObj(gCurtainId);
		curtain.style.height = gScreenY + "px";
		curtain.style.width  = gScreenX + "px";
	}

	_DEBUG("PrestoCommon(): Screen size set at: " + gScreenX + "x" + gScreenY);
}


// -------------------------------------------------------------------
// getObj()
//   The quirksmode DHTML micro api 
// Arguments:
//	 name - the name of the element. 
// -------------------------------------------------------------------
//
function getObj(name) {
	if (document.getElementById) {
		this.obj		= document.getElementById(name);
		this.style		= document.getElementById(name).style;
	} else if (document.all) {
		this.obj		= document.all[name];
		this.style		= document.all[name].style;
	} else if (document.layers) {
		this.obj		= document.layers[name];
		this.style		= document.layers[name];
	}
	this.ClassName		= this.obj.className;
	this.AddClass		= function(className) {AddCssClass(this.obj, className);}
	this.RemoveClass	= function(className) {RemoveCssClass(this.obj, className);}
	this.id				= name;
	this.GetOpacity		= function()  {GetOpacityOfElement(this.obj)};
	this.SetOpacity		= function(p) {SetOpacityOfElement(this.obj, p);}
}


// -------------------------------------------------------------------
// GetOpacityOfElement()
//   Gets an int value (0-100) that represent's an element's opacity 
// Arguments:
//	 el - the element to examine. 
// -------------------------------------------------------------------
//
function GetOpacityOfElement(el) {
	// first, let's try and get the "filter" value from IE
	//
	if (el.style.filter) {
		var filterStr = el.style.filter;
		if (filterStr == null || filterStr == "") {
			_DEBUG("GetOpacityOfElement(): No opacity declared in " + el.id + ", returning 100");
			SetOpacityOfElement(el, 100);
			return 100;
		}
		
		var ary = filterStr.split("=");
		var op	= parseInt(ary[1].substring(0, ary[1].length -1));
		_DEBUG("GetOpacityOfElement(): Returning opacity: " + el.id + " is: " + op);
		return op;
	
	// otherwise, let's use the mozilla/safari "opacity" value
	//
	} else {
		var opacityStr 	= el.style.opacity || el.style.MozOpacity ||  el.style.KhtmlOpacity;
		if (opacityStr == null || opacityStr == "") {
			_DEBUG("GetOpacityOfElement(): No opacity declared in " + el.id + ", returning 100");
			SetOpacityOfElement(el, 100);
			return 100;
		}
		
		var op = opacityStr * 100;
		_DEBUG("GetOpacityOfElement(): Returning opacity: " + el.id + " is: " + op);
		return op;
	}
}

// -------------------------------------------------------------------
// SetOpacityOfElement()
//   Sets the opacity of an object using an int value (0-100) 
// Arguments:
//	 e - the element to examine. 
//	 percent - an int, (0-100) that represents the opacity value to set
// -------------------------------------------------------------------
//
function SetOpacityOfElement(e, percent) {
	_DEBUG("SetOpacityOfElement(): Setting opacity of " + e.id + " to " + percent);
	e.style.filter 		= "alpha(opacity=" + percent + ")";
	e.style.opacity 	= percent/100;
	e.style.MozOpacity	= percent/100;
	e.style.KhtmlOpacity= percent/100;	
}



// -------------------------------------------------------------------
// createInput()
//   Creates HTML input elements since IE is broken 
// Arguments:
//	 type - the type of input to create
//   id - the HTML id of the new element.
// -------------------------------------------------------------------
//
function CreateInput(type, id) {
	var element = null;

	// First try the IE way; if this fails then use the standard way
	//
	try {
		element		= document.createElement("<input type=\"" + type + "\" id=\""+id+"\" name=\"" + id + "\">");
	// Probably failed because we’re not running on IE, so do it the normal way
	//
	} catch (e) {
		element		= document.createElement("input");
		element.id  = id;
		element.name= id;
		element.setAttribute("type", type);
	}
	return element;
}


// -------------------------------------------------------------------
// focus()
// Arguments:
//   id :  id of the element
// -------------------------------------------------------------------
//
function focusThis(id) {
	var e = document.getElementById(id);
	e.focus();
}


// -------------------------------------------------------------------
// OpenTos()
//   open TOS, PP, Billing pages and Supplies More Info in a new window
// -------------------------------------------------------------------
//
function OpenTos(url) {
	var name	= "tosWindow";
	var f		= "toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=700,height=600";
	var win		= window.open(url,name,f);
	win.focus();
	return false;	
}
function OpenPP(url) {
	var name	= "ppWindow";
	var f		= "toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=700,height=600";
	var win		= window.open(url,name,f);
	win.focus();
	return false;	
}
function OpenBilling(url) {
	var name	= "billingWindow";
	var f		= "toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=560,height=320";
	var win		= window.open(url,name,f);
	win.focus();
	return false;	
}
	
function OpenMoreSupplyInfoPricing(url) {
	var name	= "moreSupplyInfoPricingWindow";
	var f		= "toolbar=no,location=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,width=590,height=610";
	var win		= window.open(url,name,f);
	win.focus();
	return false;	
}


// -------------------------------------------------------------------
// GetElementsLeftPosition()
//   Gets the x coordinate for a given element
// Arguments:
//	 obj - the HTML element.
// -------------------------------------------------------------------
//
function GetElementsLeftPosition(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	} else if (obj.x)
		curleft += obj.x;
	return curleft;
}


// -------------------------------------------------------------------
// GetElementsTopPosition()
//   Gets the y coordinate for a given element
// Arguments:
//	 obj - the HTML element.
// -------------------------------------------------------------------
//
function GetElementsTopPosition(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	} else if (obj.y)
		curtop += obj.y;
	return curtop;
}

// -------------------------------------------------------------------
// GetOffsetTop()
//   Gets the height for a given element
// Arguments:
//	 obj - the HTML element.
// -------------------------------------------------------------------
//
function GetOffsetTop(obj) {
	var cur = 0;
	if(obj.offsetParent) {		
		while(obj.offsetParent) {
			cur += obj.offsetTop;
			obj = obj.offsetParent;
		}
	}		
	return cur;
}

// -------------------------------------------------------------------
// AddEvent()
//   Attaches an event listener to an object. 
//	 This isn't a 100% reliable method, but for simple elements 
//   (anchors, and what not) it should work fine. 
// Arguments:
//	 element - the HTML element to attach the event listener to
///	 mozillaEvent - the name of the eventLister for mozilla and safari
//   ieEvent - the name of the stupid IE event 
//	 f - 
// -------------------------------------------------------------------
//
function AddEvent(element, mozillaEvent, ieEvent, f) {

	// mozilla
	//
	if (navigator.userAgent.toLowerCase().indexOf("msie")==-1) {
		element.addEventListener(mozillaEvent,f, false);
	}
	// ie
	//
	else {
		element.attachEvent(ieEvent,f);
	}
}


// -------------------------------------------------------------------
// RemoveCssClass()
//   Removes a CSS class from an HTML element. 
// Arguments:
//	 element - the element with the class to remove
//	 className - the className to remove
// -------------------------------------------------------------------
//
function RemoveCssClass(element, className) {
	var regExStr = Trim(className) + "\\b";
	if (element.className.indexOf(className) != -1) {
		element.className = element.className.replace(new RegExp(regExStr), "");
	}
}


// -------------------------------------------------------------------
// AddCssClass()
//   Adds a CSS class from an HTML element. 
// Arguments:
//	 element - the element
//	 className - the className to add
// -------------------------------------------------------------------
//
function AddCssClass(element, className) {
	var newClassStr = " " + className;
	if (element.className.indexOf(className) == -1) {
		element.className += newClassStr;
	}
}



// -------------------------------------------------------------------
// LTrim(), RTrim(), Trim()
//   Removes white space from the given string
// Arguments:
//	 str - the string to trim
// -------------------------------------------------------------------
//
function LTrim(str) {
   var whitespace = new String(" \t\n\r");
   var s = new String(str);

   if (whitespace.indexOf(s.charAt(0)) != -1) {
      // We have a string with leading blank(s)...
      //
      var j=0, i = s.length;
      
      // Iterate from the far left of string until we
      // don't have any more whitespace...
      //
      while (j<i && whitespace.indexOf(s.charAt(j)) != -1)
         j++;
      s = s.substring(j, i);
   }
   return s;
}
function RTrim(str){
   var whitespace = new String(" \t\n\r");
   var s = new String(str);

   if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {
      var i = s.length - 1; 
      while (i>=0 && whitespace.indexOf(s.charAt(i)) != -1)
         i--;
      s = s.substring(0, i+1);
   }
   return s;
}
function Trim(str) {
	if (str.length != 0) {
		var newStr = RTrim(LTrim(str));
		return newStr;
	} else {
		return null;
	}
}

// -------------------------------------------------------------------
// PadString()
//   Pads a the leftside of a string
// Arguments:
//	 str - the string 
//	 c - the char to pad with
//	 l - the length of the padded string
// -------------------------------------------------------------------
//
function LeftPadString(str, c, l) {
	if (str.length >= l) {return str;}
	if (c.length != 1) {return str;}
	var a = l-str.length;
	for (var i=0; i<a; i++) {
		str = c + str;
	}
	return str;
}


// -------------------------------------------------------------------
// Common Set, Get and Delete cookie methods. 
// -------------------------------------------------------------------
//
function SetCookie(name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + escape(value) +
        ((expires)? "; expires=" + expires : "") +
        ((path)	  ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

function GetCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1) {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

function DeleteCookie(name, path, domain) {
	if (GetCookie(name)) document.cookie = name + "=" +
		((path)   ? ";path=" + path : "") +
		((domain) ? ";domain=" + domain : "" ) +
		";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function TestCookies() {
	// set the test cookie
	var cookieName	= "testCookie";
	var cookieVal	= "set";
	SetCookie(cookieName, "set");
	if (GetCookie(cookieName) == cookieVal) {
		_DEBUG("cookie found");
	} else {
		_DEBUG("no cookie found");
		document.location.href = gBasePath + "Compatibility.aspx?returnUrl=" + encodeURIComponent(document.location);
	}
	DeleteCookie(cookieName);
}


// -------------------------------------------------------------------
// ToggleCustomSecret()
//   Toggles the custom secret question input
// Arguments:
//	 select - the SecretQuestionSelect
// -------------------------------------------------------------------
//
function ToggleCustomSecret(select) {
	var customQ = document.getElementById("SecretQuestion_CustomSecretQuestion");
	if (select.value == "Other...") {
		RemoveCssClass(customQ, "hidden");
		AddCssClass(select, "greyed");
	} else {
		AddCssClass(customQ, "hidden");
		RemoveCssClass(select, "greyed");
		customQ.value = "";
	}
}


// -------------------------------------------------------------------
// OverlayProgressDiv()
//   Puts a progress meter above a selected element, with the parent
//	 element's dimensions. 
// Arguments:
//	 progressDiv - the element to posistion
//	 parent	- the element to reference
// -------------------------------------------------------------------
//
function OverlayProgressDiv(progressDiv, parent) {
	var x, y, w, h;

	x = GetElementsLeftPosition(parent);
	y = GetElementsTopPosition(parent);
	w = parent.offsetWidth;
	h = parent.offsetHeight;
	
	//alert(x + ", " + y  + ", " + w  + ", " + h);
	
	progressDiv.style.display	= "block";
	progressDiv.style.height	= h + "px";
	progressDiv.style.width	= w + "px";
	progressDiv.style.top		= y + "px ";
	progressDiv.style.left		= x + "px";
	progressDiv.style.position = "absolute";
}


// -------------------------------------------------------------------
// ReplaceAll()
//   Puts a progress meter above a selected element, with the parent
// Arguments:
//	 progressDiv - the element to posistion
//	 parent	- the element to reference
// -------------------------------------------------------------------
//
String.prototype.ReplaceAll = function(needle, replacement)
{
	var haystack	 = this;
	var indexOfMatch = this.indexOf(needle);
	while (indexOfMatch != -1){
		haystack	 = haystack.replace(needle, replacement)
		indexOfMatch = haystack.indexOf(needle);
	}
	return haystack;
}


// -------------------------------------------------------------------
// _DEBUG()
//   Allows you to make trace statements in js
// Arguments:
//	 message: printf, baby, printf. 
// -------------------------------------------------------------------
//
function _DEBUG(message) {
	if (gDubug) {
		var dbgBox;
		var output = _DEBUGFormatMessage(message);
		if (!document.getElementById("debugOutput")) {
			if (!document.getElementById("dbg")) {
				gDebugMsg = output + gDebugMsg;
			} else {
				dbgBox = document.createElement("textarea");
				dbgBox.setAttribute("id", "debugOutput");
				//dbgBox.setAttribute("style", "width: 700px; height:200px;");
				dbgBox.style.height = "150px";
				dbgBox.style.width  = "700px";
				dbgBox.value = _DEBUGFormatMessage("Creating debug output window") + gDebugMsg;
				document.getElementById('dbg').appendChild(dbgBox);
			}
		} else {
			dbgBox = document.getElementById("debugOutput");
			dbgBox.value = output + dbgBox.value;
		}
	}
}

// -------------------------------------------------------------------
// _DEBUGFormatMessage()
//   formats the debug statements. 
// Arguments:
//	 message: printf, baby, printf. 
// -------------------------------------------------------------------
//
function _DEBUGFormatMessage(message) {
	if (gStartTime == null) {gStartTime = new Date();}
	var now			= new Date();
	var dateDiff	= now - gStartTime;
	var output		= "" + now.getHours() + ":" + now.getMinutes() + ":"	+ now.getSeconds() + " " + now.getMilliseconds() + " : " + message + " (" + dateDiff + "ms)\n";
	return output;
}


// -------------------------------------------------------------------
// doesElementIdExist()
//   Checks if an element with an id (passed in as arg) exists in the document. 
// Arguments:
//	 element: string name of the id you wish to check if it exists
// Returns:
//   Boolean 
// -------------------------------------------------------------------
//
function doesElementIdExist(elementName)
{
    if (document.getElementById)
    {
        if(document.getElementById(elementName) != undefined)
            return true
    }
    else if (document.all) 
    {
        if (document.all[elementName] != undefined) 
            return true
    }
    else if (document.layers) 
    {
        if (document.layers[elementName] != undefined)
            return true
    }
    
    return false;
}

// -------------------------------------------------------------------
// EmailAddressTrim(emailString)
// This function looks for an @ sign and grabs everything to the left of it
// 
// Arguments:
//	 emailString: string of the email address you would like to trim
// Returns:
//   string: trimmed email 
// -------------------------------------------------------------------
//

function EmailAddressTrim(emailString)
{
    //Set up the variable to hold the split apart email address
    //
    var bits;
    
    //Check for an empty string. If we find it return
    //
    if (emailString.value == null || emailString.value.length == 0)
    {
        return false;
    }
    
    //ok now attempt to split the string on the @ symbol
    //
    if (emailString.value.indexOf("@") != -1)
    {
        //Split the string on the @ symbol. We want to keep everything to the left of the @ symbol
        //
        bits = emailString.value.split("@");
        
        //Set the emailString to the first index of bits
        //
        emailString.value = bits[0];
    }
    else
    {
        //Ok no @ symbol found (so no email address) so do nothing
        //
        return false;
    }
}

_DEBUG("Setting gBasePath as: " + gBasePath);
_DEBUG("Completed loading PrestoCommon.js...");

//This is a method to walk the dom of the page it is called on an turn the visibilty of the selection boxes off
//
function selectionSwap(inOrOut){

    //lets first walk thru the DOM and set the visibilty of all of the selection boxes to hidden
    //
    var selectArray = document.getElementsByTagName("select");
    
    //This is to target IE 6 and its inablity to handle z-indexes and layers
    //
    if (window.external && (typeof window.XMLHttpRequest == "undefined")) {

        if(inOrOut == "outSwap")
        {
            for(var i = 0; i < selectArray.length; i++)
            {
                selectArray[i].style.visibility ="hidden";
            }
        }
        else
        {
             for(var i = 0; i < selectArray.length; i++)
            {
                selectArray[i].style.visibility ="visible";
            }
        }
    }
}
