
/**
 * Gmap v3 with some jquery
 * 
 * api key: ABQIAAAAmZi9-MY_O4gdJN30bog71xTmv4AvPefq4PL1JkEicOyBxE4nRRSEo6PuVcAToqDJELhxFWCDEEL_ww
 * 
 */
var gLocalSearch;
var gMap;
var gInfoWindow;
var gSelectedResults = [];
var gCurrentResults = [];
var gSearchForm;
var members = [
{
	"postal":"5600 Norheimsund",
	"address":"Gamle Dalavegen 90",
	"url":"http://www.botnen.no",
	"phone":"56553750",
	"lat": 60.369512,
	"lon": 6.133919
},
{
	"postal":"1776 Halden",
	"address":"Marcus Thranesgt 2a",
	"url":"http://www.byggevarer-as.no",
	"phone":"69184880",
	"lat": 59.12780,
	"lon":11.38230
},
{
	"postal":"3716 Skien",
	"address":"Alexander Kiellandsgt. 43",
	"url":"http://www.snekkern-skien.no",
	"phone":"35546433",
	"lat": 59.217761,
	"lon":9.606235
},
{
	"postal":"3050 Mjøndalen",
	"address":"Drammensveien 1",
	"url":"http://www.eiker-tre.no",
	"phone":"32876344",
	"lat": 59.74812,
	"lon":10.00797
}, 
{
	"postal":"1624 Gressvik",
	"address":"Gamle Ålevei 11",
	"url":"http://www.fjeldstad-bygg.no",
	"phone":"69354560",
	"lat": 59.23165,
	"lon":10.90417
},//59.23165, 10.90417
{
	"postal":"3157 Barkåker",
	"address":"Barkåkerveien 87",
	"url":"http://www.gulli.no",
	"phone":"33003280",
	"lat": 59.316199,
	"lon":10.378682
},
{
	"postal":"4636 Sørlandsparken",
	"address":"Buråsen 13",
	"url":"http://www.hansen-justnaes.no",
	"phone":"38144500",
	"lat": 58.171902,
	"lon":8.131566
},
{
	"postal":"4720 Hægeland",
	"address":"",
	"url":"http://www.haegeland-trevare.no",
	"phone":"38152490",
	"lat": 58.38519,
	"lon":7.74256
},
{
	"postal":"2004	Lillestrøm",
	"address":"Sørumsgt. 66",
	"url":"http://www.ojohansen.no",
	"phone":"63811161",
	"lat": 59.955862,
	"lon":11.069288
},
{
	"postal":"3615 Kongsberg",
	"address":"Bergmannsv. 403",
	"url":"http://www.snekkern-kongsberg.no",
	"phone":"32723020",
	"lat": 59.62485,
	"lon":9.605530
},
{
	"postal":"3770	Kragerø",
	"address":"Kammerfossveien 2",
	"url":"http://www.kgr.no",
	"phone":"35986530",
	"lat": 58.875735,
	"lon":9.365663
},
{
	"postal":"1870	Ørje",
	"address":"Industrivn. 6",
	"url":"http://www.lokentrevare.no",
	"phone":"69813500",
	"lat":59.473915,
	"lon": 11.664798
},
{
	"postal":"4810	Eydehavn",
	"address":"Handsverkstunet",
	"url":"http://www.snekkern-eydehavn.no",
	"phone":"37030077",
	"lat": 58.50396,
	"lon":8.84963
},
{ 
	"postal":"2321 Hamar",
	"address":"Midtstranda",
	"url":"http://www.snekkern-hamar.no/",
	"phone":"62 52 40 72",
	"lat": 60.79729,
	"lon": 11.110096
},

 { 
	"postal":"7350 Buvika",
	"address":"",
	"url":"http://www.ksolem.no",
	"phone":"72865112",
	"lat": 63.30874,
	"lon":10.1765
},
{
	"postal":"4900 Tvedestrand",
	"address":"Solfjellveien 1",
	"url":"http://www.solfjeld.no",
	"phone":"37162138",
	"lat": 58.62551,
	"lon":8.93638
},
{
	"postal":"2092 Minnesund",
	"address":"Røisiåsen 137",
	"url":"http://www.sollihogda.com",
	"phone":"63968005",
	"lat": 60.406435,
	"lon":11.249399
},
{
	"postal":"3570 Ål",
	"address":"Yliv. 8",
	"url":"http://www.strendo.no",
	"phone":"32081623",
	"lat": 60.649607,
	"lon":8.604484
},
{
	"postal":"2406 Elverum",
	"address":"Vindheiaveien 27",
	"url":"http://www.systemtre.no",
	"phone":"62410444",
	"lat": 60.87780,
	"lon": 11.54677
}, 
{
	"postal":"4640 Søgne",
	"address":"Linnegrøvan 14",
	"url":"http://www.sor-tre.no",
	"phone":"38053888",
	"lat": 58.09305,
	"lon": 7.81737
},
{
	"postal":"3262	Larvik",
	"address":"Elveveien 15",
	"url":"http://www.sorum-trevare.no",
	"phone":"33139090",
	"lat": 59.039848,
	"lon":10.049744
}
];

