var mapviewer, searcher, loading, markers, search;
var filter1, filter2, filter3, boolean1, filter4, filter5, filter6, return_fields, submitbtn;
var funcRef = resultsLoaded;
var funcRef2 = countryResultsLoaded;
var funcRef3 = newResultsLoaded;
// Including the 'client_id' ensures that clicking on a result logs it as such within the reports:
var rfs = ['client_id', 'branch_name', 'street', 'town','pc', 'lat', 'lon', 'id','branch_short_name'];
function clearForms() {
  var i;
  for (i = 0; (i < document.forms.length); i++) {
    document.forms[i].reset();
  }
}
function onLoad() {
    // Construct Map Viewer and display default location:
 	initSearch();	
 	clearForms();
 	countryList();
 	shopOnlineList();
 	DisamHandler.init( document.getElementById( 'homeimage' ) );
        
}
function countryList () {
  var rfs = ['country']; 
 	var funcRef2 = countryListLoaded;
    var clist=document.getElementById('countryList');
    otherSearcher = MMFactory.createSearchRequester( funcRef2 );
    search = new MMSearch(); 
    search.return_fields = rfs;
    search.radius_units = 'miles';
    search.count = 1000; 
    search.filters = new Array();
    search.filters.push( new MMSearchFilter('lat', 'not', ' ') );
    search.filters.push( new MMSearchFilter('lon', 'not', ' ') );
    search.filters.push( new MMSearchFilter('GeoQuality', 'not', '0') );
    search.filters.push( new MMSearchFilter('GeoQuality', 'not', '7') );
    search.filters.push( new MMSearchFilter('country', 'not', 'UNITED KINGDOM') );
    search.order_by_fields='country'; 
    otherSearcher.search( search );
}

function countrySearch () {
 	DisamHandler.clearDisam();
    var clist=document.getElementById('countryList');
    var cresult=clist.options[clist.selectedIndex].value;
    searcher = MMFactory.createSearchRequester( funcRef2 );
    // Set return fields, radius units, and maximum number of records to return from search:
    search = new MMSearch(); 
    search.return_fields = rfs;
    search.radius_units = 'miles';
    search.count = 1000; 
    search.filters = new Array();
    search.filters.push( new MMSearchFilter('country', 'eq', cresult) );
    search.logic='AND';
    search.filters.push( new MMSearchFilter('lat', 'not', ' ') );
    search.filters.push( new MMSearchFilter('lon', 'not', ' ') );
    search.filters.push( new MMSearchFilter('GeoQuality', 'not', '0') );
    search.filters.push( new MMSearchFilter('GeoQuality', 'not', '7') );
    search.order_by_fields='branch_name'; 
    searcher.search( search );
}  
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 = 'miles';
    search.radius = 10000000;
    search.count = 1000; 
    search.filters = new Array();
    search.filters.push( new MMSearchFilter('shop_online_link', 'contains', 'http') );

    search.logic='AND';

    search.order_by_fields='shop_online_country'; 
    shoponlinesearcher.search( search );
}  
function initSearch () {
    searcher = MMFactory.createSearchRequester( funcRef );
    // Set return fields, radius units, and maximum number of records to return from search:
    search = new MMSearch(); 
    search.return_fields = rfs;
    search.radius_units = 'miles';
    search.count = 1000; 
    search.filters = new Array();
    search.filters.push( new MMSearchFilter('country', 'eq', 'UNITED KINGDOM') );
    search.order_by_fields='branch_name'; 
    searcher.search( search );
}          
function resultsLoaded ( ) {
    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,record.branch_name,'shoptypeList');            
            }        
        } 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;
        }
        
    } 
   newStores();                        
}
function countryListLoaded ( ) {
    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(),record.country.toUpperCase(),'countryList'); 
                } 
            }        
        }       
    }    
                    
}
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;     
    // 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;				
                 	appendOptionLast(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=="") {
       	 	DisamHandler.say('Please enter a Location before you search.');
       		return false;
       	 } else {
       	 	DisamHandler.clearDisam;
			return 1;
       	 }

}
function check_uk() {
		var location=document.getElementById('loc').value;
		var shoptypeList=document.getElementById('shoptypeList').value;
		if (location=="" && shoptypeList=="" ) {
       	 	DisamHandler.say('Please enter a Location before you search.');
       		return false;
       	 } else {
       	 	DisamHandler.clearDisam;
			return 1;
       	 }

}
function newStores() {
	 searcher = MMFactory.createSearchRequester( funcRef3 );
    // Set return fields, radius units, and maximum number of records to return from search:
    search = new MMSearch(); 
    search.return_fields = rfs;
    search.radius_units = 'miles';
    search.count = 4; 
    search.filters = new Array();
    search.filters.push( new MMSearchFilter('country', 'eq', 'United Kingdom') );
    search.logic = 'AND';
    search.filters.push( new MMSearchFilter('new_store_opening', 'eq', 'new') );
    search.order_by_fields='branch_name'; 
    searcher.search( search );
	
}
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;     
    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,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 newResultsLoaded ( ) {
    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];      
                var newStore="newStore"+record_count; 
                if (record.branch_short_name) {
         			    var	branch_name=titleCase(record.branch_short_name);
     			    	} else {
     			     		var	branch_name=titleCase(record.branch_name);     			    		
     			    	}
     			    		
     			    	  anchor = document.createElement ( 'a' );
					      anchor.className="newstoreLink";
						  anchor.href = 'storesearch.asp?location=&postcode=&storename='+record.branch_name+'&x=21&y=14';
     			    	
	 	  				  anchor2 = document.createElement ( 'a' );
					      anchor2.className="newstoreLink2";
						  anchor2.href = 'storesearch.asp?location=&postcode=&storename='+record.branch_name+'&x=21&y=14';
     			    	
						  
					      
					  	  para = document.createElement('p');	
						  para.appendChild(document.createTextNode( branch_name )); 
				  	  
						  anchor.appendChild(para);	      
						  
					
						  impara=document.createElement('p');  
  
   						  impara.appendChild(document.createTextNode( 'View' ));   
				  		      					  					  
				
					      anchor2.appendChild(impara);	
			
				
					//	  para.appendChild(impara);

			
				               	   							  											  
						  var ns=document.getElementById(newStore).appendChild(anchor);        			
						  var ns2=document.getElementById(newStore).appendChild(anchor2);  								 
								
						
			
            }       
        } 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 appendOptionLast(num,val,elem)
{
  var elOptNew = document.createElement('option');
  elOptNew.text =  num;
  elOptNew.value = val;
  if (num) {
		var elSel = document.getElementById(elem);
		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);
     	elSel.options.length = 0;
} 
MMAttachEvent( window, 'load', onLoad ); 
function titleCase(original)
	{
		var o_split = original.split(" ");
		var special_words = new Array('and');
		for (i=0;i<o_split.length;i++) {
				o_split[i] = (o_split[i].substring(0,1)).toUpperCase() + o_split[i].substring(1).toLowerCase();
		}
		retval = o_split.join(' ');
		return retval;
	}
	function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}
