// basic variables
var mpstatus = false;
var map = null;
var maplocs = [];
var maploca = [];
var linktext = '';
var mainIcon = null;
var greyIcon = null;
var bounds = null;
var lastlink = "";
var order =100;
var gmaplink = '';

$(document).ready(function(){
	// input fields default values cleared on click
	$("input#email").each(function(){
		$(this).click(function(){
			$(this).attr("value","");
		});
	});
	
	//initMap();
	
});
function googleReady() {
	google.load("maps", "2", {"callback" : initMap});
}

function initMap(){
	getLocations();
	var iphone = false;
	if(navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i)){
    // some code
    	iphone = true;
	}

	// if we have javascript make link
	// but first check if we have anything to show
	if (maplocs.length > 0) {
		$("div#maphook").each(function(){
			// here we need to fork for the iphone
			if (iphone) {
				//var href = "maps:q="+$(this).attr("rel");
				//$(this).find('a').href(href);
				//$(this).find('span').html('View this on Google maps');
				$(this).after("<a href='maps:q="+$(this).attr("rel")+"' class='listmap' id='lmaplink'><span style='font-size:12px;'><font size='2'>View this on Google maps</font></span></a>");
				$(this).remove();
		
			} else {
				linktext = $(this).html();
				if($(this).attr("rel")){
					gmaplink = "<a id='gmaplink' href='http://maps.google.com/maps?q="+$(this).attr("rel")+"' class='listmap' target='_blank'><span style='font-size:12px;'>View this on Google Maps</span></a>";
				}
				//console.log(gmaplink);
				$(this).after("<a href='#' class='listmap' id='lmaplink'><span>"+linktext+"</span></a>");
				$(this).remove();
				// assign action
				makeMapLink();	
			}

		});
	}
}


function makeMapLink() {
	$("a#lmaplink").unbind();
	$("a#lmaplink").click(function(me){
		if(mpstatus) {
			removeMap();
		} else {
			mpstatus = true;
			makeMap(linktext);
		}
		return false;
	});
}

function removeMap() {

	$("div#maphd").slideUp();
	$("div#gmap").remove();
	$("div#maphd").remove();
	$("a#gmaplink").remove();
	map = null;
	$("a#lmaplink").html('<span style="font-size:12px;">'+lastlink+'</span>');
	mpstatus = false;
	window.setTimeout(function(){
			makeMapLink();
		},200);
}
function locObj(lng,lat,html,en,marker,links,ids) {
	this.lng = lng;
	this.lat = lat;
	this.html = html;
	this.en = en;
	this.marker = marker;
	this.links = links;
	this.ids = ids;
	//console.log('creating object'+this.links[0]);
	return this;
}
function getLocations() {
	var c = -1;
	$("div.vevent").add("div.location").add("div.nearvenue").each(function(i){
		c++;
		// getting location data
		var lng = '';
		var lat = '';
		var html = '';
		var en = '';
		var el = '';
		var eloc = '';
		var elocl = '';
		var marker = '';
		var links = [];
		var ids = [];
		var mtype = true;
		$(this).find("span.greym").each(function(){
			mtype = false;
		});
		$(this).find("abbr.geo").each(function(){
			// lat and long
			var loc = this.getAttribute("title").split(";");
			lng = loc[0];
			lat = loc[1];
		});
		$(this).find("span.geo").each(function(){
			// lat and long
			var loc = this.getAttribute("title").split(";");
			lng = loc[0];
			lat = loc[1];
		});
		$(this).find("a.url").each(function(){
			//event and event link
			en = this.childNodes[0].nodeValue;
			el = this.getAttribute("href");
			//links.push(en);
			$(this).attr('id','a'+c);
		});
		$(this).find("span.org").find("a").each(function(){
			// venue and venue link
			eloc = this.childNodes[0].nodeValue;
			elocl = this.getAttribute('href');
			$(this).attr('id','a'+c);
			//links.push(eloc);
		});
		// here we need to check if we are on a venue detail page and if we are then
		// we need to get the information from the h1 tag and not from the a tag
		// is it possible to use div.detail as hook?
		if (eloc == '') {
			$(this).find("a").each(function(){
				$(this).attr('id','a'+c);
				if (this.childNodes[0] != null) {
					
					eloc = this.childNodes[0].nodeValue;
					
					elocl = this.getAttribute('href');
					//console.log(elocl);
				} else {
					if (en == '') {
						eloc = $("div.vevent").find('h1').html();
					}
				}
			});
			if (eloc == '') {
				eloc = $("div.vevent").find('h1').html();
			}
		}
		if (en != '') {
			html = "<div style='width:200px;line-height:1.5em;margin:0px 0px 5px 0px;'><h4 style='margin-left:0px;font-size:1.2em;'><a href='"+el+"'>"+en+"</a></h4><p><a href='"+elocl+"' style='color:#838383;'>"+eloc+"</a></p></div>";
		} else if (eloc != '') {
			html = "<div style='width:200px;line-height:1.5em;margin:0px 0px 5px 0px;'><h4 style='margin-left:0px;font-size:1.2em;'><a href='"+elocl+"'>"+eloc+"</a></h4></div>";
		} else {
			html = 'test';
		}
		
		links.push(eloc);
		ids.push('a'+c);
		
		if (GBrowserIsCompatible() && html != '' && lat != '' && lng != '' && lat != 0) {
			if (mainIcon == null) {
				mainIcon = new GIcon(G_DEFAULT_ICON, "/layout/img/marker_green.png");
				greyIcon = new GIcon(G_DEFAULT_ICON, "/layout/img/main_markerm.png");
			}
			var point = new GLatLng(lat,lng);
			marker = createMarker(point,en,html,mtype);
			maplocs[maplocs.length] = new locObj(lng,lat,html,en,marker,links,ids);
		}
	});
	
	checkForDouble();
}

