
var emailURL = '';



var lastHashCalled = "";
var lastTabCalled = "";

var maxHistoryTabs = 7;

function getAbsoluteTop(node, includeIE)
{
	return getAbsoluteTopFromID(node, "content", includeIE);
}

function getAbsoluteTopFromID(node, id, includeIE)
	{
	var tally = 0;
	var hasParent = (node.offsetParent != null);
	var allowBreak = (! isIE() )||( includeIE );
    if(hasParent)
    {
        while(hasParent)
        {
        	tally += node.offsetTop;
        	if(!hasParent)
        	{
        		break;
        	}
        	node = node.offsetParent;
			if((node.id == id)&&( allowBreak ))
			{
				break;
			}
			hasParent = (node.offsetParent != null);
        }
    }
    else if(node.y){
    	tally += node.y;
    }

    return tally;
}

function getAbsoluteLeft(node, includeIE)
{
	return getAbsoluteLeftFromID(node, "content", includeIE);
}

function getAbsoluteLeftFromID(node, id, includeIE)
{
	var tally = 0;
	var hasParent = (node.offsetParent != null);
	var allowBreak = (! isIE() )||( includeIE );
    if(hasParent)
    {
        while(hasParent)
        {
        tally += node.offsetLeft;
          if(!hasParent)
          {
            break;
          }
          node = node.offsetParent;
		  if((node.id == id)&&( allowBreak ))
          {
        	  break;
          }
          hasParent = (node.offsetParent != null);
        }
    }
    else if(node.x){
    	tally += node.x;
    }
    return tally;
}

function escapeStringForOutput(val){
	var retval = val.replace("\\\\", "\\\\\\\\");
	retval = retval.replace("\"", "\\\\\"");
	return retval;
}

/* standard trim method */
function stringTrim(str) {
    return str.replace(/^\s+|\s+$/g,"");
}

function URLDecode(val)
{

	
	 // Replace + with ' '
	   // Replace %xx with equivalent character
	   // Put [ERROR] in output if %xx is invalid.
	   var HEXCHARS = "0123456789ABCDEFabcdef"; 
	   var plaintext = "";
	   var i = 0;
	   while (i < val.length) {
	       var ch = val.charAt(i);
		   if (ch == "+") {
		       plaintext += " ";
			   i++;
		   } else if (ch == "%") {
				if (i < (val.length-2) 
						&& HEXCHARS.indexOf(val.charAt(i+1)) != -1 
						&& HEXCHARS.indexOf(val.charAt(i+2)) != -1 ) {
					plaintext += unescape( val.substr(i,3) );
					i += 3;
				} else {
					plaintext += "%[ERROR]";
					i++;
				}
			} else {
			   plaintext += ch;
			   i++;
			}
		} 

	   return plaintext;



}


function URLEncode (val) {
    var retval = "";  
    var charCode = '';
    var hexVal = "";  
    var position = 0; 
    var regex = /(^[a-zA-Z0-9_.]*)/;

    //while the position in the val is less then the end of the string
    while (position  < val.length) {                                  
            //match on valid characters                               
            var match = regex.exec(val.substr(position));             
            if (match != null && match.length > 1 && match[1] != '') {
                    //valid char                                      
                    retval += match[1];                               
                    position  += match[1].length;                     
            } else {                                                  
                    // a space found                                  
                    if (val.charCodeAt(position) == 32)               
                            retval += '+';       
                    else if(val.charCodeAt(position) > 127){
                        //encode the extended char in utf-8
                    	var newCode = ((val.charCodeAt(position) >> 6) | 192);
                        hexVal = newCode.toString(16).toUpperCase();  
                        if(hexVal.length == 1)                    
                        {                                         
                        	hexVal = "%0" + hexVal;           
                        }else                                     
                        {                                         
                        	hexVal = "%" + hexVal;            
                        }
                    	newCode = ((val.charCodeAt(position) & 63) | 128);  
                        var _hexVal = newCode.toString(16).toUpperCase();  
                        
                        if(_hexVal.length == 1)                    
                        {                                         
                        	_hexVal = "%0" + _hexVal;           
                        }else                                     
                        {                                         
                        	_hexVal = "%" + _hexVal;            
                        }                                         
                        retval = retval + hexVal + _hexVal; 
                    }else {                                            
                            //some other invalid character            
                            var newCode = val.charCodeAt(position);   
                            hexVal = newCode.toString(16);            
                            hexVal = hexVal.toUpperCase();            
                            if(hexVal.length == 1)                    
                            {                                         
                            	hexVal = "%0" + hexVal;           
                            }else                                     
                            {                                         
                            	hexVal = "%" + hexVal;            
                            }                                         
                            retval = retval + hexVal;                 
                    }                                                 
                    position++;                                       
            }                                                         
    }                                                                 
    return retval;                                                    
}                 


