// 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);
	var volumePriceCont = document.getElementById("volumePriceCont");

	select.name = "select" + variationID;
	quantity.name = "qty" + variationID;
	category.name = "category" + variationID;

	if(volumePriceCont){
		var volumePrices = volumePriceCont.getElementsByTagName("ul");
		for(var x=0; x<volumePrices.length; x++){
			volumePrices[x].style.display = "none";
			if(volumePrices[x].id.slice(11) == variationID){
				volumePrices[x].style.display = "";
			}
		}
	}
}

//changes the price based on the selected variation
function setVariationPrice(index){
	var buyPriceCont = document.getElementById("SBBuyPrice");
	var regPriceCont = document.getElementById("SBRegPrice");
	var shipping = document.getElementById("SBProductShipping");
	var html = "";
	var buyPrice = dollarList[index] +"."+ centList[index];
	var regPrice = regPriceList[index];
	var shipPrice = shipPriceList[index];
	var productCode = document.getElementById("SBProductCode");
	var buyPriceDollars = document.getElementById("buyPriceDollars");
	var buyPriceCents = document.getElementById("buyPriceCents");

	if(regPriceCont){
		if(saleList[index] == 1){
			html = "<span class=\"SBProductLabel\">Sale:</span> ";
			regPriceCont.innerHTML = "<span class=\"SBProductLabel\">Regular:</span> "+ regPrice;
		}
		else{
			html = "<span class=\"SBProductLabel\">Price:</span> ";
			regPriceCont.innerHTML = "";
		}
	}
	if(buyPriceCont){
		html += "<span id=\"SBBuyPriceCont\">"+ dollarList[index] + ".<sup>"+ centList[index] + "</sup></span>";
		buyPriceCont.innerHTML = html;
		buyPriceDollars.value = dollarList[index];
		buyPriceCents.value = centList[index];
	}

	productCode.innerHTML = productCodeList[index];

	if(shipPrice != "" && shipping){
		html = shipPrice;
		shipping.innerHTML = html;
	}
}

/** adds the 'sewn badge' to the form and adds its price to the product's price.
*/
function addSewnBadge(){
	if(document.getElementById("addBadge")){
		var badgeSelect = document.getElementById("badgeSelect");
		if(document.getElementById("addBadge").checked){
			badgeSelect.value = 1;
		}
		else{
			badgeSelect.value = 0;
		}
	}
}

//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);
		}
	}
}

// toggles a media tab
function toggleMedia(tab, tabContentAreaID, tabContentID){
	var tabContentArea = document.getElementById(tabContentAreaID);
	var tabContent = document.getElementById(tabContentID);
	var divs;
	if(tab){
		var tabs = tab.parentNode.getElementsByTagName("a");
	}

	if(tabContentArea && tabContent){
		divs = $(tabContentAreaID).getElementsByTagName("div");
		for(var x=0; x<divs.length; x++){
			if(divs[x].id.slice(0, 7) == "Product"){
				if(divs[x].id == tabContentID){
					divs[x].style.display = "";
				}
				else{
					divs[x].style.display = "none";
				}
			}
		}

		// deactivate whichever tab was active before
		if((tab) && (tabs)){
			for(var i=0; i < tabs.length; i++){
				if(tabs[i].className.indexOf("active") > -1){
					tabs[i].className = "";
				}
			}
			tab.className = "active";
		}
	}
}

/** shows the selected video's div.
*/
function showVideo(parentID, videoID){
	var divs;

	if($(parentID)){
		divs = $(parentID).getElementsByTagName("div");
		for(var x=0; x<divs.length; x++){
			if(divs[x].id == videoID){
				divs[x].style.display = "";
			}
			else{
				divs[x].style.display = "none";
			}
		}
	}
}