function checkForDouble(){
	// precision
	var pc = 1000;
	for(i=0;i<maplocs.length;i++){
		var sameLocation = [];
		for(var j=0;j<maplocs.length-i;j++){
			//get out the matching pairs
			if(Math.round(maplocs[i].lng*pc) == Math.round(maplocs[j].lng*pc) && Math.round(maplocs[i].lat*pc) == Math.round(maplocs[j].lat*pc) && i != j){
			
				sameLocation[sameLocation.length] = j;
				
			}
		}
		// check length of sameLocation if > 0
			// i is receiving object
			// loop though matches
			// move info and remove match from orignal array
		
		if(sameLocation.length > 0){
			var parentLoc = maplocs[i];
			for ( var n=0;n<sameLocation.length;n++){
				parentLoc.html += maplocs[parseInt(sameLocation[n]-n)].html;
				parentLoc.links.push(maplocs[parseInt(sameLocation[n]-n)].links[0]);
				parentLoc.ids.push(maplocs[parseInt(sameLocation[n]-n)].ids[0]);
				maplocs.splice(parseInt(sameLocation[n]-n),1);
				//console.log(parentLoc.ids);
			}
		}
	}
	

	assignActions();
	
}

function assignActions(){
	for(var i=0;i<maplocs.length;i++){
		
		for(var j=0;j<maplocs[i].ids.length;j++){
			//console.log(maplocs[i].ids[j]);
			$('body').find("a#"+maplocs[i].ids[j]).each(function(){
				//console.log('-- '+maplocs[i].ids[j]);
				var loc = maplocs[i];
				$(this).hover(function(){
					if(map != null) {
						map.panTo(new GLatLng(loc.lat,loc.lng));
						window.setTimeout(function() {
							loc.marker.openInfoWindowHtml(loc.html);
						}, 1000);
					}
				},function(){});
				
				addOverState(loc);
				
			});
		}
	}
}


function addOverState(loc){

	GEvent.addListener(loc.marker, "click", function() {
		if (map!=null) {
			loc.marker.openInfoWindowHtml(loc.html);
		}
	});

}

function makeMap(lt) {
		
		//console.log('making map')
		mpstatus = true;
		$("div#gmap").remove();
		$("div#maphd").remove();
		var mapwidth = $("a#lmaplink").width();
		
		$("a#lmaplink").after("<div id='maphd' style='clear:both;margin:0;height:300px;width:"+mapwidth+"px;'></div>");
		$("div#maphd").hide();
		$("div#maphd").load(("/content.php?page_id=20"),function(){
			$("div#maphd").slideDown('slow',function(){
				$("a#lmaplink").html('<span>Click here to hide this map</span>');
				if(gmaplink){
					$("a#lmaplink").after(gmaplink);
				}
				if (GBrowserIsCompatible()) {
					var mapDIV = document.getElementById("gmap");

					map = new GMap(mapDIV);
					map.addControl(new GSmallMapControl());
					map.setCenter(new GLatLng(0,0),0);
					bounds = new GLatLngBounds();

					for(i=0;i<maplocs.length;i++){
						
						var temp = maplocs[i];
						drawMarker(temp);
					}
					// ===== determine the zoom level from the bounds =====
					map.setZoom(map.getBoundsZoomLevel(bounds));
					// ===== determine the centre from the bounds ======
					var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
					var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
					map.setCenter(new GLatLng(clat,clng));			
				}
			});
		});
		//assignActions();
		lastlink = lt;
	}

function drawMarker(temp) {
	if (temp.lat != '' && temp.lng != '' && temp.lat !=0 && temp.lng != 0) {
		var point = new GLatLng(temp.lat,temp.lng);
		var marker = temp.marker;
		map.addOverlay(marker);
		bounds.extend(point);
	}
}

function createMarker(point,name,html,mtype) {
	if (mtype) {
		var marker = new GMarker(point, {title:name, icon: mainIcon, zIndexProcess:importanceOrder});
	} else {
		var marker = new GMarker(point, {title:name, icon: greyIcon, zIndexProcess:importanceOrder});
	}
	order--;
	marker.importance = order;
	return marker;
}

function importanceOrder (marker,b) {
	return GOverlay.getZIndex(marker.getPoint().lat()) + marker.importance*1000000;
}

