﻿function deleteCartItem(itemId)
{
    if($('body').hasClass('wait'))
      return;
      $('body').addClass('wait');
		$.post("/_layouts/LRMSCartAPI.asmx/DeleteProductFromCart",
			{cartItemId: itemId},
			function(data){
        $('body').removeClass('wait');
				refreshCart();
			});
}
//call this one if you want to get a new cart from the server and repopulate the cart bar
function refreshCart(){
	$.post("/_layouts/LRMSCartAPI.asmx/GetCart",{},
		function(data)
		{
			cart = $.xml2json(data);

			if(typeof cart.New_Billtocountry === 'undefined' )
			{
				var userLocation = userLocation || {},
					userCountry;
				
				if(userLocation.hasOwnProperty('countryName') && userLocation.countryName != null){
					userCountry = userLocation.countryName.toUpperCase();
				} else {
					userCountry = 'UNITED STATES';
				}
				$.post("/_layouts/LRMSCartAPI.asmx/UpdateCartCountry",
					{ country: userCountry },
					function(updateCountryData)
					{
						cart = $.xml2json(updateCountryData);
					});
			}

			populateCart(true);
		}
	);
}
var stateList = null;
function PopulateStates(selectid, defaultState, defaultcountry) {
    if (stateList == null) {
        $.get('/_layouts/LRMSCartAPI.asmx/GetStateList', function (data) {
            stateList = $.xml2json(data);
            buildStateSelect(selectid, defaultState, defaultcountry);
        });
    } else {
        buildStateSelect(selectid, defaultState, defaultcountry);
    }
}
function buildStateSelect(selectid, defaultState, defaultcountry) {
    var classes = $('#' + selectid)[0]?$('#'+selectid)[0].className : '';
    var name = $('#' + selectid).attr('name');
    var prev = $('#' + selectid).prev();
    var preValue = $('#' + selectid).val();
    var preType = $('#' + selectid).attr('type');
    $('#' + selectid).remove();
    var stateEl = document.createElement('select');
    $(stateEl).attr('id', selectid);
    $(stateEl).attr('name', name);
    $(stateEl).addClass(classes);
    $(stateEl).removeClass("inactive");
    var country = 'UNITED STATES';
    if (defaultcountry != null && defaultcountry != '')
        country = defaultcountry;
    for (var i = 0; i < $(stateList.CartState).length; i++) {
        var item = $(stateList.CartState)[i];
        if (item.Country == country) {
            var state = item.State;
            var abbr = item.Abbr;
            if (abbr == defaultState) {
                $(stateEl).append("<option selected value='" + abbr + "'>" + state + "</option>");
            } else {
                $(stateEl).append("<option value='" + abbr + "'>" + state + "</option>");
            }
        }
    }
    if ($(stateEl).children('option').length == 0) {
        stateEl = document.createElement('input');
        $(stateEl).attr('id', selectid);
        $(stateEl).addClass(classes);
        $(stateEl).attr('type', 'text');
        $(stateEl).attr('name', name);
        $(stateEl).attr('default', 'State or Province');
        if (preType == "text" && preValue != '') {
            $(stateEl).val(preValue);
            $(stateEl).removeClass("inactive");
        }
        else if (defaultState != '') {
            $(stateEl).val(defaultState);
            $(stateEl).removeClass("inactive");
        }
        else {
            $(stateEl).val("State or Province");
            $(stateEl).addClass("inactive");
        }

        $(stateEl).blur(function () {
            if (this.value == '') {
                this.value = $(this).attr('default');
                $(this).addClass('inactive');
            }
        });
        $(stateEl).focus(function () {
            if (this.value == $(this).attr('default')) {
                this.value = '';
                $(this).removeClass('inactive');
            }
        });
    }
    prev.after(stateEl);
    $(stateEl).focus();
    $(stateEl).blur();
}

//call this one if you've already got the cart variable populated and just want to update the cartbar
var itemTpl = $("<tr class='cart-item'><td class='item'></td><td class='qty'></td><td class='price'></td><td class='actions'></td></tr>");
$('.ui-cart-remove').live('click',function(e){
	e.preventDefault();	
	deleteCartItem($(this).closest('tr.cart-item').data('cart-item').New_Lrmscartitemid);
});

$('.ui-cart-edit').live('click',function(e){
	e.preventDefault();
	populateCart(true);
});

$('.ui-cart-save').live('click',function(e){
	
});

