Ext.Ajax.defaultHeaders = {
    "Content-Type" : "application/json"
};

//  Declare IO namespace
io = {};

//  Spinner singleton class
io.Spinner = function(){
    var mask;
    return {
        init: function(){
			mask = Ext.get(document.body);
        },

        showSpinner: function() {
            if(mask){
                mask.mask('Please wait...', 'x-mask-loading');
            }
        },

        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 = {};

			switch(window.pageType){
				case 'report':
					this.initCentreResults();
					this.initReportControls();
					break;
				case 'centres':
				case 'results':
					this.initCentreResults();
					this.initSidebar();
					if(window.version == 2){
						this.attachSidebar();
						this.getLocalConsultant();

						if(window.pageType == 'results'){
							this.getSearchRefine();
							this.getExtraSearch();
						}
						if(window.pageType == 'centres'){
							Ext.fly('start-new-search').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 '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", '');
			});
        },

        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']);
				}
			}
            
            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']);
				}
            }

            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]', 'showMap');
            if (lnkShowMap.length == 0) {
                return;
            }
            lnkShowMap = lnkShowMap[0];

            var lnkHideMap = Ext.DomQuery.select('a[id$=lnkHideMap]', '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);

            lnkPrev.setVisibilityMode(Ext.Element.DISPLAY);
            lnkNext.setVisibilityMode(Ext.Element.DISPLAY);

            lnkPrev[cur > 0 ? 'show' : 'hide']();
            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));
        },

        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;
						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/>'));
					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 = reportData.dateView.format('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, mode) {
            if (!this.mapEl) {
                this.mapEl = Ext.get('map');
            }
            window.scrollTo(0, this.mapEl ? this.mapEl.getTop() : 0);

            //  ensure map is visible
            this.setMapVisible(true);
            eval('window.showBubble' + mode.toString() + '(' + index.toString() + ')');
        },

        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]', '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, updateSources) {
            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, updateSources: updateSources }, this.onGetPrivateRequirementsComplete.createDelegate(this), { updateCentres : updateCentres, updateSources : updateSources, countryId : countryId });
        },

        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(){
            if (!Page_ClientValidate()) {
                return false;
            }
            
            var listRules = [-1];
            var copyEl = Ext.query('input[type=checkbox]', 'panelCopy');
            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]', 'panelAdditional');
            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,
                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 : this.getFieldValue('cmbSource'),
	            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, true);
        },
        
        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, true);
            }
        },
        
        //  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(args.updateSources) {
                this.updatePrivateSources(data.sources);
            }
            if(data.countryData){
                this.onUpdateRequirementsCountry(data.countryData, args.countryId);
            }
            this.updateReferrals(data.refs);

            io.Spinner.hideSpinner();
        },
        
        //  private
        updatePrivateSources : function(sources){
            var cmbSource = Ext.query('select[id$=cmbSource]')[0];
            this.updateListOptions(cmbSource, sources, 1);
        },
        
        //  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.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.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.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.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.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;
        },

        //  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 = new Ext.Window({
                    layout: 'form',
                    width: 400,
                    height: 200,
                    modal: true,
                    closeAction: 'hide',
                    resizable: false,
                    title: 'Instant Offices Login [Use Fred Profile]',
                    bodyStyle: 'background-color:white;',
                    items: [
                        {
                            xtype: 'form',
                            bodyBorder: false,
                            border: false,
                            bodyStyle: 'padding:10px;',
                            items: [
                                { xtype: 'label', html: '<h3>Authorized Access Only</h3><br/>' },
                                { xtype: 'textfield', width: '150px', fieldLabel: 'Email', allowBlank: false, id: 'emailField', msgTarget: 'side' },
                                { xtype: 'textfield', width: '150px', fieldLabel: 'Password', allowBlank: false, id: 'passwordField', msgTarget: 'side', inputType: 'password' },
                                { xtype: 'label', width: '200px', 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(true);
        },

        //  private
        validateLogin: function() {
            var form = this.loginDlg.items.get(0);
            if (!form.form.isValid()) {
                return;
            }

            io.Spinner.showSpinner();

            var email = this.loginDlg.findById('emailField').getValue();
            var password = this.loginDlg.findById('passwordField').getValue();
            var status = this.loginDlg.findById('statusField');

            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.removeClass("rating-select");
				li.addClass(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.removeClass("rating-select-large");
				li.addClass(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.removeClass(li.defclass);
					li.addClass("rating-select");
				}
				else{
					li.removeClass("rating-select");
					li.addClass(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.removeClass(li.defclass);
					li.addClass("rating-select-large");
				}
				else{
					li.removeClass("rating-select-large");
					li.addClass(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.removeClass("rating-select-large");
					li.removeClass("rating-active-large");
					li.removeClass("rating-clear-large");
					if(i <= ratingValue){
						li.defclass = "rating-active-large";
					}
					else{
						li.defclass = "rating-clear-large";
					}
					li.addClass(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.removeClass("rating-select");
					li.removeClass("rating-active");
					li.removeClass("rating-clear");
					if(i <= ratingValue){
						li.defclass = "rating-select";
					}
					else{
						li.defclass = "rating-clear";
					}
					li.addClass(li.defclass);
					li.removeClass("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.tagName == 'TABLE') {
                    var tbody = Ext.query('tbody', t)[0];
                    if (!tbody) {
                        t = Ext.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.sectionUpdaters = {
				'featured-office' : 'getFeaturedOffice',
				'featured-consultant': 'getFeaturedConsultant',
				'city-guides': 'getCityGuides',
				'news-press': 'getNewsArticles'
			};
			this.attachTabs('tab-search', 'tab-office', 'tab-case');
			
			this.getLandingDetails();
			//this.getFeaturedOffice();
			this.getPopularSearches();
			
			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');
			var cb = new Ext.form.ComboBox ({
				store: [[0, 'UK (Headquarters)'], [1, 'USA'], [2, 'Australia']],
				hideLabel: true,
				width: 300,
				mode: 'local',
				value: cl.getAttribute('io:value'),
				allowBlank: false,
				forceSelection: true,
				triggerAction: 'all',
				selectOnFocus:true,
				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');
			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.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));
			}
        },

        getExtraSearch: function(){
			var extra = Ext.get('extra-search');
			if(extra){
				extra.mask('', 'x-mask-loading');
				this.invokeMethod('GetExtraSearch', window.searchParams, this.onGetExtraSearchSucceeded.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);
				}
			}
		},
		
        onGetExtraSearchSucceeded: function(d, args){
			if(!this.templates['extraSearchTemplate']) {
				this.templates['extraSearchTemplate'] = this.getCompiledTemplate(Ext.get('extraSearchTemplate').dom.innerHTML);
			}
			
			var f = function(p){
				p.linkurl = window.siteBaseUrl + p.linkurl + '.aspx';
			};
			
			if(d.postcode && d.postcode.length == 1){
				d.postcode.pop();
			}
			
			if(d.district){
				Ext.each(d.district, f);
			}
			if(d.postcode && d.postcode.length > 0){
				Ext.each(d.postcode, f);

				if(!parseInt(window.searchParams.cities)){
				//	d.district = [];
				}
			}
			if(d.expand){
				Ext.each(d.expand, f);
			}
			
			var es = Ext.get('extra-search');
			es.unmask();
			
			if(d.district || d.postcode || d.expand){
				this.templates['extraSearchTemplate'].overwrite(es, d);
			}
        },
        
        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(); 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);
			}
			
			Ext.apply(Ext.form.VTypes, {
				phoneNumber:  function(v) {
					return /^\+?[-0-9 ]{6,}$/.test(v);
				},
				phoneNumberText: 'invalid phone number',
				phoneNumberMask: /[ \d-]/
			}); 
			
			var form = Ext.query('#form', '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,
						mode: 'local',
						emptyText: userTitle.getAttribute('io:emptyText'),
						blankText: userTitle.getAttribute('io:blankText'),
						allowBlank: false,
						forceSelection: true,
						triggerAction: 'all',
						selectOnFocus:true,
						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,
						mode: 'local',
						emptyText: userCountry.getAttribute('io:emptyText'),
						blankText: userCountry.getAttribute('io:blankText'),
						allowBlank: false,
						valueField: 'id',
						displayField: 'country',
						forceSelection: true,
						triggerAction: 'all',
						selectOnFocus:true,
						editable: false,
						renderTo: userCountry,
						msgTarget: 'title',
						listWidth: 200,
						listeners:{
							'select': function(combo, rec){
								this.getSidebarCountryData(rec.data.id);
							},
							scope: this
						}
					}),
				userRegion: new Ext.form.ComboBox ({
						store: new Ext.data.JsonStore({fields: ['countystateregionid', 'name']}),
						hideLabel: true,
						width: 120,
						mode: 'local',
						emptyText: userRegion.getAttribute('io:emptyText'),
						blankText: userRegion.getAttribute('io:blankText'),
						valueField: 'countystateregionid',
						displayField: 'name',
						allowBlank: false,
						forceSelection: true,
						triggerAction: 'all',
						selectOnFocus:true,
						editable: false,
						renderTo: userRegion,
						msgTarget: 'title',
						listWidth: 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,
						mode: 'local',
						emptyText: peopleNumber.getAttribute('io:emptyText'),
						blankText: peopleNumber.getAttribute('io:blankText'),
						allowBlank: false,
						valueField:'value',
						displayField: 'option_text',
						forceSelection: true,
						triggerAction: 'all',
						selectOnFocus:true,
						editable: false,
						renderTo: peopleNumber,
						msgTarget: 'title',
						listWidth: 200
					}),
				startDate: startDate ? new Ext.form.ComboBox ({
						store: Ext.decode(startDate.getAttribute('io:data')),
						hideLabel: true,
						width: 120,
						mode: 'local',
						emptyText: startDate.getAttribute('io:emptyText'),
						blankText: startDate.getAttribute('io:blankText'),
						allowBlank: false,
						forceSelection: true,
						triggerAction: 'all',
						selectOnFocus:true,
						editable: false,
						renderTo: startDate,
						msgTarget: 'title',
						listWidth: 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.invokeMethod('GetSidebarContent', null, this.onGetSidebarContentSucceeded.createDelegate(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);
			}
			
			Ext.get('local-consultant').update(this.templates['local-consultant-template'].apply(d));
			Ext.get('local-consultant').unmask();
        },

        onWindowBeforeUnload: function(){
			var sideData = {};
			for(var e in this.sidebarControls){
				if(this.sidebarControls.hasOwnProperty(e)){
					var f = this.sidebarControls[e];
					if(f && f.getValue){
						var v = f.getValue();
						if(Ext.isDate(v)){
							v = v.format('Y-m-d');
						}
						sideData[e] = v;
					}
				}
			}
			this.invokeMethodSync('SaveVisitorData', sideData);
        },
        
        getSidebarCountryData: function(countryId) {
            //Ext.get('form').mask('', 'x-mask-loading');
            this.invokeMethod('GetSidebarCountryData', { countryId: countryId }, this.onGetSidebarCountryDataSucceeded.createDelegate(this));
        },

        onGetSidebarCountryDataSucceeded: function(d, args) {
			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);
			}
			var phone = this.sidebarControls.userPhone;
			if (phone.getValue().length < 6) {
				phone.setValue(d.prefix);
			}

            //Ext.get('form').unmask();
        },

        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.setValue(d.sideData[e]);
					
					if(e == 'furtherDetails' && d.sideData[e] && d.sideData[e].length > 0){
						this.sidebarControls.showSpecial(true);
					}
				}
			}
        },

        attachLeftMenuSearch: function(){
			if(!document.getElementById('leftmenu-search')){
				return;
			}
			
			var srch = function(e){
				this.onInstantSearch(e, '../');
			};
			
			var cs = document.getElementById('leftmenu-search-country');
			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,
				mode: '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.data.id, '../');
					},
					scope: this
				},
				store: new Ext.data.JsonStore({
					fields: [
						'id', 'countryname', 'worldzoneid'
					]
				}),
				renderTo: cs
			});
			this.quickSearchCity = new Ext.form.ComboBox({
				hideParent: true,
				hideLabel: true,
				mode: '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.data.areaid), '../');
					},
					scope: this
				},
				store: new Ext.data.JsonStore({
					fields: [
						'areaid', 'areaname'
					]
				}),
				renderTo: as
			});
			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: 0, regionId: 0, cityId: 0, districtId: 0 }, this.onGetLandingDetailsSucceeded.createDelegate(this));
        },
        
        tryCountrySearch: function(countryId, rel){
			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(d.cities && d.cities.length > 0){
				this.quickSearchCity.show();
				this.quickSearchCity.store.loadData(d.cities);
			}
			else if(this.quickSearchCity) {
				this.quickSearchCity.collapse();
				this.quickSearchCity.hide();
			}
        },

        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,
				mode: '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
			});
			this.quickSearchRegion = new Ext.form.ComboBox({
				hideParent: true,
				hideLabel: true,
				mode: '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
			});
			this.quickSearchCity = new Ext.form.ComboBox({
				hideParent: true,
				hideLabel: true,
				mode: '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
			});
			/*
			this.quickSearchDistrict = new Ext.form.ComboBox({
				hideParent: true,
				hideLabel: true,
				mode: '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
			});
			*/

			this.quickSearchCountry.store = new Ext.data.JsonStore({
				fields: [
					'id', 'countryname', 'worldzoneid'
				]
			});

			this.quickSearchRegion.store = new Ext.data.JsonStore({
				fields: [
					'countystateregionid', 'regionname'
				]
			});

			this.quickSearchCity.store = new Ext.data.JsonStore({
				fields: [
					'areaid', 'areaname', 'areatype', 'areacode'
				]
			});

			this.quickSearchText = new Ext.form.TextField({
				width: 230,
				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();
			}

			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.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.countries && d.countries.length > 0){
				this.quickSearchCountry.setValue('');
				this.quickSearchCity.setValue('');
				this.quickSearchCountry.show();
				this.quickSearchCountry.hasFocus = false;
				this.quickSearchCountry.store.loadData(d.countries);
			}
			else{
				this.quickSearchCountry.collapse();
				this.quickSearchCountry.hide();
			}

			if(this.quickSearchRegion){
				if(d.regions && d.regions.length > 0 && (window.countryId == 35 || window.countryId == 50)){
					this.quickSearchRegion.setValue('');
					this.quickSearchCity.setValue('');
					this.quickSearchRegion.show();
					this.quickSearchRegion.hasFocus = false;
					this.quickSearchRegion.store.loadData(d.regions);
				}
				else{
					this.quickSearchRegion.collapse();
					this.quickSearchRegion.hide();
				}
			}

			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.show();
			}
			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.show();
				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.hide();
				}
			}

			/*			
			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');
					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();
				}
				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) {
							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().child('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.getFeaturedOffice();
			
			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();
			
			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();
			
			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();
			
			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();
			
			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();
			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: 0/*this.quickSearchCountry.getValue() || window.countryId*/, regionId: 0, cityId: 0, districtId: 0, query: q }, 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({
						root: '',
						proxy: new Ext.data.HttpProxy({
							url: wsRefs.iows + '/GetLanguages'
						}),
						fields: [
							'langid', 'language', 'languagefolder'
						],
						listeners: {
							'beforeload' : function(store, options){
								options.params = { jsonData: {} };
							},
							'load' : function(store, options){
								this.languageSelect.setValue(window.langId == 8 ? 1 : window.langId);
							}, 
							scope: this
						}
					}),
					mode: 'local',
					forceSelection: true,
					triggerAction: 'all',
					selectOnFocus:true,
					editable: false,
					valueField: 'langid',
					displayField: 'language',
					width: 130,
					renderTo: ls
					
				});
				this.languageSelect.store.load();
				this.languageSelect.on('select', this.onLanguageSelected, this);
			}
		},
		
		onLanguageSelected: function(combo, rec, index){
			this.changeLanguage(rec.data.languagefolder, true);
		},
        
        onSiteLoginPrompt : function(e){
			e.stopEvent();
			if(!this.loginDialog) {
				this.loginDialog = new Ext.Window({
					width:900,
					modal: true,
					closeAction: 'hide',
					id: 'login-dialog-cmp',
					applyTo: 'login-dialog',
					resizable: false,
					y: 100
				});
				this.loginDialog.userNameField = new Ext.form.TextField({ cls:'login-textbox', renderTo: 'login-form-username', hideLabel: true, name: 'email', xtype: 'textfield', allowBlank: false });
				this.loginDialog.passwordField = new Ext.form.TextField({ cls:'login-textbox', renderTo: 'login-form-password', hideLabel: true, name: 'password', xtype: 'textfield', allowBlank: false, autoCreate: {tag: 'input', type: 'password'} });
				
				Ext.fly('login-form-submit').on('click', this.onSiteProcessLogin, this);
				Ext.fly('login-form-forgot').on('click', this.onSiteProcessPasswordRemind, this);
			}
			Ext.fly('remind-msg').addClass('x-hide-display');
			Ext.fly('login-error').addClass('x-hide-display');
			this.loginDialog.show();
			return false;
        },
        
        onSiteProcessLogin: function(e){
			e.stopEvent();
			Ext.fly('remind-msg').addClass('x-hide-display');
			Ext.fly('login-error').addClass('x-hide-display');
			
			var a = [
				this.loginDialog.userNameField.getValue().trim(),
				this.loginDialog.passwordField.getValue().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').addClass('x-hide-display');
			Ext.fly('login-error').addClass('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').removeClass('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').removeClass('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.removeClass('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.addClass('selected');
        },
        
        getPopularSearches: function(){
            this.invokeMethod('GetPopularSearches', null, this.onPopularSearchesLoaded.createDelegate(this));
        },
        
        getFeaturedOffice: function(){
			var left = Ext.get('left');
			if(left){
				left.mask('', 'x-mask-loading');
				this.invokeMethod('GetFeaturedOffice', { countryId: window.countryId || 0, regionId: window.regionId || 0, cityId: window.cityId || 0}, this.onInfoSectionLoaded.createDelegate(this, ['featured-office', 'left'], true));
            }
        },
        
        getFeaturedConsultant: function(){
			var left = Ext.get('left');
			if(left){
				left.mask('', 'x-mask-loading');
				this.invokeMethod('GetFeaturedConsultant', null, this.onInfoSectionLoaded.createDelegate(this, ['featured-consultant', 'left'], true));
			}
        },

        getCityGuides: function(){
			var left = Ext.get('left');
			if(left){
				left.mask('', 'x-mask-loading');
				this.invokeMethod('GetCityGuides', null, this.onInfoSectionLoaded.createDelegate(this, ['city-guides', 'left'], true));
			}
        },

        getNewsArticles: function(){
			var right = Ext.get('right');
			if(right){
				right.mask('', 'x-mask-loading');
				this.invokeMethod('GetNewsArticles', null, this.onInfoSectionLoaded.createDelegate(this, ['news-press', 'right'], true));
			}
        },
        
        onPopularSearchesLoaded: function(d){
			if(!this.templates['popSearchTemplate']) {
				this.templates['popSearchTemplate'] = this.getCompiledTemplate(Ext.get('popSearchTemplate').dom.innerHTML);
			}
			if(d && d.length > 0){
				Ext.get('popSearch').update(this.templates['popSearchTemplate'].apply(d));
			}
        },

        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();
        },
        
        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 caseStudyDlg = new Ext.Window({
				width:a.getAttribute('popupwidth'),
				height:a.getAttribute('popupheight'),
				modal: true,
				closeAction: 'close',
				applyTo: csId,
				resizable: false,
				autoScroll: true,
				y: 100
			});
			caseStudyDlg.show();
			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', 'centrePage');
            var aCentreLnk = Ext.query('*.tipTarget', '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', '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.addClass(li.defclass);
								if(pci.ratingAllowed){
									li.addClass("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('*', 'reviews-validation')[0])[pci.reviewAllowed ? 'hide' : 'show']();
						
						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.addClass(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.addClass(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('hidden')){
						var tip = new Ext.ToolTip({  
							target: centreLnk.dom,
							anchor: 'bottom',
							html: null,
							width: 415,
							dismissDelay: 0,
							autoHide: true,
							anchorOffset: 20,
							closable: false,
							contentEl: centreTip.dom,

						   syncAnchor : function(){
								var anchorPos, targetPos, offset;
								switch(this.tipAnchor.charAt(0)){
									case 't':
										anchorPos = 'b';
										targetPos = 'tl';
										offset = [20+this.anchorOffset, 3];
										break;
									case 'r':
										anchorPos = 'l';
										targetPos = 'tr';
										offset = [-2, 11+this.anchorOffset];
										break;
									case 'b':
										anchorPos = 't';
										targetPos = 'bl';
										offset = [20+this.anchorOffset, -3];
										break;
									default:
										anchorPos = 'r';
										targetPos = 'tl';
										offset = [2, 11+this.anchorOffset];
										break;
								}
								this.anchorEl.alignTo(this.el, anchorPos+'-'+targetPos, offset);
							}
						});
						tip.addClass('io-tip');
					}
                }
                
                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();
			var reviewOp = Ext.get('your-review-op').getValue();
			
			if(!(rating && name.length && ((review.length >= 20 && review.length <= 500) || (reviewOp.length >= 20 && reviewOp.length <= 500)))) {
				Ext.fly(Ext.query('div', 'reviews-validation')[2]).show();
				return;
			}
			
			Ext.fly(Ext.query('div', 'reviews-validation')[2]).hide();

			io.Spinner.showSpinner();			
			this.invokeMethod('SaveCentreReview', { centreId: centreId, rating: rating, name: name, review: review, reviewOp: reviewOp, rid: window.rid }, this.onSaveCentreReview.createDelegate(this, [reviewRatingBlockEl], true));
        },

        onSaveCentreReview: function(ratingValue, d, reviewRatingBlockEl){
			Ext.fly(Ext.query('div', 'reviews-validation')[1]).show();
			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.removeClass("rating-select-large");
					li.removeClass("rating-active-large");
					li.removeClass("rating-clear-large");
					if(i <= ratingValue){
						li.defclass = "rating-active-large";
					}
					else{
						li.defclass = "rating-clear-large";
					}
					li.addClass(li.defclass);
					li.removeClass("rating-selectable");
					li.removeAllListeners();
				}
			}
        },

        //  private
        onSidebarUpdated: function(o, data) {
			if(!this.sidebarAnchor){
				return;
			}
			
			var efs = Ext.fly('has-selection');
			if(efs){
				efs[data.centres ? 'addClass' : 'removeClass']('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.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']();
			}
			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) {
            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) {
			if(data.first && window.basketalert){
				Ext.Msg.alert('InstantOffices', data.first);
			}
            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'){
						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 : 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('.faq', 'contentAbout');
            for(var i = 0, n = panels.length; i < n; i++){
                new Ext.Panel({
                    autoHeight: true,
                    applyTo: panels[i].id,
                    baseCls: 'faq',
                    collapsible: true,
                    titleCollapse: true,
                    hideCollapseTool: true,
                    collapsed: true
                });
            };
        }
    };
}();