function isIE()
{
	/*@cc_on
	  @if (@_jscript)
	return true;
	  @else */
	return false;   /*
	  @end
	@*/
}



/* generic method to change the index of a dynamic pulldown */
function setPulldownSelectedIndex(index, max, prefix, targetClassname, offClassname, textField, wrappingDiv)
{
	if((index > 0)&&(max > index))
	{
		var current = null;
		var targetDiv = null;
		var i = 1;
		current = prefix+i;
		targetDiv = document.getElementById(current);
		while( targetDiv != null)
		{
			targetDiv.className = offClassname;
			i++;
			current = prefix+i;
			targetDiv = document.getElementById(current);
		}
		
		current = prefix+index;
		targetDiv = document.getElementById(current);
		if(targetDiv != null)
		{
			
			
			targetDiv.className = targetClassname;
			
			var divs = targetDiv.getElementsByTagName("div");
			
			var node;
			for (var i=0;i<= divs.length;i++)
			{
				node = divs.item(i);
				if(node != null)
				{
					//uncomment this line to populate the text box on mouse over
					//textField.value = node.innerHTML;
					
					//now scroll to this attrib
					//first, find out where we are on the page

					if(wrappingDiv != null){
						var offsetScroll = wrappingDiv.scrollTop;
						
						var scrollLength = getAbsoluteTopFromID(targetDiv, wrappingDiv.id, true);
						if(scrollLength < offsetScroll){
							wrappingDiv.scrollTop = scrollLength;
						}else if(scrollLength > (offsetScroll + wrappingDiv.offsetHeight - targetDiv.offsetHeight) ){
							wrappingDiv.scrollTop = scrollLength - wrappingDiv.offsetHeight + (1 * targetDiv.offsetHeight);
						}
					}
				}
			}
		}
	}
}


/* generic method to change the index of a dynamic pulldown */
function getValueOfPulldownAtIndex(index, max, prefix)
{
	if((index > 0)&&(max > index))
	{
		var current = null;
		var targetDiv = null;
		
		
		current = prefix+index;
		targetDiv = document.getElementById(current);
		if(targetDiv != null)
		{
			
			var divs = targetDiv.getElementsByTagName("div");
			
			var node;
			for (var i=0;i<= divs.length;i++)
			{
				node = divs.item(i);
				if(node != null)
				{
					return node.innerHTML;
				}
			}
		}
	}
	return "";
}



function loadSearchResultPortlets()
{

}

function hidePleaseWaitBlock()
{
	var pleaseWaitDiv = document.getElementById("TabListPanelPleaseWait");
	var targetDiv = document.getElementById("TabListPanelBody");
	pleaseWaitDiv.style.display = "none";
	targetDiv.style.display = "inline";
	loadSearchResultPortlets();

	loadSubTabs();
}

function showPleaseWaitBlock()
{
	var pleaseWaitDiv = document.getElementById("TabListPanelPleaseWait");
	var targetDiv = document.getElementById("TabListPanelBody");
	targetDiv.style.display = "none";
	pleaseWaitDiv.style.display = "inline";
}

function loadSubTabs()
{
	var recTab = document.getElementById("loadRecommendedListFocusedTab");
	if(recTab != null)
	{
		var tab = recTab.innerHTML;
		recTab = document.getElementById("loadRecommendedListKey");
		var key = recTab.innerHTML;
		loadRecommendedList(tab , key);
	}
}

