var quoteoptionsLinePriceCalc = new Class({ //start calc class here
    Implements: [Options, Events],

    options: {
        row:1,
        equip:null
    },
    initialize: function(options){
        this.setOptions(options);
        //build HTML
        this.row_container = $('row-container');
        //create var holding lineprice html
        var linePriceHtml = '<div class="quotelineprice" id="lineprice">\
        <div class="quoteoptions">\
            <label for="select-equipment-xx">Select Equipment</label>\
            <select NAME="select-equipment-xx" class="select-equipment" id="select-equipment-xx">\
                <optgroup id="option-adult-skis-xx" label="Adult Skis"></optgroup>\
                <optgroup id="option-junior-skis-xx" label="Junior Skis"></optgroup>\
                <optgroup id="option-snowboards-xx" label="Snowboards"></optgroup>\
            </select>\
        </div>\
        \
        <div class="quoteoptions">\
            <label for="number-of-days-xx">Days</label>\
            <select class="numberselect number-of-days" name="number-of-days-xx" id="number-of-days-xx">\
                <option value="one_day_price" selected="selected">1</option>\
                <option value="two_day_price">2</option>\
                <option value="three_day_price">3</option>\
                <option value="four_day_price">4</option>\
                <option value="five_day_price">5</option>\
                <option value="six_day_price">6</option>\
                <option value="seven_day_price">7</option>\
                <option value="eight_day_price">8</option>\
                <option value="nine_day_price">9</option>\
                <option value="ten_day_price">10</option>\
            </Select>\
        </div>\
        <div class="quoteoptions">\
            <label for="select-boots-xx">Boots</label>\
            <input type="checkbox" name="select-boots-xx" id="select-boots-xx" ></input>\
        </div>\
        <div class="quoteoptions">\
            <a class="quickquoteremove" id="remove-row-xx" href="#">Remove</a>\
        </div>\
        <div class="lineprice" name="line-price-xx" id="line-price-xx">0</div>\
        </div>\
    </div>\
        ';
        //add suffix labelling associating elements to class
        linePriceHtml = linePriceHtml.replace(/-xx/g, ['-'+this.options.row])
        this.row = new Element('div', {id:'row'+this.options.row});
        this.row.set('html', linePriceHtml);
        this.row.inject(this.row_container);
        //associate elements with class variables
        this.select_equipment = $('select-equipment'+'-'+[this.options.row]); // the ski selector box
        this.select_days = $('number-of-days'+'-'+[this.options.row]); //number  of days select box
        //this.select_people = $('number-of-people'+'-'+[this.options.row]); //number of people select box
        this.select_boots = $('select-boots'+'-'+[this.options.row]); //Boots select box
        this.line_price = $('line-price'+'-'+[this.options.row]) //the line price
        //populate data and add events to elements
        this.parseEquipmentData(this.options.equip);    //all data in Equipment_types table     
        
		
		var ps = this.row.getPrevious('div');
		if (ps){
		    this.select_equipment.value = $$('#'+ ps.id + ' .select-equipment')[0].value;
    		this.select_days.value = $$('#'+ ps.id + ' .number-of-days')[0].value;
		}else{
		    this.select_equipment.value = 1;
		}
		
		this.addSelectChangeEvents();
        this.calculateLinePrice();
		pageTracker._trackPageview('/quickquote/AddRow/');
    },
    
    removeRow: function(){
        $('row'+this.options.row).dispose();
		pageTracker._trackPageview('/quickquote/RemoveRow/');
        calculateTotalPrice();
    },
    
    addSelectChangeEvents: function(){
        
            if (this.options.row == 0){
                $('remove-row-'+this.options.row).dispose();
            }else{
                $('remove-row-'+this.options.row).addEvent('click', function(){
                    this.removeRow();
                }.bind(this));
            }
            
        
                this.select_equipment.addEvent('change', function(){
                    //(re)calculate the line price?
				    pageTracker._trackPageview('/quickquote/ChangeEquipment/' + this.select_equipment[this.select_equipment.selectedIndex].text);
                    this.calculateLinePrice();
                }.bind(this));
    
                /*this.select_people.addEvent('change', function(){
                    //(re)calculate the line price?
					pageTracker._trackPageview('/quickquote/ChangePeople/' + this.select_people.value);
                    this.calculateLinePrice();
                }.bind(this));*/
        
                this.select_days.addEvent('change', function(){
                    //(re)calculate the line price?
					pageTracker._trackPageview('/quickquote/ChangeDays/' + this.select_days.value);
                    this.calculateLinePrice();
                }.bind(this));
        
                this.select_boots.addEvent('change', function(){
                    //(re)calculate the line price?
                    pageTracker._trackPageview('/quickquote/ChangeBoots/' + this.select_days.checked ? "On" : "Off");
                    this.calculateLinePrice();
                }.bind(this));
    },
    
    calculateLinePrice: function (){
        //calculate the line price?     
        var equip = this.options.equip;
        var noDaysPriceSki = (equip[this.select_equipment.value][this.select_days.value]);
        var noDaysPriceBoot = 0;
        var noPeople = 1;//this.select_people.value;
        var linePrice = 0; 
        
        //add on boot price
        if (this.select_boots.checked == true){
            switch(this.select_equipment.value)     
                {
                case "7":
                //  .value == 7 == Beginner skis == Progression ski boots .value == 6
                    noDaysPriceBoot = (equip[6][this.select_days.value]);
                  break;
                case "1":
                //  .value == 1 == Progression skis == Progression ski boots .value == 6
                    noDaysPriceBoot = (equip[6][this.select_days.value]);
                  break;
                case "2":
                //  .value == 2 == Performance skis == Performance ski Boots .value == 17
                    noDaysPriceBoot = (equip[6][this.select_days.value]);
                  break;    
                case "3":
                //  .value == 3 == Exclusive skis == Performance ski Boots .value == 17
                    noDaysPriceBoot = (equip[6][this.select_days.value]);
                  break;          
                case "14":
                //  .value == 14 == Progression Snowboards == Adult Boots 1 .value == 21
                    noDaysPriceBoot = (equip[21][this.select_days.value]);
                  break;
                case "8":
                //  .value == 8 == Performance Snowboards == Adult Boots 1 .value == 21
                    noDaysPriceBoot = (equip[21][this.select_days.value]);
                  break;
                case "13":
                //  .value == 13 == Junior Snowboards (3-12yrs Old) == Junior Boots .value == 34
                    noDaysPriceBoot = (equip[34][this.select_days.value]);
                  break;
                case "12":
                //  .value == 12 == Child Skis (3-6yrs old) == Child Boots 3-6 yrs old.value == 18
                    noDaysPriceBoot = (equip[18][this.select_days.value]);
                  break;
                case "11":
                //  .value == 11 == Junior skis (7-12yrs old) == Junior Boots 7-12 yrs old .value == 22
                    noDaysPriceBoot = (equip[22][this.select_days.value]);
                  break;
                case "10":
                //  .value == 10 == Teenager skis (13-16yrs old) == Teenager Boots .value == 33
                    noDaysPriceBoot = (equip[33][this.select_days.value]);
                  break;
                  default:
            }
        }
        linePrice = '&euro;'+([noDaysPriceSki + noDaysPriceBoot]* noPeople);
        //Display the line price
        this.line_price.set('html',linePrice);
        calculateTotalPrice();
    },

    parseEquipmentData: function(e){
        var equip = e;      
        var opt; // temp var to create the option elements
        
        for (var i in equip){
            //do not display boots, only skis boards snowshoes helmets?
            if (equip[i].equipment_kind == 'Ski'){
                // create the option element
                opt = new Element('option', {'value':i});
                // set the display of this option:
                opt.appendText(equip[i].name);
                //add option to the appropriate select box OptGroup
                if (equip[i].equipment_category_id == 3){
                    $('option-adult-skis'+'-'+[this.options.row]).appendChild(opt);
                }
                if (equip[i].equipment_category_id == 2){
                    $('option-junior-skis'+'-'+[this.options.row]).appendChild(opt);
                }
                if (equip[i].equipment_category_id == 9){
                    $('option-snowboards'+'-'+[this.options.row]).appendChild(opt);
                }               
            }
        }
    }
}); //End calc class

