var mouseLogin = false;

var defaultCookieOptions = 
    {
	path: "/",
	domain: ".ziginy.com"
    };    

$(document).ready(function() {

    //Show correct item total in cart    
    $("#numItems").text( getItemCount() );

    //Setup click on search field
    $("#query").click(
	function()
	{
	    if($("#query").val() == "search zigi") $("#query").val('');
	}
    );

    //Setup Login Box
    $("#showLogin").click(
	function()
	{
	    $("#login").fadeIn(200);
	    $("#loginEmail").focus();
	}
    );
    
    $(".loginWrap").hover(
	function()
	{ 
            mouseLogin = true; 
	}, 

	function()
	{ 
            mouseLogin = false; 
	}
    );

    $("body").mouseup(
	function()
	{ 
            if(!mouseLogin) $('#login').hide();
	}
    );

    //If user is logged in
    if($.cookies.get("email", defaultCookieOptions) && $.cookies.get("key", defaultCookieOptions))
    {
	//reset cookie timers and touch timestamp in db
	var dataString = 'email='+ $.cookies.get('email', defaultCookieOptions) + '&key=' + $.cookies.get('key', defaultCookieOptions);
	$.ajax({
	    type: "POST",
	    url: "/cgi/touch.cgi",
	    data: dataString
	});

	var options =
	    {
		hoursToLive: 1,
		path: "/",
		domain: ".ziginy.com"
	    }

	var rememberOptions = 
	    {
		hoursToLive: 24 * 30,
		path: "/",
		domain: ".ziginy.com"
	    }
    	
	if($.cookies.get("remember", defaultCookieOptions) == "remember")
	{
	    $.cookies.set("email", $.cookies.get("email", defaultCookieOptions), rememberOptions);
	    $.cookies.set("remember", "remember", rememberOptions);
	}

	else
	{
	    $.cookies.set("email", $.cookies.get("email", defaultCookieOptions), options);
	}

	$.cookies.set("key", $.cookies.get("key", defaultCookieOptions), options);

	$("#showLogin").html('<strong>My Profile-</strong> ' + $.cookies.get("email", defaultCookieOptions));
	$("#notLoggedIn").hide();
	$("#loggedIn").show();

	var dataString = 'email='+ $.cookies.get('email', defaultCookieOptions) + '&key=' + $.cookies.get('key', defaultCookieOptions);
	$.ajax({
	    type: "POST",
	    url: "/cgi/b2b_check_nostyle.cgi",
	    data: dataString,
	    success: function(d)
	    {
		$("#categories").prepend('<li><a href="/coming-soon.html"><strong>Pre Order</strong></a></li>');
		//$('.item_price_b2b').show();
		
		//FFS Change all the category links to point to the private pages
		$("#subNav a, #categories a, #brands a, #splash_category a").each(
		    function()
		    {
			if(!$(this).attr('href').match(/coming\-soon/))
			    $(this).attr('href' , '/private-category.html?' + $(this).attr('href').replace(".html", "").replace("../", "").replace(/^\//, ""));
		    }
		);

		//show appropriate brands based on label data returned
		$("#brands li a").each(
		    function()
		    {
			try
			{
			    var label = CATEGORIES[$(this).attr('id').replace("lm_", "")].cat_id;
			    if(!d.match(label))
			    {
				$(this).hide();
			    }
			    else $(this).show().css("visibility", "visible");
			}

			catch(e) {}
		    }
		);
		$("#brands").show();
	    },
	    error: function()
	    {
		$("#brands").show();
	    }
	});  
    }

    else
    {
	//not logged in, show all brands by default
	$("#brands").show();
    }

    if($.cookies.get("remember", defaultCookieOptions) == "remember" && $.cookies.get("email", defaultCookieOptions))
    {
	$("#loginEmail").val($.cookies.get("email", defaultCookieOptions));
	$("#remember").attr('checked', 'checked');
    }


    //Setup enter on login form
    $("#loginEmail, #loginPassword").keypress(
	function(e)
	{
	    if(e.keyCode == 13) login();
	}
    );
    
});


//////////////////////////////////////////////////////////
//
// Ack/Error Functions 
//
//////////////////////////////////////////////////////////

function showError()
{
   if(window.location.href.indexOf('error.html?') >= 0)
    {
	var which = window.location.href.substring(window.location.href.indexOf('?') + 1);
	switch(which)
	{
	case 'cart_add_item_error' :
	    $("#error").html('Cannot add to shopping bag - item not found.');
	    break;
	case '500' :
	    $("#error").html('500 Internal Server Error - please contact <a href="mailto:support@ziginy.com">ZiGiny Support</a>.');
	    break;
	case 'regdupe' :
	    $("#error").html('An account with that email address already exists.');
	    break;
	case 'forgot' :
	    $("#error").html('An error occured while attempting to reset your password, please contact <a href="mailto:support@ziginy.com">ZiGiny Support</a>.');
	    break;
	case 'reset' :
	    $("#error").html('An error occured while attempting to reset your password, please contact <a href="mailto:support@ziginy.com">ZiGiny Support</a>.');
	    break;
	case 'register' :
	    $("#error").html('An error occured while attempting to register your account, please contact <a href="mailto:support@ziginy.com">ZiGiny Support</a>.');
	    break;
	case 'update' :
	    $("#error").html('An error occured while attempting to update your account, please contact <a href="mailto:support@ziginy.com">ZiGiny Support</a>.');
	    break;
	case 'args' :
	    $("#error").html('Missing arguments, please contact <a href="mailto:support@ziginy.com">ZiGiny Support</a>.');
            break;
	case 'subscribe' :
	    $("#error").html('Your email address was blank- please enter a valid email to subscribe to our newsletter.');
            break;
	case 'contact' :
	    $("#error").html('Your email address or message was blank.');
            break;
	case 'file' :
	    $("#error").html('One or more of your files was an invalid format.  Please try again.');
            break;
	case 'tax' :
	    $("#error").html('There was a problem adding your tax id, please contact <a href="mailto:support@ziginy.com">ZiGiny Support</a>.');
	    break;
	}
	
    }

}

function showAck()
{
    if(window.location.href.indexOf('ack.html?') >= 0)
    {
	var which = window.location.href.substring(window.location.href.indexOf('?') + 1);
	switch(which)
	{
	case 'order' :
	    $("#ack").html('Your order has been received by ZiGiny. Please check your email for confirmation and receipt.');
	    $.cookies.del("cart", defaultCookieOptions);
	    break;
	case 'subscribe' :
	    $("#ack").html('You have been subscribed to the ZiGiny mailing list!  Please check your email for more info.');
	    break;
	case 'contact' :
	    $("#ack").html('Thank you for your message- a representative will contact you shortly.');
	    break;
	case 'register' :
	    $("#ack").html('Thank you for registering with ZiGiny! Please check your email for more information.');
	    break;
	case 'forgot' :
	    $("#ack").html('Password reset link sent- please check your email.');
	    break;
	case 'reset' :
	    $("#ack").html('Your password has been changed.');
	    break;
	case 'update' :
	    $("#ack").html('Your account information has been updated.');
	    break;
	case 'tax' :
	    $("#ack").html('Thank you! ZiGiny will review your information and contact you shortly.');
	    break;
	}
    }
}



//////////////////////////////////////////////////////////
//
// Cart Functions 
//
//////////////////////////////////////////////////////////

//Cart object a JSON array of the form:
// [
//   { upc : "upcCode1" , qty : "x" } , 
//   { upc : "upcCode2" , qty : "y" } , 
//   { upc : "upcCode3" , qty : "z" } , 
//   ...
// ]

//Cart cookie is stored as
// upcCode1###qty1!upcCode2###qty2!upcCode3###qty3


//Create a cookie from a cart object
function createCart(c)
{
    var options = 
	{
	    hoursToLive: 24*30,
	    path: "/",
	    domain: ".ziginy.com"
	};    

    $.cookies.del("cart", defaultCookieOptions);

    if(!c) return;

    var cString = "";
    for(var i = 0; i < c.length; i++)
    {
	cString += c[i].upc + "###" + c[i].qty;
	if(i < c.length - 1 ) cString += "!";
    }
    if(cString != "") $.cookies.set("cart", cString, options);
}


//Return a cart object from the cookie
function getCart()
{
    var cString = $.cookies.get('cart', defaultCookieOptions);

    if(cString)
    {
	var cart = [];
	var cItems = [];
	if(cString.indexOf("!") < 0) cItems = [ cString ];
	else cItems = cString.split('!');
	for(var i = 0; i < cItems.length; i++)
	{
	    var thisItem = cItems[i].split("###");
	    cart.push({ upc : thisItem[0] , qty : thisItem[1] });
	}
	return cart;
    }

    else return [];
}

function addItem()
{
    var cart = getCart();
    
    //Check if this item is already in cart - if so, just update qty
    var currqty = 0;

    //Get UPC and add to cart
    if(B2BAUTH)
    {
	var index = getB2BIndex($("#color").val(), $("#size").val());
	var upc = B2B_FIXED[index].UPC_NO;
	currqty = isInCart(upc);

	if(!B2B_FIXED[index].AVAILABLE)
	{
	    alert("We're sorry, that item is currently sold out.");
	    return false;
	}
	
	else if(parseInt($("#qty").val()) + currqty > B2B_FIXED[index].toSell && !B2B_FIXED[index].preOrder)
	{
	    alert("We're sorry, our inventory is limited and we can only sell " + B2B_FIXED[index].toSell + " case(s) of this item currently.");
	    $("#qty").val(B2B_FIXED[index].toSell);
	    lastQty = B2B_FIXED[index].toSell;
	    return false;
	}
	
	else B2B_FIXED[index].toSell -= parseInt($("#qty").val());

	$.get(
	    "/cgi/atc_notify.cgi",
	    { style : STYLE , color : $("#color").val() , scale : $("#size").val() , email : $.cookies.get("email", defaultCookieOptions) }
	);
    }

    else
    {
	var index = getRetailIndex($("#color").val(), $("#size").val());
	var upc = RETAIL_FIXED[index].UPC_NO;
	currqty = isInCart(upc);

	if(RETAIL_FIXED[index].AVAILABLE <= 0)
	{
	    alert("We're sorry, that item is currently sold out.");
            return false;
	}

	else if(parseInt($("#qty").val()) > RETAIL_FIXED[index].AVAILABLE)
	{
	    alert("We're sorry, our inventory is limited and we can only sell " + RETAIL_FIXED[index].AVAILABLE + " pair(s) of this item currently.");
            $("#qty").val(RETAIL_FIXED[index].AVAILABLE);
            lastQty = RETAIL_FIXED[index].AVAILABLE;
            return false;
	}

	else RETAIL_FIXED[index].AVAILABLE -= parseInt($("#qty").val());

	//retail live
	return false;
    }

    if(currqty > 0)
    {
        updateQty(upc, parseInt(currqty) + parseInt($("#qty").val()));
    }

    else
    {
        cart.push({ upc : upc , qty: $("#qty").val() });
        createCart(cart);
	
        //Show correct item total in cart and blurb:
        window.scroll(0,0);
        $("#added").html('This item has been added to your shopping bag').fadeIn(function() { $(this).fadeOut(5000) });
        $("#numItems").text( getItemCount() );
    }
}


function getItemCount()
{
    var cart = getCart();
    var num = cart.length;
    var txt = " Items";
    if(num == 1) txt = " Item";
    return num + txt;
}


//Check if item is in cart- if so return the quanity, otherwise return 0
function isInCart(upc)
{
    var cart = getCart();

    for(var i = 0; i < cart.length; i++)
    {
        if(cart[i].upc == upc)
        {
	    return parseInt(cart[i].qty);
	}
    }

    return 0;
}


function deleteItem(upc)
{
    var cart = getCart();

    for(var i = 0; i < cart.length; i++)
    {
	if(cart[i].upc == upc)
	{
	    cart.splice(i, 1);
	    createCart(cart);
	    
	    //Show correct item total in cart
	    $("#numItems").text( getItemCount() );
	}
    }

    if(window.location.href.indexOf('checkout.html') >= 0) checkCart();
}


function updateQty(upc, qty)
{
    if(isNaN(parseInt(qty))) return false;

    var cart = getCart();

    for(var i = 0; i < cart.length; i++)
    {
	if(cart[i].upc == upc)
	{
	    cart[i].qty = parseInt(qty);
	    createCart(cart);
	    return true;
	}
    }

    return false;
}


function updateQtyInCart(upc, field, origqty)
{
    if(!updateQty(upc, field.value))
    {
	field.value = origqty;
    }
    else
    {
	viewCart();
    }
}



function viewCart()
{
    $("#cart").empty();
    $("#cartLoading").show();

    //Build a shopping cart
    var cart = getCart();

    //If nothing in cart exit early
    if(cart.length == 0)
    {
	$("#cartCallout").text("Your shopping bag is empty.");
	$("#cartLoading").hide();
	return;
    }

    //Get a list of items in cart
    var itemStr = ''
    for(var i = 0; i < cart.length; i++)
    {
	itemStr += cart[i].upc;
	if(i < cart.length -1)
	{
	    itemStr += '+';
	}
    }

    //Load international/domestic discounts and shipping information

    var dataString = 'upcs=' + itemStr;

    if($.cookies.get("email", defaultCookieOptions) && $.cookies.get("key", defaultCookieOptions))
    {
	dataString += '&email='+ $.cookies.get('email', defaultCookieOptions) + '&key=' + $.cookies.get('key', defaultCookieOptions);
    }

    $.ajax(
	{
	    type: "POST",
	    url: "/cgi/cart_discount.cgi",
	    data: dataString,
	    success: function(d2)
	    {
		DISCOUNTS = eval("(" + d2 + ")");
		//Lookup info on items
		$.ajax(
		    {
			url : "/cgi/cart_lookup.cgi?" + itemStr , 
			success : function(d)
			{
			    var newcart = eval(d);
			    
			    //Copy qty values into newcart from original cart object
			    for(var i = 0; i < newcart.length; i++)
			    {
				for(var j =0; j < cart.length; j++)
				{
				    if(cart[j].upc == newcart[i].UPC_NO)
				    {
					newcart[i].qty = cart[j].qty;
				    }
				}
			    }
			    
			    buildCart(newcart);
			}
		    }
		);
	    },
	    error: function(d2)
	    {
		//Lookup info on items
		$.ajax(
		    {
			url : "/cgi/cart_lookup.cgi?" + itemStr , 
			success : function(d)
			{
			    var newcart = eval(d);
			    
			    //Copy qty values into newcart from original cart object
			    for(var i = 0; i < newcart.length; i++)
			    {
				for(var j =0; j < cart.length; j++)
				{
				    if(cart[j].upc == newcart[i].UPC_NO)
				    {
					newcart[i].qty = cart[j].qty;
				    }
				}
			    }
			    
			    buildCart(newcart);
			}
		    }
		);	
	    }
	}
    );
}

function buildCart(newcart)
{
    //Paint cart based on newcart
    var cartTable = '<table id="cartTable"><tr><th></th><th></th><th>Color</th><th>Size</th><th>Qty.</th><th>Price</th><th>Line Total</th><th></th></tr>';
    var taxTotal = 0;
    var shipTotal = 0;
    var subTotal = 0;
    var dueTotal = 0;
    var poFlag = false;

    if(window.location.href.indexOf('checkout.html') >= 0) { Date.firstDayOfWeek = 0; Date.format = 'yyyy-mm-dd'; }

    for(var i = 0; i < newcart.length; i++)
    {
	var preOrder = false;

	var loc = "Anywhere";
	if($("#ship_country").val())
	{
	    if($("#ship_country").val() == "US") loc = "Domestic";
	    else loc = "International";
	}

	var basePrice = parseFloat(newcart[i].LINE_PRICE);
	if(newcart[i].UPC_NO.match(/^mcx/)) basePrice = Math.floor((scaleLookup[newcart[i].SCALE].shoecount * parseFloat(newcart[i].LINE_PRICE)) * 100) / 100;

	var finalPrice = basePrice;
	if(newcart[i].UPC_NO.match(/^mcx/)) finalPrice = computeCartDiscount(newcart[i].UPC_NO, scaleLookup[newcart[i].SCALE].shoecount, basePrice, loc);
	else finalPrice = computeCartDiscount(newcart[i].UPC_NO, 1, basePrice, loc);

	var eachPriceTxt = '$' + formatPrice(basePrice);
	var linePriceTxt = '$' + formatPrice(Math.round((basePrice * newcart[i].qty) * 100)/100);

	if(finalPrice != basePrice)
	{
	    eachPriceTxt = '<strike>$' + formatPrice(basePrice) + '</strike><br /><strong>$' + formatPrice(finalPrice) + '</strong>';
	    linePriceTxt = '<strike>$' + formatPrice(Math.round((basePrice * newcart[i].qty) * 100)/100) + '</strike><br /><strong>$' + formatPrice(Math.round((finalPrice * newcart[i].qty) * 100)/100) + '</strong>';
	}

	var itemText = "";
	var thisSize = "";

	if(newcart[i].UPC_NO.match(/^mcx/))
	{
	    thisSize = scaleLookup[newcart[i].SCALE].sizerun;
	    
	    var numShoes = scaleLookup[newcart[i].SCALE].shoecount;
	    
	    var dateValid = false;
	    var dateText = "";
	    
	    if(newcart[i].avail_date)
	    {
		var now = new Date();
		
		var dateData = newcart[i].avail_date.match(/\d+/g);
		if(dateData[1].charAt(0) == '0') dateData[1] = dateData[1].substring(1);
		var ad = new Date(dateData[0], parseInt(dateData[1]) - 1, dateData[2]);
		ad = new Date(ad.getTime() + (1000 * 60 *60 * 24 * 4));		
		var weekAgo = new Date(now.getTime() - (1000 * 60 *60 * 24 * 4));
		if(ad > weekAgo) dateValid = true;
		dateText = ad.getFullYear() + '-' + parseInt(parseInt(ad.getMonth()) + 1) + '-' + ad.getDate();
	    }
	    
	    if(parseInt(newcart[i].ON_HAND) >= numShoes) {}
	    
	    else if(dateValid || (parseInt(newcart[i].WIP) >= numShoes))
	    {
		poFlag = true;
		preOrder = true;
	    }
	    	    
	    var cartLink = '/styles/' + newcart[i].STYLE.toLowerCase().replace(/\s/g, "-").replace(/\+/g, "plus") + '.html';
	    if($.cookies.get("email", defaultCookieOptions) && $.cookies.get("key", defaultCookieOptions))
	    {
		cartLink = '/private-detail.html?' + newcart[i].STYLE.toLowerCase().replace(/\s/g, "_").replace(/\+/g, "plus");
	    }
	    
	    itemText = '<strong><a href="/private-detail.html?' + newcart[i].STYLE.toLowerCase().replace(/\s/g, "_").replace(/\+/g, "plus") + '">' + newcart[i].STYLE + '</a></strong>';
	    
	    if(preOrder)
	    {
		if(dateValid) itemText = '<strong><a href="' + cartLink + '">' + newcart[i].STYLE + ' (Pre-Order)</a></strong><br /><span class="cart-po">Ships ' + ad.toDateString().substring(4);
		else itemText = '<strong><a href="' + cartLink + '">' + newcart[i].STYLE + ' (Pre-Order)</a></strong><br /><span class="cart-po">No shipping date scheduled';
		linePriceTxt += '<br /><em class="poprice">Pre-Order: $0 due at checkout</span>';
	    }
	    
	    else itemText += '<br /><span class="cart-po">Ships Next Day';

	    if(window.location.href.indexOf('checkout.html') >= 0) itemText += ' (or choose a preferred shipping date)</span>';
	    
	    if(window.location.href.indexOf('checkout.html') >= 0)
	    {
		//preferred date change
		itemText += '<br /><input type="text" value="Specfiy preferred shipping date..." class="preferred-date" readonly /><input type="hidden" class="preferred-upc" value="' + newcart[i].UPC_NO + '" /><input type="hidden" class="preferred-ad" value="' + dateText + '" />';
	    }
	}

	else
	{
	    itemText = '<strong><a href="/styles/' + newcart[i].STYLE.toLowerCase().replace(/\s/g, "-").replace(/\+/g, "plus") + '.html">' + newcart[i].STYLE + '</a></strong>';
	    thisSize = newcart[i].SCALE;
	}
	    
	cartTable += '<tr>' +
	    '<td class="cartThumb"><img src="images/shoes/sm/' + newcart[i].IMAGE + '_1.jpg" /></td>' +
	    '<td class="noborder">' + itemText + '</td>' +
	    '<td>' + newcart[i].material + '</td>' +
	    '<td>' + thisSize + '</td>' +
	    '<td>x ' + newcart[i].qty + '</td>' +
	    '<td>' + eachPriceTxt + '</td>' +
	    '<td>' + linePriceTxt + '</td>' + 
	    '<td class="noborder"><a class="hoverLink" onclick="deleteItem(\'' + newcart[i].UPC_NO + '\'); viewCart();"><img src="/images/trash-delete.gif" /></a></td>' +
	    '</tr>';

	subTotal += finalPrice * newcart[i].qty;
	if(!preOrder) dueTotal += finalPrice * newcart[i].qty;

	subTotal = Math.round(subTotal * 100) / 100;
	dueTotal = Math.round(dueTotal * 100) / 100;

	//tax
	if(!B2BAUTH)
	{
	    if($("#ship_state_td select").val() == "CA") taxTotal += Math.round((parseFloat(finalPrice * newcart[i].qty) * .1075) * 100) / 100;
	    else if($("#ship_state_td select").val() == "NY") taxTotal += Math.round((parseFloat(finalPrice * newcart[i].qty) * .08875) * 100) / 100;
	    else if($("#ship_state_td select").val() == "NJ") taxTotal += Math.round((parseFloat(finalPrice * newcart[i].qty) * .07) * 100) / 100;
	    taxTotal = Math.round(taxTotal * 100) / 100;
	}

	//shipping
	var shipAmt = 0;

	if(newcart[i].UPC_NO.match(/^mcx/))
	{
	    //B2B Shipping
	    if(loc == "Domestic")
	    {
		if($('#ship_zigi').is(':checked'))
		{
		    if(DISCOUNTS[newcart[i].UPC_NO].nullify_domestic == 1 && finalPrice != basePrice) shipAmt = 45 * newcart[i].qty;
		}
	    }

	    else if(loc == "International")
	    {

	    }
	}

	else
	{
	    //Retail shipping
	    if(loc == "Domestic")
	    {

	    }

	    else if(loc == "International")
	    {

	    }
	}
	
	shipTotal += shipAmt;
	if(!preOrder) dueTotal += shipAmt;

	shipTotal = Math.round(shipTotal * 100) / 100;
	dueTotal = Math.round(dueTotal * 100) / 100;
    }

    if(window.location.href.indexOf('checkout') < 0)
    {
	if(poFlag) cartTable += '<tr><td colspan="7" class="noborder"><div id="cartSubtotal"><strong>Total: $' + formatPrice(subTotal) + ' ($' + formatPrice(dueTotal) + ' due at checkout)</strong></div></td></tr></table><div id="fund-alert">Please note: while no payment is due upon checkout for preordered items, your credit card will be validated for the total amount of your order and funds will be held for 24 hours before being released.</div>';
	else cartTable += '<tr><td colspan="7" class="noborder"><div id="cartSubtotal"><strong>Total: $' + formatPrice(subTotal) + '</strong></div></td></tr></table>';
	cartTable += '<div id="cartCheckout"><a href="https://secure.ziginy.com/checkout.html">Checkout &raquo;</a></div>';
    }

    else
    {
	var grandTotal = subTotal + shipTotal + taxTotal;

	if(poFlag) cartTable += '<tr><td colspan="7" class="noborder"><div id="cartSubtotal">Subtotal: $' + formatPrice(subTotal) + '<br />Shipping: $' + formatPrice(shipTotal) + '<br />Tax: $' + formatPrice(taxTotal) + '<br /><strong>Total: $' + formatPrice(grandTotal) + ' ($' + formatPrice(dueTotal) + ' due at checkout)</strong></div></td></tr></table><div id="fund-alert">Please note: while no payment is due upon checkout for preordered items, your credit card will be validated for the total amount of your order and funds will be held for 24 hours before being released.</div>';
	else cartTable += '<tr><td colspan="7" class="noborder"><div id="cartSubtotal">Subtotal: $' + formatPrice(subTotal) + '<br />Shipping: $' + formatPrice(shipTotal) + '<br />Tax: $' + formatPrice(taxTotal) + '<br /><strong>Total: $' + formatPrice(grandTotal) + '</strong></div></td></tr></table>';

	if(B2BAUTH)
	{
	    if(loc == "International")
	    {
		if($('#ship_zigi').is(':checked')) cartTable += '<div id="intl-shipping-alert">Please contact ZiGi to arrange shipping.</div>';
		else cartTable += '<div id="intl-shipping-alert">Shipping rates will be calculated post-checkout via your shipping company.</div>';
	    }

	    else
	    {
		if($('#ship_zigi').is(':checked')) cartTable += '<div id="intl-shipping-alert">Free shipping for all items (excludes markdowns).</div>';
		else cartTable += '<div id="intl-shipping-alert">Free shipping for all items (excludes markdowns)- shipping rates will be calculated post-checkout via your shipping company.</div>';
	    }
	}
    }
    


    //set hidden form fields if they exist on this page
    try
    {
	document.checkout.total.value = formatPrice(subTotal);
    }
    catch(e) {}
    
    $("#cart").html(cartTable);

    //setup datepickers
    $('.preferred-date').each(
	function()
	{
	    if($(this).siblings('.preferred-ad').val() != "")
	    {
		$(this).datePicker({ startDate: $(this).siblings('.preferred-ad').val() });
	    }

	    else $(this).datePicker();
	}
    );

    $("#cartLoading").hide();
}

function formatPrice(p)
{
    p = p.toString();
    if(p.indexOf('.') < 0) return p + '.00';
    else
    {
	if(p.substring(p.indexOf('.')).length == 3) return p;
	else if(p.substring(p.indexOf('.')).length == 2) return p + '0';
	else if(p.substring(p.indexOf('.')).length == 1) return p + '00';
	else return(Math.round(p * 100) / 100);
    }
}




//////////////////////////////////////////////////////////
//
// Checkout Functions 
//
//////////////////////////////////////////////////////////

var CARTOK = false;

function initCheckout()
{
    if(window.location.href.substring(window.location.href.indexOf('?') + 1) == 'generic') 
	alert("We're sorry- there was a problem authorizing your credit card.\nPlease try again or contact ZiGiny for assistance");
    else if(window.location.href.substring(window.location.href.indexOf('?') + 1) == 'avs') 
	alert("We're sorry- there was a problem authorizing your credit card (billing address incorrect).\nPlease try again or contact ZiGiny for assistance");
    else if(window.location.href.substring(window.location.href.indexOf('?') + 1) == 'funds') 
	alert("We're sorry- there was a problem authorizing your credit card (insufficient funds).\nPlease try again or contact ZiGiny for assistance");
    else if(window.location.href.substring(window.location.href.indexOf('?') + 1) == 'invalid') 
	alert("We're sorry- there was a problem authorizing your credit card (credit card number is invalid).\nPlease try again or contact ZiGiny for assistance");
    else if(window.location.href.substring(window.location.href.indexOf('?') + 1) == 'accepted') 
	alert("We're sorry- there was a problem authorizing your credit card (credit card type not accepted).\nPlease try again or contact ZiGiny for assistance");
    
    $("#ship_zigi").click(
	function()
	{
	    viewCart();

	    if($('#ship_zigi').is(':checked'))
	    {
		$(".shipRow").fadeTo(300, '.40');
	    }

	    else
	    {
		$(".shipRow").fadeTo(300, '1');
	    }
	}
    );

    if($.cookies.get("email", defaultCookieOptions) && $.cookies.get("key", defaultCookieOptions))
    {
	var dataString = 'email='+ $.cookies.get('email', defaultCookieOptions) + '&key=' + $.cookies.get('key', defaultCookieOptions);
	$.ajax(
	    {
		type: "POST",
		url: "/cgi/customer-data.cgi",
		data: dataString,
		success: populateCustomerInfoCheckout
	    }
	);  

	$.ajax(
	    {
		type: "POST",
		url: "/cgi/stored-cc-info.cgi",
		data: dataString,
		success: populateStoredCCInfoCheckout
	    }
	);  
    }

    else 
    {
	checkCart();
	viewCart();
    }
}

function populateCustomerInfoCheckout(d)
{
    d = eval( "(" + d + ")" );
    for(var i in d)
    {
	d = d[i];
	break;
    }

    if(d.account_type == "B") B2BAUTH = true;

    document.checkout.email.value = d.email;
    document.checkout.email.readOnly = "true";
    document.checkout.bill_first.value = d.bill_first;
    document.checkout.bill_last.value = d.bill_last;
    document.checkout.bill_address1.value = d.bill_address1;
    document.checkout.bill_address2.value = d.bill_address2;
    document.checkout.bill_city.value = d.bill_city;
    document.checkout.bill_zip.value = d.bill_zip;
    document.checkout.bill_phone.value = d.bill_phone;
    document.checkout.bill_fax.value = d.bill_fax;
    document.checkout.bill_mobile.value = d.bill_mobile;

    document.checkout.ship_first.value = d.ship_first;
    document.checkout.ship_last.value = d.ship_last;
    document.checkout.ship_address1.value = d.ship_address1;
    document.checkout.ship_address2.value = d.ship_address2;
    document.checkout.ship_city.value = d.ship_city;
    document.checkout.ship_zip.value = d.ship_zip;
    document.checkout.ship_phone.value = d.ship_phone;
    document.checkout.ship_fax.value = d.ship_fax;
    document.checkout.ship_mobile.value = d.ship_mobile;

    document.checkout.ship_company_other.value = d.ship_company_other;
    document.checkout.ship_account.value = d.ship_account;

    if(d.ship_zigi == "Y") 
    {
	$("#ship_zigi").attr("checked", true);
	$(".shipRow").fadeTo(300, '.40');
	$(".shipRow .b2b-required").hide();
    }

    if(d.exclusive == "Y")
    {
	$("#invoice_cell").show();
	$("#invoice").click(
	    function()
	    {
		if($("#invoice").is(':checked')) $(".ccinfo, #stored_cc_cell").fadeTo(300, '.40');
		else $(".ccinfo, #stored_cc_cell").fadeTo(300, '1');
	    }
	);
    }

    $("#bill_country").val(d.bill_country);
    $("#ship_country").val(d.ship_country);
    changeCheckoutStateOptions('bill');
    changeCheckoutStateOptions('ship');
    $("#bill_state_td select").val(d.bill_state);
    $("#ship_state_td select").val(d.ship_state);
    $("#sco_sel").val(d.ship_company);

    checkCart();
}

function populateStoredCCInfoCheckout(d)
{
    var stored = false;
    var seen = {};

    d = eval( "(" + d + ")" );    
    for(var i in d)
    {
	if(!seen[i])
	{
	    stored = true;
	    seen[i] = true;
	    $("#stored_cc").append('<option value="' + d[i].customer_id + '!!!' + d[i].cc_token + '!!!' + d[i].cc_desc + '">' + d[i].cc_desc + '</option>');
	}
    }

    if(stored) $("#stored_cc_cell").show();
}

function checkCart()
{
    //runs through the cart and makes sure items are valid for checkout
    var invalidB2B = false;
    var invalidRetail = false;
    $("#checkoutBtn, #saveInfoRow, .shipRow, .shipRowInfo").hide();

    var cart = getCart();
    for(var i = 0; i < cart.length; i++)
    {
	if(cart[i].upc.match(/^mcx/) && !B2BAUTH)
	    invalidB2B = true;

	else if(B2BAUTH && !cart[i].upc.match(/^mcx/))
	    invalidRetail = true;
    }

    if(invalidB2B) alert("You cannot purchase wholesale items without a valid business account.  Please remove the items, login with a valid business account, or contact ZiGiny for information.");
    else if(invalidRetail) alert("You cannot purchase retail items with a business account.  Please remove the items, login with a retail account, or checkout anonymously.");
    else
    {
	CARTOK = true;
	$("#checkoutBtn").show();
	if(B2BAUTH) $("#saveInfoRow, .shipRow, .shipRowInfo").show();
	else $("#ship_zigi").attr("checked", true);
    }
}

function updateStoredCC()
{
    if($("#stored_cc").val() == "") $(".ccinfo").fadeTo(300, '1');
    else $(".ccinfo").fadeTo(300, '.40');
}

function sameCheckoutInfo()
{
    document.checkout.ship_first.value = document.checkout.bill_first.value;
    document.checkout.ship_last.value = document.checkout.bill_last.value;
    document.checkout.ship_address1.value = document.checkout.bill_address1.value;
    document.checkout.ship_address2.value = document.checkout.bill_address2.value;
    document.checkout.ship_city.value = document.checkout.bill_city.value;
    document.checkout.ship_zip.value = document.checkout.bill_zip.value;
    document.checkout.ship_phone.value = document.checkout.bill_phone.value;
    document.checkout.ship_fax.value = document.checkout.bill_fax.value;
    document.checkout.ship_mobile.value = document.checkout.bill_mobile.value;
    document.checkout.ship_country.selectedIndex = document.checkout.bill_country.selectedIndex;
    changeCheckoutStateOptions('ship');
    document.checkout.ship_state.selectedIndex = document.checkout.bill_state.selectedIndex;
    viewCart();
}

function changeCheckoutStateOptions(which)
{
    //which should be either 'bill' or 'ship'
    if(which != 'bill' && which != 'ship') return;

    var country;
    if(which == 'bill') country = document.checkout.bill_country.options[document.checkout.bill_country.selectedIndex].value;
    else if(which == 'ship') country = document.checkout.ship_country.options[document.checkout.ship_country.selectedIndex].value;

    if(country == 'US' || country == 'CA')
    {
	$("#" + which + "_state_td").empty().append( $("#" + country + "_state_select").clone()[0] );
	$("#" + which + "_state_td select").attr('name', which + "_state");
    }

    else
    {
	$("#" + which + "_state_td").empty().append( $("#other_state_select").clone()[0] );
	$("#" + which + "_state_td select").attr('name', which + "_state");
    }

    if(which == 'ship') 
    {
	viewCart();
	$("#ship_state_td select").change(viewCart);
    }
}


function validateCheckoutForm() {
    var res = true;
    var why;

    if(getCart().length == 0)
    {
	alert("You haven't added any products to your shopping bag!");
	return false;
    }

    if(!CARTOK)
    {
	checkCart();
        return false;
    }

    //Append cart cookie so we know which items this user purchased, their login email, and a grand total field to make it easy to charge/store
    document.checkout.cart.value = $.cookies.get('cart', defaultCookieOptions);
    document.checkout.login.value = $.cookies.get('email', defaultCookieOptions);

    //Append preferred ship dates, if entered
    var pdVals = "";
    $(".preferred-date").each(
	function()
	{
	    if($(this).val() != "Specfiy preferred shipping date...")
	    {
		pdVals += $(this).siblings('.preferred-upc').val() + "|" + $(this).val() + "!!!";
	    }
	}
    );

    if(pdVals != "")
    {
	pdVals = pdVals.replace(/\!\!\!$/, "");
	$("#preferred_dates").remove();
	$('form[name="checkout"]').prepend('<input type="hidden" id="preferred_dates" name="preferred_dates" value="' + pdVals + '" />');
    }

    if(document.checkout.bill_first.value == '') { res = false; why = 'first name (billing)'; }
    else if(document.checkout.bill_last.value == '') { res = false; why = 'last name (billing)'; }
    else if(document.checkout.bill_address1.value == '') { res = false; why = 'address (billing)'; }
    else if(document.checkout.bill_city.value == '') { res = false; why = 'city (billing)'; }
    else if(document.checkout.bill_zip.value == '') { res = false; why = 'zip (billing)'; }
    else if(document.checkout.bill_phone.value == '') { res = false; why = 'phone (billing)'; }
    else if(document.checkout.email.value == '' || document.checkout.email.value.indexOf('@') < 0) { res = false; why = 'email'; }
    else if(document.checkout.bill_state.selectedIndex == 0 && (document.checkout.bill_country.selectedIndex == 1 || document.checkout.bill_country.selectedIndex == 2)) { res = false; why = 'state (billing)'; }
    else if(document.checkout.bill_country.selectedIndex == 0 || document.checkout.bill_country.selectedIndex == 3) { res = false; why = 'country (billing)'; }
    else if(document.checkout.ship_first.value == '') { res = false; why = 'first name (shipping)'; }
    else if(document.checkout.ship_last.value == '') { res = false; why = 'last name (shipping)'; }
    else if(document.checkout.ship_address1.value == '') { res = false; why = 'address (shipping)'; }
    else if(document.checkout.ship_city.value == '') { res = false; why = 'city (shipping)'; }
    else if(document.checkout.ship_zip.value == '') { res = false; why = 'zip (shipping)'; }
    else if(document.checkout.ship_phone.value == '') { res = false; why = 'phone (shipping)'; }
    else if(document.checkout.ship_state.selectedIndex == 0 && (document.checkout.ship_country.selectedIndex == 1 || document.checkout.ship_country.selectedIndex == 2)) { res = false; why = 'state (shipping)'; }
    else if(document.checkout.bill_country.selectedIndex == 0 || document.checkout.bill_country.selectedIndex == 3) { res = false; why = 'country (shipping)'; }

    if($("#stored_cc").val() == "" && !$('#invoice').is(':checked'))
    {
	if(!document.checkout.cc_type[0].checked && !document.checkout.cc_type[1].checked && !document.checkout.cc_type[2].checked) { res = false; why = 'card type'; }
	else if(document.checkout.cc_num.value == '') { res = false; why = 'credit card number'; }
	else if(document.checkout.cv_num.value == '') { res = false; why = 'card verification number'; }    
    }

    if(!$('#ship_zigi').is(':checked'))
    {
	if(document.checkout.ship_company.value == '') { res = false; why = 'shipping company name'; }
	else if($("#sco_sel").val() == "other" && document.checkout.ship_company_other.value == '') { res = false; why = 'shipping company name'; }
	else if(document.checkout.ship_account.value == '') { res = false; why = 'shipping company account number'; }
    }

    if(!res)
    {
	alert('You must enter your ' + why + '.');
	return false;
    }
    else return true;
}



//////////////////////////////////////////////////////////
//
// Register/Update Functions 
//
//////////////////////////////////////////////////////////

function initRegister()
{
    changeRegisterStateOptions('bill');
    changeRegisterStateOptions('ship');
    changeRegisterStateOptions('normal');
    $("#b2bCB").click(
	function()
	{
	    if(document.register.b2b.checked)
	    {
		$(".b2b-required").show();
	    }
	    else 
	    {
		$(".b2b-required").hide();
	    }
	}
    );

    $("#ship_zigi").click(
	function()
	{
	    if($('#ship_zigi').is(':checked'))
	    {
		$(".shipRow").fadeTo(300, '.40');
		$(".shipRow .b2b-required").hide();
	    }

	    else
	    {
		$(".shipRow").fadeTo(300, '1');
		$(".shipRow .b2b-required").show();
	    }
	}
    );

    if(window.location.href.indexOf('?') >= 0)
    {
	document.register.email.value = window.location.href.substring(window.location.href.indexOf('?') + 1);
    }
}

function regSelect(type)
{
    //cosmetically modify the registration page based on type
    if(type == "b2b")
    {
	document.register.b2b.checked = true;
	$("#businessInfo th").html("Your business information-");
	$("#retailInfo th").html("Your personal information-");
	$("#businessInfo").remove().prependTo("#regWrap");
	$("#optionalNotice").hide();
	$("#bdayrow").hide();
	$(".b2b-required").show();
    }

    else if(type == "b2c")
    {
	$("#businessInfo").hide();
    }

    $("#regSelect").hide();
    $("#regWrap").show();
}

function sameRegisterInfoBilling()
{
    document.register.bill_first.value = document.register.firstname.value;
    document.register.bill_last.value = document.register.lastname.value;
    document.register.bill_address1.value = document.register.address1.value;
    document.register.bill_address2.value = document.register.address2.value;
    document.register.bill_city.value = document.register.city.value;
    document.register.bill_zip.value = document.register.zip.value;
    document.register.bill_phone.value = document.register.phone.value;
    document.register.bill_fax.value = document.register.fax.value;
    document.register.bill_mobile.value = document.register.mobile.value;
    document.register.bill_country.selectedIndex = document.register.country.selectedIndex;
    changeRegisterStateOptions('bill');
    document.register.bill_state.selectedIndex = document.register.normal_state.selectedIndex;
}

function sameRegisterInfoShipping()
{
    document.register.ship_first.value = document.register.bill_first.value;
    document.register.ship_last.value = document.register.bill_last.value;
    document.register.ship_address1.value = document.register.bill_address1.value;
    document.register.ship_address2.value = document.register.bill_address2.value;
    document.register.ship_city.value = document.register.bill_city.value;
    document.register.ship_zip.value = document.register.bill_zip.value;
    document.register.ship_phone.value = document.register.bill_phone.value;
    document.register.ship_fax.value = document.register.bill_fax.value;
    document.register.ship_mobile.value = document.register.bill_mobile.value;
    document.register.ship_country.selectedIndex = document.register.bill_country.selectedIndex;
    changeRegisterStateOptions('ship');
    document.register.ship_state.selectedIndex = document.register.bill_state.selectedIndex;
}

function changeRegisterStateOptions(which)
{
    var country;
    if(which == 'bill') country = document.register.bill_country.options[document.register.bill_country.selectedIndex].value;
    else if(which == 'ship') country = document.register.ship_country.options[document.register.ship_country.selectedIndex].value;
    else if(which == 'normal') country = document.register.country.options[document.register.country.selectedIndex].value;

    if(country == 'US' || country == 'CA')
    {
	$("#" + which + "_state_td").empty().append( $("#" + country + "_state_select").clone()[0] );
	$("#" + which + "_state_td select").attr('name', which + "_state");
    }

    else
    {
	$("#" + which + "_state_td").empty().append( $("#other_state_select").clone()[0] );
	$("#" + which + "_state_td select").attr('name', which + "_state");
    }
}


//this is a dual purpose validation function for both the register and update forms, since they are so similar
function validateRegisterForm() {
    try
    {
	var res = true;
	var why;

	//if update form, populate the hidden inputs with the login info, so we can validate on the backend if they have permission to update their account
	if(document.register.formType.value == "update")
        {
	    document.register.email.value = $.cookies.get("email", defaultCookieOptions);
	    document.register.key.value = $.cookies.get("key", defaultCookieOptions);
	}

	if(document.register.email.value == '' || document.register.email.value.indexOf('@') < 0) { res = false; why = 'email'; }

	//register form has a password and confirm email field, update doesn't
	if(document.register.formType.value == "register")
	{
	    if(document.register.email.value != document.register.cemail.value)
	    {
		alert('Your email addressses do not match.');
		return false;
	    }

	    if(document.register.password.value == '') { res = false; why = 'password'; }
	    if(document.register.password.value != document.register.cpassword.value)
	    {
		alert('Your passwords do not match.');
		return false;
	    }
	}

	if(document.register.firstname.value == '') { res = false; why = 'first name'; }
	else if(document.register.lastname.value == '') { res = false; why = 'last name'; }

	if(document.register.b2b.checked)
	{
	    if(document.register.business.value == '') { res = false; why = 'business name'; }
	    else if(document.register.business_phone.value == '') { res = false; why = 'business phone number'; }
	    else if(document.register.tax_id.value == '') { res = false; why = 'tax ID'; }
	    else if(document.register.dba.value == '') { res = false; why = 'business (doing business as)'; }
	    else if(document.register.phone.value == '') { res = false; why = 'phone number'; }
	    else if(document.register.address1.value == '') { res = false; why = 'address'; }
	    else if(document.register.city.value == '') { res = false; why = 'city'; }
	    else if(document.register.zip.value == '') { res = false; why = 'zip'; }
	    else if(document.register.normal_state.selectedIndex == 0 && (document.register.country.selectedIndex == 1 || document.register.country.selectedIndex == 2)) { res = false; why = 'state'; }
	    else if(document.register.country.selectedIndex == 0 || document.register.country.selectedIndex == 3) { res = false; why = 'country'; }
	    else if(document.register.bill_first.value == '') { res = false; why = 'first name (billing)'; }
	    else if(document.register.bill_last.value == '') { res = false; why = 'last name (billing)'; }
	    else if(document.register.bill_address1.value == '') { res = false; why = 'address (billing)'; }
	    else if(document.register.bill_city.value == '') { res = false; why = 'city (billing)'; }
	    else if(document.register.bill_zip.value == '') { res = false; why = 'zip (billing)'; }
	    else if(document.register.bill_phone.value == '') { res = false; why = 'phone (billing)'; }
	    else if(document.register.bill_state.selectedIndex == 0 && (document.register.bill_country.selectedIndex == 1 || document.register.bill_country.selectedIndex == 2)) { res = false; why = 'state (billing)'; }
	    else if(document.register.bill_country.selectedIndex == 0 || document.register.bill_country.selectedIndex == 3) { res = false; why = 'country (billing)'; }
	    else if(document.register.ship_first.value == '') { res = false; why = 'first name (shipping)'; }
	    else if(document.register.ship_last.value == '') { res = false; why = 'last name (shipping)'; }
	    else if(document.register.ship_address1.value == '') { res = false; why = 'address (shipping)'; }
	    else if(document.register.ship_city.value == '') { res = false; why = 'city (shipping)'; }
	    else if(document.register.ship_zip.value == '') { res = false; why = 'zip (shipping)'; }
	    else if(document.register.ship_phone.value == '') { res = false; why = 'phone (shipping)'; }
	    else if(document.register.ship_state.selectedIndex == 0 && (document.register.ship_country.selectedIndex == 1 || document.register.ship_country.selectedIndex == 2)) { res = false; why = 'state (shipping)'; }
	    else if(document.register.bill_country.selectedIndex == 0 || document.register.bill_country.selectedIndex == 3) { res = false; why = 'country (shipping)'; }

	    if(!$('#ship_zigi').is(':checked'))
	    {
		if(document.register.ship_company.value == '') { res = false; why = 'shipping company name'; }
		else if($("#sco_sel").val() == "other" && document.register.ship_company_other.value == '') { res = false; why = 'shipping company name'; }
		else if(document.register.ship_account.value == '') { res = false; why = 'shipping company account number'; }		
	    }
	}
	
	if(!res)
	{
	    alert('You must enter your ' + why + '.');
	    return false;
	}

	else return true;
    }

    catch(e)
    {
	//console.log(e.toString());
	return false;
    }
}

function toggleSCO()
{
    if($("#sco_sel").val() == "other") $("#sco").slideDown();
    else $("#sco").slideUp();
}

function initUpdateAcct()
{
    if($.cookies.get("email", defaultCookieOptions) && $.cookies.get("key", defaultCookieOptions))
    {
	changeRegisterStateOptions('bill');
	changeRegisterStateOptions('ship');
	changeRegisterStateOptions('normal');

	$("#b2bCB").click(
	    function()
	    {
		if(document.register.b2b.checked)
		{
		    $(".b2b-required").show();
		}
		else 
		{
		    $(".b2b-required").hide();
		}
	    }
	);

	$("#ship_zigi").click(
	    function()
	    {
		if($('#ship_zigi').is(':checked'))
		{
		    $(".shipRow").fadeTo(300, '.40');
		    $(".shipRow .b2b-required").hide();
		}
		
		else
		{
		    $(".shipRow").fadeTo(300, '1');
		    $(".shipRow .b2b-required").show();
		}
	    }
	);
	
	var dataString = 'email='+ $.cookies.get('email', defaultCookieOptions) + '&key=' + $.cookies.get('key', defaultCookieOptions);
	$.ajax(
	    {
		type: "POST",
		url: "/cgi/customer-data.cgi",
		data: dataString,
		success: populateCustomerInfoUpdate
	    }
	);

	$.ajax(
	    {
		type: "POST",
		url: "/cgi/stored-cc-info.cgi",
		data: dataString,
		success: populateStoredCCInfoUpdate
	    }
	);  
    }

    else
    {
	$("#register").empty().html('<p>You must be logged in to update your account!</p>');
    }
}


function populateCustomerInfoUpdate(d)
{
    d = eval( "(" + d + ")" );
    for(var i in d)
    {
	d = d[i];
	break;
    }

    if(d.account_type == "B")
    {
	$("#b2bCB").attr("checked", true);
	$("#b2bCall").hide();
	$("#optionalNotice").hide();
	document.register.old_account_type.value = d.account_type;
	document.register.old_approved.value = d.approved;
	$(".b2b-required").show();
    }

    document.register.display_email.value = d.email;
    document.register.firstname.value = d.firstname;
    document.register.lastname.value = d.lastname;
    document.register.phone.value = d.phone;
    document.register.address1.value = d.address1;
    document.register.address2.value = d.address2;
    document.register.city.value = d.city;
    document.register.zip.value = d.zip;
    document.register.business.value = d.business;
    document.register.business_phone.value = d.business_phone;
    document.register.tax_id.value = d.tax_id;
    document.register.dba.value = d.dba;
    document.register.fax.value = d.fax;
    document.register.mobile.value = d.mobile;
    document.register.comments.value = d.comments;

    if(d.newsletter == "Y") $("#newsCheck").attr("checked", true);

    var bvals = d.birthday.split('-');
    $("#birthday_year").val(bvals[0]);
    $("#birthday_month").val(bvals[1]);
    $("#birthday_day").val(bvals[2]);

    document.register.bill_first.value = d.bill_first;
    document.register.bill_last.value = d.bill_last;
    document.register.bill_address1.value = d.bill_address1;
    document.register.bill_address2.value = d.bill_address2;
    document.register.bill_city.value = d.bill_city;
    document.register.bill_zip.value = d.bill_zip;
    document.register.bill_phone.value = d.bill_phone;
    document.register.bill_fax.value = d.bill_fax;
    document.register.bill_mobile.value = d.bill_mobile;

    document.register.ship_first.value = d.ship_first;
    document.register.ship_last.value = d.ship_last;
    document.register.ship_address1.value = d.ship_address1;
    document.register.ship_address2.value = d.ship_address2;
    document.register.ship_city.value = d.ship_city;
    document.register.ship_zip.value = d.ship_zip;
    document.register.ship_phone.value = d.ship_phone;
    document.register.ship_fax.value = d.ship_fax;
    document.register.ship_mobile.value = d.ship_mobile;

    if(d.ship_zigi == "Y") 
    {
	$("#ship_zigi").attr("checked", true);
	$(".shipRow").fadeTo(300, '.40');
	$(".shipRow .b2b-required").hide();
    }

    document.register.ship_company_other.value = d.ship_company_other;
    document.register.ship_account.value = d.ship_account;

    $("#bill_country").val(d.bill_country);
    $("#ship_country").val(d.ship_country);
    $("#country").val(d.country);

    changeRegisterStateOptions('bill');
    changeRegisterStateOptions('ship');
    changeRegisterStateOptions('normal');

    $("#bill_state_td select").val(d.bill_state);
    $("#ship_state_td select").val(d.ship_state);
    $("#normal_state_td select").val(d.state);

    $("#sco_sel").val(d.ship_company);
}


function populateStoredCCInfoUpdate(d)
{
    var stored = false;
    var seen = {};

    d = eval( "(" + d + ")" );    
    for(var i in d)
    {
	if(!seen[i])
	{
	    stored = true;
	    seen[i] = true;
	    var card = d[i].cc_desc.substring(0, d[i].cc_desc.indexOf(' ')).toLowerCase();
	    $("#stored-accounts").append('<p id="cc-' + d[i].customer_id + '"><a href="javascript:deleteStoredCCInfo(\'' + d[i].customer_id + '\');"><img src="images/false.gif" /></a> <img src="images/' + card + '.gif" /> <em>' + d[i].cc_desc + '</em></p>');
	}
    }

    if(stored) $("#update-stored-accounts").show();
}

function deleteStoredCCInfo(cid)
{
    if(confirm("Remove this saved account?"))
    {
	if($.cookies.get("email", defaultCookieOptions) && $.cookies.get("key", defaultCookieOptions))
	{
	    $("#stored-accounts-loading").show();
	    $("#stored-accounts").hide();

	    var dataString = 'email='+ $.cookies.get('email', defaultCookieOptions) + '&key=' + $.cookies.get('key', defaultCookieOptions) + '&cid=' + cid;
	    $.ajax(
		{
		    type: "POST",
		    url: "/cgi/delete-stored-cc.cgi",
		    data: dataString,
		    success: function(d)
		    {
			$("#stored-accounts-loading").hide();
			$("#stored-accounts").show();

			if(d.match("Successfully Deleted " + cid))
			{
			    $("#cc-" + cid).html('<span class="red">Deleted!</span>').fadeOut(3000);
			}

			else alert("There was an error removing this account, please contact ZiGiny support.");
		    },
		    error: function()
		    {
			$("#stored-accounts-loading").hide();
			$("#stored-accounts").show();

			alert("There was an error removing this account, please contact ZiGiny support.");
		    }
		}
	    );  
	}
    }
}


//////////////////////////////////////////////////////////
//
// Login Functions 
//
//////////////////////////////////////////////////////////

function login()
{
    var email = $("#loginEmail").val();
    var password = $("#loginPassword").val();
    var dataString = 'email='+ email + '&password=' + password;

    $("#loginPassword").val('');

    $("#loginLoading").show();
    $("#loginResults").empty();
    
    $.ajax({
	type: "POST",
	url: "/cgi/login.cgi",
	data: dataString,
	success: function(d)
	{
	    var key = d;
	    $.cookies.del("email", defaultCookieOptions);
	    $.cookies.del("key", defaultCookieOptions);

	    var options = 
		{
		    hoursToLive: 1,
		    path: "/",
		    domain: ".ziginy.com"
		}

	    var rememberOptions = 
		{
		    hoursToLive: 24 * 30,
		    path: "/",
		    domain: ".ziginy.com"
		}

	    if($("#remember").attr('checked'))
	    {
		$.cookies.set("remember", "remember", rememberOptions);
		$.cookies.set("email", email, rememberOptions);
	    }
	    
	    else
	    {
		$.cookies.del("remember", defaultCookieOptions);
		$.cookies.set("email", email, options);
	    }

	    $.cookies.set("key", key, options);
	    $("#loginLoading").hide();
	    $("#loginResults").html('<span class="green">Logged in.</span>');
	    $("#showLogin").html('<strong>My Profile-</strong>' + $.cookies.get("email", defaultCookieOptions));
	    checkTaxID();
	    setTimeout(
		function()
		{
		    $("#login")
			.fadeOut(
			    'slow', 
			    function()
			    {
				$("#loginResults").empty();
				$("#notLoggedIn").hide();
				$("#loggedIn").show();					    
			    }
			);
		},
		1500
	    );

	    $("#categories").prepend('<li><a href="/coming-soon.html"><strong>Pre Order</strong></a></li>');

	    //FFS Change all the category links to point to the private pages
	    $("#subNav a, #categories a, #brands a").each(
		function()
		{
		    if(!$(this).attr('href').match(/coming\-soon/))
			$(this).attr('href' , '/private-category.html?' + $(this).attr('href').replace(".html", "").replace("../", ""));
		}
	    );

	    //if on a style page, do the b2b_check
	    if(window.location.href.match(/\/styles\//)) window.location.href=window.location.href;

	    //if on a category page, redirect to private category page to show correct shoes and fix nav links
	    for(var i in CATEGORIES)
	    {
		if(window.location.href.match("/" + i + ".html")) window.location = "/private-category.html?" + i;
	    }

	    //if on checkout page, reload
	    if(window.location.href.indexOf('checkout.html') >= 0) window.location = "/checkout.html";
	},

	error: function(d)
	{
	    $.cookies.del("email", defaultCookieOptions);
	    $.cookies.del("key", defaultCookieOptions);
	    $.cookies.del("remember", defaultCookieOptions);

	    $("#loginLoading").hide();
	    $("#loginResults").html('<span class="red">Login error.</span>');
	    $("#showLogin").text("Login");
	}
    });  
}

function logout()
{
    var dataString = 'email='+ $.cookies.get('email', defaultCookieOptions) + '&key=' + $.cookies.get('key', defaultCookieOptions);
    $.ajax({
	type: "POST",
	url: "/cgi/logout.cgi",
	data: dataString,
	success: function(d)
	{
	    $.cookies.del("email", defaultCookieOptions);
	    $.cookies.del("key", defaultCookieOptions);
	    $.cookies.del("remember", defaultCookieOptions);

	    $("#showLogin").text("Login");
	    $("#logoutResults").html('<span class="green">Logged out.</span>');
	    
	    window.location = "/";
	},
	error: function()
	{
	    $.cookies.del("email", defaultCookieOptions);
	    $.cookies.del("key", defaultCookieOptions);
	    $.cookies.del("remember", defaultCookieOptions);

	    $("#showLogin").text("Login");
	    $("#logoutResults").html('<span class="green">Logged out.</span>');
	    
	    window.location = "/";
	}
    });  
}

function checkTaxID()
{
    var dataString = 'email='+ $.cookies.get('email', defaultCookieOptions) + '&key=' + $.cookies.get('key', defaultCookieOptions);
    $.ajax(
	{
	    type: "POST",
	    url: "/cgi/check_taxid.cgi",
	    data: dataString,
	    success: function(d)
	    {
		if(d == "")
		{
		    $("#taxAlert, #shade").show();
		}
	    }
	}
    );
}

function addTaxID()
{
    var dataString = 'email='+ $.cookies.get('email', defaultCookieOptions) + '&key=' + $.cookies.get('key', defaultCookieOptions) + '&tax_id=' + $("#newTaxID").val();
    $.ajax(
	{
	    type: "POST",
	    url: "/cgi/add_taxid.cgi",
	    data: dataString,
	    success: function(d)
	    {
		if(d == "ok")
		{
		    window.location = "/ack.html?tax";
		}

		else
		{
		    window.location = "/error.html?tax";
		}
	    }
	}
    );
}

function taxLater()
{
    $("#taxAlert, #shade").hide();
}

function showAvailableB2BItems()
{
    if(!$.cookies.get('email', defaultCookieOptions)) document.location = "/login.html";

    var dataString = 'email='+ $.cookies.get('email', defaultCookieOptions) + '&key=' + $.cookies.get('key', defaultCookieOptions);

    $.ajax({
	type: "POST",
	url: "/cgi/b2b_list_all.cgi",
	data: dataString,
	success: function(d)
	{
	    var b2bList = [];
	    var b2bStyleData = eval( "(" + d + ")" );
	    
	    for(var i in b2bStyleData)
	    {
		b2bList.push({"style_fixed":b2bStyleData[i].style_fixed , "style":b2bStyleData[i].style})
	    }

	    b2bList.sort(
		function(a,b)
		{ 
                    if (a.style < b.style) return -1;
                    if (a.style > b.style) return 1;
                    return 0;
		}
	    );

	    //build list of styles to show to b2b user
	    var b2bHtml = '<h2>Hello <em>' + $.cookies.get('email', defaultCookieOptions) + '</em>, please select a style to purchase:</h2><ul id="b2b-style-list">';
	    for(var i = 0; i < b2bList.length; i++)
	    {
		b2bHtml += '<li><a href="/styles/' + b2bList[i].style_fixed + '.html">' + b2bList[i].style + '</a></li>';
	    }
	    b2bHtml += '</ul>';

	    $("#b2b-home").html(b2bHtml);
	},
	error: function(d)
	{

	}
    });      
}



//////////////////////////////////////////////////////////
//
// Password Reset Functions
//
//////////////////////////////////////////////////////////

function populatePWResetValues()
{
    var args = window.location.search.split('&');

    $("#email").val(unescape(args[0].substring(args[0].indexOf('=') + 1)));
    $("#key").val(args[1].substring(args[1].indexOf('=') + 1));
}

function validatePWResetForm()
{
    if(document.getElementById('password').value == '')
    {
	alert("Your password cannot be blank");
	return false;
    }

    else if(document.getElementById('password').value != document.getElementById('c_password').value)
    {
	alert("Your passwords do not match");
	return false;
    }

    else return true;
}




//////////////////////////////////////////////////////////
//
// Order History Functions
//
//////////////////////////////////////////////////////////

function loadOrderHistory()
{
    var dataString = 'email='+ $.cookies.get('email', defaultCookieOptions) + '&key=' + $.cookies.get('key', defaultCookieOptions);
    $.ajax(
	{
	    type: "POST",
	    url: "/cgi/order-history.cgi",
	    data: dataString,
	    success: showOrderHistory
	}
    );  
}

function showOrderHistory(r)
{
    r = eval( "(" + r + ")" );

    var html = '<table id="order-results-table"><thead><tr>' + 
	'<th class="actions"></th>' +
	'<th>Order #</th>' +
	'<th>Date</th>' + 
	'<th>Total</th>' +
	'<th>Outstanding</th>' + 
	'</tr></thead><tbody>';

    for(var i in r)
    {
	for(var j in r[i])
	{
	    if(!r[i][j]) r[i][j] = "";
	}
	
	var outTag = '<strong>';
	if(parseInt(r[i].outstanding_payment) > 0) outTag = '<strong class="red">';

	html += '<tr><td class="actions"><a onclick="orderDetail(' + r[i].ROW_ID + ');"><img src="images/detail.gif" /></a></td>' +
	    '<td class="orderNum">#B' + r[i].order_type + r[i].ROW_ID + '</td>' +
	    '<td class="orderDate">' + r[i].timestamp.substring(0, 10) + '</td>' +
	    '<td class="orderTotal">$' + formatPrice(r[i].total) + '</td>' +
	    '<td class="orderOutstanding">' + outTag + '$' + formatPrice(r[i].outstanding_payment) + '</strong></td>' +
	    '</tr>';

	var shipInfo = "Shipped by: <em> " + r[i].ship_company + '</em>';
	if(r[i].ship_company == "other") shipInfo = "Shipped by: <em> " + r[i].ship_company_other + '</em>';
	if(r[i].ship_zigi == "Y") shipInfo = "Shipped by: <em> FedEx (via ZiGiny)"  + r[i].ship_company_other + '</em>';

	var notes = "";
	if(r[i].notes && r[i].notes != "") notes = '<p class="notes"><strong>Order Notes:</strong> ' + r[i].notes + '</p>';

	html += '<tr class="detailRow" id="detail-' + r[i].ROW_ID + '"><td colspan="6">' + notes + 
	    '<p class="billDetail"><strong>Billing Information</strong><br /><br />' +
	    r[i].bill_first + ' ' + r[i].bill_last + '<br />' + r[i].bill_address1 + '<br />' + r[i].bill_address2 + '<br />' +
	    r[i].bill_city + ' ' + r[i].bill_state + ' ' + r[i].bill_zip + ' ' + r[i].bill_country + '<br />' +
	    'Phone: ' + r[i].bill_phone + '<br />Fax: ' + r[i].bill_fax  + '<br />Mobile: ' + r[i].bill_mobile + '<br />' +
	    'Account: ' + r[i].cc_desc_decrypted + 
	    '</p>' +
	    '<p class="shipDetail"><strong>Shipping Information</strong><br /><br />' +
	    r[i].ship_first + ' ' + r[i].ship_last + '<br />' + r[i].ship_address1 + '<br />' + r[i].ship_address2 + '<br />' +
	    r[i].ship_city + ' ' + r[i].ship_state + ' ' + r[i].ship_zip + ' ' + r[i].ship_country + '<br />' +
	    'Phone: ' + r[i].ship_phone + '<br />Fax: ' + r[i].ship_fax  + '<br />Mobile: ' + r[i].ship_mobile + '<br />' + shipInfo +
	    '</p><p class="itemDetails" id="itemDetail-' + r[i].ROW_ID + '"></p>' +
	    '</td></tr>';
    }

    html += '</tbody></table>';

    $("#loading").hide();
    $("#results").append(html);

    $("#order-results-table").tablesorter(); 
    $("#order-results-table th").click(
	function()
	{
	    $(".detailRow").hide();
	}
    ); 
}

function orderDetail(which)
{
    $("#detail-" + which).show();

    var dataString = 'email='+ $.cookies.get('email', defaultCookieOptions) + '&key=' + $.cookies.get('key', defaultCookieOptions) + '&ROW_ID=' + which;
    $.ajax(
	{
	    type: "POST",
	    url: "/cgi/order-detail.cgi",
	    data: dataString,
	    success: showOrderDetail
	}
    );  
}

function showOrderDetail(r)
{
    r = eval( "(" + r + ")" );

    var which = "";

    var html = '<strong>Item Information</strong><br /><br />';
    
    for(var i in r)
    {
	which = r[i].ROW_ID;
	for(var j in r[i])
	{
	    if(!r[i][j]) r[i][j] = "";
	}

	var shipped = '<strong class="oh-noship">This item has not yet shipped.</strong>';
	if(r[i].shipped == 'Y')
	{
	    shipped = '<strong class="oh-yesship">This item has shipped!</strong> <span class="oh-track">Tracking #' + r[i].tracking_num + '</span>';
	}

	if(r[i].preorder == "Y")
	{
	    shipped += "<br />Pre-order";
	    if(r[i].expected_ship_date.match(/\d\d\d\d\-\d\d\-\d\d/) && r[i].expected_ship_date != "0000-00-00")
	    {
		var ed = new Date(r[i].expected_ship_date);
		shipped += " - Expected Ship Date: " + ed.toDateString().substring(4);
	    }
	}

	html += "<strong><em>" + r[i].STYLE + ' in ' + r[i].material + ' x' + r[i].qty + ' @ ' + formatPrice(r[i].price) + ' ea.</em></strong><br />' + shipped + '<br /><br />'; 

    }

    $("#itemDetail-" + which).html(html);
}


//////////////////////////////////////////////////////////
//
// Private Area Functions
//
//////////////////////////////////////////////////////////

function showPrivateItems()
{
    var dataString = 'email='+ $.cookies.get('email', defaultCookieOptions) + '&key=' + $.cookies.get('key', defaultCookieOptions);
    $.ajax({
	type: "POST",
	url: "/cgi/show_private_products.cgi",
	data: dataString,
	success: function(d)
	{
	    $("#coming-soon").html(d);
	    initCat('coming-soon');
	    $(".item_price_b2b").show();
	},
	error: function()
	{
	    window.location = "/";
	}
    });  
}

function showPrivateCategory()
{
    var fn = window.location.href.substring(window.location.href.indexOf('?') + 1);
    var arg = CATEGORIES[fn].cat_id;
    var lookup = "";

    if(arg.match(/\D/)) lookup = "&label=" + arg.replace('&' , 'AND');
    else lookup = "&cat=" + arg;

    document.title = document.title + " " + CATEGORIES[fn].category;
    $("#splash_category").append('<a href="' + CATEGORIES[fn].link + '"><img src="/images/splash/categories/' + fn + '.jpg" class="splash_category_img" alt="' + CATEGORIES[fn].category + '" /></a>');

    var dataString = 'email='+ $.cookies.get('email', defaultCookieOptions) + '&key=' + $.cookies.get('key', defaultCookieOptions) + lookup;
    $.ajax({
	type: "POST",
	url: "/cgi/show_private_category.cgi",
	data: dataString,
	success: function(d)
	{
	    $("#private-category").html(d);
	    initCat(fn);
	    $(".item_price_b2b").show();
	},
	error: function()
	{
	    window.location = "/";
	}
    });  
}

function showPrivateDetail()
{
    var style = window.location.href.substring(window.location.href.indexOf('?') + 1).toUpperCase();
    document.title = document.title + style.replace("_", " ");

    var dataString = 'email='+ $.cookies.get('email', defaultCookieOptions) + '&key=' + $.cookies.get('key', defaultCookieOptions) + '&style=' + style;
    $.ajax({
	type: "POST",
	url: "/cgi/show_private_detail.cgi",
	data: dataString,
	success: function(d)
	{
	    $("#product").html(d);
	    B2BAUTH = true;
	    $("#b2b_price").show();
	    
	    var dataString = 'email='+ $.cookies.get('email', defaultCookieOptions) + '&key=' + $.cookies.get('key', defaultCookieOptions) + '&style=' + style + '&customer=B';
	    $.ajax({
		type: "POST",
		url: "/cgi/product_discount.cgi",
		data: dataString,
		success: function(d2)
		{
		    DISCOUNTS = eval("(" + d2 + ")");
		    loadProductInfo();
		    loadLargeImages();
		},
		error: function(d2)
		{
		    loadProductInfo();
		    loadLargeImages();
		}
	    });
	    
	},
	error: function()
	{
	    window.location = "/";
	}
    });  
}


//////////////////////////////////////////////////////////
//
// Product Page Functions 
//
//////////////////////////////////////////////////////////

var B2BAUTH = false;
var DISCOUNTS = {};

function checkB2B()
{
    //STYLE is a 'global' set in <body> (see /page_builder/styles/includes/style.frm)
    var dataString = 'email='+ $.cookies.get('email', defaultCookieOptions) + '&key=' + $.cookies.get('key', defaultCookieOptions) + '&style=' + STYLE;
    $.ajax({
	type: "POST",
	url: "/cgi/b2b_check.cgi",
	data: dataString,
	success: function(d)
	{
	    if(d == "ok")
	    {
		B2BAUTH = true;
		$("#b2b_price").show();

		var dataString = 'email='+ $.cookies.get('email', defaultCookieOptions) + '&key=' + $.cookies.get('key', defaultCookieOptions) + '&style=' + STYLE + '&customer=B';
		$.ajax({
		    type: "POST",
		    url: "/cgi/product_discount.cgi",
		    data: dataString,
		    success: function(d2)
		    {
			DISCOUNTS = eval("(" + d2 + ")");
			loadProductInfo();
			loadLargeImages();
		    },
		    error: function(d2)
		    {
			loadProductInfo();
			loadLargeImages();
		    }
		});
	    }

	    else
	    {
		var dataString = 'style=' + STYLE + '&customer=C';
		$.ajax({
		    type: "POST",
		    url: "/cgi/product_discount.cgi",
		    data: dataString,
		    success: function(d2)
		    {
			DISCOUNTS = eval("(" + d2 + ")");
			loadProductInfo();
			loadLargeImages();
		    },
		    error: function(d2)
		    {
			loadProductInfo();
			loadLargeImages();
		    }
		});
	    }
	},

	error: function(d)
	{
	    var dataString = 'style=' + STYLE  + '&customer=C';
            $.ajax({
                type: "POST",
                url: "/cgi/product_discount.cgi",
                data: dataString,
                success: function(d2)
                {
		    DISCOUNTS = eval("(" + d2 + ")");
		    loadProductInfo();
		    loadLargeImages();
		},
                error: function(d2)
                {
		    loadProductInfo();
		    loadLargeImages();
                }
            });
	}
    });
}



var RETAIL;
var RETAIL_FIXED;
var RETAIL_BASE_PRICE;

var IMG = "1"; //keeps track of what image is currently being viewed

function loadProductInfo()
{
    $.ajax({
	//STYLE is a 'global' set in <body> (see /page_builder/styles/includes/style.frm)
	url : "/cgi/retail_lookup.cgi?" + STYLE , 
	success : function(d)
	{
	    RETAIL = eval( "(" + d + ")" );
	    RETAIL_FIXED = [];

	    for(var i in RETAIL)
	    {
		RETAIL_FIXED.push({ "UPC_NO" : RETAIL[i].UPC_NO , "CLR_ABBR" : RETAIL[i].CLR_ABBR , "SIZE" : RETAIL[i].SIZE , "AVAILABLE" : parseInt(RETAIL[i].AVAILABLE) });
	    }

	    if(B2BAUTH) loadB2BInfo();
	    else
	    {
		RETAIL_BASE_PRICE = $("#curr_price").val();

		RETAIL_FIXED.sort( 
		    function(a,b)
		    { 			    
			if (parseFloat(a.SIZE) < parseFloat(b.SIZE)) return -1;
			else if (parseFloat(a.SIZE) > parseFloat(b.SIZE)) return 1;
			return 0;
		    }
		);

		for(var i = 0; i < RETAIL_FIXED.length; i++)
		{
		    if(RETAIL_FIXED[i].AVAILABLE > 0)
			$("#master-sizes").append('<option class="sr-' + RETAIL_FIXED[i].CLR_ABBR + '" value="' + RETAIL_FIXED[i].SIZE + '">' + RETAIL_FIXED[i].SIZE  + '</option>');
		    else
			$("#master-sizes").append('<option class="sr-' + RETAIL_FIXED[i].CLR_ABBR + '" value="' + RETAIL_FIXED[i].SIZE + '" disabled>' + RETAIL_FIXED[i].SIZE  + '</option>');
		}
		
		$("#qtyAdd, #size").show();
		$("#msrp").hide();

		$("#price").css("fontSize", "18px").css("fontWeight", "bold");

		//trigger a color change here so the right sizes/images/prices are shown
		changeColor();
	    }
	},
	error: function(d)
	{
	    
	}
    });

    //magnification
    $(".ps").jqzoom(
	{
	    zoomType:"reverse",
	    zoomHeight: 406
	}
    );

    //setup hover on 360
    $("#d360").hover(
	function()
	{
	    $("#note360").fadeIn('fast');
	},

	function()
	{
	    $("#note360").fadeOut('fast');
	}
    );

    //thumbs
    $("#controlImages img").hover(
	function()
	{
	    var newIMG = $(this).attr('id').replace("pc-", "");
	    if(newIMG != IMG)
	    {
		IMG = newIMG;
		$("#pc-" + IMG + "a").click();
		$(".ps").hide();
		$("#ps-" + IMG).fadeIn('fast');
	    }
	},
	function()
	{

	}
    );
}

function bindLightbox()
{
    //this is called by the hacked jqzoom plugin to call it only after creating the element it needs to work on (.zoomPad)
    $(".zoomPad").click(
	function()
	{
	    window.scroll(0,0);
	    $("#pz-" + IMG).show();
	    $("#shade").show();
	    $("#productZoom").fadeIn();
	}
    );

    $("#productZoom, #shade").click(
	function()
	{
	    $(".prodZoom").hide();
	    $("#shade").hide();
	    $("#productZoom").hide();
	}
    );
}

var B2B;
var B2B_FIXED;

function loadB2BInfo()
{
    $.ajax({
	//STYLE is a 'global' set in <body> (see /page_builder/styles/includes/style.frm)
	url : "/cgi/b2b_lookup.cgi?" + STYLE , 
	success : function(d)
	{
	    B2B = eval( "(" + d + ")" );
	    
	    B2B_FIXED = [];
	    
	    for(var i in B2B)
	    {		
		//this try/catch in here because ZiGi sends invalid SCALE values occationally
		try { var numShoes = scaleLookup[B2B[i].SCALE].shoecount; }
		catch(e)
		{ 
		    //console.log(B2B[i].SCALE + ' - ' + e.toString());
		    continue; 
		}

		var totalPrice = Math.floor((parseFloat(B2B[i].LINE_PRICE) * numShoes) * 100) / 100;
		var toSell = parseInt(parseInt(B2B[i].ON_HAND / numShoes));
		var now = new Date();
		
		var dateValid = false;
		if(B2B[i].avail_date)
		{
		    //zigi wants to add 3 days to the availability date in the DB to account for warehouse delay or something
		    //don't ask why it's * 4 at the end instead of * 3, I don't know
		    var dateData = B2B[i].avail_date.match(/\d+/g);
		    if(dateData[1].charAt(0) == '0') dateData[1] = dateData[1].substring(1);
		    var ad = new Date(dateData[0], parseInt(dateData[1]) - 1, dateData[2]);
		    ad = new Date(ad.getTime() + (1000 * 60 *60 * 24 * 4));
		
		    //we also need a compare date one week in the past (from the pseudo availability date 3 days ahead from above)
		    //this translates to 4 days before now
		    var weekAgo = new Date(now.getTime() - (1000 * 60 *60 * 24 * 4));
		    if(ad > weekAgo) dateValid = true;
		}
		
		//make sure we have enough stock
		if(parseInt(B2B[i].ON_HAND) >= numShoes)
		{
		    B2B_FIXED.push({ "UPC_NO" : B2B[i].UPC_NO , "CLR_ABBR" : B2B[i].CLR_ABBR , "SCALE" : B2B[i].SCALE, "SIZERUN" : scaleLookup[B2B[i].SCALE].sizerun, "material" : B2B[i].material, "COUNT" : numShoes , "WIP" : B2B[i].WIP, "LINE_PRICE" : B2B[i].LINE_PRICE , "TOTAL_PRICE" : totalPrice, "AVAILABLE" : true, "toSell" : toSell , "avail_date" : null , "preOrder" : false });
		}
		
		//else check if this item is preorderable (have enough stock in the WIP field to sell at least one case, or availability date is < 1 week late)
		else if(dateValid || (parseInt(B2B[i].WIP) >= numShoes))
		{
		    B2B_FIXED.push({ "UPC_NO" : B2B[i].UPC_NO , "CLR_ABBR" : B2B[i].CLR_ABBR , "SCALE" : B2B[i].SCALE, "SIZERUN" : scaleLookup[B2B[i].SCALE].sizerun, "material" : B2B[i].material, "COUNT" : numShoes , "WIP" : B2B[i].WIP, "LINE_PRICE" : B2B[i].LINE_PRICE , "TOTAL_PRICE" : totalPrice, "AVAILABLE" : true, "toSell" : 99999999999 , "avail_date" : ad , "preOrder" : true });
		}
		
		//neither, mark as out of stock
		else
		{
		    B2B_FIXED.push({ "UPC_NO" : B2B[i].UPC_NO , "CLR_ABBR" : B2B[i].CLR_ABBR , "SCALE" : B2B[i].SCALE, "SIZERUN" : scaleLookup[B2B[i].SCALE].sizerun, "material" : B2B[i].material, "COUNT" : numShoes , "WIP" : B2B[i].WIP, "LINE_PRICE" : B2B[i].LINE_PRICE , "TOTAL_PRICE" : totalPrice, "AVAILABLE" : false, "toSell" : 0 , "avail_date" : ad , "preOrder" : false });
		}
	    }
	    
	    B2B_FIXED.sort( 
		function(a,b)
		{ 			    
		    if (a.AVAILABLE && !b.AVAILABLE) return -1;
		    else if (b.AVAILABLE && !a.AVAILABLE) return 1;
		    else if (a.preOrder && !b.preOrder) return -1;
		    else if (b.preOrder && !a.preOrder) return 1;
		    else if (a.SIZERUN < b.SIZERUN) return -1;
		    else if (a.SIZERUN > b.SIZERUN) return 1;
		    return 0;
		}
	    );
	    
	    for(var i = 0; i < B2B_FIXED.length; i++)
	    {
		$("#master-sizes").append('<option class="sr-' + B2B_FIXED[i].CLR_ABBR + '" value="' + B2B_FIXED[i].SCALE + '">' + B2B_FIXED[i].SIZERUN  + '</option>');
	    }
	    
	    
	    $("#b2b").append('<p id="b2bPriceInfo">&nbsp;</p>');
	    $("#b2b").append('<p id="oos"><span id="so_notice">Sold Out - </span><a href="javascript:notifyOOS();">Notify me when this product is available</a></p>');
	    $("#b2b").append('<p id="ships"><span id="lastCase">Hurry! Only 1 case left! - </span> Ships Next Day!</p>');
	    $("#b2b").append('<p id="sizeHelp"><a target="_blank" href="/sizes.html">View ZiGi Size Runs</a></p>');
	    $("#price").addClass('b2bPrice');
	    
	    $("#b2b").append('<p id="po"><span id="po-date"></span> You may preorder this shoe now.</p>');
	    
	    $("#quanLabel").html("Case Qty:");
	    $("#qtyAdd, #size, #msrp, #free-shipping").show();
	    
	    //trigger a color change here so the right sizes/images/prices are shown
	    changeColor();
	}
    });
}


function loadLargeImages()
{
    //download these after the page loads to help speed issues
    var img = $("#img_name").val();
    $("#productZoom").append(
        '<img id="pz-1" class="prodZoom" src="../images/shoes/lg/' + img + '_1.jpg" alt="' + STYLE + ' Image 1" />' +
            '<img id="pz-2" class="prodZoom" src="../images/shoes/lg/' + img + '_2.jpg" alt="' + STYLE + ' Image 2" />' +
            '<img id="pz-3" class="prodZoom" src="../images/shoes/lg/' + img + '_3.jpg" alt="' + STYLE + ' Image 3" />' +
            '<img id="pz-4" class="prodZoom" src="../images/shoes/lg/' + img + '_4.jpg" alt="' + STYLE + ' Image 4" />' +
            '<img id="pz-5" class="prodZoom" src="../images/shoes/lg/' + img + '_5.jpg" alt="' + STYLE + ' Image 5" />'
    );

    //$("#d360").html('<img id="p360" src="/images/shoes/360/' + STYLE.toLowerCase() + '.gif" />');
}

function changeSize()
{
    if(!B2BAUTH) return;

    //update price field
    var newColor = $("#color").val();
    var newSize = $("#size").val();
    var i = getB2BIndex(newColor, newSize);
    var qty = parseInt($("#qty").val());
    var pcs = qty * parseInt(B2B_FIXED[i].COUNT);

    var newTotal = Math.floor((parseFloat(B2B_FIXED[i].TOTAL_PRICE) * qty)*100)/100;
    if(computeProductDiscount(newColor, pcs, newTotal) != newTotal)
    {
	$("#b2bPriceInfo").html(pcs + ' pairs @ $' + formatPrice(B2B_FIXED[i].LINE_PRICE) + ' ea pair = <span id="b2bTotal"><strike>$' + formatPrice(newTotal) + '</strike></span><br /><span class="salePrice">Sale Price: <strong>$' + formatPrice(computeProductDiscount(newColor, pcs, newTotal)) + '</strong></span>');
    }

    else
    {
	$("#b2bPriceInfo").html(pcs + ' pairs @ $' + formatPrice(B2B_FIXED[i].LINE_PRICE) + ' ea pair = <span id="b2bTotal">$' + formatPrice(newTotal) + '</span>');
    }

    $("#wsp").html("$" + formatPrice(B2B_FIXED[i].LINE_PRICE));

    if(B2B_FIXED[i].preOrder)
    {
	//$("#curr_price").val(computeProductDiscount(newColor, parseInt(B2B_FIXED[i].COUNT), B2B_FIXED[i].TOTAL_PRICE));

	if(B2B_FIXED[i].avail_date)
	{
	    var now = new Date();
	    var weekAgo = new Date(now.getTime() - (1000 * 60 *60 * 24 * 4));

	    if(B2B_FIXED[i].avail_date > weekAgo)
	    {
		$("#po-date").text('This item will be available on ' + B2B_FIXED[i].avail_date.toDateString().substring(4));
	    }
	}

	else $("#po-date").text('');

	$("#ships").fadeOut('fast');
	$("#so_notice").hide();
	$("#po, #oos").fadeIn('fast');
    }

    else
    {
	//$("#curr_price").val(computeProductDiscount(newColor, parseInt(B2B_FIXED[i].COUNT), B2B_FIXED[i].TOTAL_PRICE));

	$("#po").fadeOut('fast');
	
	if(!B2B_FIXED[i].AVAILABLE)
	{
	    $("#po, #ships").fadeOut('fast');
	    $("#so_notice").show();
	    $("#oos").fadeIn('fast');
	}

	else
	{
	    if(B2B_FIXED[i].toSell == 1) $("#lastCase").show();
	    else $("#lastCase").hide();

	    $("#oos, #po").fadeOut('fast');
	    $("#ships").fadeIn('fast');
	}
    }
}

function changeColor()
{
    //show the correct sizes for this color and update images
    var newColor = $("#color").val();
    $("#size").empty();

    $("#master-sizes option").each(
	function()
	{
	    if($(this).hasClass("sr-" + newColor))
	    {
		if(!$(this).attr('disabled'))
		    $("#size").append($('<option></option>').val($(this).val()).html($(this).text()));
		else
		    $("#size").append($('<option></option>').val($(this).val()).attr('disabled', 'disabled').html($(this).text()));
	    }
	}
    );

    //if its retail, we need to update prices here (retail sizes are all the same price, but different colors can have different prices/discounts
    if(!B2BAUTH)
    {
	//$("#curr_price").val(computeProductDiscount(newColor, 1, RETAIL_BASE_PRICE));

	if(parseFloat(computeProductDiscount(newColor, 1, RETAIL_BASE_PRICE)) != parseFloat(RETAIL_BASE_PRICE))
	    $("#price").html('<strike>$' + formatPrice(RETAIL_BASE_PRICE) + '</strike><br /><span style="color:#880000;">Sale: $' + formatPrice(computeProductDiscount(newColor, 1, RETAIL_BASE_PRICE)) + '</span>');
	else
	    $("#price").html('$' + formatPrice(RETAIL_BASE_PRICE));
    }

    changeImages();

    //trigger a size change as well since the dropdown changed
    //B2B price changes are handled in this function since B2B items can have different prices based on size
    changeSize();
}

function colorMenuSelect(clr)
{
    $("#color").val(clr).change();
}

function changeImages()
{
    if($("#color").val() == "") return;

    var newCLR = STYLE.toLowerCase() + '_' + $("#color").val().toLowerCase();

    //do these in order of importance
    for(var i = 1; i < 6; i++) { document.getElementById('pc-' + i).src = '../images/shoes/sm/' + newCLR + '_' + i + '.jpg'; }
    for(var i = 1; i < 6; i++) { document.getElementById('ps-' + i).href = '../images/shoes/huge/' + newCLR + '_' + i + '.jpg'; } 
    for(var i = 1; i < 6; i++) { document.getElementById('ps-' + i + "i").src = '../images/shoes/med/' + newCLR + '_' + i + '.jpg'; }
    for(var i = 1; i < 6; i++) { document.getElementById('pz-' + i).src = '../images/shoes/lg/' + newCLR + '_' + i + '.jpg'; }
    
    $(".zoomPup img, .zoomWrapperImage img").each(
	function()
	{
	    $(this).attr('src', $(this).attr('src').replace(/\/\w+\_(\d).jpg/, "/" + newCLR + "_$1.jpg"));
	}
    );


    //IMG = 1;

    //redo magnification
    /*$(".ps").unbind();
    $(".ps").jqzoom(
	{
	    zoomType:"reverse",
	    zoomHeight: 406
	}
    );*/

    //document.getElementById('ps-1i').src = '../images/shoes/med/' + newCLR + '_1.jpg';
    //$("#pc-1a").removeClass("zoomThumbActive").click();

    //Change the description here too
    $(".pDesc").hide();
    $("#pDesc-" + $("#color").val()).show();
}


function getB2BIndex(clr, scale)
{
    //returns the index in the B2B_FIXED array that corresponds to this clr/scale combo
    //end result of making the dynamic size select x-browser, since some don't support custom attributes (i.e. index)
    for(var i = 0; i < B2B_FIXED.length; i++)
    {
	if(B2B_FIXED[i].CLR_ABBR == clr && B2B_FIXED[i].SCALE == scale) return i;
    }

    return -1;
}

function getRetailIndex(clr, size)
{
    //returns the index in the RETAIL_FIXED array that corresponds to this clr/size combo
    //end result of making the dynamic size select x-browser, since some don't support custom attributes (i.e. index)
    for(var i = 0; i < RETAIL_FIXED.length; i++)
    {
	if(RETAIL_FIXED[i].CLR_ABBR == clr && RETAIL_FIXED[i].SIZE == size) return i;
    }

    return -1;
}

function notifyOOS()
{
    $("#oos").html('<img src="/images/loading_trans.gif">');

    $.get(
	"/cgi/notify_oos.cgi",
	{ style : STYLE , color : $("#color").val() , scale : $("#size").val() , email : $.cookies.get("email", defaultCookieOptions) , key : $.cookies.get("key", defaultCookieOptions) },
	function(res)
	{
	    if(res == "ok")
	    {
		$("#oos").html('Thank You!').fadeOut(5000,
		    function()
		    {
			$("#oos").html('<a href="javascript:notifyOOS();">Notify me when this product is available</a></p>');
		    }
		);
	    }

	    else
	    {
		$("#oos").html('Error - please contact <a href="mailto:support@ziginy.com">ZiGiny Support</a>.');
	    }
	}
    );
}

var lastQty = 1;

function checkQty()
{
    if($("#qty").val() == "") return;

    $("#qty").val($("#qty").val().replace(/\D/g, ""));

    if(isNaN(parseInt($("#qty").val()))) $("#qty").val(lastQty);
    else lastQty = $("#qty").val();

    //trigger a size change here to update the prices
    changeSize();
}

function computeProductDiscount(color, qty, origPrice)
{
    if(!DISCOUNTS[color]) return origPrice;
    else
    {
	origPrice = parseFloat(origPrice);
	return Math.round(((origPrice - (origPrice * DISCOUNTS[color].rate/100)) - DISCOUNTS[color].amount * qty) * 100) / 100;
    }
}

function computeCartDiscount(upc, qty, origPrice, location)
{
    if(!DISCOUNTS[upc]) return origPrice;
    else
    {
	origPrice = parseFloat(origPrice);
	if(location == "Domestic")
	    return Math.round(((origPrice - (origPrice * DISCOUNTS[upc].domestic_rate/100)) - DISCOUNTS[upc].domestic_amount * qty) * 100) / 100;
	else if(location == "International")
	    return Math.round(((origPrice - (origPrice * DISCOUNTS[upc].international_rate/100)) - DISCOUNTS[upc].international_amount * qty) * 100) / 100;
	else if(location == "Anywhere")
	    return Math.round(((origPrice - (origPrice * DISCOUNTS[upc].anywhere_rate/100)) - DISCOUNTS[upc].anywhere_amount * qty) * 100) / 100;
	else return origPrice;
    }
}

//////////////////////////////////////////////////////////
//
// Category Page Functions
//
//////////////////////////////////////////////////////////

var numPages = 1;
var currentPage = 1;

function loadPagination()
{
    //This function checks the number of item lists on a category page and sets up a pagination counter at the bottom
    //Counters here start at "1" to keep things simple (pages 1 ... n)

    numPages = $(".item_list").length;

    if(numPages > 1)
    {
	//Setup unique IDs
	$(".item_list").each( 
	    function(index)
	    {
		var num = index + 1;
		$(this).attr("id", "item_list_" + num);
	    }			     
	);

	//Create pagination links
	var code = '<a href="javascript:gotoPage(1);">&laquo;</a>';
	code += '<a href="javascript:gotoPage(currentPage - 1);">&lt;</a>';

	for(var i = 1; i <= numPages; i++)
	{
	    code += '<a href="javascript:gotoPage(' + i + ');">' + i + '</a>';
	}

	code += '<a href="javascript:gotoPage(currentPage + 1);">&gt;</a>';
	code += '<a href="javascript:gotoPage(numPages);">&raquo</a>';
	
	$("#pagination").html(code);
    }


}

function gotoPage(which)
{
    if(which > 0 && which <= numPages)
    {
	$("#item_list_" + currentPage).hide();
	$("#item_list_" + which).show();
	currentPage = which;
    }
}

function filterLabels()
{
    var label = $("#label-filter").val();
    
    if(label == "")
    {
	$(".item_list").show();
	$(".label-header").show();

	//Hide all label headers that have no items because filtrexx can't do it
	$(".item_list").each(
	    function()
	    {
		if($(this).children().size() == 0) 
		{
		    $(this).prev('p').hide();
		}
	    }
	);
    }

    else
    {
	$(".item_list").hide();
	$(".label-header").hide();
	$("#list-" + label).show();
	$("#header-" + label).show();
    }
}








//////////////////////////////////////////////////////////
//
// Splash / Banner Functions
//
//////////////////////////////////////////////////////////

function initCat(which)
{
    //Hide all label headers that have no items because filtrexx can't do it
    $(".item_list").each(
	function()
	{
	    if($(this).children().size() == 0) 
	    {
		$(this).prev('p').hide();
	    }
	}
    );

    if(which == "rock-and-candy")
    {
	breakout(which);
    }

}

function setupSplashSS()
{
    setInterval(rotateSplashMain, 4000);
    rotateSplashMain();
}

function rotateSplashMain()
{
    $("#splash_slides img:first").fadeOut(
        500,
        function()
        {
            $("#splash_slides img:first").remove().appendTo("#splash_slides");
            $("#splash_slides img:first").fadeIn(500);
        }
    );
}

//Generic popup functions
function showPopup(which)
{
    $("#shade").show();
    $("#" + which + "_popup").fadeIn();
}

function hidePopup(which)
{
    $("#shade").hide();
    $("#" + which + "_popup").fadeOut();
}



//////////////////////////////////////////////////////////
//
// Breakout Page Functions
//
//////////////////////////////////////////////////////////

function breakout(which)
{
    //Each breakoutpage get styled slightly differently, so modify the existing design rather than making a bunch of manual pages
    if(which == 'rock-and-candy')
    {
	$("#main").height('1080px');
	$("#wrapper").addClass('wrapper-rock-and-candy');
	//$("#brands").addClass('brands-rock-and-candy');
	$("#splash_category a").remove();
	$("#splash_category").append('<a href="/rock-and-candy.html" id="rcLink"></a>');
    }
}


//////////////////////////////////////////////////////////
//
// Data and Utilities
//
//////////////////////////////////////////////////////////

var scaleLookup = 
    {
	"1A" : { "sizerun" : "12A" , "shoecount" : 12 },
	"1B" : { "sizerun" : "12E" , "shoecount" : 12 },
	"1C" : { "sizerun" : "12F" , "shoecount" : 12 },
	"1D" : { "sizerun" : "8A" , "shoecount" : 8 },
	"1F" : { "sizerun" : "6A" , "shoecount" : 6 },
	"1G" : { "sizerun" : "9A" , "shoecount" : 9 },
	"1H" : { "sizerun" : "9L" , "shoecount" : 9 },
	"1L" : { "sizerun" : "12L" , "shoecount" : 12 },
	"ZW" : { "sizerun" : "ZW" , "shoecount" : 12 },
	"ZX" : { "sizerun" : "ZX" , "shoecount" : 12 },
	"ZY" : { "sizerun" : "ZY" , "shoecount" : 12 },
	"K1" : { "sizerun" : "Zigi K1" , "shoecount" : 15 },
	"K2" : { "sizerun" : "KIDS SR13" , "shoecount" : 6 },
	"K3" : { "sizerun" : "KIDS SR" , "shoecount" : 6 },
	"M0" : { "sizerun" : "OPEN STOCK" , "shoecount" : 11 },
	"4M" : { "sizerun" : "12M" , "shoecount" : 12 },
	"A0" : { "sizerun" : "" , "shoecount" : 5 },
	"A1" : { "sizerun" : "" , "shoecount" : 3 },
	"D1" : { "sizerun" : "12MB" , "shoecount" : 12 },
	"D2" : { "sizerun" : "12R" , "shoecount" : 12 },
	"D3" : { "sizerun" : "12L2" , "shoecount" : 12 },
	"D4" : { "sizerun" : "9706" , "shoecount" : 6 },
	"D5" : { "sizerun" : "9707" , "shoecount" : 9 },
	"D6" : { "sizerun" : "9612" , "shoecount" : 12 },
	"D8" : { "sizerun" : "9812" , "shoecount" : 12 },
	"D9" : { "sizerun" : "9809" , "shoecount" : 9 },
	"NW" : { "sizerun" : "12W" , "shoecount" : 12 },
	"NY" : { "sizerun" : "12Y" , "shoecount" : 12 },
	"NZ" : { "sizerun" : "12Z" , "shoecount" : 12 },
	"F1" : { "sizerun" : "06W005" , "shoecount" : 6 },
	"F2" : { "sizerun" : "06W069" , "shoecount" : 6 },
	"F3" : { "sizerun" : "09W027" , "shoecount" : 9 },
	"F4" : { "sizerun" : "12W335" , "shoecount" : 12 },
	"F5" : { "sizerun" : "12W004" , "shoecount" : 12 },
	"P1" : { "sizerun" : "679" , "shoecount" : 7 },
	"P2" : { "sizerun" : "619" , "shoecount" : 5 },
	"P3" : { "sizerun" : "05R" , "shoecount" : 4 },
	"P4" : { "sizerun" : "621" , "shoecount" : 6 },
	"BA" : { "sizerun" : "A RUN" , "shoecount" : 12 },
	"BB" : { "sizerun" : "B RUN" , "shoecount" : 12 },
	"BC" : { "sizerun" : "C RUN" , "shoecount" : 12 }
    }

//This function fixed the jquery zoom plugin's awesome want to pop up alter messages
function alertfoo() { return; }
