var map, bounds, aVenues, iVenueID, point, srch, marker, oldzindex, id, databounds;
var markers = [];
var lock = false;
var first_run = true;
var yPos = 0;
var xPos = 0;
var LngSpan = 0;
var LatSpan = 0;
var iteratorVenue = 0;
var temp = '';
var venuesvisible = 10;
var sBaseURL = "http://floosh.com";
var existingMarkers = new Hash2();
var alphabet = new Array();
alphabet[0] = "A";
alphabet[1] = "B";
alphabet[2] = "C";
alphabet[3] = "D";
alphabet[4] = "E";
alphabet[5] = "F";
alphabet[6] = "G";
alphabet[7] = "H";
alphabet[8] = "I";
alphabet[9] = "J";
alphabet[10] = "K";
alphabet[11] = "L";
alphabet[12] = "M";
alphabet[13] = "N";
alphabet[14] = "O";
alphabet[15] = "P";
alphabet[16] = "Q";

var icon = new GIcon();
icon.shadow = sBaseURL+"/img/pins/shadow.png";
icon.iconSize = new GSize(24, 34);
icon.shadowSize = new GSize(49, 38);
icon.iconAnchor = new GPoint(12, 32);
icon.infoWindowAnchor = new GPoint(5, 1);
icon.transparent = sBaseURL+"/img/pintrans.png";
icon.imageMap = [15,34, 10,34, 4,26, 0,16, 0,6, 6,0, 17,0, 24,6, 24,18]

/*currently not used.  Provides AJAX History and Bookmark support*/
function load_history(){
	dhtmlHistory.initialize();
	//dhtmlHistory.addListener(historyChange);

	var location = document.URL;
	location = location.substr(location.indexOf("#"),location.length);
	if(location.match("map")){
		lat = location.substr(location.indexOf(":")+1,location.indexOf("_")-(location.indexOf(":")+1));
		location = location.substr(location.indexOf("_")+1,location.length);
		lng = location.substr(0,location.indexOf("_"));
		zoom = location.substr(location.indexOf("_")+1,location.length);
		map.setCenter(new GLatLng(lat, lng), zoom);
		first_run = true;
		loadData();
	}
	if(location.match("venue")){
		iVenueID = location.substr(location.indexOf(":")+1,location.length);
		ModalWindow(sBaseURL+'/venues/ajax_view_venue/'+iVenueID,'divVenue');
	}
	
	if (dhtmlHistory.isFirstLoad()) {
		var center = map.getCenter();
		lat = center.lat();
		lng = center.lng();
		tmp = 'map.setCenter(new GLatLng('+lat+', '+lng+'), '+map.getZoom()+'); CloseModalWindow()';
		//dhtmlHistory.add('map:'+Math.round(lat*1000)/1000+'_'+Math.round(lng*1000)/1000+'_'+map.getZoom(),tmp);
	}
}

/*currently not used.  Provides AJAX History and Bookmark support*/
function historyChange(newLocation, historyData) {
	try{
		eval(historyData);
	}catch(e){
		alert('oops');
	}
}

/*loads the google map*/
function loadMap(){
	if (GBrowserIsCompatible()) {
		map = new GMap2($('divMap'));
		map.addControl(new GLargeMapControl());
		map.setCenter(new GLatLng(lat, lng), zoom);
		map.enableDoubleClickZoom();
		map.enableContinuousZoom();
		map.enableScrollWheelZoom();
	}	
}

/*initial page load function  calls loadmap and loaddata*/
function loads() {
	loadMap();
	loadData();
}

/*loads external javascript if not already loaded and executes one of the functions*/
function userscripts(callback){
	try{
		eval(callback);
	}catch(e){
		temp = callback;
		var headID = document.getElementsByTagName("head")[0];         
		var newScript = document.createElement('script');
		newScript.type = 'text/javascript';
		newScript.src = sBaseURL+'/js/user.js';
		headID.appendChild(newScript);
	}
}

/*callback for external javascript functions*/
function loaded(){
	eval(temp);	
}

/*true if empy false otherwise*/
function IsEmpty(aTextField) {
	try{
		if ((aTextField.length==0) || (aTextField==null)) {
			return true;
		}
		else { return false; }
	}catch(e){ return true; }
}

