﻿//==========================================================================
//      Operating Cost Estimate
//      Copyright (c) Wrightsoft Corporation 2006.  All Rights Reserved.
//      $Id: ParameterBehavior.js 87 2007-01-18 11:38:01Z liup $
//==========================================================================

Type.registerNamespace('Wrightsoft.OCE.Web.AjaxControls');

// Create an alias for the namespace to save some chars each time it's used since
// this is a very long script and will take awhile to download
var $OCE = Wrightsoft.OCE.Web.AjaxControls;

$OCE.ParameterBehavior = function(element) {
    $OCE.ParameterBehavior.initializeBase(this, [element]);

    // Custom properties
    this._Name = "";
    this._Title = "";
    this._DefaultValue = 0;
    this._MinimalValue = null;
    this._MaximalValue = null;
    this._RegExp = null;
    // WebServides properties
    this._ServicePath = null;
    this._GetAllInvestmentMethod = null;
    this._PressEnter = false;

    // Event Handler
    this._keypressHandler = null;
    this._changeHandler = null;
    
    this._filterType =  $OCE.FilterTypes.Custom;
    this._validChars = null;
    
    this.charTypes = new Object(); 
    
    this.charTypes["LowercaseLetters"] = "abcdefghijklmnopqrstuvwxyz";
    this.charTypes["UppercaseLetters"] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    this.charTypes["Numbers"]          = "0123456789";
    this._ProgressIndicatorID = "ProgressIndicator";
    this._ProgressIndicatorElement = null;
}