var row = 0;
var discount = 0;
var equip;
function startquoteoptions(e){
    equip = e;
    addRow();
    $('another-line-price').addEvent('click', function(){
        addRow();
    });
}

function addRow(){
    new quoteoptionsLinePriceCalc({equip:equip, row:row++})
}

function setDiscountAmount(response){

    amt = eval(response);
    if (amt > 0){
        // success
        $('discountcode').value = 'Save ' + amt + '%';
        discount = amt;
    }else{
        $('discountcode').value = 'Not valid';
        discount = 0;
    }
    calculateTotalPrice();
}

function checkDiscountCode(){
    var req = new Request.JSON({
	    method: 'get',
	    url: '/pages/check_discount_code?c=' + $('discountcode').value,
	    onComplete: function(response) { setDiscountAmount(response); }
    }).send();
}

function calculateTotalPrice(){
    var total_price = 0;
    var total_prices = $$('.lineprice')
    for (var i = total_prices.length - 1; i >= 0; i--){
        total_price +=parseInt(total_prices[i].get('html').substring(1));
    };
    
    // work out 10% discount for 8 or more:
    var discount_people = 8;
    
    if (discount > 0){
        discount_price = Math.round(total_price * ((100-discount)/100))
        $('discount-row').set('html', 'Including your '+discount+'% discount for your code, instead of &euro;'+ total_price +' saving you &euro;' + (total_price-discount_price) + '!');
        $('discount-row').setStyle('display','block');
        $('total-price').set('html','&euro;'+discount_price);
    }else if (total_prices.length >= discount_people){
        discount_price = Math.round(total_price *.9)
        $('discount-row').set('html', 'Including your 10% discount for '+ discount_people +' or more people, instead of &euro;'+ total_price +' saving you &euro;' + (total_price-discount_price) + '!');
        $('discount-row').setStyle('display','block');
        $('total-price').set('html','&euro;'+discount_price);
    }else{
        $('discount-row').setStyle('display','none');
        $('total-price').set('html','&euro;'+total_price);
    }
    
    $('total-people').set('html', total_prices.length + (total_prices.length > 1 ? ' people' : ' person') + ', ');
    
    
}

function loadEquipmentData(){
    var req = new Request.JSON({
	    method: 'get',
	    url: '/pages/equipment.json',
	    onComplete: function(response) { startquoteoptions(response); }
    }).send();
}

//on dom ready...
window.addEvent('domready', function() {
    loadEquipmentData()
    $('discountcheck').addEvent('submit', function(){
        checkDiscountCode();
        return false;
    });
});
