//****************CART functions

var cart = new Array();
var cartCookieName = 'jmbamboo_cart_cookie';
var serializedCart = '';
var cartTotal = 0;

function addCartItem(id, size, price, name) {
	if (price && name) {
		//this was called from the item tag so show the message
		//if no price & name, this is an increment from the cart
		//and no msg should show
		showAddedMessage(id, size);
	}
	
	addOrIncrementCartItem(id, size, price, name);	
	propagateCartChange();
}


function addOrIncrementCartItem(id, size, price, name) {

	var inCart = false;

	for (var i=0;i<cart.length; i++) {
		if (cart[i].id == id && cart[i].size == size) {
			cart[i].quantity++;
			inCart = true;
		}
	}

	if (!inCart) {

		cart[cart.length] = new Object();
		cart[cart.length-1].id = id + '';
		cart[cart.length-1].size = size + '';
		cart[cart.length-1].price = price + '';
		cart[cart.length-1].quantity = 1;
		cart[cart.length-1].name = name + '';

	}
	
}

function saveCart() {

	serializedCart = serializeCart();
	setCookie(cartCookieName, serializedCart, null, null, 'jmbamboo.com');
	/*
	/* cookies are sensitive to the www - make sure we set it for both paths /
	if (document.location.href.indexOf('://www') == -1) {
		setCookie(cartCookieName, serializedCart, null, null, 'jmbamboo.com');
	}
	*/

}


function serializeCart() {

	var serializedCart = '';

	for (var i=0;i<cart.length ; i++) {

		if (cart[i] != null && cart[i] != '') {
			serializedCart += '|' + cart[i].id + '][' + cart[i].size + '][' + cart[i].price + '][' + cart[i].quantity + '][' + cart[i].name + '][' + '|';
		}
	
	}

	return(serializedCart);

}


function setSerializedCartFromCookie() {

	var sCart = '';
	
	if (document.location.href.indexOf('cc=') == -1) {
		sCart = getCookie(cartCookieName);
	} else {
		sCart = document.location.search.substring(1)
		sCart = unescape(sCart.substring(sCart.indexOf('cc=') + 3));		
	}	

	if (sCart != null && sCart != '') {
		serializedCart = sCart;
	}

	populateCartFromCookie();
	saveCart();

}

function populateCartFromCookie() {

	cart = new Array();

	var sCart = serializedCart;

	if (sCart != null && sCart != '') {
		cItems = replace(sCart, '||', '|').split('|');

		for (var i=0;i<cItems.length; i++) {

			if (cItems[i] != null && cItems[i] != '') {

				var thisItemData = cItems[i].split('][');

				cart[cart.length] = new Object();

				cart[cart.length - 1].id = thisItemData[0] + '';
				cart[cart.length - 1].size = thisItemData[1] + '';
				cart[cart.length - 1].price = thisItemData[2];
				cart[cart.length - 1].quantity = thisItemData[3];
				cart[cart.length - 1].name = thisItemData[4];
			}
		}


	}

}

function loadAndBuildCart() {
	//only try to load and build a cart if there is a cart div on the page
	if (document.getElementById('cartContentsDiv')) {
		setSerializedCartFromCookie();
		updateTopCart();
	}

}


function updateTopCart() {

	var topCartML = '';

	var itemCnt = 0;
	cartTotal = 0;

	if (cart.length > 0) {

		for (var i=0;i<cart.length ; i++) {

			if (cart[i] != null) {
				itemCnt = itemCnt + (cart[i].quantity-0);
				cartTotal += (cart[i].price*cart[i].quantity);
			}	

		}

		topCartML = 'You cart contains ' + itemCnt + ' item' + (itemCnt==0?'s':(itemCnt>1?'s':'')) + '.<br>';
		topCartML += '<p style="margin-top:5px;margin-bottom:5px;">Cart Total: <strong style="font-size:14px;">' + formatDollars(cartTotal) + '</strong> &nbsp; <span style="color:#550606;font-size:9px;">(free shipping)</span></p>';

		topCartML += '<a href="javascript:viewCart();">View Cart &#187;</a> &nbsp; &nbsp; &nbsp; &nbsp;' +
					 '<a href="javascript:checkout();">Checkout &#187;</a>';

		colorizeCart('on');
	} else {
		document.getElementById('cartContentsDiv').innerHTML = 'Your cart is empty';
		colorizeCart('off');
	}


	if (topCartML != '') {
		document.getElementById('cartContentsDiv').innerHTML = topCartML;
	}

}


