/*function initialize_google_maps() {
	var latlng = new google.maps.LatLng(40.7608333, -111.8902778);
	var myOptions = {
		zoom: 11,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	var maps = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}*/

// Plotting Logic

var option_overlay;
var map;
var mode = "";
var umodes = Array('zone','radius','location','mark');
var markersArray = [];
var overlayArray = [];
var infoBoxArray = [];
var zonebounds = '';
var curPage = 0;
var tooltipout = 0;
var notooltip = 0;
var singletip = false;
var singleArray = Array();
var boundshandler;
var pinarray = Array();
var labelId;
var mapSection = 'restaurants';
var map_sectionTypes = '';
var pull_limit = 350;

pullTimer = "";

function initialize_google_maps() {
	
	var myLatLng = new google.maps.LatLng(40.7608333, -111.8902778);
	var myOptions = {
		zoom: 7,
		center: myLatLng,
		mapTypeId: google.maps.MapTypeId.ROADMAP 
	};
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);   
		
	if(singletip) {
		var marker = new google.maps.Marker({
			position: singleArray[0],
			map: map,
			icon: 'http://ent.mediaut.com/img/map_marker_lrg.png',
			zIndex: 1,
			label: singleArray[1],
			title: singleArray[2]
		});
		
		map.panTo(singleArray[0]);
		map.setZoom(15);
		
		return;	
	}
	
	bnds = map.getBounds();
		
	boundshandler = google.maps.event.addListener(map, 'bounds_changed', function() {		
		pullVisible(bnds);
		google.maps.event.removeListener(boundshandler);
		//pullQueue();
		//clearPoints();												 
	});
	google.maps.event.addListener(map, 'dragstart', function() {		
		clearPoints();											 
	});
	google.maps.event.addListener(map, 'dragend', function() {
		var bounds = map.getBounds();									
		pullVisible(bounds);
	});
	google.maps.event.addListener(map, 'zoom_changed', function() {
		pullQueue();
		clearPoints();
	});	
}

function changeSection(sectionName, types){
	clearPoints();
	mapSection = sectionName;
	map_sectionTypes = types;
	bnds = map.getBounds();
	pullVisible(bnds);
}

function pullQueue(bounds) {
	setTimeout('pullVisible("'+bounds+'")',500); // only allow this to be called every 0.5 seconds.
}

function changePerPage() {
	$('#perPage').val($('#perPageList').val());
}

function pullVisible(bounds) {

	if(!bounds || bounds == "undefined")
		bounds = map.getBounds();
		
	var ajx = new ajax;
	
	parameters = 'bounds=' + bounds;
	
	if(mapSection == 'bars') {
		mapSection = 'restaurants';
		map_sectionTypes = 'bars';
	}
	
	ajx.open('post','/'+mapSection+'/get_map_points/bounds:' + bounds + '/pins:' + pinarray + '/types:' + map_sectionTypes + '/limit:' + pull_limit, true);
	ajx.onreadystatechange = function() {
		if(ajx.readyState == 4) {
			plotPoints(ajx.responseText);
		}
	}
	ajx.send(null);
}

google.maps.Marker.prototype.lbl = function(label){
	
	var div;

	this.setTitle(label);
	div = document.createElement('DIV');
	div.style.border = "0px solid none";
	div.style.position = "absolute";
	div.style.paddingLeft = "0px";
	div.style.cursor = 'pointer';
	
	var point = this.getPosition();
	
	if (point) {
	  div.style.left = point.x + 'px';
	  div.style.top = point.y + 'px';
	}
	
	div.innerHTML = label;
	map.controls[point].push(div);
}
	
Array.prototype.has = function(value) {
	var i;
	for (var i=0, loopCnt=this.length; i<loopCnt; i++) {
		if (this[i] == value) {
			return true;
		}
	}
	return false;
};

function getPosition(arrayName,arrayItem){
    for(var i=0;i<arrayName.length;i++){ 
       if(arrayName[i]==arrayItem)
            return i;
    }
}

function gotoPoint(lat,long,id){
	
	clearPoints();
	var myLatlng = new google.maps.LatLng(lat,long);
	map.panTo(myLatlng);
	map.setZoom(15);
	scroll(0,0);
	var bounds = map.getBounds();									
	pullVisible(bounds);
	
}

