Ext.Ajax.defaultHeaders = {
    "Content-Type" : "application/json"
};

Ext.data.proxy.Ajax.prototype.actionMethods['read'] = 'POST';

//  Declare IO namespace
io = {};

//  Spinner singleton class
io.Spinner = function(){
    var mask;
    return {
        init: function(){
			mask = Ext.getBody();
        },

        showSpinner: function() {
            if(mask){
                var m = mask.mask('Please wait...', 'x-mask-loading');
                m.setHeight(Ext.core.Element.getDocumentHeight()); 
            }
        },

        hideSpinner: function() {
            if(mask){
                mask.unmask();
            }
        }        
    };
}();

io.ApplicationManager = function(config) {
    var s = {};
    Ext.apply(s, config);

    Ext.apply(s, new Ext.util.Observable, {
        tourPopupWindow: null,
        
        languageMap: {
			'en' : [0, 0],
			'de' : [4, 0],
			'fr' : [4, 0],
			'cn' : [2, 42],
			'jp' : [2, 14],
			'nl' : [4, 18],
			'es' : [0, 0]
        },
        
        init: function() {
 			this.templates = {};
 			
 			var ua = navigator.userAgent.toLowerCase();
 			Ext.isIE9 = /msie 9/.test(ua);
 			if(Ext.isIE9){
				var bd = document.body || document.getElementsByTagName('body')[0];
				bd.className = bd.className.replace('ie6', 'ie9');
			}
 			
			Ext.apply(Ext.form.VTypes, {
				phoneNumber:  function(v) {
					return /^\+?[-0-9 ]{6,}$/.test(v);
				},
				phoneNumberText: 'invalid phone number',
				phoneNumberMask: /[+ \d-]/
			}); 
			
			switch(window.pageType){
				case 'report':
					this.initCentreResults();
					this.initReportControls();
					this.initSurvey();
					break;
				case 'centres':
				case 'results':
					this.initCentreResults();
					this.initSidebar();
					if(window.version == 2){
						this.attachSidebar();
						this.getLocalConsultant();

						if(window.pageType == 'results'){
                            this.getSearchRefine();
							this.attachExtraResults();
							this.attachSortPricing();
						}
						if(window.pageType == 'centres'){
							this.attachReview();
							this.attachRelated();
							
							var sns = Ext.get('start-new-search');
							if(sns){
								sns.child('a').dom.href = window.siteBaseUrl;
							}
							var active = 0;
							Ext.each(window.centreOptions, function(o){
								if(o){
									return false;
								}
								active++;
							});
							var tab = document.location.href.split('#')[1];
							if(tab == 'map'){
								active = 2;
							}
							
							this.attachTabs({ id: 'menu', vis: window.centreOptions, active: active });
						}
					}
					
					break;
				case 'click2call':
					this.sidebarAnchor = document.getElementById('sidebarAnchor');
					this.attachC2CSidebar();
					break;
				case 'virtual':
					this.sidebarAnchor = document.getElementById('sidebarAnchor');
					this.attachVirtualSidebar();
					break;
				case 'default':
					if(window.version == 2){
						this.initDefault();
					}
					break;
				case 'contact-us':
					if(window.version == 2){
						this.initContactUs();
					}
					break;
			}
			this.attachLanguages();
			this.attachLeftMenuSearch();
			this.attachLogin();
			
			//	Try qtip
			var arr = Ext.query('*[extqtip]');
			Ext.each(arr, function(i){
				i.setAttribute("ext:qtip", i.getAttribute('extqtip'));
				i.setAttribute("ext:qtitle", '');
			});
        },
        
        attachC2CSidebar: function(){
			var sidebarAnchor = document.getElementById('sidebarAnchor');

			var sl = Ext.fly('submit-link');
			if(sl){
				sl.on('click', function(e){ 
					e.stopEvent(); 
					
					this.createC2CReport(false); 
					return false; 
				}, this);
			}
			
			var form = Ext.query('#form', sidebarAnchor)[0];

			//Ext.get('form').mask('', 'x-mask-loading');
			
			var userName = Ext.query('#user-name', form)[0];
			var userCountry = Ext.query('#user-country', form)[0];
			var userPhone = Ext.query('#user-telephone', form)[0];
			var userLocation = Ext.query('#user-location', form)[0];
			
			this.sidebarControls = {
				sidebarAnchor: this.sidebarAnchor,
				
				userName: new Ext.form.TextField({
						width: 120,
						hideLabel: true,
						allowBlank: false,
						blankText: userName.getAttribute('io:blankText'),
						renderTo: userName,
						msgTarget: 'title'
					}),
				userCountry: new Ext.form.ComboBox ({
						store: new Ext.data.JsonStore({fields: ['id', 'country']}),
						hideLabel: true,
						width: 120,
						queryMode: 'local',
						emptyText: userCountry.getAttribute('io:emptyText'),
						blankText: userCountry.getAttribute('io:blankText'),
						allowBlank: false,
						valueField: 'id',
						displayField: 'country',
						forceSelection: true,
						triggerAction: 'all',
						editable: false,
						renderTo: userCountry,
						msgTarget: 'title',
						matchFieldWidth: false,
						listConfig:{
							width:200
						},
						listeners:{
							'select': function(combo, rec){
								this.getSidebarCountryData(rec[0].data.id);
							},
							scope: this
						}
					}),
				userPhone: new Ext.form.TextField({
						width: 120,
						hideLabel: true,
						allowBlank: false,
						blankText: userPhone.getAttribute('io:blankText'),
						renderTo: userPhone,
						vtype: 'phoneNumber',
						vtypeText: userPhone.getAttribute('io:vtypeText'),
						msgTarget: 'title'
					}),
				userLocation: new Ext.form.ComboBox({
					width: 120,
					matchFieldWidth: false,
					listConfig:{
						width:300,
						height: 200
					},
					hideTrigger: true,
					hideLabel: true,
					queryMode: 'remote',
					editable:true,
					minChars: 3,
					queryDelay: 500,
					valueField: 'areaid',
					displayField: 'areatitle',
					store: new Ext.data.JsonStore({
						fields: ['areaid', 'areaname', 'areatype', 'areatitle', 'countryid', 'regionid', 'cityid', 'districtid', 'latitude', 'longitude'],
						proxy: new Ext.data.AjaxProxy({
							startParam: null,
							limitParam: null,
							pageParam: null,
							url: wsRefs.iows + '/GetSearchSuggestions',
							buildUrl: function(request){
								var r = Ext.data.proxy.Server.prototype.buildUrl.call(this, request);
								request.jsonData = request.operation.params;
								delete request.operation.params;
								return r;
							}
						}),
						listeners: {
							'beforeload' : function(store, options){
								options.params = { query: options.params.query.trim(), wzId: 0, countryId: 0, gaz: false };
							},
							'load': function(store){
								if(store.getCount() == 0){
									this.sidebarControls.userLocation.collapse();
								}
							},
							scope: this
						}
					}),
					renderTo: userLocation
				})
			}
			form.style.display = '';
			
			this.invokeMethod('GetSidebarContent', null, this.onGetC2CSidebarContentSucceeded.createDelegate(this));
        },
        
        attachVirtualSidebar: function(){
			var sidebarAnchor = document.getElementById('sidebarAnchor');

			var sl = Ext.fly('submit-link');
			if(sl){
				sl.on('click', function(e){ 
					e.stopEvent(); 
					
					this.createVirtualReport(false); 
					return false; 
				}, this);
			}
			
			var form = Ext.query('#form', sidebarAnchor)[0];

			//Ext.get('form').mask('', 'x-mask-loading');
			
			var userCity = Ext.query('#user-city', form)[0];
			var userName = Ext.query('#user-name', form)[0];
			var userCompany = Ext.query('#user-company', form)[0];
			var userPhone = Ext.query('#user-telephone', form)[0];
			var userEmail = Ext.query('#user-email', form)[0];
			
			this.sidebarControls = {
				sidebarAnchor: this.sidebarAnchor,
				
				userCity: new Ext.form.ComboBox({
					width: 120,
					hideTrigger: true,
					hideLabel: true,
					queryMode: 'remote',
					editable:true,
					minChars: 3,
					queryDelay: 500,
					matchFieldWidth: false,
					listConfig:{
						width:300
					},
					valueField: 'areaid',
					displayField: 'areatitle',
					store: new Ext.data.JsonStore({
						fields: ['areaid', 'areaname', 'areatype', 'areatitle', 'countryid', 'regionid', 'cityid', 'districtid', 'latitude', 'longitude'],
						proxy: new Ext.data.AjaxProxy({
							startParam: null,
							limitParam: null,
							pageParam: null,
							url: wsRefs.iows + '/GetSearchSuggestions',
							buildUrl: function(request){
								var r = Ext.data.proxy.Server.prototype.buildUrl.call(this, request);
								request.jsonData = request.operation.params;
								delete request.operation.params;
								return r;
							}
						}),
						listeners: {
							'beforeload' : function(store, options){
								options.params = { query: options.params.query.trim(), wzId: 0, countryId: 1, gaz: false };
							},
							'load': function(store){
								if(store.getCount() == 0){
									this.sidebarControls.userCity.collapse();
								}
							},
							scope: this
						}
					}),
					blankText: userName.getAttribute('io:blankText'),
					renderTo: userCity
				}),
				userName: new Ext.form.TextField({
						width: 120,
						hideLabel: true,
						allowBlank: false,
						blankText: userName.getAttribute('io:blankText'),
						renderTo: userName,
						msgTarget: 'title'
					}),
				userCompany: new Ext.form.TextField({
						width: 120,
						hideLabel: true,
						allowBlank: false,
						blankText: userCompany.getAttribute('io:blankText'),
						renderTo: userCompany,
						msgTarget: 'title'
					}),
				userPhone: new Ext.form.TextField({
						width: 120,
						hideLabel: true,
						allowBlank: false,
						blankText: userPhone.getAttribute('io:blankText'),
						renderTo: userPhone,
						vtype: 'phoneNumber',
						vtypeText: userPhone.getAttribute('io:vtypeText'),
						msgTarget: 'title'
					}),
				userEmail: new Ext.form.TextField({
						width: 120,
						hideLabel: true,
						allowBlank: false,
						blankText: userEmail.getAttribute('io:blankText'),
						renderTo: userEmail,
						vtype: 'email',
						vtypeText: userEmail.getAttribute('io:vtypeText'),
						msgTarget: 'title'
					})
			}
			form.style.display = '';
			
			this.invokeMethod('GetSidebarContent', null, this.onGetVirtualSidebarContentSucceeded.createDelegate(this));
        },

        attachExtraResults: function() {
			var a = Ext.query('div.results-content-left-container > h2', document.getElementById('extra-search-ns'));
			Ext.each(a, function(h){
				var p = Ext.core.DomHelper.insertHtml("beforeEnd", h, '<div class="x-tool x-tool-default" style="float:right; margin-right:5;"><img class="x-tool-toggle" src="' + Ext.BLANK_IMAGE_URL + '"/></div>');
				var block = Ext.get(p.parentNode.parentNode);
				var table = Ext.get(Ext.query('table', p.parentNode.parentNode)[0]);
				table.enableDisplayMode('block');
				
				p.collapsed = window.expandrefine === false;
				
				var toggle = function(){
					block.removeCls(p.collapsed ? 'x-panel-expanded' : 'x-panel-collapsed');
					block.addCls(p.collapsed ? 'x-panel-collapsed' : 'x-panel-expanded');
					
					table[p.collapsed ? 'hide' : 'show']();
				};
				
				toggle.call(this);
				
				Ext.fly(h).on('click', function(){
					p.collapsed = !p.collapsed;
					toggle.call(this);					
				});
			}, this);
        },

        attachReview: function() {
			var h = Ext.query('#review-ns > h2')[0];
			if(!h){
				return;
			}
			
			var p = Ext.core.DomHelper.insertHtml("beforeEnd", h, '<div class="x-tool x-tool-default" style="float:right; margin-right:5;"><img class="x-tool-toggle" src="' + Ext.BLANK_IMAGE_URL + '"/></div>');
			var block = Ext.get(p.parentNode.parentNode);
			var table = Ext.get(Ext.query('#review-ns > div', p.parentNode.parentNode)[0]);
			table.enableDisplayMode('block');
			
			p.collapsed = window.reviewCollapsed === true;
			
			var toggle = function(){
				block.removeCls(p.collapsed ? 'x-panel-expanded' : 'x-panel-collapsed');
				block.addCls(p.collapsed ? 'x-panel-collapsed' : 'x-panel-expanded');

				table[p.collapsed ? 'hide' : 'show']();
			};
			
			toggle.call(this);
			
			Ext.get(h).on('click', function(){
				p.collapsed = !p.collapsed;
				toggle.call(this);					
			});
        },

        attachRelated: function() {
			var h = Ext.query('div[id$=relSearch] > div > h2')[0];
			if(!h){
				return;
			}
			
			var p = Ext.core.DomHelper.insertHtml("beforeEnd", h, '<div class="x-tool x-tool-default" style="float:right; margin-right:5;"><img class="x-tool-toggle" src="' + Ext.BLANK_IMAGE_URL + '"/></div>');
			var block = Ext.get(p.parentNode.parentNode);
			var table = Ext.get(Ext.query('.relevant-search')[0]);
			table.enableDisplayMode('block');
			
			p.collapsed = window.relatedCollapsed === true;
			
			var toggle = function(){
				block.removeCls(p.collapsed ? 'x-panel-expanded' : 'x-panel-collapsed');
				block.addCls(p.collapsed ? 'x-panel-collapsed' : 'x-panel-expanded');

				table[p.collapsed ? 'hide' : 'show']();
			};
			
			toggle.call(this);
			
			Ext.get(h).on('click', function(){
				p.collapsed = !p.collapsed;
				toggle.call(this);					
			});
        },

        selectCentre: function(centreId) {
            io.Spinner.showSpinner();
            
			if(window._gaq){
				if(window.langId === 2){
					window._gaq.push(['_trackEvent', 'Add Centre', 'Click', 'DE']);
				}
				else if(window.langId === 3){
					window._gaq.push(['_trackEvent', 'Add Centre', 'Click', 'FR']);
				}
				
				if(window.pageType == 'centres'){
					window._gaq.push(['_trackPageview', 'detailsrequestedcenter']); 
				}
				else {
					window._gaq.push(['_trackPageview', 'detailsrequested']); 
				}
			}
            
            this.invokeMethod('SelectCentre', { centreId: centreId }, this.onCentresBasketLoaded.createDelegate(this));
        },

        requestViewing: function(centreId) {
            io.Spinner.showSpinner();

			if(window._gaq){
				if(window.langId === 2){
					window._gaq.push(['_trackEvent', 'Arrange Viewing', 'Click', 'DE']);
				}
				else if(window.langId === 3){
					window._gaq.push(['_trackEvent', 'Arrange Viewing', 'Click', 'FR']);
				}
				
				if(window.pageType == 'centres'){
					window._gaq.push(['_trackPageview', 'viewingrequestedcenter']); 
				}
				else {
					window._gaq.push(['_trackPageview', 'viewingrequested']); 
				}
            }

            this.invokeMethod('RequestViewing', { centreId: centreId }, this.onCentresBasketLoaded.createDelegate(this));
        },

        removeCentre: function(centreId) {
            io.Spinner.showSpinner();
            this.invokeMethod('RemoveCentre', { centreId: centreId }, this.onCentresBasketLoaded.createDelegate(this));
        },

        reflectSidebarCountry: function(countryId, initial, args) {
            if (!initial) {
                io.Spinner.showSpinner();
            }
            this.invokeMethod('ReflectSidebarCountry', { countryId: countryId }, this.onUpdateSidebarCountry.createDelegate(this), args);
        },

        reflectRequirementsCountry: function(countryId, initial) {
            if (!initial) {
                io.Spinner.showSpinner();
            }
            this.invokeMethod('ReflectRequirementsCountry', { countryId: countryId }, this.onUpdateRequirementsCountry.createDelegate(this), null);
        },

        getCountryCities: function(countryId, citiesListId) {
            io.Spinner.showSpinner();
            this.invokeMethod('GetCountryCities', { countryId: countryId }, this.onUpdateCitiesList.createDelegate(this), citiesListId);
        },

        clearDefaultText: function(field) {
            if (field.getAttribute("defvalue") == field.value) {
                field.value = "";
            }
        },

        setMapVisible: function(show) {
            var googleMap = Ext.DomQuery.select('div[id$=googleMap]');
            if (googleMap.length == 0) {
                return;
            }
            googleMap = googleMap[0];

            var lnkShowMap = Ext.DomQuery.select('a[id$=lnkShowMap]', document.getElementById('showMap'));
            if (lnkShowMap.length == 0) {
                return;
            }
            lnkShowMap = lnkShowMap[0];

            var lnkHideMap = Ext.DomQuery.select('a[id$=lnkHideMap]', document.getElementById('showMap'));
            if (lnkHideMap.length == 0) {
                return;
            }
            lnkHideMap = lnkHideMap[0];

            lnkShowMap.style.display = (show ? "none" : "");
            lnkHideMap.style.display = (show ? "" : "none");

            if (show) {
                googleMap.style.visibility = '';
                googleMap.style.position = '';
                document.cookie = "mapDisplay=true;path=/";
            }
            else {
                googleMap.style.visibility = 'hidden';
                googleMap.style.position = 'absolute';
                document.cookie = "mapDisplay=false;path=/";
            }
        },

        initMapVisibility: function(id) {
            var show = this.readCookie("mapDisplay") == "true";

            this.setMapVisible(show);
        },

        scrollPhotos: function(dir) {
            if (!window.photoData) {
                return;
            }

            var cur = this.currentPhoto || 0;
            var maxIndex = window.photoData.photoCellEl.length - 3;

            cur += dir;
            cur = Math.max(0, cur);
            cur = Math.min(maxIndex, cur);

            var lnkPrev = Ext.get(window.photoData.prevEl);
            var lnkNext = Ext.get(window.photoData.nextEl);

			if(lnkPrev){
				lnkPrev.setVisibilityMode(Ext.Element.DISPLAY);
				lnkPrev[cur > 0 ? 'show' : 'hide']();
            }
            if(lnkNext){
				lnkNext.setVisibilityMode(Ext.Element.DISPLAY);
				lnkNext[cur < maxIndex ? 'show' : 'hide']();
			}

            for (var i = 0, n = window.photoData.photoCellEl.length; i < n; i++) {
                var cell = Ext.get(window.photoData.photoCellEl[i]);
                cell.setVisibilityMode(Ext.Element.DISPLAY);
                cell[i >= cur && i < (cur + 3) ? 'show' : 'hide']();
            }

            this.currentPhoto = cur;
        },

        checkIOLogin: function() {
            io.Spinner.showSpinner();
            this.invokeMethod('CheckIOStaff', null, this.onStaffChecked.createDelegate(this));
        },
        
        createC2CReport: function(){
			var invalid = [];
			var reportData = {};
			
			var search = this.sidebarControls.userLocation.getValue();
			var index = this.sidebarControls.userLocation.store.findExact('areaid', search);
			var rec = this.sidebarControls.userLocation.store.getAt(index);
			
			//fields: ['areaid', 'areaname', 'areatype', 'areatitle', 'countryid', 'regionid', 'cityid', 'districtid', 'latitude', 'longitude'],
			
			if(rec){
				search = rec.data.areaname;
			}
			
			Ext.apply(reportData, {
				name: this.sidebarControls.userName.getValue(),
				countryId: this.sidebarControls.userCountry.getValue(),
				telephone: this.sidebarControls.userPhone.getValue(),
				search: search
			});
			
			Ext.iterate(this.sidebarControls, function(key, ctrl){
				ctrl.preventMark = false;
				if(ctrl.isValid && !ctrl.isValid()){
					invalid.push(ctrl.activeErrors[0]);
				}
			});
			
			if(invalid.length > 0){
				Ext.Msg.alert('Error', invalid.join('<br/>'));
				return false;
			}
			
			io.Spinner.showSpinner();
            this.invokeMethod('CreateC2CReport', { data: reportData  }, this.onCreateC2CReport.createDelegate(this));
        },

        createVirtualReport: function(){
			var invalid = [];
			var reportData = {};
			
			var city = this.sidebarControls.userCity.getValue();
			var index = this.sidebarControls.userCity.store.findExact('areaid', city);
			var rec = this.sidebarControls.userCity.store.getAt(index);
			
			//fields: ['areaid', 'areaname', 'areatype', 'areatitle', 'countryid', 'regionid', 'cityid', 'districtid', 'latitude', 'longitude'],
			
			var search = city;
			if(rec){
				search = rec.data.areaname;
			}
			var a= this.sidebarControls.userName.getValue().split(' ');
			Ext.apply(reportData, {
				firstname: a[0] || '',
				lastname: a[1] || '',
				countryId: 1,
				telephone: this.sidebarControls.userPhone.getValue(),
				company: this.sidebarControls.userCompany.getValue(),
				email: this.sidebarControls.userEmail.getValue(),
				city: city,
				search: search
			});
			
			Ext.iterate(this.sidebarControls, function(key, ctrl){
				ctrl.preventMark = false;
				if(ctrl.isValid && !ctrl.isValid()){
					invalid.push(ctrl.activeErrors[0]);
				}
			});
		
			if(invalid.length > 0){
				Ext.Msg.alert('Error', invalid.join('<br/>'));
				return false;
			}
			
			io.Spinner.showSpinner();
            this.invokeMethod('CreateVirtualReport', { data: reportData  }, this.onCreateVirtualReport.createDelegate(this));
        },

        createReport: function(ioreq) {
			var reportData = {
				whitelabelId: window.whitelabelId,
				centreId: window.centreId
			};
			
			if(window.uiCountryId  == 49 && !this.panelCentres.isVisible()){
				Ext.Msg.alert('Instant Offices', window.localStrings.AssertSelection);
				return;
			}
			
			if(window.version >= 2){
				var invalid = [];
				var valid = true;
				Ext.iterate(this.sidebarControls, function(p, f){
					if(f && typeof(f.getValue) == 'function'){
						f.preventMark = false;
						
						var li = f.getEl().up('li');
						if(li && li.dom && li.dom.style.display != 'none'){
							f.clearInvalid();
							valid = valid && f.isValid();
							if(!f.isValid()){
								invalid.push(f.activeError);
							}
						}
						f.preventMark = true;
					}
				});
				if(!ioreq && !valid){
					Ext.Msg.alert('Error', invalid.join('<br/>'));
					this.processSidebarForm(true);
					return;
				}
				io.Spinner.showSpinner();
				Ext.apply(reportData, {
					countryId: this.sidebarControls.userCountry.getValue(),
					regionId: this.sidebarControls.userRegion.getValue(),
					companyName: this.sidebarControls.userCompanyName.getValue(),
					title: this.sidebarControls.userTitle ? this.sidebarControls.userTitle.getValue() : '',
					firstName: this.sidebarControls.userFirstName ? this.sidebarControls.userFirstName.getValue() : '',
					lastName: this.sidebarControls.userLastName.getValue(),
					email: this.sidebarControls.userEmail.getValue(),
					numPeople: this.sidebarControls.peopleNumber.getValue(),
					telephone: this.sidebarControls.userPhone.getValue(),
					startDate: this.sidebarControls.startDate ? this.sidebarControls.startDate.getValue() : '',
					dateView: this.sidebarControls.viewDate.getValue(),
					timeView: this.sidebarControls.viewTime.getValue(),
					furtherDetails: this.sidebarControls.furtherDetails.getValue()
				});
				if(reportData.dateView){
					reportData.dateView = Ext.Date.format(reportData.dateView, 'd/m/Y');
				}
			}
			else {
				if (!ioreq && !Page_ClientValidate()) {
					return false;
				}

				io.Spinner.showSpinner();
				Ext.apply(reportData, {
					countryId: this.getSidebarFieldValue('side_country'),
					regionId: this.getSidebarFieldValue('side_region'),
					companyName: this.getSidebarFieldValue('side_companyname'),
					title: this.getSidebarFieldValue('side_title') || '',
					firstName: this.getSidebarFieldValue('side_firstname') || '',
					lastName: this.getSidebarFieldValue('side_lastname') || '',
					email: this.getSidebarFieldValue('side_email'),
					numPeople: this.getSidebarFieldValue('side_numpeople'),
					telephone: this.getSidebarFieldValue('side_telephone'),
					startDate: this.getSidebarFieldValue('side_startdate') || '',
					dateView: this.getSidebarFieldValue('dtView'),
					timeView: this.getSidebarFieldValue('tmView')
				});
			}
			
            this.invokeMethod('CreateReport', { data: reportData  }, this.onCreateReport.createDelegate(this), { ioreq: ioreq });
        },

        openInstantTourPopup: function(url) {
            if (this.tourPopupWindow != null) {
                tourPopupWindow.close();
            }
            tourPopupWindow = window.open(url, 'tour', 'scrollbars=yes,width=432,height=480');
        },

        showCentreOnMap: function(index) {
            if (!this.mapEl) {
                this.mapEl = Ext.get('map');
            }
            window.scrollTo(0, this.mapEl ? this.mapEl.getTop() : 0);

            //  ensure map is visible
            this.setMapVisible(true);

   			if(window.googleMap){
				window.googleMap.showPointBubbleByTag(index);
			}
        },

        requestReportViewing: function(reportGuid, centreId, enquiryId, userId, tab, dt, tm) {
            io.Spinner.showSpinner();
            
            if(window.version == 2){
				dt = Ext.getCmp('dtView' + centreId);
				tm = Ext.getCmp('tmView' + centreId);
            }
            this.invokeMethod('RequestReportViewing', { guid: reportGuid, nCentreID: centreId, nEnquiryID: enquiryId, nUAID: userId, dtView: dt.getValue(), tmView: tm.getValue() }, this.onRequestReportViewingComplete.createDelegate(this), { tab: tab });
        },

        reportFeedback: function(reportGuid) {
            if (!Page_ClientValidate()) {
                return false;
            }

            io.Spinner.showSpinner();

            try {
                var choice = 0;
                var address = '';
                var choices = Ext.DomQuery.select('input[name=choice]');
                for (var i = 0; i < choices.length; i++) {
                    var chk = choices[i];
                    if (chk.checked) {
                        choice = chk.value;

                        if (chk.value == 0) {
                            address = Ext.DomQuery.select('input[id$=txtOtherAddress]')[0].value;
                            break;
                        }
                        if (chk.value == -1) {
                            address = Ext.DomQuery.select('input[id$=txtAltAddress]')[0].value;
                            break;
                        }
                        break;
                    }
                }

                this.invokeMethod('ReportFeedback', { guid: reportGuid, choice: choice, address: address }, this.onReportFeedbackComplete.createDelegate(this));
            }
            catch (e) {
                io.Spinner.hideSpinner();
            }
        },

        changeLanguage: function(folder, updateMap) {
            var url = window.siteBaseUrl.slice(0, window.siteBaseUrl.length - 1);
            var i = url.lastIndexOf('/');
            url = url.slice(0, i+1);
            if(url.length == 0){
                url = "/global/";
            }
            if(updateMap === true){
				document.cookie = 'switchmap=' + folder + ';path=/';
            }
            document.location = url + folder + '/';
        },

        filterResults: function(rawUrl) {
            var cmbSizeFilter = Ext.query('select[id$=cmbSizeFilter]')[0];
            var cmbSort = Ext.query('select[id$=cmbSort]')[0];
            if(cmbSizeFilter && cmbSort){
				io.Spinner.showSpinner();
                this.invokeMethod('SetSearchResultsParams', { rawUrl: rawUrl, reqSize: cmbSizeFilter.value, reqSort : cmbSort.value}, this.onSearchParamsSet.createDelegate(this), rawUrl);
            }
        },
        
        maskMap: function(){
			var b = Ext.fly('default-top-content-right');
			if(b){
				//b.mask('', 'x-mask-loading');
			}
        },

        unmaskMap: function(){
			var b = Ext.fly('default-top-content-right');
			if(b){
				//b.unmask();
			}
        },

        gotoCountryLanding: function(countryId, rel) {
            if (countryId) {
                io.Spinner.showSpinner();
                this.invokeMethod('GetCountryLandingUrl', { countryId: countryId }, this.onGetLandingUrl.createDelegate(this, [rel], true));
            }
        },

        gotoCityLanding: function(cityId, rel) {
            if (cityId.length > 0) {
                io.Spinner.showSpinner();
                this.invokeMethod('GetCityLandingUrl', { countryId: window.countryId, cityId: cityId }, this.onGetLandingUrl.createDelegate(this, [rel], true));
            }
        },

        gotoRegionLanding: function(regionId) {
            if (regionId.length > 0) {
                io.Spinner.showSpinner();
                this.invokeMethod('GetRegionLandingUrl', { countryId: window.countryId, regionId: regionId }, this.onGetLandingUrl.createDelegate(this));
            }
        },

        doLandingSearch: function(rel) {
            var query = '';
            var countryId = 0;
            var regionId = 0;
            var cityId = 0;

            var txtQuery = Ext.DomQuery.select('input[id$=txtQuery]');
            var txtSearch = Ext.DomQuery.select('input[id$=txtSearch]');
            if (txtQuery.length == 0 && txtSearch.length == 0) {
                return;
            }

            if (txtQuery.length == 1) {
                query = txtQuery[0].value;
            }
            else if (txtSearch.length == 1) {
                query = txtSearch[0].value;
            }
            if (query.trim().length == 0) {
                return;
            }

            var cmbCountry = Ext.DomQuery.select('select[id$=cmbCountry]');
            if (cmbCountry.length == 1) {
                countryId = cmbCountry[0].value;
            }

            var cmbRegion = Ext.DomQuery.select('select[id$=cmbRegion]');
            if (cmbRegion.length == 1) {
                regionId = cmbRegion[0].value;
            }

            var cmbCity = Ext.DomQuery.select('select[id$=cmbCity]');
            if (cmbCity.length == 1) {
                cityId = cmbCity[0].value;
            }

            io.Spinner.showSpinner();
            this.invokeMethod('LandingSearch', { countryId: countryId || window.countryId, regionId: regionId || 0, cityId: cityId || 0, query: query }, this.onLandingSearchComplete.createDelegate(this, [rel], true));
        },

        checkLandingCityDistricts: function(chkCity) {
            var cityID = chkCity.getAttribute("cityid");
            var arr = Ext.DomQuery.select('input[type=checkbox]');
            for (var i = 0; i < arr.length; i++) {
                var valAttr = arr[i].getAttribute("districtcityid");
                if (valAttr != null && valAttr == cityID) {
                    arr[i].checked = chkCity.checked;
                }
            }
        },

        loadLandingBasket: function() {
            var divBasket = Ext.DomQuery.select('div[id$=divBasket]')[0];
            this.btnSearchBasket = Ext.DomQuery.select('input[id$=btnSearchBasket]', divBasket)[0];
            this.basketContainer = Ext.DomQuery.select('ul[id=basketContainer]', divBasket)[0];
            this.templateBasket = Ext.query('span[id=templateBasket]', divBasket)[0];
            this.templateBasket = this.getCompiledTemplate(this.templateBasket.innerHTML);

            //  initial load of the basket data
            this.invokeMethod('GetLandingBasketData', null, this.onLandingBasketLoaded.createDelegate(this));
        },

        addLandingBasketItem: function(mapPartId) {
            if (this.basketContainer.partsCount == 6) {
                //Ext.Msg.alert('Warning', 'You can choose maximum 6 cities or districts.');
                return;
            }
            this.invokeMethod('AddLandingBasketItem', { mapPartId: mapPartId }, this.onLandingBasketLoaded.createDelegate(this));
        },

        removeLandingBasketItem: function(mapPartId) {
            this.invokeMethod('RemoveLandingBasketItem', { mapPartId: mapPartId }, this.onLandingBasketLoaded.createDelegate(this));
        },

        doLandingBasketSearch: function() {
            io.Spinner.showSpinner();
            this.invokeMethod('LandingBasketSearch', { countryId: window.countryId, regionId: window.regionId, cityId: window.cityId }, this.onLandingSearchComplete.createDelegate(this));
        },

        doLandingSelectionSearch: function() {
            var sel = [];
            var divTickBoxes = Ext.DomQuery.select('div[id$=divTickBoxes]');
            var arr = Ext.DomQuery.select('input[type=checkbox]', document.getElementById('divTickBoxes'));
            for (var i = 0, n = arr.length; i < n; i++) {
                if (arr[i].checked) {
                    sel.push({ areaId: arr[i].getAttribute('aid'), cityId: arr[i].getAttribute('districtcityid') });
                }
            }

            io.Spinner.showSpinner();
            this.invokeMethod('LandingSelectionSearch', { sel: sel, countryId: window.countryId, regionId: window.regionId, cityId: window.cityId }, this.onLandingSearchComplete.createDelegate(this));
        },

        updateRequirements: function(partnerName, partnerId, countryId, updateCentres) {
            var panelSheet = Ext.DomQuery.select('div[id$=panelSheet]')[0];
            if (!panelSheet) {
                return;
            }

            io.Spinner.showSpinner();
            this.cmbPeople = Ext.DomQuery.select('select[id$=cmbPeople]')[0];
            var people = this.cmbPeople && this.cmbPeople.value;
            
            if(partnerName !== null){
                Ext.get('lblPartner').update(partnerName);
            }
            this.partnerId = partnerId;

            this.invokeMethod('GetPrivateRequirements', { people: people || -1, partnerId: this.partnerId || 0, countryId : countryId || 0, updateCentres : updateCentres }, this.onGetPrivateRequirementsComplete.createDelegate(this), { updateCentres : updateCentres, countryId : countryId });
        },
        
        attachPrivateSources: function(){
			this.lnkSelect = Ext.query('a[id$=lnkSelect]')[0];
			this.lnkClear = Ext.query('a[id$=lnkClear]')[0];
			Ext.fly(this.lnkSelect).on('click', this.selectPartner, this);
			Ext.fly(this.lnkClear).on('click', this.clearPartner, this);

			this.updatePartnerControls();			
			Ext.fly('cmbSource').on('change', this.onPrivateSourceChange, this);
        },
        
        updatePartnerControls: function(){
			var cmbSource = Ext.fly('cmbSource').dom;
	        var o = cmbSource.options[cmbSource.selectedIndex];

	        if(o.getAttribute('prid') > 0){
				this.partnerId = parseInt(o.getAttribute('prid'));
		        Ext.fly('lblPartner').update(o.getAttribute('prname'));
		        this.lnkSelect.style.display = 'none'; 
		        this.lnkClear.style.display = 'none'; 
	        }
	        else {
				this.partnerId = 0;
		        Ext.fly('lblPartner').update('');
		        this.lnkSelect.style.display = (parseInt(o.getAttribute('pr')) ? '' : 'none'); 
		        this.lnkClear.style.display = (parseInt(o.getAttribute('pr')) ? '' : 'none'); 
	        }
	        
	        return o.getAttribute('prname');
        },
        
        onPrivateSourceChange: function(){
			var pname = this.updatePartnerControls();
	        
	        this.updateRequirements(pname, this.partnerId, 0, false);
        },

        removePrivateCentre: function(centreId) {
            var people = this.cmbPeople && this.cmbPeople.value;

            io.Spinner.showSpinner();
            this.invokeMethod('RemovePrivateCentre', { centreId: centreId, people: people || -1, partnerId: this.partnerId || 0 }, this.onGetPrivateRequirementsComplete.createDelegate(this), true);
        },
        
        checkCustomerEmail: function(email, id){
            io.Spinner.showSpinner();
            this.invokeMethod('CheckCustomerEmail', { email : email, userId : id || 0}, this.onCheckCustomerEmailComplete.createDelegate(this), email);
        },
        
        createPrivateReport : function(){
			var cmbSource = Ext.fly("cmbSource").dom;
			var o = cmbSource.options[cmbSource.selectedIndex];

			var partnerID = this.partnerId || 0;
			var partnerValid = false;
			var prid = parseInt(o.getAttribute('prid'));
			
			if(parseInt(o.getAttribute('pr'))){
				partnerValid = (prid && prid == partnerID) || partnerID > 0;
			}
			else {
				partnerValid = partnerID == 0;
			}
			
			if(!partnerValid){
				alert('Please check you have selected a source which allows partners to be selected and selected a partner, or remove the partner.');
				return false;
			}

			var sourceValue = cmbSource.value;
			if(!sourceValue || sourceValue.length == 0){
				alert('You must select enquiry source');
				return false;
			}

            if (!Page_ClientValidate()) {
                return false;
            }
            
            var listRules = [-1];
            var copyEl = Ext.query('input[type=checkbox]', document.getElementById('copyContainer'));
            for(var i = 0, n = copyEl.length; i < n; i++){
                if(copyEl[i].checked){
                    listRules.push(copyEl[i].value);
                }
            }

            var listRecip = [-1];
            var recipEl = Ext.query('input[type=checkbox]', document.getElementById('recipContainer'));
            for(var i = 0, n = recipEl.length; i < n; i++){
                if(recipEl[i].checked){
                    listRecip.push(recipEl[i].value);
                }
            }

            io.Spinner.showSpinner();
            var reportData = {
                userId : this.customerId || 0,
                countryId: this.getFieldValue('cmbCountry'),
                regionId: 0,
                cityId: this.getFieldValue('cmbCity') || 0,
	            companyName : this.getFieldValue('txtCompanyName'),
	            title : this.getFieldValue('txtTitle') || '',
	            firstName : this.getFieldValue('txtFirstName') || '',
	            lastName : this.getFieldValue('txtLastName') || '',
	            email : this.getFieldValue('txtEmail'),
	            numPeople : this.getFieldValue('cmbPeople'),
	            telephone : this.getFieldValue('txtTelephone'),
	            mobile : this.getFieldValue('txtMobile'),
	            startDate : this.getFieldValue('cmbStartDate'),
	            webAddress : this.getFieldValue('txtWebSite'),
	            lengthOfTerm : this.getFieldValue('txtLengthOfTerm'),
	            businessType : this.getFieldValue('cmbBusiness'),
	            partnerId : this.partnerId || 0,
	            listRules : listRules,
	            listRecip : listRecip,
	            consultantId : this.getFieldValue('cmbUsers'),
	            source : sourceValue,
	            confidential1 : this.getFieldValue('chkConfidential1'),
	            confidential2 : this.getFieldValue('chkConfidential2'),
	            privateNotes : this.getFieldValue('txtPrivateNotes'),
	            specialRequirements : this.getFieldValue('txtSpecialRequirements'),
	            gradingId : this.getFieldValue('cmbGrading'),
	            gradingColorId : this.getFieldValue('cmbColors'),
	            
	            chkOwnEmail : this.getFieldValue('chkOwnEmail'),
	            chkExcelClient : this.getFieldValue('chkExcelClient'),
	            chkExcelMe : this.getFieldValue('chkExcelMe'),
	            chkExcelAdditional : this.getFieldValue('chkExcelAdditional'),
	            chkPDFClient : this.getFieldValue('chkPDFClient'),
	            chkPDFMe : this.getFieldValue('chkPDFMe'),
	            chkPDFAdditional : this.getFieldValue('chkPDFAdditional'),
	            chkSMS : this.getFieldValue('chkSMS'),
	            chkEdit : this.getFieldValue('chkEdit'),
	            languageId : this.getFieldValue('cmbLanguage'),
	            copyEmail : this.getFieldValue('txtCopyEmail'),
	            recontactDate : this.getFieldValue('dtRecontact'),
	            whitelabelId: window.whitelabelId
            };
            this.invokeMethod('CreatePrivateReport', { data: reportData }, this.onCreatePrivateReport.createDelegate(this));
        },
        
        //  private
        onSearchParamsSet : function(p, url){
			document.location = url;
        },
        
        onCreatePrivateReport: function(url){
            document.location = window.siteBaseUrl + url;
        },
        
        clearPartner: function(){
			this.updateRequirements('', 0, 0, false);
        },
        
        selectPartner: function(){
            if (!this.partnersDlg) {
                // create the Data Store
                var store = new Ext.data.JsonStore({
                    root: 'data',
                    totalProperty: 'totalCount',
                    idProperty: 'PartnerID',
                    remoteSort: true,
                    baseParams:{
						filter: ''
                    },

                    fields: [
                        'PartnerID', 'Name', 'CompanyName', 'FirstName', 'LastName'
                    ]
                });
                store.proxy = this.createProxy('GetPartners', store);
                store.setDefaultSort('PartnerID', 'ASC');
                
                function renderContactName(value, p, r){
                    return String.format('{0} {1}', r.data['FirstName'], r.data['LastName']);
                }

                var grid = new Ext.grid.GridPanel({
                    store: store,
                    trackMouseOver:true,
                    disableSelection:true,
                    loadMask: true,
                    sm: new Ext.grid.RowSelectionModel({singleSelect: true}),

                    // grid columns
                    columns:[{
                        header: "ID",
                        dataIndex: 'PartnerID',
                        width: 50,
                        sortable: true
                    },{
                        header: "Name",
                        dataIndex: 'Name',
                        width: 200,
                        sortable: true
                    },{
                        header: "Company Name",
                        dataIndex: 'CompanyName',
                        width: 200,
                        sortable: true
                    },{
                        header: "Contact Name",
                        dataIndex: 'FirstName',
                        width: 150,
                        sortable: true,
                        renderer : renderContactName
                    }],

                    // customize view config
                    viewConfig: {
                        forceFit:true,
                        enableRowBody:true
                    },
                    
                    tbar: [
                        '->',
                        { id: 'partnerSearch', xtype:'textfield' },
                        '-',
                        { 
                            text: 'Search', 
                            iconCls:'icon-search', 
                            handler: function(){
                                var partnerSearch = Ext.getCmp('partnerSearch');
                                var filter = partnerSearch.getValue();
                                grid.store.load({
									params: { 
										jsonData: {
											start:0, 
											limit:14, 
											filter: filter
										}
									}
								});
                            }
                        }
                    ],

                    // paging bar on the bottom
                    bbar: new Ext.PagingToolbar({
                        pageSize: 25,
                        store: store,
                        displayInfo: true,
                        displayMsg: 'Displaying partners {0} - {1} of {2}',
                        emptyMsg: "No partners to display"
                    })
                });
                grid.on('dblclick', this.partnerSelected.createDelegate(this, [grid]), this);
                
                this.partnersDlg = new Ext.Window({
                    layout: 'fit',
                    width: 600,
                    height: 445,
                    modal: true,
                    closeAction: 'hide',
                    resizable: false,
                    title: 'Select Partner',
                    bodyStyle: 'background-color:white;',
                    
                    items: [
                        grid
                    ],

                    buttons: [{
                        text: 'Select',
                        handler: io.ApplicationManager.partnerSelected.createDelegate(this, [grid]),
                        scope: this
                    }, {
                        text: 'Cancel',
                        handler: function() {
                            this.partnersDlg.hide();
                        },
                        scope: this
                    }
                   ]
                });
                
                // trigger the data store load
                store.load({
					params: { 
						jsonData: {
							start:0, 
							limit:14, 
							filter: ''
						}
					}
				});
            }

            this.partnersDlg.show(true);
        },
        
        partnerSelected : function(grid){
            var r = grid.getSelectionModel().getSelected();
            if(r){
                this.partnersDlg.hide();
                this.updateRequirements(r.data.Name, r.data.PartnerID, 0, false);
            }
        },
        
        //  private 
        onCheckCustomerEmailComplete: function(cdt, email){
            io.Spinner.hideSpinner();
            if(cdt.totalCount <= 0){
                return;
            }
            if(cdt.totalCount == 1){
                this.fillCustomerData(cdt.data);
                if(cdt.countryData){
                    this.onUpdateRequirementsCountry(cdt.countryData);
                }
                return;
            }
            
            if (!this.userDlg) {
                // create the Data Store
                var store = new Ext.data.JsonStore({
                    root: 'data',
                    totalProperty: 'totalCount',
                    idProperty: 'UserID',
                    remoteSort: true,

                    fields: [
                        'UserID', 'Name', 'Address', 'FirstCity', 'LastEnquiryDate'
                    ]
                });
                
                store.setDefaultSort('UserID', 'ASC');
                
                var grid = new Ext.grid.GridPanel({
                    store: store,
                    trackMouseOver:true,
                    disableSelection:true,
                    loadMask: true,
                    sm: new Ext.grid.RowSelectionModel({singleSelect: true}),

                    // grid columns
                    columns:[{
                        header: "Name",
                        dataIndex: 'Name',
                        width: 200,
                        sortable: true
                    },{
                        header: "Address",
                        dataIndex: 'Address',
                        width: 200,
                        sortable: true
                    },{
                        header: "City Of Search",
                        dataIndex: 'FirstCity',
                        width: 150,
                        sortable: true
                    },{
                        header: "Last Enquiry Date",
                        dataIndex: 'LastEnquiryDate',
                        width: 150,
                        sortable: true
                    }],

                    // customize view config
                    viewConfig: {
                        forceFit:true,
                        enableRowBody:true
                    }
                });
                grid.on('dblclick', this.customerSelected.createDelegate(this, [grid]), this);
                
                this.userDlg = new Ext.Window({
                    layout: 'fit',
                    width: 600,
                    height: 445,
                    modal: true,
                    closeAction: 'hide',
                    resizable: false,
                    title: 'Select Customer',
                    bodyStyle: 'background-color:white;',
                    items: [
                        grid
                    ],

                    buttons: [{
                        text: 'Select',
                        handler: io.ApplicationManager.customerSelected.createDelegate(this, [grid]),
                        scope: this
                    }, {
                        text: 'Cancel',
                        handler: function() {
                            this.userDlg.hide();
                        },
                        scope: this
                    }
                   ]
                });
                
                this.userDlg.grid = grid;
            }

            this.userDlg.grid.store.loadData(cdt);
            this.userDlg.grid.email = email;
            this.userDlg.show(true);
        },
        
        //  private 
        customerSelected : function(grid){
            var r = grid.getSelectionModel().getSelected();
            if(r){
                this.userDlg.hide();
                this.checkCustomerEmail(grid.email, r.data.UserID);
            }
        },
        
        //   private
        fillCustomerData : function(userData){
            var user = userData[0];
            this.customerId = user.ID;
			Ext.query('input[id$=txtTitle]')[0].value = user.Title;
			Ext.query('input[id$=txtFirstName]')[0].value = user.FirstName;
			Ext.query('input[id$=txtLastName]')[0].value = user.LastName;
			Ext.query('input[id$=txtCompanyName]')[0].value = user.CompanyName;
			Ext.query('input[id$=txtTelephone]')[0].value = user.Telephone;
			Ext.query('input[id$=txtMobile]')[0].value = user.TelMobile;
			Ext.query('input[id$=txtWebSite]')[0].value = user.WebAddress;
			Ext.query('input[id$=txtLengthOfTerm]')[0].value = user.LengthOfTerm;
			Ext.query('select[id$=cmbCountry]')[0].value = user.UserCountryID;
			Ext.query('select[id$=cmbCity]')[0].value = user.UserCityID;
			Ext.query('select[id$=cmbBusiness]')[0].value = user.BusinessType;
			Ext.query('select[id$=cmbPeople]')[0].value = user.NumberOfPeople;
			Ext.query('select[id$=cmbStartDate]')[0].value = user.StartDate;
			Ext.query('select[id$=cmbLanguage]')[0].value = user.UserLangID;
        },

        //  private
        onGetPrivateRequirementsComplete: function(data, args) {
            if(args.updateCentres) {
                this.updatePrivateCentres(data);
            }
            if(data.countryData){
                this.onUpdateRequirementsCountry(data.countryData, args.countryId);
            }
            this.updateReferrals(data.refs);

            io.Spinner.hideSpinner();
        },
        
        //  private
        updateReferrals: function(data) {
            var copyContainer = Ext.DomQuery.select('td[id=copyContainer]')[0];
            var copyTemplate = Ext.query('span[id=copyTemplate]')[0];
            copyTemplate = this.getCompiledTemplate(copyTemplate.innerHTML);

            var recipContainer = Ext.DomQuery.select('td[id=recipContainer]')[0];
            var recipTemplate = Ext.query('span[id=recipTemplate]')[0];
            recipTemplate = this.getCompiledTemplate(recipTemplate.innerHTML);

            for (var i = 0, n = copyContainer.childNodes.length; i < n; i++) {
                copyContainer.removeChild(copyContainer.childNodes[0]);
            }
            for (var i = 0, n = recipContainer.childNodes.length; i < n; i++) {
                recipContainer.removeChild(recipContainer.childNodes[0]);
            }

            for (var i = 0, n = data.normal.length; i < n; i++) {
                var p = data.normal[i];
                var listHTML = copyTemplate.applyTemplate(p);
                Ext.core.DomHelper.append(copyContainer, listHTML);
            }

            for (var i = 0, n = data.additional.length; i < n; i++) {
                var p = data.additional[i];
                var listHTML = recipTemplate.applyTemplate(p);
                Ext.core.DomHelper.append(recipContainer, listHTML);
            }
        },

        //  private
        updatePrivateCentres: function(data) {
            io.Spinner.hideSpinner();
            var panelSheet = Ext.DomQuery.select('div[id$=panelSheet]')[0];
            if (!panelSheet) {
                return;
            }

            panelSheet = Ext.get(panelSheet);
            panelSheet.setVisibilityMode(Ext.Element.DISPLAY);

            if (!data.centres) {
                var panelNoCentres = Ext.get(Ext.DomQuery.select('div[id=panelNoCentres]')[0]);
                panelNoCentres.setVisibilityMode(Ext.Element.DISPLAY);
                panelNoCentres.show();

                panelSheet.hide();
                return;
            }

            panelSheet.show();

            var listContainer = Ext.DomQuery.select('tbody[id$=listContainer]')[0];
            var templateSelected = Ext.query('span[id$=templateSelected]')[0];
            templateSelected = this.getCompiledTemplate(templateSelected.innerHTML);

            for (var i = 0, n = listContainer.childNodes.length; i < n; i++) {
                listContainer.removeChild(listContainer.childNodes[0]);
            }

            var hasRequest = false;
            for (var i = 0, n = data.indexes ? data.indexes.length : 0; i < n; i++) {
                var p = data.indexes[i];
                var ci = data.centres[p];

                var d = [];
                d.push(p);
                d.push(ci.cityKey);
                d.push(ci.addressKey);
                d.push(ci.address);
                d.push(ci.ref);
                d.push(ci.imgStyle);
                d.push(ci.removeAction);
                d.push(window.officesUrlPrefix);

                var listHTML = templateSelected.applyTemplate(d);
                Ext.core.DomHelper.append(listContainer, listHTML);
            }
        },

        //  private 
        onLandingBasketLoaded: function(data) {
            if (!data) {
                return;
            }

            for (var i = 0, n = this.basketContainer.childNodes.length; i < n; i++) {
                this.basketContainer.removeChild(this.basketContainer.childNodes[0]);
            }
            this.basketContainer.partsCount = 0;

            for (var i = 0, n = data.length; i < n; i++) {
                var itemData = data[i];

                var d = [];
                d.push(itemData.title);
                d.push(itemData.mapPartId);
                d.push(itemData.mapPartId > 0 ? '' : 'none');

                this.basketContainer.partsCount += (itemData.mapPartId > 0 ? 1 : 0);

                var el = Ext.core.DomHelper.append(this.basketContainer, this.templateBasket.apply(d));
                for (var k in itemData.attributes) {
                    if (itemData.attributes.hasOwnProperty(k)) {
                        el[k] = itemData.attributes[k];
                    }
                }
            }

            this.btnSearchBasket.style.display = this.basketContainer.partsCount ? '' : 'none';
        },

        //  private
        onLandingSearchComplete: function(res, o, rel) {
            var places = Ext.query('div[id=multiple-results]')[0];
            if (res.places) {
                io.Spinner.hideSpinner();

                var listContainer = Ext.query('ul[id$=listContainerMS]', places)[0];
                var templatePlace = Ext.query('span[id$=templatePlace]', places)[0];
                templatePlace = this.getCompiledTemplate(templatePlace.innerHTML);

                places.style.display = '';

                for (var i = 0, n = res.places.length; i < n; i++) {
                    var pl = res.places[i];
                    var placeTitle = '';

                    if (pl.PostCode.length == 0) {
                        if (pl.RegionName.length > 0) {
                            placeTitle = [pl.CountryName, pl.RegionName, pl.CityName].join(', ');
                        }
                        else {
                            placeTitle = [pl.CountryName, pl.CityName].join(', ');
                        }

                        if (pl.DistrictName.length > 0) {
                            placeTitle = [placeTitle, pl.DistrictName].join(', ');
                        }
                    }
                    else {
                        placeTitle = [pl.CountryName, pl.PostCode].join(', ');
                    }

                    var d = [];
                    d.push(window.siteBaseUrl + pl.LandingUrl);
                    d.push(placeTitle);

                    Ext.core.DomHelper.append(listContainer, templatePlace.apply(d));
                }
                
                return;
            }
            if(places){
				places.style.display = 'none';
            }
            document.location = window.siteBaseUrl + res;
        },

        //  private
        onGetLandingUrl: function(url, o, rel) {
            document.location = window.siteBaseUrl + (rel || '') + url;
        },

        // private
        onReportFeedbackComplete: function(res) {
            io.Spinner.hideSpinner();

            var el = Ext.DomQuery.select('div[id$=panelFeedback]')[0];
            el.style.display = 'none';
            var elDone = Ext.DomQuery.select('div[id$=panelDone]')[0];
            elDone.style.display = '';

            var id = 'lblFoundWithUs';
            if (res == 1) {
                id = 'lblFoundWithoutUs';
            }
            else if (res == 2) {
                id = 'lblElse';
            }
            el = Ext.DomQuery.select('span[id$=' + id + ']', elDone)[0];
            el.style.display = '';
        },

        //  private
        onRequestReportViewingComplete: function(o, data) {
            io.Spinner.hideSpinner();

            if (data && data.tab) {
                data.tab.dom.onclick();
            }
        },
        
        //  private
        getSidebarFieldValue: function(id) {
            return this.getFieldValue(id, 'sidebarAnchor');
        },

        //  private
        getFieldValue: function(id, parentRef) {
            var ctrl = Ext.query('*[id$=' + id + ']', parentRef);
            ctrl = ctrl.length > 0 ? ctrl[0] : null;
            if (ctrl) {
                return ctrl.type == 'checkbox' ? ctrl.checked : ctrl.value;
            }
            return null;
        },
        
        onCreateC2CReport: function(o){
			document.location = window.siteBaseUrl + 'click2call_confirm.aspx';
        },
        
        onCreateVirtualReport: function(o){
			document.location = window.siteBaseUrl + 'thanks-virtual-uk.aspx';
        },

        //  private
        onCreateReport: function(o, args) {
            document.location = args.ioreq ? window.ioreqUrl : window.reportRedirectUrl;
        },

        //  private
        onStaffChecked: function(valid) {
            io.Spinner.hideSpinner();

            if (valid) {
                this.createReport(true);
                return;
            }

            if (!this.loginDlg) {
                this.loginDlg = Ext.create('Ext.Window', {
                    layout: 'fit',
                    width: 400,
                    height: 200,
                    modal: true,
                    closeAction: 'hide',
                    resizable: false,
                    title: 'Instant Offices Login [Use Fred Profile]',
                    bodyStyle: 'background-color:white;',
                    items: 
                    [
                        {
                            xtype: 'form',
							layout: 'anchor',
                            bodyStyle: 'padding:10px;',
                            defaults: {
								style: 'margin-bottom:5px'
                            },
                            items: [
                                { xtype: 'displayfield', html: '<h3>Authorized Access Only</h3><br/>', anchor: '100%' },
                                { xtype: 'textfield', width: '150px', fieldLabel: 'Email', allowBlank: false, id: 'emailField' },
                                { xtype: 'textfield', width: '150px', fieldLabel: 'Password', allowBlank: false, id: 'passwordField', inputType: 'password' },
                                { xtype: 'displayfield', anchor: '100%', html: '<br/><h3>Login Incorrect</h3>', id: 'statusField', hidden: true, cls: 'error' }
                            ]
                        }
                    ],

                    buttons: [{
                        text: 'Log-IN',
                        handler: io.ApplicationManager.validateLogin,
                        scope: this
                    }, {
                        text: 'Cancel',
                        handler: function() {
                            this.loginDlg.hide();
                        },
                        scope: this
                    }
                   ]
                });
            }

            this.loginDlg.show();
        },

        //  private
        validateLogin: function() {
            var form = this.loginDlg.items.get(0);
            if (!form.form.isValid()) {
                return;
            }

            io.Spinner.showSpinner();

            var email = Ext.ComponentQuery.query('#emailField', this.loginDlg)[0].getValue();
            var password = Ext.ComponentQuery.query('#passwordField', this.loginDlg)[0].getValue();
            var status = Ext.ComponentQuery.query('#statusField', this.loginDlg)[0];

            this.invokeMethod('ValidateIOLogin', { email: email, password: password }, this.onLoginValidated.createDelegate(this), { status: status });
        },

        //  private
        onLoginValidated: function(valid, args) {
            io.Spinner.hideSpinner();

            if (valid) {
                this.createReport(true);
                return;
            }
            args.status.show();
        },

        //  private
        onUpdateCitiesList: function(data, citiesListId) {
            if (data) {
                var citiesList = Ext.fly(citiesListId);
                this.updateListOptions(citiesList.dom, data, 1);
            }

            io.Spinner.hideSpinner();
        },

        //  private
        onUpdateSidebarCountry: function(data, args) {
			var phone = Ext.fly(args.phone);
			if (phone.dom.value.length < 6) {
				phone.dom.value = data.prefix;
			}

			var panel = Ext.get(args.panelRegions);
			if (panel) {
				panel.setVisibilityMode(Ext.Element.DISPLAY);
				if (data.regions) {
					panel.show();
					var regions = Ext.fly(args.comboRegions);
					this.updateListOptions(regions.dom, data.regions, 1);
					regions.dom.value = '0';
				}
				else {
					panel.hide();
				}
			}

			if (data.people) {
				var people = Ext.fly(args.comboPeople);
				var saveValue = people.getValue();
				this.updateListOptions(people.dom, data.people, 0);
				people.dom.value = saveValue;
			}

            io.Spinner.hideSpinner();
        },

        //  private
        onUpdateRequirementsCountry: function(data, countryId) {
            var panelCity = Ext.get(Ext.query('div[id$=panelCity]')[0]);
            var cmbPeople = Ext.query('select[id$=cmbPeople]')[0];
            var cmbCity = Ext.query('select[id$=cmbCity]')[0];
            var txtTelephone = Ext.query('input[id$=txtTelephone]')[0];
            
            if(countryId > 0){
                var cmbCountry = Ext.query('select[id$=cmbCountry]')[0];
                cmbCountry.value = countryId;
            }
            
            if (txtTelephone.value.length < 6) {
                txtTelephone.value = data.prefix;
            }
            
            if (panelCity) {
                panelCity.setVisibilityMode(Ext.Element.DISPLAY);
                if (data.cities) {
                    panelCity.show();
                    this.updateListOptions(cmbCity, data.cities, 0);
                }
                else {
                    panelCity.hide();
                }
            }

            if (data.people) {
                this.updateListOptions(cmbPeople, data.people, 0);
            }

            io.Spinner.hideSpinner();
        },

        resetRating: function(e, el, p, rbEl){
			for(var i = 1; i <= 5; i++){
				var li = Ext.get(Ext.query('li:nth(' + i.toString() + ')' , rbEl.dom)[0]);
				li.removeCls("rating-select");
				li.addCls(li.defclass);
			}
        },
        
        resetRatingLarge: function(e, el, p, rbEl){
			for(var i = 1; i <= 5; i++){
				var li = Ext.get(Ext.query('li:nth(' + i.toString() + ')' , rbEl.dom)[0]);
				li.removeCls("rating-select-large");
				li.addCls(li.defclass);
			}
        },

        selectStar: function(e, el, p, li, index){
			var ul = li.dom.parentNode;
			for(var i = 1; i <= 5; i++){
				var li = Ext.get(Ext.query('li:nth(' + i.toString() + ')' , ul)[0]);
				if(i <= index){
					li.removeCls(li.defclass);
					li.addCls("rating-select");
				}
				else{
					li.removeCls("rating-select");
					li.addCls(li.defclass);
				}
			}
        },

        selectStarLarge: function(e, el, p, li, index){
			var ul = li.dom.parentNode;
			for(var i = 1; i <= 5; i++){
				var li = Ext.get(Ext.query('li:nth(' + i.toString() + ')' , ul)[0]);
				if(i <= index){
					li.removeCls(li.defclass);
					li.addCls("rating-select-large");
				}
				else{
					li.removeCls("rating-select-large");
					li.addCls(li.defclass);
				}
			}
        },

        updateRating: function(e, el, p, rbEl, centreId, i){
			this.invokeMethod('UpdateRating', { centreId: centreId, rating: i }, this.onRatingUpdated.createDelegate(this), [centreId, rbEl, i]);
        },
        
        updateRatingLarge: function(e, el, p, reviewRatingBlockEl, centreId, ratingValue){
			reviewRatingBlockEl.dom.rating = ratingValue;

			for(var i = 1; i <= 5; i++){
				var li = Ext.get(Ext.query('li:nth(' + i.toString() + ')' , reviewRatingBlockEl.dom)[0]);
				if(li){
					li.removeCls("rating-select-large");
					li.removeCls("rating-active-large");
					li.removeCls("rating-clear-large");
					if(i <= ratingValue){
						li.defclass = "rating-active-large";
					}
					else{
						li.defclass = "rating-clear-large";
					}
					li.addCls(li.defclass);
				}
			}
        },

        onRatingUpdated: function(ratingValue, args){
			var centreId = args[0];
			var rbEl = args[1];
			var myRating = args[2];

			this.fireEvent("rated", myRating, args);

			this.refreshRating(ratingValue,rbEl);			
        },
        
        refreshRating: function(ratingValue, rbEl){
			rbEl.removeAllListeners();
			for(var i = 1; i <= 5; i++){
				var li = Ext.get(Ext.query('li:nth(' + i.toString() + ')' , rbEl.dom)[0]);
				if(li){
					li.removeCls("rating-select");
					li.removeCls("rating-active");
					li.removeCls("rating-clear");
					if(i <= ratingValue){
						li.defclass = "rating-select";
					}
					else{
						li.defclass = "rating-clear";
					}
					li.addCls(li.defclass);
					li.removeCls("rating-selectable");
					li.removeAllListeners();
				}
			}
        },
        
        initSidebar: function(){
            this.sidebarAnchor = document.getElementById('sidebarAnchor');
            if (this.sidebarAnchor) {
                var t = Ext.query('*[id=listContainer]', this.sidebarAnchor)[0];
                if(t){
					if (t.tagName == 'TABLE') {
						var tbody = Ext.query('tbody', t)[0];
						if (!tbody) {
							t = Ext.core.DomHelper.append(t, '<tbody></tbody>');
						}
						else {
							t = tbody;
						}
					}

					this.listContainer = Ext.get(t);

					this.templateSelected = Ext.query('span[id$=templateSelected]', this.sidebarAnchor)[0];
					this.templateRequested = Ext.query('span[id$=templateRequested]', this.sidebarAnchor)[0];
					this.panelNoCentres = Ext.get(Ext.query('div[id$=panelNoCentres]', this.sidebarAnchor)[0]);
					this.panelCentres = Ext.get(Ext.query('div[id$=panelCentres]', this.sidebarAnchor)[0]);

					this.panelNoCentres.setVisibilityMode(Ext.Element.DISPLAY);
					this.panelCentres.setVisibilityMode(Ext.Element.DISPLAY);

					this.templateSelected = this.getCompiledTemplate(this.templateSelected.innerHTML);
					this.templateRequested = this.getCompiledTemplate(this.templateRequested.innerHTML);
	                
					//	inject tracking script 
					var support = Ext.get(Ext.query('div[id$=panelSupport]')[0]);
					if(support){
						var abtn = support.down('>a');
						if(abtn){
							abtn.on('click', function(){
								var img = document.createElement("img");
								img.src="https://tsw0.com/7132/?aid=3&value=non";
								img.height = 1;
								img.width = 1;
								img.border = 0;
								support.dom.appendChild(img);
							});
						}
					}
				
	                //  initial load of the basket data
					this.invokeMethod('GetBasketData', {hasbasket: true}, this.onCentresBasketLoaded.createDelegate(this));
				}
			}
        },
        
        //	private 
        initDefault: function(){
			this.attachTabs('tab-search', 'tab-office', 'tab-case');
			
			this.getLandingDetails();
			
			var aWorld = document.getElementById('world-map-link');
			if(aWorld){
				aWorld = Ext.fly(aWorld);
				aWorld.on('click', this.switchLandingPage.createDelegate(this, 0, true), this);
			}
        },
        
        initContactUs: function(){
			var cl = document.getElementById('contact-location');
			if(cl){
				var cb = new Ext.form.ComboBox ({
					store: [[0, 'UK (Headquarters)'], [1, 'USA'], [2, 'Australia']],
					hideLabel: true,
					width: 300,
					queryMode: 'local',
					value: parseInt(cl.getAttribute('io:value')),
					allowBlank: false,
					forceSelection: true,
					triggerAction: 'all',
					editable: false,
					renderTo: cl,
					msgTarget: 'title'
				});
				cb.on('select', function(combo, rec, index){
					var url = 'contact-uk.aspx';
					switch(index){
						case 1:
							url = 'contact-usa.aspx';
							break;
						case 2:
							url = 'contact-aus.aspx';
							break;
					}
					document.location = url;
				}, this);
			}			
			
			var map = document.getElementById('map-area');
			if(map){
				var q = map.getAttribute('io:geo').split(',');
				window.strings = ['',''];
				PD(map.getAttribute('io:title'), map.getAttribute('io:address'), '', q[0], q[1], '', '' , '', 0, 1, 1);
			}
			
			this.contactUserPhone = new Ext.form.TextField({
				width: 206,
				hideLabel: true,
				allowBlank: false,
				applyTo: Ext.query('input[id$=txtTelephone]')[0],
				vtype: 'phoneNumber',
				msgTarget: 'title'
			});
			
			this.invokeMethod('GetSidebarContent', null, this.onGetSessionDataSucceeded.createDelegate(this));
			
			Ext.fly(window).on('beforeunload', this.onWindowBeforeUnload, this);				
			
			this.attachTabs('menu');
        },

        refineSearchResults: function() {
			io.Spinner.showSpinner();
			
			var types = [];
			var s = this.refinePeopleNumber.getValue();
			var index = this.refinePeopleNumber.store.find('value', s);
			var rec = this.refinePeopleNumber.store.getAt(index);
			
            this.invokeMethod('SetRefineSearchResults', { rawUrl: window.rawUrl, reqSize: (rec ? rec.data.value : 0), reqSizeText: (rec ? rec.data.option_text : ''), minPrice : null, maxPrice: null, near: null, types: types}, this.onSearchParamsSet.createDelegate(this), rawUrl);
            return false;
        },
        
        getSearchRefine: function(){
			var refine = Ext.get('search-refine');
			if(refine){
				refine.mask('', 'x-mask-loading');
				this.invokeMethod('GetSearchRefine', { countryId: window.searchParams.countryID}, this.onGetSearchRefineSucceeded.createDelegate(this));
			}
        },

        onGetSearchRefineSucceeded: function(d, args){
			Ext.get('search-refine').unmask();
			
			this.refinePeopleNumber = new Ext.form.ComboBox ({
				store: new Ext.data.JsonStore({fields: ['value', 'option_text']}),
				hideLabel: true,
				width: 130,
				mode: 'local',
				allowBlank: true,
				emptyText: Ext.fly('refinePeopleNumber').dom.getAttribute('io:emptyText'),
				valueField:'value',
				displayField: 'option_text',
				forceSelection: true,
				triggerAction: 'all',
				selectOnFocus:true,
				editable: false,
				renderTo: 'refinePeopleNumber',
				msgTarget: 'title',
				listWidth: 200
			});
			//	Remove not sure option
			if(d.people.length > 0){
				d.people.splice(d.people.length-1, 1);
			}
			this.refinePeopleNumber.store.loadData(d.people);
			this.refinePeopleNumber.on('select', this.refineSearchResults, this);

			if(window.refine){
				if(window.refine.size > 0){
					this.refinePeopleNumber.setValue(window.refine.size);
				}
			}
		},
		
        attachSidebar: function(){
			if(!this.sidebarAnchor){
				return;
			}
			
			Ext.fly(window).on('beforeunload', this.onWindowBeforeUnload, this);
			var sl = Ext.fly('submit-link');
			if(sl){
				sl.on('click', function(e){ 
					e.stopEvent(); 
					
					if(window._gaq){
						if(window.pageType == 'centres'){
							window._gaq.push(['_trackPageview', 'requestsubmittedcenter']); 
						}
						else {
							window._gaq.push(['_trackPageview', 'requestsubmitted']); 
						}
					}
					
					this.createReport(false); 
					return false; 
				}, this);
			}
			var il = Ext.fly('iostaff-link');
			if(il){
				il.on('click', function(e){ e.stopEvent(); this.checkIOLogin(); return false; }, this);
			}
			
			var form = Ext.query('#form', document.getElementById('sidebarAnchor'))[0];

			//Ext.get('form').mask('', 'x-mask-loading');
			
			var userCompanyName = Ext.query('#user-companyname', form)[0];
			var userTitle = Ext.query('#user-title', form)[0];
			var userFirstName = Ext.query('#user-firstname', form)[0];
			var userLastName = Ext.query('#user-lastname', form)[0];
			var userCountry = Ext.query('#user-country', form)[0];
			var userRegion = Ext.query('#user-region', form)[0];
			var userPhone = Ext.query('#user-telephone', form)[0];
			var userEmail = Ext.query('#user-email', form)[0];
			var peopleNumber = Ext.query('#people-number', form)[0];
			var startDate = Ext.query('#start-date', form)[0];
			var viewDate = Ext.query('#view-date', form)[0];
			var viewTime = Ext.query('#view-time', form)[0];
			var furtherDetails = Ext.query('#further-details', form)[0];

			Ext.fly('further-details-link').on('click', function(e){
				e.stopEvent();
				this.sidebarControls.showSpecial(true);
				return false;
			}, this);

			this.sidebarControls = {
				sidebarAnchor: this.sidebarAnchor,
				
				userCompanyName: new Ext.form.TextField({
						width: 120,
						hideLabel: true,
						allowBlank: false,
						blankText: userCompanyName.getAttribute('io:blankText'),
						renderTo: userCompanyName,
						msgTarget: 'title'
					}),
				userTitle: userTitle ? new Ext.form.ComboBox ({
						store: Ext.decode(userTitle.getAttribute('io:data')),
						hideLabel: true,
						width: 120,
						queryMode: 'local',
						emptyText: userTitle.getAttribute('io:emptyText'),
						blankText: userTitle.getAttribute('io:blankText'),
						allowBlank: false,
						forceSelection: true,
						triggerAction: 'all',
						editable: false,
						renderTo: userTitle,
						msgTarget: 'title'
					}) : null,
				userFirstName: userFirstName ? new Ext.form.TextField({
						width: 120,
						hideLabel: true,
						allowBlank: false,
						emptyText: userFirstName.getAttribute('io:emptyText'),
						blankText: userFirstName.getAttribute('io:blankText'),
						renderTo: userFirstName,
						msgTarget: 'title'
					}) : null,
				userLastName: new Ext.form.TextField({
						width: 120,
						hideLabel: true,
						allowBlank: false,
						emptyText: userLastName.getAttribute('io:emptyText'),
						blankText: userLastName.getAttribute('io:blankText'),
						renderTo: userLastName,
						msgTarget: 'title'
					}),
				userCountry: new Ext.form.ComboBox ({
						store: new Ext.data.JsonStore({fields: ['id', 'country']}),
						hideLabel: true,
						width: 120,
						queryMode: 'local',
						emptyText: userCountry.getAttribute('io:emptyText'),
						blankText: userCountry.getAttribute('io:blankText'),
						allowBlank: false,
						valueField: 'id',
						displayField: 'country',
						forceSelection: true,
						triggerAction: 'all',
						editable: false,
						renderTo: userCountry,
						msgTarget: 'title',
						matchFieldWidth: false,
						listConfig:{
							width:200
						},
						listeners:{
							'select': function(combo, rec){
								this.getSidebarCountryData(rec[0].data.id);
							},
							scope: this
						}
					}),
				userRegion: new Ext.form.ComboBox ({
						store: new Ext.data.JsonStore({fields: ['countystateregionid', 'name']}),
						hideLabel: true,
						width: 120,
						queryMode: 'local',
						emptyText: userRegion.getAttribute('io:emptyText'),
						blankText: userRegion.getAttribute('io:blankText'),
						valueField: 'countystateregionid',
						displayField: 'name',
						allowBlank: false,
						forceSelection: true,
						triggerAction: 'all',
						editable: false,
						renderTo: userRegion,
						msgTarget: 'title',
						matchFieldWidth: false,
						listConfig:{
							width:200
						}
					}),
				userPhone: new Ext.form.TextField({
						width: 120,
						hideLabel: true,
						allowBlank: false,
						blankText: userPhone.getAttribute('io:blankText'),
						renderTo: userPhone,
						vtype: 'phoneNumber',
						vtypeText: userPhone.getAttribute('io:vtypeText'),
						msgTarget: 'title'
					}),
				userEmail: new Ext.form.TextField({
						width: 120,
						hideLabel: true,
						allowBlank: false,
						blankText: userEmail.getAttribute('io:blankText'),
						renderTo: userEmail,
						vtype: 'email',
						vtypeText: userEmail.getAttribute('io:vtypeText'),
						msgTarget: 'title'
					}),
				peopleNumber: new Ext.form.ComboBox ({
						store: new Ext.data.JsonStore({fields: ['value', 'option_text']}),
						hideLabel: true,
						width: 120,
						queryMode: 'local',
						emptyText: peopleNumber.getAttribute('io:emptyText'),
						blankText: peopleNumber.getAttribute('io:blankText'),
						allowBlank: false,
						valueField:'value',
						displayField: 'option_text',
						forceSelection: true,
						triggerAction: 'all',
						editable: false,
						renderTo: peopleNumber,
						msgTarget: 'title',
						matchFieldWidth: false,
						listConfig:{
							width:200
						}
					}),
				startDate: startDate ? new Ext.form.ComboBox ({
						store: Ext.decode(startDate.getAttribute('io:data')),
						hideLabel: true,
						width: 120,
						queryMode: 'local',
						emptyText: startDate.getAttribute('io:emptyText'),
						blankText: startDate.getAttribute('io:blankText'),
						allowBlank: false,
						forceSelection: true,
						triggerAction: 'all',
						editable: false,
						renderTo: startDate,
						msgTarget: 'title',
						matchFieldWidth: false,
						listConfig:{
							width:200
						}
					}) : null,
				viewDate: new Ext.form.DateField ({
						width: 120,
						hideLabel: true,
						renderTo: viewDate,
						format: 'd/m/Y',
						//allowBlank: false,
						blankText: viewDate.getAttribute('io:blankText'),
						msgTarget: 'title'
					}),
				viewTime: new Ext.form.TimeField ({
						width: 120,
						hideLabel: true,
						renderTo: viewTime,
						//allowBlank: false,
						blankText: viewTime.getAttribute('io:blankText'),
						msgTarget: 'title'
					}),
				furtherDetails: new Ext.form.TextArea({
						width: 120,
						hideLabel: true,
						renderTo: furtherDetails
					}),
					
				showRegions: function(v){
					Ext.each(Ext.query('*[io-switch=region]', this.sidebarAnchor), function(e){
						e.style.display = v ? '' : 'none';
					});
				},
				
				showSpecial: function(v){
					Ext.each(Ext.query('*[io-switch=special]', this.sidebarAnchor), function(e){
						e.style.display = v ? '' : 'none';
					});
					Ext.fly('further-details-cont').dom.style.display = v ? 'none' : '';
				}
			}
			
			form.style.display = '';
			
			this.layoutSidebar();
			
			if(this.sidebarControls.userCompanyName){
				attachEventHandler(this.sidebarControls.userCompanyName.inputEl.dom, 'focus', function() { _gaq.push(['_trackEvent', 'form', 'fieldfocus', 'company']); } );
			}
			if(this.sidebarControls.userTitle){
				attachEventHandler(this.sidebarControls.userTitle.inputEl.dom, 'focus', function() { _gaq.push(['_trackEvent', 'form', 'fieldfocus', 'title']); } );
			}
			if(this.sidebarControls.userFirstName){
				attachEventHandler(this.sidebarControls.userFirstName.inputEl.dom, 'focus', function() { _gaq.push(['_trackEvent', 'form', 'fieldfocus', 'name']); } );
			}
			if(this.sidebarControls.userLastName){
				attachEventHandler(this.sidebarControls.userLastName.inputEl.dom, 'focus', function() { _gaq.push(['_trackEvent', 'form', 'fieldfocus', 'lastname']); } );
			}
			if(this.sidebarControls.userCountry){
				attachEventHandler(this.sidebarControls.userCountry.inputEl.dom, 'focus', function() { 
					_gaq.push(['_trackEvent', 'form', 'fieldfocus', 'country']); 
					} );
			}
			if(this.sidebarControls.userPhone){
				attachEventHandler(this.sidebarControls.userPhone.inputEl.dom, 'focus', function() { _gaq.push(['_trackEvent', 'form', 'fieldfocus', 'phone']); } );
			}
			if(this.sidebarControls.userEmail){
				attachEventHandler(this.sidebarControls.userEmail.inputEl.dom, 'focus', function() { _gaq.push(['_trackEvent', 'form', 'fieldfocus', 'email']); } );
			}
			if(this.sidebarControls.peopleNumber){
				attachEventHandler(this.sidebarControls.peopleNumber.inputEl.dom, 'focus', function() { _gaq.push(['_trackEvent', 'form', 'fieldfocus', 'size']); } );
			}
			if(this.sidebarControls.startDate){
				attachEventHandler(this.sidebarControls.startDate.inputEl.dom, 'focus', function() { _gaq.push(['_trackEvent', 'form', 'fieldfocus', 'start']); } );
			}	
			if(sl){	
				attachEventHandler(sl.dom, 'mouseover', function() { 
					_gaq.push(['_trackEvent', 'form', 'submitbutton', 'submitmouseover']); 
				} );
			}

			this.invokeMethod('GetSidebarContent', null, this.onGetSidebarContentSucceeded.createDelegate(this));
        },
        
        layoutSidebar: function(){
			Ext.iterate(this.sidebarControls, function(key, item){
				if(item && item.doComponentLayout){
					delete item.componentLayout.lastComponentSize;
					item.doComponentLayout();
				}
			}, this);
        },
        
		getLocalConsultant: function(){
			if(!Ext.get('local-consultant')){
				return;
			}
			Ext.get('local-consultant').mask('', 'x-mask-loading');
            this.invokeMethod('GetLocalConsultant', { firstCentreId: this.firstCentreId, reqSize: window.searchParams ? window.searchParams.reqSize : 1}, this.onGetLocalConsultantSucceeded.createDelegate(this));
        },
        
        onGetLocalConsultantSucceeded: function(d, args){
			if(!this.templates['local-consultant-template']) {
				this.templates['local-consultant-template'] = this.getCompiledTemplate(Ext.get('local-consultant-template').dom.innerHTML);
			}
			
			var cel = Ext.get('local-consultant');
			cel.update(this.templates['local-consultant-template'].apply(d));
			
			var mailto = Ext.query('a[href^=mailto]', Ext.getDom(cel))[0];
			if(mailto){
				Ext.fly(mailto).on('click', function(){
					if(window._gaq){
						if(window.pageType == 'centres'){
							window._gaq.push(['_trackPageview', 'emailrequestedcenter']);
						}
						else {
							window._gaq.push(['_trackPageview', 'emailrequested']);
						}
						return true;
					}
				}, this);
			}
			
			cel.unmask();
        },
        
        processSidebarForm: function(validation){
			var saveData = {};
			var missing = [];
			var incorrect = [];
			var hasValues = false;

			if(window.pageType == 'contact-us'){
				var d = Ext.query('input', document.getElementById('contact-us')).concat(Ext.query('select', document.getElementById('contact-us')));
				Ext.each(d, function(f){
					var id = f.id.split('_');
					id = id[id.length-1].toLowerCase();
					switch(id){
						case 'cmbtitle':
							id = 'userTitle';
							break;
						case 'txtfirstname':
							id = 'userFirstName';
							break;
						case 'txtlastname':
							id = 'userLastName';
							break;
						case 'txtcompanyname':
							id = 'userCompanyName';
							break;
						case 'txttelephone':
							id = 'userPhone';
							break;
						case 'txtmobile':
							id = 'userMobile';
							break;
						case 'txtemail':
							id = 'userEmail';
							break;
						case 'cmbcountry':
							id = 'userCountry';
							break;
					}
					saveData[id] = f.value;
				});
			}
			else{
				for(var e in this.sidebarControls){
					if(this.sidebarControls.hasOwnProperty(e)){
						var f = this.sidebarControls[e];
						if(f && f.getValue){
							f.preventMark = false;

							var v = f.getValue();
							
							var li = f.getEl().up('li');
							if(li && li.dom && li.dom.style.display != 'none')
							{
								var defValue = f.getEl().dom.getAttribute("defvalue");
								if((!v || v == defValue) && !f.disabled && !f.allowBlank) {
									missing.push(e);
								}
								else if(e == 'userPhone' && !f.isDirty() && !f.isValid(!validation)){
									missing.push(e);
								}
								
								if(f.isDirty() && e != 'userCountry'){
									hasValues = true;
								}
								
								if(v && v != f.getEl().dom.getAttribute("defvalue") && !f.isValid(!validation) && (e != 'userPhone' || f.isDirty())) {
									incorrect.push(e);
								}
								f.preventMark = true;
								if(Ext.isDate(v)){
									v = v.format('Y-m-d');
								}
							}
							
							saveData[e] = v;
						}
					}
				}
			}
			this.invokeMethodSync('SaveVisitorData', { data: saveData, missing: missing, incorrect: incorrect, validation: validation, hasValues : hasValues } );
        },

        onWindowBeforeUnload: function(){
			this.processSidebarForm(false);
        },
        
        getSidebarCountryData: function(countryId) {
            //Ext.get('form').mask('', 'x-mask-loading');
            this.invokeMethod('GetSidebarCountryData', { countryId: countryId }, this.onGetSidebarCountryDataSucceeded.createDelegate(this));
        },

        getContactCountryData: function(ctrl, phone) {
            this.invokeMethod('GetSidebarCountryData', { countryId: ctrl.value || 0 }, this.onGetContactCountryDataSucceeded.createDelegate(this, phone, true));
        },

        onGetSidebarCountryDataSucceeded: function(d, args) {
			if(this.sidebarControls.userRegion){
				var store = this.sidebarControls.userRegion.store;
				if(d.regions){
					this.sidebarControls.userRegion.enable();
					store.loadData(d.regions);
					this.sidebarControls.userRegion.setValue('');
					this.sidebarControls.showRegions(true);
				}
				else {
					this.sidebarControls.userRegion.disable();
					store.removeAll();
					this.sidebarControls.userRegion.setValue('');
					this.sidebarControls.showRegions(false);
				}
			}
			
			this.layoutSidebar();
			
			var phone = this.sidebarControls.userPhone;
			if (phone.getValue().length < 6) {
				phone.originalValue = d.prefix;
				phone.setValue(d.prefix);
			}

            //Ext.get('form').unmask();
        },

        onGetContactCountryDataSucceeded: function(d, args, phone) {
			var ctrl = Ext.fly(phone);
			if (ctrl.getValue().length < 6) {
				ctrl.dom.value = d.prefix;
			}
        },

        onGetSidebarContentSucceeded: function(d, args){
			this.sidebarControls.userCountry.store.loadData(d.countries);
			this.sidebarControls.peopleNumber.store.loadData(d.people);
			if(d.io){
				Ext.fly('iostaff-link').show();
			}
			this.onGetSidebarCountryDataSucceeded(d);
			
			Ext.iterate(this.sidebarControls, function(n, f){
				if(f && f.clearInvalid){
					f.clearInvalid();
					f.preventMark = true;
				}
			});
			
			for(var e in d.sideData){
				if(d.sideData.hasOwnProperty(e) && this.sidebarControls[e]){
					var c = this.sidebarControls[e];
					c.originalValue = d.sideData[e];
					if(!(e == 'userPhone' && (d.sideData[e] || '').length == 0))
					{
						c.setValue(d.sideData[e]);
					}
					
					if(e == 'furtherDetails' && d.sideData[e] && d.sideData[e].length > 0){
						this.sidebarControls.showSpecial(true);
					}
				}
			}
        },

        onGetC2CSidebarContentSucceeded: function(d, args){
			this.sidebarControls.userCountry.store.loadData(d.countries);
			
			this.sidebarControls.userCountry.setValue(window.visitorCountry || 1);

			var phone = this.sidebarControls.userPhone;
			if (phone.getValue().length < 6) {
				phone.originalValue = d.prefix;
				phone.setValue(d.prefix);
			}

			Ext.iterate(this.sidebarControls, function(n, f){
				if(f && f.clearInvalid){
					f.clearInvalid();
					f.preventMark = true;
				}
			});
        },

        onGetVirtualSidebarContentSucceeded: function(d, args){
			var phone = this.sidebarControls.userPhone;
			if (phone.getValue().length < 6) {
				phone.originalValue = d.prefix;
				phone.setValue(d.prefix);
			}

			Ext.iterate(this.sidebarControls, function(n, f){
				if(f && f.clearInvalid){
					f.clearInvalid();
					f.preventMark = true;
				}
			});
        },
	
		onGetSessionDataSucceeded: function(d, args){
			Ext.iterate(d.sideData, function(id, data){
				var a = Ext.query('#' + id);
				if(a.length == 0){
					switch(id){
						case 'userTitle':
							id = 'cmbTitle';
							break;
						case 'userFirstName':
							id = 'txtFirstName';
							break;
						case 'userLastName':
							id = 'txtLastName';
							break;
						case 'userCompanyName':
							id = 'txtCompanyName';
							break;
						case 'userPhone':
							id = 'txtTelephone';
							break;
						case 'userMobile':
							id = 'txtMobile';
							break;
						case 'userEmail':
							id = 'txtEmail';
							break;
						case 'userCountry':
							id = 'cmbCountry';
							break;
					}
					a = Ext.query('[id$=' + id + ']');
				}
				var field = a[0];
				if(field){
					field.value = data;
				}
			});
        },
        
        attachSortPricing: function() {
			var fs = document.getElementById('sort-pricing-field');
			if(!fs){
				return;
			}
			
			var optionsData = Ext.decode(fs.getAttribute('io:data'));
			if(window.sortopts){
				var t = optionsData;
				optionsData = [t[0]];
				Ext.each(window.sortopts.split(','), function(index){
					if(index){
						optionsData.push(t[index]);
					}
				});
			}

			this.sortPrice = new Ext.form.ComboBox({
				hideParent: true,
				hideLabel: true,
				queryMode: 'local',
				forceSelection: true,
				triggerAction: 'all',
				editable: false,
				valueField: 'id',
				displayField: 'text',
				width: 200,
				emptyText: fs.getAttribute('io:emptyText'),
				listeners:
				{	
					'select': function(combo, rec){
						this.onChangeResultsSort(combo.value);
						return;
					},
					scope: this
				},
				store: optionsData,
				renderTo: fs,
				value: window.sortId || ''
			});
        },
        
        onChangeResultsSort: function(sortId){
			var url = window.rawUrl;
			var a = document.URL.split("?");
			var params = Ext.urlDecode(a[1]);
			params.sort = sortId;
			document.location = a[0] + '?' + Ext.urlEncode(params);
        },

        attachLeftMenuSearch: function(){
			if(!document.getElementById('leftmenu-search')){
				return;
			}
			
			rel = '';//window.siteBaseUrl;
			
			var srch = function(e){
				this.onInstantSearch(e, rel);
			};
			
			var cs = document.getElementById('leftmenu-search-country');
			var rs = document.getElementById('leftmenu-search-region');
			var as = document.getElementById('leftmenu-search-city');
			var fs = document.getElementById('leftmenu-search-text');
			var gb = document.getElementById('leftmenu-search-go');
			if(gb){
				Ext.fly(gb).on('click', srch, this);
			}

			this.quickSearchCountry = new Ext.form.ComboBox({
				hideParent: true,
				hideLabel: true,
				queryMode: 'local',
				forceSelection: true,
				triggerAction: 'all',
				selectOnFocus:true,
				editable: true,
				valueField: 'id',
				displayField: 'countryname',
				width: 200,
				emptyText: cs.getAttribute('io:emptyText'),
				listeners:
				{	
					'select': function(combo, rec){
						this.tryCountrySearch(rec[0].data.id, rel);
					},
					scope: this
				},
				store: new Ext.data.JsonStore({
					fields: [
						'id', 'countryname', 'worldzoneid'
					]
				}),
				renderTo: cs
			});
			
			if(rs){
				this.quickSearchRegion = new Ext.form.ComboBox({
					hideParent: true,
					hideLabel: true,
					queryMode: 'local',
					forceSelection: true,
					triggerAction: 'all',
					selectOnFocus:true,
					editable: true,
					valueField: 'countystateregionid',
					displayField: 'regionname',
					width: 200,
					emptyText: rs.getAttribute('io:emptytext'),
					listeners:
					{	
						'select': function(combo, rec){
							this.gotoRegionLanding(String(rec[0].data.countystateregionid), rel);
						},
						scope: this
					},
					store : new Ext.data.JsonStore({
						fields: [
							'countystateregionid', 'regionname'
						]
					}),
					renderTo: rs
				});
			}
			
			this.quickSearchCity = new Ext.form.ComboBox({
				hideParent: true,
				hideLabel: true,
				queryMode: 'local',
				forceSelection: true,
				triggerAction: 'all',
				selectOnFocus:true,
				editable: true,
				valueField: 'areaid',
				displayField: 'areaname',
				width: 200,
				emptyText: as.getAttribute('io:emptyText'),
				listeners:
				{	
					'select': function(combo, rec){
						this.gotoCityLanding(String(rec[0].data.areaid), rel);
					},
					scope: this
				},
				store: new Ext.data.JsonStore({
					fields: [
						'areaid', 'areaname'
					]
				}),
				renderTo: as
			});
			
			if(window.pt){
				this.quickSearchText = new Ext.form.ComboBox({
					width: 200,
					id:'txtSearch',
					hideTrigger: true,
					hideLabel: true,
					queryMode: 'local',
					editable:true,
					minChars: 3,
					queryDelay: 500,
					valueField: 'areaid',
					displayField: 'areatitle',
					store: new Ext.data.JsonStore({
						fields: ['areaid', 'areaname', 'areatype', 'areatitle', 'countryid', 'regionid', 'cityid', 'districtid', 'latitude', 'longitude'],
						proxy: new Ext.data.AjaxProxy({
							startParam: null,
							limitParam: null,
							pageParam: null,
							url: wsRefs.iows + '/GetSearchSuggestions',
							buildUrl: function(request){
								var r = Ext.data.proxy.Server.prototype.buildUrl.call(this, request);
								request.jsonData = request.operation.params;
								delete request.operation.params;
								return r;
							}
						}),
						listeners: {
							'beforeload' : function(store, options){
								options.params = { query: options.params.query.trim(), wzId: 0, countryId: this.quickSearchCountry.getValue() || 0, gaz: window.gaz || false };
							},
							'load': function(store){
								if(store.getCount() == 0){
									this.quickSearchText.collapse();
								}
							},
							scope: this
						}
					}),
					listeners:
					{	
						'specialkey': function(f, e){
							if(e.getKey() == e.ENTER){
								srch.apply(this, [e]);
							}
						},
						scope: this
					},
					renderTo: fs
				});
			}
			else {
				this.quickSearchText = new Ext.form.TextField({
					width: 200,
					id:'txtSearch',
					hideLabel: true,
					listeners:
					{	
						'specialkey': function(f, e){
							if(e.getKey() == e.ENTER){
								srch.apply(this, [e]);
							}
						},
						scope: this
					},
					renderTo: fs
				});
			}
			
			this.invokeMethod('GetLandingDetails', {mapId: 0, wzId: 0, countryId: window.countryId || 0, regionId: 0, cityId: 0, districtId: 0 }, this.onGetLandingDetailsSucceeded.createDelegate(this));
        },
        
        tryCountrySearch: function(countryId, rel){
			if(this.quickSearchRegion){
				this.quickSearchRegion.container.hide('display');
			}
			if(this.quickSearchCity){
				this.quickSearchCity.container.hide('display');
			}
			this.invokeMethod('GetLandingDetails', {mapId: 0, wzId: 0, countryId: countryId, regionId: 0, cityId: 0, districtId: 0 }, this.onTryCountrySearchSucceeded.createDelegate(this, [rel], true));
        },
        
        onTryCountrySearchSucceeded: function(d, rel){
			if(d.url){
				document.location = window.siteBaseUrl + (rel || '') + d.url;
				return;
			}

			window.countryId = d.map[0].countryid || 0;
			window.wzId = d.map[0].worldzoneid || 0;
			
			if(this.quickSearchRegion && d.regions && d.regions.length > 0){
				this.quickSearchRegion.container.removeCls('x-hide-display');
				this.quickSearchRegion.container.show('display');
				this.quickSearchRegion.store.loadData(d.regions);
			}
			if(d.cities && d.cities.length > 0){
				this.quickSearchCity.container.removeCls('x-hide-display');
				this.quickSearchCity.container.show('display');
				this.quickSearchCity.store.loadData(d.cities);
			}
			else if(this.quickSearchCity) {
				this.quickSearchCity.collapse();
				this.quickSearchCity.container.hide('display');
			}

			delete this.quickSearchCountry.componentLayout.lastComponentSize;
			this.quickSearchCountry.doComponentLayout();

			delete this.quickSearchCity.componentLayout.lastComponentSize;
			this.quickSearchCity.doComponentLayout();

			if(this.quickSearchRegion){
				delete this.quickSearchRegion.componentLayout.lastComponentSize;
				this.quickSearchRegion.doComponentLayout();
			}
        },

        getLandingDetails: function(){
			this.maskMap();
			
			var cs = document.getElementById('quick-search-country');
			var ds = document.getElementById('quick-search-district');
			var rs = document.getElementById('quick-search-region');
			var as = document.getElementById('quick-search-city');
			var fs = document.getElementById('quick-search-text');
			var gb = document.getElementById('quick-search-go');
			Ext.fly(gb).on('click', this.onInstantSearch, this);

			this.quickSearchCountry = new Ext.form.ComboBox({
				hideParent: true,
				hideLabel: true,
				queryMode: 'local',
				forceSelection: true,
				triggerAction: 'all',
				selectOnFocus:true,
				editable: true,
				valueField: 'id',
				displayField: 'countryname',
				width: 230,
				emptyText: cs.getAttribute('io:emptyText'),
				listeners:
				{	
					'select': this.onCountrySelected,
					scope: this
				},
				renderTo: cs,
				store: new Ext.data.JsonStore({
					fields: [
						'id', 'countryname', 'worldzoneid'
					]
				})				
			});
			
			this.quickSearchRegion = new Ext.form.ComboBox({
				hideParent: true,
				hideLabel: true,
				queryMode: 'local',
				forceSelection: true,
				triggerAction: 'all',
				selectOnFocus:true,
				editable: true,
				valueField: 'countystateregionid',
				displayField: 'regionname',
				width: 230,
				emptyText: rs.getAttribute('io:emptytext'),
				listeners:
				{	
					'select': this.onRegionSelected,
					scope: this
				},
				renderTo: rs,
				store: new Ext.data.JsonStore({
					fields: [
						'countystateregionid', 'regionname'
					]
				})
			});
			this.quickSearchCity = new Ext.form.ComboBox({
				hideParent: true,
				hideLabel: true,
				queryMode: 'local',
				forceSelection: true,
				triggerAction: 'all',
				selectOnFocus:true,
				editable: true,
				valueField: 'areacode',
				displayField: 'areaname',
				width: 230,
				emptyTextCity: as.getAttribute('io:emptytextcity'),
				emptyTextDistrict: as.getAttribute('io:emptytextdistrict'),
				listeners:
				{	
					'select': this.onCitySelected,
					scope: this
				},
				renderTo: as,
				store: new Ext.data.JsonStore({
					fields: [
						'areaid', 'areaname', 'areatype', 'areacode'
					]
				})				
			});
			/*
			this.quickSearchDistrict = new Ext.form.ComboBox({
				hideParent: true,
				hideLabel: true,
				queryMode: 'local',
				forceSelection: true,
				triggerAction: 'all',
				selectOnFocus:true,
				editable: true,
				valueField: 'areaid',
				displayField: 'areaname',
				width: 230,
				emptyText: ds.getAttribute('io:emptyText'),
				listeners:
				{	
					'select': this.onDistrictSelected,
					scope: this
				},
				renderTo: ds
			});
			*/

			if(window.pt){
				this.quickSearchText = new Ext.form.ComboBox({
					width: 230,
					hideLabel: true,
					hideTrigger: true,
					queryMode: 'remote',
					editable:true,
					//typeAhead: true,
					//typeAheadDelay: 50,
					queryDelay: 500,
					minChars: 3,
					valueField: 'areaid',
					displayField: 'areatitle',
					store: new Ext.data.JsonStore({
						fields: ['areaid', 'areaname', 'areatype', 'areatitle', 'countryid', 'regionid', 'cityid', 'districtid', 'latitude', 'longitude'],
						proxy: new Ext.data.AjaxProxy({
							startParam: null,
							limitParam: null,
							pageParam: null,
							url: wsRefs.iows + '/GetSearchSuggestions',
							buildUrl: function(request){
								var r = Ext.data.proxy.Server.prototype.buildUrl.call(this, request);
								request.jsonData = request.operation.params;
								delete request.operation.params;
								return r;
							}
						}),
						listeners: {
							'beforeload' : function(store, options){
								options.params = { query: options.params.query.trim(), wzId: window.wzId || 0, countryId: window.countryId || 0, gaz: window.gaz || false };
							},
							'load': function(store){
								if(store.getCount() == 0){
									this.quickSearchText.collapse();
								}
							},
							scope: this
						}
					}),
					listeners:
					{	
						'specialkey': function(f, e){
							if(e.getKey() == e.ENTER){
								this.onInstantSearch(e);
							}
						},
						scope: this
					},
					renderTo: fs
				});
			}
			else {
				this.quickSearchText = new Ext.form.TextField({
					width: 230,
					id:'txtSearch',
					hideLabel: true,
					listeners:
					{	
						'specialkey': function(f, e){
							if(e.getKey() == e.ENTER){
								this.onInstantSearch(e);
							}
						},
						scope: this
					},
					renderTo: fs
				});
			}
			
			var tryLang = this.readCookie('switchmap');
			if(tryLang && tryLang.length > 0){
				var a = this.languageMap[tryLang] || [];
				window.wzId = a[0] || 0;
				window.countryId = a[1] || 0;
				window.mapId = 0;
			}
			this.deleteCookie('switchmap', '/');
			
			this.invokeMethod('GetLandingDetails', {mapId: window.mapId, wzId: window.wzId, countryId: window.countryId, regionId: 0, cityId: 0, districtId: 0 }, this.onGetLandingDetailsSucceeded.createDelegate(this));
        },
        
        onGetLandingDetailsSucceeded: function(d, args, rel){
			window.focus();
			this.updateVal('');
			
			if(d.url){
				document.location = window.siteBaseUrl + d.url;
				return;
			}

			var landingareas = Ext.get("landing-areas");
			if(landingareas){
				landingareas.setVisibilityMode(Ext.Element.DISPLAY);
				landingareas.hide();
			}

			var dropdownarea = Ext.get('drop-down-area');
			if(dropdownarea){
				dropdownarea.setVisibilityMode(Ext.Element.DISPLAY);
				dropdownarea.hide();
			}
			
			if(window.pt){
				this.quickSearchText.store.removeAll();
				this.quickSearchText.lastQuery = '';
			}
			this.quickSearchText.setValue('');

			var landingmap = Ext.get('landing-map');
			if(landingmap){
				landingmap.setVisibilityMode(Ext.Element.DISPLAY);
				landingmap.hide();
			}

            var places = Ext.query('div[id=multiple-results]')[0];
			if(d.places){
                var listContainer = Ext.query('ul[id$=listContainerMS]', places)[0];
                var templatePlace = Ext.query('span[id$=templatePlace]', places)[0];
                templatePlace = this.getCompiledTemplate(templatePlace.innerHTML);

                places.style.display = '';
                listContainer.innerHTML = '';

                for (var i = 0, n = d.places.length; i < n; i++) {
                    var pl = d.places[i];
                    var placeTitle = '';

                    if (pl.PostCode.length == 0) {
                        if (pl.RegionName.length > 0) {
                            placeTitle = [pl.CountryName, pl.RegionName, pl.CityName].join(', ');
                        }
                        else {
                            placeTitle = [pl.CountryName, pl.CityName].join(', ');
                        }

                        if (pl.DistrictName.length > 0) {
                            placeTitle = [placeTitle, pl.DistrictName].join(', ');
                        }
                    }
                    else {
                        placeTitle = [pl.CountryName, pl.PostCode].join(', ');
                    }

                    var dp = [];
                    dp.push(window.siteBaseUrl + pl.LandingUrl);
                    dp.push(placeTitle);

                    Ext.core.DomHelper.append(listContainer, templatePlace.apply(dp));
                }
				this.unmaskMap();
                return;
			}
			places.style.display = 'none';

			window.countryId = d.map[0].countryid || 0;
			window.wzId = d.map[0].worldzoneid || 0;
			window.regionId = d.map[0].regionid || 0;
			window.cityId = d.map[0].cityid || 0;
			window.districtId = d.map[0].districtid || 0;
			
			if(d.map[0].sectiontitle1){
				var ts = document.getElementById('sectiontitle1');
				if(ts){
					ts.innerHTML = d.map[0].sectiontitle1;
				}
			}
			if(d.map[0].sectiontitle2){
				var ts = document.getElementById('sectiontitle2');
				if(ts){
					ts.innerHTML = d.map[0].sectiontitle2;
				}
			}
			if(d.map[0].sectiontext1){
				var ts = document.getElementById('sectiontext1');
				if(ts){
					ts.innerHTML = d.map[0].sectiontext1;
				}
			}
			if(d.map[0].sectiontext2){
				var ts = document.getElementById('sectiontext2');
				if(ts){
					ts.innerHTML = d.map[0].sectiontext2;
				}
			}
			
			if(d.countries && d.countries.length > 0){
				this.quickSearchCity.setValue('');
				this.quickSearchCountry.container.removeCls('x-hide-display');
				this.quickSearchCountry.container.show('display');
				this.quickSearchCountry.hasFocus = false;
				this.quickSearchCountry.store.loadData(d.countries);
				
				this.quickSearchCountry.setValue('');
				if(window.countryId > 0){
					var r = this.quickSearchCountry.store.getById(window.countryId);
					if(r){
						this.quickSearchCountry.setValue(countryId);
					}
				}
			}
			else{
				this.quickSearchCountry.collapse();
				this.quickSearchCountry.container.hide('display');
			}

			if(this.quickSearchRegion){
				if(d.regions && d.regions.length > 0 && (window.countryId == 35 || window.countryId == 50 || window.countryId == 37)){
					this.quickSearchRegion.setValue('');
					this.quickSearchCity.setValue('');
					
					this.quickSearchRegion.container.removeCls('x-hide-display');
					this.quickSearchRegion.container.show('display');
					this.quickSearchRegion.hasFocus = false;
					this.quickSearchRegion.store.loadData(d.regions);
				}
				else{
					this.quickSearchRegion.collapse();
					this.quickSearchRegion.container.hide('display');
				}
			}

			if(d.cities && d.cities.length > 0){
				this.quickSearchCity.emptyText = this.quickSearchCity.emptyTextCity;
				this.quickSearchCity.setValue('');
				this.quickSearchCity.hasFocus = false;
				this.quickSearchCity.applyEmptyText();
				this.quickSearchCity.store.loadData(d.cities);
				this.quickSearchCity.container.removeCls('x-hide-display');
				this.quickSearchCity.container.show('display');
			}
			if(d.alldistricts && d.alldistricts.length > 0){
				if(!d.cities || d.cities.length == 0){
					this.quickSearchCity.emptyText = this.quickSearchCity.emptyTextDistrict;
				}
				
				this.quickSearchCity.setValue('');
				this.quickSearchCity.getEl().blur();
				this.quickSearchCity.hasFocus = false;
				this.quickSearchCity.applyEmptyText();
				this.quickSearchCity.store.loadData(d.alldistricts, (d.cities.length > 0));
				this.quickSearchCity.container.removeCls('x-hide-display');
				this.quickSearchCity.container.show('display');
				this.quickSearchCity.store.sort('areaname', 'ASC');
			}
			
			if((!d.cities || d.cities.length == 0) && (!d.alldistricts || d.alldistricts.length == 0)){
				if(this.quickSearchCity) {
					this.quickSearchCity.collapse();
					this.quickSearchCity.container.hide('display');
				}
			}

			/*			
			if(d.alldistricts && d.alldistricts.length > 0){
				this.quickSearchDistrict.store = new Ext.data.JsonStore({
					fields: [
						'areaid', 'areaname', 'areatype'
					]
				});
				this.quickSearchDistrict.show();
				this.quickSearchDistrict.store.loadData(d.alldistricts);
			}
			else if(this.quickSearchDistrict) {
				this.quickSearchDistrict.collapse();
				this.quickSearchDistrict.hide();
			}
			*/

			//	render quick links
			if(d.maplinks && d.maplinks.length > 0 && Ext.fly('quickLinksTemplate')){
				if(!this.templates['quickLinksTemplate']) {
					this.templates['quickLinksTemplate'] = this.getCompiledTemplate(Ext.get('quickLinksTemplate').dom.innerHTML);
				}
				Ext.each(d.maplinks, function(a){
					a.linkurl = /*a.mapsefpagename ? a.mapsefpagename + '.aspx' : */a.linkurl || '';
				});
				
				var quickLinks = Ext.get('quickLinks');
				quickLinks = quickLinks.update(this.templates['quickLinksTemplate'].apply(d.maplinks));
				Ext.each(Ext.query('a', quickLinks.dom), function(a, i){
					if(d.maplinks[i].linkurl.length > 0){
						return true;
					}
					var mapid = a.id.substring('quick-link-'.length);
					a = Ext.fly(a);
					a.on('click', this.switchLandingPage.createDelegate(this, [mapid], true), this);
				}, this);
			}
			
			var breadcrumb = Ext.get('breadcrumb-links');
			if(breadcrumb){
				if(!this.templates['breadcrumbTemplate']) {
					this.templates['breadcrumbTemplate'] = this.getCompiledTemplate(Ext.get('breadcrumbTemplate').dom.innerHTML);
				}

				breadcrumb.update(this.templates['breadcrumbTemplate'].apply([]));
				if(d.breadcrumb && d.breadcrumb.length > 0 && Ext.fly('breadcrumbTemplate')){
					
					breadcrumb = breadcrumb.update(this.templates['breadcrumbTemplate'].apply(d.breadcrumb));
					Ext.each(Ext.query('a', breadcrumb.dom), function(a){
						var mapid = a.id.substring('breadcrumb-link-'.length);
						a = Ext.fly(a);
						a.on('click', this.switchLandingPage.createDelegate(this, [mapid], true), this);
					}, this);
				}
			}
			
			if(landingareas){
				if(d.map[0].mapimage && d.mapparts && d.mapparts.length > 0){
					var imgMap = Ext.get('imgMap');
					
					var mapparts = Ext.get('mapparts');
					
					for(var n = 0; n < mapparts.dom.childNodes.length; n++){
						var mp = Ext.fly(mapparts.dom.childNodes[n]);
						if(mp){
							if(mp.clearListeners) mp.clearListeners();
							if(mp.removeAllListeners) mp.removeAllListeners();
						}
					}
					
					mapparts.update('');

					imgMap.dom.src = window.appBaseUrl + 'images/maps_2/' + d.map[0].mapimage + '_bg.gif';
					imgMap.dom.style.backround = 'url(\'' + imgMap.dom.src + '\') no-repeat center center';
					Ext.each(d.mapparts, function(p){
						var a = document.createElement('area');
						a.shape = 'poly';
						a.coords = p.mappartcoords2;
						a.alt = p.parttitle;
						//a.href = window.siteBaseUrl + p.mapsefpagename + '.aspx';
						a.href = "";
						a = Ext.fly(a);
						a.on('mouseover', this.swapMapImage.createDelegate(this, [imgMap, window.appBaseUrl + 'images/maps_2/' + p.mappartimage + '.gif'], true), this);
						a.on('mouseout', this.swapMapImage.createDelegate(this, [imgMap, window.appBaseUrl + 'images/maps_2/' + p.mapimage + '_bg.gif'], true), this);
						a.on('click', this.switchLandingPage.createDelegate(this, [p.mapid], true), this);
						mapparts.appendChild(a);
					}, this);

					landingmap.show();
					dropdownarea.show();
					
					delete this.quickSearchCountry.componentLayout.lastComponentSize;
					this.quickSearchCountry.doComponentLayout();

					delete this.quickSearchCity.componentLayout.lastComponentSize;
					this.quickSearchCity.doComponentLayout();

					delete this.quickSearchRegion.componentLayout.lastComponentSize;
					this.quickSearchRegion.doComponentLayout();
				}
				else 
				{
					if(d.areas){
						if(!this.templates['areasTemplate']) {
							this.templates['areasTemplate'] = this.getCompiledTemplate(Ext.get('areasTemplate').dom.innerHTML);
						}
						
						var td = { hasdistricts: false, cityid: 'br', areacode: null};
						var br = { hasdistricts: false, cityid: 'br', areacode: null};
						
						var i = 0;
						var dc = [];
						var needbr = false;
						Ext.each(d.areas, function(c) {
							c.hasdistricts = !!(c.hasdistricts === true || c.hasdistricts != '0');
							if(c.hasdistricts && !c.citydistrictid) {
								if(i % 2 > 0){
									dc.push(td);
									i++;
								}								

								dc.push(c);	
								i++;

								dc.push(td);
								i++;
							}
							else{
								if(needbr && !c.citydistrictid){
									dc.push(td);
									dc.push(td);
									dc.push(td);
									needbr = false;
								}
								
								dc.push(c);
								i++;

								if(c.citydistrictid){
									needbr = true;
								}
							}
						});
						if(i % 2 == 0){
							dc.push(td);
						}								
						
						d.areas = dc;
						
						landingareas.update(this.templates['areasTemplate'].apply(d));
						
						var cityChecks = Ext.query('input[aid^=C]', landingareas.dom);
						Ext.each(cityChecks, function(c){
							Ext.fly(c).on('click', function(e, dom){
								Ext.each(Ext.query('input[districtcityid^=' + dom.getAttribute('cityid') + ']', landingareas.dom), function(d){
									d.checked = dom.checked;
								});
							});
						});
						
						var areaChecks = Ext.query('input', landingareas.dom);
						Ext.each(areaChecks, function(c){
							var c = Ext.fly(c);
							var lnk = c.parent().down('a');
							lnk.on('click', function(e, dom, o, chk){
								var sel = [];
								sel.push({ areaId: chk.getAttribute('aid'), cityId: chk.getAttribute('districtcityid') });

								io.Spinner.showSpinner();
								this.invokeMethod('LandingSelectionSearch', { sel: sel, countryId: window.countryId, regionId: window.regionId, cityId: window.cityId }, this.onLandingSearchComplete.createDelegate(this));

							}.createDelegate(this, [c.dom], true));
						}, this);
						
						var a = Ext.fly(Ext.query('#search-selection', landingareas.dom)[0]);
						a.on('click', function(e){
							e.stopEvent();
							this.doLandingSelectionSearch();
						}, this);
						
						dropdownarea.hide();
						landingareas.show();
					}
				}
			}			
			
			this.unmaskMap();
        },
        
        switchLandingPage: function(e, dom, o, mapId){
			e.stopEvent();
			this.maskMap();
			//this.invokeMethod('GetLandingDetails', {mapId: mapId || 0, wzId: window.wzId, countryId: window.countryId, regionId: window.regionId, cityId: window.cityId, districtId: window.districtId }, this.onGetLandingDetailsSucceeded.createDelegate(this));
			this.invokeMethod('GetLandingDetails', {mapId: mapId || 0, wzId: 0, countryId: 0, regionId: 0, cityId: 0, districtId: 0 }, this.onGetLandingDetailsSucceeded.createDelegate(this));
        },
        
        swapMapImage: function(e, mp, o, imgMap, url){
			imgMap.dom.src = url;
        },
        
        onCountrySelected: function(combo, rec, index){
			this.maskMap();
			rec = rec[0];
			
			var countryId = rec.data.id;
			var wzId = rec.data.worldzoneid;
			this.invokeMethod('GetLandingDetails', {mapId: 0, wzId: wzId, countryId: countryId, regionId: 0, cityId: 0, districtId: 0 }, this.onGetLandingDetailsSucceeded.createDelegate(this));
        },
        
        onRegionSelected: function(combo, rec, index){
			this.maskMap();
			rec = rec[0];
			
			var regionId = rec.data.countystateregionid;
			this.invokeMethod('GetLandingDetails', {mapId: 0, wzId: window.wzId, countryId: window.countryId, regionId: regionId, cityId: 0, districtId: 0 }, this.onGetLandingDetailsSucceeded.createDelegate(this));
        },

        onDistrictSelected: function(combo, rec, index){
			this.maskMap();
			rec = rec[0];
			
			var districtId = rec.data.areaid;
			this.invokeMethod('GetLandingDetails', {mapId: 0, wzId: window.wzId, countryId: window.countryId, regionId: 0, cityId: 0, districtId: districtId }, this.onGetLandingDetailsSucceeded.createDelegate(this));
        },

        onCitySelected: function(combo, rec, index){
			this.maskMap();
			rec = rec[0];
			
			var areaId = rec.data.areaid;
			var areaType = rec.data.areatype;
			
			if(areaType == 0){
				this.invokeMethod('GetLandingDetails', {mapId: 0, wzId: window.wzId, countryId: window.countryId, regionId: window.regionId, cityId: areaId, districtId: 0 }, this.onGetLandingDetailsSucceeded.createDelegate(this));
			}
			else {
				this.invokeMethod('GetLandingDetails', {mapId: 0, wzId: window.wzId, countryId: window.countryId, regionId: window.regionId, cityId: 0, districtId: areaId }, this.onGetLandingDetailsSucceeded.createDelegate(this));
			}
			//this.gotoCountryLanding(rec.data.id);
        },

        onInstantSearch: function(e, rel){
			e.stopEvent();
			this.maskMap();
			
			var q = this.quickSearchText.getValue();
			
			var regionId = 0;
			var cityId = 0;
			var districtId = 0;
			var gid = 0;
			var latitude = null;
			var longitude = null;

			if(window.pt){
				var rec = null;		
				var index = this.quickSearchText.store.find('areaid', q);
				if(index >= 0){
					rec = this.quickSearchText.store.getAt(index);
				}
				if(rec){
					countryId = rec.data.countryid;
					if(rec.data.areatype === -1){
						q = '';
						latitude = rec.data.latitude;
						longitude = rec.data.longitude;
						gid = rec.data.areaid;
					}
					else if(rec.data.areatype === 0){
						q = '';
						cityId = rec.data.cityid;
					}
					else if(rec.data.areatype === 1){
						q = '';
						regionId = rec.data.regionid;
					}
					else if(rec.data.areatype === 2){
						q = '';
						districtId = rec.data.districtid;
					}
				}
				else{
					q = this.quickSearchText.getRawValue();
					if(!q || q.length == 0){
						this.updateVal('Please select a location from the dropdown menu or type a location in the search box');
						return;
					}
				}
			}			
			
            this.invokeMethod('InstantSearch', { wzId: window.wzId, countryId: countryId/*this.quickSearchCountry.getValue() || window.countryId*/ || 0, regionId: regionId, cityId: cityId, districtId: districtId, query: q, gid: gid, latitude: latitude, longitude: longitude }, this.onGetLandingDetailsSucceeded.createDelegate(this, [rel], true));
            return false;
        },

		updateVal: function(t){        
			var v = Ext.fly('val');
			if(v){
				v.update(t);
			}
		},
        
        attachLogin: function(){
			var el = Ext.get('login-link');
			if(el){
				el.on("click", this.onSiteLoginPrompt, this);
			}
        },
        
        attachLanguages: function(){
			var ls = document.getElementById('language-select');
			if(ls){
				this.languageSelect = new Ext.form.ComboBox({
					store: new Ext.data.JsonStore({
						fields: [
							'langid', 'language', 'languagefolder'
						]
					}),
					queryMode: 'local',
					triggerAction: 'all',
					editable: false,
					valueField: 'langid',
					displayField: 'language',
					width: 130,
					renderTo: ls
				});
				
				this.invokeMethod('GetLanguages', null, this.onLanguagesLoaded.createDelegate(this));
				
				this.languageSelect.on('select', this.onLanguageSelected, this);
			}
		},
		
		onLanguagesLoaded: function(d){
			this.languageSelect.store.loadData(d);
			this.languageSelect.setValue((window.langId == 8 ? 1 : window.langId).toString());			
		},
		
		onLanguageSelected: function(combo, rec, index){
			this.changeLanguage(rec[0].data.languagefolder, true);
		},
        
        onSiteLoginPrompt : function(e){
			e.stopEvent();
			if(!this.loginDialog) {
				var body = Ext.DomQuery.select('#login-dialog .x-window-body')[0];

				this.loginDialog = new Ext.Window({
					width:920,
					modal: true,
					closeAction: 'hide',
					id: 'login-dialog-cmp',
					html: body.innerHTML,
					resizable: false,
					y: 100,
					listeners:
					{
						'afterrender': function(){
							var userNameField = Ext.core.DomHelper.append('login-form-username', { tag: 'input', name: 'email', cls: 'login-textbox' });
							var passwordField = Ext.core.DomHelper.append('login-form-password', { tag: 'input', name: 'password', type: 'password', cls: 'login-textbox' });
							
							this.loginDialog.userNameField = userNameField;
							this.loginDialog.passwordField = passwordField;

							var el = Ext.get('login-form-submit');
							if(el){
								el.on('click', this.onSiteProcessLogin, this);
							}
							
							el = Ext.get('login-form-forgot');
							if(el){
								el.on('click', this.onSiteProcessPasswordRemind, this);
							}
						},
						'show': function(){
							Ext.fly('remind-msg').addCls('x-hide-display');
							Ext.fly('login-error').addCls('x-hide-display');
						},
						scope: this
					}
				});
				
				body.parentNode.removeChild(body);
			}
			this.loginDialog.show();
			return false;
        },
        
        onSiteProcessLogin: function(e){
			e.stopEvent();
			Ext.fly('remind-msg').addCls('x-hide-display');
			Ext.fly('login-error').addCls('x-hide-display');
			
			var a = [
				this.loginDialog.userNameField.value.trim(),
				this.loginDialog.passwordField.value.trim()
			];
			
			if(!a[0] || !a[1]){
				//this.loginDialog.userNameField.isValid();
				//this.loginDialog.passwordField.isValid();
				return;
			}
			
			var p = {};
			
			p[this.loginDialog.userNameField.name] = a[0];
			p[this.loginDialog.passwordField.name] = a[1];

			io.Spinner.showSpinner();			
            this.invokeMethod('ProcessLogin', p, this.onProcessLoginSucceeded.createDelegate(this));
        },
        
        onSiteProcessPasswordRemind: function(e){
			e.stopEvent();
			Ext.fly('remind-msg').addCls('x-hide-display');
			Ext.fly('login-error').addCls('x-hide-display');
			
			var a = [
				this.loginDialog.userNameField.getValue().trim()
			];
			
			if(!a[0]){
				this.loginDialog.userNameField.isValid();
				return;
			}
			
			var p = {};
			
			p[this.loginDialog.userNameField.name] = a[0];

			io.Spinner.showSpinner();			
            this.invokeMethod('ProcessPasswordRemind', p, this.onProcessPasswordRemindSucceeded.createDelegate(this));
        },

        onProcessPasswordRemindSucceeded: function(d){
			io.Spinner.hideSpinner();
			Ext.fly('remind-msg').removeCls('x-hide-display');
        },
        
        onProcessLoginSucceeded: function(d){
			io.Spinner.hideSpinner();
			if(d && d.url){
				this.loginDialog.close();
				document.location = (d.url.indexOf('http://') == 0 ? d.url : (window.siteBaseUrl + d.url));
				return;
			}
			Ext.fly('login-error').removeCls('x-hide-display');
        },
        
        attachTabs: function(tabs){
			var me = this;
			Ext.each(arguments, function(a) {
				var id = a;
				var vis = [];
				var active = 0;
				if(Ext.isObject(a)){
					id = a.id;
					vis = a.vis;
					active = a.active || 0;
				}
				var d = document.getElementById(id);

				if(d){
					var hasVisible = false;
					var index = 0;
					var items = Ext.query('li', d);
					Ext.each(items, function(i){
						var targetId = i.getAttribute('io:targetid');
						if(!targetId){
							return;
						}
						var el = Ext.fly(i);
						el.enableDisplayMode();
						var v = (vis[index] == undefined ? true : vis[index]);
						hasVisible = hasVisible || v;
						el[v ? 'show' : 'hide']();
						el.on('click', me.onTabElementClick, me);
						Ext.fly(targetId).enableDisplayMode();
						
						index++;
					});
					
					if(!hasVisible){
						Ext.fly(d).hide();
					}
					
					if(active > 0 && active < items.length){
						this.selectMenuTab(items[active]);
					}
				}
            }, this); 
        },
        
        onTabElementClick : function(e){
			e.stopEvent();
			e.preventDefault();
			var dom = e.getTarget('li');
			
			this.selectMenuTab(dom);
        },
        
        selectMenuTab: function(dom){
			var selTab = Ext.get(Ext.query('.selected', dom.parentNode)[0]);
			if(selTab){
				var selSection = Ext.get(selTab.dom.getAttribute('io:targetid'))
				selSection.hide();
				selTab.removeCls('selected');
			}
			
			var destSection = Ext.get(dom.getAttribute('io:targetid'));
			var destTab = Ext.get(dom);
			var updateHandler = this.sectionUpdaters && this.sectionUpdaters[destSection.id];
			if(updateHandler){
				destSection.update('');
				this[updateHandler]();
			}
			destSection.dom.style.position = ""; 
			destSection.dom.style.visibility = "visible"; 
			destSection.show();
			destTab.addCls('selected');
        },
        
        onInfoSectionLoaded: function(d, args, sectionId, partId){
			if(!this.templates[sectionId]) {
				this.templates[sectionId] = this.getCompiledTemplate(Ext.get(sectionId + '-template').dom.innerHTML);
			}
			if(d){
				Ext.each(d, function(s){
					s.url = window.baseUrl + s.url;
				}, this);
				Ext.get(sectionId).update(this.templates[sectionId].apply(d));
			}
			Ext.get(partId).unmask();
        },
        
        initSurvey: function(){
			Ext.defer(function q(){
				var sd;
				sd = new Ext.Window({
					title: 'Survey',
					cls: 'survey-window',
					width: 400,
					modal: true,
					resizable: false,
					autoScroll: true,
					layout: 'fit',
					buttons:
					[
						{ text: 'Yes', handler: function(btn){ 
							btn.hide();
							sd.setSize(500, 500);
							sd.doLayout();
							sd.center();
							sd.items.get(0).layout.setActiveItem(1);
						} },
						{ text: 'Close', handler: function(){ 
							sd.close() ;
						} }
					],
					items:
					[
						{
							layout: 'card',
							activeCard: 0,
							height:80,
							border: false,
							items:
							[
								{ cls: 'survey-prompt', html: '<div>We are constantly improving our site and would appreciate your feedback.<br/>Would you like to take a five minute survey?</div>', border: false },
								{ html: '<iframe src="https://www.surveymonkey.com/s/X3BD6J9" height="100%" width="100%" frameborder="false"/>', border: false, layout: 'fit' }
							]
						}
						
					]
				});
				sd.show();
			}, 20000, this);
        },
        
        initReportControls: function(){
			var a = Ext.query('div[id$=divResult]');
			Ext.each(a, function(d){
				var cid = d.getAttribute('cid');
				var dtp = Ext.query('span[id$=arrangeDate]', d)[0];
				var tmp = Ext.query('span[id$=arrangeTime]', d)[0];

				var viewDate = new Ext.form.DateField ({
					id : 'dtView' + cid,
					//width: 120,
					hideLabel: true,
					renderTo: dtp,
					format: 'd/m/Y',
					allowBlank: false,
					msgTarget: 'title'
				});
				var viewTime = new Ext.form.TimeField ({
					id : 'tmView' + cid,
					//width: 120,
					hideLabel: true,
					renderTo: tmp,
					allowBlank: false,
					msgTarget: 'title'
				});
			});
        },

        showCaseStudyDlg : function(a, csId){
			var body = Ext.DomQuery.select('#' + csId)[0];
			
			var caseStudyDlg = new Ext.Window({
				title: Ext.query('.x-window-header', body)[0].innerHTML,
				width: parseInt(a.getAttribute('popupwidth')),
				//height: parseInt(a.getAttribute('popupheight')),
				modal: true,
				closeAction: 'hide',
				resizable: false,
				autoScroll: true,
				y: 100,
				items:
				[
					{ html: Ext.query('.x-window-body', body)[0].innerHTML }
				]
			});
			//body.parentNode.removeChild(body);
			caseStudyDlg.show();

			Ext.defer(function(){			
				var fclose = function(e){
					if (caseStudyDlg.getTargetEl() && !e.within(caseStudyDlg.getTargetEl().dom, false)) {
						e.stopPropagation();
						Ext.get(document).un('click', fclose);
						caseStudyDlg.close();
					} 	
					return false;				
				};
				Ext.get(document).on('click', fclose);
			}, 500);
			
			return false;
        },

        //  private
        initCentreResults: function() {
            if (window.pageCentresData) {
                this.centresData = window.pageCentresData;
            }
            
            this.firstCentreId = 0;
            
            var z = 0;
            var stf = Ext.query('a.send-to-friend');

            var aCentreTip = Ext.query('div.centreTip', document.getElementById('centrePage'));
            var aCentreLnk = Ext.query('*.tipTarget', document.getElementById('centrePage'));
            
            var cindex = 0;
            for (var p in this.centresData) {
                if (this.centresData.hasOwnProperty(p)) {
                    var pci = this.centresData[p];
                    
                    if(!this.firstCentreId){
						this.firstCentreId = p;
                    }

					if(stf && stf.length > 0){                    
						if(window.pageType == 'centres'){
							for(var ii=0; ii < stf.length; ii++){
								Ext.fly(stf[ii]).on('click', this.onSendToFriend.createDelegate(this, [p], true), this);
							}
						}
						else{
							if(stf[z]){
								Ext.fly(stf[z]).on('click', this.onSendToFriend.createDelegate(this, [p], true), this);
							}
							z++;
						}
					}
                    
                    var reviewRatingBlockEl = Ext.get(Ext.query('ul.rating-block-large', document.getElementById('centrePage'))[0]);
                    if(reviewRatingBlockEl){
						this.on("rated", this.updateReviewRating.createDelegate(this, [reviewRatingBlockEl], true), this);

						if(pci.ratingAllowed){
							reviewRatingBlockEl.on("mouseout", this.resetRatingLarge.createDelegate(this, [reviewRatingBlockEl], true), this);
						}
						reviewRatingBlockEl.dom.rating = pci.ratingValueMy;
						for(var i = 1; i <= 5; i++){
							var li = Ext.get(Ext.query('li:nth(' + i.toString() + ')' , reviewRatingBlockEl.dom)[0]);
							if(li){
								if(i <= pci.ratingValueMy){
									li.defclass = "rating-active-large";
								}
								else{
									li.defclass = "rating-clear-large";
								}
								li.addCls(li.defclass);
								if(pci.ratingAllowed){
									li.addCls("rating-selectable");
									li.on("click", this.updateRatingLarge.createDelegate(this, [reviewRatingBlockEl, p, i], true), this);
									li.on("mouseover", this.selectStarLarge.createDelegate(this, [li, i], true), this);
								}
							}
						}
						
						var rvs = Ext.get('reviews-submission');
						rvs.setVisibilityMode(Ext.Element.DISPLAY);
						rvs[pci.reviewAllowed ? 'show' : 'hide']();
						
						Ext.fly(Ext.query('*', document.getElementById('reviews-validation'))[0])[pci.reviewAllowed ? 'hide' : 'show']('display');
						Ext.query('*', document.getElementById('reviews-validation'))[1].style.display = 'none';
						Ext.query('*', document.getElementById('reviews-validation'))[2].style.display = 'none';
						
						var submitReview = Ext.get(Ext.query('*[id$=submitReview]')[0]);
						submitReview.on('click', this.submitCentreReview.createDelegate(this, [p, reviewRatingBlockEl], true), this);
                    }
                    
                    var rbEl = Ext.get(pci.ratingBlockEl);
                    if(rbEl){
						for(var i = 1; i <= 5; i++){
							var li = Ext.get(Ext.query('li:nth(' + i.toString() + ')' , rbEl.dom)[0]);
							if(li){
								if(i <= pci.classification){
									li.defclass = "rating-active";
								}
								else{
									li.defclass = "rating-clear";
								}
								li.addCls(li.defclass);
							}
						}
                    }

                    rbEl = Ext.get(pci.ratingCustomerEl);
                    if(rbEl){
						this.centreRbEl = rbEl;
						for(var i = 1; i <= 5; i++){
							var li = Ext.get(Ext.query('li:nth(' + i.toString() + ')' , rbEl.dom)[0]);
							if(li){
								if(i <= pci.ratingValue){
									li.defclass = "rating-select";
								}
								else{
									li.defclass = "rating-clear";
								}
								li.addCls(li.defclass);
							}
						}
						var liAvg = Ext.get('avg');
						liAvg.update('' + pci.ratingValue);
                    }

                    for (var i = 0, n = pci.addedCentreEl.length; i < n; i++) {
                        pci.addedCentreEl[i] = Ext.get(pci.addedCentreEl[i]);
                        if (pci.addedCentreEl[i]) {
                            pci.addedCentreEl[i].setVisibilityMode(Ext.Element.DISPLAY);
                        }
                    }

                    for (var i = 0, n = pci.arrangedCentreEl.length; i < n; i++) {
                        pci.arrangedCentreEl[i] = Ext.get(pci.arrangedCentreEl[i]);
                        if (pci.arrangedCentreEl[i]) {
                            pci.arrangedCentreEl[i].setVisibilityMode(Ext.Element.DISPLAY);
                        }
                    }

                    for (var i = 0, n = pci.notAddedCentreEl.length; i < n; i++) {
                        pci.notAddedCentreEl[i] = Ext.get(pci.notAddedCentreEl[i]);
                        if (pci.notAddedCentreEl[i]) {
                            pci.notAddedCentreEl[i].setVisibilityMode(Ext.Element.DISPLAY);
                        }
                    }

                    for (var i = 0, n = pci.notArrangedCentreEl.length; i < n; i++) {
                        pci.notArrangedCentreEl[i] = Ext.get(pci.notArrangedCentreEl[i]);
                        if (pci.notArrangedCentreEl[i]) {
                            pci.notArrangedCentreEl[i].setVisibilityMode(Ext.Element.DISPLAY);
                        }
                    }
                    
                    var centreTip = Ext.get(aCentreTip[cindex])
                    var centreLnk = Ext.get(aCentreLnk[cindex]);
                    
                    if(centreTip && centreLnk && !centreTip.dom.getAttribute('disabled')){
						var tip = new Ext.ToolTip({  
							target: centreLnk.dom,
							anchor: 'bottom',
							html: null,
							width: 415,
							dismissDelay: 0,
							autoHide: true,
							closable: false,
							contentEl: centreTip.dom
						});
					}
                }
                
                cindex++;
            }

            this.on("updated", this.onCentresUpdated, this);
            this.on("updated", this.onSidebarUpdated, this);
        },
        
        onSendToFriend: function(e, dom, o, centreId){
			e.stopEvent();
			if(!this.stfDialog) {
				var loc = Ext.query('#stf-dialog')[0];
				this.stfDialog = new Ext.Window({
					modal: true,
					closeAction: 'hide',
					id: 'stf-dialog-cmp',
					applyTo: 'stf-dialog',
					resizable: false,
					width:400,
					items:
					[
						{
							xtype:'panel', 
							layout:'form',
							border: false,
							id: 'stf-dialog-form-cmp',
							applyTo: 'stf-dialog-form',
							bodyStyle: 'margin:5px;background-color:transparent',
							items:
							[
								{
									xtype:'fieldset',
									title: loc.getAttribute('section1'),
									items:
									[
										{ fieldLabel: loc.getAttribute('fieldlabel1'), name: 'myName', xtype: 'textfield', allowBlank: false, width:240, msgTarget:'title' },
										{ fieldLabel: loc.getAttribute('fieldlabel2'), name: 'myEmail', xtype: 'textfield', allowBlank: false, width:240, vtype: 'email', msgTarget:'title' }
									]
								},
								{
									xtype:'fieldset',
									title: loc.getAttribute('section2'),
									items:
									[
										{ fieldLabel: loc.getAttribute('fieldlabel3'), name: 'friendName', xtype: 'textfield', allowBlank: false, width:240, msgTarget:'title' },
										{ fieldLabel: loc.getAttribute('fieldlabel4'), name: 'friendEmail', xtype: 'textfield', allowBlank: false, width:240, vtype: 'email', msgTarget:'title' }
									]
								}
							],
							buttons:
							[
								{ text: loc.getAttribute('btntext'), handler: this.onProcessSendCentreToFriend, scope: this }
							]
						}
					]
				});
			}
			this.stfDialog.centreId = centreId;
			var f = this.stfDialog.getEl().getAlignToXY(dom, 'tl');
			this.stfDialog.x = f[0];
			this.stfDialog.y = f[1];
			this.stfDialog.show();
			return false;
        },
        
        onProcessSendCentreToFriend: function(btn, e){
			var p = {};
			var dlg = Ext.getCmp('stf-dialog-cmp');
			var frm = Ext.getCmp('stf-dialog-form-cmp');
			var b = true;
			
			frm.cascade(function(c){
				if(c.isValid){
					if(!c.isValid()){
						b = false;
						return false;
					}
					p[c.name] = c.getValue();
				}
			});
			
			if(!b){
				return;
			}
			
			p.centreId = dlg.centreId;

			io.Spinner.showSpinner();			
            this.invokeMethod('SendCentreToFriend', p, this.onProcessSendCentreToFriendSucceeded.createDelegate(this, dlg, true) );
        },
        
        onProcessSendCentreToFriendSucceeded: function(d, args, dlg){
			dlg.hide();
			this.selectCentre(dlg.centreId);
			io.Spinner.hideSpinner();			
        },
        
        submitCentreReview: function(e, el, p, centreId, reviewRatingBlockEl){
			e.stopEvent();
			var rating = reviewRatingBlockEl.dom.rating;
			var name = Ext.get('your-name').getValue();
			var review = Ext.get('your-review').getValue();
			
			if(!(rating && name.length && ((review.length >= 20 && review.length <= 500)))) {
				Ext.query('div', document.getElementById('reviews-validation'))[2].style.display = 'block';
				return;
			}
			
			Ext.query('div', document.getElementById('reviews-validation'))[2].style.display = 'none';

			io.Spinner.showSpinner();			
			this.invokeMethod('SaveCentreReview', { centreId: centreId, rating: rating, name: name, review: review, reviewOp: '', rid: window.rid }, this.onSaveCentreReview.createDelegate(this, [reviewRatingBlockEl], true));
        },

        onSaveCentreReview: function(ratingValue, d, reviewRatingBlockEl){
			Ext.query('div', document.getElementById('reviews-validation'))[1].style.display = 'block';;
			Ext.get('reviews-submission').hide();
			
			this.updateReviewRating(ratingValue, null, reviewRatingBlockEl);
			this.refreshRating(ratingValue, this.centreRbEl);
			
			io.Spinner.hideSpinner();
        },
        
        updateReviewRating: function(ratingValue, args, reviewRatingBlockEl){
			reviewRatingBlockEl.dom.rating = ratingValue;
			
			//	Stop large rating selection
			reviewRatingBlockEl.removeAllListeners();
			for(var i = 1; i <= 5; i++){
				var li = Ext.get(Ext.query('li:nth(' + i.toString() + ')' , reviewRatingBlockEl.dom)[0]);
				if(li){
					li.removeCls("rating-select-large");
					li.removeCls("rating-active-large");
					li.removeCls("rating-clear-large");
					if(i <= ratingValue){
						li.defclass = "rating-active-large";
					}
					else{
						li.defclass = "rating-clear-large";
					}
					li.addCls(li.defclass);
					li.removeCls("rating-selectable");
					li.removeAllListeners();
				}
			}
        },

        //  private
        onSidebarUpdated: function(o, data) {
			if(!this.sidebarAnchor){
				return;
			}
			
			var efs = Ext.fly('has-selection');
			if(efs){
				efs[data.centres ? 'addCls' : 'removeCls']('orange');
			}
			
            this.panelNoCentres[data.centres ? 'hide' : 'show']();
            this.panelCentres[data.centres ? 'show' : 'hide']();

            for (var i = 0, n = this.listContainer.dom.childNodes.length; i < n; i++) {
                this.listContainer.dom.removeChild(this.listContainer.dom.childNodes[0]);
            }

            var hasRequest = false;
            for (var i = 0, n = data.indexes ? data.indexes.length : 0; i < n; i++) {
                var p = data.indexes[i];
                var ci = data.centres[p];
                var viewRequested = ci.viewRequested;

                hasRequest = hasRequest || viewRequested;

                var d = [];
                d.push(p);
                d.push(ci.cityKey);
                d.push(ci.addressKey);
                d.push(ci.address);
                d.push(window.thumbUrlPrefix + ci.imgSrc);
                d.push(ci.imgStyle);
                d.push(ci.removeAction);
                d.push(window.officesUrlPrefix);

                var listHTML = (viewRequested ? this.templateRequested : this.templateSelected).applyTemplate(d);
                Ext.core.DomHelper.append(this.listContainer.dom, listHTML);
            }

			if(window.version == 2){
				Ext.each(Ext.query('*[io-switch=viewing]', this.sidebarAnchor), function(e){
					e.style.display = hasRequest ? '' : 'none';
				});
				this.sidebarControls.viewDate[hasRequest ? 'enable' : 'disable']();
				this.sidebarControls.viewTime[hasRequest ? 'enable' : 'disable']();

				this.layoutSidebar();
			}
			else{
                this.panelViewing = Ext.get(Ext.query('div[id$=panelViewing]', this.sidebarAnchor)[0]);
                this.panelViewing.setVisibilityMode(Ext.Element.DISPLAY);
				this.panelViewing[hasRequest ? 'show' : 'hide']();
            }
        },

        //  private
        onCentresUpdated: function(o, data) {
			if(window.googleMap){
				//	update google map bubble
				window.googleMap.updateInfoWindow();
			}

            for (var p in this.centresData) {
                if (this.centresData.hasOwnProperty(p)) {
                    var pci = this.centresData[p];

                    //  try get page's centre data
                    var ci = data.centres && data.centres[p];
                    var added = !!ci;
                    var viewRequested = ci && ci.viewRequested;
                    
                    if(!pci.addedCentreEl){
						continue;
                    }

                    for (var i = 0, n = pci.addedCentreEl.length; i < n; i++) {
						if(pci.addedCentreEl[i]){
							pci.addedCentreEl[i][added ? 'show' : 'hide']();
						}
                    }

                    for (var i = 0, n = pci.arrangedCentreEl.length; i < n; i++) {
						if(pci.arrangedCentreEl[i]){
							pci.arrangedCentreEl[i][viewRequested ? 'show' : 'hide']();
						}
                    }

                    for (var i = 0, n = pci.notAddedCentreEl.length; i < n; i++) {
						if(pci.notAddedCentreEl[i]){
							pci.notAddedCentreEl[i][added ? 'hide' : 'show']();
						}
                    }

                    for (var i = 0, n = pci.notArrangedCentreEl.length; i < n; i++) {
						if(pci.notArrangedCentreEl[i]){
							pci.notArrangedCentreEl[i][viewRequested ? 'hide' : 'show']();
						}
                    }
                }
            }
        },

        //  private
        updateListOptions: function(list, arr, start) {
            for (var i = start, n = list.options.length; i < n; i++) {
                list.remove(start);
            }
            for (var i = 0, n = arr.length; i < n; i++) {
                var opt = document.createElement("option");
                opt.value = arr[i][0];
                opt.text = arr[i][1];
                if(!arr[i][1]) {
                    opt.text = opt.value;
                }
                try {
                    list.add(opt);
                }
                catch (e) {
                    list.add(opt, null);
                }
            }
            list.value = '';
        },

        onCentresBasketLoaded: function(data) {
			var basketTop = Ext.get(this.sidebarAnchor).getTop();
			if(data.first && window.basketalert) {
				Ext.Msg.show({
					cls: 'basket-alert',
					width: 400,
					height: 300,
					closable:false,
					title: data.title,
					msg: data.first + '<br/>',
					buttons: Ext.Msg.OK,
					fn: function(){
						if(Ext.Msg.msgButtons['ok'].origText){
							Ext.Msg.msgButtons['ok'].setText(Ext.Msg.msgButtons['ok'].origText);
						}
						window.scrollTo(0, basketTop);
					}
				});
				Ext.Msg.msgButtons['ok'].origText = Ext.Msg.msgButtons['ok'].getText();
				Ext.Msg.msgButtons['ok'].setText(data.btn);
			}
            this.bagData = data;
            this.fireEvent("updated", this, data);
            io.Spinner.hideSpinner();
        },

        hasCentre: function(centreId) {
            return this.bagData && this.bagData.centres && this.bagData.centres[centreId];
        },

        invokeMethod: function(method, params, callback, args) {
            // convert object to JSON
            //var paramsJson = params ? Ext.encode(params) : params;
            Ext.Ajax.request({
                method: 'POST',
                jsonData: params || {},
                url: wsRefs.iows + '/' + method,
                success: function(response, opts) {
                    //  Decode resulting JSON to object
                    var data = Ext.decode(response.responseText);
                    callback.call(opts.scope, data, args);
                },
                failure: function(response, opts) {
                    io.Spinner.hideSpinner();
                    var s = response.responseText || response.statusText;
                    if(s.toLowerCase() != 'communication failure' && s.toLowerCase() != 'transaction aborted'){
						//alert(s);
                    }
                },
                args: args,
                scope: this
            });
        },
        
        deleteCookie : function(name, path, domain ) {
			document.cookie = name + "=" +
				(path ? ";path=" + path : "") +
				(domain ? ";domain=" + domain : "" ) +
				";expires=Thu, 01-Jan-1970 00:00:01 GMT";
		},

        //  Private
        readCookie: function(key, skips) {
            // Set skips to 0 if parameter was omitted:
            if (skips == null)
                skips = 0;

            // Get cookie string and separate into individual cookie phrases:
            var cookie_string = "" + document.cookie;
            var cookie_array = cookie_string.split("; ");

            // Scan for desired cookie:
            for (var i = 0; i < cookie_array.length; ++i) {
                var single_cookie = cookie_array[i].split("=");
                if (single_cookie.length != 2)
                    continue;
                var name = unescape(single_cookie[0]);
                var value = unescape(single_cookie[1]);

                // Return cookie if found:
                if (key == name && skips-- == 0)
                    return value;
            }

            // Cookie was not found:
            return "";
        },

        getCompiledTemplate: function(html) {
            html = html.replace("<!--", "").replace("-->", "");
            html = html.replace('\r', '');
            html = html.replace('\n', '');
            html = html.replace('\t', '').trim();
            var t = new Ext.XTemplate(html);
            t.compile();
            return t;
        },
        
        createProxy : function(method, store){
            var proxy = new Ext.data.HttpProxy({
                url: wsRefs.iows + '/' + method
            });
            
            proxy.on('beforeload', function(proxy, params){
                delete params.data;
				params.jsonData = params.jsonData || Ext.apply({}, params);
				delete params.jsonData.sort;
                params.jsonData.sortField = store.fields.findIndex("name", params.sort);
                params.jsonData.dir = params.dir;
            });        
            
            proxy.on('exception', function(proxy, type, name, options, response){
                Ext.Msg.alert('Error', response.statusText);
            });
            
            return proxy;
        },
        
        invokeMethodSync: function(method, data) {
			var xmlhttp = null;
			if (window.XMLHttpRequest) {
				xmlhttp = new XMLHttpRequest();
			}
			else if (window.ActiveXObject) {
				if (new ActiveXObject("Microsoft.XMLHTTP")) {
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				}
				else {
					xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
				}
			}
				// to be ensure non-cached version of response
			var url = wsRefs.iows + '/' + method + '?rnd=' + Math.random(); 
		    
			xmlhttp.open("POST", url, false);//false means synchronous
			xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
			xmlhttp.send(Ext.encode(data));
			var responseText = xmlhttp.responseText;
			return responseText;
		}
    });

    s.addEvents({
        "updated": true,
        "rated" : true
    });

    return s;
} ();

