

Ext.override(Ext.data.Connection, {
        
        timeout: 70000,
        handleFailure : function(response, e){
                this.transId = false;
                var options = response.argument.options;
                response.argument = options ? options.argument : null;
                this.fireEvent("requestexception", this, response, options, e);
                Ext.callback(options.failure, options.scope, [response, options]);
                Ext.callback(options.callback, options.scope, [options, false, response]);
                
                var r = "";
                if (!response.responseText || response.responseText == "undefined") {
                        r = "Connection Error: unable to connect to the server to get data. Please try again!";
                } else {
                        r = response.responseText;
                } 
                var win = new Ext.Window({
                        autoHeight: true,
                        width: 600,
                        height: 300,
                        maxHeight: 600,
                        resizable: true,
                        autoScroll: true,
                        style: 'padding-left:5',
                        closable: true,
                        modal: true,
                        title: 'Error!',
                        html: '<p style="color: red;">' + r + '</p>',
                        shadow: true
                });
                win.show(this);
                return null;
        }
});

Ext.form.VTypes.email = function(v){
        return /^([\w]+)(\.[\w]+)*@([\w\-]+\.){1,5}([A-Za-z]){2,4}$/.test(v);
}


Ext.onReady(function() {
        
        Ext.BLANK_IMAGE_URL = '/images/spacer.gif'; 
        
        Ext.QuickTips.init();
        // turn on validation errors beside the field globally
        Ext.form.Field.prototype.msgTarget = 'side';
        
});

Ext.jgs = function(){
        
        var msgCt;
        var navState;
        var nfirst;
        var cmsg = false;       
        
        function createBox(t, s) {
                return ['<div class="msg">',
                '<div class="x-box-tl"><div class="x-box-tr"><div class="x-box-tc"></div></div></div>',
                '<div class="x-box-ml"><div class="x-box-mr"><div class="x-box-mc"><h3>', t, '</h3>', s, '</div></div></div>',
                '<div class="x-box-bl"><div class="x-box-br"><div class="x-box-bc"></div></div></div>',
                '</div>'].join('');
        }
        
        return {
                
                msg : function(title, format, xpos, ypos, delay) {
                        if(!msgCt){
                                msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
                        }
                        if (!xpos) { xpos = 0; }
                        if (!ypos) { ypos = 0; }
                        if (!delay) { delay = 3; }
                        msgCt.alignTo(document, 't-t', [xpos, ypos]);
                        var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
                        var m = Ext.DomHelper.append(msgCt, {html:createBox(title, s)}, true);
                        
                        this.cmsg = Ext.get(m.id);
                        
                        Ext.get(m.id).on({
                                click: function() {
                                        Ext.get(m.id).hide();
                                }
                        });
                        
                        m.slideIn('t').pause(delay).ghost("t", {remove:true});
                },

                msgSide : function(title, format, xpos, ypos, delay) {
                        if(!msgCt){
                                msgCt = Ext.DomHelper.insertFirst(document.body, {id:'msg-div'}, true);
                        }
                        if (!xpos) { xpos = 0; }
                        if (!ypos) { ypos = 0; }
                        if (!delay) { delay = 3; }
                        msgCt.alignTo(document, 'r-r', [xpos, ypos]);
                        var s = String.format.apply(String, Array.prototype.slice.call(arguments, 1));
                        var m = Ext.DomHelper.append(msgCt, {html:createBox(title, s)}, true);
                        m.slideIn('r').pause(delay).ghost("r", {remove:true});
                },
                
                readCookie : function(name) {
                        var nameEQ = name + "=";
                        var ca = document.cookie.split(';');
                        for(var i=0;i < ca.length;i++) {
                                var c = ca[i];
                                while (c.charAt(0)==' ') c = c.substring(1,c.length);
                                if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
                        }
                        return null;
                },
                
                addCommas : function(nStr)
                {
                        nStr += '';
                        x = nStr.split('.');
                        x1 = x[0];
                        x2 = x.length > 1 ? '.' + x[1] : '';
                        var rgx = /(\d+)(\d{3})/;
                        while (rgx.test(x1)) {
                                x1 = x1.replace(rgx, '$1' + ',' + '$2');
                        }
                        return x1 + x2;
                },
                
                phoneFormat : function(phoneNumber)
                {
                        var tempPhone = phoneNumber.replace(/[^0-9xX]/g,"");
                        tempPhone = tempPhone.replace(/[xX]/g,"Ext: ");
                                        
                        var extension = "";
                        if(tempPhone.indexOf("x") > -1)
                        {
                                extension = " "+tempPhone.substr(tempPhone.indexOf("Ext: "));
                                tempPhone = tempPhone.substr(0,tempPhone.indexOf("Ext: "));
                        }
                
                        switch(tempPhone.length)
                        {
                                case(10):
                                        return tempPhone.replace(/(...)(...)(....)/g,"($1) $2-$3")+extension;
                                case(11):
                                        if(tempPhone.substr(0,1) == "1")
                                        {
                                                return tempPhone.substr(1).replace(/(...)(...)(....)/g,"($1) $2-$3")+extension;
                                        }
                                        break;
                                default:
                        }
                
                        return phoneNumber;
                }       
                
    };
    
   
}();



