/*******************************************************************
 * Utility.js
 * This page contains generic client-side scripting functions. Do
 * not add functions to this page unless they can be re-used in
 * any website.
 ******************************************************************/

//==========
// Variables
//==========
/*

/^
\w+									User name
(?:
	[-.]\w+
)*
@
(?:									Host (mail server)
	(?:									Domain name
		(?:									Sub-domain (optional)
			[a-zA-Z][a-zA-Z0-9]*
			(?:
				-[a-zA-Z0-9]+
			)*
			\.
		)?
		[a-zA-Z][a-zA-Z0-9]*							Label
		(?:
			-[a-zA-Z0-9]+
		)*
		\.[a-zA-Z]{2,4}						Top-level domain
	)
	|
	(?:								IP address enclosed in sqaure brackets
		\[
		(?:
			[12]?[012345]?\d\.
		){3}
		[12]?[012345]?\d\]
	)
	|
	(?:								IP address w/o square brackets
		(?:
			[12]?[012345]?\d\.
		){3}
		[12]?[012345]?\d
	)
)
$/

*/
// var EmailRegExp = /^\w+(?:[-.]\w+)*@(?:(?:(?:[a-zA-Z][a-zA-Z0-9]*(?:-[a-zA-Z0-9]+)*\.)?[a-zA-Z][a-zA-Z0-9]*(?:-[a-zA-Z0-9]+)*\.[a-zA-Z]{2,4})|(?:\[(?:[12]?[012345]?\d\.){3}[12]?[012345]?\d\])|(?:(?:[12]?[012345]?\d\.){3}[12]?[012345]?\d))$/;
/* use version w/o non-capturing groups for Mac IE */
var EmailRegExp = /^\w+([-.]\w+)*@((([a-zA-Z][a-zA-Z0-9]*(-[a-zA-Z0-9]+)*\.)?[a-zA-Z][a-zA-Z0-9]*(-[a-zA-Z0-9]+)*\.[a-zA-Z]{2,4})|(\[([12]?[012345]?\d\.){3}[12]?[012345]?\d\])|(([12]?[012345]?\d\.){3}[12]?[012345]?\d))$/;

/*
The following is from RFC-1035:
<domain> ::= <subdomain> | " "
<subdomain> ::= <label> | <subdomain> "." <label>
<label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
<ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
<let-dig-hyp> ::= <let-dig> | "-"
<let-dig> ::= <letter> | <digit>
<letter> ::= any one of the 52 alphabetic characters A through Z in upper case and a through z in lower case
<digit> ::= any one of the ten digits 0 through 9


/^
(?:							Protocol declaration (optional)
	http\:\/\/
)?
(?:							Host
	(?:							Domain
		[a-zA-Z][a-zA-Z0-9]*
		(?:
			-[a-zA-Z0-9]+
		)*
		\.
	)?
	[a-zA-Z][a-zA-Z0-9]*
	(?:
		-[a-zA-Z0-9]+
	)*
	\.[a-zA-Z]{2,4}
	|						IP Address
	(?:
		[012]?[012345]?\d\.
	){3}
	[012]?[012345]?\d
)
(?:\/[\w.]+)*				optional path (allows decimal in folder name which is interchangable with file name w/ extension)
\/?							optional trailing slash
$/
*/

//var UrlRegExp = /^(?:http\:\/\/)?(?:(?:[a-zA-Z][a-zA-Z0-9]*(?:-[a-zA-Z0-9]+)*\.)?[a-zA-Z][a-zA-Z0-9]*(?:-[a-zA-Z0-9]+)*\.[a-zA-Z]{2,4}|(?:[012]?[012345]?\d\.){3}[012]?[012345]?\d)(?:\/[\w.]+)*\/?$/
// use w/o non-capturing groups for IE Mac
var UrlRegExp = /^(http\:\/\/)?(([a-zA-Z][a-zA-Z0-9]*(-[a-zA-Z0-9]+)*\.)?[a-zA-Z][a-zA-Z0-9]*(-[a-zA-Z0-9]+)*\.[a-zA-Z]{2,4}|([012]?[012345]?\d\.){3}[012]?[012345]?\d)(\/[\w.]+)*\/?$/
			