/* 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.lastIndexOf("?" + this.preCheck) > -1) || (loc.lastIndexOf("&" + this.preCheck) > -1)){
			expandCart();
		}
	}
}

function expandCart(){
	if($('cartWrapper')){
		if($jq("#cartWrapper").css("display") == "none"){
			$jq("#cartWrapper").show("normal");
			//$jq("#cartWrapper").animate({height: "100%"}, "normal");
		}
		else{
			//$jq("#cartWrapper").animate({height: "0%"}, "normal");
			$jq("#cartWrapper").hide("normal");
		}
	}
}

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 a product to cart.
If a sewing association cookie is set, sets the sewProducts cookie to link them as sewn together.
*/
function addProduct(form, productID, badgeType){
	var submitForm = true;
	var sewnBadge = false;
	if(document.getElementById("addBadge")){
		if(document.getElementById("addBadge").checked){
			document.getElementById("badgeQty").value = document.getElementById("qty" + productID).value;
			document.getElementById("sewProducts").value = 1;
			sewnBadge = true;
		}
		else{
			document.getElementById("sewProducts").value = 0;
		}
	}
	if(document.getElementById("badgeTextCont") || sewnBadge){
		submitForm = checkBadgeText(productID, badgeType, sewnBadge);
	}
	if(submitForm){
		form.submit();
	}
}

/** checks if all the badge text boxes are empty and alerts the user.
*/
function checkBadgeText(productID, badgeType, sewnBadge){
	var hasEmpty = 0;
	if(sewnBadge){
		var embroideredText = document.getElementById("embroideredText");
		if(embroideredText){
			if(embroideredText.value == ""){
				hasEmpty++;
			}
		}
	}
	else{
		var table = document.getElementById("multipleTextTable");
		var inputs = table.getElementsByTagName("input");
		var singleBadgeText = document.getElementById("singleBadgeText");
		var textOptions;
		var singleText = true;
		
		var threadColour = document.getElementById("threadColour");
		var insignia = document.getElementById("insignia");
		var insigniaLocation = document.getElementById("insigniaLocation");
		var missingOptions = false;
		
		if(threadColour){
			//If this option is hidden, don't check if it is filled out or not
			if(threadColour.value == "" && threadColour.parentNode.style.display != "none"){
				missingOptions = true;
			}
		}
		
		if(insignia){
			//If this option is hidden, don't check if it is filled out or not
			if(insignia.value == "" && insignia.parentNode.style.display != "none"){
				missingOptions = true;
			}
		}
		
		if(insigniaLocation){
			//If this option is hidden, don't check if it is filled out or not
			if(insigniaLocation.value == "" && insigniaLocation.parentNode.style.display != "none"){
				missingOptions = true;
			}
		}
		
		if(missingOptions){
			return alert("You have not entered all the options for your " + badgeType + ". Please fill out all the options.");
		}

		if(singleBadgeText){
			textOptions = singleBadgeText.getElementsByTagName("input");
			for(var x = 0; x < textOptions.length; x++){
				if(textOptions[x].type == "radio"){
					if((textOptions[x].value == 1) && (textOptions[x].checked)){
						singleText = false;
					}
				}
			}
		}

		if((inputs.length == 0) || (singleText)){
			var input = document.getElementById("embroideredText" + productID);
			if(input){
				if(input.value == ""){
					hasEmpty++;
				}
			}
		}
		else{
			for(var x = 0; x < inputs.length; x++){
				if(inputs[x].value == ""){
					hasEmpty++;
				}
			}
		}
	}

	if(hasEmpty > 0){
		if(hasEmpty == 1){
			return confirm("You have not entered text for your " + badgeType + ". Do you still want to add to cart?");
		}
		else{
			return confirm("You have not entered text for all of your " + badgeType + "s. Do you still want to add to cart?");
		}
	}
	return true;
}

/** links to the 'sew onto' page for a product and sets a cookie to indicate whether to sew the current product onto a resultant 'sew onto' product if it's added.
*/
function viewSewing(url){
	if(sewingProductID > 0){
		setCookie("sewingProductID", sewingProductID, 0, "/", "");
	}
	if(sewingBadgeID > 0){
		setCookie("sewingBadgeID", sewingBadgeID, 0, "/", "");
	}
	window.location = url;
}

/** links to the 'sew onto' page for a product and sets a cookie to indicate whether to sew the current product onto a resultant 'sew onto' product if it's added.
*/
function viewCartSewing(url, sewToProduct, productID){
	if(sewToProduct == 1){
		setCookie("sewingProductID", productID, 0, "/", "");
	}
	else{
		setCookie("sewingBadgeID", productID, 0, "/", "");
	}
	window.location = url;
}

