jQuery.fn.purchaseOptions = function() {
	if(!jQuery.fn.purchaseOptions.hasrun){
		jQuery.fn.purchaseOptions.init();
	}
	return this.each(function() {	
		$(this).each(function() {
			var me = $(this)
			me.find("input").attr("checked", false).bind("click, change", function() {
				var checkbox = $(this);
				var value = prl[checkbox.attr('name')]*1
				var weight = wht[checkbox.attr('name')]*1
				var optname = checkbox.val();
				var image = $("#"+checkbox.attr("id").replace("option_", "option_image_"));
				
				if(checkbox.attr("checked")) {
					if(!jQuery.fn.purchaseOptions.changing){
						jQuery.fn.purchaseOptions.changing = true;
						$("."+checkbox.attr("class")+":checked[id!="+checkbox.attr("id")+"]").trigger("click");
						jQuery.fn.purchaseOptions.changing = false;
						
					}
					image.fadeIn();
					jQuery.fn.purchaseOptions.totalprice += value;
					jQuery.fn.purchaseOptions.calcWeight(weight)
				} else {
					image.fadeOut();
					jQuery.fn.purchaseOptions.totalprice -= value
					jQuery.fn.purchaseOptions.calcWeight(weight*-1);
				}
				jQuery.fn.purchaseOptions.update();
			});
		});
	});
}
jQuery.fn.purchaseOptions.calcWeight = function(weightchange){
	weight = jQuery.fn.purchaseOptions.totalweight * 16;
	weight += weightchange;
	jQuery.fn.purchaseOptions.totalweight = weight / 16;
	
}
jQuery.fn.purchaseOptions.update = function(){
	$("#totalprice").text(jQuery.fn.purchaseOptions.totalprice.formatMoney())
	$("#amount").val(jQuery.fn.purchaseOptions.totalprice+".00");
	$("#weight").val(jQuery.fn.purchaseOptions.totalweight);
	
}
jQuery.fn.purchaseOptions.init = function(){
	jQuery.fn.purchaseOptions.totalprice =  $("#totalprice").text()*1;
	jQuery.fn.purchaseOptions.totalweight = $("#weight").val();
	jQuery.fn.purchaseOptions.update();
	jQuery.fn.purchaseOptions.hasrun = true;
}
jQuery.fn.purchaseOptions.hasrun = false;
jQuery.fn.purchaseOptions.totalprice = 0;
jQuery.fn.purchaseOptions.totalweight = 0;
jQuery.fn.purchaseOptions.changing = false;


jQuery.fn.cart = function(){
	if(!jQuery.fn.cart.hasrun)
	{
		jQuery.fn.cart.init();
	}
}
jQuery.fn.cart.callFoxy = function(callback, params){
	var cb = callback;
	if(typeof params == "undefined"){
		params="";
	}
	// add google analytics to Foxy
	if(typeof _gat != "undefined" && params != ""){
		var pageTracker = _gat._getTrackerByName();
		params += '&h:ga=' +  escape(pageTracker._getLinkerUrl('', true));
	}
	
	
	jQuery.getJSON('https://'+storedomain+'/cart?output=json' + fcc.session_get() + params + '&callback=?', function(cart) {
		
		// update json
		fcc.cart_update.call(fcc);
		
		// do an callback passing response (json update doesn't seem immediate for some reason)
		cb(cart);
	});
}

