/*
 * jQuery Calculation Plug-in
 *
 * Copyright (c) 2007 Dan G. Switzer, II
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Revision: 6
 * Version: 0.4a
*/
(function($){var defaults={reNumbers:/(-|-\$)?(\d+(,\d{3})*(\.\d{1,})?|\.\d{1,})/g,useFieldPlugin:(!!$.fn.getValue),onParseError:null,onParseClear:null};$.Calculation={version:"0.4a",setDefaults:function(options){$.extend(defaults,options)}};$.fn.parseNumber=function(options){var aValues=[];options=$.extend(options,defaults);this.each(function(){var $el=$(this),sMethod=($el.is(":input")?(defaults.useFieldPlugin?"getValue":"val"):"text"),v=$el[sMethod]().match(defaults.reNumbers,"");if(v==null){v=0;if(jQuery.isFunction(options.onParseError))options.onParseError.apply($el,[sMethod]);$.data($el[0],"calcParseError",true)}else{v=v[0].replace(/[^0-9.\-]/g,"");if($.data($el[0],"calcParseError")&&jQuery.isFunction(options.onParseClear)){options.onParseClear.apply($el,[sMethod]);$.data($el[0],"calcParseError",false)}}aValues.push(parseFloat(v,10))});return aValues};$.fn.calc=function(expr,vars,cbFormat,cbDone){var $this=this,exprValue="",$el,parsedVars={},tmp,sMethod,hVars,bIsError=false;for(var k in vars){if(!!vars[k]&&!!vars[k].jquery){parsedVars[k]=vars[k].parseNumber()}else{parsedVars[k]=vars[k]}}this.each(function(i,el){$el=$(this);sMethod=($el.is(":input")?(defaults.useFieldPlugin?"setValue":"val"):"text");hVars={};for(var k in parsedVars){if(typeof parsedVars[k]=="number"){hVars[k]=parsedVars[k]}else if(typeof parsedVars[k]=="string"){hVars[k]=parseFloat(parsedVars[k],10)}else if(!!parsedVars[k]&&(parsedVars[k]instanceof Array)){tmp=(parsedVars[k].length==$this.length)?i:0;hVars[k]=parsedVars[k][tmp]}if(isNaN(hVars[k]))hVars[k]=0}try{exprValue=eval(expr.replace(/([A-Za-z]+)/g,"hVars.$1"));if(!!cbFormat)exprValue=cbFormat(exprValue)}catch(e){exprValue=e;bIsError=true}$el[sMethod](exprValue.toString())});if(!!cbDone)cbDone(this);return this};$.each(["sum","avg","min","max"],function(i,method){$.fn[method]=function(bind,selector){if(arguments.length==0)return math[method](this.parseNumber());var bSelOpt=selector&&selector.constructor==Object&&!(selector instanceof jQuery);var opt=bind&&bind.constructor==Object?bind:{bind:"keyup",selector:(!bSelOpt)?selector:null,oncalc:null};if(bSelOpt)opt=jQuery.extend(opt,selector);if(!!opt.selector)opt.selector=$(opt.selector);var self=this,sMethod,doCalc=function(){var value=math[method](self.parseNumber(opt));if(!!opt.selector){sMethod=(opt.selector.is(":input")?(defaults.useFieldPlugin?"setValue":"val"):"text");opt.selector[sMethod](value.toString())}if(jQuery.isFunction(opt.oncalc))opt.oncalc.apply(self,[value,opt])};doCalc();return self.bind(opt.bind,doCalc)}});var math={sum:function(a){var total=0;$.each(a,function(i,v){total+=v});return total},avg:function(a){return math.sum(a)/a.length},min:function(a){return Math.min.apply(Math,a)},max:function(a){return Math.max.apply(Math,a)}}})(jQuery);


function recalc(){
	$("strong.sub-total").calc(
		// the equation to use for the calculation
		"qty * price",
		// define the variables used in the equation, these can be a jQuery object
		{
			qty: $("input.qty"),
			price: $("span.each")
		},
		// define the formatting callback, the results of the calculation are passed to this function
		function (s){
			// return the number as a dollar amount
			return s.toFixed(2);
		},
		// define the finish callback, this runs after the calculation has been complete
		function ($this){
			// sum the total of the $("[@id^=total_item]") selector
			var sum = $this.sum();
			//console.log(sum);
			$("#total span").text(
				// round the results to 2 digits
				sum.toFixed(2)
			);
		}
	);
}


