//********************
//cookie functions
//******************


function cartIsEmpty(){
  var nvc = readCookie('nvc');
  if(nvc) {
    var nvc_array = nvc.split('&');
    var cart_index = cartCookieIndex(nvc_array);
    if(cart_index) {
      return false;
    }
  }
  return true;
}


// *******************
// REMOVE A PRODUCT FROM THE CART
function removeCartCookie(product_id) {
  //remove product from cart cookie
  var nvc = readCookie('nvc');
  if(nvc) {
    var nvc_array = nvc.split('&');
    var cart_index = cartCookieIndex(nvc_array);
    if(cart_index) {
      var current_cart = nvc_array[cart_index];
      var cart_list = current_cart.split(',');
      var index_in_cart = cartProductIndex(cart_list, product_id);                      
      if(index_in_cart) {
        //remove the product from the list
        cart_list.splice(index_in_cart-1, 1);
        //set the new cookie
        nvc_array[cart_index] = cart_list.join(',');
        if(!cart_list.length) {
          //if there are no products, we should remove the cart_products label and value from the cookie                    
          nvc_array.splice(cart_index-1,2);
        } else {
          //if there are products, let's insert them in the right place                    
          nvc_array[cart_index] = cart_list.join(',');
        }
        createCookie('nvc', nvc_array.join('&'), 365);
      }
    }
  }
}

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    //TODO remove the arttoday domain when we go to production
    //the server is writing cookies to .arttoday.com, but the js is writing them to animfactory.arttoday.com
    //so I'm using this as a workaround
    document.cookie = name+"="+value+expires+"; path=/; domain=.arttoday.com;";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

//find the index of 'cart_products' section of the cookie
function cartCookieIndex(nvc_array) {
    var cart_index = 0;
    for(var k=0; k<nvc_array.length; k++) {
        //even indices are the cookie sub labels
        if(!(k % 2)) {
            if(nvc_array[k] == 'cart_products') {
                cart_index = k + 1;
                break;
            }
        }                   
    }
    return cart_index;
}

//find the index of a given product in the cart cookie
function cartProductIndex(cart_list, product_id) {
    var cart_product_quantity;
    for(var i=1;i<cart_list.length+1;i++) {
        cart_product_quantity = cart_list[i-1].split('.');
        if(cart_product_quantity[0] == product_id)
            return i;
    }
    return 0;
}

//find the quantity of a product in the cookie
function quantityInCart(product_qty) {
    var cart_product_quantity;
    cart_product_quantity = product_qty.split('.');
    cart_product_quantity[1] = cart_product_quantity[1] ? cart_product_quantity[1] : 1;
    return cart_product_quantity[1];
}

//add product to cart cookie
function addCartCookie(product_id, quantity) {
    quantity = quantity ? quantity : 1;
    var nvc = readCookie('nvc');
    var product_qty = product_id;
    if(quantity > 1)
        product_qty += '.' + quantity;
    if(nvc) {
        //if there is a cookie...
        var nvc_array = nvc.split('&');
        var cart_index = cartCookieIndex(nvc_array);
        if(cart_index) {
            var current_cart = nvc_array[cart_index];
            var cart_list = current_cart.split(',');
            var index_in_cart = cartProductIndex(cart_list, product_id);
            if(index_in_cart) {
                //the product is in the cart ...
                var quantity_in_cart = quantityInCart(cart_list[index_in_cart-1]);
                if(quantity_in_cart != quantity) {
                    //we need to update the quantity                    
                    cart_list[index_in_cart-1] = product_qty;
                    nvc_array[cart_index] = cart_list.join(',');
                    createCookie('nvc', nvc_array.join('&'), 365);
                }
            } else {
                //product is not in the cart - add it
                cart_list.push(product_qty);
                nvc_array[cart_index] = cart_list.join(',');
                createCookie('nvc', nvc_array.join('&'), 365);
            }
        } else {
            //no 'cart_products' in cookie - add it
            nvc_array.push("cart_products");
            nvc_array.push(product_qty);
            createCookie('nvc', nvc_array.join('&'), 365);
        }
    } else {
        //set a brand new cookie
        createCookie('nvc', 'cart_products&' + product_qty, 365);     
    }
}

