var loadingPopup;
var borbaPopup;

function closePopup() {
	if (borbaPopup) {
		borbaPopup.cancel();
		borbaPopup.destroy();
		borbaPopup = null;	
	}
}

var handleOk = function() { 
    borbaHideLoading();
    closePopup();
} 

var handleCancel = function() { 
    borbaHideLoading();
    closePopup();
} 

var forceRefresh = function() { 
	borbaHideLoading();
    closePopup();
    document.location = "?";
} 

var createAccountHandler = function(o) {
	closePopup();
	window.location = '/account/';
}

var handleCart = function() { 
	closePopup();
	window.location = "/cart/";
} 

var continueShoppingHandler = function(o) {
	closePopup();
}

// Loads the auto ship popup window. This is a dynamic AJAX call to the server.
function autoShipShow(id) {
	var callback = {
		success: function(o) {
			// Get the response
			var r = eval(o.responseText);
			if (r.response == 'success') {
				closePopup();
				borbaPopup = borbaShowPopup('autoShip', 'Auto Delivery Details', r.content, '370px', '150px');
			} else {
				alert('There was a problem showing the auto-ship window. The message is: '+r.message);
			}
		},
		failure: function(o) {
			alert('There was a problem loading the auto-ship window. The message is: '+o.responseText);
		},
		argument: []
	}
	closePopup();
	var transaction = YAHOO.util.Connect.asyncRequest('GET', '/cart/?action=custom&borba=auto_ship_popup&product_id='+id, callback, null); 
}

// Handles the click of the button "Add to Auto Ship" from the auto ship popup window.
function addToAutoShip() {
	
	// Submit the information to a custom code that adds the item to the cart and sets the auto ship information in there, too. 
	var params = '&product_id='+document.getElementById('auto_ship_product_id').value;
	params += '&quantity='+document.getElementById('quantity').value;
	params += '&frequency='+document.getElementById('frequency').value;

		
	var callback = {
		success: function(o) {
			// Get the response
			var r = eval(o.responseText);
			borbaHideLoading();
			if (r.response == 'success') {
				closePopup();
				borbaPopup = borbaShowPopup('response', 'Add to Auto Delivery', r.message, '400px', '100px', null, null, false, [{ text:"Checkout", handler:handleCart }, {text:'Continue Shopping', handler: handleOk} ]);
			} else {
				alert('There was a problem adding the product to the cart. The message is: '+r.message);
			}
		},
		failure: function(o) {
			alert('There was a problem adding the product to the cart. The message is: '+o.responseText);
		},
		argument: []
	}
	borbaShowLoading('Adding product to your shopping cart. Please wait...');
	var transaction = YAHOO.util.Connect.asyncRequest('GET', '/cart/?action=custom&borba=auto_ship_save'+params, callback, null); 

}

function showAutoShip() {
	var el = document.getElementById('autodelivery');
	if (el && el.checked) {
		document.getElementById('autoship').style.display = 'block';
	} else {
		document.getElementById('autoship').style.display = 'none';
	}
}



// This function to adds a product to a wishlist via a yahoo request to our perl codebase.

function addToWishList(pid){
	
	borbaShowLoading("Adding Product to Wish List");
	var params = '&product_id='+pid;

	var callback = {
		success: function(o) {			
			// Get the response
			borbaHideLoading();
			var r = eval(o.responseText);
			closePopup();
			if (r.response == 'success') {
				borbaPopup = borbaShowPopup('response', 'Add to Wishlist', r.message, '400px', '100px', null, null, false, { text:"Continue Shopping", handler:continueShoppingHandler } );
			} else {
				if (r.create_account) {
					borbaPopup = borbaShowPopup('response', 'Add to Wishlist', r.message, '400px', '100px', null, null, false, [ { text:"Create Account", handler:createAccountHandler }, { text:"Continue Shopping", handler:continueShoppingHandler } ]);
				} else {
					borbaPopup = borbaShowPopup('response', 'Add to Wishlist', r.message, '400px', '100px', null, null, false,{ text:"Continue Shopping", handler:continueShoppingHandler });
				}
			}
		},
		failure: function(o) {			
			borbaHideLoading();
			closePopup();
			borbaPopup = borbaShowPopup('response', 'Add to Wishlist', 'An error occured while adding this item to your wish list: '+o.statusText, '400px', '100px', null, null, true,{ text:"Continue Shopping", handler:continueShoppingHandler });
		},
		argument: []
	}

	var transaction = YAHOO.util.Connect.asyncRequest('GET', '?action=custom&borba=add_to_wishlist' + params,  callback, null);
}

