cart = null;
//represents the Cart on the page
function Cart()
{
    var countryId = 1;
    var currencySymbol = "€";
    var comics = new Array();

    this.hasMoreThan10Comics = function()
    {
        var amount = 0;
        for (var i = 0; i < comics.length; i++)
        {
          amount += new Number(comics[i].quantity);
        }
        return amount >= 10;
    }

    this.setCountryId = function(id)
    {
      countryId = id;
    }

    this.setCurrencySymbol = function(symbol)
    {
      currencySymbol = symbol;
    }

    this.getCountryId = function()
    {
      return countryId;
    }

    this.getCurrencySymbol = function()
    {
      return currencySymbol;
    }

    this.getComics = function()
    {
      return comics;
    }

    //calculates the total price for all the Comics
	this.getTotalPrice = function()
	{
    var ret = new Number();
    for (var i = 0; i < comics.length; i++)
    {
      ret += comics[i].totalPrice();
    }
    return ret;
	}

	this.contains = function(id)
	{
    for (var i = 0; i < comics.length; i++)
    {
  	  if (id == comics[i].id)
  	  {
  	  	return true;
  	  }
    }
    return false;
	}
	
	
	this.getLength = function()
	{
		return comics.length;
	}
	
	
	this.addComic = function (comic)
	{
		comics.push(comic)
	}
	
	
	this.removeComic = function (comic)
	{
		comics.remove(comic)
	}
	
	
	this.removeItem = function (id)
	{
    for (var i = 0; i < comics.length; i++)
    {
  	  if (id == comics[i].id)
  	  {
  	  	this.removeComic(comics[i]);
  	  	return;
  	  }
    }
	}


  this.updateQuantityOfItem = function (id, quantity)
  {
    for (var i = 0; i < comics.length; i++)
    {
  	  if (id == comics[i].id)
  	  {
  	  	comics[i].quantity = quantity;
  	  }
    }
  }


  this.updatePrices = function (price)
  {
    for (var i = 0; i < comics.length; i++)
    {
  	  comics[i].price = price;
    }
  }
  
  
  this.toJSON = function()
  {
    var ret = '{"countryId":"' + countryId + '", "currencySymbol":"' + currencySymbol + '","comics":[';
    for (var i = 0; i < comics.length; i++)
    {
      if (0 != i)
      {
        ret += ",";
      }
      ret += comics[i].toJSON();
    }
    return ret += "]}";
  }
	
}


    //used to construct the json string that is sent to the server
  


