var REGIONAL_MAP_ZOOM_FACTOR=6;
//Note the following variables hold the names of the columns used in our table of addresses.  Value on the right must match the columns in the address table
var CLIENT_ID='client_id';
var MAP_ID = 'id';
var STORE_NAME='name';
var STREET='street';
var TOWN='town';
var ADDRESS3='address3';
var POSTCODE='pc';
var TELEPHONE='telephone';
var EMAIL='email';
var OPENING_HOURS='opening_hours';
var INSTORE_SERVICES='instore_services';
var DISTANCE='distance';
var BRAND='brand';
var LAT='lat';
var LON ='lon';

var mapviewer;
var searcher;
var search;
var routeFinder;
var route;
var markers;
var stepMarkers;
var locations;

var postcodeSearchRadioButton;
var townSearchRadioButton;

var errorDiv;

var filter1;
var filter2;
var filter3;

var inputPostcode;

var sfmainDiv;
var printLinkDiv;
var nearestStoreDiv;
var nearbyStoresDiv;
var backLinkDiv;

var maxZindex = 1000;

var storeIcon;

//Hold the new HTML to be added to the div sfmain.  Used for swapping between forms in sfmain.
var searchFormHtml;
var newsfmainHTML;
var nearestStoreHtml;
var searchResultsHtml;

var page;

//String array holding the fileds that should be available when the search results are returned
var rfs = [CLIENT_ID,MAP_ID,STORE_NAME,STREET,TOWN,POSTCODE,TELEPHONE,OPENING_HOURS,INSTORE_SERVICES,DISTANCE,LAT,LON,BRAND];

var errors;
function loadMap(){
	mapviewer = new MultimapViewer( document.getElementById( 'sfmulti' ) );
	mapviewer.goToPosition( new MMLocation( new MMLatLon( 55.72697, -10.02215 ) ,REGIONAL_MAP_ZOOM_FACTOR ) );
	mapviewer.resize(540,465);
	
	postcodeSearchRadioButton = document.getElementById('postcodesearch');
	townSearchRadioButton = document.getElementById('townnamesearch');
		
	sfmainDiv = document.getElementById('sfmain');
	backLinkDiv = document.getElementById('backToPreviousPage');
	backLinkDiv.style.visibility = 'hidden';
	printLinkDiv = document.getElementById('printlink');
	printLinkDiv.style.visibility = 'hidden';
	
	errorDiv = document.getElementById('errorText');
	
	searchFormHtml=sfmainDiv.innerHTML;
	
	searcher = new MMSearchRequester( handleSearchResults );
	routeFinder=new MMRouteRequester( handleRouteResults );
	mapviewer.addWidget( new MMSmallPanZoomWidget() );
	mapviewer.addEventHandler('click', onClick);
		
	//Initlise sfmain HML to contain the direction search HTML
	newsfmainHTML = '';
	
	//Inititlaise the array of errors
	errors= new Array();
	
	storeIcon=new MMIcon('/images/storeLocator/store-marker.gif');
	storeIcon.iconSize=new MMDimensions(19,19);
	storeIcon.iconAnchor=new MMPoint(9.5,19);
	storeIcon.textAnchor = new MMPoint(0,-2);
	storeIcon.groupName = 'storeMarkers';

	renderSearchInputs();

}

//Executes a search initited from a from
function executeFormSearch(){
	
	var postcodeInput = document.getElementById('postcodeInput');
	var townInput = document.getElementById('townInput');
	cleanup();
	
    // 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';
    inputPostcode = '';
    
	if(postcodeSearchRadioButton.checked &&postcodeInput.value !== '' ){
		search.address = new MMAddress({ postal_code : postcodeInput.value, country_code : 'UK'})
		inputPostcode = postcodeInput.value;
	}	
	else if(townSearchRadioButton.checked && townInput.value !== '' ){
		search.address = new MMAddress({ city : townInput.value, country_code : 'UK'});
	}
	else{
		document.getElementById('errorText').innerHTML =  '<div class="errorSummary">Please enter either a Postcode or Your Nearest town</div>';
		return;
	}
	
    search.count = 10; 
        
    searcher.search( search );    
}


function cleanString(inputString){

	var newString = inputString.replace(/'/g,'\\\'');
	return newString;
}