//check to see if a specific product is in the cart
function productInCart(prodpair) {
    var nvc = readCookie('nvc');
    if(nvc) {
        var nvc_array = nvc.split('&');
        var cart_index = cartCookieIndex(nvc_array);
        if(cart_index) {
            var current_cart = nvc_array[cart_index];
            var cart_list = current_cart.split(',');
            var cart_product_quantity;
            for(var i=0;i<cart_list.length;i++) {
                cart_product_quantity = cart_list[i].split('.');
                if(cart_product_quantity[0] == prodpair) {
                    return true;
                }
            }
        }
    }
    return false;
}

//change message when product is added to cart
function inCartMessage(divElem, newMessage, class_name) {
    divElem.innerHTML = "<div class=\"" + class_name + "\">" + newMessage + "</div>";
}

function getMyObject(o){
    if (document.getElementById)
        return document.getElementById(o);
    else if (document.all)
        return document.all.o;
}

function refreshCartWidget() {
    $.ajax({
        url: '/checkout/box_xml.mi',
        type: 'GET',
        data: "",
        dataType: 'xml',
        timeout: 10000,
//        error: function(XMLHttpRequest, textStatus, errorThrown){
//            alert('Error loading XML document');
//        },
        success: function(xml){
            $(xml).find('cart').each(function(){
                var item_count = $(this).find("item_count").text()
                var subtotal = $(this).find("subtotal").text()
                var your_loc = $(this).find("your_loc").text()
                var shopping_loc = $(this).find("shopping_loc").text()
                var cart_loc = $(this).find("cart_loc").text()
                var items_loc = $(this).find("items_loc").text()
                var total_loc = $(this).find("total_loc").text()
                var view_loc = $(this).find("view_loc").text()
                var checkout_loc = $(this).find("checkout_loc").text()
                var add_loc = $(this).find("add_loc").text()
                var remove_loc = $(this).find("remove_loc").text()
                var empty_cart_loc = $(this).find("empty_cart_loc").text()
                var secure_server = $(this).find("secure_server").text()
                var lang = $(this).find("lang").text()
                var string = "<table cellpadding=\"2\" cellspacing=\"0\" width=\"100%\">";
                string += "<tr>";
                string += "<td nowrap style=\"border-top: 4px solid; border-left: 1px solid; border-bottom: 1px solid; border-color: #fac567;\" valign=\"top\" bgcolor=\"#fce9cb\" width=\"100%\">";
                string += "<b class=\"nav\"><font color=\"#AD4431\">" + your_loc + " " + shopping_loc + " " + cart_loc + "<br></font></b>";
                string += "</td>";
                string += "<td style=\"border-top: 4px solid; border-bottom: 1px solid; border-right: 1px solid; border-color: #fac567; valign=\"top width=\"40\" align=\"right\" bgcolor=\"#fce9cb\"><img src=\"/images/ecom/shopping_cart.gif\" width=\"30\" height=\"33\" border=\"0\"></td>";
                string += "</tr>";
                if(item_count) {
                    string += "<tr>";
                    string += "<td style=\"border-bottom: 1px solid; border-right: 1px solid; border-left: 1px solid; border-color: #fac567;\" colspan=\"2\" align=\"right\">";
                    string += your_loc + " " + shopping_loc + " " + cart_loc + "<br><font color=\"black\">" + items_loc + ":<b>" + item_count + "</b> " + total_loc + ": <b>" + subtotal + "</b></a></font>";
                    string += "<p><b class=\"nav\"><a href=\"" + secure_server + "/" + lang + "/join\">" + view_loc + "</a> | <a href=\"" + secure_server + "/" + lang + "/join\">" + add_loc + "/" + remove_loc + "</a></b><br>";
                    string += "<b class=\"nav\"><a href=\"" + secure_server + "/" + lang + "/join\">" + checkout_loc + "<img src=\"/images/pagewrap/arrow_next.gif\" border=\"0\" align=\"absmiddle\"></a></b></p>";
                    string += "</td>";
                    string += "</tr>";
                } else {
                    string += "<tr>";
                    string += "<td style=\"border-bottom: 1px solid; border-right: 1px solid; border-left: 1px solid; border-color: #fac567;\" colspan=\"2\" align=\"right\">";
                    string += empty_cart_loc;
                    string += "</td>";
                    string += "</tr>";
                }
                string += "</table>";
                getMyObject("shopping_cart_widget").innerHTML = string;
            });
        }
        
    });
}