function getHistoryURL(id)
{
	if(document.cookie.length > 0)
	{	
		var cookieName = "HistoryID"+id+"=";
		var start= document.cookie.indexOf(cookieName);
		if(start != -1){
			var end = document.cookie.indexOf(";", start);
		    if (end == -1){
		    	end=document.cookie.length;
		    }
		    return document.cookie.substring(start+cookieName.length,end);
		}
	}	
	return "";
}

function getNextAvailableHistoryID()
{
	var startingPoint = 1;
	if(document.cookie.length > 0)
	{
		while(true)
		{
			if( document.cookie.indexOf("HistoryID"+startingPoint + "=") !=-1){
				startingPoint++;
			}else{
				return startingPoint;
			}
		}
	}	
}

	
function deleteAllHistoryIDCookies()
{
	var startingPoint = 1;
	if(document.cookie.length > 0)
	{
		while(true)
		{
			if( document.cookie.indexOf("HistoryID"+startingPoint + "=") !=-1){
				document.cookie="HistoryID"+ startingPoint + "=; expires=Thu, 01-Jan-1970 00:00:01 GMT";
				startingPoint++;
			}else{
				return;
			}
		}
	}	
}

function shiftAllHistoryCookies(){
	var startingPoint = 2;
	var finished = false;
	if(document.cookie.length > 0)
	{
		while(! finished)
		{
			if( document.cookie.indexOf("HistoryID"+startingPoint + "=") !=-1){
				document.cookie="HistoryID"+ startingPoint-1 + "=" + getHistoryURL( startingPoint );
				startingPoint++;
			}else{
				document.cookie="HistoryID"+ startingPoint-1 + "=; expires=Thu, 01-Jan-1970 00:00:01 GMT";
				finished = true;
			}
		}
	}	
}

function addNewHistoryElement(url)
{
	var nextAvailableHistoryID = 0;
	var cookieNumber = 0;
	nextAvailableHistoryID = getNextAvailableHistoryID();
	if( nextAvailableHistoryID > maxHistoryTabs )
	{
		shiftAllHistoryCookies();
		nextAvailableHistoryID--;
	}
	cookieNumber = nextAvailableHistoryID;
	document.cookie="HistoryID"+ cookieNumber + "=" +url;
	return nextAvailableHistoryID;
	
}

function loadTabInListPanel(tab, params, page)
{

	lastTabCalled = tab;
	var urltarget = window.location.toString();
	if(urltarget.indexOf("#") > 0)
	{
		urltarget = urltarget.substring(0, urltarget.indexOf("#"))
	}

	lastHashCalled = params+"&tab="+tab+"&Tabpage="+page;
	
	var hashparams = URLEncode(params+"&tab="+tab+"&Tabpage="+page);
	hashparams = addNewHistoryElement(hashparams);
	window.location = urltarget+"#"+hashparams;
	var targetDiv = document.getElementById("TabListPanelChanger");
	var lis = targetDiv.getElementsByTagName("LI");
	var url = "";
	
	var node;
	for (var i=0;i<= lis.length;i++)
	{
		node = lis.item(i);
		if(node != null)
		{
			node.className = "";
		}
	}
	targetDiv = document.getElementById(tab);
		
	targetDiv.className = "TabListPanelChangerTab";
	url = "index?page="+page+params;

	targetDiv = document.getElementById("TabListPanelBody");
	showPleaseWaitBlock();
	$.get(url, function(data){
		var JTPDetect = "var pageWarp = true";
		if(data.indexOf(JTPDetect) == -1){
			targetDiv.innerHTML = data;
			setTimeout(  'hidePleaseWaitBlock();', 1000 );	
		}else{
			//if there is a jump to page, then redirect to that page
			var startingPosition = data.indexOf("detectedProductFacet=" ) + "detectedProductFacet=".length;
			var endingPosition = data.indexOf("&", startingPosition);
			if((endingPosition == -1)||( data.indexOf("\"", startingPosition) < endingPosition))
			{
				endingPosition = data.indexOf("\"", startingPosition);
			}
			var detectedProductFacet = data.substring(startingPosition, endingPosition);
			if(detectedProductFacet.lastIndexOf(".") != -1 ){
				detectedProductFacet = detectedProductFacet.substring( detectedProductFacet.lastIndexOf(".")+1 );
			}
			
			var cleanParams = params.substring(0, params.indexOf("productCode=") );
			cleanParams += params.substring( params.indexOf("&", params.indexOf("productCode="))+1 );
			
			startingPosition = data.indexOf("location.href= \"") + "location.href= \"".length;
			endingPosition = data.indexOf("\";", startingPosition);
			var jumpToPage = data.substring(startingPosition, endingPosition);
			window.location = jumpToPage + cleanParams + "&productCode=" + detectedProductFacet;
		}
	});
	
	return false;
}

