/* $Id: embedswf.js 85 2009-08-05 16:02:52Z weston $ */
(function(){
var isDebug = (/debug/.test(window.location.hash));

document.documentElement.className += ' loading-flash flash-layout';

//Add stylesheet which is enacted when Flash is embedded
//var basehostname = window.location.hostname.toLowerCase() == 'houseofantiquehardware.com' ? 'img.houseofantiquehardware.com' : window.location.hostname;
//var link = document.createElement('link');
//link.rel = 'stylesheet';
//link.type = 'text/css';
//link.href = 'http://' + basehostname + '/page-with-flash.css'; //link.href = 'http://' + basehostname + '/delay.php?' + encodeURIComponent( 'http://' + basehostname + '/page-with-flash.css' );
//document.getElementsByTagName('head')[0].appendChild(link);

var swfDistanceToTop = 0; //gets set on page load
var paddingAboveDescription = 15;
var boxes = {};
var cartURL = "http://houseofantiquehardware.com/s.nl/sc.3/.f";
var containerDiv;
var itdescr_td = document.getElementById('itdescr_td');
var lastDescriptionPosition = -1;
var swfMinHeight = 550;
var swfWidth = 815;

/**
 * This function is overritten with the logic to undo the changes made to the document
 */
function revertToHTML(){}

//Save original content that is replaced by SWF
var originalMyContent = document.getElementById('myContent').cloneNode(true);

/**
 * This function is executed by the Flash when an error occurs
 */
window.handleFlashError = function(){
	revertToHTML();
};

/**
 * This function embeds the SWF in the page when the page loads
 */
var loaded = false;
function embedswf(){
	if(loaded)
		return;
	loaded = true;

	//Calculate the offset between #prodDet_tbl and the top of the page, distance between the top of the SWF and the top of the document
	var el = document.getElementById('prodDet_tbl');
	if(el.offsetParent) {
		do {
			swfDistanceToTop += el.offsetTop;
		}
		while (el = el.offsetParent);
	}
	
	/** Add the classes to the code which will give everything the proper dimensions **/
	
	//Remove the right padding
	var tds = document.getElementById('prodDet_tbl').getElementsByTagName('td');
	for(var i = 0; i < tds.length; i++){
		tds[i].className += ' hoah_prodDet_tbl_cell'; //tds[i].style.paddingRight = 0;
	}
	
	//Spacer column
	var cell = document.getElementById('imgCol_td').nextSibling;
	while(cell){
		if(cell.nodeName.toLowerCase() == 'td'){
			cell.className += ' hoah_spacer_column'
			break;
		}
		cell = cell.nextSibling;
	}
	
	//Info boxes
	var allTables = itdescr_td.getElementsByTagName('table');
	var tables = [];
	for(var i = 0; i < allTables.length; i++){
		if(/\bmainTable\b/.test(allTables[i].className)){
			tables.push(allTables[i]);
			allTables[i].className += ' hoah_info_table';
		}
	}
	boxes = {
		features    : tables[0],
		details     : tables[1],
		description : tables[tables.length-1]
	};
	boxes.features.className += ' hoah_features_box';
	boxes.details.className += ' hoah_details_box';
	boxes.description.className += ' hoah_description_box';
	
	flashvars.yAxis = boxes.features.offsetHeight + 10 + boxes.details.offsetHeight + 20;
	boxes.description.style.top = (flashvars.yAxis + 10) + 'px';
	
	//Embed the swf
	if(window.location.hash.indexOf('preventPriceProxy') == -1)
		flashvars.pricePath = flashvars.pricePath.replace(/^.+?scriptlet\.nl/, "http://img.houseofantiquehardware.com/getprices-proxy.php");
	flashvars.pricePath = flashvars.pricePath.replace(/&/g, '%26');
	flashvars.path = flashvars.path.toLowerCase()
	var discountPercentMatch = window.location.hash.match(/testDiscountPercent=(\d+(?:.\d+)?)/);
	if(discountPercentMatch)
		flashvars.discountPercent = parseFloat(discountPercentMatch[1]);
	
	swfobject.embedSWF(
		"http://img.houseofantiquehardware.com/HoaH.swf",
		"myContent",
		swfWidth,
		swfMinHeight,
		"9.0.0",
		"http://img.houseofantiquehardware.com/expressInstall.swf" ,
		flashvars,
		{ //params
			wmode:'transparent',
			AllowScriptAccess:'always',
			scale:'noScale',
			salign:'TL'
		},
		{}, //attrs
		//Callback function
		function(result){
			if(!result.success){
				document.getElementById('myContent').parentNode.replaceChild(originalMyContent, document.getElementById('myContent'));
				document.documentElement.className = document.documentElement.className.replace(/\bloading-flash\b/, '').replace(/\bflash-layout\b/, '');
				return;
			}
			
			//Set the height of the container DIV so that when the children are positioned absolutely,
			//  then the height doesn't collapsediv
			containerDiv = itdescr_td.getElementsByTagName('div')[0];
			containerDiv.className += ' hoah_containerDiv';
			var containerHeight = containerDiv.offsetHeight;
			containerDiv.style.height = containerHeight + 'px';
			
			//Set the widths of the columns ////////////////////////////////////////////////////////////////////
			
			//Position the details table
			boxes.details.style.top = (swfDistanceToTop+boxes.features.offsetHeight + 10/*margin*/) + 'px';
			
			//Find the Recommended Categories box
			var h2s = boxes.description.getElementsByTagName('h2');
			for(var i = 0; i < h2s.length; i++){
				//If we found the box, then add a click handler that calls positionDescription after expansion
				if(h2s[i].parentNode.className.indexOf('expContainer') != -1){
					var callPositionDescription = function(){
						//Call it after 10 ms so that it has been expanded/collapsed
						window.setTimeout(function(){positionDescription()}, 10);
					};
					
					if(h2s[i].addEventListener)
						h2s[i].addEventListener('click', callPositionDescription, false);
					else if(h2s[i].attachEvent)
						h2s[i].attachEvent('onclick', callPositionDescription);
					break;
				}
			}
			
			//In IE, try moving the Flash right after the description so that the Flash menu will appear over the description
			if(/MSIE [678]\b/.test(navigator.userAgent)){ //if(window.location.hash.match(/try-reposition-fix/)){
				document.documentElement.className += " hoah-old-ie";
				boxes.description.parentNode.insertBefore(document.getElementById('myContent'), boxes.description.nextSibling);
			}
			
			//SWF Successfully loaded
			document.documentElement.className = document.documentElement.className + ' has-flash';
			document.documentElement.className = document.documentElement.className.replace(/\bloading-flash\b/, '');
			
			revertToHTML = function(){
				document.documentElement.className = document.documentElement.className.replace(/\bloading-flash\b/, '').replace(/\bflash-layout\b/, '');
				var contentBlock = document.getElementById('myContent');
				var parentBlock = contentBlock.parentNode;
				var relatedProductsBlock = document.getElementById('relatedProducts');
				//document.getElementById('myContent').parentNode.replaceChild(originalMyContent, document.getElementById('myContent'));
				document.getElementById('myContent').parentNode.removeChild(document.getElementById('myContent'));
				document.getElementById('imgCol_td').insertBefore(originalMyContent,document.getElementById('imgCol_td').firstChild);
				containerDiv.style.height = 'auto';
				//reset the top margin for the Baynote and Period Home Collections div back to default
				relatedProductsBlock.style.marginLop = 0;
				relatedProductsBlock.style.marginLeft = 0;
				revertToHTML = callPositionDescription = function(){};
			};
			
			//Provide a revert to HTML button 
			if(isDebug){
				var parent = document.getElementById('prodDet_td').getElementsByTagName('h1')[0];
				var button = document.createElement('button');
				button.setAttribute('type', 'button');
				button.onclick = revertToHTML;
				button.appendChild(document.createTextNode('Revert to HTML'));
				parent.appendChild(document.createTextNode(' '));
				parent.appendChild(button);
			}
			
			//window.setTimeout(function(){
			//	revertToHTML();
			//}, 2000);
			
			return;
		}
	);
};

if(document.addEventListener)
	document.addEventListener('DOMFrameContentLoaded', embedswf, false);
if(document.attachEvent){ //from jQuery
	document.attachEvent("onreadystatechange", function(){
		if ( document.readyState === "complete" ){
			embedswf();
		}
	});
}
if(window.attachEvent)
	window.attachEvent('onload', embedswf);
else
	window.addEventListener('load', embedswf, false);

/**
 * This function is called by the Flash and positions the description so that there is no whitespace
 * and so that it does not overlap any of the controls.
 * 
 */
window.positionDescription = function positionDescription(cartCtlsHeight){
	
	//Save the position that was provided
	if(cartCtlsHeight)
		lastDescriptionPosition = cartCtlsHeight;
	//If no cartCtlsHeight provided, then use the saved position
	else if(lastDescriptionPosition != -1)
		cartCtlsHeight = lastDescriptionPosition;
	//If no argument and no saved position, then abort
	else return;
	
	//Dynamically change the height of the Flash to be maximal
	var swf = document.getElementById('myContent');
	if(swf.nodeName.toLowerCase() == 'object')
		swf.height = Math.max(swfMinHeight, flashvars.yAxis + cartCtlsHeight);

	//The following functions are in the lexical scope
	// - boxes.features
	// - boxes.details
	// - boxes.description
	//Position of cart is: swfDistanceToTop + flashvars.yAxis + cartCtlsHeight
	
	//boxes.description.style.top = (swfDistanceToTop + flashvars.yAxis + cartCtlsHeight + paddingAboveDescription) + 'px';
	//alert(swfDistanceToTop + ' + ' + flashvars.yAxis  + ' + '+ cartCtlsHeight  + ' + '+ paddingAboveDescription);
	boxes.description.style.top = (swfDistanceToTop + flashvars.yAxis + cartCtlsHeight + paddingAboveDescription) + 'px';
	containerDiv.style.height = (flashvars.yAxis + cartCtlsHeight + paddingAboveDescription + boxes.description.offsetHeight/* + 75*/) + 'px';
	
	//boxes.description.style.top = (swfDistanceToTop+document.getElementById('myContent').offsetHeight) + 'px'; //717px
	//containerDiv.style.height = (document.getElementById('myContent').offsetHeight + tables.description.offsetHeight + 75 /*Recommended Cats Expanded*/) + 'px';
}



/**
 * Cross-browser way to create XHR
 */
function createXMLHttpRequest(){
	try {
		if(window.XMLHttpRequest)
			return new XMLHttpRequest();
		else {
			// use the ActiveX control for IE5.x and IE6
			try {
				return new ActiveXObject("MSXML2.XMLHTTP");
			}
			catch (e){
				return new ActiveXObject("Microsoft.XMLHTTP");
			}
		}
	}
	catch (e) {
		alert("Unable to add items to the cart. If possible, please try a different browser.");
		return null;
	}
}

/**
 * Routine that is called by Flash to add items to cart
 */
window.addItemsToCart = function addItemsToCart(items){	
	document.body.style.cursor = "wait";
	
	var pendingRequests = 0;
	var statusCodes = [];
	function handleComplete(){
		document.body.style.cursor = "";
		var swf = document.getElementById('myContent');
		
		for(var i = 0; i < statusCodes.length; i++){
			if(statusCodes[i] >= 400){
				//document.body.style.cursor = "default";
				//alert("Unable to add items to the cart. Server responded with status code " + statusCodes[i] + ". Please try again or use a different browser.");
				if(window.console && console.error)
					console.error("One of the XHR requests returned with HTTP status " + statusCodes[i]);
					
				try {
					swf.addToCartCallback(false);
				}
				catch(e){
					if(window.console && console.error)
						console.error(e);
				}
				return false;
			}
		}
		
		if(cartURL.indexOf('?') == -1)
			cartURL += '?_rand=' + (new Date()).valueOf();
		else
			cartURL += '&_rand=' + (new Date()).valueOf();
		
		try {
			swf.addToCartCallback(true);
		}
		catch(e){
			if(window.console && console.error)
				console.error(e);
		}
		
		if(window.location.hash.indexOf('openCartInNewWindow') != -1)
			window.open(cartURL);
		else if(!(window.location.hash.indexOf('confirmCartRedirect') != -1) || confirm('Item(s) added to the cart. Go to cart now?'))
			window.location = cartURL;
			
		return true;
	};
	
	var requestQueue = [];
	
	var readyStateHandler = function(){
		if(this.readyState == 4){
			//pendingRequests--;
			
			//NetSuite serves a javascript redirect to IE that must be followed to get the error;
			// actually, just re-getting window.location will display any error
			if(this.responseText.toLowerCase().indexOf('<title') == -1){
				var xhr = createXMLHttpRequest();
				xhr.open('GET', window.location.href.replace(/#.*/, '')); //if the hash isn't removed, then IE gets a 404 for some reason
				//xhr.onreadystatechange = arguments.callee;
				xhr.onreadystatechange = function(e){
					readyStateHandler.apply(xhr, [e]);
				};
				pendingRequests++;
				xhr.send(null);
			}
			//Server responded with an error (this does not happen when adding items to the cart, however)
			else if(this.status >= 400){
				statusCodes.push(this.status);
				alert("Unable to add items to the cart. Server responded with status code " + this.status + ". Please try again or use a different browser.");
			}
			//Maintenance
			//else if(/Unavailable\s+[Oo]ptions/.test(this.responseText)){
			//Unavailable options error
			else if(/Unavailable\s+[Oo]ptions/.test(this.responseText)){
				var msg = "Unavailable Options\n\n";
				var matches = this.responseText.match(/(We do not sell.+?)(?=<)/);
				if(matches)
					msg += matches[0];
				statusCodes.push(400); //bad request
				alert(msg);
			}
			//Everything ok
			else {
				document.body.appendChild(document.createTextNode('Everything ok'));
				statusCodes.push(this.status);
			}
			//if(pendingRequests == 0){
			//	handleComplete();
			//}
			
			//Kick off the next request
			if(requestQueue.length){
				var nextRequest = requestQueue.shift();
				nextRequest.xhr.send(nextRequest.body);
			}
			else {
				handleComplete();
			}
		}
	};
	
	
	for(var i = 0; i < items.length; i++){
		(function(){
			var xhr = createXMLHttpRequest();
			
			//Open request to the cart
			xhr.open('POST', 'http://houseofantiquehardware.com/app/site/backend/additemtocart.nl');
			xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xhr.setRequestHeader('Cache-Control', 'no-cache');
			xhr.setRequestHeader('Pragma', 'no-cache');
			
			//Create the POST body for the cart
			var body;
			var pairs = [];
			for(var key in items[i]){
				pairs.push(key + '=' + encodeURIComponent(items[i][key]));
			}
			body = pairs.join('&');
			
			//Keep track of when this request completes
			//xhr.onreadystatechange = readyStateHandler; //This does not work in FF2
			xhr.onreadystatechange = function(e){
				readyStateHandler.apply(xhr, [e]);
			};
			
			////Send request
			//pendingRequests++;
			
			//xhr.send(body);
			requestQueue.push({
				xhr:xhr,
				body:body
			});
		})();
	}
	var firstRequest = requestQueue.shift();
	firstRequest.xhr.send(firstRequest.body);
	
	return true;
};

})();