// Create our "tiny" marker icon
var gYellowIcon = new google.maps.MarkerImage(
	"http://labs.google.com/ridefinder/images/mm_20_yellow.png",
	new google.maps.Size(12, 20),
	new google.maps.Point(0, 0),
	new google.maps.Point(6, 20));
var gRedIcon = new google.maps.MarkerImage(
	"http://labs.google.com/ridefinder/images/mm_20_red.png",
	new google.maps.Size(12, 20),
	new google.maps.Point(0, 0),
	new google.maps.Point(6, 20));
var gSmallShadow = new google.maps.MarkerImage(
	"http://labs.google.com/ridefinder/images/mm_20_shadow.png",
	new google.maps.Size(22, 20),
	new google.maps.Point(0, 0),
	new google.maps.Point(6, 20));
 
// Set up the map and the local searcher.
function OnLoad() {

	// Initialize the map with default UI.
	gMap = new google.maps.Map(document.getElementById("map"), {
		center: new google.maps.LatLng(62.32228, 4.1414),
		zoom:5,
		mapTypeId: 'roadmap'
	});

	var infowindow = new google.maps.InfoWindow();
	var markerInit, i;
		
	for(var i in members)	{
		markerInit = new google.maps.Marker({
			position: new google.maps.LatLng(members[i].lat, members[i].lon),
			map: gMap
		});

		google.maps.event.addListener(markerInit, 'click', (function(markerInit, i) {
			return function() {
				windHtml = '<div style="font: normal 11px arial, sans-serif;">';
				windHtml += '<h3 style="font: bold 12px arial, sans-serif; margin:0;padding:0"><a href="'+members[i].url+'">'+members[i].url+'</a></h3>';
				windHtml += ''+members[i].address+' '+members[i].postal+'<br />';
				windHtml +='Tlf '+members[i].phone;
				windHtml += '</div>';
				infowindow.setContent(windHtml);
				infowindow.open(gMap, markerInit);
			}
		})(markerInit, i));
	}


	// Create one InfoWindow to open when a marker is clicked.
	gInfoWindow = new google.maps.InfoWindow;
	google.maps.event.addListener(gInfoWindow, 'closeclick', function() {
		unselectMarkers();
	});
 
	// Initialize the local searcher
	gLocalSearch = new GlocalSearch();
	gLocalSearch.setSearchCompleteCallback(null, OnLocalSearch);
}
 
function unselectMarkers() {
	for (var i = 0; i < gCurrentResults.length; i++) {
		gCurrentResults[i].unselect();
	}
}
 
// 
function doSearch(location) {

	var query = $("input#queryInput").val();
	
	//requestCompanies(query);
	
	// change zoom perspective on search
	gMap.setZoom(12);
	
	gLocalSearch.setCenterPoint(gMap.getCenter());
	gLocalSearch.execute(query);
}

function requestCompanies(query){
	var tmpAddresses  = [];
	$.ajax({
		type: 'get',
		url: 'extra/MemberCompanies.php',
		data: 'req=loc&location='+query,
		success: function(result){
			
			// temp result - should loop through markers
			tmp = result.split('#');
			tmpAddresses.push(tmp);
			alert(tmpAddresses.toString().replace(/,/g,"\n"));
		},
		error: function(){
			alert('Forespørsel feilet.');
		}
	});
}
 
