/*=======================================================================================
    NewHomeCombined.js
    
    This file is the concatenation of NewHome.js, CookieHelper.js and dfajax.js
    It is used by the HomeRedesign2.xslt template to reduce the number of HTTP gets 
    generated by the Comcast home page.
========================================================================================*/


/*=======================================================================================
	NewHome.js
========================================================================================*/

// Pre fetch the images needed by the menu
var imgBase = "/images/newhome/menu/";
FetchImage(imgBase + "DropShadowBottom.png");
FetchImage(imgBase + "DropShadowMiddle.png");
FetchImage(imgBase + "DropShadowTop.png");
FetchImage(imgBase + "HoverBottomBg.gif");
FetchImage(imgBase + "HoverTopBg.gif");
FetchImage(imgBase + "BlueBottomBg.gif");
FetchImage(imgBase + "BlueTopBg.gif");
FetchImage(imgBase + "GreenBottomBg.gif");
FetchImage(imgBase + "GreenTopBg.gif");
FetchImage(imgBase + "OrangeTopBg.gif");
FetchImage(imgBase + "OrangeBottomBg.gif");
FetchImage(imgBase + "PurpleTopBg.gif");
FetchImage(imgBase + "PurpleBottomBg.gif");
FetchImage(imgBase + "RedTopBg.gif");
FetchImage(imgBase + "RedBottomBg.gif");
FetchImage(window.location.protocol + "//www.comcast.com/images/dot.gif");

function FetchImage(src)
{
	var img = new Image();
	img.src = src;
}


function InitLogInForm()
{
	var currentSession = GetCookie("Session", "Hash");
	if (currentSession && currentSession != '')
	{
		document.getElementById("SignIn").style.display = "none";
		document.getElementById("SignOut").style.display = "block";
	    makeRequest('/UserServices/Membership/MembershipAjaxService.asmx/GetUsersName?sessionHash='+ currentSession,'loggedInUser', fixupNotLink)
	}
	else
	{
		document.getElementById("SignOut").style.display = "none";
		document.getElementById("SignIn").style.display = "block";
    }
}

function fixupNotLink()
{
//	var loggedInUser = document.getElementById("loggedInUser");
//	var notUser = document.getElementById("notUser");
//	notUser.innerHTML = "Not " + loggedInUser.innerHTML + "?";
}

function InitLocalizedData()
{
	populateLocalizationHeader()
	
	if(isMacintosh())
	{
		
		if(isSafari())
		{
			setInterval(redrawSafari, 10);
			document.getElementById("LocalizationContent").style.display = "none";
			document.getElementById("SafariContent").style.display = "block";
		}
		else
		{
			setInterval(redrawFirefox, 40);
		}
		return;
	}
	
	var locCookie = getCookieVal("Serviceability");
	var streetCookie = false;
	var aptCookie = false;
	if(locCookie.length == 0)
	{
		locCookie = getCookieVal("PermLocalization");
		streetCookie = GetCookie("PermLocalization", "StreetAddress");
		aptCookie = GetCookie("PermLocalization", "AptNum");
	}else{
		streetCookie = GetCookie("Serviceability", "StreetAddress");
		aptCookie = GetCookie("Serviceability", "AptNumber");
	}
    if(locCookie.length > 0)
    {
		if(get5DigitZip() != "")
		{
			// populate localization form
			var streetAddress = document.getElementById("StreetName");
			var aptNum = document.getElementById("AptNumber");
			var zipCode = document.getElementById("Zip");
						
			zipCode.value = get5DigitZip();
			if(streetCookie != false)
				streetAddress.value = streetCookie.replace(/\+/g, ' ');
			if(aptCookie != false)
				aptNum.value = aptCookie;
				
			var notLocalizedContent = document.getElementById("NotLocalized");
			var localizedContent = document.getElementById("LocalizedContent");
			notLocalizedContent.style.display = "none";
			localizedContent.style.display = "block";
        }
    }
}

function populateLocalizationHeader()
{
	var locCookie = getCookieVal("Serviceability");
    if(locCookie.length > 0)
    {
		if(GetCookie("Serviceability","Zip") != false)
		{
			var locHeader = document.getElementById("LocationData");
			locHeader.style.display = "inline";
			var zipHeader = document.getElementById("zipInfo");
			zipHeader.innerHTML = get5DigitZip();
		}
		var ResetLink = document.getElementById("ResetLink");
        ResetLink.style.display = "inline";
	}
}

/*****NEED THESE FOR TRIM FUNCTIONS******/	
String.prototype.trim = trim;

/*
@func String Object | trim | Trims leading and trailing white space from string. Uses prototype definition  "String.prototype.trim = trim;".
@rdesc Returns Copy of string with leading and trailing whitespace stripped off.
*/

function trim() {
	
	return this.replace(/^\s+/,'').replace(/\s+$/,'');
}

