/*
This script file is dipendent of global.js for all
global constants and variables.
*/

/*
============================================================
Function: processCartRequest

Last Modified: Jun/25/2008

This function 
============================================================
*/
function checkOut( ) {
    // Hide whatever is shown now and show the list screen.
    hideShowAndInsertAsTopElement(currentlyShownElement, calendarPageDivElement,
        null, null, null, null);
    if (document.getElementById("cframe")){
        currentlyShownElement.removeChild( document.getElementById("cframe") );
    }
        
    node = document.createElement( "iframe" );
    node.id = "cframe";
    node.src = "./php/checkout.php";
    node.width = "100%";//"765";
    node.height = "470";
    node.frameBorder = "0";
    node.scrolling = "no";
        
    currentlyShownElement.appendChild( node );
}

/*
============================================================
Function: processCartRequest

Last Modified: Jun/25/2008

This function processes the cart operation. This is an event
handler for the 
DIV elements that include the cart info text. It brings up 
the screen containing the cart.
============================================================
*/
function processCartRequest( ) {
    // Set the page query here.
    addToCart( "show", "", "", "" );
    // Hide whatever is shown now and show the list screen.
    hideShowAndInsertAsTopElement(currentlyShownElement, cartListPageDivElement,
        null, null, null, null);
    
    // Set the header text.
    setHeader( "cartHeader", "Kundvagn" );
} // End of function processCartRequest

/*
============================================================
Function: changeCartViewStyleForSelection

Last Modified: Jun/24/2008

This function simulates the menuitem highlighting for the
menu items. All the cart are DIV elements with
menu text inside of them. When the user moves his mouse over 
this element, this event handler will be called.
It simply applies a different style to that DIV element.
That makes a visual cue for the user by highlighting the 
text in a different color.

This function gets the menu item number where the 
mouse is at now. Refer to the HTML file from where this
parameter is passed.
============================================================
*/
function changeCartViewStyleForSelection() {
    // Get the current DIV element that is being moused over.
    // Caller gives us the DIV element number (deposit, debit or portfolio).
    // From that number, get the HTML id and get the element object.
    var menuItemElement = 
    document.getElementById("cartView");
    // Simply assign the CSS rule for that classname.
    // That is all you have to do to simulate the menu highlighting. 
    menuItemElement.className = "cartSelect";
} // End of function changeCartViewStyleForSelection

/*
============================================================
Function: changeCartViewStyleToDefault

Last Modified: Jun/25/2008

This function simulates the cart unhighlighting for the
menu items. All the menu items are DIV elements with
menu text inside of them. When the user moves his mouse out of 
this element, this event handler will be called.
It simply applies a different style to that DIV element.
That makes a visual cue for the user by removing the 
hightlighted text into a normal text with no background color.

This function gets the menu item number where the 
mouse is at now. Refer to the HTML file from where this
parameter is passed.
============================================================
*/
function changeCartViewStyleToDefault() {
    // Get the current DIV element from where the mouse is moving out.
    // Caller gives us the DIV element number (deposit, debit or portfolio).
    // From that number, get the HTML id and get the element object.   
    var menuItemElement = document.getElementById("cartView");
    menuItemElement.className = "cart";
} // End of function changeCartViewStyleToDefault

