

function inCart(_root){

    this.root         = $(_root);
    this.opened = false;
    this.cookieName = "cart";
    this.render()
}

inCart.prototype.render = function(){

    var _this = this;
    var _timeout;
    
    _this.holder = $("<div>",{
        id:"incart_holder"
    });
    _this.plate = $("<div>",{
        id:"incart_plate"
    });
    _this.label = $("<div>",{
        id:"incart_label"
    });
    _this.tableHolder = $("<div>",{
        id:"incart_table_holder"
    });

    _this.holder.appendTo(_this.root );
    
    _this.plate.appendTo(_this.holder);
    _this.label.appendTo(_this.holder);

    _this.tableHolder.appendTo(_this.plate);


    
    _this.holder.bind("mouseout",function(){
        myMouseOut=function(){
            _this.toggleOpen(false);
        }
        _timeout = setTimeout("myMouseOut()", 1500);
    });
    _this.holder.bind("mouseover",function(){
        clearTimeout(_timeout);
    });
    
    _this.label.bind("click",function(){
        _this.toggleOpen();
    });

    _this.holder.css({
        left:-(_this.plate.width()+2)+"px"
    });

    this.updateCart();
}


inCart.prototype.changeQty= function(_ID,sum){

    var data = JSON.parse($.JSONcookie(this.cookieName));
    var len = data.items.length;
    for (var i = 0; i < len; i++) {
        _o = data.items[i];
        if(_o.id==_ID){
            _o.qty = Math.max(_o.qty+sum,0);
            break;
        }

    }
    this.saveCookie(data);
    this.updateCart();
    
}

inCart.prototype.updateCart = function(){


    var cookie = $.JSONcookie(this.cookieName);

    if(cookie==null){

    //this.saveCookie({})
    }else{

        var data = JSON.parse($.JSONcookie(this.cookieName));
    }
   
    var paypalItems = "";
    var paypalform  = "";
    var checkout    = "";

    var HTML = "<h2 dir='ltr'>Your Shopping Cart</h2>";
    if (data == null || data.items.length==0){
        HTML += "<div style='background-color:white;padding:20px;direction:ltr;'>The cart is empty</div>";
        
    }else{

        var len = data.items.length;
       

        HTML += "<table border=0 cellpadding=0 cellspacing=0 width='100%'>";
        HTML += "<tr>";
        HTML += "<th width='25'><label>&nbsp;</label></th>";
        HTML += "<th width='170'><label>product</label></th>";
        HTML += "<th width='75'><label>quantity</label></th>";
        HTML += "<th width='*'><label>price</label></th>";
        HTML += "</tr>";
        var _total =0;
       
        for (var i = 0; i < len; i++) {

            _plus = "<a href='javascript:void(0)' class='incart_qty_bt' id='plusQty' onclick='myCart.changeQty("+data.items[i].id+",1)'></a>";
            _minus = "<a href='javascript:void(0)' class='incart_qty_bt' id='minusQty' onclick='myCart.changeQty("+data.items[i].id+",-1)'></a>";
            _productTotal = data.items[i].price*data.items[i].qty;
            HTML += "<tr class='incart_productrow'>";
            HTML += "<td><a href='javascript:void(0)' onclick='myCart.removeFromCart("+data.items[i].id+")'><img src='/images/incart_del_bt.png' title='remove this item from the cart' alt='remove this item from the cart' border='0'></a></td>";
            HTML += "<td>"+data.items[i].link+"</td>";
            HTML += "<td>"+_minus+data.items[i].qty+_plus+"</td>";
            HTML += "<td>$"+_productTotal+"</td>";
            HTML += "</tr>";

            _total += _productTotal;

            var counter = i+1;
            paypalItems  += "<input type='hidden' name='item_name_"+counter+"'     value='"+data.items[i].link+"' readonly/>";
            paypalItems  += "<input type='hidden' name='amount_"+counter+"'        value='"+data.items[i].price+"' readonly/>";
            paypalItems  += "<input type='hidden' name='quantity_"+counter+"'       value='"+data.items[i].qty+"' readonly/>";
            paypalItems  += "<input type='hidden' name='item_name_"+counter+"'     value='"+data.items[i].title+"' readonly/>";
        }



        //alert("updated "+HTML);

        HTML += "<tr class='incart_totalrow'>";
        HTML += "<td>&nbsp;</td>";
        HTML += "<td>&nbsp;</td>";
        HTML += "<td><strong>Total</strong></td>";
        HTML += "<td><strong>$"+_total+"</strong></td>";
        HTML += "</tr>";


        paypalform += "";
        paypalform += "<form action='https://www.sandbox.paypal.com/cgi-bin/webscr' METHOD='GET' target='_blank'>";
        paypalform += "<input type='hidden' name='cmd'           value='_cart' readonly/>";
        paypalform += "<input type='hidden' name='upload' value='1'>";
        paypalform += "<input type='hidden' name='business'      value='mail@itaynoy.com' readonly/>";
        paypalform += "<input type='hidden' name='no_shipping'   value='0' readonly/>";
        paypalform += "<input type='hidden' name='return'        value='http://local.shirleylev.com/thanks.php' readonly/>";
        paypalform += "<input type='hidden' name='currency'      value='USD' readonly/>";
        paypalform += "<input type='hidden' name='lc'            value='US' readonly/>";
        paypalform += "<input type='hidden' name='bn'            value='PP-BuyNowBF' readonly/>";
        paypalform += "<input type='hidden' name='shipping_1'        value='24' readonly/>";
        paypalform += "<input type='submit' name='submit'      value='BUY NOW' readonly/>";
        paypalform += paypalItems;

        paypalform += "</form>";

        checkout = "<a href='/checkout/' id='incart_checkout'>Checkout</a>";
    }


    HTML += "</table>";
    //HTML += paypalform;
    HTML += checkout;
    
    
    this.tableHolder.html(HTML);
    $("tr th:first-child label").css({
        "border":"0"
    });

}


