/**
 * BillyReid.com - Cart JS.
 * 
 * @author Randy Little
 * @created 11/03/2011
 * @updated 11/19/2011
 * @version 1
 * @copyright Billy Reid, Inc.
 */
/**
 * Global Variable Declaration
 */
 var _addingToCart = false;
 /**
 * Global Function Declaration
 */

 if ( location.href.match('https') )
     _prot = "https";
 else
     _prot = "http";

function constructCartLine(id)
{
        this.beg = "<tr>";
        this.end = "</tr>";
        this.qty = "";
        this.desc = "";
        this.price = "";
        this.term = "<td data-id=\""+id+"\" class=\"border-left del\">x</td>";

        this.setQty = function(_qty) {
                this.qty = "<td class=\"border-right qty\">"+
                        _qty+"</td>";
        }
        this.setDesc = function(_desc) {
                this.desc = "<td class=\"border-right\">"+
                        _desc+"</td>";
        }
        this.setPrice = function(_price) {
                this.price = "<td class=\"total\">"+
                        _price+"</td>";
        }
        this.toString = function() {
                return this.beg +
                        this.qty +
                        this.desc +
                        this.price +
                        this.term +
                        this.end;
        }
}
/**
 * Cart Total Updater
 */
function updateCartTotal()
{
        /**
         * Create Total
         */
        _total = 0;
        jQuery(".total","#cart").each(function(){
                _current = jQuery(this).text().replace("$","");
                _current = _current.replace(",","");
                _total += parseFloat ( _current );
        });
        /**
         * Update Total
         */
        jQuery("#sub-total").text ("$" + number_format ( _total , 2 ));
        /**
         * Update Item Count.
         */
        updateCartItemCount();
}
/**
 * Cart Item Count Updater
 */
function updateCartItemCount()
{
        _total = 0;
        jQuery(".qty","#cart").each(function(){
                if ( parseInt ( jQuery(this).text() ) < 0 )
                {
                        _total++;
                } else {
                        _total+= parseInt ( jQuery(this).text() );
                }
        });
        jQuery(".cart-item-count").text(_total);
        /**
         * Bind Cart Actions
         */
        bindCart();
}
/**
 * Cart Binder
 */
function bindCart()
{
        /**
         * Unbind previously bound actions.
         */
        jQuery(".del","#cart").unbind();
        
        /**
         * Bind Deletion Link
         */
        jQuery(".del","#cart").click(function(){
                var _params = new constructRequest();
                    _params.add ( 'action', 'Cart' );
                    _params.add ( 'method', 'del' );
                    _params.add ( 'id', jQuery(this).attr('data-id') );
                    
                /**
                 * Partially delete table row.
                 */
                jQuery(this).parent("tr").css({
                        "opacity":"0.25",
                        "filter":"alpha(opacity=25)"
                });
                jQuery(this).unbind();
                
                /**
                 * Make jSON Request.
                 */
                delFromCart ( _params.toString() , this );
        });
}
function openCart()
{
    if ( jQuery(".drop-down").length )
        jQuery(".drop-down").slideUp(300);
    jQuery("#cart").stop().animate({"top":"32px"},750,"easeOutQuart");
}
function closeCart()
{
    if ( jQuery(".drop-down").length )
        jQuery(".drop-down").slideUp(300);
    jQuery("#cart").stop().animate({"top":((jQuery("#cart").height()*-1)
        -10)+"px"},500, "swing");
}
/**
 * Dollar Processor
 */
function number_format ( data , decimal )
{
        var _complex = data.toString().split(".");

        if ( _complex.length > 1 )
        {
        if ( _complex[1].length() > 1 )
                return _complex[0] + "." + _complex[1].substring(0,2);
        else if ( _complex[1].length() = 1 )
                return _complex[0] + "." + _complex[1] + "0";
        else
                return _complex[0] + ".00";
        } else {
                return _complex[0] + ".00";
        }

}
function putItemInCart(id)
{
        /**
         * Prepare cart item.
         */
        cartLine = new constructCartLine(id);
                cartLine.setQty ( jQuery("#product-qty").val() );
                cartLine.setDesc ( jQuery("#product-title").text() );
		
		if ( jQuery("#product-price-sale").html() )
                cartLine.setPrice ( jQuery("#product-price-sale").text() );
		else
				cartLine.setPrice ( jQuery("#product-price").text() );

        /**
         * Put item in cart.
         */
        jQuery(cartLine.toString())
                .appendTo("tbody[data-name=content]","#cart")

        /**
         * Update Cart Totals.
         */
        updateCartTotal();
}
function delItemInCart(item)
{
        /**
         * Remove cart item.
         */
        jQuery(item).parent("tr").remove();
        /**
         * Update Cart Totals.
         */
        updateCartTotal();
}
function addToCartMessage(params)
{
        switch ( params )
        {
                case 'working':
                        _addingToCart = true;
                        jQuery("#add-to-cart").css("background",
                        "url('http://www.billyreid.com/store/media/images/add-to-cart-working.png')");
                        break;
                case 'success':
                        _addingToCart = true;
                        jQuery("#add-to-cart").css("background",
                        "url('http://www.billyreid.com/store/media/images/add-to-cart-success.png')");
                        break;
                case 'oos':
                        _addingToCart = true;
                        jQuery("#add-to-cart").css("background",
                        "url('http://www.billyreid.com/store/media/images/add-to-cart-out-of-stock.png')");
                        break;
                default:
                        _addingToCart = false;
                        jQuery("#add-to-cart").css("background",
                        "url('http://www.billyreid.com/store/media/images/add-to-cart.png')");
                        break;
        }
}
/**
 * Add to cart function.
 */