Ext.app.SearchField = Ext.extend(Ext.form.TwinTriggerField, {
        initComponent : function(){
                Ext.app.SearchField.superclass.initComponent.call(this);
                this.on('specialkey', function(f, e){
                        if(e.getKey() == e.ENTER){
                                this.onTrigger2Click();
                        }
                }, this);
        },
        
        validationEvent:false,
        validateOnBlur:false,
        trigger1Class:'x-form-clear-trigger',
        trigger2Class:'x-form-search-trigger',
        hideTrigger1:true,
        width:180,
        hasSearch : false,
        paramName : 'query',

        onTrigger1Click : function(){
                if(this.hasSearch){
                        this.el.dom.value = '';
                        var o = {start: 0};
                        this.triggers[0].hide();
                        this.hasSearch = false;
                }
        },

        onTrigger2Click : function(){
                
                var cp = new Ext.state.CookieProvider({
					expires: new Date(new Date().getTime()+(1000*60*60*24*300)) //300 days
			 });
                
                var v = this.getRawValue();
                if(v.length < 1){
                        this.onTrigger1Click();
                        return;
                }
                var o = {start: 0};
                
                var g = new GClientGeocoder();
          	g.getLocations( v , function(response) {
                        if (!response || response.Status.code != 200) {
                                Ext.MessageBox.alert('Error', 'Code '+response.Status.code+' Error Returned');
                        }else{
                                place = response.Placemark[0];
                                addressinfo = place.AddressDetails;
                                accuracy = addressinfo.Accuracy;
                                if (accuracy === 0) {
                                        Ext.MessageBox.alert('Unable to Locate Address', 'Unable to Locate the Address you provided');
                                }else{
                                       place.Point.coordinates[1], place.Point.coordinates[0]
                                       if (accuracy < 3) {
                                              if (Ext.getCmp('jgs_gmap')) {
                                              	point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
                                              	Ext.getCmp('jgs_gmap').getMap().setCenter( point, 6 );
                                              } else {
                                              	cp.set('lng', place.Point.coordinates[0]);
                                              	cp.set('lat', place.Point.coordinates[1]);
                                              	cp.set('term', v);
                                              	window.location.href = Ext.SEARCH_PAGE;
                                              }
                                         }else{
                                            if (Ext.getCmp('jgs_gmap')) {
                                            	point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
                                            	Ext.getCmp('jgs_gmap').getMap().setCenter( point, 14 );
                                            } else {
                                             	cp.set('lng', place.Point.coordinates[0]);
                                              	cp.set('lat', place.Point.coordinates[1]);
                                              	cp.set('term', v);
                                              	window.location.href = Ext.SEARCH_PAGE;
                                            }
                                      }
                                }
                        }       
          });
                                
                this.hasSearch = true;
                this.triggers[0].show();
        }
});




/*
 * Ext JS Library 2.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 * 
 * http://extjs.com/license
 */

/**
 * @author Shea Frederick
 */

Ext.namespace('Ext.ux');
 
/**
 * This extension adds Google maps functionality to any panel or panel based component (ie: windows).
 * @class ux.GMapPanel
 * @extends Ext.Panel
 */