function loadData(){
	databounds = map.getBounds();
	var southWest = databounds.getSouthWest();
	var northEast = databounds.getNorthEast();

	LngSpan = northEast.lng() - southWest.lng();
	LatSpan = northEast.lat() - southWest.lat();
	if(map.getZoom() < 13){
		var NewN = northEast.lng()+(LngSpan*0.5);
		var NewE = northEast.lat()+(LatSpan*0.5);
		var NewS = southWest.lng()-(LngSpan*0.5);
		var NewW = southWest.lat()-(LatSpan*0.5);		
	}else{
		var NewN = northEast.lng()+(LngSpan*1.6);
		var NewE = northEast.lat()+(LatSpan*1.6);
		var NewS = southWest.lng()-(LngSpan*1.6);
		var NewW = southWest.lat()-(LatSpan*1.6);
	}
	if(!lock){
		lock = true;
		if(IsEmpty(srch)){
			var url = sBaseURL+'/venues/ajax_data3/'+NewN+'/'+NewE+'/'+NewS+'/'+NewW;
			var myAjax = new Ajax.Request(
				url, 
				{
					method: 'get',
					onComplete: function(originalRequest) {
						eval(originalRequest.responseText);
						aVenues = temp;
						if(first_run){
							//load_history();
							GEvent.addListener(map, 'moveend', function() {Move()});
							Move();
							Element.hide('lightbox');
							Element.hide('overlay');
							first_run = false;
						}
						lock = false;
					}
				}
			);
		}else{
			var url = sBaseURL+'/venues/ajax_search/'+NewN+'/'+NewE+'/'+NewS+'/'+NewW+'/'+srch;
			var myAjax = new Ajax.Request(
				url, 
				{
					method: 'get',
					onComplete: function(originalRequest) {
						eval(originalRequest.responseText);
						aVenues = temp;
						Element.hide('lightbox');
						Element.hide('overlay');
						ShowVenues();
						lock = false;
					}
				}
			);
		}
	}
}

/*everytime the map is moved (or zoomed) determine if we need to load new data and call showvenues*/
function Move() {
	var center = map.getCenter();
	lat = center.lat();
	lng = center.lng();
	point = new GLatLng(lat,lng);
	if((databounds.contains(point) != true)&&(map.getZoom() <= zoom)){
		loadData();
		iteratorVenue = 0;
		var center = map.getCenter();
		lat = center.lat();
		lng = center.lng();
	}
	iteratorVenue = 0;
	zoom = map.getZoom();
	//tmp = 'map.setCenter(new GLatLng('+lat+', '+lng+'), '+map.getZoom()+'); CloseModalWindow()';
	//dhtmlHistory.add('map:'+Math.round(lat*1000)/1000+'_'+Math.round(lng*1000)/1000+'_'+map.getZoom(),tmp);
	ShowVenues();
}

function CreateVenue(iVenueID, nLong, nLat, iRating, visible) {
	point = new GPoint(nLong,nLat);
	marker = new GMarker(point, icon);

	marker.id = iVenueID;
	GEvent.addListener(marker, 'click', function() { 
		ModalWindow(sBaseURL+'/venues/ajax_view_venue/'+iVenueID,'divVenue');
		//dhtmlHistory.add('venue:'+iVenueID, 'ModalWindow(\''+sBaseURL+'/venues/ajax_view_venue/'+iVenueID+'\',\'divVenue\')')
		id = iVenueID;
	});
	
	GEvent.addListener(marker, 'mouseover', function() {
		$(''+iVenueID+'').className = 'bold';
	});
	
	GEvent.addListener(marker, 'mouseout', function() {
		$(''+iVenueID+'').className = 'empty';
	});

	map.addOverlay(marker);
	return marker;
}

/*usefull little function*/
function zindex(src,index){
	var x = document.body.getElementsByTagName('img');
	for(y=0;y<x.length;y++){
		if(x[y].src == src){
			temp = x[y].src
			oldzindex = x[y].style.zIndex;
			x[y].style.zIndex = index;
			if(temp.search("_grey2.png") != -1){
				x[y].style.width = "24px";
				x[y].style.height = "34px";
				x[y].src = temp.replace("_grey2.png","_grey.png");
				try{
					temp = x[y].style.left;
					temp = temp.replace("px","");
					temp = parseInt(temp) + parseInt(8);
					temp = temp+'px';
					x[y].style.left = temp;
				}catch(e){
					
				}
				
				try{
					temp = x[y].style.top;
					temp = temp.replace("px","");
					temp = parseInt(temp) + parseInt(18);
					temp = temp+'px';
					x[y].style.top = temp;
				}catch(e){
					
				}
			}else{
				x[y].style.width = "62px";
				x[y].style.height = "64px";
				x[y].src = temp.replace("_grey.png","_grey2.png");
				temp = x[y].style.left;
				temp = temp.replace("px","");
				temp -= 8;
				temp = temp+'px';
				x[y].style.left = temp;
				
				temp = x[y].style.top;
				temp = temp.replace("px","");
				temp -= 18;
				temp = temp+'px';
				x[y].style.top = temp;
			}
		}
	}
}