function loadContentInTabInListPanel(tab, params, page)
{

	lastTabCalled = tab;
	var urltarget = window.location.toString();
	if(urltarget.indexOf("#") > 0)
	{
		urltarget = urltarget.substring(0, urltarget.indexOf("#"))
	}

	lastHashCalled = params+"&tab="+tab+"&Tabpage="+page;
	
	var hashparams = URLEncode(params+"&tab="+tab+"&Tabpage="+page);
	hashparams = addNewHistoryElement(hashparams);
	window.location = urltarget+"#"+hashparams;
	var targetDiv = document.getElementById("TabListPanelChanger");
	var lis = targetDiv.getElementsByTagName("LI");
	
	
	var node;
	for (var i=0;i<= lis.length;i++)
	{
		node = lis.item(i);
		if(node != null)
		{
			node.className = "";
		}
	}
	targetDiv = document.getElementById(tab);
		
	targetDiv.className = "TabListPanelChangerTab";

	showPleaseWaitBlock();
	setTimeout(  'hidePleaseWaitBlock();', 1000 );	
	
	return false;
}

var addRecommenedHistory = false;
function historyCallback(hash)
{
	hash = URLDecode(getHistoryURL(hash));
	if(isIE())
	{
		hash = URLDecode(hash);
	}
	
	if((hash.length > 0)&&(lastHashCalled != hash))
	{
		//alert("Loading "+ hash);
		if(hash.indexOf("page=recommend") > -1)
		{
			var startIdx = hash.indexOf("&focusedTab=");
			var tabIdx = hash.indexOf("&key=");
			var focusedTab = hash.substring(startIdx+"&focusedTab=".length, tabIdx);
			var key = hash.substring(tabIdx+"&key=".length);
	
			loadRecommendedListWithHistory(focusedTab , key, addRecommenedHistory);
		}else{
			var startIdx = hash.indexOf("&tab=");
			var tabIdx = hash.indexOf("&Tabpage=");
			var params = hash.substring(0, startIdx);
	
			var tab = hash.substring(startIdx+5, tabIdx);
			var page = hash.substring(tabIdx+9);
			var targetDiv = document.getElementById("TabListPanelChanger");
			if(targetDiv != null)
			{
				loadTabInListPanel(tab, params, page);
			}
		}
	}
}



function toggleNodeInfoCategoryData()
{
	var targetDiv = document.getElementById("nodeInfoCategoryData");

	if(targetDiv.style.display == "none")
	{
		targetDiv.style.display = "block";
	}else{
		targetDiv.style.display = "none";
	}
}

function hideAllRecommendedContent()
{
	var targetDiv = document.getElementById("AllRecommendedContent");
	var divs = targetDiv.getElementsByTagName("DIV");
	var node;
	for (var i=0;i<= divs.length;i++)
	{
		node = divs.item(i);
		if(node != null)
		{
			if(node.id.match("^RecomendedDownloadListPanelBody_")=="RecomendedDownloadListPanelBody_")
			{
				node.style.display = "none";
			}
		}
	}
}

function hideAllFileContent()
{
	var targetDiv = document.getElementById("AllFileContent");
	var divs = targetDiv.getElementsByTagName("DIV");
	var node;
	for (var i=0;i<= divs.length;i++)
	{
		node = divs.item(i);
		if(node != null)
		{
			if(node.id.match("^FileDownloadListPanelBody_")=="FileDownloadListPanelBody_")
			{
				node.style.display = "none";
			}
		}
	}
}