function overItem(evt)
{	
	evt = (evt) ? evt : ((window.event) ? window.event : null);
	
	var targetElt = this;
	
	var oLink = targetElt.getElementsByTagName("a")[0];
	if( oLink && oLink.getAttribute("index") != null)
	{
		var index = oLink.getAttribute("index")
		
		// Create child lists if needed
		if(index < aMenu.length && targetElt.getElementsByTagName("ul").length == 0)
		{
			InsertChildren(targetElt, index);			
		}
	}
	
	if (targetElt.parentNode.id == "Menu")
	{
		// the shim is only needed in mac browsers.  It causes issues in netscape 7.2 for pc
		if(isMacintosh() && this.getElementsByTagName("ul").length > 0)
		{
			var iframe = this.getElementsByTagName("iframe")[0];
			if (iframe) 
			{
				//iframe.style.visibility = "visible";
				iframe.style.display = "block";
			}
			else
			{	
				iframe = document.createElement("iframe");
				iframe.setAttribute("src", window.location.protocol + "//www.comcast.com/images/dot.gif");
				iframe.setAttribute("scrolling", "no");
				iframe.setAttribute("frameborder", "0");
				iframe.style.zIndex="0";
				iframe.style.borderWidth="0";
				if(isSafari())
				{
					iframe.style.opacity = "0.0";
				}

				var firstC = this.firstChild;
				while(firstC.nodeName=="#text" && firstC.nextSibling != null)
					firstC = firstC.nextSibling;
				if (firstC.nodeName=="#text")
					firstC = null;
				
				if (firstC != null && firstC.nodeName.toUpperCase() == "A") 
				{
					var ul = this.getElementsByTagName("ul")[0].childNodes.length - 1; 
					iframe.width = 234
					iframe.height = MENU_HEIGHT * ul + 20; //+MENU_PADDING;
				}
				else
				{
					iframe.width = 0;
					iframe.height = 0;
				}
				if (MENU_TOP_MARGIN > 0)
					iframe.style.top = MENU_TOP_MARGIN + "px";
				iframe.style.left = "113px";
				iframe.style.position = "absolute";
				this.appendChild(iframe);
			}
		}
	}
	
	// IE hack for rollover state
	if(document.all && document.getElementById)
	{
		targetElt.className+=" sfhover";
	}
	setSelectedTabCookie("&lid=//Shop//Digital Cable with On Demand");
	setSelectedTabCookie("&lid=//Shop//Comcast Bundles");
	setSelectedTabCookie("&lid=//Shop//High-Speed Internet ");
	if(menuIsIE)
		setSelectedTabCookie("&lid=//Shop//Comcast Digital Voice%C2%AE");
	else
		setSelectedTabCookie(unescape("&lid=//Shop//Comcast Digital Voice%AE"));
	
}
function setSelectedTabCookie(name)
{
  	var x=document.getElementsByName(name);
	if(x.length > 0) {
		if(menuIsIE)
			x[0].onclick = new function() {SetCookie("BuyFlow", "SelectedTab", "", false, true);};
		else
			x[0].setAttribute("onclick", "SetCookie(\"BuyFlow\", \"SelectedTab\", \"\", false, true);");
	}		 
}

function getLeftRelBody(item) 
{
	if (item.parentNode.tagName == "body")
		return document.body.offsetLeft;
	return item.offsetLeft + getLeftRelbody(item.parentNode);
}

function getTopRelBody(item) 
{
	if (item.parentNode.tagName == "body")
		return document.body.offsetTop;
	return item.offsetTop + getTopRelBody(item.parentNode);
}

function outItem()
{

	var targetElt = this;
	// IE hack for rollover state
	if(document.all && document.getElementById)
	{
		targetElt.className=targetElt.className.replace(new RegExp(" sfhover\\b"), "");
	}
	var iframe = this.getElementsByTagName("iframe")[0];
	if (iframe && isMacintosh())
	{
		iframe.style.display = "none";
		//iframe.style.visibility = "hidden";
	}
}

// Add list children to uls
function InsertChildren(ListItem, Index)
{
	var ul = document.createElement("ul");
	var shadowDiv = document.createElement("div");
	shadowDiv.className = "shadow"
	if(aMenu[Index] != "")
	{
		ul.innerHTML = aMenu[Index];
		ul.style.zIndex = "99";
		ListItem.appendChild(ul);
		var items = ul.getElementsByTagName("li");
		if(items.length > 0)
		{
			var middleHeight = (items.length * 26) - 41;
			shadowDiv.innerHTML = "<div class='shadowTop'></div>" +
				"<div style='width:234px;height:" + middleHeight + "px;' class='shadowMiddle' ></div>" +
				"<div class='shadowBottom'></div>";
			ul.appendChild(shadowDiv);
		}
	}
}

function InitMenu()
{
	var mainMenu;
	mainMenu = document.getElementById("menu");
	if (mainMenu == null || mainMenu == undefined)
	    mainMenu = document.getElementById("Menu");
	var primaryItems = mainMenu.getElementsByTagName("li");
	for(var i = 0;i < primaryItems.length;i++)
	{
		var item = primaryItems[i];
		var link = item.getElementsByTagName("a")[0];
		if(link != null)
			link.setAttribute("index", i);
		item.onmouseover = overItem;
		item.onmouseout = outItem;	
	}
	// Add PageName field to the search form
	var pageNameField = document.createElement("input");
	pageNameField.setAttribute("type","hidden");
	pageNameField.setAttribute("name","PageName");
	pageNameField.setAttribute("value", document.title.replace(" ", "+"));
	var searchForm = document.getElementById("SearchForm");
	searchForm.appendChild(pageNameField);

}

