/*- STATIC GLOBALS
----------------------------------------------------------------------*/
var VIEWABLE_WIDTH = 960;
var iOS = false

if (navigator.userAgent.match(/like Mac OS X/i)) {
    iOS = true;
}

/*- MAIN APPLICATION
----------------------------------------------------------------------*/
var ic = (function(){
    
    var init = function(){
        //cartManager.init();
        mainNavigation.init();
        footer.init();
    };
    
    /*- Cart Manager
    ----------------------------------------------------------------------*/
    var cartManager = (function(){
        var _cartCookie;
        var _cartBadge;
        
        var init = function(){
            _cartBadge = $("#navigation #cart-badge");
            fetchProducts(function(result) {
                updateTotal(result.total);
                updateBadge(result.count);
            });
        };
        
        function updateTotal(total){
			if(total != undefined){
            	$('#total h4').html("$" + total);
			}
        };
        
        function updateBadge(count){
            if(count > 0){
                var i = 'item';
                if(count > 1){i+='s';}
                _cartBadge.find("h5").html(count + " "+ i +" in cart");
                _cartBadge.fadeIn(500);
            }else{
                _cartBadge.fadeOut(200);
            }
        };
        
        var get = function(method, data, success) {
            $.ajax({
                type: 'GET',
                url: 'http://invisiblecreature.dev.interfacecms.com/extensions/' + method,
                dataType: 'json',
                data: data,
                success: function(result) {
                    if (success) success(result);
                    if (result.total) updateTotal(result.total);
                }
            });            
        };

        var server = function(method, data, success) {
            $.ajax({
                type: 'POST',
                url: 'http://invisiblecreature.dev.interfacecms.com/extensions/'+ method,
                dataType: 'json',
                data: data,
                success: function(result) {
                    if (success) success(result);
					
					if(result.error) return;
                    updateTotal(result.total);
                    updateBadge(result.count);
                }
            });
        };

        var fetchProducts = function(success) {
            get('fetch_products', null, success);
        };
        
        var checkShipping = function(address, success) {
            get('check_shipping', address, success);
        };
        
        var addToCart = function(item, success) {
            server('add_to_cart', item, success);
        };
        
        var updateQuantity = function(item, quantity, success) {
            item.quantity = quantity;
            server('update_quantity', item, success);
        };

        var removeFromCart = function(item, success) {
            server('remove_from_cart', item, success);
        };
        
        var clearCart = function(success) {
            server('clear_cart', null, success);
        };
        
        var applyCode = function(data, success) {
            server('apply_code', data, success);
        };

		var fetchCodeApplied = function(success){
			get('fetch_code_applied', null, success);
		}
		
		var checkCodeBalance = function(data, success){
		    get('giftcard_balance', data, success);
		}

        return {
            init: init,
            fetchProducts: fetchProducts,
			fetchCodeApplied: fetchCodeApplied,
			checkCodeBalance: checkCodeBalance,
            checkShipping: checkShipping,
            addToCart: addToCart,
            updateQuantity: updateQuantity,
            removeFromCart: removeFromCart,
            applyCode: applyCode,
            clearCart: clearCart
        };
        
    })();    

    /*- Main Navigation Methods
    ----------------------------------------------------------------------*/
    var mainNavigation = (function(){
        
        var OVER_Y = "-15px";
        
        var _prevBtn;
        var _currBtn;
        
        var _navArray = ["home", "work", "about", "shop", "blog", "faq", "contact"];
        var _navBtns = [];
        
        var init = function(){
            $("#navigation ul li").each(function(index){
                var li = $(this);
                var bgPos = li.css("backgroundPosition");
                if(bgPos == undefined || bgPos == null){
                    var x = li.css("background-position-x");
                    var y = li.css("background-position-y");
                }else{
                    bgPos = bgPos.split(" ");
                    var x = bgPos[0];
                    var y = bgPos[1];
                }
                
            
                li.branch = _navArray[index];
                    
                var handleOver = function(){
                    li.stop().animate({backgroundPosition:(x + " " + OVER_Y)}, 150);
                };
                
                var handleOut = function(){
                    li.stop().animate({backgroundPosition:(x + " " + y)}, 150);
                };
                
                li.enable = function(){
                    handleOut();
                    li.hover(handleOver, handleOut);
                    this.css({borderBottom: "none"});
                };
                
                li.disable = function(){
                    this.unbind();
                    handleOver();
                    this.css({borderBottom: "2px solid #fff", paddingBottom: "2px"});
                };
                
                li.hover(handleOver, handleOut);
                _navBtns.push(li);
                
            });
            
        };
        
        var changeNav = function(){
            
            var btn = _navBtns[4];
            btn.disable();
                
        };
        
        return{
            init: init,
            changeNav: changeNav
        };
        
    })();
    
    /*- FOOTER Methods
       ----------------------------------------------------------------------*/
    var footer = (function(){
        
        var init = function(){
            $("#footer a.back-to-top").click(function(e){
                e.preventDefault();
                $('html, body').animate({ scrollTop: 0 }, 500, 'easeInOutExpo');
            });
        };
        
        return {init:init};
    })();
    
 
    return {
        mainNavigation: mainNavigation,
        footer: footer,
        init: init
    };

})();

/*- INITIALIZATION
----------------------------------------------------------------------*/
$(document).ready(function(){
    ic.init();
    ic.mainNavigation.changeNav();
});

//IE FIX for indexOf
if (!Array.prototype.indexOf){
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;
    
    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}
