var minicartTimeout;
var autocloseCart = true;
var wideCart = false;

$(document).ready(function(){
	$('.slideshow').hover(
		function() {
//			alert("hover");
			$('.slideshow').cycle('pause');
		}, 
		function() {
			$('.slideshow').cycle('resume');
//			$('.slideshow').resume();
//			alert("resume");
		}
	);

	// hint for search box
	$('input#search[title!=""]').hint();

	// horizontal menu hover event handler
	$('.topmenu ul li').hover(
		function() {
			if ($(this)[0].id == "home")
				$(this).addClass("active_home");
			else
				$(this).addClass("active");
			$(this).find('ul').stop(true, true);
			$(this).find('ul').fadeIn();
		},
		function() {
			$(this).removeClass("active");
			$(this).removeClass("active_home");
			$(this).find('ul').fadeOut('fast');
		}
	);


//	$('#shopping_cart_mini').css('left', $('body').width() - $('#shopping_cart_mini').width() - 50);
	//$('#shopping_cart_mini').show("slow");
/*
	$('#shopping_cart_mini').dropShadow({
		color: 'black',
		swap: false,
		left: 0,
		top: 0,
		blur: 2,
		opacity: 2
	});
*/	
    var options = {
        beforeSubmit:  showRequest, 
        success:       showResponse 
    };
    $('#cart_add').ajaxForm(options);

    var options_partypacks = {
        beforeSubmit:  showRequestPartypacks, 
        success:       showResponse
    };
    $('#cart_add_partypacks').ajaxForm(options_partypacks);
    
    // popup message
    $('#popup_message').css('left', $('body').width() - $('#popup_message').width() - 50);
    $('#popup_message').dropShadow({
		color: 'black',
		swap: false,
		left: 0,
		top: 0,
		blur: 2,
		opacity: 2
	});
    $('#popup_message_close_button').click(function() {
    	close_popup_message();
    });
});

function showRequest(formData, jqForm, options) {
	
	// check quantity of requested products
	for (var i=0; i < formData.length; i++) { 
		
		re = /qty_(\d+)/i;
    	found = formData[i].name.match(re);
    	if (found == null) {
    		continue;
    	}
    	
		var requested_quantity = formData[i].value;
		var product_id = found[1];
		
		// ticket #74; do nothing if user set product quantity to 0 or empty string
		if(requested_quantity == null) {
			continue;
		}
		
		requested_quantity = $.trim(requested_quantity);
		
	    if(requested_quantity == "" || parseInt(requested_quantity) == 0) {
	    	continue;
	    }
		
		var returning_value = true;
		
		// check quantity of requested item
		$.ajax({
			async: false,
			type: 'POST',
			url: "/item_quantity_service.php",
			data: { product_id: product_id},
			success: function(result){
				
    	    	// check quantity of requested product
    		    if(!check_product_quantity(requested_quantity, result)){
    		    	returning_value = false;
    		    }
		    },
			dataType: "json"
		});
		
		// disallow adding to cart if quantity of at least one product is not enough
		if(!returning_value) {
			return false;
		}
		
		var price = $('#old_pack_price_' + product_id).val();
		kissmetrics_event_added_to_cart_old_partypack(product_id, requested_quantity, price);
	}
    
    return true;
}