function loadRecommendedListWithHistory(focusedTab, key, addHistory){
	var urltarget = window.location.toString();
	if(urltarget.indexOf("#") > 0)
	{
		urltarget = urltarget.substring(0, urltarget.indexOf("#"))
	}
	var targetDiv = document.getElementById("RecommendedTabListPanelChanger");
	if(targetDiv == null){
		return false;
	}


	if(addHistory){
		lastHashCalled = "page=recommend&focusedTab="+focusedTab+"&key="+key;
		
		var hashparams = URLEncode("page=recommend&focusedTab="+focusedTab+"&key="+key);
		hashparams = addNewHistoryElement(hashparams);
		window.location = urltarget+"#"+hashparams;
	}
	var lis = targetDiv.getElementsByTagName("LI");
	var tabkey = focusedTab.substring("RecommendedTabListPanelChanger_".length);
	var node;
	for (var i=0;i<= lis.length;i++)
	{
		node = lis.item(i);
		if(node != null)
		{
			node.className = "";
		}
	}
	targetDiv = document.getElementById(focusedTab);
	hideAllRecommendedContent();
	targetDiv.className = "TabListPanelChangerTab";
	targetDiv = document.getElementById("RecomendedDownloadListPanelBody_"+tabkey);
	targetDiv.style.display = "block";
	return false;
}

function loadRecommendedList(focusedTab , key){
	return loadRecommendedListWithHistory(focusedTab, key, true);
}

function loadFileList(focusedTab , key){
	var urltarget = window.location.toString();
	if(urltarget.indexOf("#") > 0)
	{
		urltarget = urltarget.substring(0, urltarget.indexOf("#"))
	}

	lastHashCalled = "page=downloadsList&focusedTab="+focusedTab+"&key="+key;
	
	var hashparams = URLEncode("page=downloadsList&focusedTab="+focusedTab+"&key="+key);
	hashparams = addNewHistoryElement(hashparams);
	window.location = urltarget+"#"+hashparams;
	var targetDiv = document.getElementById("FileTabListPanelChanger");
	var lis = targetDiv.getElementsByTagName("LI");
	var tabkey = focusedTab.substring("FileTabListPanelChanger_".length);
	var node;
	for (var i=0;i<= lis.length;i++)
	{
		node = lis.item(i);
		if(node != null)
		{
			node.className = "";
		}
	}
	targetDiv = document.getElementById(focusedTab);
	hideAllFileContent();
	targetDiv.className = "TabListPanelChangerTab";
	targetDiv = document.getElementById("FileDownloadListPanelBody_"+tabkey);
	targetDiv.style.display = "block";
	return false;
}

function changeOSList(newOS, ignoreKey)
{
	if(newOS != ignoreKey)
	{
		document.OSSelectAction.elements['os'].value = newOS;
		document.OSSelectAction.elements['page'].value = "downloadsList"; 
		document.OSSelectAction.submit();
	}
}

function changeOSListLocale(locale)
{
	document.OSSelectAction.elements['oslocale'].value = locale;	
	document.OSSelectAction.submit();
}

function hideEmailLink()
{

	$("#EmailPageDiv").css("display","none");
	$("#pageOptionsdownblocker").css("display","none");
	

}

function toggleEmailPagePanel()
{
	var targetDiv = document.getElementById("EmailPageDiv");
	if(targetDiv != null)
	{
		if(	targetDiv.style.display == "inline")
		{
			hideEmailLink();
		}else
		{
			targetDiv.style.display = "inline";
			var anchor = document.getElementById("eplActions");
			var myTop = 20;
			var myLeft = 230; 
			if( isIE())
			{
				myTop = 21;
				myLeft = 221;
			}

			myTop += getAbsoluteTop(anchor, false);
			myLeft += getAbsoluteLeft(anchor, false);

			targetDiv.style.top = myTop+"px";
			targetDiv.style.left = myLeft+"px";
			var blockingIframe = document.getElementById("pageOptionsdownblocker");

			blockingIframe.style.width = targetDiv.offsetWidth;
			blockingIframe.style.height = targetDiv.offsetHeight;
			blockingIframe.style.top = targetDiv.style.top;
			blockingIframe.style.left = targetDiv.style.left;
			blockingIframe.style.zIndex = targetDiv.style.zIndex +1; 
			blockingIframe.style.display = "block";

		}
	}
	targetDiv = document.getElementById("linkDisplayDiv");
	if(targetDiv != null)
	{
		targetDiv.style.display = "none";
		blockingIframe.style.display = "none";
	}
}