function ShowVenues() {
	var maybe_visible=0;
	var sidebar=$("divSidebar");
	var image = "";
	temp = aVenues.length;
	bounds = map.getBounds();

	for( var x=0;x<temp;x++){
		aVenues[x][4] = 0;
	}
	temp = '';
	markers = [];
	sidebar.innerHTML= "";
	map.clearOverlays();
	existingMarkers = new Hash2();
	if (aVenues.length > 0){
		temp += "<table cellpadding=\"0\" cellspacing=\"0\">";
		for (i=0,done=0,visible=0;((i<aVenues.length)&&(done==0));i++) {
			point = new GLatLng(aVenues[i][1],aVenues[i][2]);
			if ((aVenues[i][4]==0) && (bounds.contains(point) == true)) {
				if(maybe_visible>=iteratorVenue){
					var html_link = "<a href=\"#\" onclick=\"ModalWindow('"+sBaseURL+"/venues/ajax_view_venue/"+aVenues[i][0]+"','divVenue'); return false\" onmouseover=\"zindex('"+sBaseURL+"/img/pins/"+alphabet[visible]+"_grey.png','1')\" onmouseout=\"zindex('"+sBaseURL+"/img/pins/"+alphabet[visible]+"_grey2.png',oldzindex)\"";
					tmp = aVenues[i][1]+' '+aVenues[i][2];
					icon.image = sBaseURL+"/img/pins/"+alphabet[visible]+"_grey.png";
					temp+="<tr><td valign=\"top\">";
					temp+=html_link+"> <img src=\""+sBaseURL+"/img/pins/"+alphabet[visible]+"_grey_side.gif\" border=\"0\"></a> &nbsp; ";
					temp+="</td><td valign=\"top\"><div id=\""+aVenues[i][0]+"\" class=\"empty\">";
					temp+=html_link+" class=\"sidebar_link\">"+aVenues[i][5].substring(0,40)+"";
					if(aVenues[i][5].length > 40){ temp+= "..."; }
					temp+="</a><div class=\"sidebar_phone\"><br />"+aVenues[i][6]+"</div></div>";
					temp+="</td></tr>";
					if (!existingMarkers.hasItem(tmp)) {
						markers[visible] = CreateVenue(aVenues[i][0],aVenues[i][2], aVenues[i][1], aVenues[i][3], visible);
						existingMarkers.setItem(tmp, tmp);
					}else{
						var a = aVenues[i][1];
						var b = aVenues[i][2];
						tmp = a+' '+b;
						for(x=0;existingMarkers.hasItem(tmp);x++){
							a += 0.00005 * Math.abs((map.getZoom()-18));
							if(x%2==0){
								b += 0.00003 * Math.abs((map.getZoom()-18)* 10);
							}else{
								b -= 0.00003 * Math.abs((map.getZoom()-18)* 10);
							}
							tmp = a+' '+b;
						}
						markers[visible] = CreateVenue(aVenues[i][0],b,a, aVenues[i][3], visible);
						var polyline = new GPolyline([
							new GLatLng(aVenues[i][1], aVenues[i][2]),
							new GLatLng(a, b),
						], "#FF0000", 5);
						map.addOverlay(polyline);
						
						existingMarkers.setItem(tmp, tmp);
					}
					visible++;
				}
				maybe_visible++;
			}
			if(visible >= venuesvisible){
				done=1;
			}
		}
		temp += "</table>";
		sidebar.innerHTML = temp;

		var navigate = $('navigate');
		sidebar.innerHTML += navigate.innerHTML;
		if(iteratorVenue <= 0){
			Element.hide('prev');
		}else{
			Element.show('prev');
		}
		if(i>=aVenues.length){
			Element.hide('next');
		}else{
			Element.show('next');
		}
	}
}

/*next pagination function*/
function next(){
	iteratorVenue += venuesvisible + 1;
	ShowVenues();
}

