var product_name = '';
var current_product_id = '';
var quantity = 0;
var size = '';
var form_id = '';
var link_cell = null;
var item_row = null;
var stop_execution = false;
$(document).ready(function(){
	$(".form_ajax_request").click(function(event){
		form = $(this).closest("form");
		form_id = form.attr('id');
		var options = { 
				beforeSubmit:  preSubmit, 
				success:       processResponse, 
				dataType:  'json' 
		}; 
		$('#'+form_id).ajaxForm(options);
	});
	$(".form_ajax_request_multiple").live('click', function(event){
		form = $(this).closest("form");
		form_id = form.attr('id');
		var options = { 
				beforeSubmit:  multiplePreSubmit, 
				success:       processMultipleResponse, 
				dataType:  'json' 
		}; 
		$('#'+form_id).ajaxForm(options);
	});
	$(".cart_ajax_request").click(function(event){
		var options = { 
				beforeSubmit:  cartPreSubmit, 
				success:       cartProcessResponse, 
				dataType:  'json' 
		}; 
		$('#quick_add_form').ajaxForm(options);
	});
	$(".omniture_form_ajax_request").click(function(event){
		form = $(this).closest("form");
		form_id = form.attr('id');
		var options = { 
			beforeSubmit:  preSubmit, 
			success:       processResponse, 
			dataType:  'json' 
		}; 
		$('#'+form_id).ajaxForm(options);
	});
	
	// items slide
	var v_first = 1;
	var v_last = 4;
	var h_first = 1;
	var h_last = 3;
	var h_show = [1, 2, 3];
	var v_show = [1, 2, 3, 4];
	var first_set = true;
	$('#move_up').click(function(event){
		event.preventDefault();
		if (first_set) {
			$('#v_item_1').hide();
			$('#v_item_2').hide();
			$('#v_item_3').hide();
			$('#v_item_4').hide();
			$('#v_item_5').show();
			$('#v_item_6').show();
			$('#v_item_7').show();
			$('#v_item_8').show();
			first_set = false;
		} else {
			$('#v_item_1').show();
			$('#v_item_2').show();
			$('#v_item_3').show();
			$('#v_item_4').show();
			$('#v_item_5').hide();
			$('#v_item_6').hide();
			$('#v_item_7').hide();
			$('#v_item_8').hide();
			first_set = true;
		}
		//	$(this).hide();
		//	$('#move_down').show();
	});
	
	$('#move_down').click(function(event){
		event.preventDefault();
		if (first_set) {
			$('#v_item_1').hide();
			$('#v_item_2').hide();
			$('#v_item_3').hide();
			$('#v_item_4').hide();
			$('#v_item_5').show();
			$('#v_item_6').show();
			$('#v_item_7').show();
			$('#v_item_8').show();
			first_set = false;
		} else {
			$('#v_item_1').show();
			$('#v_item_2').show();
			$('#v_item_3').show();
			$('#v_item_4').show();
			$('#v_item_5').hide();
			$('#v_item_6').hide();
			$('#v_item_7').hide();
			$('#v_item_8').hide();
			first_set = true;
		}
	});
	$('#move_left').click(function(event){
		event.preventDefault();
		if (h_show[0] != 1) {
			$.each(h_show, function(index, value) { 
				h_show[index] = value - 3; 
			});
		} else {
			$.each(h_show, function(index, value) { 
				h_show[index] = value + 6; 
			});
		}
		$('.omniture_item_container').hide();
		$.each(h_show, function(index, value) { 
			$('#h_item_'+value).show();
		});
		/*if (h_show[0] == 1)
			$(this).hide();
		if (h_show[2] != 9)
			$('#move_right').show();*/
	});
	$('#move_right').click(function(event){
		event.preventDefault();
		if (h_show[0] != 7){
			$.each(h_show, function(index, value) { 
				h_show[index] = value + 3; 
			});
		} else {
			$.each(h_show, function(index, value) { 
				h_show[index] = value - 6; 
			});
		}
		$('.omniture_item_container').hide();
		$.each(h_show, function(index, value) { 
			$('#h_item_'+value).show();
		});
	});
	// remove item from cart
	$(".remove_from_cart").live('click', function(event){
		event.preventDefault();
		blockUI('Please wait while the item is removed from your cart...');
		link_cell = $(this).parent();
		item_row = link_cell.parent();
		$.ajax({
			  url: root+'index.php',
			  data: { main_page: "shopping_cart", action: "remove_product", product_id: $(this).attr('id') },
			  success: processRemoveResponse,
			  dataType: 'json'
		});
	});
	// change pack size
	$('body').delegate('select', 'change', function(){});
	$('body').delegate('a', 'click', function(){});
	$('.change_weight').live('change', function(){
		parent_col = $(this).parent();
		product_name = parent_col.prev().find('#product_name_link').text().replace(/^\s+/g,'').replace(/\s+$/g,''); 
		blockUI('Please wait while cart totals are re-calculated...');
		var options = { 
				success:   processItemsResponse, 
				dataType:  'json' 
		}; 
		$('#cart_items').ajaxSubmit(options);
	});
	$('.item_quantity_list').live('change', function(){
		parent_col = $(this).parent();
		product_name = parent_col.parent().find('#product_name_holder').find('#product_name_link').text().replace(/^\s+/g,'').replace(/\s+$/g,''); 
		blockUI('Please wait while cart totals are re-calculated...');
		var options = { 
				success:   processItemsResponse, 
				dataType:  'json' 
		}; 
		$('#cart_items').ajaxSubmit(options);
	});
	$('#shipping_quotes').live('change', function(event){
		//$('#cart_items').submit();
		if ($(this).val() == 'flat_flat') {
			window.location = root+'index.php?main_page=shopping_cart&shipping=flat_flat';
			return;
		}
		event.preventDefault();
		blockUI('Please wait while cart totals are re-calculated...');
		$.ajax({
			  url: root+'index.php?main_page=shopping_cart&shipping='+$(this).val(),
			  success: function(data){
							if (data.success == true) {
								$('#main_cart_container').load(root+'index.php?main_page=shopping_cart #main_cart_container', function(response, status, xhr){
									if (status == "error"){
										window.location.reload();
										return;
									}
									$.unblockUI();
									$.growlUI('Shipping updated', 'cart totals have been re-calculated', 4500);
								});
							} else {
								$.unblockUI();
								$.growlUIError('An error has occured', 'the shipping method could not be updated', 4500);
							}
						},
			  dataType: 'json'
		});
	});
	$('#freesampleadd').live('change', function(event){
		event.preventDefault();
		blockUI('Please wait while the free sample is added to your cart...');
		product_name = $('#freesampleadd option:selected').text();
		quantity = 1;
		$.ajax({
			  type: 'POST',
			  url: root+'index.php?main_page=shopping_cart&action=add_product',
			  data: { products_id: $(this).val(), cart_quantity: "1", need_return: false},
			  success: cartProcessResponse,
			  dataType: 'json'
		});
	});
	$('#redeem_coupon').live('click', function(event){
		event.preventDefault();
		$('#cart_items').submit();
	});
	$('#cart_items').live('submit', function(event){
		if (stop_execution)
			return;
		event.preventDefault();
		stop_execution = false;
		blockUI('Please wait while the coupon is verified...');
		default_msg = $('#redemtion_message_default').html().toString();
		msg = $('<div/>');
		msg.load(root+'index.php?main_page=shopping_cart&dc_redeem_code='+$('#disc-ot_coupon').val()+' #redemtion_message', function(response, status, xhr){
			if (status == "error"){
				window.location.reload();
				return;
			}
			if ($(msg).find('#redemtion_message').html() != null && $(msg).find('#redemtion_message').html().toString() == default_msg)
			{
				$('#main_cart_container').load(root+'index.php?main_page=shopping_cart #main_cart_container', function(response, status, xhr){
					if (status == "error"){
						window.location.reload();
						return;
					}
					$.unblockUI();
					$.growlUI('Done', 'Congratulations you have redeemed the Discount Coupon', 4500);
				});
			} else {
				$.unblockUI();
				$.growlUIError('Coupon invalid', $(msg).find('#redemtion_message').html().toString(), 4500);	
			}
			
		});
	});
	$('.remove_size_options').live('click', function(event){
		event.preventDefault();
		form = $(this).closest('form');
		$.unblockUI({});
		jQuery('input:checkbox', form).removeAttr('checked');
		jQuery('input:text', form).val('1');
	});
});

