// TODO - PRI - create on error handlers.  Build a logging/postback utility that sends error information back to the web site
// 
// This is the base iTalkies script file - it contains helper functions that are use in many pages

var ie = (window.navigator.appName == "Microsoft Internet Explorer");
var moz = (window.navigator.appName == "Mozilla" || window.navigator.appName == "Netscape");
var safari = ((navigator.userAgent.toLowerCase().indexOf("safari") > -1) || (navigator.userAgent.toLowerCase().indexOf("konqueror") > -1));
var opera = (navigator.userAgent.toLowerCase().indexOf("opera") > -1);

var redirector = "";

function iTFindAll (root, idToFind) 
{  
	var nodes = root.childNodes;
	for (var i = 0; i < nodes.length; i++)
	{
		if (nodes[i].id == idToFind) 
		{
			return nodes[i];
		}
		else
		{
			if (nodes[i].hasChildNodes())
			{
				var tempNode = iTFindAll (nodes[i], idToFind);
				if (tempNode != null) return tempNode;
			}
		}
	}
	return null;
}

function iTFindFrames (root, idToFind)
{
	var iframes = root.getElementsByTagName ("iframe");
	var temp;
	for (var i = 0; i < iframes.length; i++)
	{
		if (iframes[i].id == idToFind) return iframes[i];
	}
	
	return null;
}

function BuildNodesCollection (element, idToFind)
{
	var retNodes = new Array();
	var nodes = element.childNodes;
	for (var i = 0; i < nodes.length; i++)
	{
		// if this node has the id we were looking for push it into the array
		if (nodes[i].id == idToFind) 
		{
			retNodes.push(nodes[i]);
		}
		// Now recurse through any children to see if they need to be added
		if (nodes[i].hasChildNodes())
		{
			var tempNode = BuildNodesCollection (nodes[i], idToFind);
			if (tempNode != null)
			{
				retNodes = retNodes.concat (tempNode);
				delete tempNode;
			}
		}
	}
	
	if (retNodes.length == 0)
	{
		return null;
	}
	else
	{
		return retNodes;
	}
}
	
function iTFindAllDoc (root, idToFind)
{
	return BuildNodesCollection(root.body, idToFind);
}
	
var imageLocation = null;

var hasUserCookie = false;
if (window.location.protocol.toLowerCase() == "https:")
{
	imageLocation = iTalkiesGetSmartHref (true, "/images");
	if (window.document.cookie.indexOf ("UserID=") > -1)
		hasUserCookie = true;
}
else
{
	imageLocation = iTalkiesGetSmartHref (false, "/images");
}


function iTalkiesCancelBubble (e)
{
	if (ie) window.event.cancelBubble = true;
	if (moz) e.stopPropagation();
}

function iTalkiesCumulativeParentOffset (element)
{
	var ret = new Array (2);
//	var ret = new Array (3);
	var tempRet;
	
	if ((element != null) && (element.offsetParent != null))
	{
		tempRet = iTalkiesCumulativeParentOffset (element.offsetParent);
		ret[0] = element.offsetLeft + tempRet[0];
		ret[1] = element.offsetTop + tempRet[1];
//		ret[2] = tempRet[2] + " " + element.tagName + "(Left=" + element.offsetLeft + ", Top=" + element.offsetTop + ")";
		delete tempRet;
	}
	else if (element != null)
	{
		ret[0] = element.offsetLeft;
		ret[1] = element.offsetTop;
//		ret[2] = element.tagName + "(Left=" + element.offsetLeft + ", Top=" + element.offsetTop + ")";
	}
	else
	{
		ret[0] = 0;
		ret[1] = 0;
//		ret[2] = "";
	}
	
	return ret;
}

function iTalkiesOffsetElement (elementToOffset, elementOffsetFrom, xdistance, ydistance)
{
	var cumlOffset = iTalkiesCumulativeParentOffset(elementOffsetFrom.offsetParent);
	
//	alert ("Left = " + elementOffsetFrom.style.left);
//	alert ("Top = " + elementOffsetFrom.style.top);
//	alert ("Left = " + elementOffsetFrom.offsetLeft);
//	alert ("Top = " + elementOffsetFrom.offsetTop);
//	alert ("Left Cuml = " + cumlOffset[0]);
//	alert ("Top Cuml = " + cumlOffset[1]);

	elementToOffset.style.left = cumlOffset[0] + elementOffsetFrom.offsetLeft + xdistance;
	elementToOffset.style.top = cumlOffset[1] + elementOffsetFrom.offsetTop + ydistance;
//	alert (cumlOffset[2]);
}

function iTalkiesUnderlineOnMouseOver (srcSpanElement)
{
	srcSpanElement.style.textDecoration = "underline";
}