function showRequestPartypacks(formData, jqForm, options) {
	// check quantity of requested partypacks
	for (var i=0; i < formData.length; i++) { 
		
		re = /qty_(\d+)/i;
    	found = formData[i].name.match(re);
    	if (found == null) {
    		continue;
    	}
    	
		var requested_quantity = formData[i].value;
		var pack_id = found[1];
		
		if(requested_quantity == null) {
			continue;
		}
		
		requested_quantity = $.trim(requested_quantity);
		
	    if(requested_quantity == "" || parseInt(requested_quantity) == 0) {
	    	continue;
	    }

        // We should ignore all partypacks that is not related with submit button.
        // In other words, we only process partypack that user wants to add.
        // (other packs event with non-zero quantity are ignored).
        var processFlag = false;
        $.each(formData, function(index, obj) {
            if(obj.name == 'submit_' + pack_id) {
                processFlag = true;
            }
        });

        if(!processFlag) {
           continue;
        }

		var returning_value = true;
		
		// check quantity of requested item
		$.ajax({
			async: false,
			type: 'POST',
			url: "/item_quantity_service.php",
			data: { pack_id: pack_id},
			success: function(result){
				
    	    	// check quantity of requested partypacks
    		    if(!check_product_quantity(requested_quantity, result)){
    		    	returning_value = false;
    		    }
		    },
			dataType: "json"
		});
		
		// disallow adding to cart if quantity of at least one product is not enough
		if(!returning_value) {
			return false;
		}

        if($('#_params_' + pack_id).length > 0) {

            var seewhy_params = $('#_params_' + pack_id).text();

            seewhy_params = jQuery.parseJSON(seewhy_params);

            seewhy_fire_intent_event(seewhy_params);
        }

		var price = $('#tprice_' + pack_id).val();
		kissmetrics_event_added_to_cart_partypack(pack_id, requested_quantity, price);
	}
    
    return true;
}

function seewhy_fire_intent_event(seewhy_params) {
    $.ajax({
      url: "/cart_ajax.php?without_content",
      dataType: "json",
      success: function(data_cart){
        // Fire SeeWhy event.
        cy.FunnelLevel="3";
        // cy.Custom1="Guest";
        cy.Custom2="Add to cart";
        cy.Value=data_cart.subtotal;
        cy.ReturnToLink=seewhy_params.cart_url + "&global_basket_id=" + data_cart.global_basket_id;
        // cy.UserId="[Email address if logged in]";

        cyNewBasketLine();
        cyAddBasketLineDetail('ItemName', seewhy_params.name);
        cyAddBasketLineDetail('ItemImageURL', seewhy_params.image_url);
        cyAddBasketLineDetail('ItemPrice', seewhy_params.price);
        cyAddBasketLineDetail('ItemPageURL', seewhy_params.url);

        // Commented out by SeeWhy recommendation.
        // cy_getImageSrc();
      }
    });
}

function showResponse(responseText, statusText, xhr, $form)  {
	process_cart(responseText);
}

function check_product_quantity(quantity_requested, quantity_data) {
	
	if(quantity_data == null || quantity_data.available == 0 || quantity_data.error == 1) {
		return true;
	}
	
	quantity_requested = parseInt(quantity_requested);
	var quantity_in_stock = parseInt(quantity_data.quantity_in_stock);
	var quantity_in_cart = parseInt(quantity_data.quantity_in_cart);
	
	if(quantity_requested == 0) {
		return true;
	}
	
	var error_text = '';
	if(quantity_data.name != null && quantity_data.name != '') {
		error_text += "<b>" + quantity_data.name + "</b><br/>";
	}
	
	if(quantity_in_stock == 0) {
		error_text += 
			"Sorry, this item is currently out of stock.<br/>"+
			"Thanks!";
		
		display_popup_message(error_text);
		return false;
	}
	
	if(quantity_in_cart >= quantity_in_stock) {
		error_text += 
			"Sorry, there are no more of this item available. <br/>"+
			"The other items that you added are still in your cart. Thanks!";
		
		display_popup_message(error_text);
		return false;
	}
	
	if((quantity_requested + quantity_in_cart) > quantity_in_stock) {
		error_text += 
			"Sorry, we only have " + (quantity_in_stock - quantity_in_cart) + " of this item in stock right now.<br/>"+
			"Please check the quantity entered and try again. Thanks!";
		
		display_popup_message(error_text);
		return false;
	}
	
	return true;
}