function colorizeCart(toggle) {

	var onColor = '#CBFFFA';
	var offColor = '#E7FBEA';

	var newColor = offColor;

	if (toggle == 'on') {
		newColor = 	onColor;
	}

	document.getElementById('tctd').style.backgroundColor = newColor;
	document.getElementById('tccd').style.backgroundColor = newColor;
	document.getElementById('tcbd').style.backgroundColor = newColor;
	document.getElementById('tclt').style.color = newColor;
	document.getElementById('tcrt').style.color = newColor;
	document.getElementById('tclb').style.color = newColor;
	document.getElementById('tcrb').style.color = newColor;
}


function viewCart() {
	document.getElementById('viewCartDiv').style.top = '70px';
	document.getElementById('viewCartDiv').style.width = '500px';
	document.getElementById('viewCartDiv').style.left = '160px';
	updateCartML();
	document.getElementById('cartBtnsDiv').style.display = 'block';
	document.getElementById('viewCartDiv').style.display = 'block';
}

function hideCart() {
	document.getElementById('viewCartDiv').style.display = 'none';
}

function getCartML() {
	var cartML = '';
	cartTotal = 0;
	var cnt = 0;

	for (var i=0;i<cart.length ; i++) {

		if (cart[i] != null) {
			cnt++;
			cartTotal += (cart[i].price*cart[i].quantity);
			cartML += '<tr><td width="20px;" style="text-align:right;">' + cnt + '.</td>' +
					  '<td width="100%">' + replace(cart[i].name, '\\\'', '\'') + ' #' + cart[i].size + '</td>' +
					  '<td>' + cart[i].quantity + ' &nbsp; <span style="font-size:14px;"><a href="javascript:increment(' + i + ')">+</a>/<a href="javascript:decrement(' + i + ')">&ndash;</a></span></td>' +
					  '<td style="text-align:right;">' + formatDollars(cart[i].price) + '</td><tr>';
		}	

	}

	if (cartML != '') {
		cartML  = '<table cellpadding="3" cellspacing="0" border="0" style="font-size:12px;display:block;">' +
				  '<tr><td>&nbsp;</td><td><strong>Name</strong></td><td><strong>Quantity</strong></td><td style="text-align:right;"><strong>Price</strong></td></tr>' +
				  cartML + 
				  '<tr><td>&nbsp;</td><td>&nbsp;</td><td><strong style="font-size:16px;">Total:</strong></td><td style="text-align:right;"><strong style="font-size:16px;">' + formatDollars(cartTotal)  + '</strong></td></tr>' +
				  '</table>';
	} else {
		cartML = 'Your cart is empty.';
	}


	return(cartML);
}

function updateCartML() {
	var cartML = getCartML();	
	document.getElementById('viewCartDivContent').innerHTML = cartML;
	if (cartML == 'Your cart is empty.'){
		if (document.getElementById('cartBtnsDiv')) {
			document.getElementById('cartBtnsDiv').style.display = 'none';
		}
		
	}	
}

function increment(which) {
	addCartItem(cart[which].id, cart[which].size);
	updateCartML();

	propagateCartChange();

}

function decrement(which) {

	cart[which].quantity = cart[which].quantity - 1;
	if (cart[which].quantity == 0) {
		if (confirm('Are you sure you want to remove this item from your cart?')) {
			removeCartItem(which);
		} else {
			cart[which].quantity = 1;
		}
	}

	propagateCartChange();

}
function propagateCartChange() {
	saveCart()
	updateTopCart();
	updateCartML();
}

function removeCartItem(which) {
	var newCart = new Array();
	
	for (var i=0;i<cart.length ; i++) {
		if (i != which) {
			newCart[newCart.length] = cart[i];
		}
	}

	cart = newCart;
}

function emptyCart() {
	if (confirm('Are you sure you want to completely empty your cart?')) {
		cart = new Array();
		propagateCartChange();
		document.getElementById('cartBtnsDiv').style.display = 'none';
	}
}


function checkout() {

	document.location.href='https://www.jmbamboo.com/orders/checkoutForm.php?cc=' + serializedCart;

}