// Called when Local Search results are returned, we clear the old
// results and load the new ones.
function OnLocalSearch() {
	if (!gLocalSearch.results) return;
	//var searchWell = document.getElementById("searchwell");
 
	// Clear the map and the old search well
	//searchWell.innerHTML = "";
	for (var i = 0; i < gCurrentResults.length; i++) {
		gCurrentResults[i].marker().setMap(null);
	}
	// Close the infowindow
	gInfoWindow.close();
 
	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);
	}
 
	// Move the map to the first result
	var first = gLocalSearch.results[0];
	gMap.setCenter(new google.maps.LatLng(parseFloat(first.lat),
		parseFloat(first.lng)));

 
}
 
// Cancel the form submission, executing an AJAX Search API search.
function CaptureForm(searchForm) {
	gLocalSearch.execute(searchForm.input.value);
	return false;
}
 
 
 
// A class representing a single Local Search result returned by the
// Google AJAX Search API.
function LocalResult(result) {
	var me = this;
	me.result_ = result;
	me.resultNode_ = me.node();
	me.marker_ = me.marker();
	google.maps.event.addDomListener(me.resultNode_, 'mouseover', function() {
		// Highlight the marker and result icon when the result is
		// mouseovered.  Do not remove any other highlighting at this time.
		me.highlight(true);
	});
	google.maps.event.addDomListener(me.resultNode_, 'mouseout', function() {
		// Remove highlighting unless this marker is selected (the info
		// window is open).
		if (!me.selected_) me.highlight(false);
	});
	google.maps.event.addDomListener(me.resultNode_, 'click', function() {
		me.select();
	});
//document.getElementById("searchwell").appendChild(me.resultNode_);
}
 
LocalResult.prototype.node = function() {
	if (this.resultNode_) return this.resultNode_;
	return this.html();
};
 
// Returns the GMap marker for this result, creating it with the given
// icon if it has not already been created.
LocalResult.prototype.marker = function() {
	var me = this;
	if (me.marker_) return me.marker_;
	var marker = me.marker_ = new google.maps.Marker({
		position: new google.maps.LatLng(parseFloat(me.result_.lat),
			parseFloat(me.result_.lng)),
		icon: gYellowIcon, 
		shadow: gSmallShadow, 
		map: gMap
	});
	google.maps.event.addListener(marker, "click", function() {
		me.select();
	});
	return marker;
};
 
// Unselect any selected markers and then highlight this result and
// display the info window on it.
LocalResult.prototype.select = function() {
	unselectMarkers();
	this.selected_ = true;
	this.highlight(true);
	gInfoWindow.setContent(this.html(true));
	gInfoWindow.open(gMap, this.marker());
};
 
LocalResult.prototype.isSelected = function() {
	return this.selected_;
};
 
// Remove any highlighting on this result.
LocalResult.prototype.unselect = function() {
	this.selected_ = false;
	this.highlight(false);
};
 
// Returns the HTML we display for a result before it has been "saved"
LocalResult.prototype.html = function() {
	var me = this;
	var container = document.createElement("div");
	container.className = "unselected";
	container.appendChild(me.result_.html.cloneNode(true));
	return container;
}
 
LocalResult.prototype.highlight = function(highlight) {
	this.marker().setOptions({
		icon: highlight ? gRedIcon : gYellowIcon
	});
	this.node().className = "unselected" + (highlight ? " red" : "");
}
 
GSearch.setOnLoadCallback(OnLoad);


$(function(){

	$('body').append('<style>	.ui-autocomplete-loading { background: white url(images/ui-anim_basic_16x16.gif) right center no-repeat; }</style>');
	
	var tmpArr = [];
	for(var i in members)	{
		tmpArr.push(members[i].postal);
	}

	$( "#queryInput" ).autocomplete({
		source: tmpArr,
		select: function(event, ui){
			
			// temp - should use chords instead
			for(var i in members)	{
				if(members[i].postal == $(this).val() ){
					doSearch(members[i].address+", "+members[i].postal);
				//alert(members[i].address+", "+$(this).val());
				}
			}
		}	
	});
});

