var Leed = Class.create({
	 osqft : null,
    load : function(obj) {
        $('business_name').observe('change', this.displayValue.bindAsEventListener(this, 'business_display'));
        $('help_business_name').observe('click', this.popupHelp.bindAsEventListener(this));
        
        $('square_footage').observe('blur', this.displayValue.bindAsEventListener(this, 'square_footage_display'));
        $('square_footage').observe('keyup', this.forceNumbers.bindAsEventListener(this));
        $('square_footage').observe('blur', this.forceNumbers.bindAsEventListener(this));
        $('square_footage').observe('blur', this.setSqFt.bindAsEventListener(this));
        $('square_footage').observe('blur', this.checkCoreShell.bindAsEventListener(this,this.calcCandsSqFt));
        $('help_square_footage').observe('click', this.popupHelp.bindAsEventListener(this));
        

        $('usable_square_feet').observe('keyup', this.forceNumbers.bindAsEventListener(this));
        $('usable_square_feet').observe('blur', this.forceNumbers.bindAsEventListener(this));                
        $('help_usable_square_feet').observe('click', this.popupHelp.bindAsEventListener(this));
        
        $('help_cands_square_feet').observe('click', this.popupHelp.bindAsEventListener(this));
        
        $('leed_certification_id').observe('change', this.displayLinkedValue.bindAsEventListener(this, 'certification_display'));
        //$('leed_certification_id').observe('change', this.checkCoreShell.bindAsEventListener(this,this.calcUsableSqFt));
        $('leed_certification_id').observe('change', this.checkCoreShell.bindAsEventListener(this,this.calcCandsSqFt));
        $('leed_certification_id').observe('change', this.getReferenceGuide.bindAsEventListener(this));
        $('leed_certification_id').observe('change', this.showBuildingActivity.bindAsEventListener(this));
        $('help_leed_certification_id').observe('click', this.popupHelp.bindAsEventListener(this));
        
        $('leed_building_id').observe('change', this.displayLinkedValue.bindAsEventListener(this, 'building_display'));
        $('help_leed_building_id').observe('click', this.popupHelp.bindAsEventListener(this));
        
        $('leed_guide_id').observe('change', this.displayLinkedValue.bindAsEventListener(this, 'guide_display'));
        $('leed_guide_id').observe('change', this.getOffsetValues.bindAsEventListener(this));
        $('leed_guide_id').observe('change', this.getPurchaseYears.bindAsEventListener(this));
        $('help_leed_guide_id').observe('click', this.popupHelp.bindAsEventListener(this));
        
        $('offset').observe('change', this.displayLinkedValue.bindAsEventListener(this, 'offset_display'));
        $('help_offset').observe('click', this.popupHelp.bindAsEventListener(this));
        
        $('help_start_date').observe('click', this.popupHelp.bindAsEventListener(this));
        
        $('purchase_years').observe('change', this.displayDates.bindAsEventListener(this));
        $('help_purchase_years').observe('click', this.popupHelp.bindAsEventListener(this));

        $('calculate_button').observe('click', this.calculate.bindAsEventListener(this));
		$('calculate_button').observe('mouseover', this.animateButton.bindAsEventListener(this, 'over'));
		$('calculate_button').observe('mouseout', this.animateButton.bindAsEventListener(this, 'out'));
        /*
        $('purchase_button').observe('click', this.purchase.bindAsEventListener(this));
        $('purchase_button').observe('mouseover', this.animateButton.bindAsEventListener(this, 'over'));
		$('purchase_button').observe('mouseout', this.animateButton.bindAsEventListener(this, 'out'));
        
        $('summary_button').observe('click', this.showSummaryWindow.bindAsEventListener(this));
        $('summary_button').observe('mouseover', this.animateButton.bindAsEventListener(this, 'over'));
		$('summary_button').observe('mouseout', this.animateButton.bindAsEventListener(this, 'out'));
        */
    },
    displayValue : function(event, display_id) {
        var field = Event.element(event);
        var value = field.value;
        if(value == null || value == "") {
            value = "&nbsp;";
        }
        $(display_id).innerHTML = value;
    },
    displayLinkedValue : function(event, display_id) {
        var field = Event.element(event);
        var number = field.value;
        var value = null;
        if(field.id == "") {
            field = field.up();
        }
        $$('#' + field.id + ' option').each(function(option) {
            if(field.value == option.value) {
                value = option.innerHTML;
            }
        })
        if(value == null || value == "") {
            value = "&nbsp;";
        }
        $(display_id).innerHTML = value;
    },
    displayDates : function(event) {
        var field = Event.element(event);
        var years = field.value;
        var startDate = $F('start_date');
        if(startDate!='') {
	        var startYear = startDate.substring(startDate.length - 4, startDate.length);
	        var endYear = parseInt(startYear) + parseInt(years);
	        var endDate = startDate.replace(startYear, endYear);
	        $('duration_display').innerHTML = startDate + " - " + endDate;
        }
    },
    forceNumbers : function(event) {
        var field = Event.element(event);
        var value = new String(field.value);
        var ret = "";
        for(var i = 0; i < value.length; i++) {
            if (value.charCodeAt(i) >= 48 && value.charCodeAt(i) <= 57) {
                ret += value.charAt(i);
            }
        }
        field.value = ret;
    },
    
    setSqFt : function(event) {
    	this.osqft = Number($('square_footage').value);
    },
    
    checkCoreShell : function(event,calcFunc) {
		var value = $('leed_certification_id').value;
		if(value == 5) {
			//get relevant data and perform calculation
			$('usable_square_feet_group').show();
			$('cands_square_feet_group').show();
			$('cands_li').show();

			var cFunc = calcFunc.bindAsEventListener(this);			
			
			$('usable_square_feet').stopObserving('blur',cFunc);
			$('usable_square_feet').observe('blur', cFunc);
			
			$('square_footage').stopObserving('blur',cFunc);
			$('square_footage').observe('blur', cFunc);
			/*
			var tsf = this.osqft;
			if(Number($('usable_square_feet').value)==0) {
				$('usable_square_feet').stopObserving('blur');
				$('usable_square_feet').observe('blur', calcFunc.bindAsEventListener(this,tsf));
				$('usable_square_feet_group').show();
				$('cands_square_feet_group').show();
			} else {
				calcFunc('',tsf);
			}
			*/
		} else {
			//$('square_footage').value = this.osqft;
			$('usable_square_feet_group').hide();
			$('cands_square_feet_group').hide();
			$('cands_li').hide();
			return;
		} 

    },
    

    
    calcUsableSqFt : function(event,tsf) {
    	var usf = Number($('usable_square_feet').value);
		if(tsf == 0) {
			$('square_footage').value = 0;
		} else {
			var cs_per = parseFloat(((tsf-usf)/tsf));
			if(cs_per>0.15){
				$('cands_square_feet').value = tsf - usf;
			} else {
				$('cands_square_feet').value = tsf*0.15;
			}
		}
    },
    
    calcCandsSqFt: function(event) {
    	var tsf = $('square_footage').value;
    	var usf = $('usable_square_feet').value;
		var cs_per = parseFloat(((tsf-usf)/tsf));
		if(cs_per>0.15){
			$('cands_square_feet').value = tsf - usf;
		} else {
			$('cands_square_feet').value = tsf*0.15;
		}
		$('cands_square_feet_display').innerHTML = $('cands_square_feet').value;
    },
    
    getReferenceGuide : function(event) {
        this.clearList('leed_guide_id');
        $('leed_guide_id_group').hide();
        $('guide_display').innerHTML = '&nbsp;';
        $('building_display').innerHTML = '&nbsp'; // if we are hiding the select, then clear the display
        this.clearList('offset');
        $('offset_group').hide();
        $('offset_display').innerHTML = '&nbsp;';
        if($F('leed_certification_id') > 0 ) {
            new Ajax.Request('/leed/ajax/guide',
            {
                method: 'post',
                parameters: {certification_id: $F('leed_certification_id')},
                requestHeaders: {Accept: 'application/json'},
                onSuccess: function(transport){
                    var json = transport.responseText.evalJSON();
                    if(json.length > 0) {
                        json.each(function(item) {
                            var option = new Element('option');
                            option.value = item.id;
                            option.innerHTML = item.version;
                            $('leed_guide_id').insert(option);
                        })
                        $('leed_guide_id_group').show();
                    }
                    
                },
                onFailure: function(){
                    alert('Could not retrieve Reference Guide.');
                }
            });
        }
        return false;
    },
    getOffsetValues : function(event) {
        this.clearList('offset');
        $('offset_group').hide();
        $('offset_display').innerHTML = '&nbsp;';
        if($F('leed_guide_id') > 0) {
            new Ajax.Request('/leed/ajax/offset',
            {
                method: 'post',
                parameters: {id: $F('leed_guide_id')},
                requestHeaders: {Accept: 'application/json'},
                onSuccess: function(transport){
                    var json = transport.responseText.evalJSON();
                    if(json.offset_values) {
                        var values = json.offset_values;
                        for (i=0; i<values.length; i++) {
                            var option = new Element('option');
                            option.value = values[i];
                            option.innerHTML = values[i] + "%";
                            $('offset').insert(option);
                        }
                        $('offset_group').show();
                    }
                },
                onFailure: function(){
                    alert('Could not retrieve Minimum Offset.');
                }
            });
        }
        return false;
    },
    getPurchaseYears : function(event) {
        this.clearList('purchase_years');
        $('purchase_years_group').hide();
        if($F('leed_guide_id') > 0) {
            new Ajax.Request('/leed/ajax/contractlen',
            {
                method: 'post',
                parameters: {id: $F('leed_guide_id')},
                requestHeaders: {Accept: 'application/json'},
                onSuccess: function(transport){
                    var json = transport.responseText.evalJSON();
                    if(json.purchase_years) {
                        var values = json.purchase_years;
                        for (i=0; i<values.length; i++) {
                            var option = new Element('option');
                            option.value = values[i];
                            option.innerHTML = values[i];
                            $('purchase_years').insert(option);
                        }
                        $('purchase_years_group').show();
                    }
                },
                onFailure: function(){
                    alert('Could not retrieve Minimum Offset.');
                }
            });
        }
        return false;
    },
    clearList : function(id) {
        var options = $(id).childElements();
        options.each(function(opt) {
            if(opt != options.first()) {
                opt.remove();
            }
         });
    },
    showBuildingActivity : function(event) {
        if($F('leed_certification_id') != 4 ) { 
            $('leed_building_id_group').show();
            $('leed_building_id').selectedIndex = 0;
        }
        else{
            $('leed_building_id').selectedIndex = 0
            $('leed_building_id_group').hide();
        }
    },
    calculate : function(event) {
        Event.element(event).blur();
        
        new Ajax.Request('/leed/ajax/calculate',
        {
            method: 'post',
            parameters: $('leed_form').serialize(true),	
            requestHeaders: {Accept: 'application/json'},
            onSuccess: function(transport){
                $$('.leed_input_error').each(function(item) {
                    item.removeClassName('leed_input_error');
                });
                $('leed_error_block').hide();
                $('leed_notice_block').hide();
                $('leed_cost_breakdown').innerHTML = '';
                $('total_credits').innerHTML = '';
                //$('total_price').innerHTML = '';
                var json = transport.responseText.evalJSON();                
                if(json.id) {
                    $('id').value = json.id;
                    $('total_credits').innerHTML = json.MWh + ' <span style="font-size: 16px;">(MWhs)</span>';
                    $('credit_contact_info').show();
                    //$('total_price').innerHTML = '$' + json.price;
                    $('leed_cost_breakdown').innerHTML = json.cost_breakdown;
                    $('cost_breakdown_mwh').innerHTML = json.MWh;
                    $('cost_breakdown_total').innerHTML = '$' + json.price;
                    if (json.show_notice_block == true) {
                        $('leed_notice_block').show();
                        //$('total_price').innerHTML = "See Notes";
                        $('leed_cost_breakdown').innerHTML = '&nbsp;';
                    }else{
                        $('leed_notice_block').hide();
                    }
                }
                else {
                    var errors = json.errors;
                    var errorString = '';
                    for (id in errors) {
                        $(id).addClassName('leed_input_error');
                        errorString += errors[id] + ' ';
                    }
                    $('leed_error_block').innerHTML = errorString;
                    $('leed_error_block').show();
                    

                }
               calcTrack('calculate', 'calculate', '');
            },
            onFailure: function(){
                alert('Could not retrieve Calculations.');
            }
            });

    },
	animateButton : function(event, action){
		switch (action) {
			case 'over':
				Event.element(event).style.backgroundImage = 'url(/includes/images/leedcalc/btn_big_rollover.gif)';
				break;
			default:
				Event.element(event).style.backgroundImage = 'url(/includes/images/leedcalc/btn_big.gif)';
				break;
		}
	},
    updateDateDisplay : function(event){
        $('calendar_date_display').innerHTML = $('start_date').value;
        //change the date range in the right pane
        if ($('purchase_years').value != 0) {
            var years = $('purchase_years').value;
            var startDate = $F('start_date');
            var startYear = startDate.substring(startDate.length - 4, startDate.length);
            var endYear = parseInt(startYear) + parseInt(years);
            var endDate = startDate.replace(startYear, endYear);
            $('duration_display').innerHTML = startDate + " - " + endDate;
        }
        
    },
    popupHelp : function(event){
        var helpDiv = 'popup_'+Event.element(event).identify();
        if ($(helpDiv).visible() == true){
            $(helpDiv).hide();
            return;
        }
        var leftVal = Event.pointerX(event)+'px';
        var topVal = Event.pointerY(event)+'px';
        $(helpDiv).setStyle({left: leftVal, top: topVal});
        $(helpDiv).show();
        $(helpDiv).observe('click', function(event){Event.element(event).hide();});
    },
    showSummaryWindow : function(event) {
        Event.element(event).blur();
        if (null == $F('id') || 0 == $F('id')) {
            return;
        }
        
        var url = '/leed_credit_calculator/summary_preview/'+$F('id');
        //calcTrack('leedcalculator', 'viewsummary', '');
        window.open(url);
    },
    purchase : function(event) {
        calcTrack('leed_purchase', 'leed_purchase', '');
        Event.element(event).blur();
        if (null == $F('id') || 0 == $F('id')) {
            return;
        }
        location.href = "/store/product.php?productid=16167&cat=254";
    }
});

function calcTrack(clickaction, clicklabel, clickvalue) {
    pageTracker._trackPageview("/leedcalculator/"+clicklabel); 
}

//Leed = new Leed;
//Event.observe(document, 'dom:loaded', Leed.load.bindAsEventListener(Leed));