inCart.prototype.addToCart = function(ID,_price,_link,_title){


    //var data = cartCookie.load();
    // alert(ID+ "  : " +_title);
    var data = JSON.parse($.JSONcookie(this.cookieName));
    if (data==null){
        //alert("new cart")
        var data = {
            itemsN:0,
            name:"cart",
            items:[{
                id:ID,
                qty:1,
                price:_price,
                title:_title,
                link:_link
            }]
        };

    }else{

        //alert(JSON.stringify(data));
        var len = data.items.length;

        var _o;
        var added = false;
        //looping through array searching if ID already exists
        //alert("legnth " + len);
        for (var i = 0; i < len; i++) {

            _o = data.items[i];
            //alert(i + " : "+ID+" : "+_o.id);
            if(_o.id==ID){
                // if ID exists, we add one to quantity
                // alert("found one");
                _o.qty +=1;
                var added=true;
                break;
            }

        }
        if (added == false){
            _o = {
                id:ID,
                qty:1,
                price:_price,
                title:_title,
                link:_link
            };
            data.items.push(_o);

        }
    }

    data.itemsN += 1;
    //alert(data.itemsN);
    this.saveCookie(data);
    this.updateCart();
    this.toggleOpen(true);
}


inCart.prototype.removeFromCart = function(_ID){

    //alert("remove "+_ID);
    var data = JSON.parse($.JSONcookie(this.cookieName));
    var len = data.items.length;
    for (var i = 0; i < len; i++) {
        _o = data.items[i];
        if(_o.id==_ID){
            data.items.splice (i,1);
            break;
        }

    }
    this.saveCookie(data);
    this.updateCart();
}

inCart.prototype.saveCookie = function(_o){

    val = JSON.stringify(_o);
    eval('obj = val', window);
    $.JSONcookie(this.cookieName, obj, {
        path: '/'
    });

}

inCart.prototype.toggleOpen=function(_open){

    var _this = this;
    var opened = (_open!=undefined)?!_open:_this.opened;
    //alert(opened);
    if(opened){
        _this.opened = false;
        _this.holder.stop().animate({
            "left":-(_this.plate.width()+2)+"px"
        },400);
    }else{
        _this.opened = true;
        _this.holder.stop().animate({
            "left":"0px"
        },400);
    }
    
}



jQuery.JSONcookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