function hidePageLink()
{
	$("#linkDisplayDiv").css("display","none");
	$("#pageOptionsdownblocker").css("display","none");
}

function togglePageLink()
{
	var targetDiv = document.getElementById("linkDisplayDiv");
	if(targetDiv != null)
	{
		if(	targetDiv.style.display == "inline")
		{
			hidePageLink();
		}else
		{
			if(lastTabCalled != "")
			{
				document.linkPageForm.elements['link'].value = document.linkPageForm.elements['link'].value + "&focusedTab="+lastTabCalled;
			}
			
			targetDiv.style.display = "inline"
			var anchor = document.getElementById("eplActions");
			var myTop = 20;
			var myLeft = 230; 
			if( isIE())
			{
				myTop = 21;
				myLeft = 221;
			}
			
			myTop += getAbsoluteTop(anchor, false);
			myLeft += getAbsoluteLeft(anchor, false);
			
			targetDiv.style.top = myTop+"px";
			targetDiv.style.left = myLeft+"px";
			


			$("#pageOptionsdownblocker").css("width",targetDiv.offsetWidth);
			$("#pageOptionsdownblocker").css("height",targetDiv.offsetHeight);
			$("#pageOptionsdownblocker").css("top",targetDiv.offsetWidth);
			$("#pageOptionsdownblocker").css("left",targetDiv.style.left);
			$("#pageOptionsdownblocker").css("zIndex",targetDiv.style.zIndex +1);
			$("#pageOptionsdownblocker").css("display","block");


			return;
		}
	}
	$("#EmailPageDiv").css("display","none");
	$("#pageOptionsdownblocker").css("display","none");
	
}

function showPrintView(url)
{
	if(lastTabCalled != "")
	{
		url += "&focusedTab="+lastTabCalled;
	}
	window.location = url;
}

function emailPage(recipient, url)
{
	if(lastTabCalled != "")
	{
		url += "&focusedTab="+lastTabCalled;
	}
	var mailURL = url + "&recipient="+ URLEncode(recipient);

	$.get(mailURL, function(data){
		$("#EmailPageDiv").css("display","none");
	});
	
}

/* this function is here as a stub for content ratings. */
function preRatingFormSubmit(formname)
{
	return true;
}

function createIFrameFloat(id){
    var targetBody = document.getElementsByTagName("BODY").item(0);
    var iframe = document.createElement("IFRAME");
    iframe.setAttribute("id", id);
    iframe.style.border = "none";
    iframe.style.display = "none";
    iframe.style.zIndex = "1000";
    iframe.width = 0;
    iframe.height = 0;
    iframe.style.position = "absolute";
     
    targetBody.appendChild(iframe);
}

var wHeight = 0;
var wWidth = 0;
$(window).bind('resize', function() {
	
	if( $(window).width() != wWidth )
	{
		wHeight = $(window).height();
		wWidth = $(window).width();

	    hideCarouselSelectorPulldown();
	    hideLocaleSelectorPulldown();
	    hidePageLink();
	    hideEmailLink();
	}
});

$(document).ready(function() {
    $.history.init(historyCallback);
	wHeight = $(window).height();
    wWidth = $(window).width();
    deleteAllHistoryIDCookies();
    $("a[@rel='history']").click(function(){
        $.history.load(this.href.replace(/^.*#/, ''));
        return false;
    });
    
    createIFrameFloat('pageOptionsdownblocker');
    createIFrameFloat('localeSelectPulldownblocker');
    
});