/***************************************************
*	cartUpdate Plugin
*	Author: Piotr Burdzinski
*	Syntax: $( button selector ).cartUpdate( contentid, { options } );
*	Options:
*		quantity	- INT/STRING (static integer or quantity textbox selector)
*		refresh		- BOOLEAN (true or false)
*		action		- STRING ('I' or 'U')
*		callback	- FUNCTION
*		attributes	- OBJECT
*	Dependencies:
*		jQuery (1.4.2 minimum)
*		formPost Plugin
*
*****************************************************/
$(document).ready(function()
{
	$('[data-method="cartUpdate"]').each(function(){
		$(this).cartUpdate($(this).attr('data-contentid'), {
			quantity: $(this).attr('data-quantity'),
			refresh: $(this).attr('data-refresh'),
			action: $(this).attr('data-action'),
			qstring: $(this).attr('data-qstring'),
			callback: $(this).attr('data-callback')
			// attributes: Every other data attribute that isn't listed above or data-method
			// attributes: this.attributes;
		});
	});
});

(function($) {
    var currentText;

    $.fn.cartUpdate = function(contentid, options) {
        var currentButton = this;
        $.fn.cartUpdate.defaults =
			{
			    contentid: '',
			    quantity: 1,
			    refresh: false,
			    callback: '',
			    qstring: '',
			    action: 'I',
			    attributes: ''
			};

        var properties = $.extend({}, $.fn.cartUpdate.defaults, options);
        var randomNumber = Math.random() + '';
        randomNumber = '&RND=' + randomNumber.replace('0.', '');
        var itemAttributes = (typeof (properties.attributes) === 'object') ?
						'&' + jQuery.param(properties.attributes) :  //true
						''; //false

        var currentQuantity = properties.quantity;

        if (properties.action === 'I') {
            currentButton.click(function() {
		

                //accounts for the user specifying an element instead of a quantity.
                if ( isNaN(properties.quantity) ) {
                    currentQuantity = $(properties.quantity).val();
                }

                //assuring that the quantity is an integer.
                currentQuantity = parseInt(currentQuantity, 10);

                //TEMPORARY FIX, use jQuery validate method in the future.
                if (isNaN(currentQuantity) || currentQuantity < 1) {
                    alert('Quantities less than 1 are not accepted.');
                    return false;
                }

                var addToCartURL = "Ajax.aspx?CN=98A129E595F9&ITEMID=" +
							contentid +
							"&HLTYPE=ADD&quantity=" +
							currentQuantity +
							itemAttributes +
							"&"+ properties.qstring +
							randomNumber;

                currentText = $(this).text();
               //$(this).addClass('active').text('Adding...');

                $.get(addToCartURL, null, function() {

                    if (properties.refresh === true || properties.refresh === 'true') {
                        window.location = window.location;
                    }
                    else {
                        notifyUpdate(currentButton, contentid);

                        if (typeof (properties.callback) === 'function') {
                            properties.callback();
                        }
                    }
                });
            });
        }
        else if (properties.action === 'U') {
            currentButton.formPost(
			{
			    action: properties.action,
			    redirect: contentid
			});
        }

        return this;
    }

    function notifyUpdate(element, contentid) {
	var randomNr = Math.random() + '';
        var currentTop = $('#session-bar').offset().top + $('#session-bar').height();
        $('body').append('<div id="updated-session"></div>');
        $('#updated-session').load('Ajax.aspx?CN=72DCC536A7EA&rnd=' + randomNr, function() {
            element.removeClass('active').text(currentText);
            $('#session-bar').html($('#updated-session').find('#session-bar').html());
            $('#updated-session').remove();
            $("#small-cart").trigger('mouseover');
            $('.small-cart-drop-down').hide();
            if ($(window).scrollTop() > currentTop) {
                $('.small-cart-drop-down').css({
                    position: 'fixed',
                    top: '0px'
                });
            }

            $(window).scroll(function() {
                if ($(window).scrollTop() < currentTop) {
                    $('.small-cart-drop-down').css({
                        position: 'absolute',
                        top: currentTop + 'px'
                    });
                };
            });

            $('.small-cart-drop-down').slideDown('fast', function() {
                $(this).find('#row-' + contentid).animate({
                    backgroundColor: '#ffffaa'
                }, 1000).animate({
                    backgroundColor: '#ffffff'
                }, 1000);
                $(this).delay(5000).fadeOut(function() {
                    $('#small-cart').trigger('mouseout');
                    $('.small-cart-drop-down').css({
							'top': currentTop + 'px'

						   });
                });
            });

        });
    }

})(jQuery);
