var mouse_is_inside = false;

$j(document).ready(function() {
	updateCartPopup();

	$j('.cart_popup').hover(function(){
        mouse_is_inside=true;
    }, function(){
        mouse_is_inside=false;
    });

	$j("body").click (function(e) {
		if ((e.target.className !== "cart_popup") && (!mouse_is_inside)) {
			hideCartPopup();
		}
	});

});

function displayCartPopup() {
	$j('.cart_popup').fadeIn();
}

function hideCartPopup() {
	$j('.cart_popup').fadeOut();
}

function toggleCartPopup() {
	$j('.cart_popup').toggle();
}

function updateCartPopup() {
	if ($j('#cart_popup_div').length == 0) {
		$j('body').prepend('<div class="cart_popup" id="cart_popup_div"></div>');
	}
	var ajax_url = (("https:" == document.location.protocol) ? "/acheckout/securecart/viewAjax?" + Math.floor(Math.random()*1001).toString() : "/checkout/cart/viewAjax?" + Math.floor(Math.random()*1001).toString());
	$j.get(ajax_url, function (html_contents) {
		var pos = $j('#cart-icon').offset();
		$j('.cart_popup').css({'left':(pos.left-143) + 'px','top':(pos.top+14) + 'px'});
		$j('.cart_popup').html(html_contents);
	});
}

function addUpdateCartPopup(html) {
	var pos = $j('#cart-icon').offset();
	$j('.cart_popup').css({'left':(pos.left-143) + 'px','top':(pos.top+14) + 'px'});
	$j('.cart_popup').html(html);
	displayCartPopup();
}

var Addtocart = Class.create();
Addtocart.prototype = {
    initialize: function(form, saveUrl){
        this.form = form;
        if ($(this.form)) {
            $(this.form).observe('submit', function(event){this.save();Event.stop(event);}.bind(this));
        }
        var ajax_url = (("https:" == document.location.protocol) ? "/acheckout/securecart/addAjax?" + saveUrl : "/checkout/cart/addAjax?" + saveUrl);
        this.saveUrl = ajax_url;
        this.validator = new Validation(this.form);
        this.onSave = this.nextStep.bindAsEventListener(this);
        this.onFailure = this.failure.bindAsEventListener(this);
        this.is_valid = false;
    },

    validate: function() {
		this.is_valid = this.validator.validate();
		return this.is_valid;
    },

    save: function(){

        if (this.validate()) {
			$j('#cart_add_button').hide();
			$j('#addtocart-please-wait').show();
            var request = new Ajax.Request(
                this.saveUrl,
                {
                    method:'post',
                    onSuccess: this.onSave,
                    onFailure: this.onFailure,
                    parameters: Form.serialize(this.form)
                }
            );
        }
    },

    nextStep: function(transport){
        if (transport && transport.responseText){
            try{
                response = eval('(' + transport.responseText + ')');
            }
            catch (e) {
                response = {};
            }
        }

        if (response.r=='failure') {
        	window.location = '/checkout/cart';
        } else {
	        addUpdateCartPopup(response.html);

	        if (response.count==1)
	        	item_text = '1 Item';
	        else
	        	item_text = response.count+" Items";

	        // save the cookie of cart items
	        var date = new Date();
			date.setTime(date.getTime() + (60 * 60 * 1000)); // 1 hour cookie
	        $j.cookie('ci', item_text, { path: '/', expires: date });

	        $j('#cart_items').html(item_text);

	        $j('#cart_add_button').show();
			$j('#addtocart-please-wait').hide();
        }

    },

    failure: function(transport){
		$j('#cart_add_button').show();
		$j('#addtocart-please-wait').hide();
    	alert("Error submitting add to cart request");
    }
}

function get_header_info() {

	var cart_items = $j.cookie('ci');
	var logged_in = $j.cookie('li');

	if (cart_items) {
		$j('#cart_items').text(cart_items);
	}

	if (logged_in) {
		if (logged_in == '1') {
			$j('#registernav').hide();
			$j('#accountnav').show();
		}
	}

	var ajax_url = (("https:" == document.location.protocol) ? "/acagogo/securecustomer/customerinfojson/?" + Math.floor(Math.random()*1001).toString() : "/acagogo/customer/customerinfojson/?" + Math.floor(Math.random()*1001).toString());
	$j.getJSON(ajax_url,
		function(data) {
			items = parseFloat(data.cart_items).toFixed(0);
			if (items==1)
				item_text = '1 Item';
			else
				item_text = parseFloat(data.cart_items).toFixed(0)+' Items';

			var date = new Date();
			date.setTime(date.getTime() + (60 * 60 * 1000)); // 1 hour cookie

			$j.cookie('ci', item_text, { path: '/', expires: date });

			$j('#cart_items').text(item_text);

			if (data.logged_in) {
				$j('#registernav').hide();
				$j('#accountnav').show();
				$j.cookie('li', '1', { path: '/', expires: date });
			} else {
				$j.cookie('li', '0', { path: '/', expires: date });
			}
		}
	);
}