$('#models')
.cycle({ 
	fx:     'fade', 
	speed:  'slow', 
	timeout: 10000,
	slideExpr: '.slide',
	cleartype:  1
})
.hover(function() {
 	$('#models').cycle('pause');
}, function() {
 	$('#models').cycle('resume');
});

$('#cart').submit(function() {
	var form = this;
	var count = 0;
	products = $('#content .copy');
	productsDiv = $('.hiddenFields', this);
	$('input', productsDiv).remove();
	$('tbody tr', products).each(function(index) {
		itemName = '';
		qty = parseFloat($('.qty:eq(0)', this).val());
		eachPrice = parseFloat($('.int .each:eq(0)', this).text());
		if(qty > 0){
			if(type = $('.type:eq(0)', this).val())
			{
				itemName += (type + " - ");
			};
			$('select', this).each(function(index) {
				itemName += ($(this).val() + " - ");
			});
			itemName = itemName.substr(0, (itemName.length - 3));
			
			++count;
			$("<input name='quantity_"+ count +"' value='"+ qty +"' type='hidden' />").appendTo(productsDiv);
			$("<input name='amount_"+ count +"' value='"+ eachPrice +"' type='hidden' />").appendTo(productsDiv);
			$("<input name='item_name_"+ count +"' value='"+ itemName +"' type='hidden' />").appendTo(productsDiv);
		}
	});
	if(count == 0){
		alert("You did not selected any items");
		return false;
	}
});

$('.add').click(function() {

	table = $(this).prev('table');
	newTr = table.find('tbody tr:last').clone(true);

	$('.qty', newTr).val('');
	$('select', newTr).each(function(index) { this.selectedIndex = 0; });
	$('strong.sub-total', newTr).text('0.00');

	$('select#guys-t-style', newTr).change(function() { update_tshirt_attributes($(this)); }).change();
	$("select#girls-t-style", newTr).change(function() { update_tshirt_attributes($(this)); }).change();
	$('select#moto-graphics', newTr).change(function() { update_moto_grapics_attributes($(this)); }).change();
	$('select#caps', newTr).change(function() { update_caps_attributes($(this)); }).change();

	newTr.appendTo(table);
	return false;
});

$("select#guys-t-style").change(function() { update_tshirt_attributes($(this)); }).change();
$("select#girls-t-style").change(function() { update_tshirt_attributes($(this)); }).change();
$("select#moto-graphics").change(function() { update_moto_grapics_attributes($(this)); }).change();
$("select#caps").change(function() { update_caps_attributes($(this)); }).change();

function update_caps_attributes(el)
{
	val = $(el).val();
	$tr = $(el).parent().parent();
	$price_select = $("span.each", $tr).text("39.95");
	if(val == 'Pen')
	{
		$price_select.text("29.95");
	}
}

function update_moto_grapics_attributes(el)
{
	val = $(el).val();
	$tr = $(el).parent().parent();
	$price_select = $("span.each", $tr).text("139.95");
	if(val == 'CRF 50 04 09')
	{
		$price_select.text("114.95");
	}
}

function update_tshirt_attributes(el)
{
	val = $(el).val();
	$tr = $(el).parent().parent();
	$colour_select = $("select.guys-t-color", $tr);
	$price_select = $("span.each", $tr).text("44.95");
	if(val == 'Karmin Spinner')
	{
		$colour_select.html("<option value='Black'>Black</option><option value='Red'>Red</option><option value='White'>White</option>");
	}
	else if(val == 'Rose')
	{
		$colour_select.html("<option value='White'>White</option>");
	}
	else if(val == 'Monster' || val == "Sweet as Candy")
	{
		$colour_select.html("<option value='White'>White</option><option value='Black'>Black</option>");
	}
	else if(val == "Pen")
	{
		$colour_select.html("<option value='White'>White</option>");
	}
	else if(val == "SlurNation")
	{
		$price_select.text("49.95");
		$colour_select.html("<option value='Black'>Black</option>");
	}
	else
	{
		$colour_select.html("<option value='Black'>Black</option>");
	}
	recalc();
}


$('.delete a').click(function() {
	$(this).parents('tr:eq(0)').remove();
	recalc();
	return false;
});



$("input.qty").bind("keyup", recalc);
recalc();