//=======================================================================================================
//-------------------------------------------------------------------------------------------------------
//	Store/Cart functions
//-------------------------------------------------------------------------------------------------------
//=======================================================================================================
$(document).ready(function(){

//-------------------------------------------------------------------------------------------------------
//	Initialize minicart
//-------------------------------------------------------------------------------------------------------
	if( !noajax )
	{
		cart	= $("#minicart");

		$(window).bind("resize scroll", function() {
			SidebarScroller();
		});
		
		//	Minimum scroll depth before switching to position fixed
		scroll_min		= $("td#right").position().top;
		SidebarScroller();
	}

//-------------------------------------------------------------------------------------------------------
//	Add Item
//-------------------------------------------------------------------------------------------------------
    var active_membership_input = $('input[name=membership]:checked');
    if(active_membership_input.length) {
        active_membership = active_membership_input.attr('id').replace(/item-/, '');
    }

    // Memberships (an either/or situation)
    $('input[name=membership]').change( function(){

        var obj = $(this);
        var obj_id = obj.attr('id').replace(/item-/, '');

        if(active_membership != obj_id) { // Either none, or the other one
            if(active_membership) {
                var remove_link = $('#remove-' + active_membership).attr('href');
                // Hit remove link, then on callback add new one to store
                $.get(remove_link, {}, function(data, status) {
                    AddToCart(obj.attr('rel'));  
                });
            } else {
                AddToCart(obj.attr('rel'));  
            }
            active_membership = obj_id;
        } 
    });

	$('input:checkbox.storeitem').click( function(){

		if( $(this).attr("checked") )
		{
			//	Ajax refresh the cart
			AddToCart($(this).attr('rel'));  

			//	Change checkbox
			var container = $(this).parent().hide();
			var dom_id = container.attr('id').replace(/item/, 'incart');
			$('#' + dom_id).toggle();
		}
	});

    $('a.storeitem').click( function(e){
		e.preventDefault();
        AddToCart($(this).attr('href'));  
        return false;
    });

    // Since links are added dynamically, we're catching the event bubbling on the 
    // container instead
    $('#minicart').click(function(e){
        var obj = $(e.target);
        if(obj.hasClass('remove-link')) {

			AjaxLoading( cart );

			var obj_id = obj.attr('id').replace(/remove-/, '');
            var remove_link = obj.attr('href');
            if(obj_id == active_membership) {
                active_membership = '';
                $('#item-' + obj_id).attr('checked', '');
            } else {
                $('#incart-' + obj_id).trigger('emptycart');
            }
            $.get(remove_link, {}, UpdateMiniCart);

			return false;
        }
    });

    $('div.in-cart').bind('emptycart', function(){
        var obj = $(this);
        if(obj.is(':visible')) {
            var dom_id = obj.attr('id').replace(/incart/, 'item');
            obj.hide();
            $('#' + dom_id).show().find('input').attr('checked', '');
        }
    });

});

var	noajax;
var cart;
var active_membership = '';
var	anim_speed	= 150;
var	scroll_min;

//-------------------------------------------------------------------------------------------------------
//	When ajax action is initialized, set up the loading banner
//-------------------------------------------------------------------------------------------------------
function AjaxLoading( obj )
{
	//	Add loading placeholder to cover updating area
	$(obj).parent().append('<div class="loading"></div>');

	//	Top/Left positioning
	$(obj).parent().find(".loading").css("top", $(obj).position().top );
	$(obj).parent().find(".loading").css("left", $(obj).position().left );

	//	Size to cover the updating area
	$(obj).parent().find(".loading").css("height", $(obj).parent().height() );
	$(obj).parent().find(".loading").css("width", $(obj).parent().width() );
}

//-------------------------------------------------------------------------------------------------------
//	When ajax action is finished, remove the loading banner
//-------------------------------------------------------------------------------------------------------
function AjaxComplete( obj )
{
	//	Remove
	$(obj).parent().find(".loading").fadeOut(anim_speed).delay(500).queue(function() {
		$(this).detach();
	});
}

//-------------------------------------------------------------------------------------------------------
//	Ajax-call the add to cart links
//-------------------------------------------------------------------------------------------------------
function AddToCart(add_link)
{
	AjaxLoading( cart );
	$.get(add_link, { uid: getUniqueId() }, function() {
		UpdateMiniCart();
	});
}

//-------------------------------------------------------------------------------------------------------
//	Ajax-update the cart widget
//-------------------------------------------------------------------------------------------------------
function UpdateMiniCart()
{
	AjaxLoading( cart );

	$.get("/store/update.php", function(data, status){

        if(cart.html()) { // if cart is already contains something, just update
            cart.html(data); 
        }
        else { //if nothing there, hide it, set it, fade in
            cart.hide(function(){
                cart.html(data).slideDown(anim_speed)
            }); 
        }
		AjaxComplete( cart );

	});
}

//-------------------------------------------------------------------------------------------------------
//	Clear the cart and set checkboxes and buttons back to add state
//-------------------------------------------------------------------------------------------------------
function emptyCart()
{
    $.get('/store/empty.php', {}, function(data, status){
        $('input:checked').attr('checked', '');
        active_membership = '';
        $('#minicart').slideUp(anim_speed, function(){
            $(this).html('').trigger('emptycart') ;
            $('div.in-cart').trigger('emptycart');
        });
    });
}

//-------------------------------------------------------------------------------------------------------
//	Dynamically change the positoning of the right column, allow it to scroll with page or position fixed
//-------------------------------------------------------------------------------------------------------
function SidebarScroller()
{
	//	Is there enough room to fix its position?
	scroll_allow	= $(window).height() - $("#innerright").height();

	if( scroll_allow <= 0 )
	{
		//	No, set to static
		$("#innerright").css("position","static");
		return;
	}

	//	Is the header scrolled above the fold (depth of header)
	if( $(window).scrollTop() > scroll_min )
	{
		//	Yes, set position fixed
		$("#innerright").css("position","fixed").css("top",36);
	}
	else
	{
		//	No, allow it to scroll with page
		$("#innerright").css("position","static");
	}
}