Ext.ux.GMapPanel = Ext.extend(Ext.Panel, {
    
        // private
    initComponent : function(){
        
        var defConfig = {
            plain: true,
            zoomLevel: 3,
            yaw: 180,
            pitch: 0,
            zoom: 0,
            gmapType: 'map',
            border: false
        };
        
        this.loaded = false;
        this.bounds = false;
        this.sv_lat = false;
        this.sv_lng = false;
        this.sv_yaw = false;
        this.sv_pitch = false;
        this.sv_zoom = false;
        this.mc  = false;
        
        Ext.applyIf(this,defConfig);
        
        Ext.ux.GMapPanel.superclass.initComponent.call(this);        

    },
    // private
    afterRender : function(){
        
        var wh = this.ownerCt.getSize();
        Ext.applyIf(this, wh);
        
        Ext.ux.GMapPanel.superclass.afterRender.call(this);    
        
        if (this.gmapType === 'map'){
            this.gmap = new GMap2(this.body.dom);
            this.bounds = new GLatLngBounds();
            this.gmap.setMapType(G_HYBRID_MAP);
        }
        
        if (this.gmapType === 'panorama') {
                        this.gmap = new GStreetviewPanorama(this.body.dom);
                        GEvent.bind(this.gmap, "error", this, function(c) {
                                this.handlePanoErrors(c);
                        });
                        GEvent.bind(this.gmap, "yawchanged", this, function(y) {
                                this.sv_yaw = y;
                        });
                        GEvent.bind(this.gmap, "pitchchanged", this, function(p) {
                                this.sv_pitch = p;
                        });
                        GEvent.bind(this.gmap, "zoomchanged", this, function(z) {
                                this.sv_zoom = z;
                        });
                        GEvent.bind(this.gmap, "initialized", this, function(l) {
                                this.sv_lat = l.latlng.lat();
                                this.sv_lng = l.latlng.lng();
                        });
        }

        if (typeof this.addControl == 'object' && this.gmapType === 'map') {
            this.getMap().addControl(this.addControl);
        }
        
        this.addMapControls();
        this.addOptions();
        
        
        if (typeof this.setCenter === 'object') {
            if (typeof this.setCenter.geoCodeAddr === 'string'){
                this.geoCodeLookup(this.setCenter.geoCodeAddr);
            }else{
                if (this.gmapType === 'map'){
                    var point = new GLatLng(this.setCenter.lat,this.setCenter.lng);
                    this.getMap().setCenter(point, this.zoomLevel);    
                }
                if (typeof this.setCenter.marker === 'object' && typeof point === 'object'){
                    this.addMarker(point,this.setCenter.marker,this.setCenter.marker.clear);
                }
            }
            if (this.gmapType === 'panorama'){
                if (this.setCenter.lat) {
                        this.getMap().setLocationAndPOV(new GLatLng(this.setCenter.lat,this.setCenter.lng), {yaw: this.setCenter.yaw, pitch: this.setCenter.pitch, zoom: this.setCenter.zoom});
                }
                  }
        }

        GEvent.bind(this.gmap, 'load', this, function(){
            this.onMapReady();
        });

    },
    
    handlePanoErrors: function(errorCode) {
                
                if (errorCode == 603) {
                        Ext.jgs.msg('Alert!', "Error: Flash doesn't appear to be supported by your browser");
                        return;
                } else if (errorCode == 600) {
                        
                        if (Ext.getCmp('jgs_sv')) {
                                this.sv_mask = new Ext.LoadMask(Ext.getCmp('jgs_sv').getEl(), {msg: 'Currently Google does not offer a StreetView for this property.',msgCls:'x-mask-loading-no-ani'});
                                this.sv_mask.show();
                        }
                        
                }
        },
    
    // private
    hasCluster : function() {
           
           this.mc = true;
           
    },
    
    // private
    onMapReady : function(){
        
        this.loaded = true;
        this.addMarkers(this.markers);
        
    },
    // private
    onResize : function(w, h){
        
        // check for the existance of the google map in case the onResize fires too early
        if (typeof this.getMap() == 'object') {
            this.getMap().checkResize();
        }
        
        Ext.ux.GMapPanel.superclass.onResize.call(this, w, h);

    },
    // private
    setSize : function(width, height, animate){
        
        // check for the existance of the google map in case setSize is called too early
        if (typeof this.getMap() == 'object') {
            this.getMap().checkResize();
        }
        
        Ext.ux.GMapPanel.superclass.setSize.call(this, width, height, animate);
        
    },
    /**
     * Returns the current google map
     * @return {GMap} this
     */
    getMap : function(){
        
        return this.gmap;
        
    },
    /**
     * Returns the maps center as a GLatLng object
     * @return {GLatLng} this
     */
    getCenter : function(){
        
        return this.getMap().getCenter();
        
    },
    /**
     * Returns the maps center as a simple object
     * @return {Object} has lat and lng properties only
     */
    getCenterLatLng : function(){
        
        var ll = this.getCenter();
        return {lat: ll.lat(), lng: ll.lng()};
        
    },
    /**
     * Creates markers from the array that is passed in. Each marker must consist of at least lat and lng properties.
     * @param {Array} an array of marker objects
     */
    addMarkers : function(markers) {
        
        if (Ext.isArray(markers)){
            for (var i = 0; i < markers.length; i++) {
                var mkr_point = new GLatLng(markers[i].lat,markers[i].lng);
                this.addMarker(mkr_point,markers[i].marker,false,markers[i].setCenter, markers[i].listeners);
            }
        }
        
    },
    /**
     * Creates a single marker.
     * @param {Object} a GLatLng point
     * @param {Object} a marker object consisting of at least lat and lng
     * @param {Boolean} clear other markers before creating this marker
     * @param {Boolean} true to center the map on this marker
     * @param {Object} a listeners config
     */
    addMarker : function(point, marker, clear, center, listeners, id){
        
        //if (!marker) {
        //      Ext.applyIf(marker,G_DEFAULT_ICON);
        //}
        
        if (clear === true){
            this.getMap().clearOverlays();
        }
        if (center === true) {
            this.getMap().setCenter(point, this.zoomLevel);
        }
                
           var mark = new GMarker(point,marker);
           
        mark.id = id;
        if (typeof listeners === 'object'){
            for (evt in listeners) {
                GEvent.bind(mark, evt, this, listeners[evt]);
            }
        }
        
        if (!this.mc) {
                this.getMap().addOverlay(mark);
                this.bounds.extend(point);
        }
        
        return mark;

    },
    // private
    addMapControls : function(){
        
        if (this.gmapType === 'map') {
            if (Ext.isArray(this.mapControls)) {
                for(i=0;i<this.mapControls.length;i++){
                    this.addMapControl(this.mapControls[i]);
                }
            }else if(typeof this.mapControls === 'string'){
                this.addMapControl(this.mapControls);
            }else if(typeof this.mapControls === 'object'){
                this.getMap().addControl(this.mapControls);
            }
        }
        
    },
    /**
     * Adds a GMap control to the map.
     * @param {String} a string representation of the control to be instantiated.
     */
    addMapControl : function(mc){
        
        var mcf = window[mc];
        if (typeof mcf === 'function') {
            this.getMap().addControl(new mcf());
        }    
        
    },
    // private
    addOptions : function(){
        
        if (Ext.isArray(this.mapConfOpts)) {
            var mc;
            for(i=0;i<this.mapConfOpts.length;i++){
                this.addOption(this.mapConfOpts[i]);
            }
        }else if(typeof this.mapConfOpts === 'string'){
            this.addOption(this.mapConfOpts);
        }        
        
    },
    /**
     * Adds a GMap option to the map.
     * @param {String} a string representation of the option to be instantiated.
     */
    addOption : function(mc){
        
        var mcf = this.getMap()[mc];
        if (typeof mcf === 'function') {
            this.getMap()[mc]();
        }    
        
    },
    /**
     * Adds a marker to the map based on an address string (ie: "123 Fake Street, Springfield, NA, 12345, USA").
     * @param {String} the address to lookup
     */
    geoCodeLookup : function(addr) {
        
        this.geocoder = new GClientGeocoder();
        this.geocoder.getLocations(addr, this.addAddressToMap.createDelegate(this));
        
    },
    // private
    addAddressToMap : function(response) {
        
        if (!response || response.Status.code != 200) {
            Ext.MessageBox.alert('Error', 'Code '+response.Status.code+' Error Returned');
        }else{
            place = response.Placemark[0];
            addressinfo = place.AddressDetails;
            accuracy = addressinfo.Accuracy;
            if (accuracy === 0) {
                Ext.MessageBox.alert('Unable to Locate Address', 'Unable to Locate the Address you provided');
            }else{
                if (accuracy < 5) {
                    Ext.MessageBox.alert('Address Accuracy', 'The address provided has a low accuracy.<br><br>Level '+accuracy+' Accuracy (8 = Exact Match, 1 = Vague Match)');
                }else{
                    point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
                    if (typeof this.setCenter.marker === 'object' && typeof point === 'object'){
                        this.centerMarker = this.addMarker(point,this.setCenter.marker,this.setCenter.marker.clear,true, this.setCenter.listeners);
                    }
                }
            }
        }
        
    },
    
    highlightMarker: function(marker) {
                
                var markerPoint = marker.getPoint();
                
                var polyPoints = Array();
                
                if (this.highlightCircle) {
                        this.getMap().removeOverlay(this.highlightCircle);
                }
                
                var mapNormalProj = G_NORMAL_MAP.getProjection();
                var mapZoom = this.getMap().getZoom();
                var clickedPixel = mapNormalProj.fromLatLngToPixel(markerPoint, mapZoom);
                
                var polySmallRadius = 35;
                
                var polyNumSides = 20;
                var polySideLength = 18;
                
                for (var a = 0; a<(polyNumSides+1); a++) {
                        var aRad = polySideLength*a*(Math.PI/180);
                        var polyRadius = polySmallRadius; 
                        var pixelX = clickedPixel.x + polyRadius * Math.cos(aRad);
                        var pixelY = clickedPixel.y + polyRadius * Math.sin(aRad);
                        var polyPixel = new GPoint(pixelX,pixelY);
                        var polyPoint = mapNormalProj.fromPixelToLatLng(polyPixel,mapZoom);
                        polyPoints.push(polyPoint);
                }
                
                // Using GPolygon(points,  strokeColor?,  strokeWeight?,  strokeOpacity?,  fillColor?,  fillOpacity?)
                this.highlightCircle = new GPolygon(polyPoints,"#000000",2,0.0,"#F6971D",.5);
                this.getMap().addOverlay(this.highlightCircle);
                                
        },
        
        setSVLocation: function(sv_lat,sv_lng,sv_yaw,sv_pitch,sv_zoom) {
                
                if (this.sv_mask) {
                        this.sv_mask.hide();
                        //this.gmap.show();
                }
                
                
                
                var svpoint = new GLatLng(sv_lat,sv_lng);
                
                if (sv_yaw && sv_pitch && sv_pitch) {
                        this.gmap.setLocationAndPOV(svpoint,{
                                yaw:            sv_yaw,
                                pitch:  sv_pitch,
                                zoom:   sv_zoom
                        });
                } else {
                        this.gmap.setLocationAndPOV(svpoint);
                }
                
                this.currentYaw         = sv_yaw;
                this.currentPitch       = sv_pitch;
                
                this.svMeasure = 0;
                this.svDir = false;
                if (this.svRunner) {
                        this.svRunner.stop(this.svCheck);
                }
                if (sv_yaw) {
                        this.svCheck = {
                                        scope: this,
                                        run: function(){
                                                this.spiral(sv_yaw,sv_pitch)
                                        },
                                        interval: 100
                                }
                        this.svRunner = new Ext.util.TaskRunner();
                        this.svRunner.start(this.svCheck);
                }
                
        },
        
        spiral: function(sv_yaw,sv_pitch) {
                if (!this.svDir && this.svMeasure <= 20) {
                        this.currentYaw += 2;
                        this.svMeasure++;
                } else if (!this.svDir && this.svMeasure > 20) {
                        this.svDir = 1;
                } else if (this.svDir == 1 && this.svMeasure >= -20) {
                        this.currentYaw -= 2;
                        this.svMeasure--;
                } else if (this.svDir == 1 && this.svMeasure < -20) {
                        this.svDir = 2;
                } else if (this.svDir == 2 && this.svMeasure < 0) {
                        this.currentYaw += 2;
                        this.svMeasure++;
                } else if (this.svDir == 2 && this.svMeasure >= 0) {
                        this.svRunner.stop(this.svCheck);
                        this.svMeasure = 0;
                        this.svDir = false;
                        this.gmap.panTo({yaw: sv_yaw, pitch: sv_pitch});
                }
                this.gmap.panTo({yaw:this.currentYaw, pitch: this.currentPitch});
        }
 
});

Ext.reg('gmappanel',Ext.ux.GMapPanel);



