﻿//<![CDATA[
    
    // Global variables
    var map,icon1,marker;
    
    // two variables to hold the lat and lng of the currently selected pub
    var currentLat, currentLng;
    currentLat = 999; currentLng = 999; // define 'null' values
    
    // two variables to hold the lat and lng of where the user is now (or claims to be)
    var userLat, userLng;
    userLat = 999; userLng = 999;
    
    function CaptureForm(searchForm) {
      gLocalSearch.execute(searchForm.input.value);
      return false;
    }
    
    LocalResult.prototype.unselectedHtml = function() {
      var container = document.createElement("div");
      container.className = "unselected";
      container.appendChild(this.result_.html.cloneNode(true));
      var saveDiv = document.createElement("div");
      saveDiv.className = "select";
      saveDiv.innerHTML = "Save this location";
      GEvent.bindDom(saveDiv, "click", this, function() {
        gMap.closeInfoWindow();
        this.select();
        gSelectedResults.push(this);
      });
      container.appendChild(saveDiv);
      return container;
    }
	
	function OnLocalSearch() {
      if (!gLocalSearch.results) return;
      var searchWell = document.getElementById("panel");

      searchWell.innerHTML = "";
      dirs.clear()

      gCurrentResults = [];
      for (var i = 0; i < gLocalSearch.results.length; i++) {
        gCurrentResults.push(new LocalResult(gLocalSearch.results[i]));
      }

      var attribution = gLocalSearch.getAttribution();
      if (attribution) {
        document.getElementById("searchwell").appendChild(attribution);
      }

      var first = gLocalSearch.results[0];
		theLat = parseFloat(first.lat)
		theLng = parseFloat(first.lng)
		userLat = theLat; userLng = theLng;
		fromStr = theLat + "," + theLng
		if (currentLat != 999) {
		    getDirections(fromStr)
		}
		// map.recenterOrPanToLatLng(new GPoint(parseFloat(first.lng), parseFloat(first.lat)));
    }
	
	function LocalResult(result) {
      this.result_ = result;
      this.resultNode_ = this.unselectedHtml();
      document.getElementById("panel").appendChild(this.resultNode_);
      // map.addOverlay(marker);
    }
    
    function load() {
      if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map"));
        dirs = new GDirections(map, document.getElementById("panel"))
		
		gSearchForm = new google.search.SearchForm(false, document.getElementById("searchform"));
      	gSearchForm.setOnSubmitCallback(null, CaptureForm);
      	// gSearchForm.input.focus();
		
		// Initialize the local searcher
      gLocalSearch = new google.search.LocalSearch();
      gLocalSearch.setCenterPoint(map);
      gLocalSearch.setSearchCompleteCallback(null, OnLocalSearch);
        map.addControl(new GLargeMapControl());
      	 map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(53.33, -2.15),6);
        initialiseIcons();
        
        // initialise geocoder
        geocoder = new GClientGeocoder();
        
      }
    }
    
    function makePin(pID, pLat,pLng,pName,pTown,pPostCode,pPhone) {
		// Strip the actual conditions out
		
		var thisIcon
		thisIcon = icon1;
		// document.getElementById("list").innerHTML += "<br>" + pName;
				
		point = new GLatLng(parseFloat(pLat),parseFloat(pLng))
		var thisMarker = new GMarker(point,thisIcon)
		GEvent.addListener(thisMarker,"click",function() {
		    document.getElementById("selectedPub").innerHTML = "";
			var html = "<div class='bubble'><b>" + pName + "</b><br>" + pTown + "<br>" + pPostCode + "<br>" + pPhone + "<br>";
			html += "<a href=\"members/add_comment.aspx?id=" + pID + "\">Click to add your comments</a><br>";
			html += "<a href=\"javascript:getComments(" + pID + ")\">View comments</a></div>";
			currentLat = pLat;
			currentLng = pLng;
			thisMarker.openInfoWindowHtml(html);
			
		});
		// alert(pName)
		map.addOverlay(thisMarker)
		
	}
    
    
    
    function initialiseIcons() {
 // create a new base icon
	  var baseIcon = new GIcon();
	  baseIcon.image = "images/gbg.png";
	  //baseIcon.shadow = "images/shad.png";
      baseIcon.iconSize = new GSize(22, 22);
	  baseIcon.shadowSize = new GSize(24, 22);
	  baseIcon.iconAnchor = new GPoint(11,11);
	  baseIcon.infoWindowAnchor = new GPoint(15,12);
	  icon1 = baseIcon;
	  
	}  
	  
	  function getDirections(startPoint) {
		
		qStr = "from: " + startPoint + " to: " + currentLat + "," + currentLng
		dirs.clear()
		document.getElementById("panel").innerHTML = ""
		dirs.load(qStr)
		//document.getElementById("printgoogledirections").style.display = 'block'
		//document.getElementById("printmaindirections").style.display = 'none'

	}
	  
	  
	    function getPubData(pName,pTown,pPostCode) {
	        criteria = pName + pTown + pPostCode;
	        if (criteria.length < 2) {
	            alert("Please enter a slightly more specific search than that!");
	            document.getElementById('waiting').innerHTML = "Try again!";
	            
	        } else {
		        map.clearOverlays();
		        document.getElementById("panel").innerHTML = "";
		        url = "getpubdata.aspx"
		        url += "?pname=" + pName + "&ptown=" + pTown + "&ppostcode=" + pPostCode;
		        url += "&cachebuster=" + Math.random()
		        // branch for native XMLHttpRequest object
		        if (window.XMLHttpRequest) {
			        req = new XMLHttpRequest();
			        req.onreadystatechange = processReqChange;
			        req.open("GET", url, true);
			        req.send(null);
		        // branch for IE/Windows ActiveX version
		        } else if (window.ActiveXObject) {
			        isIE = true;
			        req = new ActiveXObject("Microsoft.XMLHTTP");
			        if (req) {
				        req.onreadystatechange = processReqChange;
				        req.open("GET", url, true);
				        req.send();
			        }
		        }
    	    }
    	
	    }
	    
	    function getPubsByDistance(pLoc,pDist) {
	    
	    
	    
	    }
	    
	    function showAddress(address) {
          if (geocoder) {
            geocoder.getLatLng(
              address,
              function(point) {
                if (!point) {
                  alert(address + " not found");
                } else {
                  alert(point.lat() + " - " + point.lng());
                }
              }
            );
          }
        }
	  
	  
	  function processReqChange() 
		{
		    
		    if (req.readyState == 4) {
		        // only if "OK"
		        if (req.status == 200) {
		            // ...processing statements go here...
					// create the XML object
					external_xml = req.responseXML
					items = external_xml.getElementsByTagName("datum")
					document.getElementById('waiting').innerHTML = items.length + " results found";
					document.getElementById("selectedPub").innerHTML = "";
					if (items.length > 0) {
					document.getElementById("instructions").style.display = "block";
			        document.getElementById("searchform").style.display = "block";
			        } else {
					document.getElementById("instructions").style.display = "none";
			        document.getElementById("searchform").style.display = "none";
			        }
					for (f=0; f<items.length; f++) {
					    pubID = getElementTextNS("", "pubID", items[f], 0);
						PubName = getElementTextNS("", "pubName", items[f], 0);
						PubTown = getElementTextNS("", "pubTown", items[f], 0);
						PubPostCode = getElementTextNS("", "pubPostCode", items[f], 0);
						PubPhone = getElementTextNS("", "pubPhone", items[f], 0);
						
						theLat = getElementTextNS("", "pubLat", items[f], 0);
						theLng = getElementTextNS("", "pubLng", items[f], 0);
						makePin(pubID,theLat,theLng,PubName,PubTown,PubPostCode,PubPhone);
					}
		        } else {
					// Error.  Fail gracefully and give the user a useful error message.
					alert("Bugger.  Something fucked up.")      ;
		        }
		    } 
		    
		}
		
		function getComments(pID) {
	        url = "getPuBComments.aspx"
	        url += "?id=" + pID;
	        url += "&cachebuster=" + Math.random()
	        // branch for native XMLHttpRequest object
	        if (window.XMLHttpRequest) {
		        req = new XMLHttpRequest();
		        req.onreadystatechange = processNewsReqChange;
		        req.open("GET", url, true);
		        req.send(null);
	        // branch for IE/Windows ActiveX version
	        } else if (window.ActiveXObject) {
		        isIE = true;
		        req = new ActiveXObject("Microsoft.XMLHTTP");
		        if (req) {
			        req.onreadystatechange = processNewsReqChange;
			        req.open("GET", url, true);
			        req.send();
		        }
	        }
	    }
	    
	    function processNewsReqChange() 
		{
		    
		    if (req.readyState == 4) {
		        // only if "OK"
		        if (req.status == 200) {
		            // ...processing statements go here...
					// create the XML object
					external_xml = req.responseXML
					items = external_xml.getElementsByTagName("datum");
					document.getElementById("selectedPub").innerHTML = "";
					commentTableHTML = "<table cellpadding=\"2\" cellspacing=\"0\" style=\"margin=top: 10px;\">";
					commentTableHTML += "<tr><th>Poster / Date</th><th style=\"padding-left: 15px;\">Comment</th></tr>";
					numberOfComments = items.length;
					if (items.length > 10) { numberOfComments = 10 }
					for (f=0; f<numberOfComments; f++) {
					   
					    commentID = getElementTextNS("", "commentID", items[f], 0);
						comment = getElementTextNS("", "comment", items[f], 0);
						commentUser = getElementTextNS("", "commentUser", items[f], 0);
						commentDate = getElementTextNS("", "commentDate", items[f], 0);
						commentTableHTML += "<tr>";
						commentTableHTML += "<td style=\"border-bottom:1px solid #fff; width:25%;\">" + commentUser + "<br>" + commentDate + "</td>";
						commentTableHTML += "<td style=\"border-bottom:1px solid #fff; width:75%;\"><div style=\"margin-left: 15px;\">" + comment.replace("\n","<br />").replace("\r","<br />") + "</div></td>";
						commentTableHTML += "</tr>";
					}
					commentTableHTML += "</table>";
					if (items.length > 10) { commentTableHTML += "<br><a href=\"allComments.aspx?id=" + pID + "\">See all comments</a>" };
					document.getElementById("selectedPub").innerHTML = commentTableHTML;
		        } else {
					// Error.  Fail gracefully and give the user a useful error message.
					alert("Bugger.  Something fucked up.")      ;
		        }
		    } 
		    
		}
		
//////////////////////////////////////////////////////////////////////////////////////////////////////////		
		// retrieve text of an XML document element, including
// elements using namespaces
function getElementTextNS(prefix, local, parentElem, index) {
	var result = "";
	if (prefix && isIE) {
		// IE/Windows way of handling namespaces
		result = parentElem.getElementsByTagName(prefix + ":" + local)[index];
	} else {
		// the namespace versions of this method
		// (getElementsByTagNameNS()) operate
		// differently in Safari and Mozilla, but both
		// return value with just local name, provided
		// there aren't conflicts with non-namespace element names
		result = parentElem.getElementsByTagName(local)[index];
	}
	if (result) {
		// get text, accounting for possible
		// whitespace (carriage return) text nodes
		if (result.childNodes.length > 1) {
			return result.childNodes[1].nodeValue;
		} else {
			return result.firstChild.nodeValue;
		}
	} else {
		// return "n/a";
		return "";
	}
}
    //]]>