$(window).load(function () {
	$('.dynamic_update_list').each(function(i) {
		var h_id_str = $(this).attr('id');
		var current_elem = $(this);
		$.get("/weight_service.php", { product_name: h_id_str}, function(data){
			if (data.success == true) {
				form = current_elem.closest("form");
				form.attr('id', data.pid);
				form.attr('action', root+'index.php?action=add_product&number_of_uploads=0&products_id='+data.pid);
				form.prepend('<input type="hidden" value="'+data.pid+'" name="products_id">');
				current_elem.html(data.selector);
				$('#popups_holder').append(data.popup);
			} else {
				//console.log('failed on '+h_p_name+data);
			}
		}, 'json');
	});
	$('.v_dynamic_update_list').each(function(i) {
		var v_id_str = $(this).attr('id');
		var current_elem = $(this);
		$.get("/weight_service.php", { product_name: v_id_str}, function(data){
			if (data.success == true) {
				form = current_elem.closest("form");
				form.attr('id', 'v_'+data.pid);
				form.attr('action', root+'index.php?action=add_product&number_of_uploads=0&products_id='+data.pid);
				form.prepend('<input type="hidden" value="'+data.pid+'" name="products_id">');
				current_elem.html(data.selector);
				$('#popups_holder').append(data.popup);
			} else {
				//console.log('failed on '+v_p_name+data);
			}
		}, 'json');
		
	});
});