//Added constants for the menu Iframes, needs to match the style sheet
var MENU_HEIGHT = 25;
var MENU_PADDING = 0;
var MENU_HEIGHT_IE5 = 25;
var MENU_PADDING_IE5 = 0;
var MENU_TOP_MARGIN = 2;

var menuIsIE = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
var menuIsV3 = (menuIsIE && parseInt(navigator.appVersion) < 4);
var menuIsV5 = (menuIsIE && navigator.userAgent.toLowerCase().indexOf("msie 5.") != -1);
var menuIsV4 = (menuIsIE && navigator.userAgent.toLowerCase().indexOf("msie 4.") != -1);
var isIE6Up = (menuIsIE && !menuIsV4 && !menuIsV5 && !menuIsV3);

if (!isIE6Up && menuIsIE)
{
	MENU_HEIGHT = MENU_HEIGHT_IE5;
	MENU_PADDING = MENU_PADDING_IE5;
}

var LOC_NAME_LENGTH = 42;


function LocalizeSearch(searchForm)
{
    var id = getCookieVal('CorpID');
    if(id > 1)
    {
        searchForm.corp.value = id;
        searchForm.LevelNum.value = 4;
        searchForm.LevelId.value = id;           
    }
}

//This fires an async request to the specified url
//Specifically designed not to handle the onreadystatechange event
//Used primarily to call the IDGenerator.
function makeHttpRequest(url) {
	var http_request = false;
	
	if(url && url.length > 0)
	{
		reHTTP = new RegExp("^(http://|https://)");
		if(!url.match(reHTTP))
		{
			if (window.XMLHttpRequest) { // Mozilla, Safari,...
				http_request = new XMLHttpRequest();
				if (http_request.overrideMimeType) {
					http_request.overrideMimeType('text/xml');
				}
			} else if (window.ActiveXObject) { // IE
				try {
					http_request = new ActiveXObject("Msxml2.XMLHTTP");
				} catch (e) {
					try {
						http_request = new ActiveXObject("Microsoft.XMLHTTP");
					} catch (e) {}
				}
			}

			if (!http_request) {
				//alert('Giving up :( Cannot create an XMLHTTP instance');
				return false;
			}
				
			http_request.open('GET', url, true);
			http_request.send(null);
		}
	}

}

function checkEnter(e, formButtonId)  //e is event object passed from function invocation
{
	var characterCode; //literal character code will be stored in this variable
	if(e && e.which) //if which property of event object is supported (NN4)
	{
		e = e;
		characterCode = e.which; //character code is contained in NN4's which property
	}
	else{
		e = (e) ? e : ((window.event) ? window.event : null);
		characterCode = e.keyCode; //character code is contained in IE's keyCode property
	}

	if(characterCode == 13) //if generated character code is equal to ascii 13 (if enter key)
	{
	    var formToSubmit = document.getElementById(formButtonId);
		if(formToSubmit != null)
		{
			formToSubmit.click();
		}
		//document.getElementById(formId).submit();
		//document.forms[1].submit(); //submit the form
		return false;
	}
	else
	{
		return true;
	}
}

function SearchTV(initialView)
{
	// Currently called from:
	// 1. Menu Search dropdown (both templates and dynamic pages, and auto generated site map)
	// 2. Explore Flash movie callback
	// 3. Channel Lineup page
	// 4. Secondary Menu Nav "Whats On" (both templates and dynamic pages, and auto generated site map)
	// initialView can be schedule-grid, browse, or search
	var form = document.getElementById("tvSearch");
	var zipField = document.getElementById("TvZip");
	var zip = get5DigitZip();
	var defaultValue = zipField.getAttribute("defaultValue");
	if (zipField.value == defaultValue)
	{
		if (zip != false)
			zipField.value = zip;
		else
			zipField.value = "";
	}
	
	form.target="_blank";
	form.submit();
}

function get5DigitZip()
{
	//Substring is done to remove the +4 digit zip code returned from CSG
	var zip = GetCookie("Serviceability","Zip");
	if(zip == null || zip == false || zip == "")
		zip = GetCookie("PermLocalization","Zip");
	if(zip != null && zip != "")
		return zip.substring(0,5);
	return "";
}

function validateUsername(usernameField)
{
	var defaultValue = usernameField.getAttribute("defaultValue");
	if (usernameField.value.trim() == "" || usernameField.value.trim() == defaultValue)
	{
		alert("Please enter your username.");
		usernameField.focus();
		return false;
	}
	else if (!checkEmail(usernameField))
	{
		usernameField.focus();
		return false;
	}
	else
		return true;
}


