/*-----------------------------------------
//searching.js
For CentreMapsLive Ver. 2
Code for location searching
Lovell Jonhs Ltd.
01/01/10
-----------------------------------------*/

var theType;									//Type of search (addr, pc, town, coord)
var baseMappingToShow ;							//Base mapping to zoom to for the search result


//************************Show search options when user clicks search button (in order for user to choose the type of mapping)
function showSearchOptions(){
	//Define the search being performed
	if(document.searchform.searchtype[0].checked){				
		theType = "addr";
	}else if(document.searchform.searchtype[1].checked){									
		theType = "pc";
		var stringToPass = document.searchform.searchPostcode.value;		
	}else if(document.searchform.searchtype[2].checked){				
		theType = "town";
		var stringToPass = document.searchform.searchPlacename.value;		
	}else if(document.searchform.searchtype[3].checked){
		theType = "coord";
		var stringToPass = document.searchform.searchCoords.value;
	}	
	//Validate the input 
	var inputIsOK = true;
	if(theType == "addr"){
		var searchType = document.getElementById("addressSearchType").value;
		if(searchType == "pc"){			//Check building and postcode entered
			if((document.getElementById("qasBuilding").value == "") || (document.getElementById("qasPostcode").value == "")){
				if(document.getElementById("qasPostcode").value == ""){
					showDialog('Warning','Please ensure search input is fully entered.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
					inputIsOK = false;
				}else{			
					//Postcode only defined - we can just call the postcode search instead so don't flag error
				}
			}
		}else{						   //Check at least street and town entered
			if((document.getElementById("qasStreetName").value == "") || (document.getElementById("qasTown").value == "")){
				showDialog('Warning','Please ensure search input is fully entered.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
				inputIsOK = false;
			}
		}
	}else if(theType == "coord"){															//Coordinates search						
		if(stringToPass == ""){
			showDialog('Warning','Please ensure search input is fully entered.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');			
			inputIsOK = false;
		}else{
			var sep = stringToPass.indexOf(",");
			if(sep == -1){
				var sep2 = stringToPass.indexOf(" ");
				if(sep2 == -1){ 
					showDialog('Warning','Coordinate not specifed correctly. Ensure the x-y cordinates are seperated by either a space or comma.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
					inputIsOK = false;
				}else{
					searchCoords = stringToPass.split(" ");
				}
			}else{
				searchCoords = stringToPass.split(",");	
			}		
			if(inputIsOK){
				if((isNaN(searchCoords[0])) || (isNaN(searchCoords[1]))){	
					showDialog('Warning','Coordinate not specifed correctly.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
					inputIsOK = false;
				}else{
					//Check if in map bounds
					if(document.varform.region.value == "gb"){
						if((Number(searchCoords[0]) < fullExtentGB[0]) || (Number(searchCoords[0]) > fullExtentGB[2])){
							inputIsOK = false;
							
							
						}else if((Number(searchCoords[1]) < fullExtentGB[1]) || (Number(searchCoords[1]) > fullExtentGB[3])){
							inputIsOK = false;
							
							
						//}else if((Number(searchCoords[0]) > fullExtentGB[2]) || (Number(searchCoords[1]) > fullExtentGB[2])){
						//	inputIsOK = false;
						//}else if((Number(searchCoords[0]) > fullExtentGB[3]) || (Number(searchCoords[1]) > fullExtentGB[3])){
						//	inputIsOK = false;
						}
						
					}else if(document.varform.region.value == "ni"){
						if((Number(searchCoords[0]) < fullExtentNI[0]) || (Number(searchCoords[0]) > fullExtentNI[2])){
							inputIsOK = false;
						}else if((Number(searchCoords[0]) < fullExtentNI[1]) || (Number(searchCoords[1]) > fullExtentNI[3])){
							inputIsOK = false;
						//}else if((Number(searchCoords[0]) > fullExtentNI[2]) || (Number(searchCoords[1]) > fullExtentNI[2])){
						//	inputIsOK = false;
						//}else if((Number(searchCoords[0]) > fullExtentNI[3]) || (Number(searchCoords[1]) > fullExtentNI[3])){
						//	inputIsOK = false;
						}
					}
					if(inputIsOK == false){
						showDialog('Warning','Coordinate not within the mapping extent.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
					}
				}					
			}
		}				
	}else if(stringToPass == ""){			//Postcode or town search
		showDialog('Warning','Please ensure search input is fully entered.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		inputIsOK = false;
	}
	//If input ok show search zoom options
	if(inputIsOK){
		//*******RUN THE SEARCH
		doSearch("road");		
	}
}
//************************Shows result of search as the main map location called from address search
function showLocation(theX,theY,fullAddress,addressRegion){
	canHideIt = true; 															//Can now hide toolbox on mouse over map
	if((addressRegion != document.varform.region.value) && ((theX != "0") && (theY != "0"))){
		if(addressRegion == "ni"){
			showDialog('Warning','Select the Northern Ireland mapping option.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		}else{		
			showDialog('Warning','Select the GB mapping option.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
		}	
	}else{
		if((theX == "0") && (theY == "0")){
			showDialog('Error','There has been a problem retrieving the selected location.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','errordialog');
		}else{
			//Fill GroundSure Address boxes with selected address
			fullAddress = fullAddress.replace(/&nbsp;/g, " ");			
			var test = String.fromCharCode(160);						//Space seems to be coded as ASC160 Now when returning from the Address search ???? (09/09) - ensure this is replaced with proper space ASC32
			fullAddress = fullAddress.replace(new RegExp( test, "gi" ), " ");					
			var theSpaces = new Array();
			var cnt=0;
			for(c=0;c<fullAddress.length;c++){
				testChar = fullAddress.substring(c,(c+1)); 
				if(testChar == ","){
					theSpaces[cnt] = c;
					cnt +=1;
				}
			}	
			var theAddressToWrite = fullAddress.substring(0,theSpaces[cnt-1]);
			var theNewAddressToWrite = theAddressToWrite.replace(/_quote_/g, "'");
			var thePCodeToWrite = fullAddress.substring((theSpaces[cnt-1]+1),fullAddress.length);								
			document.varform.gsaddress.value = theNewAddressToWrite;
			document.varform.gspostcode.value = thePCodeToWrite;		
			//Define how far to zoom in and the base mapping type	
			if(baseMappingToShow == "hybrid"){
				var theViewSize = 250;
			}else{
				var theViewSize = 500;
			}				
			//Zoom to location
			zoomToPoint(theX,theY,theViewSize,fullAddress);
			toogleSteps("Step2");												//Update step prompt			
			hideSearchMatches();												//Hide matches layer
			toolbox.slideOut();													//Hide location search info	
		}
	}
}
//************************Shows result of search as the main map location called from Postcode or town search
function showLocation2(theX,theY,srchtype,markerLabel){
	canHideIt = true; 															//Can now hide toolbox on mouse over map
	//Define how far to zoom in and the base mapping type
	if((srchtype == "pc") || (srchtype == "coord")){
		var theViewSize = 500;
	}else if(srchtype == "town"){
		var theViewSize = 2400;
	}
	if(baseMappingToShow == "hybrid"){
		var theViewSize = 250;
	}										
	zoomToPoint(theX,theY,theViewSize,markerLabel);
	toogleSteps("Step2");												//Update step prompt
	hideSearchMatches();												//Hide matches layer
	toolbox.slideOut();													//Hide location search info		
}
//************************Show the selected search option
function selectSearchType(theType){
	var allOptions = new Array("searchaddresslayer","searchpostcodelayer","searchplacenamelayer","searchcoordslayer");
	for(i=0; i < allOptions.length;i++){
		if (theType == allOptions[i]){
			var type = document.getElementById(allOptions[i]) 
			type.style.display = "block";
		}else{
		   var type = document.getElementById(allOptions[i]) 
			type.style.display = "none";
		}
	}
	hideSearchMatches();												//Hide matches layer
}
//************************Runs search to get centre location.
function doSearch(passedBaseMapping){
	//Store the base mapping to zoom to for the search result
	if(passedBaseMapping == "road"){											//If road the layer name will be either "gb" or "ni" depending on region
		passedBaseMapping = document.getElementById("region").value;
	}	
	baseMappingToShow = passedBaseMapping;	
	//hideSearchOptions();														//Hide options layer
	//Define the search being performed
	if(document.searchform.searchtype[0].checked){				
		theType = "addr";
	}else if(document.searchform.searchtype[1].checked){									
		theType = "pc";
		var stringToPass = document.searchform.searchPostcode.value;		
	}else if(document.searchform.searchtype[2].checked){				
		theType = "town";
		var stringToPass = document.searchform.searchPlacename.value;		
	}else if(document.searchform.searchtype[3].checked){
		theType = "coord";
		var stringToPass = document.searchform.searchCoords.value;
	}
		
	//if((theType == "addr") && (document.getElementById("qasBuilding").value == "")){			//Postcode only defined - we can just call the postcode search
	//	var stringToPass = document.getElementById("qasPostcode").value;
	//	theType = "pc";
	//}
		
	//Show progress message
	document.getElementById("searchProgress_"+theType).innerHTML = "<img src='images/loader.gif'>  Please wait";	
	//Define the action for each of the searches	
	if(theType == "coord"){															//**Run the coordinates search
		var isOK = true;						
		var sep = stringToPass.indexOf(",");
		if(sep == -1){
			var sep2 = stringToPass.indexOf(" ");
			if(sep2 == -1){
				showDialog('Warning','Coordinate not specifed correctly. Ensure the x-y cordinates are seperated by either a space or comma.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
				isOK = false;
			}else{
				searchCoords = stringToPass.split(" ");
			}
		}else{
			searchCoords = stringToPass.split(",");	
		}		
		if(isOK){
			document.getElementById("searchProgress_"+theType).innerHTML = "";
			if((isNaN(searchCoords[0])) || (isNaN(searchCoords[1]))){	
				showDialog('Warning','Coordinate not specifed correctly.<br/><br/><input type="button" value="Close" id="closeButton" onclick="hideDialog();" >','warning');
			}else{
				showLocation2(searchCoords[0],searchCoords[1],"coord","Coordinate: " + searchCoords[0] + "," + searchCoords[1]);
			}	
		}else{
			document.getElementById("searchProgress_"+theType).innerHTML = "";				
		}						
	}else if(theType == "addr"){													//**Run the full address search		
		searchLocationForQas();	
	}else{																			//**Post code/locations search	
		var qstring = "sstring=" + stringToPass + "&type=" + theType + "&adaccess=" + document.varform.isadmin.value + "&region=" + document.varform.region.value;
		var myReq = new ajaxObject('runSearch.php', handleSearchResponse);
		myReq.update(qstring,'POST');									
	}				
}
//****************Run QAS TYPE SEARCH 
function searchLocationForQas(){
	//Get the values
	var qasCountry = document.getElementById("qasCountry").value;
	var qasBuilding = document.getElementById("qasBuilding").value;
	var qasPostcode = document.getElementById("qasPostcode").value;
	var qasStreetName = document.getElementById("qasStreetName").value;
	var qasTown = document.getElementById("qasTown").value;
	var searchType = document.getElementById("addressSearchType").value;	
	var myReq = new ajaxObject('getSearch.php', searchResult);
	var sendString = 'qasCountry='+qasCountry+'&searchType='+searchType+'&qasBuilding='+qasBuilding+'&qasPostcode='+qasPostcode+'&qasStreetName='+qasStreetName+'&qasTown='+qasTown+'&rand='+Math.random;
	myReq.update(sendString,'POST');
}
function searchResult(responseText, responseStatus){
	if(responseStatus == 200){
		document.getElementById("searchProgress_addr").innerHTML = "";		
		//Check number of results returned
		var linkPos = -1;
		var linkCnt = 0;
		while(linkCnt < 2){
			linkPos = responseText.indexOf("showLocation", (linkPos+1));
			if(linkPos == -1){
				break;
			}else{
				linkCnt += 1;
				var funcStartPos = linkPos;
			}
		}			
		if(linkCnt == 1){												//Only one result - zoom to it
			var endPos = responseText.indexOf(")", funcStartPos);
			var toEval = responseText.substring(funcStartPos,(endPos+1));
			eval(toEval);								
		}else{															//Show matches
			document.getElementById("searchMatches").style.display = "block";
			document.getElementById("searchMatches").style.width = "400px";					
			document.getElementById("searchMatches").innerHTML =  responseText;
		}				
	}
}
//****************Shows/hide postcode and street name
function qasToggle(showDisp){
	if(showDisp == "pcd"){
		document.getElementById('qasdstrname').style.display = "none";
		document.getElementById('qasdpcode').style.display = "block";
		document.getElementById('addressSearchType').value = "pc";			
	}else if(showDisp == "stn"){
		document.getElementById('qasdpcode').style.display = "none";
		document.getElementById('qasdstrname').style.display = "block";
		document.getElementById('addressSearchType').value = "addr";
	}
}
//****************Handles the response from running the search (postcode and place)
function handleSearchResponse(responseText, responseStatus) {
	if(responseStatus == 200){   
		document.getElementById("searchProgress_"+theType).innerHTML = "";
		if(responseText != ""){																//Check data returned
			if(responseText.indexOf('|' != -1)) {					
				responseText = responseText.replace(/&nbsp;/g, " ");							//Replace nbsp with actual character
				var tempArray = new Array();
				tempArray = responseText.split('|');
				if(theType == "pc"){
					if(tempArray[1] == 1){												//1 result zoom to location						
						var tempArray2 = new Array();
						tempArray2 = tempArray[0].split(',');						
						showLocation2(tempArray2[0],tempArray2[1],"pc",tempArray2[2]);
					}else{																//Multiple results - show as list
						document.getElementById("searchMatches").style.display = "block";
						document.getElementById("searchMatches").style.width = "350px";
						document.getElementById("searchMatches").innerHTML = tempArray[0];						
					}	
				}else if(theType == "town"){
					if(tempArray[1] == 1){												//1 result zoom to location
						var tempArray2 = new Array();
						tempArray2 = tempArray[0].split(',');						
						showLocation2(tempArray2[0],tempArray2[1],"town",tempArray2[2]);
					}else{																//Multiple results - show as list
						document.getElementById("searchMatches").style.display = "block";
						document.getElementById("searchMatches").style.width = "350px";
						document.getElementById("searchMatches").innerHTML = tempArray[0];
					}
				}									
			}										
		}
	}
}
//******************Zoom to a point (called when zooming to search location)
function zoomToPoint(theX,theY,zoomWidth,theLabel){
	var blx = Number(theX) - (Number(zoomWidth)/2);
	var bly = Number(theY) - (Number(zoomWidth)/2);
	var urx = Number(theX) + (Number(zoomWidth)/2);
	var ury = Number(theY) + (Number(zoomWidth)/2);
	var bounds = new OpenLayers.Bounds(blx,bly,urx,ury);
	map.zoomToExtent(bounds);
	if(theLabel != ""){
		if(is_ie6){
			document.getElementById("searchOptionsContentIE6").style.display = "block";		//Show the choose mapping option
		}else{
			document.getElementById("searchOptionsContent").style.display = "block";		//Show the choose mapping option
		}
		addPinMarker(theX,theY,theLabel);				//Add marker location	
	}
	if(baseMappingToShow != "hybrid"){
		toggleMapLayers(baseMappingToShow);				//Show choosen base mapping
	}
}
//******************Hide the search options layer
function hideSearchOptions(){
	if(is_ie6){
		document.getElementById("searchOptionsContentIE6").style.display = "none";
	}else{
		document.getElementById("searchOptionsContent").style.display = "none";
	}
}
//******************Hide and clear the search matches layer
function hideSearchMatches(){
	document.getElementById("searchMatches").innerHTML = "";
	document.getElementById("searchMatches").style.display = "none";
}
//******************Add location as a marker
function addPinMarker(theX,theY,markerLabel){	
	//Destroy all other before adding
	destroyAllLocMarkers();
	//Create feature for the marker
	feature = new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(theX,theY),null);
	feature.attributes.id = markerLabel;	
	markerLayer.addFeatures(feature);						//Add to layer		
	//Add a select feature control for the marker layer and visible Fixed point layers
	var visibleLayers = new Array();
	var visLayCnt = -1;
	for(c=0; c < fixedCheckBoxes.length; c++){
		if(fixedLayerArray[c] != null){
			visLayCnt += 1;				
			visibleLayers[visLayCnt] = fixedLayerArray[c];
		}			
	}	
	visLayCnt += 1;
	visibleLayers[visLayCnt] = markerLayer;
	if(fixedLayer != null){
		visLayCnt += 1;
		visibleLayers[visLayCnt] = fixedLayer;										//Ensure the fixed product layer is still selectable
	}
	selFeatureControl = new OpenLayers.Control.SelectFeature(visibleLayers);  
 	map.addControl(selFeatureControl);
	selFeatureControl.activate();
	//Show the popup info of the locality
	showLocalityPopup(feature);		
}
//**************************Show popup - called after the marker is draen
function showLocalityPopup(feature) {	
	var popupContentHTML = "<h3>" + feature.attributes.id + "</h3><br/><ul><li><a href='javascript:destroyLocMarker(feature);'>Delete Marker</a></li></ul>";
    popup = new OpenLayers.Popup.FramedCloud("featurePopup",
                             feature.geometry.getBounds().getCenterLonLat(),
                             new OpenLayers.Size(100,100),
                             popupContentHTML,
                             null, true, onPopupClose);
    popup.autosize = true;
	popup.panMapIfOutOfView = false;
	feature.popup = popup;		
    popup.feature = feature;
    map.addPopup(popup);
	callCufon();		
}
//**************************Show popup on marker feature select
function onMarkerSelect(evt) {
    feature = evt.feature; 	
	var popupContentHTML = "<h3>" + feature.attributes.id + "</h3><br/><ul><li><a href='javascript:destroyLocMarker(null);'>Delete Marker</a></li></ul>";
    popup = new OpenLayers.Popup.FramedCloud("featurePopup",
                             feature.geometry.getBounds().getCenterLonLat(),
                             new OpenLayers.Size(100,100),
                             popupContentHTML,
                             null, true, onPopupClose);
    popup.autosize = true;
	popup.panMapIfOutOfView = false;
	feature.popup = popup;		
    popup.feature = feature;
    map.addPopup(popup);
	callCufon();		
}
//**************************Destroy popup on marker feature unselect
function onMarkerUnselect(evt) {
    feature = evt.feature;
    if (feature.popup) {
        popup.feature = null;
        map.removePopup(feature.popup);
        feature.popup.destroy();
        feature.popup = null;
    }
}
//******************Delete the locality marker
function destroyLocMarker(feature){
	if(feature == null){									//Get selected feature and delete it
		//Get the selected feature
		var theSelectedFeature = null;
		for(p=0; p < markerLayer.selectedFeatures.length;p++){
			theSelectedFeature = markerLayer.selectedFeatures[p];	
		}
		if(theSelectedFeature != null){
			 if (theSelectedFeature.popup) {
				popup.feature = null;
				map.removePopup(theSelectedFeature.popup);
				theSelectedFeature.popup.destroy();
				theSelectedFeature.popup = null;
			}
			markerLayer.removeFeatures(theSelectedFeature);
		}
	}else{													//Delete the opassed feature
		 if(feature.popup) {
				popup.feature = null;
				map.removePopup(feature.popup);
				feature.popup.destroy();
				feature.popup = null;
		}
		markerLayer.removeFeatures(feature);
	}	
}
//******************Delete the all locality markers
function destroyAllLocMarkers(){
	//Get the selected feature
	var theSelectedFeature = null;
	for(p=0; p < markerLayer.features.length;p++){
		theSelectedFeature = markerLayer.features[p];	
		if(theSelectedFeature != null){
			 if (theSelectedFeature.popup) {
				popup.feature = null;
				map.removePopup(theSelectedFeature.popup);
				theSelectedFeature.popup.destroy();
				theSelectedFeature.popup = null;
			}
			markerLayer.removeFeatures(theSelectedFeature);
		}
	}	
}

//-----------------------------------------------------End of file.