/*prev pagination function*/
function previous(){
	iteratorVenue -= venuesvisible + 1;
	ShowVenues();
}

/*nuke this function in lieu of how invite a friend works*/
function SubmitInfo(type){
	if(type=="venuerating"){
		var par = 'data[Venuerating][venue_id]='+id+'&data[Venuerating][rating]='+$("VenueratingRating").value;
		var url = sBaseURL+'/venueratings/add';
	}
	var myAjax = new Ajax.Request(
		url,
		{
			method: 'post',
			parameters:par,
			onComplete: function(){
				HideSections(true);
				$("divVenueLinks").style.display='none';
				$("divVenue").innerHTML+=$("divInfoHolder").innerHTML;
				$("spnInfo").innerHTML="rating saved";
			}
		}
	);
}

/*short and sweet modal window.  Takes as an argument the url we want to load and the window id we load that info into*/
function ModalWindow(url,WindowID){
	var myAjax = new Ajax.Request(
		url,
		{
			method: 'get',
			onLoading: function(){
				getScroll();
				setScroll(0,0);
				$('overlay').style.display = 'block';
				$('lightbox').style.display = 'block';
			},
			onComplete: function(Request){
				Element.update(WindowID,Request.responseText);
				$('lightbox').style.display = 'none';
				Element.show(WindowID);
			}
		}
	);
}

/*close the modal window*/
function CloseModalWindow(){
	Element.hide('divVenue');
	Element.hide('overlay');
	Element.hide('lightbox');
	//dhtmlHistory.add('map:'+Math.round(lat*1000)/1000+'_'+Math.round(lng*1000)/1000+'_'+map.getZoom(),'CloseModalWindow()');
	setScroll(0,yPos);
}

/*loads html from url into id using paramaters pars*/
function LoadHTML(url,id,pars){
	var myAjax = new Ajax.Request(
		url,
		{
			method: 'get',
			parameters: pars,
			onSuccess: function(originalRequest){
				Element.update(id,originalRequest.responseText);
				Element.show(id);
				Element.hide('lightbox');
			}
		}
	);
	return 1;
}

function HideSections(bShowLinks) {
	var oVenueDiv=$("divVenue");
	
	var oInvite=GetObjectFromParent(oVenueDiv, 'divInvite');
	if (oInvite!=undefined) {oVenueDiv.removeChild(oInvite);}
	
	var oInfo=GetObjectFromParent(oVenueDiv, 'divInfo');
	if (oInfo!=undefined) {oVenueDiv.removeChild(oInfo);}

	var VenueRating=GetObjectFromParent(oVenueDiv, 'divVenueRating');
	if (VenueRating!=undefined) {oVenueDiv.removeChild(VenueRating);}
	
	var EventRating=GetObjectFromParent(oVenueDiv, 'divEventRating');
	if (EventRating!=undefined) {oVenueDiv.removeChild(EventRating);}
	
	if (bShowLinks!=undefined) {
		var oLinks=$("divVenueLinks");
		oLinks.style.display='block';
	}
}

function getScroll(){
	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){  // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop; 
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}
	this.yPos = yScroll;
}

function setScroll(x, y){
	window.scrollTo(x, y); 
}

function GetObjectFromParent(oParent, sID) {
	for (var i = 0; oParent.childNodes[i]; i++ ) {
		if (oParent.childNodes[i].id==sID) {
			return oParent.childNodes[i];
		}
	}
}

/*hash function I stole likely needs to be nuked in lieu of new clustering code*/
function Hash2(){
	this.length = 0;
	this.items = new Array();
	for (var i = 0; i < arguments.length; i += 2) {
		if (typeof(arguments[i + 1]) != 'undefined') {
		this.items[arguments[i]] = arguments[i + 1];
		this.length++;
		}
	}

	this.removeItem = function(in_key)
	{
		var tmp_value;
		if (typeof(this.items[in_key]) != 'undefined') {
		this.length--;
		var tmp_value = this.items[in_key];
		delete this.items[in_key];
		}

		return tmp_value;
	}

	this.getItem = function(in_key) {
		return this.items[in_key];
	}

	this.setItem = function(in_key, in_value)
	{
		if (typeof(in_value) != 'undefined') {
		if (typeof(this.items[in_key]) == 'undefined') {
			this.length++;
		}

		this.items[in_key] = in_value;
		}

		return in_value;
	}

	this.hasItem = function(in_key)
	{
		return typeof(this.items[in_key]) != 'undefined';
	}
}