function plotPoints(points) {
	
	var ico;
	var total = points.split('||');

	var zoom = map.getZoom();

	hicon = Array('http://ent.mediaut.com/img/map_marker_lrg.png','http://ent.mediaut.com/img//map_marker_lrg.png','http://ent.mediaut.com/img/map_marker_lrg.png','http://ent.mediaut.com/img/maps/dot_sm.png','http://ent.mediaut.com/img/maps/dot_med.png','http://ent.mediaut.com/img/maps/dot.png');
	//ico = hicon[2];	
		
	//var bounds = new google.maps.LatLngBounds();
		
	for(i=0;i<total.length;i++) {
		
		var markinfo = total[i].split('|');
		
		var myLatlng = new google.maps.LatLng(markinfo[1],markinfo[0]);
		
		if(pinarray.has(markinfo[2])) {
			ico = 'http://ent.mediaut.com/img/maps/map_marker_' + (getPosition(pinarray,markinfo[2])+1) + '.png';
			//bounds.extend(myLatlng);
		} else {
			if(zoom > 11){
				ico = hicon[4];
			} else {
				ico = hicon[4];
			}
		}
		if(i>pull_limit) {
			if(zoom < 13){
				var marker = new google.maps.Marker({
					position: myLatlng,
					map: map,
					icon: ico,
					zIndex: 1,
					label: markinfo[2],
					title: markinfo[3]
				});
			}
		} else {
			var marker = new google.maps.Marker({
				position: myLatlng,
				map: map,
				icon: ico,
				zIndex: 10,
				label: markinfo[2],
				title: markinfo[3]
			});		
			//marker.lbl("test");
			//var lbl = new drawLabel(myLatlng, map, 'A');
			//overlayArray.push(lbl);
		}
 		//var iw = new google.maps.InfoWindow({pixelOffset: new google.maps.Size(5,0), maxWidth:300});
		
		google.maps.event.addListener(marker, 'click', function() {
					
			if(i>10) {
			
				var myOptions = {
						 content: ' <b style="font-family:Arial; font-size:15px; color:#B22685;">' + this.title + '</b><div align="center" id="details_' + this.label + '" style="width:270px;"><img src="/img/maps/ajax-loader.gif" style="padding-top:20px"/></div>'
						,disableAutoPan: false
						,maxWidth: 300
						,pixelOffset: new google.maps.Size(-42,-129)
						,zIndex: 5
						,boxStyle: { 
							width: "280px"
							,height: "128px"
							,background: "url('/img/maps/balloon.png') no-repeat"
							,padding: "10px"
						 }
						,closeBoxMargin: "2px 22px 2px 2px"
						,closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif"
						,infoBoxClearance: new google.maps.Size(30, 30)
						,isHidden: false
						,pane: "floatPane"
						,enableEventPropagation: false
				};
			
			} else {

				var myOptions = {
						 content: ' <b style="font-family:Arial; font-size:15px; color:#B22685;">' + this.title + '</b><div align="center" id="details_' + this.label + '" style="width:270px;"><img src="/img/maps/ajax-loader.gif" style="padding-top:20px"/></div>'
						,disableAutoPan: false
						,maxWidth: 300
						,pixelOffset: new google.maps.Size(-43,-155)
						,zIndex: 5
						,boxStyle: { 
							width: "280px"
							,height: "128px"
							,background: "url('/img/maps/balloon.png') no-repeat"
							,padding: "10px"
						 }
						,closeBoxMargin: "2px 22px 2px 2px"
						,closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif"
						,infoBoxClearance: new google.maps.Size(30, 30)
						,isHidden: false
						,pane: "floatPane"
						,enableEventPropagation: false
				};
				
			}
	
			var ib = new InfoBox(myOptions);
			ib.open(map, this);
			
			labelId = this.label;
			
			// call the details via ajax
			var ajx = new ajax();
			ajx.open('get','/'+mapSection+'/get_map_point_details/'+labelId);
			ajx.onreadystatechange = function() {
				if(ajx.readyState == 4){
					var r = ajx.responseText.split('|');
					document.getElementById('details_'+labelId).setAttribute('align', 'left');
					document.getElementById('details_'+labelId).innerHTML = r[1] + '<br />' + r[2] + '<br /><br /><a href="/'+mapSection+'/view/' + r[3] + '">View Details</a>';
				}
			}
			ajx.send(null);
			infoBoxArray.push(ib);
			
		});

		markersArray.push(marker);
				
	}
	//map.fitBounds(bounds);
}

function drawLabel(myLatlng, map, label) {

  // Now initialize all properties.
  this.point_ = myLatlng;
  this.map_ = map;
  this.label_ = label;

  // We define a property to hold the image's
  // div. We'll actually create this div
  // upon receipt of the add() method so we'll
  // leave it null for now.
  this.div_ = null;

  // Explicitly call setMap() on this overlay
  this.setMap(map);
}

drawLabel.prototype = new google.maps.OverlayView();