function removeFromWishList(pid){
	
	borbaShowLoading("Removing Product from Wish List");
	var params = '&product_id='+pid;

	var callback = {
		success: function(o) {	
			handleRemoveFromWishListResults(o);
		},
		failure: function(o) {
			handleRemoveFromWishListResults(o);
		},
		argument: []
	}

	var transaction = YAHOO.util.Connect.asyncRequest('GET', '?action=custom&borba=remove_from_wishlist' + params,  callback, null);
}

// This is the callback function for removing from a wishlist
function handleRemoveFromWishListResults(o){		
	var myResponse;
	var headtext = "Error";
	var message = "";	
	
	myResponse = eval( '(' + o.responseText + ')' );
	
	borbaHideLoading();
	
	if (myResponse.errors){
		l = myResponse.errors.length;
		for (var i = 0;i<l;++i) { 
			message += myResponse.errors[i].message+"\r\n";
		}
		headtext = 'Action Unsuccessful';
			
	} else if(o.statusText != "OK"){
		message = 'An error occured while removing this product from your wish list: '+o.statusText;
	
	} else {
		message = 'This product has been removed from your wish list. ';
		headtext = 'Product Removed';
	}	
	
	closePopup();
	borbaPopup = borbaShowPopup('response', 'Remove from Wishlist', message, '400px', '100px', forceRefresh, null, null, null);
}



function submit_pform(frm) {
	document.getElementById(frm).submit();
}

function orderProduct(id, frm, name) {
	_product_name = name;
	borbaShowLoading("Adding to Cart. Please wait...");
	//document.getElementById('ajax_message').innerHTML = 
	//	'<img src="/2008/images/ajax_loader.gif" alt="Adding product to the cart..." border="0" height="32" width="32">'+
	//	'The product is being added to your cart.';
	//document.getElementById('ajax_adding').style.display = 'block';
	//var xy = getScrollXY();
	//document.getElementById('ajax_adding').style.top = (xy[1] + 100) +'px';
	//location.hash = 'ajax_adding';
	var timestamp = new Date().getTime();
	makeXMLRequestProduct('/perl/add_product.pl?site_id=92&session_id='+readCookie('sessionid')+'&time='+timestamp+'&'+getFormValues(document.getElementById(frm)), '');
}

function removeProduct(id, frm, name) {
	_product_name = name;
	
	borbaShowLoading("Remove from Cart. Please wait...");
	//document.getElementById('ajax_message').innerHTML = 
	//	'<img src="/2008/images/ajax_loader.gif" alt="Adding product to the cart..." border="0" height="32" width="32">'+
	//	'The product is being added to your cart.';
	//document.getElementById('ajax_adding').style.display = 'block';
	//var xy = getScrollXY();
	//document.getElementById('ajax_adding').style.top = (xy[1] + 100) +'px';
	//location.hash = 'ajax_adding';
	var timestamp = new Date().getTime();
	makeXMLRequestRemoveProduct('/perl/remove_product.pl?site_id=92&session_id='+readCookie('sessionid')+'&time='+timestamp+'&'+getFormValues(document.getElementById(frm)), '');
}

function getScrollXY() {
	var scrOfX = 0, scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape compliant
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM compliant
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6 standards compliant mode
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}
	return [ scrOfX, scrOfY ];
}