function check_product_quantity_cart(quantity_requested, quantity_data) {
	
	if(quantity_data == null || quantity_data.available == 0 || quantity_data.error == 1) {
		return true;
	}
	
	quantity_requested = parseInt(quantity_requested);
	var quantity_in_stock = parseInt(quantity_data.quantity_in_stock);
	var quantity_in_cart = parseInt(quantity_data.quantity_in_cart);
	
	if(quantity_requested == 0) {
		return true;
	}
	
	var error_text = '';
	if(quantity_data.name != null && quantity_data.name != '') {
		error_text += "<b>" + quantity_data.name + "</b><br/>";
	}
	
	if(quantity_in_stock == 0) {
		error_text += 
			"Sorry, we sold out of this item while you were shopping.<br/>"+
			"Please update your cart.";
		
		display_popup_message(error_text);
		return false;
	}
	
	if(quantity_requested > quantity_in_stock) {
		error_text += 
			"Sorry, we only have " + quantity_in_stock + " of this item in stock right now.<br/>"+
			"Please check the quantity entered and try again. Thanks!";
		
		display_popup_message(error_text);
		return false;
	}
	
	return true;
}

function check_item_quantity_cart(quantity_requested, quantity_data) {
	
	if(quantity_data == null || quantity_data.available == 0 || quantity_data.error == 1) {
		return true;
	}
	
	quantity_requested = parseInt(quantity_requested);
	var quantity_in_stock = parseInt(quantity_data.quantity_in_stock);
	var quantity_in_cart = parseInt(quantity_data.quantity_in_cart);
	
	if(quantity_requested == 0) {
		return true;
	}
	
	var error_text = '';
	if(quantity_data.name != null && quantity_data.name != '') {
		error_text += "<b>" + quantity_data.name + "</b><br/>";
	}
	
	if(quantity_in_stock == 0) {
		error_text += 
			"Sorry, we sold out of this item while you were shopping.<br/>"+
			"Please update your cart.";
		
		display_popup_message(error_text);
		return false;
	}
	
	if(quantity_requested > quantity_in_stock) {
		error_text += 
			"Sorry, we only have " + quantity_in_stock + " of this item in stock right now.<br/>"+
			"Please check the quantity entered and try again. Thanks!";
		
		display_popup_message(error_text);
		return false;
	}
	
	return true;
}

function display_popup_message(message) {
	var error_div = $('#popup_message #popup_message_container');
	
	error_div.html(message);
	$('#popup_message').css('left', $('body').width() - $('#popup_message').width() - 50);
	$('#popup_message').show("slow");
}

/**
 * Perform adding to cart with check of product quantity in stock
 * @param productId
 */
function add_to_cart(productId, source, seewhy_params)
{
    amount = document.getElementById('amount_' + productId).value;
//    alert('amount_' + productId);
    amount = $.trim(amount);
    
    sku = document.getElementById('sku_' + productId).value;
    sku = $.trim(sku);
    
    rprice = document.getElementById('rprice_' + productId).value;
    rprice = $.trim(rprice);
    
    // ticket #74; do nothing if user set product quantity to 0 or empty string
    if(amount == "" || parseInt(amount) == 0) {
    	return;
    }
    
	var returning_value = true;
	
	// check quantity of requested item
	$.ajax({
		async: false,
		  type: 'POST',
		  url: "/item_quantity_service.php",
		  data: { product_id: productId},
		  success: function(result){
			  
			  if(!check_product_quantity(amount, result)) {
				  returning_value = false;
			  }
			
		  },
		  dataType: "json"
	});
	
	// disallow adding to cart if quantity of product is not enough
	if(!returning_value) {
		return false;
	}
	
	url = '/product.php?p=' + productId + "&products_id=" + productId + "&action=buy_now&amount=" + amount;

	$.get(url, function(data) {
		kissmetrics_event_added_to_cart(source, sku, amount, rprice);
		
		process_cart(data);

        seewhy_fire_intent_event(seewhy_params);
	});
}