//Executes a search when the user clicks on the regional map of the UK
function executeMapSearch(position){
	cleanup();
	inputPostcode = '';
	
    // Set return fields and maximum number of records to return from search
    search = new MMSearch(); 
    search.return_fields = rfs;
    //search.count = 10;
    
    
    //Set the search point the user clciked on
    search.point = position;
    
    //Search for addresses within the bounds of the map
    search.bounding_box = mapviewer.getMapBounds();
    
    searcher.search( search );   
    

    

}

function handleSearchResults(){
   	
   	document.getElementById('errorText').innerHTML = '';
   	//Check errors on the searcher and errors on the record set
   	if( searcher.error_code ) {
   		processError(searcher.error_code);
   		return;
   	}
      
    //Display results if there any
    if(searcher.record_sets.length > 0){
    	if( searcher.record_sets[0].records ){
    	
    	//Make the print link and back link visible
    	backLinkDiv.style.visibility='visible';
    	printLinkDiv.style.visibility='visible';
    	

    	if( searcher.record_sets[0].error ) {
    	
    		processError(searcher.error_code);
    		return;
    	}
    	
    	page='results';    	
    	    	 	
		//Display first record on the left hand side of the page
		var record = searcher.record_sets[0].records[0];
		mapviewer.removeAllOverlays();
		var html = '<h2>Your Nearest Store</h2>'
			+ '<div class="gradorabox"><div class="right"><div class="left">'
			+ '<div class="clear"></div>'
			+ '<div class="col1"><strong>Map ID:</strong></div><div class="col2">' + 1 + '</div>'
			+ '<div class="col1"><strong>Store Name:</strong></div><div class="col2">' + record[STORE_NAME] + '</div>'
			+ '<div class="col1"><strong>Address:</strong></div><div class="col2">' + record[STREET] + ',' + record[TOWN] + '</div>'
			+ '<div class="col1"><strong>Postcode:</strong></div><div class="col2">' + record[POSTCODE] + '</div>'
			+ '<div class="col1"><strong>Phone Number:</strong></div><div class="col2">' + record[TELEPHONE] + '</div>'
			+ '<div class="col1"><strong>Opening Hours:</strong></div><div class="col2">' + record[OPENING_HOURS] + '</div>'
			+ '<div class="col1"><strong>Instore Services:</strong></div><div class="col2">' + record[INSTORE_SERVICES] + '</div>'
			+ '<div class="col1"><strong>Distance:</strong></div><div class="col2">' + getDistance(record) + ' miles </div>'
			+ '<div class="clear"></div>'
			+ '<div class="tright"><a href="#" onclick="displayDirectionSearchForm(\'' + cleanString(record[STORE_NAME]) + '\',\'' + record[POSTCODE] +'\',' + record.point.lat + ',' + record.point.lon + ');return false">Get directions to this store</a></div>'
			+ '</div></div></div>';
    	
    	
    	   createStoreMarker(record,1);
    	
    	   	nearestStoreDiv = document.getElementById('storeinfo');
			nearbyStoresDiv = document.getElementById('sfallstores');
    	    nearestStoreDiv.innerHTML=html;
    	        	    
    	 	nearestStoreHtml=html;
    	 		  
			var numOfStores = searcher.record_sets[0].records.length;
			
			html = '<div><span class="left">All nearby stores</span><span class="right">We have found <strong>' + numOfStores + '</strong> nearby stores</span><div class="clear"></div></div>'
			+ '<table summary="List of nearby stores" cellpadding="0" cellspacing="0">'
			+ '<tr>'
					+'<th class="col1 thcol1">Map ID</th>'
					+'<th>Store Name</th>'
					+'<th>Address</th>'
					+'<th class="col4">Phone number</th>'
					+'<th class="col5">Opening hours</th>'
					+'<th class="col6">Services</th>'
					+'<th>Distance</th>'
					+'<th class="thcol8">Directions</th>';
			
			
			
			//Put all the results in a table at the bottom of the page
            for (var i = 1; i < numOfStores; i++ ) {
            	var currentRecord = searcher.record_sets[0].records[i];
            	var recordNum = i + 1;
            	html += '<tr>'
					+ '<td class="col1 tdcol1">' + recordNum + '</td>'
					+ '<td>' + currentRecord[STORE_NAME] + '</td>'
					+ '<td>' + currentRecord[STREET] + ', <br />' + currentRecord[TOWN] + ',<br />' + currentRecord[POSTCODE] + '</td>'
					+ '<td class="col4">' + currentRecord[TELEPHONE] + '</td>'
					+ '<td class="col5">' + currentRecord[OPENING_HOURS] + '</td>'
					+ '<td class="col6">' + currentRecord[INSTORE_SERVICES] + '</td>'
					+ '<td>' + getDistance(currentRecord) + ' miles</td>'
					+ '<td class="tdcol8"><a href="#" onclick="displayDirectionSearchForm(\'' + cleanString(currentRecord[STORE_NAME]) + '\',\'' + currentRecord[POSTCODE] +'\',' + currentRecord.point.lat + ',' + currentRecord.point.lon + ');return false;">Get directions</a></td>'
				+ '</tr>';  
				
				if(currentRecord.point){
					createStoreMarker(currentRecord,recordNum);	
				}			
            }	
            
		   html +='</tr></table>';
		   	
    	   nearbyStoresDiv.innerHTML = html;
    	       	   
    	   searchResultsHtml = html;
    	   
          //Add markers to the map and scale it appropriatley
          mapviewer.goToPosition ( mapviewer.getAutoScaleLocation( markers ) );      
    	}
    }
}
function searchDirections(postcodeEndpoint){	
	cleanup();
	

	
	//Add the start point and end point as locations to the search
	var startpoint = new MMAddress();
	var endpoint = new MMAddress();
	startpoint.qs=document.getElementById('directionsfrom').value;
	
	//If no input entered or have the grey 'Enter postcode' text then throw an error.  Note that IE and firefix have different values for the colors
	//For black FF sets the colour value as 'rgb(0, 0, 0)' where as IE sets it to #000000 so both conditions for the color need to be checked.
	var textColor = document.getElementById('directionsfrom').style.color;
	if(startpoint.qs == '' || (textColor != 'rgb(0, 0, 0)' && textColor != '#000000' )){
		document.getElementById('errorText').innerHTML =  '<div class="errorSummary">The postcode field is blank.  Please enter a postcode to get directions.</div>';
		return;
	}
	
	endpoint.qs=postcodeEndpoint;
			
	locations.push(new MMLocation(startpoint),new MMLocation(endpoint));
	
	route = new MMRoute(locations);
		
	//Get route options from the form
	route.optimize_for = getRadioGroupSelectedValue('optimizefor');
	route.mode = getRadioGroupSelectedValue('mode') ;
	var exclude = '';
	
	if(document.getElementById('excmc').checked){
		route.exclude = 'motorways';
	} 
	
	routeFinder.request(route);
		
}

