// Cookie JavaScript Functions for StoreBox Enterprise Edition
// Copyright Acro Media Inc. 1998-2004, www.acromediainc.com

// getCookie
// retrieve a cookie
function getCookie(name) {
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = 0 + dc.indexOf(prefix);
	if (begin == -1){
		return 0;
	}
	begin += prefix.length;
	var end = 0 + document.cookie.indexOf(";", begin);
	if (end == -1){
		end = dc.length;
	}
	return unescape(dc.substring(begin, end));
}

// setCookie
// set a cookie
function setCookie(name, value, expires, path, domain, secure){
	var curCookie = name + "=" + escape(value) +
			((expires) ? "; expires=" + expires.toGMTString() : "") +
			((path) ? "; path=" + path : "") +
			((domain) ? "; domain=" + domain : "") +
			((secure) ? "; secure" : "");
	document.cookie = curCookie;
}

// asCurrency
// reformats a number as a two decimal place number
function asCurrency(price){
	var result;
	//although doing *100 will add the .00, it will also lose precision, use 10000 to keep precision
	var dollars = parseInt(parseFloat(price) * 10000);
	dollars = parseFloat(dollars/10000);

	var cents = parseInt(((dollars - parseInt(dollars))*100)+0.50000000001);
	if(cents<10){
		cents = "0" + cents;
	}
	result = "$"+parseInt(dollars)+"."+cents;

	return result;
}

// setup the referral tracking
var SB_startURL = document.URL.indexOf("://") + 3;
var SB_endURL = document.URL.indexOf("/", SB_startURL);
var SB_currentURL = document.URL.substr(SB_startURL, SB_endURL - SB_startURL);
var SB_entryPoint = document.referrer;

SB_currentURL.toLowerCase();
SB_entryPoint.toLowerCase();

if(SB_entryPoint.indexOf(SB_currentURL) == -1 && SB_currentURL.indexOf("storebox") == -1){
	setCookie("StoreBox_referrer", document.referrer, 0, "/", "");
}

// Within STRING, replace any MATCHing string with the REPLACEMENT.
function substitute(string, match, replacement){
        var result = '';
        var index = 0;
        var lastIndex = index;
        while(string.length > lastIndex){
                index = string.indexOf(match, lastIndex);
                if(index == -1){
                        break;
                }

                result += string.substring(lastIndex, index) + replacement;
                lastIndex = index + match.length;
        }
        result += string.substring(lastIndex, string.length);

        return result;
}

//checkValue
//enters 1 into quantity or clears it when checkbox is checked/cleared
function checkValue(name){
	if(document.forms.programForm[name].value == ""){
		document.forms.programForm[name].value = "1";
	}
	else{
		document.forms.programForm[name].value = "";
	}
}

//checkBox
//checks box when a value is entered into the box, clears it when it is cleared
function checkBox(name, otherName){
	if(document.forms.programForm[otherName].value == ""){
		document.forms.programForm[name].checked = false;
	}
	else{
		document.forms.programForm[name].checked = true;
	}
}

//setVariation
//changes the name of the hidden 'select' input to match the selected variation
function setVariation(productID, variationID){
	var select = document.getElementById("select" + productID);
	var quantity = document.getElementById("qty" + productID);
	var category = document.getElementById("category" + productID);
	select.name = "select" + variationID;
	quantity.name = "qty" + variationID;
	category.name = "category" + variationID;
}

//changes the price based on the selected variation
function setVariationPrice(index, languageCode){
	var buyPriceCont = document.getElementById("SBBuyPrice");
	var regPriceCont = document.getElementById("SBRegPrice");
	var shipping = document.getElementById("SBProductShipping");
	var html = "";
	var regPrice = regPriceList[index];
	var shipPrice = shipPriceList[index];
	var productCode = document.getElementById("SBProductCode");
	var productAvailability = document.getElementById("SBProductAvailability");

	if(regPriceCont){
		if(saleList[index] == 1){
			if(languageCode == "fr"){
				html = "VENTE ";
			}
			else{
				html = "SALE ";
			}
			regPriceCont.innerHTML = "regular: "+ regPrice;
		}
		else{
			if(languageCode == "fr"){
				html = "prix ";
			}
			else{
				html = "price ";
			}
			regPriceCont.innerHTML = "&nbsp;";
		}
	}
	if(buyPriceCont){
		html += dollarList[index] + centList[index];
		buyPriceCont.innerHTML = html;
	}

	productCode.innerHTML = productCodeList[index];
	productAvailability.innerHTML = stockStatusList[index];

	if(shipPrice != "" && shipping){
		html = shipPrice;
		shipping.innerHTML = html;
	}
}

