/*
 * $Id: PhotobookCalculator.js 84386 2009-10-01 11:47:48Z k.reimer $
 * Copyright (C) 2007 IP Labs GmbH <http://www.iplabs.de/>
 * All rights reserved.
 */

/**
 * @fileoverview
 *
 * Contains all the PhotobookCalculator class.
 * 
 * @author Thorsten Schueller (t.schueller@iplabs.de)
 * @jscram.meta info="PhotobookCalculator\nCopyright (C) 2007 IP Labs GmbH <http://www.iplabs.de/>\n$Id: PhotobookCalculator.js 84386 2009-10-01 11:47:48Z k.reimer $"
 * @version $Revision: 84386 $
 */

/** External ContextBox @type Class @jscram.public var="ContextBox" */
var ContextBox;
/** External HTMLUtils @type Class @jscram.public var="HTMLUtils" */
var HTMLUtils;
/** External Formatter @type Class @jscram.public var="Formatter" */
var Formatter;

/**
 * Constructor
 * 
 * @class
 * 
 * @constructor
 * 
 * @param {ContextBox} cb1
 *     The format context box
 * @param {ContextBox} cb2
 *     The binding contex box
 * @param {ContextBox} cb3
 *     The pages context box
 * @param {HTMLElement} sum
 *     The price sum html elememt
 *
 * @jscram.public class="PhotobookCalculator"*     
 */
function PhotobookCalculator(cb1, cb2, cb3, sum)
{
    this.photobookPrices = [];
    this.photobookFormats = [];
    this.cb1 = cb1;
    this.cb2 = cb2;
    this.cb3 = cb3;
    this.sum = sum;
    this.translateFunction = null;
}

/**
 * Initialze all context boxes
 */
PhotobookCalculator.prototype.initAllContextBoxes = function()
{
    var bindings, pages;
 
    bindings = this.fillContextBox(this.cb1, this.photobookFormats, "bindings");
    pages = this.fillContextBox(this.cb2, bindings, "pages");
    this.fillContextBox(this.cb3, pages, "");
    this.calculatePrice();
};


/**
 * Delete and refill a contextbox.
 * 
 * @param {String} cbId
 *     The contextBox id.
 * @param {Object} newItems
 *     New items Object
 *     
 * @private
 * @jscram.private method="fillContextBox"
 */
PhotobookCalculator.prototype.fillContextBox = function(cb, newItems, childName) 
{
    var i, max, cm, lis, result;
    
    result = null;
    
    cm = HTMLUtils.getElementByClassName(document.getElementById(cb.cbId), "contextMenu");
    lis = cm.getElementsByTagName("li");

    // First delete all LI's    
    for (i=lis.length; i>0; i--)
    {
        lis[i-1].parentNode.removeChild(lis[i-1]);
    }

    // and now insert the new LI's
    for (i=0, max=newItems.length; i<max; i++)
    {
        if (i==0)
        {
            result = childName!="" ? eval("newItems[i]."+childName) : null; 
            this.updateSelector(cb,newItems[i].name, newItems[i].key);
        }
        
        var li = document.createElement("li");
        li.className = (i==max-1) ? "last" : "";
        li.onclick = this.contextBoxOnClickHandler;
        li.control = this;
        li.keyName = newItems[i].key;
        li.realName = newItems[i].name;
        li.updateChildName = childName; 
        li.newItems = (childName != "") ? eval("newItems[i]."+childName) : [];
        li.appendChild(document.createTextNode(newItems[i].name));
        cm.appendChild(li);
    }
    
    return result;
};

/**
 * Contexbox onClickHandler
 * 
 * @private
 * @jscram.private method="contextBoxOnClickHandler"
 */
