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

function adjustIFrameSize( frameSize, frameId ){
    var myIframe = document.getElementById(frameId);
    if (myIframe) {
            myIframe.height = frameSize + 50;//document.body.offsetHeight;
    }
}

/*
============================================================
Function: findPosX

This function was created by Peter-Paul Koch & Alex Tingle.
you may find them at www.quirksmode.org and
at www.firetree.net
============================================================
*/
function findPosX(obj){
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
}// End of function findPosX

/*
============================================================
Function: findPosY

This function was created by Peter-Paul Koch & Alex Tingle.
you may find them at www.quirksmode.org and
at www.firetree.net
============================================================
*/
function findPosY(obj){
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
}// End of function findPosY

/*
============================================================
Function: createNamedElement

This function creates an element with an name property
regardless of browser.
============================================================
*/
function createNamedElement(type, name) {
   var element = null;
   // Try the IE way; this fails on standards-compliant browsers
   try {
      element = document.createElement('<'+type+' name="'+name+'">');
   } catch (e) {
   }
   if (!element || element.nodeName != type.toUpperCase()) {
      // Non-IE browser; use canonical method to create named element
      element = document.createElement(type);
      element.name = name;
   }
   return element;
}


/*
============================================================
Function: changeProductItemStyleForSelection

Last Modified: Jun/19/2008

This function simulates the menuitem highlighting for the
product items. All the menu items are TR elements with
product 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 TR 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 changeProductItemStyleForSelection(currentProdItem) {
    // Get the current TR element that is being moused over.
    // Caller gives us the TR element number (deposit, debit or portfolio).
    // From that number, get the HTML id and get the element object.
    var prodItemElement = document.getElementById(PROD_ITEM + currentProdItem);
    // Simply assign the CSS rule for that classname.
    // That is all you have to do to simulate the menu highlighting.

    prodItemElement.className = PROD_ITEM_SELECTION;

} // End of function changeProductItemStyleForSelection

/*
============================================================
Function: changeProductItemStyleToDefault

Last Modified: Jun/19/2008

This function simulates the product item unhighlighting for the
menu items. All the product items are TR 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 TR 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 changeProductItemStyleToDefault(currentProdItem) {
    // Get the current TR element from where the mouse is moving out.
    // Caller gives us the TR element number (deposit, debit or portfolio).
    // From that number, get the HTML id and get the element object.   
    var prodItemElement = document.getElementById(PROD_ITEM + 
        currentProdItem);

    prodItemElement.className = PROD_ITEM_DEFAULT;

} // End of function changeProductItemStyleToDefault

/*
============================================================
Function: showPicture

Last Modified: Aug/07/2008

This function shows the picture div at a position
on the site hovering over the rest of the content.
============================================================
*/
function showPicture( pObj, pData, pType ){
    
    var childNode;
    
    var x = findPosX( pObj );
    var y = findPosY( pObj );
    
    // Hide div if all ready vissible
    if ( pictureDivElement.style.visibility == CSS_STYLE_VISIBLE )
        hidePicture();
    
    if ( pType == "img" ){
        childNode = document.createElement("img");
        childNode.src = pData;
        pictureDivElement.className = "picfloat";
        pictureDivElement.style.left = x - 20 + "px";
        pictureDivElement.style.top = y - 30 + "px";
    }
    else {
        childNode = document.createElement("p");
        childNode.appendChild( document.createTextNode( pData ) );
        pictureDivElement.className = "txtfloat";
        pictureDivElement.style.left = x + 20 + "px";
        pictureDivElement.style.top = y + 20 + "px";
    }
    
    childNode.setAttribute("id", "pop");
    pictureDivElement.appendChild( childNode );
    pictureDivElement.style.visibility = CSS_STYLE_VISIBLE;
    mainPageDivElement.appendChild( pictureDivElement );
   
} // End of function showPicture

