/*****
 *
 *
 *
 * Helper
 *
 *
 *
 *****/
function transferToField(elementToTransfer, id) {
     $('bundle-option-' + id + '-qty-input').value  = elementToTransfer.value; 
}

/*
 * wird nur einmal genutzt und dank direkter verwerfung von
 * illegalen zeichen eigetnlich überflüssig
 */ 
function trim (zeichenkette) {
     return zeichenkette.replace (/^\s+/, '').replace (/\s+$/, '');
} 



     Product.VarBundle = Class.create(Product.Bundle, {


/*Product.VarBundle.prototype = {*/

/*


        OVERRIDE

*/


  initialize: function($super, config){
    $super(config);
/*
 *
 *
 * DEV MODE ???
 * in devmode no fields get disabled and you get all alerts
 *
 */
  this.devMode = false;
  /*
   * 
   * 1 Normal Level
   * 2 Everthings full with debug messages
   *
   */
  this.debuglevel = 1; 

  this.minimal_quadrat_meter = 0.5;

    this.min_insert_value = 0;
    this.max_insert_value = 301;
    /*
        Live Plissee
    */
    
    
    this.heightID = 2;
    this.widthID = 3;
    this.quaraticID = 1;
    this.handlingID = 4;
    


    this.handlingSelectable = true;

    this.pg_group_offset = 0; // if there is a PG group 0 you need a offset of one!
    if(document.title.match("^Plissee") ) {
        /*
         * Plissee dev
         */
        this.quaraticID = 5;
        this.heightID = 4;
        this.widthID = 3;
        this.handlingID = 1;
        if(this.devMode && this.debuglevel > 1) {
            alert("Quad-ID:"+this.quaraticID); 
        }
        this.pg_group_offset = 1;
        if(document.title.match("in der Fensternische")){
            this.heightID = 23;
            this.widthID = 22;
            this.quaraticID = 27;
            this.handlingID = 25;
        } else
        if(document.title.match("vor der Fensternische")){
            this.heightID = 29;
            this.widthID = 28;
            this.quaraticID = 33;
        } else
        if(document.title.match("auf dem Fensterrahmen")){
            this.heightID = 47;
            this.widthID = 46;
            this.quaraticID = 51;
            this.handlingID = 49;
        } else
        if(document.title.match("in der Fensterfalz")){
            this.heightID = 41;
            this.widthID = 40;
            this.quaraticID = 45;
            this.handlingID = 43;
        }
    } else
    
    /*
        Jalousie
    */

    if(document.title.match("^Jalousie")) {
    
        this.heightID = 7;
        this.widthID = 8;
        this.quaraticID = 17;
        //useless
        this.handlingID = 18;
        //alert("jalousie");
        this.handlingSelectable = false;
    } else
    if(document.title.match("^Auckland")) {
        this.heightID = 32;
        this.widthID = 31;
        this.quaraticID = 33;
        
    } else 
    /*
        Rollo
    */
    
    if(document.title.match("^Rollo")) {
    
        this.widthID = 15;
        this.heightID = 14;
        this.quaraticID = 17;
        this.handlingID = 13;
        this.max_insert_value = 501;
        //alert("rollo");
    }
    
    else 
    
    if(document.title.match("^Doppelrollo")) {
    
        this.widthID = 11;
        this.heightID = 12;
        this.quaraticID = 20;
        this.handlingID = 0;
        this.handlingSelectable = false;
        this.max_insert_value = 301;
        //alert("rollo");
    }   
        this.widthElem = $('bundle-option-'+this.widthID+'-qty-input');
        this.heightElem = $('bundle-option-'+this.heightID+'-qty-input');
        this.quadElem = null;
        this.quadSelectElem = null;
    },

     /*
     *
     *
     * getter und setter
     *
     */
     getQuadQty: function(){
        if(this.quadElem === null) {
          this.quadElem = $('bundle-option-'+ this.quaraticID +'-qty-input');
        }
        return this.quadElem;
     },

     getQuadSelect: function() {
        if(this.quadSelectElem === null) {
          this.quadSelectElem = $('bundle-option-'+ this.quaraticID);
        }
        return this.quadSelectElem;
     },

     getWidthElem: function(){
        if(this.widthElem === null) {
          this.widthElem = $('bundle-option-'+ this.widthID +'-qty-input');
        }
        return this.widthElem;
     },


                  /*
    initFields: function (){
        this.widthID = pagesettings['widthID'];
        this.heightID = pagesettings['heightID'];
    },
    */




    changeOptionQty: function ($super, element) {
        /*
            added 
        */
        this.convertDots(element);
        this.quadraticQty(element);

        if(this.devMode && this.debuglevel > 1) {
            alert( 'elem ID: ' + element.id + ' widthID: ' + this.widthID + ' value: ' + element.value);
        }

        /*
         * Validierung der Eingabe
         */ 

        if(
            element.id == 'bundle-option-' + this.widthID + '-qty-input' ||
            element.id == 'bundle-option-' + this.heightID + '-qty-input'
        ) {
            this.checkHeightAndWidthToHide();
        }
            //Nicht ausreichend grosse stoffe deaktivieren
            //this.hideSmall(element.value);
        /* 
            end
        */
        if(this.validateSize(element)) {
            $super(element);
        }
    },



    populateQty: function($super, optionId, selectionId){
         if(optionId != this.quaraticID){ 
            $super(optionId, selectionId);
         } else {
            //Fehlerfälle vermeiden
            if(this.getQuadQty().value == 0)
                this.getQuadQty().value = 0.96;
         }
    },

/*

        OVERRIDE END
        
*/



    /*

                        esync add

    */

    /*
     * renamed from :
     * setQuaraticQty: function(bool) {
     */
    disableQuaraticQtyField: function(bool) {
        elem = $('bundle-option-'+this.quaraticID+'-qty-input');
        if(!this.devMode){
           elem.disabled = bool;
        }
        
        /*


            this will fail if only one item is inside!


        */
        
        elem = $('bundle-option-'+this.quaraticID);
        if(!this.devMode && elem !== null){
           elem.disabled = bool;
        }
    },


    quadraticQty: function (element) {
            this.disableQuaraticQtyField(true);  
            if ( this.validateSize(element) ) {
               
                    /*
                     * Hat sich ein relevantes objekt geändert?
                     */  
                    if (element.id == 'bundle-option-' + this.widthID + '-qty-input' || element.id == 'bundle-option-'+ this.heightID + '-qty-input') {
                                h = $('bundle-option-' + this.heightID + '-qty-input').value;
                                w = $('bundle-option-' + this.widthID + '-qty-input').value;
                                /*
                                 * Wenn ungültige Zahlen eingetragen wurde,
                                 * hohe Werte zur Kalkulation nutzen
                                 */ 
                                if( h === null || h < 0) { 
                                    h = 300;
                                }
                                if( w === null || w < 0){
                                    w = 300;
                                }
                                qty = h * w;
                        calculatedPrice = qty / 10000;

                        /*
                         * Mindestquadratmeter nicht erfüllt?
                         */
                        if (calculatedPrice < this.minimal_quadrat_meter){
                            calculatedPrice = this.minimal_quadrat_meter;
                        }
                        this.getQuadQty().value  = calculatedPrice;
                    }

            }
    },

    validateSize: function (element) {
        //this.convertDots(element);
        if(
            element.value > this.min_insert_value && 
            element.value < this.max_insert_value
        ) {
            return true;
        }
        else {
            /*
                Wert anpassen
            */
            element.focus(); 

            if( element.value != '' ){
                /*if( isNaN(element.value) ) {
                    alert('Es sind nur Zahlen sowie , oder . erlaubt!');
                    element.value = 120;
                    return true;
                } else*/
                if ( element.value < this.min_insert_value) {
                    element.value = parseInt(this.min_insert_value,10)+1;
                    alert('Ihre eingabe war zu niedrig und wurde deshalb erhöht');
                    return true;
                }
                else if ( element.value > this.max_insert_value){
                    element.value = parseInt(this.max_insert_value,10)-2;
                    alert('Ihre eingabe war zu hoch und wurde deshalb reduziert');
                    return true;
                }
            }
        }
    },

    convertDots: function(element) {
        element.value = element.value.replace(/\,.*/, '.');
        this.removeIllegalNumberChars(element);
    },

    removeIllegalNumberChars: function(element) {
        //All nicht zahlen entfernen (, muss bereits Konvertiert sein)
        element.value = element.value.replace(/[^\d.]/g, "");
    },

    setSelectedQuadratic: function (index) {
        this.disableQuaraticQtyField(false);
        quadselect = $('bundle-option-' + this.quaraticID);
        try{
            quadselect.selectedIndex = parseInt(index,10) + this.pg_group_offset;
        } catch (e) {
            alert("DEV ERROR: \nCant find index to select!\n Maybe some Quadratmeters PGs are missing\nINDEX: "+index+"\n"+e);
        }
        
        //muss hier redundant aufgerufen werden zwischen dem Freischalten
        //des Feldes, damit die änderung vom Event gefunden wird 
        this.changeSelection(quadselect);
        this.disableQuaraticQtyField(true);
    },

    checkHeightAndWidthToHide: function(index){
        widthElem = $('bundle-option-'+this.widthID+'-qty-input');
        heightElem = $('bundle-option-'+this.heightID+'-qty-input');
    
        //alert('widthID: '+this.widthID+' width: '+widthElem.value+ ' height: '+heightElem.value); 

        this.hideSmall(widthElem.value, heightElem.value);  
    },

    hideSmall: function (width, height) {
        //elem = $('bundle-option-' + optionId + '-qty-input');
        childs = $('product-options-wrapper').childElements();
        //alert(childs);

        
        //this.setSelectedQuadratic(2);

        /*
        for (var option in this.config.selected) {
            if (this.config.options[option]) {
                for (var i=0; i < this.config.selected[option].length; i++) {
            
               if(
                this.config.selected[option][i] > 0 
                && width_data[this.config.selected[option][i]]
                )
                //TODO hier einfügen -> der von ihnen gewählte Stoff wurde zurück gesetzt, da es diesen nicht bis zu der von ihnen gewählten breite gibt
                if ( this.config.selected[option][i] > 10000)
                    alert ('WTF EXTRA: ' + width_data[this.config.selected[option][i]]['max_width']);
                }
            }
        }
        */


        //entfernen der einzlenen teile
        //alert('width: '+width+' height: '+height);
        var test = '';
        for (var values in width_data){
            if (typeof width_data[values]['max_width'] != "undefined"){
                /*
                    Ab hier sind alle gefunden, die ein max_width property gesetzt haben
                */
                test += ','+width_data[values]['max_width']+"\n";
                //ungültige einträge
                //for (var option in this.config.selected) {
                for (var option in this.config.options) {
                var opti = parseInt(option,10) + 1;
                //console.log('OPTION : '+option + ' opt index: '+opti);
                
                //for (var option=0; option < 10; option++) {
                    //for (var i=0; i < this.config.selected[option].length; i++) {
                    //alert(this.config.options[option].Id);
                    //for (var i=0; i < this.config.options[option].length; i++) {
                    //for (var i=2; i < 7; i++) {
                        //elem = $('max_width_'+i+'-'+values);
                        elem = $('max_width_'+opti+'-'+values);
                        if(elem !== null){
                            if( 
                                (
                                width_data[values]['max_width'] < width ||
                                width_data[values]['min_width'] > width
                                ) || (
                                width_data[values]['max_height'] !== null &&
                                ( 
                                    width_data[values]['max_height'] < height ||
                                    width_data[values]['min_height'] > height)
                                )
                                ){                  
                                    elem.style.display = 'none';
                                    //radio button  nicht mehr auswaehlen, wenn er durch einen regel entnommen wird
                                    elem = $('bundle-option-'+opti+'-'+values);
                                    elem.checked= false;
                            } else {
                                elem.style.display = 'block';
                            }
                            //console.log('\tElement gefunden mit option : '+option + ' values = '+values);
                        }
                        /*
                        else
                            console.log('kein element gefunden mit option : '+option + ' values = '+values);
                        */
                    //}
                }


            }
          }
        //alert(test);


        
    },

    changeHandling: function (doEnable) {
        
      if(this.handlingSelectable) {
        var index = 1;
        //wenn nicht auswaehlbar
        var fallback = 623;
        select = $('bundle-option-' + this.handlingID);
        if(!doEnable) {
            //if(select.selectedIndex == 0)
            select.selectedIndex = 3;
            select.options[2].disabled = true;
            select.options[1].disabled = true;
            select.options[3].disabled = false;
        } else {
            if(select.selectedIndex == 3){
                select.selectedIndex = 0;
            }
                //NeuerEintrag = new Option(document.Testform.neu.value, document.Testform.neu.value, false, true);
                //NeuerEintrag = new Option("Links", "2", false, true);
                //NeuerEintrag2 = new Option("Rechts", "1", false, true);
                //select.options[select.options.length] = NeuerEintrag;
                select.options[1].disabled = false;
                select.options[2].disabled = false;
                select.options[3].disabled = true;

        }
        this.changeSelection(select);
        //alert("ding ding "+doEnable+" "+select);
            
      }

    },

    validateFieldAndTransfer: function (fieldToValidate, destinationID) {
        if(trim(fieldToValidate.value) != ""){
            this.convertDots(fieldToValidate);
            this.removeIllegalNumberChars(fieldToValidate);
            this.validateSize(fieldToValidate);
            transferToField(fieldToValidate, destinationID);
            orgiField = $('bundle-option-' + destinationID + '-qty-input');
            this.checkHeightAndWidthToHide();
            this.changeOptionQty(orgiField);
        }
    },
    
    reloadPrice: function ($super) {
    	var ret = $super();
	var elem = $$('.price-as-configured span.price');
	if(ret < 0.01){
		elem.each (function(s) {
			if(s != null && typeof(s) != "undefined") {
				s.update("<a href=\"#product-options-wrapper\">Produkt zusammenstellen</a>");
			}
			}
			);
	}
	
	return ret;
    }
    
    /*
                    esync add end
    */


}
);












/************************ USEFUL FUNCTIONS *****************************/
function smo_input_get_label(inputElem){
    if(inputElem.parentNode){
      if(inputElem.parentNode.tagName=='label'){
        return inputElem.parentNode;
      }
    }
    var labels=document.getElementsByTagName("label"),i;
    for( i=0; i<labels.length;i++ ){
      if(labels[i].htmlFor==inputElem.id){
        return labels[i];
      }
    }
 return false;
}