PhotobookCalculator.prototype.contextBoxOnClickHandler = function(evt, obj)
{
    var pages;
    
    // Redirect event to control
    if (this.control)
    {
        return this.control.contextBoxOnClickHandler(evt ? evt : event, this);
    }
    
    // upadte bindings and pages
    if (obj.updateChildName == "bindings")
    {
        pages = this.fillContextBox(this.cb2, obj.newItems, "pages");
        this.fillContextBox(this.cb3, pages, "");
        this.updateSelector(this.cb1, obj.realName, obj.keyName);            
    }
    
    // update only pages
    if (obj.updateChildName == "pages")
    {
        this.fillContextBox(this.cb3, obj.newItems, "");
        this.updateSelector(this.cb2, obj.realName, obj.keyName);            
    }
    
    if (obj.updateChildName == "")
    {
        this.updateSelector(this.cb3, obj.realName, obj.keyName);
    }
    
    //update price
    this.calculatePrice();
     
    ContextBox.hide(); 
    return false;
};


/**
 * Add photobooks 
 *
 * @param {String} exportName
 *     The exportName
 * @param {Integer} price
 *     The price
 */
PhotobookCalculator.prototype.addPhotobook = function(exportName, price)
{
    var part, i, max, newLength, binding;
    var formatName, bindingName, format;

    part = exportName.split("_");

    if (part.length && part[0] == 'PB')
    {
        this.photobookPrices.push({"pb":part[1]+"_"+part[2]+"_"+part[3], "price":price});
        
        if (this.translateFunction !== null)
        {
            formatName = this.translateFunction(part[1]);
            bindingName = this.translateFunction(part[2]);
        }            

        format = this.objSearch(this.photobookFormats, "key", "", part[1]);
        if (format == -1)
        {
            newLength = this.photobookFormats.push(
                {
                    "key": part[1],
                    "name": formatName,
                    "bindings": []
                }
            );
            format = this.photobookFormats[newLength -1];
            
        }        
        
        binding = this.objSearch(format.bindings, "key", "", part[2]);
        if (binding == -1)
        {
            newLength = format.bindings.push(
                {
                    "key": part[2],
                    "name": bindingName,
                    "pages": []
                }
            );
            binding = format.bindings[newLength-1];
        }        
        
        binding.pages.push({"key":part[3], "name":part[3]});
   
    }
};

/**
 * Search in an array with objects.   
 * 
 * @param {Object} obj
 *     The search object.
 * @param {String} checkKey
 *     The keyname for the comparing
 * @param {String} resultKey
 *     The keyname for the result; , 
 * @param {String} value
 *     The search sring
 * @return {Object}
 *    -1 if nothing found or if the keyname is empty the
 *    the result is the found object otherwise the value 
 *    from keyname.          
 *
 * @private
 * @jscram.private method="objSearch"
 */
PhotobookCalculator.prototype.objSearch = function(obj, checkKey, resultKey, value)
{
    var i, max;

    for (i=0, max=obj.length; i<max; i++)
    {    
        if (eval("obj[i]."+checkKey) == value)
        {
            return (resultKey !="") ? eval("obj[i]."+resultKey) : obj[i];
        }            
    }
    return -1;
};    


/**
 * Update the contextbox selector
 * 
 * @param {ContextBox} cb
 *     The ContextBox object
 * @param {String} value
 *     The new text
 * @param {String} key
 *     The new key for price calculation
 *     
 * @private
 * @jscram.private method="updateSelector"
 */
PhotobookCalculator.prototype.updateSelector = function(cb, value, key)
{
    var e;
    
    e = HTMLUtils.getElementByClassName(document.getElementById(cb.chiefID), "active");
    e.replaceChild(document.createTextNode(value), e.firstChild);
    e.activeKey = key;	    
};


/**
 * Calculate and write the sum price.
 * 
 * @private
 * @jscram.private method="calculatePrice"
 */
PhotobookCalculator.prototype.calculatePrice = function()
{
    var resultKey, price;
    
    resultKey = HTMLUtils.getElementByClassName(document.getElementById(this.cb1.chiefID), "active").activeKey;
    resultKey = resultKey + "_" + HTMLUtils.getElementByClassName(document.getElementById(this.cb2.chiefID), "active").activeKey;
    resultKey = resultKey + "_" + HTMLUtils.getElementByClassName(document.getElementById(this.cb3.chiefID), "active").activeKey;

    price = this.objSearch(this.photobookPrices, "pb", "price", resultKey); 
    
    this.sum.replaceChild(document.createTextNode(Formatter.formatCurrency(price/100)), this.sum.firstChild);

    return price;
};