function process_cart(data) {
//	var cart_template = $.template('<div class="shopping_cart_container_image">${image}</div><div class="shopping_cart_container_info"><div class="shopping_cart_product"><b>${name}</b></div><div class="shopping_cart_cost">${price}</div><div class="shopping_cart_qty">Qty: ${qty}</div></div><div style="clear:both; height: 5px;"></div>');
//	var total_cart_template = $.template('<div class="shopping_cart_items_count">You have ${total} items in your cart</div><div class="shopping_cart_sub_total">Cart Sub-total ${subtotal}</div><div class="shopping_cart_button"><a href="/shopping_cart.php"><img src="/template/images/shopping_cart_mini/checkout_button.png" /></a></div>');
	var cart_template = $.template('<td width="75">${image}</td><td><a href="#">${name}</a><br/>Qty: <b>${qty}</b> <big>|</big> Price: <b>${price}</b></td>');
	
	var total_cart_template = $.template('${total} Items in Your Cart<br><b>Order Subtotal: &nbsp;&nbsp;&nbsp;${subtotal}</b><br><center><input type="image" class="button_checkout" src="/template/images/shopping_cart_mini/minicart-checkout.png" onclick="document.location.href=\'/shopping_cart.php\'"></center>');
	var free_shipping_template = $.template("Only ${priceTillFree} more for <br>free shipping!");

	if (wideCart) 
	{
		total_cart_template = $.template(
			'${total} Items in Your Cart<b style="padding-left: 40px;">Order Subtotal: &nbsp;&nbsp;&nbsp;${subtotal}</b><br>' +
			'<input type="image" class="button_checkout" src="/template/images/continue-shopping.png" onclick="close_shopping_cart()" style="margin-top: 5px; padding-right: 25px;">' +
			'<input type="image" class="button_checkout" src="/template/images/shopping_cart_mini/minicart-checkout.png" onclick="document.location.href=\'/shopping_cart.php\'">');
	
		free_shipping_template = $.template("Only ${priceTillFree} more for free shipping!");
	}

	var obj = jQuery.parseJSON(data);
	
	if(obj == null) {
		return;
	}
	
	if (obj[0] == true && obj[1] == 'cart') {
		$('#shopping_cart_container').empty();
		$.each(obj[2], function(key, value) {
			$('#shopping_cart_container').append( cart_template , {
				image: value.image,
				name: value.name,
				price: value.price,
				qty: value.quantity
			});
		});

		$('#shopping_cart_total').empty();
		$('#shopping_cart_total').append( total_cart_template , {
			total: obj[3].total,
			subtotal: obj[3].subtotal
		});
		
		$('#to_free_shipping').empty();
//		alert ('protev'+obj[3].priceTillFree);
		if (obj[3].priceTillFree != null) {
			$('#to_free_shipping').append( free_shipping_template, {
				priceTillFree: obj[3].priceTillFree
			});
		}
		$("#cart_items_count").html(obj[3].total);
		$("#cart_items_price").html(obj[3].subtotal);
		$('#shopping_cart_mini').css('left', ($('body').width() - $('#shopping_cart_mini').width()) / 2);
		$('#shopping_cart_mini').css('top', ($(window).height() - $('#shopping_cart_mini').height()) / 2);
		$('#shopping_cart_mini').slideDown();
	    clearTimeout(minicartTimeout);
	    if (autocloseCart)
	    {
			minicartTimeout = setTimeout(function() {
				$('#shopping_cart_mini').slideUp("slow");
			}, 5000);
		}
	} else {
		if (obj[0] == false && obj[1] == 'url')
			location.href = obj[2];
	}
}

function enter_shipping_zip()
{
	$('#shipping_zip').css('left', ($('body').width() - $('#shipping_zip').width()) / 2);
	$('#shipping_zip').css('top', ($(window).height() - $('#shipping_zip').height()) / 2);
//	$('#shipping_zip').slideDown("fast");
	$('#shipping_zip').show();
	$('#shipping_zip_input').focus();
}

function close_shipping_zip_popup()
{
	$('#shipping_zip').slideUp("fast");
}