jQuery.fn.cart.buildCart = function(cart){
	
	
	var cart = cart;
	
	$("#fc_quantity").text(cart.product_count);
	
	if (cart.product_count == 0){
		$("#cartholder").html('<div class="emptycart"><p><strong>Your shopping cart is empty.</strong><br /><a href="/components/" class="arrowlink">View Red Wine Audio Components</a></div>');
		$(".cartlink").removeClass('cartactive');
		$(".quantity-desc").hide();
		return;
	}
	
	if(cart.product_count > 1){
		$(".item-s").show();
	} else {
		$(".item-s").hide();
	}

	$(".cartlink").addClass('cartactive');
	$(".quantity-desc").show();
	
	$("#fc_quantity").text(cart.product_count);
	var tableData = cart.products;
	var keys = ["name", "quantity", "price"];
	
	//https://github.com/afshinm/Json-to-HTML-Table/blob/master/json-to-table.js
	var tbl = "<div id='fctableholder'><table border='0' cellpadding='0' cellspacing='0' id='fctable' class='fctable'>{0}{1}{2}</table></div>";
	var th = "<thead>{0}</thead>";
	var tb = "<tbody>{0}</tbody>";
	var tr = "<tr>{0}</tr>";
	var thRow = "<th>{0}</th>";
	var tdRow = "<td class='{0}'>{1}</td>";
	var thCon = "";
	var tbCon = "";
	var trCon = "";

	if (keys && tableData) {

		//Creating all table headers
		for (i = 0; i < keys.length; i++) {
			thCon += thRow.format(keys[i].capitalize());
		}
		th = th.format(tr.format(thCon));

		//Creating all table rows from Json data
		if (typeof(tableData[0]) == "object") {
			for (i = 0; i < tableData.length; i++) {
				for (j = 0; j < keys.length; j++) {
					if(keys[j] == 'name'){
						var opts = tableData[i]['options']
						extradata = '';
						for(option in opts){
							if(option != "leadtime"){
								extradata += '<br> &bull; ' + opts[option];
							}
						}
						tbCon += tdRow.format(keys[j], '<strong>' + tableData[i][keys[j]] + '</strong>' + extradata);
					} else if(keys[j] == 'price') {
						tbCon += tdRow.format(keys[j], '$' + tableData[i][keys[j]].formatMoney());
					} else if (keys[j] == 'quantity') {
						tbCon += tdRow.format(keys[j], '<input name="product_'+tableData[i]['id']+'" class="qty" type="number" min="0" max="10" value="'+tableData[i][keys[j]]+'" /><a href="#" class="ir rmv">Delete</a>');
					}
					
				}
				trCon += tr.format(tbCon);
				tbCon = "";
			}
		}
		tb = tb.format(trCon);
		
		var foot = '<tfoot>';
		foot += '<tr class="subtotal"><th colspan="2" class="label">Subtotal</th><th>$' + cart.total_item_price.formatMoney() + '</th></tr>';
		foot += '<tr><th colspan="2" class="label">Order Total</th><th>$' + cart.total_price.formatMoney() + '</th></tr>';
		
		tbl = tbl.format(th, tb, foot);
		tbl += '<div class="clearfix">';
		tbl += '<p class="refresh"><a href="">Refresh</a></p>';
		tbl += '<p class="checkoutlinks"><a href="https://'+storedomain+'/checkout.php?ThisAction=paypal_express' + fcc.session_get() + '" class="paypal ir paypalstorebutton">PayPal</a> <span class="or">or</span> ';
		tbl += '<a href="https://'+storedomain+'/checkout.php?' + fcc.session_get() + '" class="arrowbutton">Checkout</a></p>';
		tbl += '</div>';
	}	
	
	$("#cartholder").html(tbl);
	
	
	// Update Google Analytics after cart HTML generated

	
	// if (typeof(cart.custom_fields['ga']) != "undefined") {
	// 	$('.checkoutlinks a').each(function(){
//			var href_link = $(this).attr('href') + cart.custom_fields['ga'].replace( /\&amp;/g, '&' );
//			$(this).attr('href', href_link);
	// 	});
	// }
	
}

jQuery.fn.cart.init = function(){
	$(".cartlink").bind("click", function(){
		var me = $(this)
		var cartholder =$("#cartholder");
		if(jQuery.fn.cart.open){
			cartholder.slideUp();
			jQuery.fn.cart.open = false;
		} else {
			cartholder.slideDown();
			jQuery.fn.cart.open = true;
			_gaq.push(['_trackPageview', '/cart']);
		}
		return false;
	});
	
	
	$('.refresh a').live("click", function()
	{
		paramstring = '&cart=update';
		var i = 1;
		$.each(FC.json.products, function(){
			paramstring += '&' + i + ":quantity=" + $('.qty[name=product_'+this['id']+']').val() + "&" + i + ":id=" + this['id'];
			i++;
		});
		jQuery.fn.cart.callFoxy(jQuery.fn.cart.buildCart, paramstring);
		return false;
	});
	
	$(".qty").live("change", function(){
		$('.refresh a').removeClass('active');
		$.each(FC.json.products, function(){
			if($('.qty[name=product_'+this['id']+']').val() != this['quantity']){
				$('.refresh a').addClass("active");
				return;
			}
		});
	});
	
	$(".rmv").live("click", function(){
		$(this).prev("input").val('0');
		$('.refresh a ').trigger("click");
		return false;
	})
	
	$(".paypalstorebutton").live("click", function(e){
		// e.preventDefault(); // TODO
		_gaq.push(['_trackPageview', '/paypal_checkout']);
		// setTimeout('document.location = "' + this.href + '";', 200); // TODO
	});
	
	jQuery.fn.cart.hasrun = true;
	$("#cartholder").hide();
	jQuery.fn.cart.callFoxy(jQuery.fn.cart.buildCart);
}
jQuery.fn.cart.hasrun = false;
jQuery.fn.cart.open = false;