function handleRouteResults(){

    document.getElementById('errorText').innerHTML = '';
    if (route.error_code) {
        processError(route.error_code);
    } else {
        // Scale the route on the map by using getAutoScaleLocation , with the route bounds
        mapviewer.removeAllOverlays();
        mapviewer.goToPosition( mapviewer.getAutoScaleLocation( route.bounds ) );
        displayRouteStages(route);
        // Draw the route on the map showing all the polylines that make it up
        for( var i = 0, l = route.polyLine.length; i < l; ++i ) {
          mapviewer.addOverlay(route.polyLine[i]);
        }
    }
}

function displayDirectionSearchForm(storeName, postcodeEndpoint,lat,lon){
	
	mapviewer.goToPosition(new MMLatLon(lat,lon),14);
	
	page='directions'; 
	
	sfmainDiv.innerHTML = '<div id="storesearch" class="scontent"><div id="errorText"></div>'
	+ '<fieldset>'
	+ '<h2 class="marginbot20">Search for directions to this store</h2>'
	+ '<div class="rowpad">Directions from <input id="directionsfrom"  onfocus="if(inputPostcode== \'\'){this.value=\'\';this.style.color=\'#000000\'};" type="text" title="direct from location" class="inactive" value="Enter postcode" /></div>'
	+ '<div class="marginbot20">Directions to ' + storeName + ' - ' + postcodeEndpoint + '</div>'
	+ '<div class="radioleft rowpad"><input type="radio" name="optimizefor" id="radioq" checked="checked" value="distance" /> <label for="radioq">Quickest</label></div>'
	+ '<div class="radioright rowpad"><input type="radio" name="optimizefor" id="radios" value="time" /> <label for="radios">Shortest</label></div>'
	+ '<div class="clear"></div>'
	+ '<div class="radioleft rowpad"><input type="radio" name="mode" id="radiod" checked="checked" value="driving" /> <label for="radiod">Driving</label></div>'
	+ '<div class="radioright rowpad"><input type="radio" name="mode" id="radiow" value="walking" /> <label for="radiow">Walking</label></div>'
	+ '<div class="clear"></div>'
	+ '<div class="excmot"><input type="checkbox" id="excmc" /> <label for="excmc">Exclude motorways</label></div>'
	+ '<img src="../images/storeLocator/tc_gp_logos.gif" class="floatleft botimg" alt="" /><input onclick="searchDirections(\'' + postcodeEndpoint + '\');return false;" class="floatright botimg" type="image" id="findstorebtn" name="continue" alt="find store" src="../images/siteElements/buttons/getdirections.gif" />'
	+ '<div class="clear"></div>'
    + '</div><div class="tcenter"><a href="#" onclick="getDirectionsToAnotherStore();return false;">Search for directions to another store</a></div>'
	+ '</fieldset>';
	
	//Modify the colour of the prepoplated postcode to black
	if(inputPostcode != ''){
		document.getElementById('directionsfrom').style.color='#000000';
		document.getElementById('directionsfrom').value=inputPostcode;
		
	}
	
	
	clearSearchResults();
}