function goHome() {
	document.location.href='http://www.jmbamboo.com/index.php?cc=' + serializedCart;
}


function showAddedMessage(id, size) {
	var msgDivID = 'msgDv_' + id + '_' + size;		
	if (document.getElementById(msgDivID).innerHTML != '') {
		setOpacity(document.getElementById(msgDivID), 100);
	} else {
		document.getElementById(msgDivID).innerHTML =	'<div class="crvBoxTB">' +
														'	<div class="crvBoxTB_bgDiv">' +
														'		<div class="center_MG" style="background-color:#FFC99E;">&nbsp;</div>' +
														'	</div>' +
														'	<div class="crvBoxTB_l">' +
														'		<div class="top_MG" style="color:#FFC99E;">.</div>' +
														'	</div>' +
														'	<div class="crvBoxTB_r">' +
														'		<div class="top_MG" style="color:#FFC99E;">.</div>' +
														'	</div>' +
														'</div>' +
														'<div class="crvBoxContent_MG" style="background-color:#FFC99E;text-align:center;font-weight:bold;color:#AC492B;">' +
														'	item added' +
														'</div>' +
														'<div class="crvBoxTB">' +
														'	<div class="crvBoxTB_bgDiv">' +
														'		<div class="center_MG" style="background-color:#FFC99E;">&nbsp;</div>' +
														'	</div>' +
														'	<div class="crvBoxTB_l">' +
														'		<div class="bottom_MG" style="color:#FFC99E;">.</div>' +
														'	</div>' +
														'	<div class="crvBoxTB_r">' +
														'		<div class="bottom_MG" style="color:#FFC99E;">.</div>' +
														'	</div>' +
														'</div>';
		document.getElementById('msgDv_' + id + '_' + size).style.top = '-27px';
		document.getElementById('msgDv_' + id + '_' + size).style.display = 'block';
	}	
	driftAndFadeTagMasgDiv(id, size);
}

function driftAndFadeTagMasgDiv(id, size) {
	setTimeout('fadeOut(\'msgDv_' + id + '_' + size + '\', 100);', 250);
}



//******************END CART functions


//*************** Fade functions

function setOpacity(obj, opacity) {
  opacity = (opacity == 100)?99.999:opacity;
  
  // IE/Win
  obj.style.filter = "alpha(opacity:"+opacity+")";
  
  // Safari<1.2, Konqueror
  obj.style.KHTMLOpacity = opacity/100;
  
  // Older Mozilla and Firefox
  obj.style.MozOpacity = opacity/100;
  
  // Safari 1.2, newer Firefox and Mozilla, CSS3
  obj.style.opacity = opacity/100;
}

var fading = false;

function fadeIn(objId,opacity) {
  if (document.getElementById) {
    obj = document.getElementById(objId);
    if (opacity <= 100) {
	  fading = true;
      setOpacity(obj, opacity);
      opacity += 7;
      window.setTimeout("fadeIn('"+objId+"',"+opacity+")", 80);
    } else {
		fading = false;
	}
  }
}

function fadeOut(objId,opacity) {
  if (document.getElementById) {
    obj = document.getElementById(objId);
    if (opacity > 0) {
	  fading = true;
      setOpacity(obj, opacity);
      opacity -= 7;
      window.setTimeout("fadeOut('"+objId+"',"+opacity+")", 80);
    } else {
		fading = false;
	}
  }
}



//************** END Fade functions




//***************COOKIE functions

/*
   name - name of the cookie
   value - value of the cookie
   [expires] - expiration date of the cookie
     (defaults to end of current session)
   [path] - path for which the cookie is valid
     (defaults to path of calling document)
   [domain] - domain for which the cookie is valid
     (defaults to domain of calling document)
   [secure] - Boolean value indicating if the cookie transmission requires
     a secure transmission
   * an argument defaults when it is assigned null as a placeholder
   * a null placeholder is not required for trailing omitted arguments
*/

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;
}


/*
  name - name of the desired cookie
  return string containing value of specified cookie or null
  if cookie does not exist
*/

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}


/*
   name - name of the cookie
   [path] - path of the cookie (must be same as path used to create cookie)
   [domain] - domain of the cookie (must be same as domain used to
     create cookie)
   path and domain default if assigned null or omitted if no explicit
     argument proceeds
*/