$(document).ready(function(){
	jQuery.fn.cart();
	
	$('.sectiontitle').addClass("closed");
	$('.sectiontitle+.clearfix').hide();
	$('.sectiontitle').bind("click", function(){
		var me = $(this);
		var section = me.next('.clearfix');
		if(me.hasClass("closed")){
			section.slideDown(150, function(){
				off = me.offset();
				$('html,body').animate({scrollTop: off.top-5+"px"});
			});

		} else {
			section.slideUp(150);
		}
		me.toggleClass('closed').toggleClass('open')
	})
	
	$(".optionsform").purchaseOptions();
	
	$("#homepagepathways .hpsectiontitle").bind("click", function(){
		$("#homepagepathways .hpsectioncontent.open").animate({"height": "56px"}, function(){$(this).removeClass("open")});
		$("#homepagepathways .hpsectiontitle.open").fadeIn(function(){$(this).removeClass("open")});
		$(this).fadeOut(function(){$(this).addClass("open")});
		$(this).next(".hpsectioncontent").animate({"height": "390px"}, function(){$(this).addClass("open");});
		
	});
	
	$("#componentlink").bind("click", function(){
		$("#componentnav").slideToggle();
		return false;
	})
	
	$("#mailinglistlink").bind("click", function(){
		$("#mc-embedded-subscribe-form").slideToggle();
		return false;
	});
	
	$(".feature_overview .arrowbutton, .feature, .scroller").bind("click", function(){
		off = $($(this).attr("href")).offset();
		$('html,body').animate({scrollTop: off.top-20+"px"});
		return false;
   });

	$("form .arrowbutton").bind("click", function(){
		$(this).parents("form").trigger("submit");
		return false;
	});
	
	
	if($("#carousel_images, .calloutrotator").length > 0){
		$.getScript("/js/mylibs/jquery.cycle.min.js", function(){
			$("#carousel_images").after("<div id='carousel_nav'></div>").cycle({
				pager: '#carousel_nav',
				timeout: 5000,
				onPagerEvent: function(){
					$("#carousel_images").cycle('pause');
				}
			});
			$("#carousel_nav").css("marginLeft", $("#carousel_nav").width()/2*-1+"px")
			$(".calloutrotator").cycle();
		})
	}
});

jQuery(document).ready(function() {
	// Restart the process event collection object
	fcc.events.cart.process = new FC.client.event();
 

	// Define the new process event
	fcc.events.cart.process.add(function(e){
		if(e.tagName == 'A'){
			return true;
		}
		if(e.tagName == 'FORM'){
			// Add item to cart and rebuild the HTML
			jQuery.fn.cart.callFoxy(jQuery.fn.cart.buildCart, jQuery(e).serialize());
			
			// Scroll view to the cart
			scrollToCart = function(){
				off = $("#cartheader").offset();
				$('html,body').animate({scrollTop: off.top-5+"px"});
			}
			if(!jQuery.fn.cart.open){
				jQuery.fn.cart.open = true;
				$("#cartholder").slideDown(function(){scrollToCart();});
			} else {
				scrollToCart();
			}
			return false;
		}
		return false;
  });
});