function getFormValues(fobj) {
	var str = "";
	var valueArr = null;
	var val = "";
	var cmd = "";
	for (var i = 0;i < fobj.elements.length;i++) {
		switch (fobj.elements[i].type) {
			case "text":
				str += fobj.elements[i].name + "=" + escape(fobj.elements[i].value) + "&";
			break;
			case "hidden":
				str += fobj.elements[i].name + "=" + escape(fobj.elements[i].value) + "&";
			break;
			case "select-one":
				str += fobj.elements[i].name + "=" + fobj.elements[i].options[fobj.elements[i].selectedIndex].value + "&";
			break;
			case "button":
			break;
			default:
				//alert('Field type "'+fobj.elements[i].type+'" unknown.');
			break;
		}
	}
	str = str.substr(0,(str.length - 1));
	return str;
}

var xml_request_product = false;

function makeXMLRequestProduct(url, parameters) {
	xml_request_product = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		xml_request_product = new XMLHttpRequest();
		if (xml_request_product.overrideMimeType) {
			xml_request_product.overrideMimeType('text/plain');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			xml_request_product = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xml_request_product = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!xml_request_product) {
		alert('Cannot create XMLHTTP instance');
		return false;
	}
	xml_request_product.onreadystatechange = xml_handler_product;
	xml_request_product.open('GET', url + parameters);
	xml_request_product.send(null);
}

function xml_handler_product() {
	var headtext = "Action Unsuccessful";
	var message = "";	
	var handler = handleOk;
	closePopup();	

	if(xml_request_product.readyState != 4) return false;
	if(xml_request_product.status != 200) {
		message = 'We could not add the product to your cart as it returned a '+xml_request_product.status+' error!<br/>';
		borbaPopup = borbaShowPopup('response', 'Add to Cart', message, '400px', '100px', null, null, false, { 'text':"Continue Shopping", 'handler':handleOk });
		borbaHideLoading();
		return false;
	}
	
	var text = xml_request_product.responseText;
	if (!text) {
		message = 'An unexpected error happened while trying to add the product to your cart, please try again!<br/>';
		borbaPopup = borbaShowPopup('response', 'Add to Cart', message, '400px', '100px', null, null, false, { 'text':"Continue Shopping", 'handler':handleOk });
		borbaHideLoading();
		return false;
	}
	
	var lines = text.split("\n");
	if (lines[0].match(/^(\w+);(\d+);(.*);(.*)$/)) {
		if (RegExp.$2 == 2) {
			lines[0].match(/^(\w+);(\d+);(.*);(.*);(.*)$/);
			message = RegExp.$4+'<br>(estimated delivery on '+RegExp.$5+')<br/>';
			borbaPopup = borbaShowPopup('response', 'Add to Cart', message, '400px', '100px', null, null, false, { 'text':"Continue Shopping", 'handler':handleOk });
			activity = 'add_to_cart';
			extra = { product: _product_name };
			borbaHideLoading();
			return false;
		} else if (RegExp.$2 == 1) {
			if (RegExp.$4 == 'We do not have enough inventory for that item.') {
				message = 'We apologize but that item is sold out.<br/>';
				borbaPopup = borbaShowPopup('response', 'Add to Cart', message, '400px', '100px', null, null, false, { 'text':"Continue Shopping", 'handler':handleOk });
			} else {
				headtext = RegExp.$4;
				message = RegExp.$3+" has been added to your shopping cart."; //<br><br> How often would you like to receive a replenishment of "+RegExp.$3+"?<br> Click OK, click Auto Delivery, and select the period that works best for you,<br> or CHECK OUT to complete your purchase.";
				borbaPopup = borbaShowPopup('response', 'Add to Cart', message, '400px', '100px', null, null, false, [ { text:"Checkout", handler:handleCart }, { 'text':"Continue Shopping", 'handler':handleOk }]);
			}
			//location.hash = 'ajax_adding';
			borbaHideLoading();
			return false;
		} else {
			if (RegExp.$4 == 'Please select one option from each drop-down list.') {
				message = 'Please select one option from the size and color (if applicable) '+
					'drop-down before adding an item to your cart. Thank you.<br/>';
				borbaPopup = borbaShowPopup('response', 'Add to Cart', message, '400px', null, null, null, false, { 'text':"Continue Shopping", 'handler':handleOk });
			} else {
				message = 'An error happened while trying to add the product to your cart ('+RegExp.$4+'), please try again!<br/>';
				borbaPopup = borbaShowPopup('response', 'Add to Cart', message, '400px', '100px', null, null, false, { 'text':"Continue Shopping", 'handler':handleOk });
			}
			borbaHideLoading();
			return false;
		}
	} else {
		message = 'An unexpected error (#1) happened while trying to add the product to your cart, please try again!<br/>';
		borbaPopup = borbaShowPopup('response', 'Add to Cart', message, '400px', '100px', null, null, false, { 'text':"Continue Shopping", 'handler':handleOk });
		borbaHideLoading();
		return false;
	}
}

