Page = {
    map: null,
    container: null,
    init: function (container) {
        this.urlParams = {};
        this.getUrlParams();
        this.setUpElements();
        this.container = container;

        this.map = new MultimapViewer(this.container);
        this.handleLayout();
        this.addWidgets();
        this.addResizeEvent();
        this.addRoutingEvent();
        this.setUpSelect();
        this.setUpStoreSearch();
        this.setUpLocationSearch();
        document.body.addCssClass('storesearch');
        if (this.urlParams['homecheck']) {
            this.locationSearch.search_field.value = "home stores";
            this.locationSearch.onFormSubmit();
        } else if (this.urlParams['clearancecheck']) {
            this.locationSearch.search_field.value = "clearance stores";
            this.locationSearch.onFormSubmit();
        } else if (this.urlParams['featured']) {
            this.locationSearch.search_field.value = "featured store";
            var store = this.urlParams['featured'];
            storename = store;
            store = store.replace(/\+/g, " ");
            store = unescape(store);
            document.getElementById('store_holder').value = store;
            this.locationSearch.onFormSubmit();
        } else {
            if (this.urlParams['country']) {
                var storename = document.getElementById('storename');
                var store = this.urlParams['storename'];
                var country = this.urlParams['country'];
                storename = store;
                store = store.replace(/\+/g, " ");
                store = unescape(store);
                country = country.replace(/\+/g, " ");
                country = unescape(country);
                document.getElementById('store_holder').value = store;
                document.getElementById('country_holder').value = country;
                this.locationSearch.onFormSubmit();
            } else if (this.urlParams['storename']) {
                var storename = document.getElementById('storename');
                //this.locationSearch.search_field.value = "store name";
                var store = this.urlParams['storename'];
                storename = store;
                store = store.replace(/\+/g, " ");
                store = unescape(store);
                document.getElementById('store_holder').value = store;
                this.locationSearch.onFormSubmit();
            } else if (this.urlParams['storeid']) {
                var storename = document.getElementById('storename');
                this.locationSearch.search_field.value = "storeid";
                var store = this.urlParams['storeid'];
                document.getElementById('store_holder').value = store;
                //storename = store;
                //store = store.replace(/\+/g, " ");
                //store = unescape(store);
                //document.getElementById('store_holder').value = store;
                this.locationSearch.onFormSubmit();
            } else {
                if (this.urlParams['postcode']) {
                    var pc = this.urlParams['postcode'];
                    pc = pc.replace(/\+/g, " ");
                    pc = unescape(pc);
                    this.locationSearch.search_field.value = pc;
                    this.locationSearch.onFormSubmit();
                } else {
                    if (this.urlParams['location']) {
                        var loc = this.urlParams['location'];
                        loc = loc.replace(/\+/g, " ");
                        loc = unescape(loc);
                        this.locationSearch.search_field.value = loc;
                        this.locationSearch.onFormSubmit();
                    }
                }
            }
        }
        shopOnlineList();
        this.addInfoBoxEvent();
        this.initSearch();
        this.countryList();

        //DisamHandler.init(this.container);

    },
    addWidgets: function () {
        this.map.addWidget(new MMPanZoomWidget(new MMBox(17, undefined, undefined, 545)));
    },
    addRoutingEvent: function () {
        var to = document.getElementById('directions_to'), from = document.getElementById('directions_from'), map = this.map;
        var results = document.getElementById('directionsResults');
        from.form.onsubmit = function () {
            var directionsdiv = document.getElementById('directionsInfo');
            var direcFrom = document.getElementById('directions_from').value;
            var direcTo = document.getElementById('directions_to').value;
            directionsdiv.innerHTML = '';
            var directionsHTML = '<h1>Travel Directions</h1>';
            directionsHTML += '<p class="from"> From: ' + direcFrom + '</p>';
            directionsHTML += '<p class="to"> To: ' + direcTo + '</p>';
            directionsdiv.innerHTML = directionsHTML;
            new RouteSearch(
                map, new MMAddress({ 'qs': from.value, 'country_code': 'GB' }), new MMLocation(to.point), results, Page.createRouteSteps, Page.routingCallback,
                DisamHandler.handleGeoError
            );
            return false;
        }
    },
    addResizeEvent: function () {
        if (navigator.userAgent.indexOf('MSIE 6') > -1) {
            MMAttachEvent(window, 'resize', Page.handleLayout);
        }
    },
    getFilters: function (search) {
        search.filters = [];
        var filter = document.getElementById("store_holder");
        var country_filter = document.getElementById("country_holder");
        search.logic = 'OR';
        if (filter.value != '') {
            search.filters.push(new MMSearchFilter('branch_name', 'Eq', filter.value.toUpperCase())); ;
        }
        filter.processFilter = false;
        return search;
    },
    addInfoBoxEvent: function () {
        this.map.addEventHandler('openInfoBox', function () {
            UpdateRouting(arguments[2].recordid);
        });
    },
    setUpSelect: function () {
        //TODO: THE SEARCH DOESNT RETURN ANY VALUES- MAY REQUIRE FURTHER INVESTIGATION
        var rfs = ['EntityID', 'branch_name', 'street', 'town', 'PostalCode', 'Latitude', 'Longitude'];
        listSearcher = MMFactory.createSearchRequester(this.buildSelect);
        var listSearch = new MMSearch();
        listSearch.return_fields = rfs;
        listSearch.radius_units = 'miles';
        listSearch.count = 250;
        listSearch.filters = new Array();
        if (!this.urlParams['country'] || this.urlParams['country'] == "")
            listSearch.filters.push(new MMSearchFilter('country', 'Eq', 'UNITED KINGDOM'));
        else
            listSearch.filters.push(new MMSearchFilter('country', 'Eq', this.urlParams['country']));
            
        listSearch.filters.push(new MMSearchFilter('$getAllData', '=', ''));
        //listSearch.filters.push(new MMSearchFilter('country', 'Eq', ''));
        listSearch.order_by_fields = 'branch_name';
        listSearcher.search( listSearch);
    },
    buildSelect: function () {
        for (var count = 0, l = listSearcher.record_sets.length; count < l; count++) {
            if (listSearcher.record_sets[count].records) {
                for (var record_count = 0, rl = listSearcher.record_sets[count].records.length; record_count < rl; record_count++) {
                    var record = listSearcher.record_sets[count].records[record_count];
                    appendOptionLast(record.branch_name, 'storename');
                }
            }
        }
    },
    handleLayout: function () {
        var left = document.getElementById('left');
        var right = document.getElementById('right');
        Page.map.manageLayout(right);
        Page.map.manageLayout(left);
        Page.map.manageLayout(this.container);
    },
    createRouteSteps: function (step, id, type) {
        return Callbacks.getHtmlRoute(step, RoutingFields, 'result', 'a', id);
    },
    routingCallback: function () {
        var yourStore = document.getElementById('yourStore');
        yourStore.style.display = 'none';
        var directions = document.getElementById('directions');
        directions.style.display = 'block';
    },
    getUrlParams: function () {
        try {
            var url = window.location.search.split('?')[1].split('&');
            for (var i = 0, j = url.length; i < j; i++) {
                this.urlParams[url[i].split('=')[0]] = url[i].split('=')[1];
            }
        } catch (e) { };
    },
    setUpLocationSearch: function () {
        var location = document.getElementById('locationsearch');
        MMAttachEvent(location.form, 'submit', function () {
            DisamHandler.clearDisam();
        });
        this.locationSearch = new LocationSearch(
            location, 'GB', this.map, undefined, this.storeSearch, function () { return false; }, DisamHandler.handleGeoError
        );
    },
    initSearch: function () {
        searcher = MMFactory.createSearchRequester(this.resultsLoaded);
        // Set return fields, radius units, and maximum number of records to return from search:
        //TODO: TO BE RESTORED
        search = new MMSearch();
        var rfs = ['EntityID', 'branch_name', 'branch_short_name'];
        search.return_fields = rfs;
        search.radius_units = 'km';
        search.count = 250;
        search.filters = new Array();
        search.filters.push(new MMSearchFilter('country', 'Eq', 'UNITED KINGDOM'));
        search.filters.push(new MMSearchFilter('branch_short_name', 'Ne', ""));
        search.filters.push(new MMSearchFilter('$getAllData', '=', ''));
        search.order_by_fields = 'branch_name';
        searcher.search(search);
    },
    countryList: function () {
        var rfs = ['country'];
        var funcRef2 = this.countryListLoaded;
        var clist = document.getElementById('countryList');
        otherSearcher = MMFactory.createSearchRequester(funcRef2);
        search = new MMSearch();
        search.return_fields = rfs;
        search.radius_units = 'miles';
        search.count = 500;
        search.filters = new Array();
        search.filters.push(new MMSearchFilter('country', 'Ne', 'UNITED KINGDOM'));
        //search.filters.push(new MMSearchFilter('Latitude', 'not', 0));
        //search.filters.push(new MMSearchFilter('Longitude', 'not', 0));
        //	    search.filters.push( new MMSearchFilter('GeoQuality', 'not', '0') );
        //	    search.filters.push( new MMSearchFilter('GeoQuality', 'not', '7') );

        search.order_by_fields = 'country';
        otherSearcher.search(search);
    },
    countryListLoaded: function () {
        if (otherSearcher.error_code) {
            var err = '';
            if (otherSearcher.error_explanation) {
                err = otherSearcher.error_explanation;
            } else {
                err = 'Your request failed. Error code: ' + otherSearcher.error_code;
            }
            return;
        }
        var results_returned = 1;
        var start_index_value = 1;
        // Loop through each record set:
        for (var count = 0, l = otherSearcher.record_sets.length; count < l; count++) {
            if (otherSearcher.record_sets[count].error) {
                var err = '';
                if (otherSearcher.record_sets[count].error.error_explanation) {
                    err = otherSearcher.record_sets[count].error.error_explanation;
                } else {
                    err = 'Your request failed. Error code: ' + otherSearcher.record_sets[count].error.error_code;
                };
                return;
            }
            country_array = new Object;
            if (otherSearcher.record_sets[count].records) {
                for (var record_count = 0, rl = otherSearcher.record_sets[count].records.length; record_count < rl; record_count++) {
                    var record = otherSearcher.record_sets[count].records[record_count];
                    if (!country_array[record.country.toUpperCase()]) {
                        country_array[record.country.toUpperCase()] = 1;
                        appendOptionLast(record.country.toUpperCase(), 'countryList');
                    }
                }
            }
        }

    },
    resultsLoaded: function () {
        if (searcher.error_code) {
            var err = '';
            if (searcher.error_explanation) {
                err = searcher.error_explanation;
            } else {
                err = 'Your request failed. Error code: ' + searcher.error_code;
            }
            return;
        }
        var results_returned = 1;
        var start_index_value = 1;
        // Loop through each record set:
        for (var count = 0, l = searcher.record_sets.length; count < l; count++) {
            if (searcher.record_sets[count].error) {
                var err = '';
                if (searcher.record_sets[count].error.error_explanation) {
                    err = searcher.record_sets[count].error.error_explanation;
                } else {
                    err = 'Your request failed. Error code: ' + searcher.record_sets[count].error.error_code;
                };
                return;
            }
            if (searcher.record_sets[count].records) {
                for (var record_count = 0, rl = searcher.record_sets[count].records.length; record_count < rl; record_count++) {
                    var record = searcher.record_sets[count].records[record_count];
                    appendOptionLast(record.branch_name, 'storename');
                }
            } else {
                var total = searcher.record_sets[count].totalRecordCount;
                el = document.createElement('p');
                if (total > 0) {
                    el.appendChild(document.createTextNode('Total results found: ' + total));
                } else {
                    el.appendChild(document.createTextNode('No results returned'));
                }
                results_returned = 0;
            }

        }

    },
    setUpStoreSearch: function () {

        var icon = new MMIcon('/secure/images/1024/multimap/marker.png');
        icon.iconSize = new MMDimensions(26, 28);
        icon.iconAnchor = new MMPoint(16, 18);
        icon.textAnchor = new MMPoint(4, 2);
        icon.textDimensions = new MMDimensions(12, 12);
        icon.groupName = 'o2';
        decluttericon = new MMIcon('/secure/images/1024/multimap/clustermarker.png');
        decluttericon.iconSize = new MMDimensions(32, 36);
        Callbacks.init(this.map, MarkerFields, HtmlFields, document.getElementById('results'), icon);
        this.storeSearch = new StoreSearch(
            this.map,
            'mm.clients.next2',
            5,
            this.getFilters,
            '10000',
            function () {
                if (window.location.search.indexOf('featured') != -1)
                    document.getElementById('store_holder').value = "";

                Callbacks.storeSearch(arguments[0], arguments[1]);
            }
        );
    },
    setUpElements: function () {
        ApplyMethods(document.body);
    }
}