function update_cart() {
	var returning_value = true;
	
	var cells = $("td.qty");
	$.each(cells, function(index, value) 
	{ 
		 var new_qty = $(this).find("input[name=cart_quantity[]]").val();
		 var item_index = $(this).find("input[name=items_index[]]").val();
		 var product_id = $(this).find("input[name=products_id[]]").val();
		 var pack_id = $(this).find("input[name=packs_id[]]").val();
		 //alert (new_qty + ", " + product_id + ", " + pack_id);
	
		$.ajax({
			async: false,
			  type: 'POST',
			  url: "/item_quantity_service.php",
			  data: { item_index: item_index, product_id: product_id, pack_id: pack_id},
			  success: function(result){
				  
				  if(!check_item_quantity_cart(new_qty, result)) 
				  {
					  returning_value = false;
				  }
				  
			  },
			  dataType: "json"
		});
		
		if(!returning_value) 
		{
			return false;
		}
		 
	});
	
	if(returning_value) 
	{
		$('#cart_quantity').submit();
	}
}

/**
 * Validate quantity of products on checkout button pressing
 * @param redirect_url - url for redirect if quantity of products is valid
 */
function validate_cart(redirect_url) {
	
	var returning_value = true;
	
	var cells = $("td.qty");
	$.each(cells, function(index, value) { 
		 var new_qty = $(this).find("input[name=cart_quantity[]]").val();
		 var product_id = $(this).find("input[name=products_id[]]").val();
		 var pack_id = $(this).find("input[name=packs_id[]]").val();
	
		$.ajax({
			async: false,
			  type: 'POST',
			  url: "/item_quantity_service.php",
			  data: { product_id: product_id, pack_id: pack_id},
			  success: function(result){
				  
				  if(!check_product_quantity_cart(new_qty, result)) {
					  returning_value = false;
				  }
			  },
			  dataType: "json"
		});
		
		if(!returning_value) {
			return false;
		}
		 
	});
	
	if(returning_value) {
		location.href = redirect_url;
	}
}

function changeSortTitle() {

	var selected_item_text = $("#_search_select_top :selected").text();
	
	if ($("#search_sort_select").length > 0) {
		$("#search_sort_select").html(selected_item_text);
	}
	if ($("#search_sort_select_top").length > 0) {
		$("#search_sort_select_top").html(selected_item_text);
	}
	if ($("#search_sort_select_bottom").length > 0) {
		$("#search_sort_select_botoom").html(selected_item_text);
	}
}

function changePageTitle(el) {

	var text = el.find("option:selected").text();
	if ($("#search_page_select").length > 0) {
		$("#search_page_select").html(text);
	}
	if ($("#search_page_select2").length > 0) {
		$("#search_page_select2").html(text);
	}
	if ($("#search_select_page_top").length > 0) {
		$("#search_select_page_top").html(text);
	}
	if ($("#search_select_page_bottom").length > 0) {
		$("#search_select_page_bottom").html(text);
	}
}

function go_search() {
	var search_subject = $('#search_form #search').val();
	kissmetrics_event_used_search(search_subject);
	
	$('#search_form').trigger('submit');
}

function init_search_controls() {
	$("#search_sort_select").html($("#_search_select_top :selected").text());
	var text = $("#_search_select_page_top :selected").text();
	$("#search_page_select").html(text);
	$("#search_page_select2").html(text);
}

function init_sort_controls() {
	$("#search_sort_select_top").html($("#_search_select_top :selected").text());
	$("#search_sort_select_bottom").html($("#_search_select_top :selected").text());
}

function init_pagecount_controls() {
	$("#search_select_page_top").html($("#_search_select_page_top :selected").text());
	$("#search_select_page_bottom").html($("#_search_select_page_top :selected").text());
}

function close_shopping_cart() {
    clearTimeout(minicartTimeout);
	$('#shopping_cart_mini').slideUp("slow");
}

function close_popup_message() {
	$('#popup_message').hide("slow");
}

/* KissMetrics */
function kissmetrics_event_used_search(search_subject) {
	// It is necessary to wrap procedure call to try/catch 
	// because _kmq object does not exist on local test site.
	try {
		_kmq.push(['record', 'Used Search', {'pw search subject':search_subject}]);
	} catch (ex) {};
}