/*
============================================================
Function: createCartList

Last Modified: Jun/17/2008

This function takes JSON formated data and convert it to
a DOM table object.
============================================================
*/
function createCartList( objJSON ) {
    
    var insertParent = document.getElementById( "cartList" );
    
    // Remove tablebody if it exists
    var childnode=document.getElementById("cartlistbody");
    if ( childnode != null ){
        insertParent.removeChild( childnode );
    } // End if ( childnode != null )
    
    if (objJSON.result.length != 0){

        // Create a new table body
        var newTable = document.createElement("tbody");
        newTable.id ="cartlistbody";

        if (BrowserDetect.browser == "Explorer"){k=1}
        else{k=0};

        // Create a new table row
        for (var i=0; i < objJSON.result.length-k; i++){

            var tRow = document.createElement("tr");
            if (i % 2){
                tRow.className = "itemRowEven";
            }
            else{
                tRow.className = "itemRowOdd";
            }

            tRow.id = "prodItem" + i;

            var tCol = document.createElement("td");
            tCol.className = "itemNo";

            var text = document.createTextNode( objJSON.result[i].id );

            tCol.appendChild( text );

            tRow.appendChild( tCol );

            tCol = document.createElement("td");

            childnode = document.createElement("span");
            childnode.className = "itemName";
            text = document.createTextNode( objJSON.result[i].name );
            childnode.appendChild( text );

            tCol.appendChild( childnode );

            childnode = document.createElement("br");

            tCol.appendChild( childnode );

            childnode = document.createElement("span");
            text = document.createTextNode( "Tillgänglighet: " );
            childnode.appendChild( text );

            tCol.appendChild( childnode );

            childnode = document.createElement("img");
            childnode.src = "./pic/" + objJSON.result[i].available;

            tCol.appendChild( childnode );

            tRow.appendChild( tCol );

            tCol = document.createElement("td");
            tCol.className = "price";

            text = document.createTextNode( objJSON.result[i].price + " Kr" );
            tCol.appendChild( text );

            tRow.appendChild( tCol );

            tCol = document.createElement("td");
            tCol.className = "operation";

            var formnode = document.createElement("form");
            formnode.onsubmit = function(){ return false; };

            childnode = createNamedElement("input", "amountR");
            childnode.type = "text";
            childnode.value = objJSON.result[i].amount;
            childnode.size = "2";

            formnode.appendChild( childnode );

            childnode = createNamedElement("input", "btnR");
            childnode.type = "button";
            childnode.value = "Ändra";
            childnode.pid = objJSON.result[i].id;
            childnode.pprice = objJSON.result[i].price.replace(",", ".");
            childnode.onclick =  function(){ addToCart( 'update', this.pid, this.form.amountR.value, this.pprice );};

            formnode.appendChild( childnode );

            text = document.createTextNode( " " );
            formnode.appendChild( text );

            childnode = createNamedElement("input", "btnDR");
            childnode.type = "button";
            childnode.value = "Ta bort";
            childnode.pid = objJSON.result[i].id;
            childnode.pprice = objJSON.result[i].price.replace(",", ".");
            childnode.onclick = function(){ addToCart( 'delete', this.pid, 0, this.pprice );};

            formnode.appendChild( childnode );

            tCol.appendChild( formnode );
            tRow.appendChild( tCol );

            // Add the new row to the table body             
            newTable.appendChild( tRow );
        } // End for(var i=0; i < objJSON.result.length - 1; i++)

        // Add the total and the check out button
        var tRow = document.createElement("tr");

        var tCol = document.createElement("td");

        tCol.className = "itemNo";

        tRow.appendChild( tCol );

        tCol = document.createElement("td");

        childnode = document.createElement("span");
        childnode.className = "itemTot";
        text = document.createTextNode( "Totalt:" );
        childnode.appendChild( text );

        tCol.appendChild( childnode );

        tRow.appendChild( tCol );

        tCol = document.createElement("td");
        tCol.className = "price";
        tCol.id = "cartTotal";

        text = document.createTextNode( "0,00 Kr" );
        tCol.appendChild( text );

        tRow.appendChild( tCol );

        tCol = document.createElement("td");
        tCol.className = "operation";

        var formnode = document.createElement("form");
        formnode.onsubmit = function(){ return false;};

        childnode = createNamedElement("input", "checkout");
        childnode.type = "button";
        childnode.value = "Gå till kassan";
        childnode.onclick = function(){ checkOut();};

        formnode.appendChild( childnode );

        tCol.appendChild( formnode );
        tRow.appendChild( tCol );

        // Add the last row to the table body             
        newTable.appendChild( tRow );

        // Add the tbody object to the table
        insertParent.appendChild(newTable);
    }
    updateCartInfo( objJSON );
    
} //End function createCartList

