/*
 * Ajax Mini Cart for oScommerce 2.3.3
 *
 ***************************************/
var running;

$(function($) {
/* Mini Cart Dialog */
$.fn.ajaxMiniCart = function() {
	var $dialog = $('<div id="ajax_cart_dialog"></div>')
	.load("/boutique/ajax_cart.php", function(){
		$('#overlay').fadeOut('slow', function() {
			$('#overlay').remove();
		});
	})
	.dialog({
		resizable: false,
		modal: true,
		draggable: false,
		autoOpen: false,
        width:'80%',
		dialogClass: "ajax_cart",
		closeOnEscape: true,
		show: {effect: 'fade', duration: 250},
		hide: {effect: 'drop', direction: "down", duration: 200},
		open: function(event, ui)
		{
			//here we can apply unique styling

			$(this).parent()
			.css('top', '15%');

			$(this).parents(".ui-dialog:first")
			.find(".ui-dialog-titlebar").remove();

			$(this).parents(".ui-dialog")
			.css("background", '#FFF');

			$(this).parents(".ui-dialog:first").find(".ui-dialog-content")
			.css("padding", 0)
			.css("overflow", 'auto');
		},
		close: function( event, ui ) {
			// Refresh entire page if current page is checkout_confirmation.php - OR - shopping_cart.php!
			//
			var checkout_page = $('form[name=checkout_confirmation]').length;
			var url = $(location).attr('href').split("/");
			var filename = url[url.length - 1];
			filename = filename.split('\?')[0] ;
			if ( filename == 'checkout_confirmation.php' || filename == 'shopping_cart.php' || checkout_page != 0)
			{
				$('form[name=boxcart_quantity]').submit();
			}

			return $('#ajax_cart_dialog').dialog( "destroy" ).remove();
		}
	}).css('overflow', 'auto');

	return $dialog.dialog("open");
}



/* Dialog Controls */
/*-----------------*/

/* Init Dialog */
$('body').on('click', '.ajax_cart_init', function(event){
	event.preventDefault();
	return($(this).ajaxMiniCart());
});

/* Close Dialog */
$('body').on('click', '.closeWindow', function(event){
	event.preventDefault();
	return($('#ajax_cart_dialog').dialog('close'));
})

/* Remove Products From Cart */
$('body').on('click', '.mini-cart-delete', function(event){
	event.preventDefault();
	if(running) return false;
	running = true;
	products_id = $(this).attr('rel') ;
	return($(this).cartRemoveActionMini(products_id));
});

/* Plus/Minus - Change Product Quantity */
$('body').on('click', '.update-quantity', function() {
	if(running) return false;
	running = true;
	productID = $(this).attr('rel') ;
	action = $(this).attr('class').split(' ').slice(-1) ;
   // alert(action);

	if ( action  == 'plus' )
	{
		action = 1;
	}
	else if ( action == 'minus' )
	{
		action = -1;
	}
	else
	{
		return false;
	}

    //console.log('test'+productID);
    //id="pl-' + productID + '"][name=\'cart_quantity["' + productID + '"]\'

	return($(this).updatequantity(productID, action));
});

$('body').on('change', '.ajax_cart_qty_input', function() {
    valueToUpdate = parseInt($(this).val());
    // console.log($(this).attr('id'))
    $('#headercart').html('')
    // console.log(typeof valueToUpdate)
    $(this).updatequantity($(this).attr('id'), valueToUpdate);
});



/* Functions */
/*-----------*/

/* Remove Product from Cart */
$.fn.cartRemoveActionMini = function(productID) {

	$(document.getElementById('cart_mini_delete-' + productID)).attr('checked', true) ;

	var action = parseInt( $('input[id="pl-' + productID + '"][name=\'cart_quantity["' + productID + '"]\']').val() ) ;
	action = -1 * action;

	// Look for attributes
	//
	products_attributes = '' ;
	$('#ajax_cart').find('select option:selected').each(function() {
		products_attributes += '{' + $(this).parent().attr('name').replace(/[^0-9]/g, '') + '}' + $(this).val() ;
	});
	if ( products_attributes != '' ) {
		products_id = productID + products_attributes;
	} else {
		products_id = productID;
	}


	$.ajax({
		type: 'POST',
		url: encodeURI($('#ajax_cart').attr('action')) + '&ajax=1',
		data: $('#ajax_cart').serialize(),
		cache: false,
		async: true,
		success: function(data) {
			$(this).update_mini_cart(data, action);
		},
		dataType: 'html'
	});

	return(false);
}


/* Plus or Minus function */
$.fn.updatequantity = function(productID, action) {

 //   alert(productID);

	var val = parseInt( $('input[id="pl-' + productID + '"][name=\'cart_quantity["' + productID + '"]\']').val() ) ;
	val = val + action;

	$(document.getElementById('pl-' + productID)).val(val) ;

	$.ajax({
		type: 'POST',
		url: encodeURI($('#ajax_cart').attr('action')) + '&ajax=1',
		data: $('#ajax_cart').serialize(),
		success: function(data) {
			$(this).update_mini_cart(data, action);
		},
		dataType: 'html'
	});

	return false;
}

// Update headercart
//
$.fn.update_mini_cart = function(data, action) {

	$('#boxcart-content').html('');
	$('#contentContainer').html(data);
	$('#contentContainer').find('#boxcart-content-table').appendTo('#boxcart-content');
	if ( $('#show_total').length > 0 ) {
		var show_total = $('#show_total').html() ;
		$('#boxcart-total').html(show_total);
	} else {
		$(".boxcartTotal").hide();
	}

	var parentHeader = $('#headercart').parent();

	var qty = (($('#headercart').html()));
	var qty = qty.replace(/[^\d]/g, '') ;
	if (qty == 'undefined' || qty == '') qty = 0;
	var qty = parseInt(qty) ;

	if ( (qty + action) == 0) {
		qty = '<span id="headercart">0 item</span>';
		show_total='0.00$';
	} else {
		qty = '<span id="headercart"> ' + (qty + action) + ' item(s)</span>';
	}


	$('#headercart').remove();
	//parentHeader.append( qty ) ;
	$( qty ).insertAfter( "#picto_cart" );

	$('#minicart_total').html(show_total);

	$('#overlay').fadeOut('20', function() {
		$(this).remove();
	});

	return running = false;
}

});