window.onerror = null;
var slideIt = true;
var topMargin = 226;
var slideTime = 1200;
var ns6 = (!document.all && document.getElementById);
var ie4 = (document.all);
var ns4 = (document.layers);
function layerObject(id,left) {
if (ns6) {
this.obj = document.getElementById(id).style;
this.obj.left = left+280;
return this.obj;
}
else if(ie4) {
this.obj = document.all[id].style;
this.obj.left = left+280;
return this.obj;
}
else if(ns4) {
this.obj = document.layers[id];
this.obj.left = left+280;
return this.obj;
   }
}
function layerSetup() {
floatLyr = new layerObject('floatLayer', pageWidth * .5);
window.setInterval("main()", 10)
}
function floatObject() {
if (ns4 || ns6) {
findHt = window.innerHeight;
} else if(ie4) {
findHt = document.body.clientHeight;
   }
}
function main() {
if (ns4) {
this.currentY = document.layers["floatLayer"].top;
this.scrollTop = window.pageYOffset;
mainTrigger();
}
else if(ns6) {
this.currentY = parseInt(document.getElementById('floatLayer').style.top);
this.scrollTop = scrollY;
mainTrigger();
} else if(ie4) {
this.currentY = floatLayer.style.pixelTop;
this.scrollTop = document.body.scrollTop;
mainTrigger();
   }
}
function mainTrigger() {
var newTargetY = (this.scrollTop > 226) ? this.scrollTop + 10 : this.scrollTop + this.topMargin;
if(!slideIt) newTargetY = 226;
if ( this.currentY != newTargetY ) {
if ( newTargetY != this.targetY ) {
this.targetY = newTargetY;
floatStart();
}
animator();
   }
}
function floatStart() {
var now = new Date();
this.A = this.targetY - this.currentY;
this.B = Math.PI / ( 2 * this.slideTime );
this.C = now.getTime();
if (Math.abs(this.A) > this.findHt) {
this.D = this.A > 0 ? this.targetY - this.findHt : this.targetY + this.findHt;
this.A = this.A > 0 ? this.findHt : -this.findHt;
}
else {
this.D = this.currentY;
   }
}
function animator() {
var now = new Date();
var newY = this.A * Math.sin( this.B * ( now.getTime() - this.C ) ) + this.D;
newY = Math.round(newY);
if (( this.A > 0 && newY > this.currentY ) || ( this.A < 0 && newY < this.currentY )) {
if ( ie4 )document.all.floatLayer.style.pixelTop = newY;
if ( ns4 )document.layers["floatLayer"].top = newY;
if ( ns6 )document.getElementById('floatLayer').style.top = newY + "px";
   }
}
function start() {
if(ns6||ns4) {
pageWidth = innerWidth;
pageHeight = innerHeight;
layerSetup();
floatObject();
}
else if(ie4) {
pageWidth = document.body.clientWidth;
pageHeight = document.body.clientHeight;
layerSetup();
floatObject();
   }
   findObj("floatLayer").style.display = "block";
}

// Locates objects on the page.
function findObj(objName, docType) {
	var i;  
	if(!docType) docType=document; 
	
	var p = objName.indexOf("?")
	if(p>0 && parent.frames.length) {
		docType=parent.frames[objName.substring(p+1)].document; 
		objName=objName.substring(0,p);
	}
	
	var explorerObject = docType[objName]
	if(!explorerObject && docType.all){ explorerObject=docType.all[objName]; }
	
	for(i=0; !explorerObject && i<docType.forms.length; i++){ explorerObject = docType.forms[i][objName]; }
	for(i=0; !explorerObject && docType.layers && i<docType.layers.length; i++) explorerObject = findObj(objName,docType.layers[i].document);
	if(!explorerObject && docType.getElementById){ explorerObject=docType.getElementById(objName); }
	
	return explorerObject;
}