function preSubmit(formData, jqForm, options) { 
	if (('#use_ajax').length == 0){
		return false;
	}
	var form = jqForm[0]; 
	product_name = form.hidden_product_name.value;
	quantity = form.cart_quantity.value;
	selected_size = (formData[4]);
	if(selected_size.value == '' || formData[3].value == '') {
		product_id = form.products_id.value;
		$.blockUI({ 
			message: $('#popup-'+product_id), 
			css: { top: '20%', width: '35%', border: '3px solid #B6A52E', cursor: '' } 
		}); 
		return false;
	}
	blockUI('Please wait while the item is added to your cart...');
	return true; 
} 
function multiplePreSubmit(formData, jqForm, options) { 
	var form = jqForm[0];
	current_product_id = form.products_id.value;
	if (('#use_ajax').length == 0){
		return false;
	}
	var form = jqForm[0]; 
	checked = 0;
	$(':input', form).each(function(i) {
        if (this.type == 'checkbox') {
        	if (this.checked) {
                checked++;
           }
        }
    });
	if (checked == 0){
		alert('Please select one or more of the available sizes');
		return false;
	}
	blockUI('Please wait while the item is added to your cart...');
	return true; 
} 

function processResponse (data) {
	if (data.success) {
		$('#header_cart_items').html(data.header_cart);
		$('#shipping_wrapper').html(data.free_shipping);
		$('#shopping_cart_wrapper').html(data.cart_content);
		$.unblockUI();
		item_str = (quantity > 1) ? ' items ' : ' item ';
		$.growlUI(product_name, quantity + item_str + 'added to your cart', 6000); 
	} else {
		$.unblockUI({ 
			onUnblock: function(){ alert('An error ocurred. The item could not be added to your cart.'); } 
		});
	}
}
function processMultipleResponse (data) {
	if (data.success) {
		$('#header_cart_items').html(data.header_cart);
		$('#shipping_wrapper').html(data.free_shipping);
		$('#shopping_cart_wrapper').html(data.cart_content);
		$.unblockUI();
		item_str = (data.items_added > 1) ? ' items ' : ' item ';
		$.growlUI(product_name, data.items_added + item_str + 'added to your cart', 6000); 
		form = $('#multiple_'+current_product_id);
		$.unblockUI({});
		jQuery('input:checkbox', form).removeAttr('checked');
		jQuery('input:text', form).val('1');
	} else {
		$.unblockUI({ 
			onUnblock: function(){ alert('An error ocurred. The item could not be added to your cart.'); } 
		});
	}
}

function cartPreSubmit(formData, jqForm, options) { 
	var form = jqForm[0]; 
	product_name = form.product_name.value;
	process = (product_name && (product_name != 'Start Typing to Find Spice')) ? true : false;
	if (('#use_ajax').length == 0 || !process){
		alert('Please choose an item');
		return false;
	}
	product_name = form.product_name.value;
	quantity = form.cart_quantity.value;
	selected_size = (formData[2]);
	if(selected_size.value == '') {
		alert("Please select a size before adding this product to your cart.");
		return false;
	}
	blockUI('Please wait while the item is added to your cart...');
	return true; 
} 

function cartProcessResponse (data) {
	if (data.success) {
		$('#header_cart_items').html(data.header_cart);
		$('#main_cart_container').load(root+'index.php?main_page=shopping_cart #main_cart_container', function(response, status, xhr){
			if (status == "error"){
				window.location.reload();
				return;
			}
			$.unblockUI();
			item_str = (quantity > 1) ? ' items ' : ' item ';
			$.growlUI(product_name, quantity + item_str + 'added to your cart', 4500);
		});
	} else {
		$.unblockUI({ 
			onUnblock: function(){ alert('An error ocurred. The item could not be added to your cart.'); } 
		});
	}
}

function processItemsResponse (data) {
	if (data.success) {
		$('#header_cart_items').html(data.header_cart);
		$('#main_cart_container').load(root+'index.php?main_page=shopping_cart #main_cart_container', function(response, status, xhr){
			if (status == "error"){
				window.location.reload();
				return;
			}
			$.unblockUI();
			$.growlUI(product_name+' updated', 'cart totals have been re-calculated', 4500);
		});
	} else {
		$.unblockUI({ 
			onUnblock: function(){ alert('An error ocurred. The item could not be updated.'); } 
		});
	}
}
function processRemoveResponse (data) {
	if (data.success) {
		$('#header_cart_items').html(data.header_cart);
		$('#main_cart_container').load(root+'index.php?main_page=shopping_cart #main_cart_container', function(response, status, xhr){
			if (status == "error"){
				window.location.reload();
				return;
			}
			$.unblockUI();
			$.growlUI(data.product_name, 'item has been removed from your cart', 4500);
		});
	} else {
		$.unblockUI({ 
			onUnblock: function(){ alert('An error ocurred. The item could not be removed from cart.'); } 
		});
	}
}
function blockUI (message) {
	$.blockUI({ css: { 
    	border: 'none', 
    	padding: '15px', 
    	backgroundColor: '#000', 
    	'-webkit-border-radius': '10px', 
    	'-moz-border-radius': '10px', 
    	opacity: .5, 
    	color: '#fff'
    },
    message: '<h1 id="wait_message">'+message+'</h1>'
});  
}