//create an array based on arguments
function initArray(){
	this.length = initArray.arguments.length;
	for(var i=0;i<= this.length; i++){
		this[i] = initArray.arguments[i];
	}
}

//SBDrawMenu
function SBDrawMenu(){
	var hasContentCont = false;
	var contentCont;
	var hasMenuCont = false;
	var menuCont;
	if(document.getElementById("SBJSMenuContent")){
		hasContentCont = true;
		contentCont = document.getElementById("SBJSMenuContent");
	}
	if(document.getElementById("SBJSMenu")){
		hasMenuCont = true;
		menuCont = document.getElementById("SBJSMenu");
	}
	if(hasMenuCont){
		if(hasContentCont){
			menuCont.innerHTML = contentCont.innerHTML;
		}
		else{
			SBDrawMenuContent(menuCont);
		}
	}
}

/* addLoadEvent
************
add another event to the window.onload  event
*/
function addLoadEvent(newOnload){
  var oldOnload = window.onload;
  if(typeof window.onload != 'function'){
    window.onload = newOnload;
  }
  else{
    window.onload = function(){
      if(oldOnload){
        oldOnload();
      }
      newOnload();
    }
  }
}

var runFromUrl = {
	preCheck:"updateCart",
	init: function(){
		var loc = String(document.location.search);
		if(loc.indexOf(this.preCheck) < 0){
			return;
		}
		if(loc.substring(loc.lastIndexOf("?")+1) == this.preCheck){
			expandCart();
		}
	}
}

function expandCart(){
	if(cartAni){
		if(cartAni.el.style.opacity == 0){
			document.getElementById('cartWrapper').style.display = "block";
		}
		cartAni.toggle();
	}
}

var newWin;
/** opens a popup window.
*/
function openUp(windowURL, windowWidth, windowHeight, windowName){
	var topPos = "";
	var leftPos = "";
	if(!windowWidth) windowWidth = 0;
	if(!windowHeight) windowHeight = 0;
	if(!windowName) windowName = "acromedia";
	var regEx = new RegExp("\\s", "g");
	windowName = windowName.replace(regEx, "");

	if(windowWidth == 0){
		if(screen){
			windowWidth = screen.availWidth -10;
		}
		else{
			windowWidth = 790;
		}
		leftPos = ",left=0";
	}
	if(windowHeight == 0){
		if(screen){
			windowHeight = screen.availHeight -30;
		}
		else{
			windowHeight = 790;
		}
		topPos = ",top=0";
	}


	newWin = window.open(windowURL,windowName,"toolbar=no,menubar=0,width="+windowWidth+",height="+windowHeight+topPos+leftPos+",scrollbars=no,resizable=no");

	setTimeout('newWin.focus();',100);
}


/** Adds the current product to the recen products list, and keeps the recent products cookie up to date.
*/
function setRecentProduct(productName){
	var recentProducts = getCookie("StoreBox_recentProducts");
	var cookieValue = productName +";"+ document.URL;
	var expires = new Date();
	expires.setTime(expires.getTime() + 3E11);   // about 10 years = "forever"

	if(recentProducts != ""){
		var products = recentProducts.split("|");
		var count = 0;
		var x = 0;
		var found = false;
		var name = "";

		do{
			pos = products[x].lastIndexOf(";");
			name = products[x].slice(0, pos);
			if(name != productName){
				cookieValue += "|"+ products[x];
				count++;
			}
			// only grab the first 2 (0, 1)
			if(count == 2 || x == products.length - 1){
				found = true;
			}
			x++;
		}while(!found);
	}
	setCookie("StoreBox_recentProducts", cookieValue, expires, "/", "");
}