//	GENERAL-PURPOSE FUNCTIONS ======================================================================
	// Formats a number (integer or float) into $#.## format -----------------------------
	function formatCurrency(num) {
		num 		= num.toString().replace(/\$|\,/g,'');
		if(isNaN(num)) 
			num 	= "0";
		var sign 	= (num == (num = Math.abs(num)));
		num 		= Math.floor((num * 100) + 0.50000000001);
		var cents 	= num % 100;
		num 		= Math.floor(num/100).toString();
		if(cents < 10) 
			cents 	= "0" + cents;
		for(var i=0; i<Math.floor((num.length - (1 + i)) / 3); i++)
			num 	= num.substring(0,num.length-(4*i+3))+','+
		num.substring(num.length-(4*i+3));
		return (((sign)?'':'-') + '$' + num + '.' + cents);
	} // EO: formatCurrency --------------------------------------------------------------
//	================================================================================================

// COOKIE FUNCTIONALITY ============================================================================
	// Sets the JScript cookie's data ----------------------------------------------------
	function setCookie(param){
		// Declarations (Break down the JSON)
		name 		= (param.name);
		value 		= (escape(param.value));														// Handle special chars
		expiration	= (param.expiration)	? param.expiration	: null;								// Allow for instant expiry
		path		= (param.path)	 		? ';path=' 			+ param.path		: ';path=/';	// Ensure the cookie's on root
		domain		= (param.domain) 		? ';domain=' 		+ param.domain		: ''; 			// Only applicable to subdomains
		secure		= (param.secure) 		? ';secure' 							: ''; 			// Only used for trans-SSL
	
		// Set up the cookie's expiration
		if(expiration != null){
			var today 			= new Date();										// Define base expiry date as today
			today.setTime(today.getTime());											// Define base expiry time as "right now"
			expiration 			= (expiration) ? expiration * 3600000 : 3600000; 	// Calculate expiry in hours (default: 1 hour)
			expiration 			= new Date(today.getTime() + (expiration));			// Add calculated expiry to "right now"
			expiration			= expiration.toGMTString();							// Convert the expiry to GMT timestamp
			expiration			= ';expiration=' + expiration;
		}
		// Construct the cookie itself
		document.cookie 	= name + "=" + value +									// Set VALUE to NAME (myCookie = 'myValue')
							  expiration +											// Expiry time (defaults to 1 hour)
							  path		 +											// The path of the cookie (defaults to the root)
							  domain 	 +											// The cookie's domain (defaults to self)
							  secure;												// Whether it's tamper-proof (defaults to false)
	} // EO: setCookie -------------------------------------------------------------------
	
	// Adds a value to the existing cookie, separated by ||| -----------------------------
	function appendCookie(param){
		var currentCookieVal = readCookie(param.name);
		var newCookieVal 	 = (currentCookieVal == null) ? param.value : currentCookieVal + '|||' + param.value;
		setCookie({name:param.name, value:newCookieVal, expiration:param.expiration, path:param.path, domain:param.domain, secure:param.secure});
		return newCookieVal;
	} // EO: appendCookie ----------------------------------------------------------------
	
	function cookieValueExists(cookieName, soughtValue){
		var cookieString = readCookie(cookieName);
		if(!cookieString)  return false;
		var retVal 		 = ((cookieString.indexOf(soughtValue) != -1) || (cookieString.indexOf(('|||' + soughtValue)) != -1) || (cookieString.indexOf((soughtValue + '|||') != -1)));
		return (retVal  != -1);
	}
	
	// Reads the cookie's data -----------------------------------------------------------
	// Note: document.cookie only returns ALL of the name=value pairs, not just the one specified
	function readCookie(cookieName){
		// Declarations
		var RC_allCookies 		= document.cookie.split(';');					// Collect and explode all cookies
		var RC_currentCookie 	= '';											// The loop's current cookie
		var RC_currentName 		= '';											// The loop's current cookie name
		var RC_currentValue 	= '';											// The loop's current cookie value

		for(i=0; i<RC_allCookies.length; i++){									// Loop through the exploded cookies
			RC_currentCookie = RC_allCookies[i].split('=');						// Split each into a name/value pair
			RC_currentName   = RC_currentCookie[0].replace(/^\s+|\s+$/g, '');	// Obtain the current cookie's name & trim
			if(RC_currentName.toUpperCase() == cookieName.toUpperCase()){		// See if this is the sought cookie
				if(RC_currentCookie.length > 1)									// If there IS a value...
					RC_currentValue = RC_currentCookie[1]; 							// Grab it
				return unescape(RC_currentValue.replace(/^\s+|\s+$/g, ''))			// And return it after cleaning it up
				break;																// Bail out of the function
			}																	// Otherwise...
			RC_currentCookie 	= null;												// Reset the cookie,
			RC_currentName 		= '';												// Reset its name,
		}																			// And try again
			return null;
	} // EO: readCookie ------------------------------------------------------------------
	
	// Deletes the cookie entirely -------------------------------------------------------
	//	Ex. 	deleteCookie({name:'r2b', path:'/'});
	function deleteCookie(param) {
		if(readCookie(param.name)) 
			document.cookie = param.name + "=" +
			((param.path) ? ";path=" + param.path : "") +
			((param.domain) ? ";domain=" + param.domain : "") +
			";expires=Thu, 01-Jan-1970 00:00:01 GMT";
	} // EO: deleteCookie ----------------------------------------------------------------