function kissmetrics_event_viewed_product_page(url) {
	try {
		_kmq.push(['record', 'Viewed Product Page', {'pw new product url':url}]);
	} catch (ex) {};
}

function kissmetrics_event_viewed_old_product_page(url) {
	try {
		_kmq.push(['record', 'Viewed Old Product Page', {'pw old product url':url}]);
	} catch (ex) {};
}

function kissmetrics_event_viewed_article_page(url) {
	try {
		_kmq.push(['record', 'Viewed Article Page', {'pw article url':url}]);
	} catch (ex) {};
}

function kissmetrics_event_added_to_cart(source, sku, quantity, price) {
	var total_price = parseFloat(quantity) * parseFloat(price);
	
	try {
		_kmq.push(['record', 'Added To Cart', {'pw source':source, 'pw sku':sku, 'pw quantity':quantity, 'pw total':total_price}]);
	} catch (ex) {};
}

/**
 * 
 * I send product_id to kissmetrics instead pack_id because old packs inludes only one product.
 */
function kissmetrics_event_added_to_cart_old_partypack(product_id, quantity, price) {
	var total_price = parseFloat(quantity) * parseFloat(price);
	
	try {
		_kmq.push(
				[
				 	'record', 
				 	'Added To Cart Old Partypack', 
				 	{
				 		'pw old pack product id':product_id, 
				 		'pw old pack product quantity':quantity, 
				 		'pw old pack product total price':total_price
				 	}
				 ]
		);
	} catch (ex) {};
}

function kissmetrics_event_added_to_cart_partypack(pack_id, quantity, price) {
	var total_price = parseFloat(quantity) * parseFloat(price);
	
	try {
		_kmq.push(
				[
				 	'record', 
				 	'Added To Cart Partypack', 
				 	{
				 		'pw new pack id':pack_id, 
				 		'pw new pack product quantity':quantity, 
				 		'pw new pack product total price':total_price
				 	}
				]
		);
	} catch (ex) {};
}

function kissmetrics_event_purchased_products(quantity, total_price, shipping_type, shipping_price) {
	try {
		_kmq.push(
				[
				 	'record', 
				 	'Purchased Products', 
				 	{
				 		'pw purchased quantity':quantity, 
				 		'pw purchased total price':total_price,
				 		'pw purchased shipping type':shipping_type,
				 		'pw purchased shipping price':shipping_price
				 	}
				]
		);
	} catch (ex) {};
}

/* ~KissMetrics */

function cart_popup_update_contents(needOpen)
{
//    alert(needOpen);
	$.ajax({
		async: false,
			type: 'POST',
			url: "/cart_ajax.php",
			data: {action: 0 },
			success: function(result) {
				$('#shopping_cart_edit').empty();
				$('#shopping_cart_edit').html(result.html);
				$('#shopping_cart_edit').css('left', ($('body').width() - $('#shopping_cart_edit').width()) / 2);
				if (needOpen) 
				{
					$('#shopping_cart_edit').css('top', 70);
					$('#shopping_cart_edit').slideDown();
				}
		  },
		  dataType: "json"
	});
}

function checkout_cart_update_contents()
{
	$.ajax({
		async: false,
			type: 'POST',
			url: "/cart_ajax.php",
			data: {action: 0, template: 'checkout' },
			success: function(result) {
				$('#checkout_cart_edit').empty();
				$('#checkout_cart_edit').html(result.html);
				$('#_subtotal_price').text(result.subtotal_formatted);
				$("#cart_items_count").html(result.count);
				$("#cart_items_price").html('$'+result.subtotal_formatted);
				onchange_cart();
		  },
		  dataType: "json"
	});
}


function open_cart()
{
    cart_popup_update_contents(true);
}

function close_cart_edit() {
	clearTimeout(minicartTimeout);
	$('#shopping_cart_edit').slideUp("slow");
	if ($('#shopping_cart_edit').length > 0) checkout_cart_update_contents();
}

