var ie4 = (document.all != null);
var cookieTimeout = 60; //In Seconds
var gHLBUTTONID; 
var gCallBackMethod; //function pointer that references the call back method we want to call when returnign from process mobile.

//Global Info
var sInitialButtonText = "";
var sInitialButtonContent = "";
var tAnimateTimeout = null;

//Redefine this block server side on a per language basis.
var arRedeemStates = ["Processing", "Downloading", "Redeemed"];
var arPurchaseStates = ["Processing", "Downloading", "Purchased"];
var arFreeStates = ["Processing", "Downloading", "Downloaded"];

var arrPreloadedImages = new Array();

function preloadImages(arrayName)
{
    if (document.images)
    {
        var i = 0;
        for(i=0; i<3; i++) 
	    {
            if( arrayName[i].indexOf("http") > -1 )
            {
                preload_image_object = new Image();
                var str = arrayName[i].replace("<img src='","").replace("' border='0'/>","");
                preload_image_object.src = str;
    	        arrPreloadedImages.push(preload_image_object);
            }
	    }
    }
}
  
// variables for Redeem of physical product.
var bIsRedeem = false;
var actionButtonID="";
var actionButtonText="";
var actionButtonDigitalProductID="";
var bUseSavedShippingAddress = false;
var bShippingAddressPrompt = true;
//Used to know if we refresh to update running total on Remote Postback
var bRefreshForRunningTotal;

//Current Array in use
var arCurrentState = new Array();

function setContent(name, value) {
	var d;  
	if (ie4) { 
			d = document.all[name];
	} else {
			d = document.getElementById(name);
	}
	d.innerHTML = value;
}       

function getContent(name) {
	var d;
	if (ie4) {
			d = document.all[name];
	} else {
			d = document.getElementById(name);
	}
	return d.innerHTML;
}

function setColor(name, value) {
	var d;  
	if (ie4) { 
			d = document.all[name];
	} else {
			d = document.getElementById(name);
	}
	d.style.color = value;  
}

function getColor(name) {
	var d;
	if (ie4) {
			d = document.all[name];
	} else {
			d = document.getElementById(name);
	}
	return d.style.color;
}

var sOriginalButtonContent = "";
var detect = navigator.userAgent.toLowerCase();

function animate(name, col) {

    //Animate now only works in IE due to the Dyanmic spans and divs
    if(detect.indexOf("msie") == -1)
		return;

	if(document.getElementById(name) != null)
	{
		var value = getContent(name);
		if( !value ) return;
		
		//Cache the original
		sOriginalButtonContent = value;
		
		if (value.toLowerCase().indexOf('<span') >= 0 ) { return; }
		var length = 0;
		var str = '';
		var ch;
		var token = '';
		var htmltag = false;
		for (i = 0; i < value.length; i++) {
			ch = value.substring(i, i+1);
			if (i < value.length - 1) { nextch = value.substring(i+1, i+2); } else { nextch = ' '; }
			token += ch;
			if (ch == '<' && '/aAbBpPhHiIoOuUlLtT'.indexOf(nextch) >= 0) { htmltag = true; }
			if (ch == '>' && htmltag) { htmltag = false; }
			if (!htmltag && ch.charCodeAt(0) > 30 && ch != ' ' && ch != '\n') {		
							str += '<span id="' + name + '_' + length + '">' + token + '</span>';
				token = '';
				length++;
			}
		}				
		setContent(name, str);
		command = 'animateloop(\'' + name + '\', ' + length + ', 0, 1, \'' + col + '\', 5000)';
		tAnimateTimeout = setTimeout(command , 100);
	}
}

function animateloop(name, length, ind, delta, col, count) {
	var next = ind + delta;
	if (next >= length) { delta = delta * -1; next = ind + delta; }
	if (next < 0) { delta = delta * -1; next = ind + delta; }
    setColor(name + '_' + ind, getColor(name + '_' + next));
    setColor(name + '_' + next, col);
    command = 'animateloop(\'' + name + '\', ' + length + ', ' + next + ', ' + delta + ', \'' + col + '\', ' + (count-1) + ')';
            
    if(count > 0)
		tAnimateTimeout = setTimeout(command , 100);
	else
	{
	    tAnimateTimeout = null;
	    setContent(name, sOriginalButtonContent);
	}
}

/*******************************************************************
 * Common Code
 *******************************************************************/

var LockFurtherTransactions = false; //This is the locks until we are through the transactions
var CookieJustSet = false; //This means that a cookie was just set this round don't clear it with the clear logic.