// =================================================================================================

// MINI-CART MANAGEMENT FUNCTIONALITY ==============================================================
	var totalInCart = 0;
	function purgeAll(){
		deleteCookie({name:'d2b', path:'/', domain:'.dvd2blu.com'});	
	}
	
	//deleteCookie({name:'d2b', path:'/'});	
		
	// Reads the cookie and changes the mini-cart's contents to reflect what's in it -----
	function updateMiniCart(){
		var cookieValue = readCookie('d2b');
		if(numTitles() == 0){
			findObj("cartTotal").innerHTML = formatCurrency(0);
			findObj("miniCart").innerHTML  = 'Your cart is empty.';
			deleteCookie({name:'d2b', path:'/', domain:'.dvd2blu.com'});
			setCookie({name:'d2b', value:'', expiration:1, path:'/', domain:'.dvd2blu.com'});
			return false;
		} 
		cookieValue 	= cookieValue + "";
		var cartText 	= '<table id="miniCartTable" cellpadding="0" cellspacing="0" border="0">';
		var price		= 0;
		if(cookieValue.indexOf('|||') == -1)
			cookieValue = new Array(cookieValue);
		else
			cookieValue = cookieValue.split('|||');
		
		var selProduct 	= null;
		for(var i=0; i<cookieValue.length; i++){
			if(cookieValue[i].length != 10) continue;
			selProduct = findProductById(cookieValue[i]);
			if(selProduct){
				cartText += '<tr><td class="mc1"><a href="javascript:void(0)" onClick="removeFromCart(' + selProduct[0] + ')"><img src="interface/icn_remove.gif" class="remIcon" align="absmiddle" border="0" width="9" height="11" alt="Remove this item from my cart" title="Remove this item from my cart"></a></td>' + 
							'<td class="mc2">' + selProduct[2] + '</td>' + 
							'<td class="mc3">' + formatCurrency(selProduct[6]) + '</td></tr>';
				price 	 += parseFloat(selProduct[6]);
			}
		}
		findObj("cartTotal").innerHTML = formatCurrency(price);
		findObj("miniCart").innerHTML  = cartText + "</table>";
		
		if(numTitles() >= 15) slideIt = false;
		else slideIt = true;
	} // EO: updateMiniCart --------------------------------------------------------------
	
	function numTitles() {
		var cookieString = readCookie('d2b');
		var count = 0;
		if(cookieString == null || cookieString == "" || cookieString.length == 0) return 0;
		var arr = cookieString.split('|||');
		if(arr == null || arr.length == 0) return 0;
		for(var i = 0; i < arr.length; i++) {
			var selectedTitle = findProductById(arr[i]);
			if(arr[i].length == 10 && selectedTitle != null) count++;
		}
		return count;
	}
	
	// Adds a product (by ID) to the user's cart -----------------------------------------
	function addToCart(productId, overrideCheck){
		if(activelyRotating[productId])return false;
		if(productId == "" || productId == null) return false;
		if(cookieValueExists('d2b', productId) && overrideCheck != true) return false;

		if(numTitles() >= 25) {
			alert("You have reached the maximum of 25 titles in your cart. If you would like to add more, please remove some titles from your cart first.");
			return false;
		}
		
		var btnObj = findObj("btnUpgrade" + productId);
		rotateTitle(productId); 
		var newCookieValue = appendCookie({name:'d2b', value:productId, expiration:1, domain:'.dvd2blu.com'});
		btnObj.src = 'interface/btn_upgraded.gif';
		updateMiniCart();
		totalInCart++;
		
		if(numTitles() >= 15) slideIt = false;
		else slideIt = true;
	} // EO: addToCart -------------------------------------------------------------------
	
	// Removes the specified product from the cookie & updates the mini-cart -------------
	function removeFromCart(productId){
		if(activelyRotating[productId])return false;
		var cookieString = readCookie('d2b');
		if(cookieString.indexOf(productId) == -1) return;
		
		cookieString = cookieString.replace(('|||' + productId), '');
		cookieString = cookieString.replace((productId + '|||'), '');
		cookieString = cookieString.replace(productId, '');
		cookieString = cookieString.replace('||||||', '|||');
	
		deleteCookie({name:'d2b', path:'/', domain:'.dvd2blu.com'});
		setCookie({name:'d2b', value:cookieString, expiration:1, path:'/', domain:'.dvd2blu.com'});
		updateMiniCart();
		revertTitle(productId);
		totalInCart--;
		if(numTitles() >= 15) slideIt = false;
		else slideIt = true;
	} // EO: removeFromCart --------------------------------------------------------------
	
	function removeFromCartSecure(productId) {
		var cookieString = readCookie('d2b');
		if(cookieString.indexOf(productId) == -1) return;
		
		cookieString = cookieString.replace(('|||' + productId), '');
		cookieString = cookieString.replace((productId + '|||'), '');
		cookieString = cookieString.replace(productId, '');
		cookieString = cookieString.replace('||||||', '|||');
	
		deleteCookie({name:'d2b', path:'/', domain:'.dvd2blu.com'});
		setCookie({name:'d2b', value:cookieString, expiration:1, path:'/', domain:'.dvd2blu.com'});
	}
	
	// Constucts the link to DataPak's checkout URL --------------------------------------
	function checkoutLink(){
		var selectedIds = readCookie('d2b');
		if(selectedIds == null) return false;
		var opString = '';
		if(selectedIds.indexOf('|||') == -1){
			opString = '&product_id=' + selectedIds;
		}else{
			selectedIds = selectedIds.split('|||');
			for(var i=0; i<selectedIds.length; i++){
				opString += '&product_id=' + selectedIds[i];
			}
		}
		 
		opString = "https://secure.dvd2blu.com/process?action=add_to_cart_ext" + opString;
		document.location = opString;
	} // EO: checkoutLink ----------------------------------------------------------------
	
	function populateCart(){
		try {
			var cookieValue = readCookie('d2b');
			if(cookieValue == '' || cookieValue == null) return false;
			if(cookieValue.indexOf('|||') == -1)	cookieValue = new Array(cookieValue);
			else									cookieValue = cookieValue.split('|||');
			
			for(var i=0; i<cookieValue.length; i++){
				if(cookieValue[i] == "" || cookieValue[i].length != 10) continue;
				var selectedTitle = findProductById(cookieValue[i]);
				if(selectedTitle == null) continue;
				if(selectedTitle[7] != "BLU")
					rotateTitle(cookieValue[i]);
				else
					continue;
				findObj("btnUpgrade" + cookieValue[i]).src = 'interface/btn_upgraded.gif';
				totalInCart++;
			}
			updateMiniCart();
		} catch(e) {
			//console.log(e);
		}
	}
	
	function emptyCart(){
		var cookieValue = readCookie('d2b');
		if(cookieValue == '' || cookieValue == null) return false;
		if(cookieValue.indexOf('|||') == -1)	cookieValue = new Array(cookieValue);
		else									cookieValue = cookieValue.split('|||');
		for(var i=0; i<cookieValue.length; i++)	revertTitle(cookieValue[i]);
		deleteCookie({name:'d2b', path:'/', domain:'.dvd2blu.com'});
		updateMiniCart();
		totalInCart = 0;
		slideIt = true;
	}
	
	