function ForgotPw(form, targetPath)
{
	form.action = getPostServer() + targetPath;
	form.submit();
}

function ForgotPwLocal()
{
	if (validateUsername(document.getElementById("userName")))
		ForgotPw(document.getElementById("LogInForm"), "/customers/membership/reminder.ashx");

	return false;
}

function ForgotPwCima()
{
	ForgotPw(document.getElementById("CimaLogInForm"), "/customers/CimaReminder/CimaReminder.ashx");
	return false;
}

function GetCookie(key1,key2)
{       
	var sCookie = new String(document.cookie);
	//alert(sCookie)
	if(key1 != null)
	{
		var aCList = sCookie.split('; ');
		for(var i = 0;i < aCList.length;i++)
		{
			sCookie = aCList[i];
			var oReg = new RegExp("(^"+key1+"=)(.*)","ig");
			var aResult = oReg.exec(sCookie);
			if(aResult != null)
			{
				sCookie = RegExp.$2;
				if(key2 != null)
				{
					aCList = sCookie.split("&");
					for(var i = 0;i < aCList.length;i++)
					{
						sCookie = aCList[i];
						var oReg = new RegExp("(^"+key2+"=)(.*)","ig");
						var aResult = oReg.exec(sCookie);;
						if(aResult != null)
						{
							sCookie = unescape(RegExp.$2);
							break;
						}else {
							sCookie = false;
						}
					}
				}
				break;
			} else {
				sCookie = false;
			}
		}
	}
	return sCookie;
}

// DEPRECATED - 8/10/2007 - BH
// This function has been replaced by populateLinksAndPromo()
function populateHomeQuickLinks2()
{
	var corpID = GetCookie("Serviceability","CorpID");
	var levelNumber = 1;
	if(corpID)
	{
		levelNumber = 4;
	}
	else
	{
		corpID = 1;
	}
	var linksDiv = document.getElementById("dynamicLinks");
	linksDiv.style.display = "inline";
	var requestUri 
	    = '/userservices/localcontent.asmx/GetLinksHome2?LevelNumber=' + levelNumber + '&LevelID=' + corpID;
	makeRequest(requestUri,'dynamicLinks');
	
}

// DEPRECATED - 8/10/2007 - BH
// This function has been replaced by populateLinksAndPromo()
function populatePromoContent()
{
    var corpID = GetCookie("Serviceability","CorpID");
	var levelNumber = 1;
	if(corpID)
	{
		levelNumber = 4;
	}
	else
	{
		corpID = 1;
	}
	var requestUri
	    = '/userservices/localcontent.asmx/GetHomePageContent?LevelNumber=' + levelNumber + '&LevelID=' + corpID;
    makeRequest(requestUri,'PromoSection');
}

// New function to get both the QuickLinks and the Local PromoContent for the page
// with one WebService call
function populateLinksAndPromo()
{
    var corpID = GetCookie("Serviceability","CorpID");
	var levelNumber = 1;
	if (corpID)
	{
		levelNumber = 4;
	}
	else
	{
		corpID = 1;
	}
	var requestUri
	    = '/userservices/localcontent.asmx/GetLinksAndContent?LevelNumber=' + levelNumber + '&LevelID=' + corpID;
    makeRequestJson( requestUri, setLinksAndPromo );
}

// JSON Callback function
// Used by populateLinksAndPromo()
function setLinksAndPromo( callSuccess, resultObj )
{
	if (callSuccess)
	{
	    // There should be two properties in the resultObject
	    // the QuickLinks and the LocalPromoContent
		if (resultObj != null)
		{
			var dynamicLinks = document.getElementById( "dynamicLinks" );
			if (dynamicLinks != null && dynamicLinks != "")
			{
			    dynamicLinks.innerHTML = resultObj.LinksHome;
			}
			
			var promoSection = document.getElementById( "PromoSection" );
			if (promoSection != null && promoSection != "")
			{
			    promoSection.innerHTML = resultObj.LocalPageContent;
			}
        }
    }
}

function isMacintosh()
{
	// alert(window.navigator.userAgent);
	if(window.navigator.userAgent.indexOf("Macintosh") > -1)
		return true;
	return false;
}

function isSafari()
{
	// alert(window.navigator.userAgent);
	if(window.navigator.userAgent.indexOf("Safari") > -1)
		return true;
	return false;
}

var safariContentWidth = 0;
function redrawSafari()
{
	var locShim = document.getElementById("MiddleSection");
	locShim.style.width = 929 + safariContentWidth % 2 + "px";
	safariContentWidth = (safariContentWidth+1)%2;
}

var firefoxContentWidth = 0;
function redrawFirefox()
{
	var locShim = document.getElementById("FlashLocalization");
	locShim.style.width = 164 + firefoxContentWidth % 2 + "px";
	firefoxContentWidth = (firefoxContentWidth+1)%2;
}