/*
============================================================
Function: hidePicture

Last Modified: Aug/07/2008

This function hides the picture div.
============================================================
*/
function hidePicture(){
    
    var childNode = document.getElementById("pop");
    
    pictureDivElement.style.visibility = CSS_STYLE_HIDDEN;
    pictureDivElement.removeChild( childNode );
    mainPageDivElement.removeChild( pictureDivElement );

} // End of function hidePicture
/*
============================================================
Function: getProdList

Last Modified: Jun/17/2008

This function is the callback function for the site menu
request it gets the product list from the server in JSON
formated text.
============================================================
*/
function getProdList() {
    
    // 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();
            createProdList(obj, "ItemListPage");
        } // End  if (Tabel_request.status == HTTP_STATUS_OK)
    } // End if (Tabel_request.readyState == HTTP_READYSTATE_LOADED)
} // End function getItems()

/*
============================================================
Function: reqProdList

Last Modified: Jun/17/2008

This function initiate a Http request to get the product list.
============================================================
*/
function reqProdList( subCatID ) {
    var url = "./php/listproducts.php?subCatID=" + subCatID;
    var callbackFunction = getProdList;
    Prod_request = createRequest();
    // Send this XHR request now.
    sendHttpRequest(Prod_request, callbackFunction, url, "");	
    
}
/*
============================================================
Function: createProdList

Last Modified: Aug/07/2008

This function takes JSON formated data and convert it to
a DOM table object.
============================================================
*/
function createProdList( objJSON, parentID ) {
    
    var tCell, tSpan, tText, tForm, childNode;
    var insertParent = document.getElementById( parentID );

    // Remove item container if it exist
    childNode=document.getElementById("prodlistbody");
    if ( childNode != null ){
        insertParent.removeChild( childNode );
    } // End if ( childnode != null )
    
    // Create item container
    iList = document.createElement( "div" );
    iList.id = "prodlistbody";
    
    if (BrowserDetect.browser == "Explorer"){k=1}
    else{k=0};
    
    // Create product table cells
    for (var i=0; i < objJSON.result.length-k; i++){
        // Create div element for the product
        tCell = document.createElement("div");
        tCell.className = "table-cell";    
        tCell.id = objJSON.result[i].id;
        
        // Product image
        childNode = document.createElement("img");
        childNode.src = "./pic/products/" + objJSON.result[i].img;
        childNode.className = "table-pic";
        childNode.pimg = "./pic/products/" + objJSON.result[i].img;
        childNode.onclick = function(){ showPicture( this, this.pimg, 'img') };
        tCell.appendChild( childNode );
        tSpan = document.createElement("span");
        
        // Product name
        childNode = document.createElement("h2");
        tText = document.createTextNode( objJSON.result[i].name );
        childNode.pcomment = objJSON.result[i].comment;
        childNode.onmouseover = function(){ showPicture( this, this.pcomment, 'txt')};
   
        childNode.onmouseout = hidePicture;
        childNode.appendChild( tText );
        tSpan.appendChild( childNode );
        
        // Product price
        childNode = document.createElement("p");
        tText = document.createTextNode( "Pris: " + objJSON.result[i].price + "Kr" );
        childNode.appendChild( tText );
        tSpan.appendChild( childNode );
        
        // Add to cart form
        tForm = document.createElement("form");
        tForm.className = "picform";
        tForm.onsubmit = function(){return false;};
        
        childNode = createNamedElement("input", "amount");
        childNode.type = "text";
        childNode.value = "1";
        childNode.size = "2";
        tForm.appendChild( childNode );
        
        childNode = createNamedElement("input", "btn");
        childNode.align = "right";
        childNode.type = "button";
        childNode.value = "Köp";
        childNode.pid = objJSON.result[i].id;
        childNode.pprice = objJSON.result[i].price.replace(",", ".");
        childNode.onclick = function(){ addToCart( 'add', this.pid, this.form.amount.value, this.pprice ); this.form.amount.value = 1;};
        tForm.appendChild( childNode );
        tSpan.appendChild( tForm );
        
        // Availabilety indication
        childNode = document.createElement("span");
        tText = document.createTextNode( "Tillgänglighet: " );
        childNode.appendChild( tText );
        tSpan.appendChild( childNode );
        childNode = document.createElement("img");
        childNode.src = "./pic/" + objJSON.result[i].available;
        tSpan.appendChild( childNode );
        
        tCell.appendChild( tSpan );
        
        // Add the product cell to the item container             
        iList.appendChild( tCell );
     }// End for(var i=0; i < objJSON.result.length - 1; i++)
    
    // Add the item container object to the table
    insertParent.appendChild( iList );
    
}//End function createProdList