var PostalCodeRegExpUSA = /^\d{5}(-\d{4})?$/;
var PostalCodeRegExpCanada = /^[a-zA-Z]\d[a-zA-Z][- ]?\d[a-zA-Z]\d$/;
var PostalCodeRegExpArray = [PostalCodeRegExpUSA, PostalCodeRegExpCanada];

/*
 * For use with the validatePostalCode method
 */
var POSTAL_CODE_USA = 1;
var POSTAL_CODE_CANADA = 2;
var POSTAL_CODE_ALL = 255;

var DateRegExp = /^(0?[1-9]|1[012])\/(0?[1-9]|[12][0-9]|3[01])\/(19|20)[0-9]{2}$/;

//==========
// Functions
//==========

//================
// Popup Variables 
//================
var preloadFlag = false;
var popWin = null;  // Use this when referring to pop-up window
var winCount = 0;
var winName = "popWin";




function specs_callback(res)
{
  if(typeof(res) == 'object' && typeof(res.Tables) == 'object')
  {
    var html = [];
    
    for(var i=0; i<res.Tables[0].Rows.length; i++)
      html[html.length] = '<p>' + res.Tables[0].Rows[i].ColumnName + '</p>';
   }
}

function Querystring(qs) { // optionally pass a querystring to parse
	this.params = new Object()
	this.get=Querystring_get
	
	if (qs == null)
		qs=location.search.substring(1,location.search.length)

	if (qs.length == 0) return

// Turn <plus> back to <space>
// See: http://www.w3.org/TR/REC-html40/interact/forms.html#h-17.13.4.1
	qs = qs.replace(/\+/g, ' ')
	var args = qs.split('&') // parse out name/value pairs separated via &
	
// split out each name=value pair
	for (var i=0;i<args.length;i++) {
		var value;
		var pair = args[i].split('=')
		var name = unescape(pair[0])

		if (pair.length == 2)
			value = unescape(pair[1])
		else
			value = name
		
		this.params[name] = value
	}
}

function Querystring_get(key, default_) {
	// This silly looking line changes UNDEFINED to NULL
	if (default_ == null) default_ = null;
	
	var value=this.params[key]
	if (value==null) value=default_;
	
	return value
}




//+===============================================================+
//|Following functions are used to keep track of phone selections |
//+===============================================================+
var phoneArray = new Array()


