if (LookCorp == undefined) var LookCorp = {}; // Make sure the base namespace exists.

LookCorp.SwitchLauncher = {
    previousPostcode : null, // previously entered postcode (used to detect changed postcode)
    localityListId : 'localityList', // id of the locality list div
    loadingPopup : null,
    localitiesPopup : null,
    callbackUrl : '',
    
    // returns true if a number (or non-character key) was pressed
    filterKeypress : function(ev) {
        ev = ev || window.event;
        var key = String.fromCharCode(ev.charCode ? ev.charCode : ev.keyCode);
        
        // Check for non-character keys like tab, delete, arrows
        // The 8,9 cases are needed by safari
        if (ev.charCode == 0 || ev.charCode == 8 || ev.charCode == 9) return true; 
        
        return /\d/.test(key); // evals true if key is a digit
    },
    
    // called when the postcode changes
    // obj is the postcode element
    postcodeChanged : function(obj, fuel, customerType, customerTypeControlId, usageDdlControlId, fuelTypeControlId) {
        if (obj.value == this.previousPostcode) {
            return;
        }
        
        if (this.loadingPopup == null) {
    	    this.loadingPopup = new LookCorp.PopupQuote('switchLauncherLoading', 'Loading...',
                { width: 200, height: 57, pointerDirection: 'u', pointerPadding: 0, 
                pointerWidth: 0, pointerHeight: 5, cssClass: 'whitePopup', shadowSize: 7 });
    	}
    	
    	if (this.localitiesPopup == null) {
    	    this.localitiesPopup = new LookCorp.PopupQuote('switchLauncherLocalities', 'Results',
    	        { width: 300, height: 145, pointerDirection: 'u', pointerPadding: 0, 
    	        pointerWidth: 0, pointerHeight: 5, cssClass: 'whitePopup', shadowSize: 7 });
    	}
        
        this.smeControlId = customerTypeControlId;
        this.usageControlId = usageDdlControlId;
        this.fuelTypeControlId = fuelTypeControlId;
        this.customerType = customerType;
        
        if (obj.value.length == 4) {
        	// Show loading div
        	this.loadingPopup.positionAt(obj);
        	this.loadingPopup.show();
	        
	        var userControlId2 = obj.id.replace("_txtPostcode", "");
	        
	        // Do callback to fetch localities
	        $.post(this.callbackUrl,
	            { action : 'Launcher_GetSuburbsForPostCode', pc : obj.value, "fuel" : fuel },
	            function(value) {
		           var t = LookCorp.SwitchLauncher;
		           var noRows = 5;
		           var maxLocalityLength = 30;
		           var htmlStart = (value) ? value.indexOf("<") : -1;
		            
		           if (htmlStart >= 0) {
		               t.localitiesPopup.text = value.substr(htmlStart);
		                
		               if (t.localitiesPopup.text.indexOf('class="error"') >= 0) {
		                   var msgLen = t.localitiesPopup.text.length - 27; // 27 chars in span tags.
		                   if (t.localitiesPopup.text.indexOf('id="badPostcodeEmail"') > 0) msgLen -= 140; // Adjust for email entry
                           t.localitiesPopup.width = (msgLen > 100) ? 310 : 200;
                           t.localitiesPopup.height = Math.max((msgLen / (t.localitiesPopup.width / 8)) * 27.5, 60); // Min 2 lines. Line 27.5px.
		               } else {
                           var resultDim = value.substr(0, htmlStart).split(':');
                           if (resultDim.length >= 2) {
                               noRows = resultDim[0];
                               maxLocalityLength = resultDim[1];
                                
                               // calculate dimensions for medium size. Popup will scale depending on text size.
                               var height; 
                               var width;
                               if (noRows <= 5) {
                                   height = (noRows * 25) + 30; // 25px per row + 30 padding
                                   width = Math.max((maxLocalityLength * 9) + 21 + 40, 170); // 9px per letter (bold average) + 21px for go button + 40px padding
                               } else {
                                   height = Math.min((noRows * 26) + 40, 240); // 26px per row + 40px padding
                                   width = Math.max((maxLocalityLength * 9) + 30, 240); // 6px per letter (on average) * 2 columns + 30px padding
                               }
                               t.localitiesPopup.width = width;
                               t.localitiesPopup.height = height;
                           }
                       }
		           } else {
                       t.localitiesPopup.width = 300;
                       t.localitiesPopup.height = 60;
		               t.localitiesPopup.text = '<span class="error">Sorry, there seems to be a problem. Please try again later.</span>';
		           }
		            
		           t.localitiesPopup.positionAt(obj);
		           t.localitiesPopup.show();
		           
		           $('#' + t.localitiesPopup.id + ' a').click(t.localityClick);
		           $('#btnBadPostcodeSubmit').click(t.submitEmailAddress);
		            
		           t.loadingPopup.hide();
		       }
		    );
        } else {
            this.loadingPopup.hide();
            this.localitiesPopup.hide();
        }
        
        this.previousPostcode = obj.value;
    },
    
    smeControlId : null,
    usageControlId : null,
    fuelTypeControlId : null,
    customerType : null,
    
    localityClick : function(event) {
        var t = LookCorp.SwitchLauncher;
        var sme = "";
        var usage = "";
        
        if (t.smeControlId) {
            sme = LookCorp.getRadioValue(t.smeControlId);
            this.href = this.href + "&ct=" + sme;
        } else if (t.customerType) { 
            this.href = this.href + "&ct=" + t.customerType;
        }
        
        if (t.usageControlId) {
            usage = $('#' + t.usageControlId).val();
            this.href = this.href + "&u=" + usage + "&mh=1";
        }
        
        if (t.fuelTypeControlId) {
            var fuelType = $('#' + t.fuelTypeControlId).val();
            this.href = this.href + "&pid=" + fuelType;
            // this.href = this.href.replace('/Electricity/', '/' + fuelType + '/');
        }
    },
    
    submitEmailAddress : function(event) {
        var t = LookCorp.SwitchLauncher;
        var emailAddress = $('#txtBadPostcodeEmail').val();
        var valid = true;
        if (emailAddress.length <= 6) {
            valid = false;
        } else if (emailAddress.indexOf('@') <= 0) {
            valid = false;
        }
        
        if (!valid) {
            alert("Please enter a valid email address");
            event.preventDefault();
            return false;
        }
        
        $.post(t.callbackUrl,
            { action : 'Launcher_SubmitEmail', address : emailAddress },
            function(value) {
                if (value == "OK") {
                    t.localitiesPopup.width = 200;
                    t.localitiesPopup.height = 60;
	                t.localitiesPopup.text = 'Thanks for your interest, your email address has been submitted.';
	                t.localitiesPopup.show();
	                
	                setTimeout(function() { t.localitiesPopup.hide(); }, 4000);
                } else {
                    alert("Sorry, email address could not be sumbitted. Please try again later.");
                }
            });
    }
};