function iTalkiesNoUnderlineOnMouseOut (srcSpanElement)
{
	srcSpanElement.style.textDecoration = "none";
}

function iTalkiesClickableRowOnMouseOver(srcElement)
{
	srcElement.style.backgroundColor = "#e3eeaa";
}

function iTalkiesClickableRowOnMouseOut(srcElement)
{
	srcElement.style.backgroundColor = "";
}

function iTalkiesClickableImageMouseOver(srcImageElement)
{
}

function iTalkiesClickabelImageMouseOut(srcImageElement)
{
}

function iTalkiesSelectableElementOnMouseOver (srcElement)
{
	if (srcElement.selected == null)
	{
		srcElement.style.color = "#993333";
	}
	else
	{
		srcElement.style.color = "#993333";
	}
	srcElement.style.cursor = "pointer";
}

function iTalkiesSelectableElementOnMouseOut (srcElement)
{
	if (srcElement.selected == null)
	{
		srcElement.style.color = "#666666";
	}
	else
	{
		srcElement.style.color = "#993333";
	}	
	srcElement.style.cursor = "default";
}

function iTalkiesSelectableElementOnClick (srcElement)
{
	srcElement.selected = true;
	srcElement.style.color = "#ffffff";
}

function iTalkiesClearAllSelectableElements (srcElement, tag)
{
	var collAnchors = srcElement.getElementsByTagName(tag);
	
	if (collAnchors != null)
	{
		if (collAnchors.length != null)
		{
			for (var i=0; i < collAnchors.length; i++)
			{
				collAnchors[i].style.color = "white";
				collAnchors[i].selected = null;
			}
		}
		else
		{
			collAnchors.style.color = "white";
			collAnchors.selected = null;
		}
	}
}

function iTalkiesClearAllAlphaNavSelectableElements (srcElement, tag)
{
	var collAnchors = srcElement.getElementsByTagName(tag);
	
	if (collAnchors != null)
	{
		if (collAnchors.length != null)
		{
			for (var i=0; i < collAnchors.length; i++)
			{
				collAnchors[i].style.color = "#666666";
				collAnchors[i].selected = null;
			}
		}
		else
		{
			collAnchors.style.color = "#666666";
			collAnchors.selected = null;
		}
	}
}

function iTalkiesSaveValueOnKeyDown (e)
{
	var srcElement;
	var normalizedEvent;
	
	if (ie)
	{
		srcElement = event.srcElement;
		normalizedEvent = event;
	}
	if (moz) 
	{
		srcElement = e.target;
		normalizedEvent = e;
	}

	// let all keys other than alphanumeric keys pass thru
	if (normalizedEvent.keyCode < 47) return;
	if ((normalizedEvent.keyCode >= 91) && (normalizedEvent.keyCode <= 93)) return;
	if ((normalizedEvent.keyCode >= 112) && (normalizedEvent.keyCode <= 165)) return;
	if (normalizedEvent.keyCode >= 246) return;

	srcElement.savedValue = srcElement.value;
}

function iTalkiesOnBackspaceKeydown(e)
{
	var srcElement;
	var normalizedEvent;
	
	if (ie)
	{
		srcElement = event.srcElement;
		normalizedEvent = event;
	}
	if (moz) 
	{
		srcElement = e.target;
		normalizedEvent = e;
	}

	if (normalizedEvent.keyCode == 8)
	{
		if (srcElement.value.length == 0)
		{
			var targetElementId;
			if (srcElement.id == "CreditCardInfo_CreditCardNumberBlock4") 
				targetElementId = "CreditCardInfo_CreditCardNumberBlock3";
			else if (srcElement.id == "CreditCardInfo_CreditCardNumberBlock3") 
				targetElementId = "CreditCardInfo_CreditCardNumberBlock2";
			else if (srcElement.id == "CreditCardInfo_CreditCardNumberBlock2") 
				targetElementId = "CreditCardInfo_CreditCardNumberBlock1";
			else if (srcElement.id == "CreditCardInfo_BillingAddress_PostalCodeOptionalPart") 
				targetElementId = "CreditCardInfo_BillingAddress_PostalCode";
			else if (srcElement.id == "UserInformation_TelNumLastFour") 
				targetElementId = "UserInformation_TelNumFirstThree";
			else if (srcElement.id == "UserInformation_TelNumFirstThree") 
				targetElementId = "UserInformation_TelNumAreaCode";
			else if (srcElement.id == "UserInformation_ShippingAddress_PostalCodeOptionalPart") 
				targetElementId = "UserInformation_ShippingAddress_PostalCode";
			else
				return;
				
			var element = window.document.getElementById (targetElementId);
			element.focus();
			if (ie)
			{
				var textRange = element.createTextRange();
				textRange.move ("character", element.value.length);
				textRange.select();
			}
		}
	}

	iTalkiesSaveValueOnKeyDown (e);
}