/** submits a form to auto-update changes to sewing quantities.
*/
function updateSewing(orderProductID, sewingProductID, quantity){
	var form = document.getElementById("programForm");
	var orderProductInput = document.getElementById("workingOrderProductID");
	var action = document.getElementById("programForm_action");
	var sewingProductInput = document.getElementById("workingSewingProductID");
	var quantityInput = document.getElementById("quantity");

	orderProductInput.value = orderProductID;
	action.value = "updateSewing";
	sewingProductInput.value = sewingProductID;
	quantityInput.value = quantity;

	form.submit();
}

/** submits a form to remove all products sewn to the given order product.
*/
function removeSewing(orderProductID){
	var form = document.getElementById("programForm");
	var orderProductInput = document.getElementById("workingOrderProductID");
	var action = document.getElementById("programForm_action");

	orderProductInput.value = orderProductID;
	action.value = "removeSewing";

	form.submit();
}

/** check to display the option for entering text on the multiple badges.
*/
function checkMultipleBadges(input, productID){
	var sameText = document.getElementById("sameText");
	var differentText = document.getElementById("differentText");
	var multipleTextTable = document.getElementById("multipleTextTable");
	var differentTextInputs = differentText.getElementsByTagName("input");
	var embroideredText = document.getElementById("embroideredText" + productID);

	createBadgeTexts(productID);

	if(parseInt(input.value) > 1){
		sameText.style.display = "";
		differentText.style.display = "";
		if(differentTextInputs[0].checked == 1){
			multipleTextTable.style.display = "";
			embroideredText.style.display = "none";
		}
	}
	else{
		sameText.style.display = "none";
		differentText.style.display = "none";
		multipleTextTable.style.display = "none";
		embroideredText.style.display = "";
	}
}

/** check to display the section for enter in text for multiple badges.
*/
function splitBadgeText(input, productID){
	var multipleTextTable = document.getElementById("multipleTextTable");
	var embroideredText = document.getElementById("embroideredText" + productID);

	if(input.value == 1){
		multipleTextTable.style.display = "";
		embroideredText.style.display = "none";
	}
	else{
		multipleTextTable.style.display = "none";
		embroideredText.style.display = "";
	}
}

/** manage the # of text inputs based on the quantity entered.
*/
function createBadgeTexts(productID){
	var table = document.getElementById("multipleTextTable");
	var quantity = parseInt(document.getElementById("qty"+ productID).value);
	var inputs = table.getElementsByTagName("input");
	var html = "";
	var cellLength = 0;
	var table;
	var cell;
	var row;

	if(inputs.length > quantity){
		var x = inputs.length;
		for(var y=(table.rows.length - 1); y>=parseInt(quantity/3); y--){
			for(var i=2; i>=0; i--){
				if((table.rows[y].cells[i].getElementsByTagName("input").length == 1) && (x > quantity)){
					table.rows[y].cells[i].innerHTML = "";
					x--;
				}
			}
			if(quantity <= (y * 3)){
				table.deleteRow(y);
			}
		}
	}
	else if(inputs.length < quantity){
		var x = 0;

		// fill in any empty cells
		if(table.rows.length > 0){
			x = (table.rows.length - 1) * 3;
			for(var y=0; y<table.rows[table.rows.length - 1].cells.length; y++){
				if((x >= inputs.length) && (x < quantity)){
					html = "<input type=\"text\" name=\"embroideredText"+ productID +"_"+ (x + 1) +"\" value=\"\" />";
					table.rows[table.rows.length - 1].cells[y].innerHTML = html;
				}
				x++;
			}
		}

		// add to the table structure.
		while(x < quantity){
			row = table.insertRow(x/3);
			for(var i=0; i<3; i++){
				cell = document.createElement("td");
				row.appendChild(cell);
				if(x < quantity){
					cell.innerHTML = "<input type=\"text\" name=\"embroideredText"+ productID +"_"+ (x + 1) +"\" value=\"\" />";
				}
				x++;
			}
		}
	}
}

/*
 * Allow for a video link to exist within the StoreBox description that will switch to the video tab
 */
attachToVideoLink = function() {
  videoLinkElement = document.getElementById('videoLink');
  if(videoLinkElement){
    Event.observe(videoLinkElement, "click", onVideoLinkClick, false);
  }
}

onVideoLinkClick = function(){
  videoLinkTab = document.getElementById('ProductVideoGenericTab');
  toggleMedia(videoLinkTab, 'mediaContent', 'ProductVideoGeneric')
  
  return false;
}

Event.observe(window, 'load', attachToVideoLink, false);