function openExtTextWindow(openURL,WindowName,width,height,scroll) 
{
    var winl = (screen.width-width)/2;
    var wint = (screen.height-height)/2;
    var settings  ='height='+height+',';
      settings +='width='+width+',';
      settings +='top='+wint+',';
      settings +='left='+winl+',';
      settings +='scrollbars='+scroll+',';
      settings +='resizable=yes,toolbar=no,location=no,status=no,menubar=no,resizable=yes';
    var newwindow = window.open(openURL,WindowName,settings);
    newwindow.focus();
    return newwindow;
}

function addButtonRollover()
{
	var aImg = document.getElementsByTagName("img");
	for (var i = 0; i < aImg.length; i++)
	{
		if(aImg[i].className == "button")
		{
			aImg[i].onmouseover = buttonRollOn;
			aImg[i].onmouseout = buttonRollOff;
		}
	}
	
	var inputButtons = document.getElementsByTagName("input")
	for (var i = 0; i < inputButtons.length; i++)
	{
		if(inputButtons[i].type == "image")
		{
			inputButtons[i].onmouseover = buttonRollOn;
			inputButtons[i].onmouseout = buttonRollOff;
		}
	}
}

var buttonRollOn = function() {
	var sOrgSrc = this.getAttribute("src");
    var sImage = sOrgSrc.substring(sOrgSrc.lastIndexOf("/"),sOrgSrc.length);
	var sExtension = sImage.substring(sImage.indexOf("."), sOrgSrc.length);
	var sNewSrc = sOrgSrc.substring(0, sOrgSrc.lastIndexOf(".")) + "_over" + sExtension;
	this.setAttribute("orgSrc", sOrgSrc);
	this.setAttribute("src", sNewSrc);
}

var buttonRollOff = function() {
	var sOrgSrc = this.getAttribute("orgSrc");
	this.setAttribute("src",sOrgSrc);
}


function prepToolTips() 
{
    //var faqArea = document.getElementById("DFCMSave24");
    //var anchors = faqArea.getElementsByTagName("a");
    
    var anchors = document.getElementsByTagName("a");
    var re = /(faqdetails.ashx\?id=)(\d+)/i;
    for(i=0;i<anchors.length;i++) 
    {
        var faqmatch = anchors[i].href.toLowerCase().match(re);
        
        if (null != faqmatch && null != document.getElementById("faq" + faqmatch[2]) && anchors[i].parentNode.nodeName.toLowerCase() == "li")
        {
            var curAnchor = anchors[i];
/*
            if (anchors[i].parentNode.nodeName != "span")
            {
                var linkspan = document.createElement("span");
                curAnchor.parentNode.appendChild(linkspan);
                linkspan.appendChild(curAnchor);
                //curAnchor.parentNode.removeChild(curAnchor);
            }
*/
            //cx.arguments[1] ='faq' + faqmatch[2];
            curAnchor.setAttribute("faqid", "faq" + faqmatch[2]);
            //curAnchor.onmouseover = function(event){showToolTip(event, this.getAttribute("faqid"), this)};
            //'faq' + faqmatch[2])};
            curAnchor.onmouseout = cancelHideToolTip;
            curAnchor.onclick = function(event){showToolTip(event, this.getAttribute("faqid"), this); return false;};
            //curAnchor.href = "";
            curAnchor.onmouseover = function(event){startHideToolTip(event, 500)};
            //curAnchor.parentNode.onmousemove = Locate;
        }
    }
    
}

function showToolTip(e, divBubble, anchor)
{
    if(document.all)e = event;
    var tooltip = document.getElementById('tooltip');
    var faqcontent = document.getElementById(divBubble);
    document.getElementById('tooltip_content').innerHTML = faqcontent.innerHTML;
    tooltip.style.display = 'block';

    LocateElement(e, tooltip, anchor);
    
    tooltip.setAttribute("activetooltip", anchor);

/*    var tooltip = document.getElementById('tooltip');
    clearTimeout(tooltip.getAttribute("timer"));
    var parentPos = findPos(tooltip.parentNode)
//    var parentx = tooltip.parentNode.offsetLeft;
//    var parenty = tooltip.parentNode.offsetTop;
    var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
    var sl = Math.max(document.body.scrollLeft,document.documentElement.scrollLeft);
    if(navigator.userAgent.toLowerCase().indexOf('safari')>=0)
    {   
        st=0;
        sl=0;
    }
    var leftPos = e.clientX - 180 - parentPos[0] + sl; //180 is the offset for the div, such that the carrot is pointing at the mouse.
    if(leftPos<0)leftPos = 0;
    tooltip.style.left = leftPos + 'px';
    var topPos = e.clientY - tooltip.offsetHeight - 5 + st - parentPos[1]; // 
    tooltip.style.top = topPos + 'px';
    */
}

function startHideToolTip(e, timeout)
{
    if(document.all)e = event;
    var tooltip = document.getElementById('tooltip');
    var anchor = tooltip.getAttribute("activetooltip");
    if (e.originalTarget != anchor)
    {
        var t = setTimeout("hideToolTip();", timeout);
        tooltip.setAttribute("timer", t);
    }
}

function hideToolTip() 
{
    var t = document.getElementById('tooltip');
    t.style.display = 'none';
    t.setAttribute("activetooltip", null);
}