var fnames = new Array();var ftypes = new Array();fnames[0]='EMAIL';ftypes[0]='email';fnames[1]='FNAME';ftypes[1]='text';fnames[2]='LNAME';ftypes[2]='text';fnames[3]='RECEIVES';ftypes[3]='radio';
try {
    var jqueryLoaded=jQuery;
    jqueryLoaded=true;
} catch(err) {
    var jqueryLoaded=false;
}
var head= document.getElementsByTagName('head')[0];
if (!jqueryLoaded) {
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js';
    head.appendChild(script);
    if (script.readyState && script.onload!==null){
        script.onreadystatechange= function () {
              if (this.readyState == 'complete') mce_preload_check();
        }    
    }
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'http://downloads.mailchimp.com/js/jquery.form-n-validate.js';
head.appendChild(script);
var err_style = '';
try{
    err_style = mc_custom_error_style;
} catch(e){
    err_style = '#mc_embed_signup input.mce_inline_error{border-color:#6B0505;} #mc_embed_signup div.mce_inline_error{margin: 0 0 1em 0; padding: 5px 10px; background-color:#6B0505; font-weight: bold; z-index: 1; color:#fff;}';
}
var head= document.getElementsByTagName('head')[0];
var style= document.createElement('style');
style.type= 'text/css';
if (style.styleSheet) {
  style.styleSheet.cssText = err_style;
} else {
  style.appendChild(document.createTextNode(err_style));
}
head.appendChild(style);
setTimeout('mce_preload_check();', 250);

var mce_preload_checks = 0;
function mce_preload_check(){
    if (mce_preload_checks>40) return;
    mce_preload_checks++;
    try {
        var jqueryLoaded=jQuery;
    } catch(err) {
        setTimeout('mce_preload_check();', 250);
        return;
    }
    try {
        var validatorLoaded=jQuery("#fake-form").validate({});
    } catch(err) {
        setTimeout('mce_preload_check();', 250);
        return;
    }
    mce_init_form();
}
function mce_init_form(){
    jQuery(document).ready( function($) {
      var options = { errorClass: 'mce_inline_error', errorElement: 'div', onkeyup: function(){}, onfocusout:function(){}, onblur:function(){}  };
      var mce_validator = $("#mc-embedded-subscribe-form").validate(options);
      $("#mc-embedded-subscribe-form").unbind('submit');//remove the validator so we can get into beforeSubmit on the ajaxform, which then calls the validator
      options = { url: 'http://redwineaudio.us2.list-manage.com/subscribe/post-json?u=8732927ed821bd32f5f0fca4b&id=031c47d651&c=?', type: 'GET', dataType: 'json', contentType: "application/json; charset=utf-8",
                    beforeSubmit: function(){
                        $('#mce_tmp_error_msg').remove();
                        $('.datefield','#mc_embed_signup').each(
                            function(){
                                var txt = 'filled';
                                var fields = new Array();
                                var i = 0;
                                $(':text', this).each(
                                    function(){
                                        fields[i] = this;
                                        i++;
                                    });
                                $(':hidden', this).each(
                                    function(){
                                        var bday = false;
                                        if (fields.length == 2){
                                            bday = true;
                                            fields[2] = {'value':1970};//trick birthdays into having years
                                        }
                                    	if ( fields[0].value=='MM' && fields[1].value=='DD' && (fields[2].value=='YYYY' || (bday && fields[2].value==1970) ) ){
                                    		this.value = '';
									    } else if ( fields[0].value=='' && fields[1].value=='' && (fields[2].value=='' || (bday && fields[2].value==1970) ) ){
                                    		this.value = '';
									    } else {
	                                        this.value = fields[0].value+'/'+fields[1].value+'/'+fields[2].value;
	                                    }
                                    });
                            });
                        return mce_validator.form();
                    }, 
                    success: mce_success_cb
                };
      $('#mc-embedded-subscribe-form').ajaxForm(options);
      
      
    });
}
function mce_success_cb(resp){
    $('#mce-success-response').hide();
    $('#mce-error-response').hide();
    if (resp.result=="success"){
        $('#mce-'+resp.result+'-response').show();
        $('#mce-'+resp.result+'-response').html(resp.msg);
        $('#mc-embedded-subscribe-form').each(function(){
            this.reset();
    	});
    } else {
        var index = -1;
        var msg;
        try {
            var parts = resp.msg.split(' - ',2);
            if (parts[1]==undefined){
                msg = resp.msg;
            } else {
                i = parseInt(parts[0]);
                if (i.toString() == parts[0]){
                    index = parts[0];
                    msg = parts[1];
                } else {
                    index = -1;
                    msg = resp.msg;
                }
            }
        } catch(e){
            index = -1;
            msg = resp.msg;
        }
        try{
            if (index== -1){
                $('#mce-'+resp.result+'-response').show();
                $('#mce-'+resp.result+'-response').html(msg);            
            } else {
                err_id = 'mce_tmp_error_msg';
                html = '<div id="'+err_id+'" style="'+err_style+'"> '+msg+'</div>';
                
                var input_id = '#mc_embed_signup';
                var f = $(input_id);
                if (ftypes[index]=='address'){
                    input_id = '#mce-'+fnames[index]+'-addr1';
                    f = $(input_id).parent().parent().get(0);
                } else if (ftypes[index]=='date'){
                    input_id = '#mce-'+fnames[index]+'-month';
                    f = $(input_id).parent().parent().get(0);
                } else {
                    input_id = '#mce-'+fnames[index];
                    f = $().parent(input_id).get(0);
                }
                if (f){
                    $(f).append(html);
                    $(input_id).focus();
                } else {
                    $('#mce-'+resp.result+'-response').show();
                    $('#mce-'+resp.result+'-response').html(msg);
                }
            }
        } catch(e){
            $('#mce-'+resp.result+'-response').show();
            $('#mce-'+resp.result+'-response').html(msg);
        }
    }
}

String.prototype.capitalize = function() {
    return this.charAt(0).toUpperCase() + this.slice(1);
}
String.prototype.format = function() {
  var args = arguments;
  return this.replace(/{(\d+)}/g, function(match, number) {
    return typeof args[number] != 'undefined'
      ? args[number]
      : '{' + number + '}'
    ;
  });
};
Number.prototype.formatMoney = function(c, d, t){
    var n = this, c = isNaN(c = Math.abs(c)) ? 0 : c, d = d == undefined ? "." : d, t = t == undefined ? "," : t, s = n < 0 ? "-" : "",
    i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t)
    + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
