jQuery(function() {
	
	/*
	----------------------------------
	profile page
	----------------------------------
	*/
	
	$("#shares-list").idTabs(); 
	
	/*
	----------------------------------
	order form
	----------------------------------
	*/
	
	// add input to form
	$('form').prepend('<input name="a" value="1" type="hidden" />');
	
	// showing running total
	$('#running-total').show();
	
	// set running total
	function do_total() {
		
		var itotal = 0;
		var int 	= $('input[name="interval"]:checked').val();	// interval type
		var slen 	= $('input#season_length').val();				// season length
		var sfull 	= $('input#season_full').val();		// full season
		var addDelv = false;
		
		$('#col-left input:checked').each( function() {
			var $item = $(this);
			var c = parseFloat( $item.next('label').find('span.share-price').text() );				
			if(c) {
				itotal += c; // add em up
			}
			if($item.is('[name="delivery"]') && sfull!=1) {
				addDelv = true;
			}
		});
		
		// Process intervals.
		if(sfull!=1) {
			if(int==4) {
				itotal = itotal*slen;
			} else if(int==3) {
				itotal = itotal*(Math.floor(slen/2));
			}
		}
		else {
			if(addDelv) itotal += calcDelivery();
			if(int==4) {
				itotal = itotal*1;
			} else if(int==3) {
				itotal = itotal*(0.5);
			}
		}
		
		// Check customizables
		if(sfull!=1) {
			var valLen = $('#customizables').find('input').val().length;
			if(parseInt(valLen) > 0) {
				itotal += (3*slen);
			}
		}
	
		// Set total.		
		//$('span.total').text( itotal.toFixed(2) );
		
		
		// here is the real calc, remove above after
		
		
		var season_id = $('#season').val(); 
		var depot_id = $('#depot_id').val();  // might be undefined , not yet picked
		var interval_id= $('input[name=interval]:checked').val() ;
		var home_delivery=$('input[name="delivery"]:checked').val() ;// undefined for 0, 1 for 1
		var share_id=$('input[name=share_type]:checked').val();
		
		// update this later if multiple options, loop through and make it a list and then parse it on php side
		var add_on_ids=$('input[id=optional]:checked').val();
		
		var customized= ($('#customizables').find('input').val().length >0); // anything not 0 or undefined, is 1
		
		$('.total').fadeTo(400, 0.3).load("../includes/load_total.php", { 'add_on_ids':add_on_ids,'i':interval_id,'ssn':season_id,'d':depot_id,'c':customized,'s':share_id,'h':home_delivery, 'rand': Number(new Date()) }, function() {$(this).fadeTo(400, 1);});
		
		
	}
	
	// Calculate delivery total
	function calcDelivery() {
		var slen = $('input#season_length').val();
		return slen * (5.65);
	}
	
	// Load season
	$('#topnav a').live('click', function() 
	{
		var dtl;
		var $thelink = $(this);
		
		$('.loader').clone().appendTo( $(this).parent() ).show();
		$('.section-left .col-inner').fadeTo(400, 0.4);
		$('#form-errors-area').animate({ height: 'hide', opacity: 0 }, 300, function() { 
			$(this).empty().css('opacity', 1); 
		});
		
		var sid = $thelink.attr('href').split('-');
		$thelink.parent().addClass('current').siblings().removeClass('current');
		
		$.ajax({			
			dataType: 'json',
			data: { 'get_season': sid[1], 'rand': Number(new Date()) },
			success: function(d) {
				$('.current').children('.loader').remove();
				$('.section-left .col-inner').fadeTo(400, 1);
				
				if(!d.error) {
					$('#season').val(d.sid);
					$('input#season_length').val(d.season_length);
					$('input#season_full').val(d.season_full);
					var delvTotal = calcDelivery();	
					
					// check for full seasons
					if(d.season_full!=1) {
						$('#delivery-label')
							.html('Receive home delivery for $<span class="share-price">5.65</span>/week, HST inc ($' + Math.round(delvTotal,2) + ')');
						$('#s-customize, #o-interval').show();
						$('#o-interval p:first').show();
						$('.n-summer').hide();
					} 
					else {		
						$('#delivery-label')
							.html('Receive home delivery for $<span class="share-price">' + delvTotal + '</span> ($5.65/week, HST inc)');
						$('#s-customize').hide();
						$('.n-summer').show();
						$('#o-interval p:first').hide();
						$(':input[name="interval"]').attr('checked', '').eq(2).attr('checked', 'checked');
					}		
					//$('#location-info').html('&nbsp;');
					$('#s-info').html(d.info);
					$('#s-types').html(d.shares);
					$('#s-depots').html(d.depots);
					dtl = do_total();
					
					//update the interval options
					// for now just turn off the one time option for summer season
					if(d.sid=='7'){
						
						$('#inid_1').hide();	
						$('#inid_3').hide();
					} else {
						$('#inid_1').show();	
						$('#inid_3').show();	 
					}
					
				} else {					
					alert(d.msg);
				}					
			},
			type: 'post'
		});			
		return false;
	});
	$('#topnav a:first').click();
	
	// Update totals
	$('#col-left :radio, #col-left :checkbox').live('click', function() 
	{
		var ov = $(this).next('label').find('.share-price').text(); // text value
		if(ov) var dtl = do_total();
	});
	
	// Load depot cross streets
	$('#depot_id').livequery('change', function() 
	{
		var dval = $(this).val();
		if(dval!='') 
		{
			$('#location-info').fadeTo(400, 0.3).load("../includes/load_form.php", { 'get_location': dval, 'rand': Number(new Date()) }, function() {
				$(this).fadeTo(400, 1);
			});
		} 
		else {
			$('#location-info').empty();
		}
		var dtl=do_total();
	});
	
	// Delivery checkbox
	$(':checkbox[name="delivery"]').live('click', function() {
		if( $(this).is(':checked') ) {
			$('#s-depots').val('');
			$('#o-pickup').animate({ height: 'hide' });
			$('#delivery-info').animate({ height: 'show' });
		} else {
			$('#o-pickup').animate({ height: 'show' });
			$('#delivery-info').animate({ height: 'hide' });
		}
	});
	
	// interval radios
	$('input[name="interval"]').click( function() {
		var dtl = do_total();
	});
	
	$('#customizables input').livequery('focus', function() {
		var dtl = do_total();
	});
	
	// Form submission
	$('#form-shares').ajaxForm({
		beforeSubmit: function() {
		},
		dataType: 'json',
		success: function(d) {
			if( ! d.error) {
				window.location = d.redirect;
			} else {
				$('#form-errors-area').html(d.msg).show();	
			}
		}
	});	
	
});