function cancelHideToolTip()
{
    var tooltip = document.getElementById('tooltip');
    clearTimeout(tooltip.getAttribute("timer"));
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}

function LocateElement(e, tooltip, item) 
{
    if(document.all)e = event;
   // var tooltip = document.getElementById(itemId);
    clearTimeout(tooltip.getAttribute("timer"));
    var parentPos = findPos(tooltip.parentNode)
    var itemParentPos = findPos(item.parentNode)
    if(navigator.userAgent.toLowerCase().indexOf('safari')>=0)
    {   
        st=0;
        sl=0;
    }
    var leftPos = itemParentPos[0] - 197 - parentPos[0]; //180 is the offset for the div, such that the carrot is pointing at the mouse.  
    if(leftPos<0)leftPos = 0;
    tooltip.style.left = leftPos + 'px';
    var topPos = itemParentPos[1] - tooltip.offsetHeight  + 10 - parentPos[1]; //  
    tooltip.style.top = topPos + 'px';
}

function LocateMouse(e, itemId){

    if(document.all)e = event;
    var tooltip = document.getElementById(itemId);
    clearTimeout(tooltip.getAttribute("timer"));
    var parentPos = findPos(tooltip.parentNode)
//    var parentx = tooltip.parentNode.offsetLeft;
//    var parenty = tooltip.parentNode.offsetTop;
    var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
    var sl = Math.max(document.body.scrollLeft,document.documentElement.scrollLeft);
    if(navigator.userAgent.toLowerCase().indexOf('safari')>=0)
    {   
        st=0;
        sl=0;
    }
    var leftPos = e.clientX - 180 - parentPos[0] + sl; //180 is the offset for the div, such that the carrot is pointing at the mouse.
    if(leftPos<0)leftPos = 0;
    tooltip.style.left = leftPos + 'px';
    var topPos = e.clientY - tooltip.offsetHeight  - 5 + st - parentPos[1]; // 
    tooltip.style.top = topPos + 'px';
}

/* Wonder Factory pop up function - Used by flash movie */
function popup(url, popup, options){
	if(!url) return;
	var mypopup;
	if(!arguments.callee.popups) arguments.callee.popups = {};
	if(popup && arguments.callee.popups[popup]) mypopup = arguments.callee.popups[popup];
	var details = (typeof options == 'string' && /=/.test(options))? options + ',scrollbars=1' : 'width='+(screen.availWidth/3)+',height='+(screen.availHeight/2)+',top=200,left=500,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1';
	if(typeof mypopup != 'undefined' && !mypopup.closed) mypopup.location = url;
	else mypopup = window.open(url,(typeof popup == 'string' ? popup :''),details);
	if(typeof popup != 'undefined' && !arguments.callee.popups[popup]) arguments.callee.popups[popup] = mypopup;
	
	if(mypopup && mypopup.focus) mypopup.focus();
};


/*=======================================================================================
	CookieHelper.js
========================================================================================*/

function getCookieVal(sName)
{
	var val = "";
	var nIndex = document.cookie.indexOf(sName);
	if (nIndex != -1)
	{
		// move past the equal sign
		var nStart = nIndex + sName.length + 1;
		
		// find the end of our cookie value. Either &, ;, or end of string
		var nAmp = document.cookie.indexOf("&", nStart);
		var nSemi = document.cookie.indexOf(";", nStart);

		if ((nAmp != -1 && nAmp < nSemi) || (nSemi == -1 && nAmp != -1)) val = document.cookie.substring(nStart, nAmp);
		else if (nSemi != -1) val = document.cookie.substring(nStart, nSemi);
		else val = document.cookie.substring(nStart, document.cookie.length);
	}

	return unescape(val);
}

function GetCookie(key1,key2)
{       
    var sCookie = new String(document.cookie);
    //alert(sCookie)
    if(key1 != null)
    {
        var aCList = sCookie.split('; ');
        for(var i = 0;i < aCList.length;i++)
        {
            sCookie = aCList[i];
            var oReg = new RegExp("(^"+key1+"=)(.*)","ig");
            var aResult = oReg.exec(sCookie);
            if(aResult != null)
            {
                sCookie = RegExp.$2;
                if(key2 != null)
                {
                    aCList = sCookie.split("&");
                    for(var i = 0;i < aCList.length;i++)
                    {
                        sCookie = aCList[i];
                        var oReg = new RegExp("(^"+key2+"=)(.*)","ig");
                        var aResult = oReg.exec(sCookie);;
                        if(aResult != null)
                        {
                            sCookie = unescape(RegExp.$2);
                            break;
                        } else {
                            sCookie = false;
                        }
                    }
                }
                break;
            } else {
                sCookie = false;
            }
        }
    }
    return sCookie;
}