function deleteCookie(name, path, domain) {
  if (getCookie(name)) {
    document.cookie = name + "=" +
    ((path) ? "; path=" + path : "") +
    ((domain) ? "; domain=" + domain : "") +
    "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

// date - any instance of the Date object
// * hand all instances of the Date object to this function for "repairs"

function fixDate(date) {
  var base = new Date(0);
  var skew = base.getTime();
  if (skew > 0)
    date.setTime(date.getTime() - skew);
}

//***************END COOKIE function



//**************Item Box Functions **********************


function showSizeGuide(itemID) {
	document.getElementById('sInfo_' + itemID).style.display = 'block';
}

function hideSizeGuide(itemID) {
	document.getElementById('sInfo_' + itemID).style.display = 'none';
}


//UTILITY FUNCTIONS**********************************************************************
//general use functions

function addLoadEvent(func, order) {
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
    window.onload = func;
  } else {

	var addOrder = 'back';

	if (order != null) {
		addOrder = order;
	}

	if (addOrder == 'front') {

		window.onload = function() {
		  func();
		  oldonload();		  
		}

	} else {

		window.onload = function() {
		  oldonload();
		  func();
		}

	}
  }
}

var letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var numbers = '0123456789';

rnd.today=new Date();
rnd.seed=rnd.today.getTime();

function rnd() {
        rnd.seed = (rnd.seed*9301+49297) % 233280;
        return rnd.seed/(233280.0);
};

function rand(number) {
        return Math.ceil(rnd()*number);
};

function replace(string,text,by) {
    // Replaces text with by in string
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return string;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return string;
    if (i == -1) return string;

    var newstr = string.substring(0,i) + by;

    if (i+txtLength < strLength)
        newstr += replace(string.substring(i+txtLength,strLength),text,by);

    return newstr;
}


function Trim(TRIM_VALUE){
if(TRIM_VALUE.length < 1){
return"";
}
TRIM_VALUE = RTrim(TRIM_VALUE);
TRIM_VALUE = LTrim(TRIM_VALUE);
if(TRIM_VALUE==""){
return "";
}
else{
return TRIM_VALUE;
}
} //End Function

function RTrim(VALUE){
var w_space = String.fromCharCode(32);
var v_length = VALUE.length;
var strTemp = "";
if(v_length < 0){
return"";
}
var iTemp = v_length -1;

while(iTemp > -1){
if(VALUE.charAt(iTemp) == w_space){
}
else{
strTemp = VALUE.substring(0,iTemp +1);
break;
}
iTemp = iTemp-1;

} //End While
return strTemp;

} //End Function

function LTrim(VALUE){
var w_space = String.fromCharCode(32);
if(v_length < 1){
return"";
}
var v_length = VALUE.length;
var strTemp = "";

var iTemp = 0;

while(iTemp < v_length){
if(VALUE.charAt(iTemp) == w_space){
}
else{
strTemp = VALUE.substring(iTemp,v_length);
break;
}
iTemp = iTemp + 1;
} //End While
return strTemp;
} //End Function


var stopTicks = {dummyItem:0,dummyItem2:1};

function tickElipsis(eleID, setStopID) {

	if (setStopID) {
		eval('stopTicks.' + eleID + ' = false;');
	}

	if ((eval('stopTicks.' + eleID) + '') != 'undefined') {
		if (!eval('stopTicks.' + eleID)) {


			if (document.getElementById(eleID)) {

				if (document.getElementById(eleID).innerHTML.indexOf('...') != -1) {
					document.getElementById(eleID).innerHTML = replace(document.getElementById(eleID).innerHTML, '...', '');
				} else {
					document.getElementById(eleID).innerHTML += '.';
				} 

				setTimeout('tickElipsis(\'' + eleID + '\')', 800);
				
			}
		}
	}
	
}


function formatDollars(decimalDollars) {

	var formattedDollars = decimalDollars + '';

	if (formattedDollars.indexOf('.')== -1) {
		formattedDollars += '.00';
	} else if (formattedDollars.indexOf('.') == formattedDollars.length-2) {
		formattedDollars += '0';
	}

	formattedDollars = '$' + formattedDollars;

	return(formattedDollars);

}