$OCE.ParameterBehavior.prototype = {
    initialize : function() {
        $OCE.ParameterBehavior.callBaseMethod(this, 'initialize');
        Manager.registerParameter(this);
        
        var e = this.get_element();
        this._ProgressIndicatorElement = $get(this._ProgressIndicatorID);
        Sys.Debug.assert(this._ProgressIndicatorElement != null, "Failed to find Progress Indicator element'" + this._ProgressIndicatorID + "'");

        // Attach keypress handler to every Parameters
        this._keypressHandler = Function.createDelegate(this, this._onkeypress);
        $addHandler(e, "keypress", this._keypressHandler);

        // Attach change handler to every Parameters
        this._changeHandler = Function.createDelegate(this, this._onchange);
        $addHandler(e, "change", this._changeHandler);
        
        // Load Cookie values
        var cookievalue = Manager.Cookie(this._Name);
        if (!cookievalue || "" == cookievalue) {
            e.value = this._DefaultValue;
        } else {
            e.value = cookievalue;
        }
    },

    dispose : function() {
        var e = this.get_element();

        // Detach keypress handler from every Parameters
        if (this._keypressHandler) {
            $removeHandler(e, "keypress", this._keypressHandler);
            this._keypressHandler = null;
        }

        // Detach change handler from every Parameters
        if (this._changeHandler) {
            $removeHandler(e, "change", this._changeHandler);
            this._changeHandler = null;
        }
        
        $OCE.ParameterBehavior.callBaseMethod(this, 'dispose');
    },
        
    _getValidChars : function() {
        if (this._validChars) return this._validChars;
        
        this._validChars = "";
        
        for (type in this.charTypes) {
            var filterType = $OCE.FilterTypes.toString(this._filterType);
            
            if (filterType.indexOf(type) != -1) {   
                this._validChars += this.charTypes[type];
            }
        }

        return this._validChars;    
    },

    _onkeypress : function(evt) {
    
        // This handler will only get called for valid characters in IE, we use keyCode
        //
        // In FireFox, this will be called for all key presses, with charCode/which
        // being set for keys we should filter (e.g. the chars) and keyCode being
        // set for all other keys.
        //
        // scanCode = event.charCode
        //
        // In Safari, charCode, which, and keyCode will all be filled with the same value,
        // as well as keyIdentifier, which has the string representation either as "end" or "U+00000008"
        //
        // 1) Check for ctrl/alt/meta -> bail if true
        // 2) Check for keyIdentifier.startsWith("U+") -> bail if false
        // 3) Check keyCode < 0x20 -> bail
        // 4) Special case Delete (63272) -> bail
        
        var scanCode;
        
        
        if (evt.rawEvent.keyIdentifier) {
            
            // Safari
            // Note (Garbin): used the underlying rawEvent insted of the DomEvent instance.
            if (evt.rawEvent.ctrlKey || evt.rawEvent.altKey || evt.rawEvent.metaKey) {
                return;
            }
            
            if (evt.rawEvent.keyIdentifier.substring(0,2) != "U+") {
                return;
            }
            
            scanCode = evt.rawEvent.charCode; 
            
            if (scanCode == 63272 /* Delete */) {
                return;
            }
        }  
        else {
            scanCode = evt.charCode;
        }  

        if (scanCode == 13) {
            this._PressEnter = true;
            this._getInvestment();
            return false;
        }
        this._PressEnter = false;

        if (scanCode && scanCode >= 0x2F /* space */ ) {
            var c = String.fromCharCode(scanCode);                        
            
            if(!this._processKey(c)) {
                evt.preventDefault();
            }
        }
    },
    
    _processKey : function(key) {
     
        // Allow anything that's not a printable character,
        // e.g. backspace, arrows, etc.  Everything above 32
        // should be considered allowed, as it may be Unicode, etc.
        //
        var filter = this._getValidChars();
        
        // return true if we should accept the character.
        return (!filter || filter.length == 0 || filter.indexOf(key) != -1);
    },
    
    _onchange : function() {
        
      var text = this.get_element().value;
      var i = 0;
      var chars = this._getValidChars()
      while (i < text.length) {
        if (chars.indexOf(text.substring(i, i+1)) == -1) {
          text = text.substring(0, i) + text.substring(i+1, text.length);
        } else {
          i++;
        }
      }
      
      this.get_element().value = text;
      
      if (!this._PressEnter)
        this._getInvestment();
    },
    
    _getInvestment : function() {
        if (!Manager.checkParameters())
            return false;
        this._saveValue();
        
        // get each investment
        inv0 = Manager.getInvestment(0);
        Sys.Debug.assert(inv0 != null, "Failed to find Base System");
        
        inv1 = Manager.getInvestment(1);
        Sys.Debug.assert(inv1 != null, "Failed to Investment 1 System");
        
        inv2 = Manager.getInvestment(2);
        Sys.Debug.assert(inv2 != null, "Failed to Investment 2 System");
        
        inv3 = Manager.getInvestment(3);
        Sys.Debug.assert(inv3 != null, "Failed to Investment 3 System");
        
        if ("heatload" == this._Name.toLowerCase() ||
            "coolload" == this._Name.toLowerCase() ||
            "zipcode" == this._Name.toLowerCase()) {
            // Reselect the units
            inv0._setSystemTypeOptions();
            inv1._setSystemTypeOptions();
            inv2._setSystemTypeOptions();
            inv3._setSystemTypeOptions();
        } else {
            // Recalculation all investments
            var invs = [inv0, inv1, inv2, inv3];
            this._setIndicatorState($OCE.IndicatorTypes.Busy);
            if (this._ServicePath && this._GetAllInvestmentMethod) {
                Sys.Net.WebServiceProxy.invoke(
                    this._ServicePath, this._GetAllInvestmentMethod, false,
                    { systemtype0:inv0._selectedSystemType, outdoorunit0:inv0._selectedOutdoorUnit, indoorunit0:inv0._selectedIndoorUnit, cfcool0:inv0._ContinuousFanClgElement.checked, cfheat0:inv0._ContinuousFanHtgElement.checked,
                      systemtype1:inv1._selectedSystemType, outdoorunit1:inv1._selectedOutdoorUnit, indoorunit1:inv1._selectedIndoorUnit, cfcool1:inv1._ContinuousFanClgElement.checked, cfheat1:inv1._ContinuousFanHtgElement.checked,
                      systemtype2:inv2._selectedSystemType, outdoorunit2:inv2._selectedOutdoorUnit, indoorunit2:inv2._selectedIndoorUnit, cfcool2:inv2._ContinuousFanClgElement.checked, cfheat2:inv2._ContinuousFanHtgElement.checked,
                      systemtype3:inv3._selectedSystemType, outdoorunit3:inv3._selectedOutdoorUnit, indoorunit3:inv3._selectedIndoorUnit, cfcool3:inv3._ContinuousFanClgElement.checked, cfheat3:inv3._ContinuousFanHtgElement.checked,
                      heatload:Manager.get_HeatLoadValue(),
                      coolload:Manager.get_CoolLoadValue(),
                      zipcode:Manager.get_ZipCodeValue(),
                      natgascost:Manager.get_NatCostValue(),
                      lpgascost:Manager.get_LPCostValue(),
                      oilcost:Manager.get_OilCostValue(),
                      sumelecost:Manager.get_SumEleCostValue(),
                      winelecost:Manager.get_WinEleCostValue(),
                      gastype:Manager.get_GasType()},
                    Function.createDelegate(this, this._onComplete),
                    Function.createDelegate(this, this._onError),
                    invs);
            }
        }
        
        return true;
    },
    
    _setIndicatorState : function(state, id) {
        if ($OCE.IndicatorTypes.Error == state) {
            this._ProgressIndicatorElement.style.background = "red none repeat scroll 0%";
        } else if ($OCE.IndicatorTypes.Busy == state) {            
            this._ProgressIndicatorElement.style.background = "yellow none repeat scroll 0%";
        } else if ($OCE.IndicatorTypes.Ready == state) {
            this._ProgressIndicatorElement.style.background = "lime none repeat scroll 0%";
        } else {
            this._ProgressIndicatorElement.style.background = "lime none repeat scroll 0%";
        }        
    },
    
    _onComplete : function(result, invs, methodName) {
        if (null == result) {
            this._setIndicatorState($OCE.IndicatorTypes.Error);
        } else {
            this._setIndicatorState($OCE.IndicatorTypes.Ready);
        }

        if (methodName == this._GetAllInvestmentMethod) {
            this._PressEnter = false;
            // Init each Investment's values
            if (null == result) {
                for (i = 0; i < 4; i++) {
                    if (invs[i])
                        invs[i]._setInvestmentError("occur error");
                }
            } else {
                for (i = 0; i < 4; i++) {
                    if (invs[i])
                        invs[i]._setInvestmentValues(result[i]);
                }
            }
        }
        if (this.showprint) {
            this.showprint();
            this.showprint = null;
        }
    },

    _onError : function(webServiceError, invs, methodName) {
        // Indicate failure
        this._setIndicatorState($OCE.IndicatorTypes.Error);
        if (methodName == this._GetAllInvestmentMethod) {
            this._PressEnter = false;
            for (i = 0; i < 4; i++) {
                if (invs[i]) {
                    if (webServiceError.get_timedOut()) {
                        invs[i]._setInvestmentError("timeout");
                    } else {
                        invs[i]._setInvestmentError("occus error");
                    }
                }
            }
        }
    },
    
    _saveValue : function() {
        // Save Parameters to cookie
        Manager.Cookie(this.get_Name(), this.get_Value(), {expires: 365});
    },
    
    _validateRegExp : function(value) {
        if (!this._RegExp) {
            return true;
        } else {
	        var re = new RegExp(this._RegExp);
	        return (value.match(re) != null);
        }	    
    },
    
    _validateRange : function(value) {
        if (null == this._MinimalValue || null == this._MaximalValue)
            return true;
        else
            return (this._MinimalValue <= eval(value) && eval(value) <= this._MaximalValue);
    },


    //
    // Property get/set methods
    //
    get_Value : function() {
        return this.get_element().value;
    },
    set_Value : function(value) {
        this.get_element().value = value;
    },

    get_Name : function() {
        return this._Name;
    },
    set_Name : function(value) {
        if (this._Name != value) {
            this._Name = value;
            this.raisePropertyChanged('Name');
        }
    },

    get_Title : function() {
        return this._Title;
    },
    set_Title : function(value) {
        if (this._Title != value) {
            this._Title = value;
            this.raisePropertyChanged('Title');
        }
    },
    
    get_DefaultValue : function() {
        return this._DefaultValue;
    },
    set_DefaultValue : function(value) {
        if (this._DefaultValue != value) {
            this._DefaultValue = value;
            this.raisePropertyChanged('DefaultValue');
        }
    },
    
    get_MinimalValue : function() {
        return this._MinimalValue;
    },
    set_MinimalValue : function(value) {
        if (this._MinimalValue != value) {
            this._MinimalValue = value;
            this.raisePropertyChanged('MinimalValue');
        }
    },
    
    get_MaximalValue : function() {
        return this._MaximalValue;
    },
    set_MaximalValue : function(value) {
        if (this._MaximalValue != value) {
            this._MaximalValue = value;
            this.raisePropertyChanged('MaximalValue');
        }
    },
    
    get_RegExp : function() {
        return this._RegExp;
    },
    set_RegExp : function(value) {
        if (this._RegExp != value) {
            this._RegExp = value;
            this.raisePropertyChanged('RegExp');
        }
    },
    
    // WebServides properties
    get_ServicePath : function() {
        return this._ServicePath;
    },
    set_ServicePath : function(value) {
        if (this._ServicePath != value) {
            this._ServicePath = value;
            this.raisePropertyChanged('ServicePath');
        }
    },
        
    get_GetAllInvestmentMethod : function() {
        return this._GetAllInvestmentMethod;
    },
    set_GetAllInvestmentMethod : function(value) {
        if (this._GetAllInvestmentMethod != value) {
            this._GetAllInvestmentMethod = value;
            this.raisePropertyChanged('GetAllInvestmentMethod');
        }
    },

    get_ValidChars : function() {
        return this.charTypes["Custom"];
    },        
    set_ValidChars : function(value) {
        if (this._validChars != null || this.charTypes["Custom"] != value) {
            this.charTypes["Custom"] = value;
            this._validChars = null;
            this.raisePropertyChanged('ValidChars');
        }
    },
        
    get_FilterType : function() {
        return this._filterType;
    },        
    set_FilterType : function(value) {
        if (this._validChars != null || this._filterType != value) {
            this._filterType = value;
            this._validChars = null;
            this.raisePropertyChanged('FilterType');
        }
    },
    
    CheckIfValid : function(noalert) {
        // Checks if the value is valid
        var e = this.get_element();
        if(e.value == "") {
            if (!noalert) {
                alert(this._Title + " must be entered");
                e.focus();
            }
            return false;
        } else if (!this._validateRegExp(e.value)) {
            if (!noalert) {
                alert(this._Title + " is not valid");
                e.focus();
            }
            return false;
        } else if (!this._validateRange(e.value)) {
            if (!noalert) {
                alert(this._Title + " should be in the range: " + this._MinimalValue + " ~ " + this._MaximalValue);
                e.focus();
            }
            return false;
        }
        return true;
    }
}

$OCE.ParameterBehavior.registerClass('Wrightsoft.OCE.Web.AjaxControls.ParameterBehavior', AjaxControlToolkit.BehaviorBase);

$OCE.FilterTypes = function() {
    throw Error.invalidOperation();
}
$OCE.FilterTypes.prototype = {
    Custom           :  0x1,
    Numbers          :  0x2,
    UppercaseLetters :  0x4,
    LowercaseLetters :  0x8
}
$OCE.FilterTypes.registerEnum('Wrightsoft.OCE.Web.AjaxControls.FilterTypes', true);
if(typeof(Sys)!=='undefined')Sys.Application.notifyScriptLoaded();