drawLabel.prototype.onAdd = function() {
	
  // Create the DIV and set some basic attributes.
  var div = document.createElement('DIV');
  div.style.border = "none";
  div.style.borderWidth = "0px";
  div.style.position = "absolute";
  //div.style.color = '#FFF';
  div.style.fontWeight = 'bold';
  div.innerHTML = this.label_;


  // Set the overlay's div_ property to this DIV
  this.div_ = div;
  //this.setZIndex(100);

  // We add an overlay to a map via one of the map's panes.
  // We'll add this overlay to the overlayImage pane.
  var panes = this.getPanes();
  panes.overlayLayer.appendChild(div);
}

drawLabel.prototype.draw = function() {
  var overlayProjection = this.getProjection();
  
  var sw = overlayProjection.fromLatLngToDivPixel(this.point_);
  var ne = overlayProjection.fromLatLngToDivPixel(this.point_);

  var div = this.div_;
  div.style.left = (sw.x - 10) + 'px';
  div.style.top = (ne.y - 29) + 'px';
  div.style.width = '50px';
  div.style.height = '50px';
  div.style.zIndex = 20;
}

drawLabel.prototype.toggleDOM = function() {
  if (this.getMap()) {
    this.setMap(null);
  } else {
    this.setMap(this.map_);
  }
}

function loadTipData(id, type) {

	var ajx = new ajax;
	
	parameters = 'id=' + id;
	
	ajx.open('post','/'+mapSection+'/get_tooltip/', true);
	ajx.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajx.setRequestHeader("Content-length", parameters_1.length);
    ajx.setRequestHeader("Connection", "close");
	ajx.onreadystatechange = function() {
		if(ajx.readyState == 4) {
			if(type == "new"){
				document.getElementById('map_tip').innerHTML = ajx.responseText;
			} else {
				document.getElementById('tip_' + id).innerHTML = ajx.responseText;
			}
		}
	}
	ajx.send(parameters);

}

function clearPoints() {
	if (markersArray) {
		for (var i=0; i<markersArray.length; i++) {
			markersArray[i].setMap(null);
		}
		markersArray = [];
	}
}

function clearOverlay(){
	if (overlayArray) {
		for( var i=0; i < overlayArray.length; i++ ) {
			if(overlayArray[i]){
				overlayArray[i].setMap(null);
			}
		}
		overlayArray = [];
	}
}

function clearInfoBoxes(){
	if(infoBoxArray){
		for (var i=0; i<infoBoxArray.length; i++) {
			infoBoxArray[i].setMap(null);
		}
		infoBoxArray = [];			
	}
}

function re_load(divname) {
	//document.getElementById(divname).innerHTML = '<div align="center"><img src="/images/re_loader.gif"></div>';	
}

function setMode(umode) {

	resetMode(mode);	

	if(mode==umode) {	
		mode = null;
		return;
	} else {
		$('#button_'+umode).addClass('at');		
		mode = umode;
	}

	switch(umode) {
	
		case 'zone':
		
			clearPoints();
			clearOverlay();
			
			$('#map_results').html('<div align="center">Please select a region of the map to see results</div>');
			
			map.enableKeyDragZoom({
				boxStyle: {
				  border: "2px dashed #33649F",
				  backgroundColor: 'white',
				  opacity: 0.5
				}
			});
			
			var dz = map.getDragZoomObject();
			google.maps.event.addListener(dz, 'dragend', function(bnds) {								
				clearPoints();	
				clearOverlay();
				zonebounds = bnds;
				pullVisible(bnds);
			});				

			rtt('#button_zone', 'Hold the shift key down over the map to enable the region selection tool', 'bottomLeft');
		
		break;
		
		case 'location':
			
			if (google.loader.ClientLocation) {
				clearPoints();	
				clearOverlay();		
				latlng = new google.maps.LatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
				map.setCenter(latlng);
				map.setZoom(13);
				var bounds = map.getBounds();
				pullVisible(bounds);
				
				rtt('#button_zone', 'Based on your ip address, we have determined you are in '+google.loader.ClientLocation.address.city+' , '+google.loader.ClientLocation.address.region.toUpperCase(), 'bottomLeft');
				
			} else {
				rtt('#button_zone', 'Sorry, we can\'t determine your location at this time.', 'bottomLeft');
			}
		
		break;
	
	}
	
}

function resetMode(umode) {
	
	for(i=0;i<umodes.length;i++){
		$('#button_'+umodes[i]).removeClass('at');
	}
	
	switch(umode) {
	
		case 'zone':
		
			clearPoints();
			clearOverlay();
			var bounds = map.getBounds();									
			pullQueue(bounds);
		
		break;
	
	}	
	
}