function addToCart(params, id)
{
        if ( !_addingToCart )
        {

                addToCartMessage('working');

                //jQuery("#cart-link").click();

                setTimeout(function(){

                        jQuery.getJSON ( _prot + "://www.billyreid.com/store/Relay.php", params,
                                function(data,textStatus)
                                {
                                        if ( textStatus == 'error' )
                                        {
                                                addToCartMessage('oos');
                                                setTimeout(function(){
                                                        //jQuery("#lower","#cart").click();
                                                        addToCartMessage();
                                                },1000);
                                                return;
                                        }
                                        if ( data.result == "error" )
                                        {
                                                addToCartMessage('oos');
                                                setTimeout(function(){
                                                        //jQuery("#lower","#cart").click();
                                                        addToCartMessage();
                                                },1000);
                                                return;
                                        }
                                        addToCartMessage('success');
                                        putItemInCart(id);
                                        jQuery("#cart-link").click();
                                        setTimeout(function(){
                                                addToCartMessage();
                                        },1000);
                                        return;
                                }
                        );

                },1000);

        }
}
/**
 * Delete from cart function.
 */
function delFromCart(params,item)
{
        jQuery.getJSON ( _prot + "://www.billyreid.com/store/Relay.php", params,
                function(data,textStatus)
                {
                        if ( textStatus == 'error' )
                        {
                                jQuery(item).parent("tr").css({
                                        "opacity":"1",
                                        "filter":"alpha(opacity=100)"
                                });
                                return;
                        }
                        
                        if ( data.result == "error" )
                        {
                                jQuery(item).parent("tr").css({
                                        "opacity":"1",
                                        "filter":"alpha(opacity=100)"
                                });
                                return;
                        }
                        
                        delItemInCart(item);
                        return;
                }
        );
}
/**
 * Bindings.
 */
jQuery(function(){
        /**
         * Cart Initializer
         */
        jQuery("#cart").css({
                "top":((jQuery("#cart").height()*-1)-10)+"px",
                "display":"block"
        });
        /**
         * Cart Closer
         */
        jQuery("#lower","#cart").click(function(){
            closeCart();
        });
        /*jQuery("#cart").hoverIntent({over: function(){},
                timeout:1000,
                out:function(){
                        jQuery("#cart").stop().animate({"top":
                                        ((jQuery("#cart").height()*-1)-10)+"px"}
                                        ,500, "swing");
                }
        });*/
        jQuery("#cart").mouseleave(function(){
                jQuery("#lower","#cart").click();
        });
        /**
         * Cart Opener
         */
        jQuery("#cart-link").click(function(e){
           openCart();
           e.preventDefault();
        });
        jQuery("#cart-link").hoverIntent({over: function(){
                openCart();
                },
                timeout:500,
                out: function(){}
        });
        /**
         * Cart Click Off
         */
        jQuery("#page").click(function(){
            if ( jQuery("#add-to-cart").length )
            {
                if
                (
                        /**
                         * Verifying that user is not clicking the add
                         * to cart button which overrides this click.
                         */
                        _mouseX > jQuery("#add-to-cart").offset().left &&
                        _mouseX < (jQuery("#add-to-cart").offset().left +
                                jQuery("#add-to-cart").width()) &&
                        _mouseY > jQuery("#add-to-cart").offset().top &&
                        _mouseY < (jQuery("#add-to-cart").offset().top +
                                jQuery("#add-to-cart").height())
                ){
                        /**
                         * Do Nothing.
                         */
                } else {
                        closeCart();
                }
            }
        });
        /**
         * Update Cart Total
         */
        updateCartTotal();
        /**
         * Fix Checkout and Closer PNG's
         */
        if ( location.href.match("https") )
        {
                jQuery("#checkout","#cart").css(
                        "background-image","url('https://www.billyreid.com/store/media/images/checkout.png')"
                );
                jQuery("#lower","#cart").css(
                        "background-image","url('https://www.billyreid.com/store/media/images/closer.png')"
                );
        } else {
                jQuery("#checkout","#cart").css(
                        "background-image","url('http://www.billyreid.com/store/media/images/checkout.png')"
                );
                jQuery("#lower","#cart").css(
                        "background-image","url('http://www.billyreid.com/store/media/images/closer.png')"
                );                
        }
});