MMAttachEvent( window, 'load', function() {
    var container = document.getElementById( 'mapviewer' );
    Page.init( container );
} );

function turnOffLocation() {
   var loc=document.getElementById('locationsearch');
   loc.value="";
}
function turnOffStore() {
   var st_holder=document.getElementById('store_holder');
   st_holder.value="";
   var st=document.getElementById('storename');
   st.value="";
}

function appendOptionLast(num, elem) {
    var elOptNew = document.createElement('option');
    elOptNew.text = num;
    elOptNew.value = num;
    var elSel = document.getElementById(elem);
    if (num) {
        try {
            elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
        }
        catch (ex) {
            elSel.add(elOptNew); // IE only
        }
    }
}
 function removeOptionLast(elem)  {
      var elSel = document.getElementById(elem);
      for (var i=0;i<=elSel.length;i++) {
      		if (elSel.length > 0)	{
        		elSel.remove(elSel.length - 1);
      		}
     	}
}
function countrySearch () {
    DisamHandler.clearDisam();
  	var rfs = ['EntityID', 'branch_name', 'street', 'town','PostalCode', 'Latitude', 'Longitude'];
 	var funcRef2 = countryResultsLoaded;
    var clist=document.getElementById('countryList');
    var cresult=clist.options[clist.selectedIndex].value;
    searcher = MMFactory.createSearchRequester( funcRef2 );
    search = new MMSearch(); 
    search.return_fields = rfs;
    search.radius_units = 'miles';
    search.count = 500; 
    search.filters = new Array();
    search.filters.push( new MMSearchFilter('country', 'Eq', cresult) );
    search.logic='AND';
    search.order_by_fields='branch_name'; 
    searcher.search( search );
}
function titleCase(original) {
    var o_split = original.split(" ");
    //this probably isn't a complete list of words that shouldn't be capitalized
    var special_words = new Array('and');
    for (i = 0; i < o_split.length; i++) {
        //always capitalize the first word
        o_split[i] = (o_split[i].substring(0, 1)).toUpperCase() + o_split[i].substring(1).toLowerCase();
    }
    retval = o_split.join(' ');
    return retval;
}
function countryResultsLoaded() {

    removeOptionLast('countryStoreList');
    appendOptionLast("Please Choose a Location...", 'countryStoreList')
    if (searcher.error_code) {
        var err = '';
        if (searcher.error_explanation) {
            err = searcher.error_explanation;
        } else {
            err =  'Your request failed. Error code: ' + searcher.error_code;
        }
        return;
    } 

    var results_returned = 1;
    var  start_index_value = 1;     
    // Loop through each record set:
    for ( var count=0, l = searcher.record_sets.length; count < l; count++ ) {
        if ( searcher.record_sets[count].error ) {
            var err =  '';
            if ( searcher.record_sets[count].error.error_explanation ) {
                err =  searcher.record_sets[count].error.error_explanation;
            } else {
                err =  'Your request failed. Error code: ' + searcher.record_sets[count].error.error_code;
            };
            return;  
        } 
        if ( searcher.record_sets[count].records ) {
            for (var record_count = 0, rl = searcher.record_sets[count].records.length; record_count < rl; record_count++ ) {
                var record = searcher.record_sets[count].records[record_count];      
                appendOptionLast(record.branch_name,'countryStoreList');        
            }          
        } else {
            var total = searcher.record_sets[count].totalRecordCount; 
            el = document.createElement ('p');
            if ( total  > 0) {
                el.appendChild ( document.createTextNode( 'Total results found: ' + total ) );
            } else {
                el.appendChild ( document.createTextNode( 'No results returned' ) ); 
            }  
            results_returned = 0;
        }
        
    }                        
}
function check_country() {
		var country=document.getElementById('countryList').value;
		var countryStore=document.getElementById('countryStoreList').value;
		
		if (country && countryStore=="" || country=="" && countryStore=="" ||  countryStore=="Please Choose a Location...") {
       	 	DisamHandler.say('Please select a Location from the drop down list.');
       		return false;
       	 } else {
       	 	DisamHandler.clearDisam;
			return 1;
       	 }

}
 function switchmenu(tab,showbox) {
           		document.getElementById('MMmenu1').className='';
           		document.getElementById('MMmenu2').className='';
             	document.getElementById('MMmenu3').className='';          
           		tab.className='selected';
           		document.getElementById('shopuk').style.display='none';
           		document.getElementById('shopworldwide').style.display='none';
            	document.getElementById('shoponlinebox').style.display='none';
            	document.getElementById(showbox).style.display='block';
}
function shopOnline () {
    var clist=document.getElementById('onlineList');
    if (clist.value == "") {
        	 DisamHandler.say('Please select your country first.');  
        	 return false; 
    } else {
    	var cresult=clist.options[clist.selectedIndex].value;
    	self.parent.location.href=cresult;
    }
}  
function shopOnlineList () {
    shoponlinesearcher = MMFactory.createSearchRequester( onlineListLoaded  );
    // Set return fields, radius units, and maximum number of records to return from search:
    search = new MMSearch(); 
    search.return_fields =['shop_online_country','shop_online_link'];
    search.radius_units = 'km';
    search.radius = 10000000;
    search.count = 250; 
    search.filters = new Array();
    search.filters.push( new MMSearchFilter('shop_online_link', 'Ne', ' ') );

    search.logic='AND';

    search.order_by_fields='shop_online_country'; 
    shoponlinesearcher.search( search );
}  
function onlineListLoaded ( ) {
    if ( shoponlinesearcher.error_code ) {
        var err =  '';
        if ( shoponlinesearcher.error_explanation ) {
            err =  shoponlinesearcher.error_explanation;
        } else {
            err =  'Your request failed. Error code: ' + shoponlinesearcher.error_code;
        }
        return;
    } 
    var results_returned = 1;
    var start_index_value = 1;

    if (!shoponlinesearcher.record_sets || shoponlinesearcher.record_sets.length == 0)
        return;

    // Loop through each record set:
    for ( var count=0, l = shoponlinesearcher.record_sets.length; count < l; count++ ) {
        if ( shoponlinesearcher.record_sets[count].error ) {
            var err =  '';
            if ( shoponlinesearcher.record_sets[count].error.error_explanation ) {
                err = shoponlinesearcher.record_sets[count].error.error_explanation;
            } else {
                err =  'Your request failed. Error code: ' + shoponlinesearcher.record_sets[count].error.error_code;
            };
            return;  
        } 

        country_array = new Object;
        if (shoponlinesearcher.record_sets[count].records ) {
            for (var record_count = 0, rl = shoponlinesearcher.record_sets[count].records.length; record_count < rl; record_count++ ) {
                var record = shoponlinesearcher.record_sets[count].records[record_count];     
				if (!country_array[record.shop_online_country.toUpperCase()]) {
				
					country_array[record.shop_online_country.toUpperCase()]=1;				
                 	appendOptionLastFull(record.shop_online_country.toUpperCase(),record.shop_online_link.toUpperCase(),'onlineList'); 
                } 
            }        
        }       
    }    
                    
}
function check_country() {
		var country=document.getElementById('countryList').value;
		var countryStore=document.getElementById('countryStoreList').value;
		if (country && countryStore=="" || country=="" || countryStore=="Please Choose a Location...") {
       	 	DisamHandler.say('Please choose a store before you search.');
       		return false;
       	 } else {
       	 	DisamHandler.clearDisam;
			return 1;
       	 }

}
function check_uk() {
    var location = document.getElementById('locationsearch').value;
    var shoptypeList = document.getElementById('store_holder').value;
		if (location=="" && shoptypeList=="" ) {
       	 	DisamHandler.say('Please enter a Location before you search.');
       		return false;
       	 } else {
       	 	DisamHandler.clearDisam;
			return 1;
       	 }

}
function appendOptionLastFull(num, val, elem) {
    var elOptNew = document.createElement('option');
    elOptNew.text = num;
    elOptNew.value = val;
    if (num) {
        var elSel = document.getElementById(elem);
        try {
            if(elSel != null)
              elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
        }
        catch (ex) {
            if (elSel != null)
              elSel.add(elOptNew); // IE only
        }
    }
}
function removeOptionLast(elem)  {
      var elSel = document.getElementById(elem);
     	elSel.options.length = 0;
} 
