/*
 * Adds an item, identified by its product code, 
 * to the shopping cart
 * itemCode - product code of the item to add.
 */
function executeCartRequest() {
  cartRequest('viewCart',null);
}

function executeAddCartRequest(licenseId,type) {
	  cartRequest('addToCart',licenseId,type);
	}

	function executeRemoveItemRequest(licenseId) {
	  cartRequest('removeItem',licenseId,null);
	}

	function executeClearCartRequest() {
	  cartRequest('clearCart',null,null);
	}

	function cartRequest(action,licenseId,type) {

	  // Obtain an XMLHttpRequest instance
	  var req = newXMLHttpRequest();
	  
	  //alert(licenseId + ' ' + type);

	  // Set the handler function to receive callback notifications
	  // from the request object
	  var handlerFunction = getReadyStateHandler(req, displayCartList);
	  req.onreadystatechange = handlerFunction;
	  
	  // Open an HTTP POST connection to the shopping cart servlet.
	  // Third parameter specifies request is asynchronous.
	  req.open("POST", "/web/cart.do", true);

	  // Specify that the body of the request contains form data
	  req.setRequestHeader("Content-Type", 
	                       "application/x-www-form-urlencoded");

	  // Send form encoded data stating that I want to add the 
	  // specified item to the cart.
	  if(licenseId != null && type != null)
		req.send("action="+action + "&licenseId="+licenseId + "&type="+type);
	  else if(licenseId != null && type == null)
	    req.send("action="+action + "&licenseId="+licenseId);
	  else
	    req.send("action="+action);
	    
	}

function displayCartList(responseXML) {
    // Get the root "categories" element from the document
    var root = responseXML.getElementsByTagName("order")[0];

    // Clear the HTML list used to display the cart contents
    setCartContents("");
    var buffer = "";

    // Loop over the items in the cart
    var itemsCount = root.getElementsByTagName("item-count")[0].firstChild.nodeValue;
    var itemsTotal = root.getElementsByTagName("total")[0].firstChild.nodeValue;
    buffer += "<div style='float: right;'><a href='javascript:cart();'><img src='/images/nav/ico-close.png' alt='close' title='close' align='right'></a></div><div style='clear:both;'></div><div style='float: left;'><img src='/images/nav/ico-cart.jpg' width='69' height='69'></div><p style='margin-top: 25px;'><span style='color: #da2128;'>Your cart contains <b>" + itemsCount + "</b> items (<b>" + itemsTotal + "</b>)</span></p><div style='clear: both;'></div>";
    
    //built cart
    verticalOffset = -260;
    slide_out_speed = 1000;
    slide_in_speed = 1000;
    if(itemsCount > 0) {
        buffer += "<div id='cartItemsPanel'><div class='close'></div><table cellpadding='5' cellspacing='0' border='0' width='100%'>";
        buffer += "<tr><td class='toplabel'>License</td><td class='toplabel'>Price</td><td class='toplabel'>Services</td><td class='toplabel'>Remove</td></tr>";
        for (var i = 0 ; i < itemsCount ; i++) {
            verticalOffset -= 50;
            slide_in_speed += 50;
            slide_out_speed += 50;
            var item = root.getElementsByTagName("items")[0].getElementsByTagName("order-item")[i];
            var licenseId = item.getElementsByTagName("id")[0].firstChild.nodeValue;
            var licenseName = item.getElementsByTagName("name")[0].firstChild.nodeValue;
            var licensePrice =item.getElementsByTagName("price")[0].firstChild.nodeValue;
            var serviceName = item.getElementsByTagName("services")[0].firstChild.nodeValue;
            buffer += "<tr><td valign='top' align='left'>" + licenseName + "</td>";
            buffer += "<td valign='top' align='center'>" + licensePrice + "</td><td valign='top' align='left'>" + serviceName + "</td>";
            //buffer += "<td valign='middle' align='center'><a href='javascript:removeLicense("+licenseId+");'><img style='margin-bottom: -10px;' src='/images/nav/ico-trash.png' alt='Remove " + licenseName + "?'/></a></td></tr>";
			buffer += "<td valign='middle' align='center'><a class='button' href='javascript:removeLicense("+licenseId+");'><span>Delete</span></a></td></tr>";
        }
         buffer += "</table></div>";
    }
    
    //buffer += "<p><hr/><a href='javascript:cart();'>Hide Cart</a>";
    if(itemsCount > 0) {
        buffer += "<br /><div style='float: left;'><a href='javascript:cartEmpty();'>Empty Cart</a> |";
    	buffer += " <a href='/web/PORTAL_ORDER_DESK'>Order Desk</a></div>";
		buffer += "<div style='float: right;'><a href='/web/secure/order.do'>Checkout Through Order Desk</a></div><div style='clear: both;'></div></p>";
	}
    

    // Update the cart's total using the value from the cart document
    setCartContents(buffer);
    
    //check if total label found update it
    if(document.getElementById('cartTotalLabel') != null) {
    	document.getElementById('cartTotalLabel').innerHTML=itemsTotal;
    }
}

function setCartContents(html) {
    var contents = document.getElementById(cartcontentDiv);
    contents.innerHTML = html;
}

function setItemsContents(html) {
    var contents = document.getElementById("cartItemsPanel");
    contents.innerHTML = html;
}

/*************************************************************************
  This code is from Dynamic Web Coding at www.dyn-web.com
  Copyright 2002-4 by Sharon Paine 
  See Terms of Use at www.dyn-web.com/bus/terms.html
  regarding conditions under which you may use this code.
  This notice must be retained in the code as is!
*************************************************************************/

// change speed of slide here
var slide_in_speed = 1000;	// millisecond duration of slide into view
var slide_out_speed = 1000;// millisecond duration of slide out of view

var shoppingCart;
var cartOut = false;
var initialized = false;
var verticalOffset = -260;

var cartcontentDiv = "cartcontent";

var winW = document.body.offsetWidth;
if(winW % 2 == 1)
    winW = winW -1;

function init() {
  // Arguments to constructor: id, x, y, w, y
  shoppingCart = new dynObj('cartcontent', winW/3.5, verticalOffset, 650, 0);
  shoppingCart.show();
  // Arguments to slideTo method: destination x, destination y, duration of slide, acceleration factor 
  // which should be number between -1 and 1 ( -1 full decelerated, 1 full accelerated, 0 linear, i.e. no acceleration)
  //obj1.slideTo(500, 10, 1000, -1); 
  initialized = true;
}

function slideOut() {
	var slideYCoordinate = (document.documentElement.scrollTop) +150;
	shoppingCart.slideTo(winW/3.5,slideYCoordinate , 1000, -1);
	//javascript:scroll(0,0); //commented out, remove if needed. 
	jQuery('body').append('<div id="fade"></div>');
	jQuery('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies
    cartOut = true;
}

function slideIn() {
    shoppingCart.slideTo(winW/3.5, verticalOffset, 1000, -1);
    setTimeout("setCartContents('')",500);
	jQuery('#fade').fadeOut();
    cartOut = false;
}

function cart() {
    if(cartOut)
        slideIn();
    else {
        executeCartRequest();
        slideOut();
    }
}

function cartEmpty() {
    executeClearCartRequest();
    verticalOffset = -260;
    slide_out_speed = 1000;
    slide_in_speed = 1000;
}

function removeLicense(licenseId) {
    executeRemoveItemRequest(licenseId);
}

function addToCart(licenseId,type) {
    executeAddCartRequest(licenseId,type);
    slideOut();
}

//initialize
init();