function getDirectionsToAnotherStore(){
	sfmainDiv.innerHTML=searchFormHtml + '<div id="storeinfo"></div>';
	document.getElementById('storeinfo').innerHTML=nearestStoreHtml;
	nearbyStoresDiv.innerHTML=searchResultsHtml;
}

function backToPreviousPage(){

	if(page == 'results'){
		nearestStoreDiv.innerHTML = '';
		nearbyStoresDiv.innerHTML = '';
		backLinkDiv.style.visibility = 'hidden';		
	} else if(page == 'directions'){
		getDirectionsToAnotherStore();
		page = 'results';
	}

}

function swapsfmainHTML(){
	var temp = sfmainDiv.innerHTML;
	sfmainDiv.innerHTML = newsfmainHTML;
	newsfmainHTML = temp;
	
	clearSearchResults();
}

//Function to dispaly the stages of the route on the appropraite area of the web page
function displayRouteStages(route){
	stepMarkers = new Array();
	var currStep = 1;
	var routeInfoDiv=document.getElementById('sfmain');
	
	
	//Rmeov old directions in case they are there
	var directionsHeading = document.getElementById('directionsHeading');
	var directionsList = document.getElementById('directionsList');
	
	if(directionsHeading && directionsList){
		directionsHeading.parentNode.removeChild(directionsHeading);
		directionsList.parentNode.removeChild(directionsList);
	}
	
	
	//var htmlText = '<div class="bluegradhead top15margin" id="directionsHeading"><h2>Directions</h2></div><div class="bluegradbody" id="directionsList">';
	var htmlText = '';
	
    var directionsHeading = document.createElement('div');
    directionsHeading.id='directionsHeading';
    directionsHeading.className = 'bluegradhead top15margin';
    directionsHeading.innerHTML = '<h2>Directions</h2>';
    
    var directionsList = document.createElement('div');
    directionsList.id='directionsList';
    directionsList.className = 'bluegradbody';
    
    if(route.stages.length > 0){
    
    	    var steps = route.stages[0].steps; 
    	    for (var count=0; count < steps.length; count++) {
    	    	var imgSrc = '';
    	    	if(count==0 || count==steps.length-1){
    	    		imgSrc = '../images/siteElements/boxes/dir_entry_exit.gif';
    	    	} else{
    	    		imgSrc = '../images/siteElements/boxes/dir_right.gif';
    	    	}    	    	
	            // Create a written 'instruction' using the roadname and/ or roadnumber:
	            var instruction = steps[count].instruction;
	            var roadname = steps[count].road_name;
	            var roadnumber = steps[count].road_number; 
	
	            if (roadname && roadnumber) {
	                instruction += ' ' + roadname + ' (' + roadnumber + ') ';
	            } else if (roadname) {
	                instruction += ' ' + roadname + ' ';
	            } else if (roadnumber) {
	                instruction += ' ' + roadnumber + ' ';
	            }
	            var zindex = maxZindex - currStep + 1;
	            createStepMarker(steps[count].start_point, instruction, currStep, zindex);
	            // Show the distance of this particular step:
	            var distance = '';                    
	            if (steps[count].distance.miles > 0) { distance += steps[count].distance.miles + ' mile(s) '; }
	            if (distance != '') { distance = ' - ' + distance };
	            
	           htmlText += '<div class="innergrad"><div class="floatright"><a href="#" onClick="stepMarkers[' + (currStep-1) + '].openInfoBox();"><img src="' + imgSrc + '" alt="" /></a></div><div class="floatleft width300"><p><strong>' + (count+1) + ') </strong>' +  instruction + distance +'</p></div><div class="clear"></div></div>';
	           currStep++;
    	    }
  	              	    //routeInfoDiv.innerHTML += '</div>';
  	           directionsList.innerHTML += htmlText;
  	           sfmainDiv.appendChild(directionsHeading);
  	           sfmainDiv.appendChild(directionsList);
  	           
  	           
  
    
    }


}