// =================================================================================================

// SEARCH AND FILTER FUNCTIONALITY =================================================================
   	// Hides titles not matching the user's search query ---------------------------------
	function filterTitles(){
	try{
		var foundCount	= xmlProducts.length;
		var found = 0;
		var filterTxt 	= findObj("searchField").value;
		var originalTxt	= filterTxt;
		
		filterTxt = filterTxt.toUpperCase();
		filterTxt = filterTxt.replace(/[^a-zA-Z 0-9]+/g,'');
		filterTxt = filterTxt.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
		filterTxt = filterTxt.replace(/(\s)\1+/g, ' ');
		filterTxt = filterTxt.split(' ');
		//alert(filterTxt)
		var currentTitle = null;
		
		for(var i=0; i<xmlProducts.length; i++){
			if(!xmlProducts[i]) alert('null');
			if(xmlProducts[i][0] != null){
				currentTitle 					= findObj("buyPlate" + xmlProducts[i][0] );
				if(currentTitle == null) alert("buyPlate" + xmlProducts[i][0])
				currentTitle.style.display 		= "block";
				var titValB = "" + xmlProducts[i][2];
				var titValR = "" + xmlProducts[i][3];
				
				titValB = titValB.replace(/[^a-zA-Z 0-9]+/g,'');
				titValR = titValR.replace(/[^a-zA-Z 0-9]+/g,'');
				var aMatch = true;
				var bMatch = true;
				titValR = titValR.split(' ');
				for(var j = 0; j < filterTxt.length; j++) {
					var foundIt = false;
					for(var k = 0; k < titValR.length; k++) {
						if((titValR[k].toUpperCase()).indexOf(filterTxt[j].toUpperCase()) == 0)
							foundIt = true;
					}
					if(!foundIt){ bMatch = false; break;}
					//var x = new RegExp(filterTxt[j], "i");
					//if(titValB.search(x) == -1) aMatch = false;
					//if(titValR.search(x) == -1) bMatch = false;
				}
				
				//if(titVal.toUpperCase().indexOf(filterTxt) != 0){ // Use this if matching from front
				if(!bMatch){	// Use this if matching within
					currentTitle.style.display 	= "none";
					foundCount--;
				}
				else {
					if(found%5 == 4 || found%5 == 3)
						xmlProducts[i][8] = true;
					else
						xmlProducts[i][8] = false;
					found++;
				}
			}
		}
		if(filterTxt != ""){
			findObj("filteredBy").innerHTML = "Displaying: Titles containing <b>'" + originalTxt + "'</b>";
			findObj("xOfY").innerHTML = "Displaying <b>" + foundCount + "</b> of <b>" + (xmlProducts.length) + "</b> titles.";
		}else{			
			findObj("filteredBy").innerHTML = "Displaying: <b>All Titles</b>";
			findObj("xOfY").innerHTML = defaultCount;
		}
	}catch(e){
		alert(e.description);
	}
	} // EO: filterTitles ----------------------------------------------------------------
	
	// Hides titles not beginning with any of a number of specified letters --------------
	function letterFilter(letterChain){
		letterChain = letterChain.split(',');
		var shownCount = 0;
		for(var i=0; i<xmlProducts.length; i++){
			if(xmlProducts[i][0] != null){
				currentTitle 					= findObj("buyPlate" + xmlProducts[i][0] );
				if(currentTitle == null) return;
				currentTitle.style.display 		= "none";
				var titValB = "" + xmlProducts[i][2];
				var titValR = "" + xmlProducts[i][3];
				
				for(var j=0; j<letterChain.length; j++){
					if(titValB.toUpperCase().indexOf(letterChain[j]) == 0 || titValR.toUpperCase().indexOf(letterChain[j]) == 0){
						currentTitle.style.display 	= "block";
						if(shownCount%5 == 4 || shownCount%5 == 3)
							xmlProducts[i][8] = true;
						else
							xmlProducts[i][8] = false;
						shownCount++;
					}
				}
			}
		}
		findObj("filteredBy").innerHTML = "Displaying: Titles beginning with " + (letterChain[0] + "-" + letterChain[letterChain.length-1]);
		findObj("xOfY").innerHTML = "Displaying: <b>" + shownCount + "</b> of <b>" + xmlProducts.length + "</b> titles.";
	} // EO: letterFilter ----------------------------------------------------------------
	
	// Reveals all titles and clears the Search field ------------------------------------
	function clearFilter(){
		findObj("searchField").value = "";
		filterTitles();
	} // EO: clearFilter -----------------------------------------------------------------
// =================================================================================================