/*
============================================================
Function: getCartList

Last Modified: Jun/19/2008

This function is the callback function for the site menu
request it gets the cart list from the server in JSON
formated text.
============================================================
*/
function getCartList(){
    // Do something only when the HTTP readystate is LOADED.
    if (Prod_request.readyState == HTTP_READYSTATE_LOADED) {
        // You have nothing to do until it is 200 OK.
        if (Prod_request.status == HTTP_STATUS_OK) {
            // We will get the response data in JSON format as plain text
            var textResult = Prod_request.responseText; 
            // Convert the JSON formatted text into a JSON object.
            var obj = textResult.parseJSON();
            createCartList( obj );
        } // End  if (Tabel_request.status == HTTP_STATUS_OK)
    } // End if (Tabel_request.readyState == HTTP_READYSTATE_LOADED)
} // End function getCartList

/*
============================================================
Function: updateCartInfo

Last Modified: Jun/19/2008

This function alters the cart information at the top of the 
padge.
============================================================
*/
function updateCartInfo( objJSON ){
    var numberOfItems = document.getElementById( "nop" );
    var totalPrice = document.getElementById( "tot" );
  
    numberOfItems.removeChild( numberOfItems.firstChild );
    totalPrice.removeChild( totalPrice.firstChild );
    
    // update the number of products
    if ( objJSON.items == 0 ){
        numberOfItems.appendChild( document.createTextNode( "inga produkter" ));
    }
    else if ( objJSON.items == 1 ){
        numberOfItems.appendChild( document.createTextNode( "1 produkt" ));
        if ( ShowCheckoutInfo ){
           ShowCheckoutInfo = false;
            alert("För att gå till kassan. Klicka på varukorgsinformationen överst på sidan.");
        }
    }
    else {
        numberOfItems.appendChild( document.createTextNode( objJSON.items + " produkter" ));
        if ( ShowCheckoutInfo ){
           ShowCheckoutInfo = false;
            alert("För att gå till kassan. Klicka på varukorgsinformationen överst på sidan.");
        }
    }
    // update the total vale.
    totalPrice.appendChild( document.createTextNode( objJSON.total ));
    // change the total value on the cart page
    if (currentlyShownElement.id == DIV_CARTLIST_PAGE && document.getElementById("cartTotal")){
        var node = document.getElementById("cartTotal").childNodes[0] ;
        
        node.data = objJSON.total + " Kr";
    }
}

/*
============================================================
Function: getCartInfo

Last Modified: Jun/19/2008

This function is the callback function for the site menu
request it gets the cart info from the server in JSON
formated text.
============================================================
*/
function getCartInfo(){
    // Do something only when the HTTP readystate is LOADED.
    if (Prod_request.readyState == HTTP_READYSTATE_LOADED) {
        // You have nothing to do until it is 200 OK.
        if (Prod_request.status == HTTP_STATUS_OK) {
            // We will get the response data in JSON format as plain text.
            var textResult = Prod_request.responseText; 
            // Convert the JSON formatted text into a JSON object.
            var obj = textResult.parseJSON();
            updateCartInfo( obj );
        } // End  if (Tabel_request.status == HTTP_STATUS_OK)
    } // End if (Tabel_request.readyState == HTTP_READYSTATE_LOADED)
} // End function getCartInfo

/*
============================================================
Function: addToCart

Last Modified: Jun/19/2008

This function initiate a Http request to get the cart info.

Actions: add -> Adds item to the cart.
         delete -> Removes item from the cart.
         show -> Shows the content of the cart.
         update -> ?
         reset -> Removes all items from the cart.
============================================================
*/
function addToCart( action, prodID, amount, price ){
    var callbackFunction = getCartInfo;
    
    url = "./php/cart.php?action=" + action + "&prodID=" + prodID + "&amount=" + amount + "&price=" + price;

    if ( action == 'show' || action == 'delete'){
        callbackFunction = getCartList;
    }
    Prod_request = createRequest();
    // Send this XHR request now.
    sendHttpRequest(Prod_request, callbackFunction, url, "");
}