function makeXMLRequestRemoveProduct(url, parameters) {
	xml_request_product = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
		xml_request_product = new XMLHttpRequest();
		if (xml_request_product.overrideMimeType) {
			xml_request_product.overrideMimeType('text/plain');
		}
	} else if (window.ActiveXObject) { // IE
		try {
			xml_request_product = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xml_request_product = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {}
		}
	}
	if (!xml_request_product) {
		alert('Cannot create XMLHTTP instance');
		return false;
	}
	xml_request_product.onreadystatechange = xml_handler_product_remove;
	xml_request_product.open('GET', url + parameters);
	xml_request_product.send(null);
}

function xml_handler_product_remove() {
	var headtext = "Action Unsuccessful";
	var message = "";	
	var handler = handleOk;
	closePopup();	

	if(xml_request_product.readyState != 4) return false;
	if(xml_request_product.status != 200) {
		message = 'We could not remove the product from your cart as it returned a '+xml_request_product.status+' error!<br/>';
		borbaPopup = borbaShowPopup('response', 'Remove from Cart', message, '400px', '100px', null, null, false, { 'text':"Continue Shopping", 'handler':handleOk });
		borbaHideLoading();
		return false;
	}
	
	var text = xml_request_product.responseText;
	if (!text) {
		message = 'An unexpected error happened while trying to remove the product from your cart, please try again!<br/>';
		borbaPopup = borbaShowPopup('response', 'Remove from Cart', message, '400px', '100px', null, null, false, { 'text':"Continue Shopping", 'handler':handleOk });
		borbaHideLoading();
		return false;
	}
	
	var lines = text.split("\n");
	if (lines[0].match(/^(\w+);(\d+);(.*);(.*)$/)) {
		if (RegExp.$2 == 2) {
			lines[0].match(/^(\w+);(\d+);(.*);(.*);(.*)$/);
			message = RegExp.$4+'<br>(estimated delivery on '+RegExp.$5+')<br/>';
			borbaPopup = borbaShowPopup('response', 'Remove from Cart', message, '400px', '100px', null, null, false, { 'text':"Continue Shopping", 'handler':handleOk });
			activity = 'add_to_cart';
			extra = { product: _product_name };
			borbaHideLoading();
			return false;
		} else if (RegExp.$2 == 1) {
			headtext = RegExp.$4;
			message = RegExp.$3+" has been removed from your shopping cart."; //<br><br> How often would you like to receive a replenishment of "+RegExp.$3+"?<br> Click OK, click Auto Delivery, and select the period that works best for you,<br> or CHECK OUT to complete your purchase.";
			borbaPopup = borbaShowPopup('response', 'Removed from Cart', message, '400px', '100px', null, null, false, [ { 'text':"Continue Shopping", 'handler':handleOk }]);
			borbaHideLoading();
			return false;
		} else {
			if (RegExp.$4 == 'Please select one option from each drop-down list.') {
				message = 'Please select one option from the size and color (if applicable) '+
					'drop-down before adding an item to your cart. Thank you.<br/>';
				borbaPopup = borbaShowPopup('response', 'Remove from Cart', message, '400px', null, null, null, false, { 'text':"Continue Shopping", 'handler':handleOk });
			} else {
				message = 'An error happened while trying to remove the product from your cart ('+RegExp.$4+'), please try again!<br/>';
				borbaPopup = borbaShowPopup('response', 'Remove from Cart', message, '400px', '100px', null, null, false, { 'text':"Continue Shopping", 'handler':handleOk });
			}
			borbaHideLoading();
			return false;
		}
	} else {
		message = 'An unexpected error (#1) happened while trying to remove the product from your cart, please try again!<br/>';
		borbaPopup = borbaShowPopup('response', 'Remove from Cart', message, '400px', '100px', null, null, false, { 'text':"Continue Shopping", 'handler':handleOk });
		borbaHideLoading();
		return false;
	}
}