function SetCookie(sName, sSub, sNewValue, sPath, isPermanent)
{
	if(!sName)
		return;
		
	if(!sNewValue)
		sNewValue = "";
		
	if(!sPath)
		sPath = "/";
	
	sCookie = GetCookie(sName);
	if(sCookie == false)
		sCookie = "";
		
	var sNewCookie = sNewValue;

	if(sSub)
	{
		var sOldValue = GetCookie(sName, sSub);
		if(sOldValue != false || sCookie.indexOf(sSub) != -1)	// Cookies with no value still return false
		{
			var cPrefix = "";
			var sPre = "";
			var sSuf = "";
			
			nStartIndex = sCookie.indexOf('&' + sSub);
			if(nStartIndex > 0 )
			{
				cPrefix = '&';
				sPre = sCookie.substring(0,nStartIndex);
			}
			else
			{
				nStartIndex = 0;
			}
			
			sSub = cPrefix + sSub + "=";
			
			nEndIndex = sCookie.substring(nStartIndex + 1, sCookie.length).indexOf('&');
			if(nEndIndex >= 0)
			{
				nEndIndex += nStartIndex + 1;
				sSuf = sCookie.substring(nEndIndex, sCookie.length)
			}

			sNewCookie = sPre + sSub + sNewValue + sSuf;
		}
		else
		{
			if(sCookie.length > 0)
				sCookie += "&";
			
			sNewCookie = sCookie + sSub + "=" + sNewValue;
		}
	}
	
	if(isPermanent && isPermanent == 'true')
	{
		document.cookie = sName + '=' + sNewCookie + '; expires=Fri, 31 Dec 2020 23:59:59 GMT; path=' + sPath + ';';
	}
	else
	{
		document.cookie = sName + "=" + sNewCookie + "; path=" + sPath + ";";
	}
}

function DeleteCookie(sName, sSub)
{
	// cookies are separated by semicolons
	var aCookie = document.cookie.split("; ");
	for (var i=0; i < aCookie.length; i++)
	{
		// a name/value pair (a crumb) is separated by an equal sign
		var aCrumb = aCookie[i].split("=");
		if (sName == aCrumb[0]) 
		{
			// Get cookie substring
			var sCookieSubString = aCookie[i].substring(aCookie[i].indexOf('='),aCookie[i].length);
			
			// Get index of sSub
			var nSubIndex = sCookieSubString.indexOf(sSub);
			if(nSubIndex != -1)
			{
				var nNextIndex = sCookieSubString.substring(nSubIndex, sCookieSubString.length).indexOf('&');
				// is last key in cookie
				if(nNextIndex == -1)
				{
					nNextIndex = sCookieSubString.length;
				
					// Find possible leading &
					if(sCookieSubString.charAt(nSubIndex - 1) == '&')
					{
						nSubIndex = nSubIndex - 1;
					}
				}
				else
				{
					nNextIndex = nNextIndex + nSubIndex + 1
				}
				
				var sReplaceVal = sCookieSubString.substring(nSubIndex, nNextIndex);
				
				// Replace value
				sCookieSubString = sCookieSubString.replace(sReplaceVal,"");

				// If cookie is now empty, delete whole cookie
				if(sCookieSubString.length == 0)
				{
					document.cookie = sName + "=; expires=Fri, 31 Dec 1999 23:59:59 GMT;";
				}
				else
				{
					document.cookie = sName + sCookieSubString + "; path=/";
				}
				
				return true;
			}
		}
	}

	// a cookie with the requested name does not exist
	return false;
}

function setExploreCookie()
{
	SetCookie('Explore', "HideExploreIntro", "true", '/', 'true')
}

function getExploreCookie()
{
	if(GetCookie('Explore', 'HideExploreIntro'))
	{
		return true;
	}
	else
	{
		setExploreCookie();
		return false;
	}
}

////////////////////////
/// Check to see if the user
/// has ever logged in before or
/// is currently logged in.
////////////////////////
function onceLoggedIn()
{
	var onceLoggedIn = GetCookie("OnceLoggedIn");
	// Test to see if the OnceLoggedIn cookie is set ( user has logged in before )
	if(onceLoggedIn == "true")
	{
		return true;
	}
	else 
	{
		return false;
	}
}

function setHomePanelCookie(PanelNumber)
{
    SetCookie("HomePanel", false, PanelNumber, false, true);
}

function getHomePanelCookie()
{
	if(!GetCookie("HomePanel"))
	{
		return 0;
	}
	else
	{
		return GetCookie("HomePanel");
	}
}


/*=======================================================================================
	dfajax.js
========================================================================================*/