function iTalkiesIssueMissTypedWarning (srcElement)
{
	var savedColor = srcElement.style.backgroundColor;
	if (srcElement.iTalkiesOriginalColor == null)
	{
		srcElement.iTalkiesOriginalColor = savedColor;
	}
	
	if (savedColor.toLowerCase() == "red")
	{
		srcElement.style.backgroundColor = "#ffffa0";
	}
	else
	{
		srcElement.style.backgroundColor = "red";
	}
		
	var timerID = window.setTimeout ("iTalkiesUndoMissTypedWarning(\"" + srcElement.id + "\")", 50);
}

function iTalkiesUndoMissTypedWarning (srcElementId)
{
	var srcElement = window.document.getElementById (srcElementId)
	srcElement.style.backgroundColor = srcElement.iTalkiesOriginalColor;
}

function iTalkiesValidationResult (isValid, errorMessage)
{
	this.isValid = isValid;
	this.errorMessage = errorMessage;
	this.toString = iTalkiesValidationResultToString;
}

function iTalkiesValidationResultToString()
{
	return "IsValid: " + this.isValid + "\nErrorMessage :" + this.errorMessage + "\n";
}

function iTalkiesDisableAllInputButtonsInDocument ()
{
	var inputColl = window.document.getElementsByTagName ("input");
	
	if (inputColl != null)
	{
		if (inputColl.length != null)
		{
			for (var i=0; i < inputColl.length; i++)
			{
				if ((inputColl[i].type.toLowerCase() == "submit") ||
					(inputColl[i].type.toLowerCase() == "button"))
				{
					inputColl[i].disabled = true;
				}
			}
		}
		else
		{
			if ((inputColl.type.toLowerCase() == "submit") ||
				(inputColl.type.toLowerCase() == "button"))
			{
				inputColl.disabled = true;
			}
		}
	}
}

function iTalkiesSetSubmitAction (srcElement)
{
	// when the buttons are disabled the browser does not send their name/value
	// pairs in the post request.  Thus simulate sending the name/value pair
	// of the clicked button by setting the name/value pair of the action hidden input
	// control
	window.document.getElementById ("Action").name = srcElement.getAttribute("name");
	window.document.getElementById ("Action").setAttribute("value", srcElement.getAttribute("value"));
}

function iTalkiesGetSmartHref (secure, urlPostfix)
{
	var protocol = "http://";
	if (secure == true)
	{
		protocol = "https://";
	}
	
	if (window.location.pathname.substr (0, "/iTalkiesAdmin/".length).toLowerCase() == "/italkiesadmin/")
	{
		return protocol + window.location.host + "/iTalkiesAdmin" + urlPostfix;
	}
	else if (window.location.pathname.substr (0, "/iTalkies/".length).toLowerCase() == "/italkies/")
	{
		return protocol + window.location.host + "/iTalkies" + urlPostfix;
	}
	else
	{
		if (window.location.host.toLowerCase() == "italkies.com")
		{
			return protocol + "www.italkies.com" + urlPostfix;
		}
		return protocol + window.location.host + urlPostfix;
	}
}


function getPathFromFilename (path)
{
	var indexFilenameSeperator = path.lastIndexOf ('/');
	if (indexFilenameSeperator != -1)
		return path.substr (0, indexFilenameSeperator);
	else
		return "";
}

function getImageLocationRedirector()
{
	var tempPath = window.location.pathname.toLowerCase();
	if (tempPath.lastIndexOf ('/secure/') == -1)
	{
		// not found
		return "";
	}
	else
	{
		// found secure
		return "../";
	}
}

function iTalkiesOnClickGotoTable(page)
{
	window.location = page;
}

function iTalkiesOnClickGotoCreateAccount(srcElement)
{
	window.parent.document.getElementById("SignupButton").click();
}

function iTalkiesParentGotoPage(page)
{
	window.parent.location = page;
	if (ie) window.event.returnValue = false;
	if (moz) return false;
}

function iTalkiesTrim(str)
{
	var tempValue = str;
	var re = /^\s*/;
	tempValue = tempValue.replace (re, "");
	re = /\s*$/;
	tempValue = tempValue.replace (re, "");
	return tempValue;
}

function iTalkiesGetQueryVariableValue (varName)
{
	var query = window.location.search;
	var re = new RegExp (varName + "=", "i");
	var matchResult = query.match(re);
	if (matchResult != null)
	{
		var querySubstring = query.substr (matchResult.lastIndex);
		re = /&|#/;
		matchResult = querySubstring.match (re);
		if (matchResult != null)
		{
			return querySubstring.substr (0, matchResult.index);
		}
		else
		{
			return querySubstring
		}
	}
	else
	{
		return null;
	}
}