/** displays the recent products list.
*/
function displayRecentProducts(){
	var recentProducts = getCookie("StoreBox_recentProducts");
	var html = "";
	var name = "";
	var href = "";
	var pos = 0;

	if(document.getElementById('recentlyViewedCont') && document.getElementById('noRecentProducts')){

		document.getElementById('noRecentProducts').style.display = "none";

		if(recentProducts != ""){
			var products = recentProducts.split("|");
			if(products.length > 0){
				html = "<ul>";
				for(var x=0; x<products.length; x++){
					pos = products[x].lastIndexOf(";");
					name = products[x].slice(0, pos);
					href = products[x].slice(pos+1);

					html += "<li><a href='"+ href +"'>"+ name +"</a></li>";
				}
				html += "</ul>";
			}
			document.getElementById('recentlyViewedCont').innerHTML = html;
		}
		else{
			document.getElementById('noRecentProducts').style.display = "block";
		}
	}
}

/** toggle the state of the recently viewed products 'popup'
*/
function toggleRecentlyViewed(){
	if(document.getElementById('recentlyViewedProducts')){
		if(document.getElementById('recentlyViewedProducts').style.display == "none" || document.getElementById('recentlyViewedProducts').style.display == ""){
			document.getElementById('recentlyViewedProducts').style.display = "block";
			displayRecentProducts();
		}
		else{
			document.getElementById('recentlyViewedProducts').style.display = "none";
		}
	}
}

/** toggle the state of the recently viewed products 'popup'
*/
function toggleRemindMe(){
	if(document.getElementById('remindMeCont')){
		if(document.getElementById('remindMeCont').style.display == "none" || document.getElementById('remindMeCont').style.display == ""){
			document.getElementById('remindMeCont').style.display = "block";
		}
		else{
			document.getElementById('remindMeCont').style.display = "none";
		}
	}
}


/** toggle the state of the recently viewed products 'popup'
*/
function toggleAccount(){
	if(document.getElementById('accountPopup')){
		if(document.getElementById('accountPopup').style.display == "none" || document.getElementById('accountPopup').style.display == ""){
			document.getElementById('accountPopup').style.display = "block";
		}
		else{
			document.getElementById('accountPopup').style.display = "none";
		}
	}
}

/** toggle the state of the recently viewed products 'popup'
*/
function toggleAccountForms(containerName){
	var otherContainer = "";

	if(containerName == "login"){
		otherContainer = "createAccount";
	}
	else{
		otherContainer = "login";
	}
	document.getElementById(containerName +"Link").className = "noLink";
	document.getElementById(otherContainer +"Link").className = "";

	if(document.getElementById(containerName +'Cont')){
		if(document.getElementById(containerName +'Cont').style.display == "none" || document.getElementById(containerName +'Cont').style.display == ""){
			document.getElementById(containerName +'Cont').style.display = "block";
			document.getElementById(otherContainer +'Cont').style.display = "none";
		}
		else{
			document.getElementById(otherContainer +'Cont').style.display = "none";
		}
	}
}


/** determines method of sending AJAX request - using jQuery, or using prototype.
*/
function sendAjaxRequest(formName){
	document.getElementById('messageBox').className = "";
	document.getElementById('messageBox').style.display = "none";
	//if(window['sendAjaxJQuery']){
	if ($ == jQuery){
		sendAjaxJQuery(formName);
	}
	else{
		sendAjaxPrototype(formName);
	}
}

/** sends the email product data form to the ajax processor.
*/
function sendAjaxPrototype(formName){
	var action = "";

	// since 'action' is a form element, loop through the attributes to get the form's submit action
	for(var x=0; x<document.getElementById(formName).attributes.length; x++){
		if(document.getElementById(formName).attributes[x].name == "action"){
			action = document.getElementById(formName).attributes[x].value;
			break;
		}
	}

	var myAjax = new Ajax.Request(action, {method: 'post', parameters: Form.serialize(document.getElementById(formName)), onComplete: window[formName + "Response"]});
}