Cart.prototype.constructFromJSON = function(json)
{
   json = json.replace(/\\\"/g, '"');
   var cart = json.parseJSON();

   var comicsArr = cart.comics;

   for(var i = 0; i < comicsArr.length; i++)
   {
     var comic = comicsArr[i];
     this.addComic(new Comic(comic.id, comic.comicName, new Number(comic.price), comic.quantity, comic.imgPath));
   }
}

//creates the cart html that is placed on the page.
function cartToHTML(cart)
{
  var comics = cart.getComics();
  var ret = '<div class=\"cartTitle\">Cart</div><div class="cartItemList">';
  for (var i = 0; i < comics.length; i++)
  {
    var comic = comics[i];
    ret += "<div class=\"cartEntry\"><div>" + comic.comicName + "</div><div><img src=\"" + comic.imgPath + "\" /></div>"
		+ "<div><div class=\"cartSubLeft\">Individual price</div><div class=\"cartSubRight\">" + cart.getCurrencySymbol() + floatToCurrency(comic.price) + "</div></div>"
		+	"<div><div class=\"cartSubLeft\">Total ordered</div><div class=\"cartSubRight\">" + comic.quantity + "</div></div>"
		+ "<div><div class=\"cartSubLeft\">Total price</div><div class=\"cartSubRight\">" + cart.getCurrencySymbol() + floatToCurrency(comic.totalPrice()) + "</div></div>"
		+ "<div><div class=\"cartSubLeft\">Update quantity</div><div class=\"cartSubRight\"><select onchange=\"updateQuantity(" + comic.id + ", this.value)\">" + comic.getDropDownOptions() + "</select></div></div>"
		+ "<div style=\"clear:both\">&nbsp;</div><div class=\"cartRemoveButton\"><input name=\"cartRemoveButton\" onclick=\"removeItem(" + comic.id + ")\" border=\"0\" type=\"image\" src=\"\"/></div></div>";
  }

  if (cart.hasMoreThan10Comics())
  {
     return ret += "</div><hr /><div class=\"cartTotalPrice\">Sub Total : " + cart.getCurrencySymbol() + floatToCurrency(cart.getTotalPrice()) + "</div><div class=\"cartTotalPrice\">Discount : " + cart.getCurrencySymbol() + floatToCurrency((cart.getTotalPrice()*0.1)) + "</div><div class=\"cartTotalPrice\">Total : " + cart.getCurrencySymbol() + floatToCurrency(cart.getTotalPrice()*0.9) + "</div><div><input onclick=\"checkout()\"  id=\"cartCheckoutButton\"  border=\"0\" type=\"image\" ></div><div style=\"height:3px;\">&nbsp;</div>";
  }
  else
  {
     return ret += "</div><hr /><br /><div class=\"cartTotalPrice\">Total : " + cart.getCurrencySymbol() + floatToCurrency(cart.getTotalPrice()) + "</div><div><input onclick=\"checkout()\" id=\"cartCheckoutButton\"  border=\"0\" type=\"image\" src=\"/images/buttons/go_to_checkout.png\"/></div><div style=\"height:12px;\">&nbsp;</div>";
  }
}


function applyCartButtonEvents()
{
    var checkout = document.getElementById("cartCheckoutButton");
    checkout.src         = "/images/buttons/go_to_checkout.png";
    checkout.onmouseover = function(){this.src = "/images/buttons/go_to_checkout_hover.png"};
    checkout.onmouseout  = function(){this.src = "/images/buttons/go_to_checkout.png"};
    
    var remove = document.getElementsByName("cartRemoveButton");
    for (var i = 0; i < remove.length; i++)
    {
        remove[i].src         = "/images/buttons/remove.png";
        remove[i].onmouseover = function(){this.src = "/images/buttons/remove_hover.png"};
        remove[i].onmouseout  = function(){this.src = "/images/buttons/remove.png"};
    }

    Rounded("div#cartContainer", "#FFFFFF", "#B3DFCC");
}


function updateQuantity(id, num)
{
  cart.updateQuantityOfItem(id, num);
  showCart();
  persistCart(cart);
}


//removes item from the cart
function removeItem(id)
{
  if (!confirm("Are you sure that you want to remove this item from your shopping cart?") && true)
  {
    return;
  }

  cart.removeItem(id);
  var cartcontainer = document.getElementById("cartContainer");
	
  cartcontainer.innerHTML = cartToHTML(cart);

  applyCartButtonEvents();

  persistCart(cart);
}

//represents a Book item that can be stored on the cart
function Comic(id, comicName, price, quantity, imgPath)
{
	this.comicName = comicName;
	this.id        = id;
	this.price    = price;
	this.quantity = quantity;
	this.imgPath  = imgPath;


  this.toJSON = function()
  {
    return '{"id":"' + this.id + '", "comicName":"' + this.comicName + '", "price":"' + this.price + '", "quantity":"' + this.quantity + '", "imgPath":"' + this.imgPath + '"}';
  }
	
	this.equals = function(obj)
	{
		if (obj instanceof Comic && obj.id == this.id && obj.ComicName == this.ComicName  && obj.price == this.price && obj.quantity == this.quantity && obj.imgPath == this.imgPath)
		{
			return true;
		}
		return false;
	}
	
	this.totalPrice = function()
	{
		return this.price * this.quantity;
	}
	
	
	this.getDropDownOptions = function()
	{
		var dropLength = (this.quantity > 30) ? this.quantity : 30;
		var ret = "";
		for (var i = 0; i < dropLength; i++)
		{
			var selected = ((i + 1) == this.quantity) ? "selected=\"selected\"" : "" ;
			ret += "<option " + selected + " value=\"" + (i + 1) + "\">" + (i + 1) + "</option>";
		}
		return ret;
	}
}


Array.prototype.remove = function (obj)
{
	for (var i = 0; i < this.length; i++)
	{
		if (obj.equals(this[i]))
		{
			this.splice(i, 1);
			return;
		}
	}
}


function addToCart(id, quantity, comicName, price, imgPath)
{
  
  if (!quantity)
  {
    return alert("That item is out of stock");
  }
  
  //ajax request for other details
  if (cart.contains(id))
  {
  	return alert("You already have this item in your cart.");
  }

  var item = new Comic(id, comicName, price, quantity, imgPath);
  
  cart.addComic(item);
  
  persistCart(cart);

  var cartcontainer = document.getElementById("cartContainer");
  cartcontainer.innerHTML = cartToHTML(cart);

  applyCartButtonEvents();
}


function checkout()
{
  document.location = "shipping.php";
}


//writes the cart to the page
function showCart()
{
  var cartcontainer = document.getElementById("cartContainer");
  cartcontainer.innerHTML = cartToHTML(cart);

  applyCartButtonEvents();
}


//lists the items in the cart as JSON
function getItemsInCart()
{
	var successFunction = function(jsonString)
	{
    cart = new Cart();

    if ("empty" == jsonString)
    {
      document.getElementById("cartContainer").innerHTML = "Cart";
      return;
    }
    //fills the cart with the items using the json string
    cart.constructFromJSON(jsonString);

    showCart();
	}

  new AjaxRequest("", "GET", "", successFunction);
}


function floatToCurrency(num)
{
  var numString = new String(num.toFixed(2));

  dotPos = numString.indexOf(".");

  if (-1 == dotPos)
  {
  	numString += ".00";
  }
  else if (numString.length - 2 == dotPos)
  {
  	numString += "0";
  }

  return numString;
}


function persistCart(cart)
{
    $.ajax({
       type: "GET",
       url: "/ajax/CartControls.php",
       data: "command=PersistCart&cartString=" + cart.toJSON(),
       success: function(jsonString)
       {
         if ("true" != jsonString)
         {
           return alert(jsonString);
         }
         return;
         }
     });
}

function addToCartButton(elem)
{
    var quantity = elem.parentNode.childNodes[1].value;
    var name     = elem.parentNode.childNodes[2].value;
    var prices = document.getElementsByName("price");
    var country  = "";
    for (var i = 0; i < prices.length; i++)
    {
        if (prices[i].checked)
        {
            country = prices[i].value;
        }
    }
    var price    = new Number(country.parseJSON().price);
    var imageurl = elem.parentNode.childNodes[3].value;
    addToCart(elem.name, quantity, name, price, imageurl);
}

window.onload = function()
 {
    Rounded("div#prices", "#FFFFFF", "#89D1F0");
    Rounded("div.comicContainer","#FFFFFF","#E5F5FC");

    var prices = document.getElementsByName("price");

    for (var i = 0; i < prices.length; i++)
    {
        prices[i].onclick = function()
        {
                var prices2 = document.getElementsByName("price");

                for (var i = 0; i < prices2.length; i++)
                {
                    if (prices2[i].checked)
                    {
                        var price = prices2[i];
                        var country = price.value.parseJSON();
                        cart.updatePrices(new Number(country.price));
                        cart.setCurrencySymbol(country.symbol);
                        cart.setCountryId(country.id);
                        showCart();
                        persistCart(cart);
                    }
                }
        }
    }
    

    $.ajax({
       type: "GET", 
       url: "/ajax/CartControls.php",
       data: "command=ListAllCartItems",
       success: function(jsonString)
       {
          cart = new Cart();

          if ("empty" == jsonString)
          {
            document.getElementById("cartContainer").innerHTML = "<div class=\"cartTitle\">Cart</div><div class=\"cartItemList\">&nbsp;</div><hr/><br /><div class=\"cartTotalPrice\">&nbsp;</div><div style=\"height:21px;\">&nbsp;</div><br />";
            Rounded("div#cartContainer", "#FFFFFF", "#B3DFCC");
            return;
          }
          cart.constructFromJSON(jsonString);

          showCart();
       }
     });
 }