//Function to create a store marker on the map
function createStoreMarker(record,number){
	    	    
	    var marker = mapviewer.createMarker( record.point,{'icon':storeIcon,'text':number});
	    
	    var lat = record.point.lat;
	    var lon = record.point.lon;
	    
	    var html = '<div class="mpBH"><h2>Store Information</h2></div><p>'
		+ '<br/><b>Store Name: </b>' + record[STORE_NAME]
		+ '<br/><b>Address: </b>' + record[STREET] + ', ' + record[TOWN]
		+ '<br/><b>Postcode: </b>' + record[POSTCODE]
		+ '<br/><b>Phone Number: </b>' + record[TELEPHONE]
		+ '<br/><b>Opening Hours: </b>' + record[OPENING_HOURS]
		+ '<br/><b>Instore services: </b>' + record[INSTORE_SERVICES]
		+ '<br/><b>Distance: </b>' + getDistance(record)
		+ '<br/><a href="#" onclick="displayDirectionSearchForm(\'' + record[STORE_NAME] + '\',\'' + record[POSTCODE] +'\',' + record.point.lat + ',' + record.point.lon + ');return false">Get directions to this store</a></p>';

	    marker.setInfoBoxContent(html,{'className':'mpB',min_width:170});
	   markers.push(marker);	   
}

function createStepMarker(location, instruction, text, zindex) {
    var marker = mapviewer.createMarker(location, {zIndex: zindex, 'text' : text});
    marker.setInfoBoxContent('<p>' + instruction + '<' + '/p>');
    stepMarkers.push(marker);
}

function renderSearchInputs(){

	var postcodeSearchRadioButton = document.getElementById('postcodesearch');
	var townSearchRadioButton = document.getElementById('townnamesearch');
	
	var postcodeInput = document.getElementById('postcodeInput');
	var townInput = document.getElementById('townInput');
	
	if(postcodeSearchRadioButton.checked){
		townInput.disabled = true;
		townInput.style.backgroundColor = '#B4B4B4';
		townInput.value = '';
		if(postcodeInput.disabled){
			postcodeInput.disabled = false;
			postcodeInput.style.backgroundColor = '#FFFFFF';
		
		}	
	}
	else if(townSearchRadioButton.checked){
		postcodeInput.disabled = true;
		postcodeInput.style.backgroundColor = '#B4B4B4';
		postcodeInput.value = '';
		
		if(townInput.disabled){
			townInput.disabled = false;
			townInput.style.backgroundColor = '#FFFFFF';		
		}	
	}
	
	


}  

function onClick(type,target,position){ 
		//If user clicks on a regional UK map forward to method executeMapSearch() to execute the search
		if(mapviewer.getZoomFactor() == REGIONAL_MAP_ZOOM_FACTOR){
			executeMapSearch(position);
		}
}

//utility function to get the selected value within a radio group.  groupName is the name if the radio group to check.
function getRadioGroupSelectedValue(groupName){
	var radioGroup = document.getElementsByName(groupName);
	for(i=0;i<radioGroup.length;i++){
		if(radioGroup[i].checked){
			return radioGroup[i].value;
			break;
		}
	}
}

function cleanup(){

	markers = new Array();	
	locations = new Array();
	mapviewer.removeAllOverlays();
}

function clearSearchResults(){
	nearestStoreDiv.innerHTML = '';
	nearbyStoresDiv.innerHTML = '';
}

function getDistance(record){
	if(record.distance){
		return record.distance.miles;
	} else{
		return 0;
	}

}

//Helper method used to look up an error code returned from multimap and render it on  the page as appropraite
function processError(errorCode){
	//Lookup error message for code from array
	var errorMessage = errors[errorCode];
	//Add error to the appropriate div on the form
	document.getElementById("errorText").innerHTML = '<div class="errorSummary">' + errorMessage + '</div>';
}