function makeRequest(url, elementId, callback) {
	var http_request = initXmlHttpObj();

	if (!http_request) {
		//alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}
	
	http_request.onreadystatechange = function() { displayResponse(http_request, elementId, callback); };	
	http_request.open('GET', url, true);
	http_request.send(null);

}

function displayResponse(http_request, elementId, callback) {

	if (http_request.readyState == 4) {
		if (http_request.status == 200) {
			var xmldoc = http_request.responseXML;
			var root_node = xmldoc.getElementsByTagName("string").item(0);
			
			if(elementId && root_node.firstChild) {
				var displayElement = document.getElementById(elementId);
				displayElement.innerHTML = root_node.firstChild.data;
			}
			
			if(callback && typeof(callback) == 'function') {
				if(root_node.firstChild)
					callback(true, xmldoc);
				else
					callback(false, null);
			}
		} else {
			//alert('There was a problem with the request.');
			if(callback && typeof(callback) == 'function') {
				callback(false, null);
			}
		}
	}

}

// JSON Style
function makeRequestJson(url, callback) {
	var http_request = initXmlHttpObj();
	
	if (!http_request) {
		//alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}
	
	http_request.onreadystatechange = function() { displayResponseJson(http_request, callback); };	
	http_request.open('GET', url, true);
	http_request.send(null);

}

function initXmlHttpObj()
{
	var http_request = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		http_request = new XMLHttpRequest();
		if (http_request.overrideMimeType) {
			http_request.overrideMimeType('text/xml');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			http_request = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				http_request = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	return http_request;
}

function displayResponseJson(http_request, callback) {

	if (http_request.readyState == 4) {
		try
		{
			if (http_request.status && http_request.status == 200) {
				var responseText = http_request.responseText;
				var resultObj = null;
				try
				{
					resultObj = eval('(' + responseText + ')');
				}
				catch(e)
				{
					// eat exception
				}
				if(callback && typeof(callback) == 'function') {
					callback(true, resultObj);
				}
			} else {
				//alert('There was a problem with the request.');
				if(callback && typeof(callback) == 'function') {
					callback(false, null);
				}
			}
		}
		catch(e)
		{
			if(callback && typeof(callback) == 'function') {
					callback(false, null);
				}
		}
	}

}

function populateCLUFeatureColumn()
{
	var corpID = GetCookie("Serviceability","CorpID");
	var levelNumber = 1;
	if(corpID)
	{
		levelNumber = 4;
	}
	else
	{
		corpID = 1;
	}
	makeRequest('/userservices/localcontent.asmx/GetCLUPageContent?LevelNumber=' + levelNumber + '&LevelID=' + corpID,'feature')
}

function populateHomeQuickLinks()
{
	var corpID = GetCookie("Serviceability","CorpID");
	var levelNumber = 1;
	if(corpID)
	{
		levelNumber = 4;
	}
	else
	{
		corpID = 1;
	}
	var linksDiv = document.getElementById("dynamicLinks");
	linksDiv.style.display = "inline";
	makeRequest('/userservices/localcontent.asmx/GetLinksHome?LevelNumber=' + levelNumber + '&LevelID=' + corpID,'dynamicLinks')
	
}

function populateCustCentralQuickLinks()
{
	var corpID = GetCookie("Serviceability","CorpID");
	var levelNumber = 1;
	if(corpID)
	{
		levelNumber = 4;
	}
	else
	{
		corpID = 1;
	}
	var linksDiv = document.getElementById("dynamicLinks");
	linksDiv.style.display = "inline";
	makeRequest('/userservices/localcontent.asmx/GetLinksCustCentral?LevelNumber=' + levelNumber + '&LevelID=' + corpID,'dynamicLinks')
	
}

function populateMyAccountShopContent()
{
    var corpID = GetCookie("Serviceability","CorpID");
    makeRequest('/userservices/localcontent.asmx/GetShopContentMyAccount?CorpId='+ corpID,'shopContent')
}

function populateHomePromo()
{
	var corpID = GetCookie("Serviceability","CorpID");
	var levelNumber = 1;
	if(corpID)
	{
		levelNumber = 4;
	}
	else
	{
		corpID = 1;
	}
	var linksDiv = document.getElementById("PromoSection");
	linksDiv.style.display = "inline";
	makeRequest('/userservices/localcontent.asmx/GetHomePageContent?LevelNumber=' + levelNumber + '&LevelID=' + corpID,'PromoSection')
	
}

function searchFormClick(searchForm)
{
    var searchField = searchForm.searchField;
    if(searchField.value == '' || searchField.value == searchField.defaultValue)
    {
        alert("Please enter a search term.");
        return false;
    }
    else
    {
        return true;
    }
}

var ind = location.href.indexOf('http://comcast.com');if(ind > -1){location.href = location.href.replace('comcast.com', 'www.comcast.com');}
var _xmlHttp;var locInt=null;
function retrieveWebResponse(service, method, handler, params){_xmlHttp=initXmlHttpObj();if(_xmlHttp!=null){_xmlHttp.onreadystatechange=handler;_xmlHttp.open("POST", service+"/"+method);_xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");_xmlHttp.send(params);}}

function InitFormFields()
{
	var input = document.getElementsByTagName("input");
	for(var i = 0;i < input.length;i++)
	{
		if ( input[i].type == "text" )
		{	
			var defaultText = input[i].getAttribute("defaultValue");
			input[i].onblur = defaultField;
			input[i].onfocus = clearField 
		}
	}
}

function clearField()
{
	var defaultText = this.getAttribute("defaultValue");
	if(this.value.trim() == defaultText)
	{
		this.value = "";
	}
}

function defaultField()
{
    var defaultText = this.getAttribute("defaultValue");
	if(this.value.trim() == "")
	{
		this.value = defaultText;
	}
}