function cart_popup_delete(index)
{
	if (!confirm("Are you sure you want to remove this item?")) return;
	url = '/shopping_cart.php?action=remove_item&item_id=' + index;
	$.ajax({
		async: false,
		type: 'GET',
		url: url,
		success: function(result) {
		    cart_popup_update_contents(false);
		}
	});
}

function checkout_cart_delete(index)
{
	if (!confirm("Are you sure you want to remove this item?")) return;
	url = '/shopping_cart.php?action=remove_item&item_id=' + index;
	$.ajax({
		async: false,
		type: 'GET',
		url: url,
		success: function(result) {
			checkout_cart_update_contents(false);
		}
	});
}

// todo: optimize, probably unite with update_cart()
// update item for minicart edit popup
function update_cart_popup_item(selected_index) {
	var returning_value = false;
	
	var cells = $("td.qty");
	var qty;
	$.each(cells, function(index, value) 
	{ 
		var new_qty = $(this).find("input[name=cart_quantity[]]").val();
		var item_index = $(this).find("input[name=items_index[]]").val();
		var product_id = $(this).find("input[name=products_id[]]").val();
		var pack_id = $(this).find("input[name=packs_id[]]").val();
		if (selected_index == item_index)
		{
			$.ajax({
				async: false,
				  type: 'POST',
				  url: "/item_quantity_service.php",
				  data: { item_index: item_index, product_id: product_id, pack_id: pack_id},
				  success: function(result){
					  if (check_item_quantity_cart(new_qty, result)) 
					  {
						  returning_value = true;
						  qty = new_qty;
					  }
				  },
				  dataType: "json"
			});
			
			if (!returning_value) 
			{
				return false;
			}
		}
	});
	
	if(returning_value) 
	{
	    if (qty == 0)
	    {
			if (!confirm("Are you sure you want to remove this item?")) return;
			qty = -1;
	    }
		$.ajax({
			async: false,
				type: 'POST',
				url: "/cart_ajax.php",
				data: {action: 'update', index: selected_index, qty: qty},
				success: function(result) {
					$('#shopping_cart_edit').empty();
					$('#shopping_cart_edit').html(result.html);
					$('#shopping_cart_edit').css('left', ($('body').width() - $('#shopping_cart_edit').width()) / 2);
			  },
			  dataType: "json"
		});
		
	}
}

// update item for minicart on checkout page
function checkout_update_cart_item(selected_index) {
	var returning_value = false;
	
	var cells = $("td.qtychk");
	var qty;
	$.each(cells, function(index, value) 
	{ 
		var new_qty = $(this).find("input[name=cart_quantity[]]").val();
		var item_index = $(this).find("input[name=items_index[]]").val();
		var product_id = $(this).find("input[name=products_id[]]").val();
		var pack_id = $(this).find("input[name=packs_id[]]").val();
		if (selected_index == item_index)
		{
			$.ajax({
				async: false,
				  type: 'POST',
				  url: "/item_quantity_service.php",
				  data: { item_index: item_index, product_id: product_id, pack_id: pack_id},
				  success: function(result){
					  if (check_item_quantity_cart(new_qty, result)) 
					  {
						  returning_value = true;
						  qty = new_qty;
					  }
				  },
				  dataType: "json"
			});
			
			if (!returning_value) 
			{
				return false;
			}
		}
	});
	
	if (returning_value) 
	{
	    if (qty == 0)
	    {
			if (!confirm("Are you sure you want to remove this item?")) return;
			qty = -1;
	    }
		$.ajax({
			async: false,
				type: 'POST',
				url: "/cart_ajax.php",
				data: {action: 'update', index: selected_index, qty: qty, template: 'checkout'},
				success: function(result) {
					$('#checkout_cart_edit').empty();
					$('#checkout_cart_edit').html(result.html);
					$('#_subtotal_price').text(result.subtotal_formatted);
					$("#cart_items_count").html(result.count);
					$("#cart_items_price").html('$'+result.subtotal_formatted);

					onchange_cart();
			  },
			  dataType: "json"
		});
		
	}
}