function setCookie(name, value, expires, path, domain, secure) {
	var curCookie = name + "=" + escape(value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		((path) ? "; path=" + path : "") +
		((domain) ? "; domain=" + domain : "") +
		((secure) ? "; secure" : "");
	document.cookie = curCookie;
}
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 SelectAllPhones_Click()
{

	var pBool=new Boolean(0);
	var now = new Date();
	var phones = document.getElementById("phones-middle-col-wrapper").getElementsByTagName("input");

	setCookie('parray','',now,'','',false)


	for(cnt=0; cnt<phones.length; cnt++)
	{
		if(phones[cnt].type == "checkbox")
		{
			phones[cnt].checked = true
			phoneArray.push(phones[cnt].name)							
		}
	}

	setCookie('phonesSelected',phoneArray,'','','',false)

	/**
	var pBool=new Boolean(0);	
	var sStr = getCookie('parray');

	var phones = document.forms["phones"];

	if(sStr.length > 0)
	{

		phoneArray = sStr.split(",");
		
		for(cnt=0; cnt<phones.length; cnt++)
		{

			if((phones[cnt].type == "checkbox") &&  (phones[cnt].name.substring(0,5) != "check") )
			{							

				for(iIndex=0; iIndex<phoneArray.length; iIndex++ )
				{
					if(phoneArray[iIndex].toString() == phones[cnt].name)
					{
						phones[cnt].checked = true							
						pBool = true
						break
					}
					if(phoneArray.length == 0)
					{

						pBool = true
						break
					}
				}					
			}
			if( pBool == false)
			{
				if((phones[cnt].type == "checkbox") &&  (phones[cnt].name.substring(0,5) != "check") )
				{
					phones[cnt].checked = true
					phoneArray.push(phones[cnt].name)							
				}
			}
		}			
	}


	setCookie('phonesSelected',phoneArray,'','','',false)
	**/	
}

function ChangePhoneSelection(pcode)		
{


	var bBool=new Boolean(0)
	var i = 0;

	var tStr = getCookie('phonesSelected')

	if(tStr != null)
	{
		phoneArray = tStr.split(",")		

		for(iIndex=0; iIndex<phoneArray.length; iIndex++ )
		{
			if(phoneArray[iIndex].toString() == pcode)
			{
				phoneArray[iIndex] = null
				bBool = true
			}
		}		
	}

	if(bBool == false)
	{			
		phoneArray.push(pcode)
	}
	
	var cnt = 0;
	var tArray = new Array()
	for(iIndex=0; iIndex<phoneArray.length; iIndex++)
	{
		if(phoneArray[iIndex] != null)
		{

			tArray[cnt] = phoneArray[iIndex]
			cnt++
		}
	}

	setCookie('phonesSelected',tArray,'','','',false)
}
function Compare_Click()
{
	var pCodes = "pcodes="
	var cnt = 0;
	var tStr = getCookie('phonesSelected')

	if(tStr != null)
	{
		phoneArray = tStr.split(",")			
	}			
	for(iIndex=0; iIndex<phoneArray.length; iIndex++)
	{

		if( (phoneArray[iIndex] != ",") || (phoneArray[iIndex] != "null"))
		{
			pCodes += phoneArray[iIndex]
			if(iIndex < phoneArray.length-1)
			{
				pCodes += ","
			}
			cnt ++
		}
	}


	if(phoneArray.length < 2)
		alert("Please select more than 1 phone to compare")
	else
		window.location = "PhonesCompare.aspx?" + pCodes + "&cnt=" + cnt
}

function CompareDevices_Click()
{
	var pCodes = "pcodes="
	var cnt = 0;
	var tStr = getCookie('phonesSelected')

	if(tStr != null)
	{
		phoneArray = tStr.split(",")			
	}			
	for(iIndex=0; iIndex<phoneArray.length; iIndex++)
	{
		if( (phoneArray[iIndex] != ",") || (phoneArray[iIndex] != "null"))
		{
			pCodes += phoneArray[iIndex]
			if(iIndex < phoneArray.length-1)
			{
				pCodes += ","
			}
			cnt ++
		}
	}

	if(phoneArray.length < 2)
		alert("Please select more than 1 phone to compare")
	else
		window.location = "DeviceCompare.aspx?" + pCodes + "&cnt=" + cnt
}

function GlobalResetSelection()
{
	var phones = document.getElementById("phones-middle-col-wrapper").getElementsByTagName("input");

	for(cnt=0; cnt<phones.length; cnt++)
	{
		if(phones[cnt].type == "checkbox")
		{
			phones[cnt].checked = false
		}
	}

	setCookie('phonesSelected',"",'','','',false)	
	phoneArray = null
	tStr = null
}

function CheckSelection()
{
	var cnt = 0;
	var tStr;
	var nArr = new Array()
	var phones = document.forms["phones"];

	tStr = getCookie('phonesSelected')

	if( tStr != null)
	{
		var tArray = tStr.split(",")

		for(cnt=0; cnt<phones.length; cnt++)
		{
			if(phones[cnt].type == "checkbox")
			{
				nArr.push(phones[cnt].name);
			}
		}

		for(iIndex=0; iIndex<tArray.length; iIndex++)
		{
			if(tArray[iIndex] != null)
			{
				if(tArray[iIndex].toString() != ",")
				{
					for(iTmp=0; iTmp<nArr.length; iTmp++)
					{
						if(nArr[iTmp] == tArray[iIndex])
						{

							phones[tArray[iIndex]].checked = true
						}
					}
				}

			}
		}
	}		
}

//+==================================+
//| End of phone selection functions |
//+==================================+

function openPopWin(winURL, winWidth, winHeight, winFeatures, winLeft, winTop){
 var d_winLeft = 20;  // Default, pixels from screen left to window left
 var d_winTop = 20;   // Default, pixels from screen top to window top
 
 winName = "popWin" + winCount++; // Unique name for each pop-up window
 
 closePopWin();      // Close any previously opened pop-up window   
              
 if (openPopWin.arguments.length >= 4)  // Any additional features? 
  winFeatures = "," + winFeatures;
 
 else 
  winFeatures = "" 
 
 if (openPopWin.arguments.length == 6)  // Location specified
  winFeatures += getLocation(winWidth, winHeight, winLeft, winTop);
 
 else
  winFeatures += getLocation(winWidth, winHeight, d_winLeft, d_winTop);
  popWin = window.open(winURL, winName, "width=" + winWidth + ",height=" + winHeight + winFeatures);
 }
 
function closePopWin(){    // close pop-up window if it is open 
 // Do not close if early IE
 if ((navigator.appName != "Microsoft Internet Explorer") || (parseInt(navigator.appVersion) >=4)) { 
  if(popWin != null) {
   if(!popWin.closed) {
    popWin.close();
   }
  }
 }
}
 
function getLocation(winWidth, winHeight, winLeft, winTop){
 var winLocation = ""
 
 if (winLeft < 0)
  winLeft = screen.width - winWidth + winLeft;
 if (winTop < 0)
  winTop = screen.height - winHeight + winTop;
 if (winTop == "cen")
  winTop = (screen.height - winHeight)/2 - 20;
 if (winLeft == "cen")
  winLeft = (screen.width - winWidth)/2;
 if (winLeft>0 && winTop>0)
  winLocation =  ",screenX=" + winLeft + ",left=" + winLeft + ",screenY=" + winTop + ",top=" + winTop;
 else
  winLocation = "";
 return winLocation;
}

function clearFormField(field) {
	if (field.tagName) {
		switch (field.tagName) {
			case "SELECT":
				field.selectedIndex = -1;
				break;
			case "OPTION":
				if (field.parentElement) {
					field.parentElement.selectedIndex = -1;
				}
				break;
			case "INPUT":
				switch (field.type) {
					case "text":
					case "password":
						field.value = "";
						break;
					case "checkbox":
					case "radio":
						field.checked = false;
						break;
				}
				break;
		}
	}
	else {
		if (field.value!=null) {
			switch (field.type) {
				case "text":
				case "password":
					field.value = "";
					break;
				case "checkbox":
				case "radio":
					field.checked = false;
					break;
			}
		}
		else {
			field.selectedIndex = -1;
		}
	}
}

function clearFormFields(form) {
	for (var i=0; i<form.elements.length; i++) {
		var e = form.elements[i];
		clearFormField(e);
		e = null;
	}
}

function confirmDelete(type, item) {
	var s;
	if (item==null) {
		s = "Are you sure you want to delete the selected " + type + "?";
	}
	else {
		s = "You are about to delete the following " + type + ":\n\n" + 
			item + "\n\n" + 
			"Do you want to continue?";
	}
	return confirm(s);
}

function getOffset(property, elem) {
	if (elem.offsetParent) {
		return elem[property] + getOffset(property, elem.offsetParent);
	}
	else {
		return elem[property];
	}
}

function getPropertiesHTML(obj, recursive) {
	var s = "<ol>";
	if (recursive==null) {
		recursive = false;
	}
	for (var prop in obj) {
		if ((typeof(obj[prop])=="object") && (recursive==true)) {
			s += "<li>" + prop + "=" + getPropertiesHTML(obj[prop], false) + "</li>";
		}
		else {
			s += "<li>" + prop + "=" + obj[prop] + "</li>";
		}
	}
	s += "</ol>";
	return s;
}

function getPropertiesText(obj, recursive) {
	var s = "";
	if (recursive==null) {
		recursive = false;
	}
	for (var prop in obj) {
		if ((typeof(obj[prop])=="object") && (recursive==true)) {
			s += "\n" + prop + "=" + getPropertiesHTML(obj[prop], false);
		}
		else {
			s += "\n" + prop + "=" + obj[prop];
		}
	}
	return s;
}

function getSelectedCheckboxValues(ctl) {
	if (ctl==null) {
		return null;
	}
	var values = new Array();
	if (ctl.length==null) {
		if (ctl.checked) {
			values.push(ctl.value);
		}
	}
	else {
		for (var i=0; i<ctl.length; i++) {
			if (ctl[i].checked) {
				values.push(ctl[i].value);
			}
		}
	}
	return values;
}

function getSelectedOptionValue(ctl) {
	if (ctl==null) {
		return null;
	}
	if (ctl.length==null) {
		if (ctl.checked) {
			return ctl.value;
		}
	}
	else {
		for (var i=0; i<ctl.length; i++) {
			if (ctl[i].checked) {
				return ctl[i].value;
			}
		}
	}
	return null;
}

function selectListItem(list, value) {
	for (var i=0; i<list.options.length; i++) {
		if (list.options[i].value==value) {
			list.selectedIndex = i;
			return;
		}
	}
	list.selectedIndex = -1;
}

function setImageSource(imgName, source) {
	var img = document.images[imgName];
	if (img) {
		img.src = source;
	}
}

function showProperties(obj, recursive) {
	var features = "scrollbars=yes," +
			"resizable=yes," + 
			"width=400," + 
			"height=400";
	var w = window.open("", "Utility", features, null);
	w.document.write("<html><head><title>Object Properties</title></head><body>" + 
			getPropertiesHTML(obj, recursive) + 
			"</body></html>");
}

function stripPhone(number) {
	var s = "",mask="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", t;
	for (var i=0; i<number.length; i++) {
		t = number.substr(i,1).toUpperCase();
		if (mask.indexOf(t)!=-1) {
			s += t;
		}
	}
	return s;
}

function validateDate(date) {
	return DateRegExp.test(date);
}

function validateEmail(email) {
	return EmailRegExp.test(email);
}

/*
 * context is a bit mask specifying which country's postal code
 * rules to apply. Use the variables defined at the top of
 * this page
 */
function validatePostalCode(postalCode, context) {
	for (var i=0; i<PostalCodeRegExpArray.length; i++) {
		if (context & (Math.pow(2, i))) {
			if (PostalCodeRegExpArray[i].test(postalCode)) {
				return true;
			}
		}
	}
	return false;
}

function validateUrl(url) {
	return UrlRegExp.test(url);
}


function showImage(image, width, height, desc) {

	var url = "/ShowImage.aspx?width=" + width + "&height=" + height + "&image=" + image + "&desc=" + escape(desc);
	var newheight = parseInt(height) + 30;
	var snewheight = newheight.toString();
	
openPopWin(url, width, snewheight, '','cen','cen');		
		
}

//=====
// Body
//=====

// The following code block works with the BrowserInfo Backend function
var isWin = (window.navigator.platform.indexOf("Win")!=-1)
var isMac = (window.navigator.platform.indexOf("Mac")!=-1)
if (document.cookie.indexOf("browser=")==-1) {
	document.cookie = "browser=" + 
		"layers=" + (document.layers!=null) +
		"&getElementById=" + (document.getElementById!=null) +
		"&all=" + (document.all!=null) + 
		"&isMac=" + isMac + 
		"&isWin=" + isWin;
	if (document.layers) {
		if (isMac) {
			window.location.href = "/Home.asp";
		}
		else {
			window.setTimeout("window.location.reload();", 1000);
		}
	}
}