Ext.onReady(function(){
    try {
    	Ext.QuickTips.init();

        io.Spinner.init();
        io.ApplicationManager.init();
        
        if(window.wrapInitMap){
            wrapInitMap();

			var mapLink = Ext.fly('map-link');
			if(mapLink){
				mapLink.removeClass('x-hide-display');
			}
        }
    }
    catch(e){
    }
    /*
    setTimeout(function(){
        Ext.get('loading').remove();
        Ext.get('loading-mask').remove();
    }, 250);
    */
});

// fix combo focus -> expand bug
Ext.override(Ext.form.TriggerField, {
    updateEditState: function(){
        if(this.rendered){
            if (this.readOnly) {
                this.el.dom.readOnly = true;
                this.el.addClass('x-trigger-noedit');
                //this.mun(this.el, 'click', this.onTriggerClick, this);
                this.mun(this.el, 'mousedown', this.onTriggerClick, this);
                this.trigger.setDisplayed(false);
            } else {
                if (!this.editable) {
                    this.el.dom.readOnly = true;
                    this.el.addClass('x-trigger-noedit');
                    //this.mon(this.el, 'click', this.onTriggerClick, this);
                    this.mon(this.el, 'mousedown', this.onTriggerClick, this);
                } else {
                    this.el.dom.readOnly = false;
                    this.el.removeClass('x-trigger-noedit');
                    //this.mun(this.el, 'click', this.onTriggerClick, this);
                    this.mun(this.el, 'mousedown', this.onTriggerClick, this);
                }
                this.trigger.setDisplayed(!this.hideTrigger);
            }
            this.onResize(this.width || this.wrap.getWidth());
        }
    }
});
 
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.dqTask.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);
    }
});