function btnAction_StateChange(hlButtonID, sOrig, sNew, bAnimate)
{    
	//debugger;
	if(sOrig != null && sNew != sOrig)
	{
	    if(tAnimateTimeout != null)
	    {
	        clearTimeout(tAnimateTimeout);	    
	        tAnimateTimeout = null;
	        setContent(hlButtonID, sOriginalButtonContent);
	    }
	
	    var spActionButton = document.getElementById(hlButtonID);   	    	    	    
	    //spActionButton.innerHTML = spActionButton.innerHTML.replace(new RegExp( sOrig.replace("$", "\\$").replace(".", "\\."), "g" ), sNew);	 	    
	    if( spActionButton != null )
	    {
	        var spActionButtonHref = spActionButton.childNodes[0];
            if( spActionButtonHref.innerHTML.indexOf("http") > -1 )
            {
		        // andy was here
		        var image = spActionButtonHref.firstChild;

		        var regExurl = new RegExp(/src=([^ ]+)/i);
		        var srcURL = regExurl.exec(sNew)[1].replace(/'/g,""); 
        		
		        //debugger;
		        //image.src = srcURL.replace(/'/g,"");

		        for(var i = 0; i < arrPreloadedImages.length; i++)
		        {
			        var preloadedImage = arrPreloadedImages[i];
			        if(preloadedImage.src == srcURL)
			        {
				        image.src = preloadedImage.src;
				        break;
			        }
		        }
		    }
		    else
		    {
		        spActionButtonHref.innerHTML = sNew;
		    }

		    //alert(image.src);
            //spActionButtonHref.innerHTML = sNew;

            if(bAnimate)
	            animate(hlButtonID, "#ff0000");
	    } 
	}
}

/*******************************************************************
 * Mobile Prompts
 *******************************************************************/
function ProcessMobilePhone()
{
    var MobilePhone = document.getElementById("txtMobilePhone");
    
    window.status = "Processing Mobile # Request";
	hideMobilePhoneDiv();

	var sDataPacket = MobilePhone.value.replace("#","") + "#" + gHLBUTTONID + "#" + document.location.href;
	RS.Execute("RemoteProcessing.aspx", "ProcessMobilePhone", sDataPacket, gCallBackMethod);
}

function ProcessMobilePassword()
{
    var MobilePhone = document.getElementById("txtMobilePhone");
    var MobilePassword = document.getElementById("txtMobilePassword");
    
    window.status = "Processing Mobile Password Request";
	hideMobilePasswordDiv();

	var sDataPacket = MobilePhone.value.replace("#","") + "#" + gHLBUTTONID + "#" + document.location.href + "#" + MobilePassword.value.replace("#","");
	RS.Execute("RemoteProcessing.aspx", "ProcessMobilePassword", sDataPacket, gCallBackMethod);
}

function ProcessTextMobilePassword()
{
    var MobilePhone = document.getElementById("txtMobilePhone");
    
    window.status = "Processing Mobile Password Text Request";
	hideMobilePasswordDiv();

	var sDataPacket = MobilePhone.value.replace("#","") + "#" + gHLBUTTONID + "#" + document.location.href;
	RS.Execute("RemoteProcessing.aspx", "ProcessTextMobilePassword", sDataPacket, gCallBackMethod);
}

//function cb_ProcessMobilePhone()
//{
//	var sResultArray = new Array();
//	sResultArray = results.split("#!#");
//	
//	window.status = "Processing Phone Response";
//	
//	hideMobilePhoneDiv();
//	
//	if(sResultArray[0] == "CellPhoneError")
//		ShowCellPhoneErrorDiv(sResultArray[1], "Processing", "Download", sResultArray[2]);
//	else if(sResultArray[0] == "Empty")
//	{
//		document.location.href = sResultArray[2];
//		ClearLastDownload();
//		//do NOT deliver CRCdownload yet, when the page loads it up should deliver it.
//		return;
//	}
//}
/*******************************************************************
 * Begin CRC Downloads
 *******************************************************************/

//Was Intialize Download
function InitD( hlButtonID, sCurrentText, DigitalProductID )
{
	if(LockFurtherTransactions)
		return;	
	
	// Setting flag to be use by prompt of shipping address
	bIsRedeem = true;
	actionButtonID = hlButtonID;
	actionButtonText = sCurrentText;
	actionButtonDigitalProductID = DigitalProductID;
	
	LockFurtherTransactions = true;
    //Remove href logic so it's not clickable
    
    if(document.getElementById(hlButtonID) == null)
	{
		RS.Execute("RemoteProcessing.aspx", "ClearCartSession", "");
		return;
	}
    
    //set the array of labels for this type
    arCurrentState = arRedeemStates;
    
    if(sCurrentText == null)
        sCurrentText = getCookie("NMP_InitialButtonText");
    
    sInitialButtonText = sCurrentText;
    setCookie("NMP_InitialButtonText", sInitialButtonText, cookieTimeout);
    
    var spActionButton = document.getElementById(hlButtonID);
    sInitialButtonContent = spActionButton.innerHTML;
    spActionButton.innerHTML = spActionButton.innerHTML.replace(/href="[^\"]*"/gi, "href=\"javascript:void(0);\"");    
	btnAction_StateChange(hlButtonID, sCurrentText, arCurrentState[0], (arCurrentState[0].indexOf("img") == -1));
	ProcessDownload(DigitalProductID, hlButtonID);
}
function ProcessDownload(DigitalProductID, hlButtonID)
{
	window.status = "Processing Download Request";
		
	var sDataPacket = DigitalProductID + "#" + hlButtonID + "#" + document.location.href + "#" + bShippingAddressPrompt + "#" +  bUseSavedShippingAddress;
	RS.Execute("RemoteProcessing.aspx", "ProcessCRCDownloadRequest", sDataPacket, cb_ProcessDownload);
}

 
function UpdateCreditCounter(iCredits)
{
    if(typeof(DecCounter) != "undefined" && DecCounter != null)
	    DecCounter(iCredits);
}

function cb_ProcessDownload(results)
{
//asdf;
	gCallBackMethod = cb_ProcessDownload;
	var sResultArray = new Array();
	sResultArray = results.split("#!#");
	
	window.status = "Download Request Successful";
    
	//Decrement only if the download was a actual redeemed
	if(sResultArray[0] == "Redeemed" || sResultArray[0] == "PreviousDownload")
	{
	    if(typeof(DecCounter) != "undefined" && DecCounter != null && typeof(sResultArray[4]) != "undefined" && sResultArray[4] != null)
		    DecCounter(sResultArray[4]);
		setTimeout("DeliverCRCDownload(\"" + sResultArray[1] + "\",\"" + sResultArray[2] + "\", \"" + sResultArray[3] + "\", 'downloadStatusDiv', 'downloadInfoDiv');", 1600);
	}
	else if(sResultArray[0] == "MobileRedeemed")
	{
        if(typeof(DecCounter) != "undefined" && DecCounter != null)
		    DecCounter(sResultArray[4]);
		setTimeout("DeliverCRCDownload(\"" + sResultArray[1] + "\",\"" + sResultArray[2] + "\", \"" + sResultArray[3] + "\", 'mobileStatusDiv', 'mobileInfoDiv');", 1600);
		RS.Execute("RemoteProcessing.aspx", "ClearCartSession", "",cb_ShowCellPhoneErrorDiv);
	}
	else if(sResultArray[0] == "EnterCellPhone")
		showMobilePhoneDiv(sResultArray[1], sResultArray[2], arCurrentState[0], "Redeemed");
	else if(sResultArray[0] == "EnterCellPhonePassword")
		showMobilePasswordDiv(sResultArray[1], sResultArray[2], arCurrentState[0], "Redeemed");
	else if(sResultArray[0] == "CellPhoneError")
		ShowCellPhoneErrorDiv(sResultArray[1], arCurrentState[0], sInitialButtonText, sResultArray[2]);
	else if(sResultArray[0] == "RedeemPhysicalProduct")
	{
		document.location.href = sResultArray[2];
		//RS.Execute("RemoteProcessing.aspx", "PageRedirect", sResultArray[2]);
		return;
	}
	else if(sResultArray[0] == "PromptShippingAddress")
	{
		var divShippingAddressPrompt = getElement('divShippingAddressPrompt');
		var lblShippingAddres = getElement('lblShippingAddres');

		divShippingAddressPrompt.style.visibility = 'visible';
		lblShippingAddres.innerHTML = sResultArray[2];
		LockFurtherTransactions = false;
		return;
	}
	else if(sResultArray[0] == "DirectRedeemPhysicalProduct")
	{
		showMobileErrorDiv(sResultArray[2], sResultArray[1]);
		if(typeof(DecCounter) != "undefined" && DecCounter != null)
			DecCounter(sResultArray[3]);
		btnAction_StateChange(sResultArray[1], arCurrentState[0], 'Redeemed', false);
		window.status = sResultArray[2];
		LockFurtherTransactions = false;
		return;
	}
	else if(sResultArray[0] == "Empty")
	{
		document.location.href = sResultArray[2];
		ClearLastDownload();
		//RS.Execute("RemoteProcessing.aspx", "PageRedirect", sResultArray[2]);
		return;
	}		
	
	//Redirect to the download
	window.status = "";
	
//	if(sResultArray.length == 8)
//		deliverPreLicense( sResultArray[5], sResultArray[6], sResultArray[7] );		
}
function showShippingAddressPrompt(sShippingAddress)
{
	var divMobileError = getElement('divShippingAddressPrompt');
	var lblMobileError = getElement('lblShippingAddres');
	
	divMobileError.style.visibility = 'visible';
	lblMobileError.innerHTML = sShippingAddress;

}
function btnYesProcessSavedShippingAddress()
{
	bUseSavedShippingAddress = true;
	bShippingAddressPrompt = false;
	
	document.getElementById('divShippingAddressPrompt').style.visibility = 'hidden';
	LockFurtherTransactions = false;
	InitD( actionButtonID, actionButtonText, actionButtonDigitalProductID );
}
function btnNoProcessSavedShippingAddress()
{
	bUseSavedShippingAddress = false;
	bShippingAddressPrompt = false;
	LockFurtherTransactions = false;
	InitD( actionButtonID, actionButtonText, actionButtonDigitalProductID )
}
function DeliverCRCDownload(hlButtonID, DownloadURL, DownloadContent, statusDiv, infoDiv)
{
	//btnAction_StateChange(hlButtonID, arCurrentState[0], arCurrentState[1], (arCurrentState[1].indexOf("img") == -1));		
	ShowJavaLinkForAlbums(DownloadURL);
	initAd(DownloadContent, statusDiv, infoDiv);
	//btnAction_StateChange(hlButtonID, arCurrentState[0], arCurrentState[1], (arCurrentState[1].indexOf("img") == -1));
	// fix this line to be same as next line but from 0 to 1 and try to use a settime to get the downloadING --> setTimeout("btnAction_StateChange(hlButtonID, arCurrentState[0], arCurrentState[1], (arCurrentState[1].indexOf(\"img\") == -1));", 100);		
	setTimeout("btnAction_StateChange(\"" + hlButtonID + "\",\"" + arCurrentState[1] + "\",\"" + arCurrentState[2] + "\", false);LockFurtherTransactions = false;", 8000);		

	btnAction_StateChange(hlButtonID, arCurrentState[0], arCurrentState[1], (arCurrentState[1].indexOf("img") == -1));		
	
	setCookie("NMP_LastDownloadFunction", "DeliverCRCDownload", cookieTimeout);
	setCookie("NMP_LastButtonID", hlButtonID, cookieTimeout);
	setCookie("NMP_InitialButtonText", sInitialButtonText, cookieTimeout);	
	setCookie("NMP_LastDownloadURL", DownloadURL, cookieTimeout);
	setCookie("NMP_LastDownloadContent", DownloadContent, cookieTimeout);
	setCookie("NMP_DeliveryPage", document.location.href, cookieTimeout);
	setCookie("NMP_AttemptCount", "1", cookieTimeout);
	CookieJustSet = true;
	
	CheckJavaWebStartVersion(DownloadURL);
	if(DownloadURL != "")
		document.location.href = DownloadURL;
} 

/*******************************************************************
 * End CRC Downloads
 *******************************************************************/

/*******************************************************************
 * Begin Free Downloads
 *******************************************************************/

function InitF( hlButtonID, sCurrentText, DigitalProductID )
{
		
	if(LockFurtherTransactions)
		return;		
	
	LockFurtherTransactions = true;
	
	if(document.getElementById(hlButtonID) == null)
	{
		RS.Execute("RemoteProcessing.aspx", "ClearCartSession", "");
		return;
	}
	
	//set the array of labels
    arCurrentState = arFreeStates;
	
	if(sCurrentText == null)
        sCurrentText = getCookie("NMP_InitialButtonText");
	
	sInitialButtonText = sCurrentText;
	setCookie("NMP_InitialButtonText", sInitialButtonText, cookieTimeout);	
	
	var spActionButton = document.getElementById(hlButtonID);
	sInitialButtonContent = spActionButton.innerHTML;
    spActionButton.innerHTML = spActionButton.innerHTML.replace(/href="[^\"]*"/gi, "href=\"javascript:void(0);\"");
	
	btnAction_StateChange(hlButtonID, sCurrentText, arCurrentState[0], (arCurrentState[0].indexOf("img") == -1));	
	ProcessFreeDownload(DigitalProductID, hlButtonID);
}

function ProcessFreeDownload(DigitalProductID, hlButtonID)
{
	window.status = "Processing Download Request";
	
	var sDataPacket = DigitalProductID + "#" + hlButtonID + "#" + document.location.href;
	RS.Execute("RemoteProcessing.aspx", "ProcessFreeDownloadRequest", sDataPacket, cb_ProcessFreeDownload);
}

function cb_ProcessFreeDownload(results)
{
    gCallBackMethod = cb_ProcessFreeDownload;
    
	var sResultArray = new Array();
	sResultArray = results.split("#!#");
	
	window.status = "Download Request Successful";
	
	//redirect (for instance: redirect to login if not already logged in on payment)
	if(sResultArray[0] == "Empty")
	{
		document.location.href = sResultArray[2];
		ClearLastDownload();
		return;
		//do NOT deliver free download yet, when the page loads it up should deliver it.
	}
	else if(sResultArray[0] == "MobileRedeemed")
		setTimeout("DeliverFreeDownload(\"" + sResultArray[1] + "\",\"" + sResultArray[2] + "\", \"" + sResultArray[3] + "\", 'mobileStatusDiv', 'mobileInfoDiv');", 1600);
	else if(sResultArray[0] == "Redeemed")
		setTimeout("DeliverFreeDownload(\"" + sResultArray[1] + "\",\"" + sResultArray[2] + "\", \"" + sResultArray[3] + "\", \"downloadStatusDiv\", \"downloadInfoDiv\");", 1600);
	else if(sResultArray[0] == "EnterCellPhone")
		showMobilePhoneDiv(sResultArray[1], sResultArray[2], arCurrentState[0], "Redeemed");
	else if(sResultArray[0] == "EnterCellPhonePassword")
		showMobilePasswordDiv(sResultArray[1], sResultArray[2], arCurrentState[0], "Redeemed");
	else if(sResultArray[0] == "CellPhoneError")
		ShowCellPhoneErrorDiv(sResultArray[1], arCurrentState[0], sInitialButtonText, sResultArray[2]);
	
	//Redirect to the download
	window.status = "";
	
//	if(sResultArray.length == 7)
//		deliverPreLicense( sResultArray[4], sResultArray[5], sResultArray[6] );
}

function DeliverFreeDownload(hlButtonID, DownloadURL, DownloadContent, statusDiv, infoDiv)
{
	btnAction_StateChange(hlButtonID, arCurrentState[0], arCurrentState[1], (arCurrentState[1].indexOf("img") == -1));	
	ShowJavaLinkForAlbums(DownloadURL);
	initAd(DownloadContent, statusDiv, infoDiv);
	setTimeout("btnAction_StateChange(\"" + hlButtonID + "\",\"" + arCurrentState[1] + "\",\"" + arCurrentState[2] + "\", false);LockFurtherTransactions = false;", 8000);
	
	setCookie("NMP_LastDownloadFunction", "DeliverFreeDownload", cookieTimeout);
	setCookie("NMP_LastButtonID", hlButtonID, cookieTimeout);
	setCookie("NMP_InitialButtonText", sInitialButtonText, cookieTimeout);	
	setCookie("NMP_LastDownloadURL", DownloadURL, cookieTimeout);
	setCookie("NMP_LastDownloadContent", DownloadContent, cookieTimeout);
	setCookie("NMP_DeliveryPage", document.location.href, cookieTimeout);
	setCookie("NMP_AttemptCount", "1", cookieTimeout);
	CookieJustSet = true;		
	
	if(DownloadURL != "")
	    document.location.href = DownloadURL;
}

/*******************************************************************
 * End Free Downloads
 *******************************************************************/

/*******************************************************************
 * Begin E-Commerce Downloads
 *******************************************************************/

function FinalizePurchase(hlButtonID, DigitalProductID)
{
    arCurrentState = arPurchaseStates;
	if(document.getElementById(hlButtonID) == null)
	{
		RS.Execute("RemoteProcessing.aspx", "ClearCartSession", "");
		return;
	}
	
	LockFurtherTransactions = true;
	window.status = "Finalizing Purchase";
	
	sInitialButtonText = getCookie("NMP_InitialButtonText");		
	btnAction_StateChange(hlButtonID, sInitialButtonText, arCurrentState[0], (arCurrentState[0].indexOf("img") == -1));	
		
	RS.Execute("RemoteProcessing.aspx", "FinalizePurchaseRequest", DigitalProductID + "#" + hlButtonID + "#" + document.location.href, cb_FinalizePurchase);
}

function cb_FinalizePurchase(results)
{
    gCallBackMethod = cb_FinalizePurchase;

	var sResultArray = new Array();
	sResultArray = results.split("#!#");
	
	if(sResultArray[0] == "FINALIZED")
	{
		window.status = "";
		
//		if(sResultArray.length == 7)
//			deliverPreLicense( sResultArray[4], sResultArray[5], sResultArray[6] );
		
		setTimeout("DeliverECDownload(\"" + sResultArray[1] + "\",\"" + sResultArray[2] + "\",\"" + sResultArray[3] + "\", 'downloadStatusDiv', 'downloadInfoDiv');", 1600);
	}
	else if(sResultArray[0] == "MOBILEPURCHASED")

		setTimeout("DeliverECDownload(\"" + sResultArray[1] + "\",\"" + sResultArray[2] + "\",\"" + sResultArray[3] + "\", 'mobileStatusDiv', 'mobileInfoDiv');", 100);


	else if(sResultArray[0] == "EnterCellPhone")
		showMobilePhoneDiv( sResultArray[1], sResultArray[2], arCurrentState[0], "Purchased");
	else if(sResultArray[0] == "EnterCellPhonePassword")
		showMobilePasswordDiv( sResultArray[1], sResultArray[2], arCurrentState[0], "Purchased");
	else if(sResultArray[0] == "CellPhoneError")
		ShowCellPhoneErrorDiv(sResultArray[1], arCurrentState[0], sInitialButtonText, sResultArray[2]);
	else if(sResultArray[0] == "Empty")
		document.location.href = sResultArray[2];
}

function InitP(hlButtonID, hlConfirmLink)
{
	if(LockFurtherTransactions)
		return;
	
	var spActionButton = document.getElementById(hlButtonID);
	var spConfirmButton = document.getElementById(hlConfirmLink);
	
	spActionButton.style.display = 'none';
	spConfirmButton.style.display = '';		
}

function ConfP(hlButtonID, hlConfirmLink, sCurrentText, DigitalProductID) 
{
	if(LockFurtherTransactions)
		return;
	
	LockFurtherTransactions = true;
	
	//set the array of labels
    arCurrentState = arPurchaseStates;
	
	if(sCurrentText == null)
        sCurrentText = getCookie("NMP_InitialButtonText");
	
	sInitialButtonText = sCurrentText;	
	setCookie("NMP_InitialButtonText", sInitialButtonText, cookieTimeout);	
	
	var spActionButton = document.getElementById(hlButtonID);
	var spConfirmButton = document.getElementById(hlConfirmLink);
	
	spActionButton.style.display = '';
	spConfirmButton.style.display = 'none';
	
	//var spActionButton = document.getElementById(hlButtonID);
	sInitialButtonContent = spActionButton.innerHTML;
    spActionButton.innerHTML = spActionButton.innerHTML.replace(/href="[^\"]*"/gi, "href=\"javascript:void(0);\"");
			
	btnAction_StateChange(hlButtonID, sCurrentText, arCurrentState[0], (arCurrentState[0].indexOf("img") == -1));		
	
	window.status = "Confirming Purchase";
	var DataPacket = DigitalProductID + "#" + hlButtonID + "#" + document.location.href;
	RS.Execute("RemoteProcessing.aspx", "ProcessECDownloadRequest", DataPacket, cb_ConfirmPurchase);
}

function cb_ConfirmPurchase(results)
{
    
    //Refresh set to true on confirm, never refresh again unless we confirm another.
    bRefreshForRunningTotal = true;
    gCallBackMethod = cb_ConfirmPurchase;

	var sResultArray = new Array();
	sResultArray = results.split("#!#");
	
	window.status = "Processing Next State";
	
	if(sResultArray[0] == "PURCHASED")
	{
		//Prelicense the file Here
		
//		if(sResultArray.length == 7)
//			deliverPreLicense( sResultArray[4], sResultArray[5], sResultArray[6] );
		
		setTimeout("DeliverECDownload(\"" + sResultArray[1] + "\",\"" + sResultArray[2] + "\",\"" + sResultArray[3] + "\", 'downloadStatusDiv', 'downloadInfoDiv');", 1600);
	}
	else if(sResultArray[0] == "MOBILEPURCHASED")
	{
		setTimeout("DeliverECDownload(\"" + sResultArray[1] + "\",\"" + sResultArray[2] + "\",\"" + sResultArray[3] + "\", 'mobileStatusDiv', 'mobileInfoDiv');", 100);
		RS.Execute("RemoteProcessing.aspx", "ClearCartSession", "",cb_ShowCellPhoneErrorDiv);
	}
	else if(sResultArray[0] == "EnterCellPhone")
		showMobilePhoneDiv( sResultArray[1], sResultArray[2], arCurrentState[0], "Confirm");
	else if(sResultArray[0] == "EnterCellPhonePassword")
		showMobilePasswordDiv( sResultArray[1], sResultArray[2], arCurrentState[0], "Confirm");
	else if(sResultArray[0] == "CellPhoneError")
		ShowCellPhoneErrorDiv(sResultArray[1], arCurrentState[0], sInitialButtonText, sResultArray[2]);
	else
		document.location.href = sResultArray[2];
}

//shows additional link in popup div for Downloading latest version of JAVA for albums only
function ShowJavaLinkForAlbums(DownloadURL)
{
    if(DownloadURL.indexOf("BulkGet") > -1)
	{
	    adTime = 90;
	}
	else
	{	    
	    document.getElementById("trDownloadJavaLink").style.display = 'none';
	}

}

function DeliverECDownload(hlButtonID, DownloadURL, DownloadContent, statusDiv, infoDiv)
{
	btnAction_StateChange(hlButtonID, arCurrentState[0], arCurrentState[1], (arCurrentState[1].indexOf("img") == -1));			
	
	
	ShowJavaLinkForAlbums(DownloadURL); 
	initAd(DownloadContent, statusDiv, infoDiv);
	setTimeout("btnAction_StateChange(\"" + hlButtonID + "\",\"" + arCurrentState[1] + "\",\"" + arCurrentState[2] + "\", false);LockFurtherTransactions = false", 8000);
	window.status = "";    
	
	setCookie("NMP_LastDownloadFunction", "DeliverECDownload", cookieTimeout);
	setCookie("NMP_LastButtonID", hlButtonID, cookieTimeout);
	setCookie("NMP_InitialButtonText", sInitialButtonText, cookieTimeout);	
	setCookie("NMP_LastDownloadURL", DownloadURL, cookieTimeout);
	setCookie("NMP_LastDownloadContent", DownloadContent, cookieTimeout);
	setCookie("NMP_DeliveryPage", document.location.href, cookieTimeout);
	setCookie("NMP_AttemptCount", "1", cookieTimeout);
	CookieJustSet = true;

   	if(DownloadURL != "")	
		document.location.href = DownloadURL;
		
    if(typeof(bIsRunningTotal) != 'undefined' && bIsRunningTotal == true && bRefreshForRunningTotal == true)          
        RS.Execute("RemoteProcessing.aspx", "RefreshRunningTotal", document.location.href,cb_RefreshRunningTotal);
    
	

				
		
}

function cb_RefreshRunningTotal(results)
{
    
    var divRunningTotal  = document.getElementById("runningTotal");   
    divRunningTotal.innerHTML = results;

}



/*******************************************************************
 * End E-Commerce Downloads
 *******************************************************************/

/*******************************************************************
 * Begin Exit Page Download Functions
 *******************************************************************/
 
function DeliverExitDownload( DownloadURL, DownloadContent, PreLicenseData, divStatus, divInfo )
{
	if(!divStatus)
	    divStatus = "downloadStatusDiv";
	    
	if(!divInfo)
	    divInfo = "downloadInfoDiv";
	
//	if(PreLicenseData != null)
//	{
//		var sPreLicenseArray = PreLicenseData.split("#!#");
//		deliverPreLicense( sPreLicenseArray[0], sPreLicenseArray[1], sPreLicenseArray[2] );
//	}
    ShowJavaLinkForAlbums(DownloadURL);
	initAd(DownloadContent, divStatus, divInfo);
	setCookie("NMP_LastDownloadFunction", "DeliverExitDownload", cookieTimeout);		
	setCookie("NMP_LastDownloadURL", DownloadURL, cookieTimeout);
	setCookie("NMP_LastDownloadContent", DownloadContent, cookieTimeout);
	setCookie("NMP_DeliveryPage", document.location.href, cookieTimeout);
	setCookie("NMP_AttemptCount", "1", cookieTimeout);
	CookieJustSet = true;
	
	setTimeout("LockFurtherTransactions = false;", 8000);
	if(DownloadURL != "")
	    setTimeout("document.location.href = \"" + DownloadURL + "\"", 800);
}
 
 /*******************************************************************
 * End Exit Page Download Functions
 *******************************************************************/

/*******************************************************************
 * Begin Last Download Functions
 *******************************************************************/

function CheckLastDownload()
{
    
	if( getCookie("NMP_DeliveryPage") != document.location.href )
	{
		//If we are not on the page we delivered the download from we can't deliver it anymore ...		
		ClearLastDownload();
	}


	if(getCookie("NMP_LastDownloadFunction") != null && !CookieJustSet)
	{
		var attempts = parseInt(getCookie("NMP_AttemptCount"));		

		if(attempts < 2)
		{
			var sDownloadURL = getCookie("NMP_LastDownloadURL");
			var DataPacket = "";			
			if((sDownloadURL != null) && (sDownloadURL != "") && (sDownloadURL.indexOf("OID=") > -1))
				DataPacket = sDownloadURL.substring(sDownloadURL.indexOf("OID=")+4, sDownloadURL.length);			
            else if((sDownloadURL != null) && (sDownloadURL != "") && (sDownloadURL.indexOf("OrderItemID=") > -1))
            {
			    DataPacket = sDownloadURL;
			
			}
			RS.Execute("RemoteProcessing.aspx", "CheckLastDownload", DataPacket, cb_CheckLastDownload);
		}
		else
		{
			ClearLastDownload();
	    }
	}
}

function cb_CheckLastDownload(results)
{	
    
	if(results == "true")	
	{
		LockFurtherTransactions = true;
		switch(getCookie("NMP_LastDownloadFunction"))
		{
			case "DeliverECDownload":
			    arCurrentState = arPurchaseStates;			
				var sLastButton = getCookie("NMP_LastButtonID");
				sInitialButtonText = getCookie("NMP_InitialButtonText");								
				btnAction_StateChange(sLastButton, sInitialButtonText, arCurrentState[0], (arCurrentState[0].indexOf("img") == -1));
				DeliverECDownload(sLastButton, getCookie("NMP_LastDownloadURL"), getCookie("NMP_LastDownloadContent"), 'downloadStatusDiv', 'downloadInfoDiv');
				break;
			case "DeliverCRCDownload":			    
			    arCurrentState = arRedeemStates;			    
				var sLastButton = getCookie("NMP_LastButtonID");
				sInitialButtonText = getCookie("NMP_InitialButtonText");				
				btnAction_StateChange(sLastButton, sInitialButtonText, arCurrentState[0], (arCurrentState[0].indexOf("img") == -1));				
				DeliverCRCDownload(sLastButton, getCookie("NMP_LastDownloadURL"), getCookie("NMP_LastDownloadContent"), 'downloadStatusDiv', 'downloadInfoDiv');
				break;
			case "DeliverExitDownload":
				DeliverExitDownload( getCookie("NMP_LastDownloadURL"), getCookie("NMP_LastDownloadContent"), null );
				break;
		}
		
		var AttemptCnt = parseInt(getCookie("NMP_AttemptCount"));
		setCookie("NMP_AttemptCount", AttemptCnt++, cookieTimeout);
	}
	else
		ClearLastDownload();
}

function ClearLastDownload()
{	
	delCookie("NMP_LastDownloadFunction");
	delCookie("NMP_LastButtonID");
	delCookie("NMP_LastDownloadURL");
	delCookie("NMP_LastDownloadContent");	
	delCookie("NMP_DeliveryPage");
	delCookie("NMP_AttemptCount");	
}

//Call This everytime!
setTimeout("CheckLastDownload();", 800);
 
 /*******************************************************************
 * End Last Download Functions
 *******************************************************************/

/*******************************************************************
 * Begin Cell Phone Entry Functions
 *******************************************************************/

function ShowCellPhoneErrorDiv(hlButtonID, sOrig, sNew, error)
{
    LockFurtherTransactions = false;
	RS.Execute("RemoteProcessing.aspx", "ClearCartSession", "", cb_ShowCellPhoneErrorDiv);
	btnAction_StateChange(hlButtonID, sOrig, sNew, false);	
	//Reset the button
	var spActionButton = document.getElementById(hlButtonID);   	    	    	    
	spActionButton.innerHTML = sInitialButtonContent;
	showMobileErrorDiv(error, hlButtonID);
}

function cb_ShowCellPhoneErrorDiv(results)
{
}

 /*******************************************************************
 * End Cell Phone Entry Functions
 *******************************************************************/
 
/*******************************************************************
 * Begin Cookie Functions
 *******************************************************************/
 
function getCookie(name)
{ 
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function setCookie(name, value, expireseconds) 
{ 
    if (expireseconds) {
		var date = new Date();
		date.setTime(date.getTime()+(parseInt(expireseconds)*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}



function delCookie (name) 
{ 
	setCookie(name,"",-1);
}

/*******************************************************************
 * End Cookie Functions
 *******************************************************************/
 
 
function getTopOffset(child, startPosition)
{
    var parent = child.offsetParent;
    if(parent)
    {
        var offset = startPosition + child.offsetTop;
        return getTopOffset(parent, offset);
    }
    else
    {
        var x = startPosition;
        return x;
    }
}

function positionDivBelowButton(div, btn)
{
    var btnTopOffset = getTopOffset(btn, 0);
    
    div.style.top = (btnTopOffset + 25) + 'px';
}

function getElement(elementID)
{
    var element = null;
    if (document.getElementById) // DOM3 = IE5, NS6
	{
		element = document.getElementById(elementID);
	}
	else if (document.layers) // Netscape 4
	{
		element = document.divMobileError;
	}
	else // IE 4
	{
		element = document.all.divMobileError;
	}
	return element;
}

function getButton(hlButtonID)
{    
    return getElement(hlButtonID);
}

function showMobilePhoneDiv(hlButtonID, errMsg, sOrig, sNew)
{    
    gHLBUTTONID = hlButtonID;
    var divMobilePhone = getElement('divMobilePhone');
    var button = hlButtonID ? getButton(hlButtonID) : null;
    var divErrorMsg = getElement('divErrMsg');
    
    if(button)
        positionDivBelowButton(divMobilePhone, button);
	
	divMobilePhone.style.visibility = 'visible';
	divErrorMsg.innerHTML = errMsg;		
	
	LockFurtherTransactions = false;
	btnAction_StateChange(hlButtonID, sOrig, sNew, false);
}

function hideMobilePhoneDiv()
{
	if (document.getElementById) // DOM3 = IE5, NS6
		document.getElementById('divMobilePhone').style.visibility = 'hidden';
	else if (document.layers) // Netscape 4
		document.divMobilePhone.visibility = 'hidden';
	else // IE 4
		document.all.divMobilePhone.style.visibility = 'hidden';
}

function showMobileErrorDiv(error, hlButtonID)
{
    var divMobileError = getElement('divMobileError');
    var lblMobileError = getElement('lblMobileError');
    var button = hlButtonID ? getButton(hlButtonID) : null;
    
    if(button)
        positionDivBelowButton(divMobileError, button);
    
    divMobileError.style.visibility = 'visible';
	
	lblMobileError.innerHTML = error;
}
function hideMobileErrorDiv()
{
	if (document.getElementById) // DOM3 = IE5, NS6
		document.getElementById('divMobileError').style.visibility = 'hidden';
	else if (document.layers) // Netscape 4
		document.divMobileError.visibility = 'hidden';
	else // IE 4
		document.all.divMobileError.style.visibility = 'hidden';
}

function showMobilePasswordDiv(hlButtonID, errMsg, sOrig, sNew)
{
    gHLBUTTONID = hlButtonID;
    
    var divMobilePassword = getElement('divMobilePassword');
    var button = hlButtonID ? getButton(hlButtonID) : null;
    
    if(button)
        positionDivBelowButton( divMobilePassword, button );
    
    divMobilePassword.style.visibility = 'visible';

    if( document.getElementById && errMsg && document.getElementById('divErrMsgMobilePassword'))
        document.getElementById('divErrMsgMobilePassword').innerHTML = errMsg;
        
    LockFurtherTransactions = false;
	btnAction_StateChange(hlButtonID, sOrig, sNew, false);
}

function hideMobilePasswordDiv()
{
	if (document.getElementById) // DOM3 = IE5, NS6
		document.getElementById('divMobilePassword').style.visibility = 'hidden';
	else if (document.layers) // Netscape 4
		document.divMobilePassword.visibility = 'hidden';
	else // IE 4
		document.all.divMobilePassword.style.visibility = 'hidden';
}

function hideCompleteProfileDiv()
{
	if (document.getElementById) // DOM3 = IE5, NS6
		document.getElementById('divCompleteProfile').style.visibility = 'hidden';
	else if (document.layers) // Netscape 4
		document.divCompleteProfile.visibility = 'hidden';
	else // IE 4
		document.all.divCompleteProfile.style.visibility = 'hidden';
}

function showCompleteProfileDiv()
{
	if (document.getElementById) // DOM3 = IE5, NS6
		document.getElementById('divCompleteProfile').style.visibility = 'visible';
	else if (document.layers) // Netscape 4
		document.divCompleteProfile.visibility = 'visible';
	else // IE 4
		document.all.divCompleteProfile.style.visibility = 'visible';
}
function hidePhoneCarrierDiv()
{
	if (document.getElementById && document.getElementById('divPhoneCarriers')) // DOM3 = IE5, NS6
		document.getElementById('divPhoneCarriers').style.visibility = 'hidden';
	else if (document.layers && document.divPhoneCarriers) // Netscape 4
		document.divPhoneCarriers.visibility = 'hidden';
	else if(document.all.divPhoneCarriers) // IE 4
		document.all.divPhoneCarriers.style.visibility = 'hidden';
}

function showPhoneCarrierDiv()
{
	if (document.getElementById) // DOM3 = IE5, NS6
		document.getElementById('divPhoneCarriers').style.visibility = 'visible';
	else if (document.layers && document.divPhoneCarriers) // Netscape 4
		document.divPhoneCarriers.visibility = 'visible';
	else if(document.all.divPhoneCarriers) // IE 4
		document.all.divPhoneCarriers.style.visibility = 'visible';
}
function showPictureDiv(fileLink)
{
    //temporary image to get the size
    // preload the image
    var tempImage = new Image();
    tempImage.src = fileLink;
    
    var command = 'showResizedPicture("' + fileLink + '");';
    setTimeout(command, 250);
}

function showResizedPicture(fileLink)
{
    var tempImage = new Image();
    tempImage.src = fileLink;
    
    var strImageTag = '<img src="'+ tempImage.src + '"';
    
    if(!tempImage.width || tempImage.width == 0 || tempImage.width > 280)
        strImageTag += ' width="280"'

    strImageTag += ' alt="Artist Photo" id="imgPicturePopUp" />'
    initAd(strImageTag, 'divPicturePopUp', 'pictureInfoDiv');
}



		 
function webstartVersionCheck(versionString)
 {
	// Mozilla may not recognize new plugins without this refresh
	navigator.plugins.refresh(true);
	// First, determine if Web Start is available
	if (navigator.mimeTypes['application/x-java-jnlp-file']) {
		// Next, check for appropriate version family
		for (var i = 0; i < navigator.mimeTypes.length; ++i) {
			pluginType = navigator.mimeTypes[i].type;
			if (pluginType == "application/x-java-applet;version=" + versionString) {
				return true;
			}
		 }
	 }
 }

function checkPlatform(string)
{
	place = detect.indexOf(string) + 1;
	return place;
}

function CheckJavaWebStartVersion(downloadURL)
{
	return;
	var sApplicationURL = downloadURL; 
	var detect = navigator.userAgent.toLowerCase();
	var windowsIE = (navigator.appName=='Microsoft Internet Explorer')?true:false;

	if (windowsIE)
	{
		document.write("<OBJECT codeBase='http://java.sun.com/update/1.6.0/jinstall-6-windows-i586.cab' classid='clsid:5852F5ED-8BF4-11D4-A245-0080C6F74284' height='0' width='0'>");
		//document.write("<PARAM name='app' VALUE='" + sApplicationURL + "'");  
		document.write("<PARAM NAME='back' VALUE='false'>");
		document.write("</OBJECT>");
		document.location.href  = sApplicationURL
	}
	if(!windowsIE)
	{
		if (webstartVersionCheck("1.5")){
			document.location.href  = sApplicationURL;
		}
		else {
			alert("Please install latest java on your computer and try your download again.");
			sleep(1000);
			document.location.href ="http://jdl.sun.com/webapps/getjava/BrowserRedirect?locale=en&host=java.com";
		}
	}
}