function readCookie(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 PopUp() {
// 	if (document.getElementById('popup').style.display == "none") { 
// 		document.getElementById('popup').style.visibility = "visible";
// 		document.getElementById('popup').style.display = "block";
// 	} else {
// 		document.getElementById('popup').style.visibility = "hidden";
// 		document.getElementById('popup').style.display = "none";
// 	}
// }

function view_large() {
	var left_column = document.getElementById('left_column');
	var select = document.getElementsByTagName('select');
	var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
	if (document.getElementById('view_large').style.display == 'none') {
		//first hide the other popup
		if (document.getElementById('popup')) {
			document.getElementById('popup').style.visibility = "hidden";
			document.getElementById('popup').style.display = "none";
		}
		
		//then show ours
		document.getElementById('view_large').style.display = 'block';
		
		//hide all drop downs for IE6
		if (isIE6) {
			for (var i=0; i<select.length; i++) {
				select[i].style.visibility = 'hidden';
			}
		}
	} else {
		document.getElementById('view_large').style.display = 'none';
		
		//restore all drop downs for IE6
		if (isIE6) {
			document.getElementById('product_attributes').style.visibility = 'visible';
			for (var i=0; i<select.length; i++) {
				select[i].style.visibility = 'visible';
			}
		}
	}
}
 
function left_arrow() {
	var prodMan = prod + " by " + man;
	eventTracker._trackEvent('Product', 'Product-Left-Arrow', prodMan);
}
function right_arrow() {
	var prodMan = prod + " by " + man;
	eventTracker._trackEvent('Product', 'Product-Right-Arrow', prodMan);
}

function tabselect(id){	
	$('#tabs div.content').children('div').hide();
	$('#tabs a').removeClass();
	$('#info_'+id).show();
	$('#'+id).addClass('active');
};
 
function borbaShowPopup(name, headtext, bodytext, wd, ht, ok_callback, save_callback, show_cancel, extra_buttons) {
	var newdiv = document.createElement('div');
	newdiv.setAttribute('id','popup-'+name);
	newdiv.innerHTML = '<div class="hd">'+headtext+'</div><div class="bd">'+bodytext+'</div>';
	document.body.appendChild(newdiv);

	var handleCancel = function() {
		this.cancel();
		this.destroy();
	}
	
	var mybuttons = new Array();
	if (extra_buttons) {
		if (extra_buttons.length) {
			for (i=0; i<extra_buttons.length; i++) {
				mybuttons.push(extra_buttons[i]);
			}
		} else {
			mybuttons.push(extra_buttons);	
		}
	}
	if (ok_callback) {
		mybuttons.push({ text:"OK", handler:ok_callback });
	}
	if (save_callback) {
		mybuttons.push({ text:"Save", handler:save_callback });
	}
	if (show_cancel) {
		mybuttons.push({ text:"Cancel", handler:handleCancel });
	}
	
	var newDialog = new YAHOO.widget.Dialog("popup-"+name, {
		fixedcenter: true,
		visible: false,
		width: wd,
		height: ht,
		modal: false,
		close: true,
		buttons : mybuttons,
		autofillheight: 'body',
		monitorresize: false
	} ); 

	newDialog.render(); 
	newDialog.show(); 
	return newDialog;
}

function borbaShowLoading(message) {
	borbaHideLoading();
	if (!message) {
		message = "Loading, please wait...";
	}
	loadingPopup = borbaShowPopup('pleasewait', message, '<img src="/images/rel_interstitial_loading.gif" />');
}

function borbaHideLoading() {
	if (loadingPopup) {
		loadingPopup.cancel(); 
		loadingPopup.destroy(); 
		loadingPopup = null;	
	}
}