function populateCart(editable) {
    editable = true;
    var itemCount = 0,
    	outer = $("#cartBar thead, #cartBar tfoot"),
    	itemList = $("#cartBar .item-list"),
    	subtotal = $("#cartBar .subtotal");
    
    itemList.html('');
	
	if(cart.ItemList != null && cart.ItemList != ''){
	    $(cart.ItemList.LrmsNew_Lrmscartitem).each(function (i, cartItem) {
	        var cartItemRow = itemTpl.clone(false),
	        	item = cartItemRow.find('.item'),
	        	qty = cartItemRow.find('.qty'),
	        	price = cartItemRow.find('.price');
	
			cartItemRow.data('cart-item',cartItem);
			item.html(cartItem.New_Productid.Name);
	        if (!isNaN(cartItem.New_Donationrecurday) && cartItem.New_Donationrecurday > 0) {
				item.html(
					item.html()
					.concat(' - monthly<br />Donation recurs every ')
					.concat(cartItem.New_Donationrecurday)
					.concat(getSuffixForDay(cartItem.New_Donationrecurday))
					.concat(' day of the month.')
				); 
	        }
	        
	        if (parseInt(cartItem.New_Quantity) > 0)
	            itemCount += parseInt(cartItem.New_Quantity);
	        else
	            itemCount++;

	        if(editable){
				qty.html("<input type='text' value='".concat(cartItem.New_Quantity).concat("'>"));
			} else {
				qty.html(cartItem.New_Quantity);
			}
			
			price.html(cart.CurrencySymbol.concat(cleanPrice(cartItem.New_Amount)));			
			
			itemList.append(cartItemRow);
	    });
	    if(itemCount>0){
			itemList.find('tr:even').addClass('alt');
			outer.show();
			
			subtotal.html(cart.CurrencySymbol.concat(cleanPrice(cart.New_Subtotal)));
		}
	} else{
		outer.hide();
		itemList.append("<tr><td>Your cart is empty</td></tr>");		
		subtotal.html('');
	}
	
	if(editable){
		$('#cartBar td.actions').html("<a href='Remove' class='ui-cart-remove'>x</a>");
    	$('#cartBar th.actions').html('');
    	$("#cartBar .ui-cart-checkout").show();
    	$("#cartBar .ui-cart-save").hide();
    } else {
		$('#cartBar th.actions').html("<a href='Edit' class='ui-cart-edit'>edit</a>");
    	$('#cartBar td.actions').html('');
    	$("#cartBar .ui-cart-checkout").show();
    	$("#cartBar .ui-cart-save").hide();

    }
}

function getSuffixForDay(day) {
    var daySuffix = "th";

    if (day == "1")
        daySuffix = "st";
    if (day == "2")
        daySuffix = "nd";
    if (day == "3")
        daySuffix = "rd";
    if (day == "21")
        daySuffix = "st";
    if (day == "22")
        daySuffix = "nd";
    if (day == "23")
        daySuffix = "rd";
    if (day == "31")
        daySuffix = "st";

    return daySuffix;
}

function cleanPrice(price)
{
	var p = price + '';
	var decPlace = p.indexOf('.');
	if(decPlace != -1)
	{
		return p.substring(0, decPlace+3);
	}
	else
	{
		price = price + ".00";
	}
	return price;
}
var countryList = null;
function PopulateCountries(selectid, defaultCountry) {
    if (countryList == null) {
        $.get('/_layouts/LRMSCartAPI.asmx/GetCountryList', function (data) {
            countryList = $.xml2json(data);
            buildCountrySelect(selectid, defaultCountry);
        });
    } else {
        buildCountrySelect(selectid, defaultCountry);
    }
}
function buildCountrySelect(selectid, defaultCountry) {
    $("#" + selectid + " option").remove();
    $(countryList.CartCountry).each(function (idx, item) {
        if (item.Name == defaultCountry) {
            $("#" + selectid).append("<option selected value='" + item.Name + "'>" + item.Name + "</option>");
        } else {
            $("#" + selectid).append("<option value='" + item.Name + "'>" + item.Name + "</option>");
        }
    });
}

$(function(){
	$(".cartBar .ui-cart-checkout").click(function(e){
	    e.preventDefault();
    	
        var trigger = $(this);
    	if(trigger.is('.disabled')) return;
    	trigger.addClass('disabled');
    	var items =	$('#cartBar tbody .cart-item'),
    		processed = 0;
    	items.each(function(){
    		var item = $(this).data('cart-item');
    		$.post('/_layouts/LRMSCartAPI.asmx/UpdateCartItem',{
    			cartItemId:item.New_Lrmscartitemid,
    			qty:$(this).find('.qty input').val(),
    			price:item.New_Amount
    		},function(data){
    			if(++processed==items.length){ 
    				trigger.removeClass('disabled'); 
    				
    			}
    		});
    	});
        window.location.href = "/pages/Cart.aspx?mode=checkout";
	

		
	});
	refreshCart();
});


$('.ui-cart-view').live('click',function(e){
	e.preventDefault();
    showCartBar();
});

function showCartBar()
{
    $('#cartBar').reveal({animation: 'fade', animationspeed: 300, closeonbackgroundclick: true, dismissmodalclass: 'ui-modal-close'});
}