//  Spinner singleton class
io.FAQManager = function(){
    return {
        init: function(){
            var panels = Ext.DomQuery.select('div.faq');
            for(var i = 0, n = panels.length; i < n; i++){
				var title = Ext.DomQuery.select('.faq-header', panels[i])[0];
				var body = Ext.DomQuery.select('.faq-body', panels[i])[0];
				var p = new Ext.Panel({
					title: title.innerHTML,
					html: body.innerHTML,
                    autoHeight: true,
                    renderTo: panels[i].id,
                    collapsible: true,
                    titleCollapse: true,
                    hideCollapseTool: true,
                    collapsed: true,
                    border: false
                });
                panels[i].removeChild(title);
                panels[i].removeChild(body);
            };
        }
    };
}();

Ext.onReady(function(){
	Ext.QuickTips.init();

    io.Spinner.init();
    io.ApplicationManager.init();
    
    if(window.wrapInitMap){
        wrapInitMap();

		var mapLink = Ext.fly('map-link');
		if(mapLink){
			mapLink.removeCls('x-hide-display');
		}
    }

    /*
    setTimeout(function(){
        Ext.get('loading').remove();
        Ext.get('loading-mask').remove();
    }, 250);
    */
});

Ext.override(Ext.form.ComboBox, {
    lookupString : '',
    lookupTimeoutID : -1,
    
    onKeyUp : function(e){
        var k = e.getKey();
        if(this.editable !== false && this.readOnly !== true && (k == e.BACKSPACE || !e.isSpecialKey())){
            this.lastKey = k;
            this.doQueryTask.delay(this.queryDelay);
        }
        
        if(!this.editable){
			if (k >= 32 && !e.isNavKeyPress()) {
				clearTimeout(this.lookupTimeoutID);
				this.lookupString = this.lookupString + String.fromCharCode(k);
				var recIndex = this.store.find(this.displayField, this.lookupString, 0, false, false);
				if (recIndex >= 0) {
					if(!this.isExpanded()){
						this.onTriggerClick(); 
					}
					this.select(recIndex);
				}
				var ctrl = this;
				//  Reset lookup string after some reasonable time
				this.lookupTimeoutID = setTimeout(function() {
					ctrl.lookupString = '';
					ctrl.lookupTimeoutID = -1;
				}, 1000);
			}
        }
       
        Ext.form.ComboBox.superclass.onKeyUp.call(this, e);
    }
});

Ext.override(Ext.form.TextField, {
    filterKeys : function(e){
        if(e.ctrlKey){
            return;
        }
        var k = e.getKey();
        if((Ext.isGecko || Ext.isOpera) && (e.isNavKeyPress() || k == e.BACKSPACE || (k == e.DELETE && e.button == -1))){
            return;
        }
        var cc = String.fromCharCode(e.getCharCode());
        if(!Ext.isGecko && e.isSpecialKey() && !cc){
            return;
        }
        if(!this.maskRe.test(cc)){
            e.stopEvent();
        }
    }
});

if ((typeof Range !== "undefined") && !Range.prototype.createContextualFragment)
{
	Range.prototype.createContextualFragment = function(html)
	{
		var frag = document.createDocumentFragment(), 
		    div = document.createElement("div");
		frag.appendChild(div);
		div.outerHTML = html;
		return frag;
	};
}

Ext.apply(String.prototype, {
	trim : function(){
		return Ext.String.trim(this);
	}
}); 