DisamHandler = {
    container: null,
    disam: {
        container: null,
        disam: null
    },
    init: function( container ) {
        this.container = container;
        this.createDisam();
        this.setUpCloseButton();
        this.switchDisamDisplayState( 'none' );
    },
    setStyle: function( o, css ) {
        if ( navigator.userAgent.indexOf( 'MSIE' ) > -1 ) {
            o.style.setAttribute( 'cssText', this.IECss( css ) );
        } else {
            o.setAttribute( 'style', css );
        }
    },
    IECss: function( css ) {
        return css.replace( /opacity\:\s?.{3}/g, 'filter: alpha( opacity=75 )' );
    },
    createDisam: function() {
        this.dimensions = this.calculateDisamDimensions();
        var cssText = 'position: absolute; background: #FFF; z-index: 999999; ', containerCss, disamCss;
        var container = document.createElement( 'div' ), disam = document.createElement( 'div' ), close = document.createElement( 'a' );
        var parent = this.container.parentNode;
        var ie = navigator.userAgent.indexOf( 'MSIE' ) > -1;

        container.id = 'disam';
        containerCss = cssText + 'top: ' + this.dimensions['top'] +  'px; left: ' + this.dimensions['left'] + 'px; width: ' + this.dimensions['width'] + 'px; height: ' + this.dimensions['height'] + 'px; opacity: 0.5;';
        this.setStyle( container, containerCss );
        parent.appendChild( container );
        
        disamCss = cssText + 'top: ' + ( this.dimensions['top'] + 150 ) + 'px; left: ' + ( this.dimensions['left'] + 20 ) + 'px; ';
        disamCss += 'width: ' + ( this.dimensions['width'] - 72 ) + 'px; height: ' + ( this.dimensions['height'] - 332 ) + 'px; ';
        disamCss += 'border: 1px solid #000066; padding: 15px; overflow-x: hidden; overflow-y: auto;';
        this.setStyle( disam, disamCss );
        parent.appendChild( disam );

        close.className = 'MMclose';
        close.href = '#';
        closeCss = cssText + 'top: ' + ( this.dimensions['top'] + 160 ) + 'px; left: ' + ( this.dimensions['left'] + this.dimensions['width'] - 46 ) + 'px;';
        closeCss += 'width: 16px; height: 16px; background: url( /secure/images/1024/multimap/close.png ) no-repeat;';
        this.setStyle( close, closeCss );
        parent.appendChild( close );

        return this.disam = { container: container, disam: disam, close: close };
    },
    calculateDisamDimensions: function() {
        var offset, dimensions;
        offset = this.getOffset( this.container, this.container.parentNode );
        dimensions = {
            width: Number( this.container.offsetWidth ),
            height: Number( this.container.offsetHeight ),
            left: offset.x,
            top: offset.y
        }
        return dimensions;
    },
    clearDisam: function() {
        this.disam.disam.innerHTML = '';
        this.switchDisamDisplayState( 'none' );
    },
     setUpCloseButton: function() {
        if ( this.disam && this.disam.close ) {
            this.disam.close.onclick = function() {
                DisamHandler.clearDisam();
                return false;
            }
        }
    },
    getOffset: function( o, parent ) {
        var ret = { x: o.offsetLeft, y: o.offsetTop };
        parent = parent ? parent : document.body;
        while( o.offsetParent && o.offsetParent != parent ) {
            o = o.offsetParent;
            ret.x += o.offsetLeft;
            ret.y += o.offsetTop;
        }
        return ret;
    },
 	say: function( message) {
        var me = DisamHandler, callback;
            var o = document.createElement( 'h3' );
            o.innerHTML = message;
            me.populateDisam( o );
           
	},
    populateDisam: function( child ) {
        this.clearDisam();
        this.disam.disam.appendChild( child );
        this.switchDisamDisplayState( 'block' );
    },
    switchDisamDisplayState: function( style ) {
        for ( var element in this.disam ) {
            this.disam[element].style.display = style;
        }
    }
}

//]]> 
// -->