/** handles the response from adding a product to favourites.
*/
function favouriteFormResponse(xmlResponse){
	var response = xmlResponse.responseXML.getElementsByTagName("response");
	var success;
	var errors;
	var message = "";
	var comma = "";

	if(response.length > 0){
		errors = response[0].getElementsByTagName("error");
		success = response[0].getElementsByTagName("success");
		if(success.length > 0){
			message = success[0].getAttribute("message");
			document.getElementById('accountPopup').style.display = "none";
		}
		else{
			for(var x=0; x<errors.length; x++){
				message += comma + errors[x].firstChild.nodeValue;
				comma = "<br />";
			}
			document.getElementById('messageBox').className = "failure";
		}
		document.getElementById('messageBox').innerHTML = message;
		document.getElementById('messageBox').style.display = "block";
	}
}


/** handles the response from sending a product email.
*/
function emailFormResponse(xmlResponse){
	var response = xmlResponse.responseXML.getElementsByTagName("response");
	var success;
	var errors;
	var message = "";
	var comma = "";

	if(response.length > 0){
		errors = response[0].getElementsByTagName("error");
		success = response[0].getElementsByTagName("success");
		if(success.length > 0){
			message = success[0].getAttribute("message");
			document.getElementById('remindMeCont').style.display = "none";
		}
		else{
			for(var x=0; x<errors.length; x++){
				message += comma + errors[x].firstChild.nodeValue;
				comma = "<br />";
			}
			document.getElementById('messageBox').className = "failure";
		}
		document.getElementById('messageBox').innerHTML = message;
		document.getElementById('messageBox').style.display = "block";
	}
}

/** handles the response from adding a product to favourites.
*/
function loginFormResponse(xmlResponse){
	var response = xmlResponse.responseXML.getElementsByTagName("response");
	var success;
	var errors;
	var message = "";
	var comma = "";


	if(response.length > 0){
		errors = response[0].getElementsByTagName("error");
		success = response[0].getElementsByTagName("success");
		if(success.length > 0){
			message = success[0].getAttribute("message");
		}
		else{
			for(var x=0; x<errors.length; x++){
				message += comma + errors[x].firstChild.nodeValue;
				comma = "<br />";
			}
			document.getElementById('messageBox').className = "failure";
		}
		document.getElementById('messageBox').innerHTML = message;
		document.getElementById('messageBox').style.display = "block";
	}
	if(errors.length == 0){
		sendAjaxRequest('favouriteForm');
	}
}

/** handles the response from adding a product to favourites.
*/
function createAccountFormResponse(xmlResponse){
	var response = xmlResponse.responseXML.getElementsByTagName("response");
	var success;
	var errors;
	var message = "";
	var comma = "";

	if(response.length > 0){
		errors = response[0].getElementsByTagName("error");
		success = response[0].getElementsByTagName("success");
		if(success.length > 0){
			message = success[0].getAttribute("message");
		}
		else{
			for(var x=0; x<errors.length; x++){
				message += comma + errors[x].firstChild.nodeValue;
				comma = "<br />";
			}
			document.getElementById('messageBox').className = "failure";
		}
		document.getElementById('messageBox').innerHTML = message;
		document.getElementById('messageBox').style.display = "block";
	}
	if(success.length > 0){
		sendAjaxRequest('favouriteForm');
	}
}

function isLoggedIn(){
	var customerID = getCookie("StoreBox_customerID");
	if(customerID != ""){
		sendAjaxRequest('favouriteForm');
	}
	else{
		document.getElementById('accountPopup').style.display = "block";
	}
}

if(typeof(Event) == 'object' && typeof(Event.observe) == 'function' && typeof(jQuery) == 'function'){
	Event.observe(window, 'load', function(){
		jQuery('.benefit-header').click(function(){
			toggleBenefits(this);
		});
	});
}

function toggleBenefits(elem){
	var found = false;
	jQuery(".benefit-content").each(function(){
		jQuery(this).parent(".benefit-header").each(function(header){
			if(this == elem){
				found = true;
			}
		});
		if(!found){
			jQuery(this).hide();
		}
	});
	jQuery(".benefit-header").each(function(){
		if(this != elem){
			jQuery(this).removeClass("active");
		}
	});
	jQuery(elem).children(".benefit-content").toggle();
	jQuery(elem).toggleClass("active");
}
