/*!
 * wheresmychai.com product locator
 * http://www.wheresmychai.com/
 *
 * Copyright 2010, Marti Holguin
 * Licensed under the MIT or GPL Version 2 licenses.
 
 * Date: Fri Mar 15 15:23:05 2010 -0800
 */
 $(document).ready(function(){	
 					chaiMap = new mapObject();	// jquery based init function, creating object that holds googlemap, processes user requests, displays location markers, and formats results 
 				});	 

		
 var mapObject = function() {
	this.smallWindow = 1;
	//alert("new mapObject");
	this.iconUrl = "http://www.morningglorychai.com/wheresmychai/images/markerFlowerIcon.png"; // 'http://www.morningglorychai.com/wheresmychai/marker_icon_flower_w_stem.png';  //http://www.morningglorychai.com/wheresmychai/marker_icon_pruple_flower.png
	this.map = null;
	this.geocoder = new google.maps.Geocoder();
	this.infowindow = null;
	this.locationArray = new Array();
	this.markerDataArray = new Array();  //this should be combined!!!
	this.markerObjectArray = new Array();
	$(".searchButton").click( this.initNewSearch );
	if ( $(window).width() > 600) { this.smallWindow = 0; this.initWMC();}	 //alert("SMALL widows width:" + ($(window).width()) );

	

	
	//temp hack for small widows (iphone etc)
	//do not instantiane gmap until after setting width
	
	
	
	
};

mapObject.prototype.buildCutomControls = function() {
	// Create a div to hold the control.
	var controlDiv = document.createElement('DIV');
	//var controlDiv = $("<div id='backButton'>Show Search</id>");
	// Set CSS styles for the DIV containing the control
	// Setting padding to 5 px will offset the control
	// from the edge of the map
	controlDiv.style.padding = '25px 0px 0px 0px';
	
	// Set CSS for the control border
	var controlUI = document.createElement('DIV');
	controlUI.style.backgroundColor = 'white';
	controlUI.style.borderStyle = 'solid';
		controlUI.style.borderColor = 'green';
	controlUI.style.borderWidth = '1px';
	controlUI.style.cursor = 'pointer';
	controlUI.style.textAlign = 'center';
	controlUI.title = 'Click start a new search';
	controlDiv.appendChild(controlUI);
	
	// Set CSS for the control interior
	var controlText = document.createElement('DIV');
	controlText.style.fontFamily = 'Arial,sans-serif';
	controlText.style.fontSize = '12px';
	controlText.style.padding = '2px 5px 2px 5px';
	controlText.innerHTML = 'New Search';
	controlText.id = "backButton";
	controlUI.appendChild(controlText);

	//var myControl = new MyControl(controlDiv);
	
	this.map.controls[google.maps.ControlPosition.TOP_LEFT].push(controlDiv);
	//$("#backButton").click( this.backButtonClicked );
	google.maps.event.addDomListener(controlUI, 'click', function() {
   		//alert ("BACK!");	
   		mapObject.backButtonClicked();
 	 });

};

mapObject.backButtonClicked = function() {
	$("#mapCanvas").hide(); 
	$("#searchColumn").show();
	
};

mapObject.prototype.initNewSearch = function() {
	//alert("ALMOST THERE! MAKE CLICKING A SLECTING RESULT SHOW MAP along with showing marker infowindow!\noption: DONT show map on results for mobile, show results list, and show map on clicking a item!");
	
	var map = chaiMap; 
	var ww =  $(window).width();
	 //$("#searchResultsList").hide();
	if(chaiMap.smallWindow == 1) { $("#searchColumn").hide();	$("#mapCanvas").show();  } //
	
	if(chaiMap.clearMarkers()) {	chaiMap.initWMC(); } //using declared object name directly. not best practice..
	//temp hack for small widows (iphone etc)

};


mapObject.prototype.initMap = function(locationValues) {	
	$("#searchResultsList").slideUp(0);
	var latlng = new google.maps.LatLng(locationValues.lat,locationValues.lng);
	if(!this.map) {
			var myOptions = {
			      zoom: locationValues.mapZoom, //11 is full city  
			      center: latlng,
			      mapTypeId: google.maps.MapTypeId.ROADMAP
			};
			this.map = new google.maps.Map(document.getElementById("mapCanvas"), myOptions); 
			var contentString = "Where's my chai?";
			this.infowindow = new google.maps.InfoWindow({content: contentString});
			this.buildMarkerData(locationValues); 
			if(this.smallWindow == 1) {this.buildCutomControls(); }
		
			 
		} else {
			this.map.setCenter( latlng ); //the lat is wrong: wtf
			this.map.setZoom(locationValues.mapZoom);
			this.buildMarkerData(locationValues); 
			
		}
		if(this.youAreHereMarker) {
			this.youAreHereMarker.setPosition(latlng);
		} else {
			this.youAreHereMarker = new google.maps.Marker({
				      position: latlng,
				      map: this.map, 
				      title: ("Your Location")   //move string to config
			 });
		}


};

mapObject.prototype.parseFormValues = function() {
	var  locationValues = new Array();
	var me = this;
	locationValues.lat = 47.700174; 
	locationValues.lng = -122.355356;
	locationValues.initalState = 1; //flag for using default inital values
	locationValues.selectedFlavortList="";
 	locationValues.selectedProductList="";
 	locationValues.product = $('#product').val();
 	locationValues.flavor = $('#flavor').val();
	 locationValues.fullAddress =  $('#address').val();
	 locationValues.searchRadius =  $('#radius').val(); 
	 locationValues.mapZoom = me.setZoom(locationValues.searchRadius);
	
	 $('input[name=flavor]:checked').each( function(i) { locationValues.selectedFlavortList += ('&flavor[]=' +  me.value);  });
	$('input[name=product]:checked').each( function(i) { locationValues.selectedProductList += ('&product[]=' +  me.value); });
	  if (locationValues.fullAddress.length < 5) {
	  		 me.initMap(locationValues); //use default values
	  } else {
	  	//geocode and get lat/lng here
	  	me.geocoder.geocode( { 'address': locationValues.fullAddress}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				locationValues.initalState = 0;
				locationValues.lat = results[0].geometry.location.lat();
				locationValues.lng = results[0].geometry.location.lng()		 
				me.initMap(locationValues); //Call initMap after values have been returned
			} else { alert("There was an issue looking up you location.\nPlease check the address, and try again.\n\ngeocode failed:" + status);}
		});
	}
	
};

mapObject.prototype.setZoom = function(searchRadius) {
	var mapZoom = 14;
	if(searchRadius == 1) {mapZoom = 14;}
	if(searchRadius == 3) {mapZoom = 13;}
	if(searchRadius == 5) {mapZoom = 12;}
	if(searchRadius == 10) {mapZoom = 11;}
	if(searchRadius == 25) {mapZoom = 10;}
	if(searchRadius == 0) {mapZoom = 7;} //7 for whole NW US
	return(mapZoom);
};


mapObject.prototype.buildMarkerData = function(locationValues) {
	devString = 'marker:\n';
	if(locationValues.initalState == 1) {
		dataUrl = "startingLocations.xml";
	} else {
		dataUrl = "serviceGetLocations.php?radius="+ locationValues.searchRadius +"&lat="+  locationValues.lat +"&lng=" +  locationValues.lng +"&flavor="+  locationValues.flavor +"&product=" +  locationValues.product; 
	}
	dataUrl = "serviceGetLocations.php?radius="+ locationValues.searchRadius +"&lat="+  locationValues.lat +"&lng=" +  locationValues.lng +"&flavor="+  locationValues.flavor +"&product=" +  locationValues.product; 
	map = this;
	$.get(dataUrl,{},function(content) {
		$('marker',content).each(function(i) {
		 	var nameTest = $(this).attr('name');	
	         var markerItem = {
				    name: $(this).attr('name'), 
				    address: $(this).attr('address'), 
				    lat:  $(this).attr('lat'),
				    lng: $(this).attr('lng'),
				    phone: $(this).attr('phone'),
				    photo_url: $(this).attr('photo_url'),
				    website_url: $(this).attr('website_url'),
				    productList:[],
				    productQuickContent:''
					  //  type: $(this).attr('type') 
				}
				$(this).find('item').each(function(){
					var productItem = {
						product_id:  $(this).attr('product_id'), 
						flavor_id:  $(this).attr('flavor_id'), 
						product_name:  $(this).attr('product_name'), 
						flavor_name:  $(this).attr('flavor_name'),
						product_description: ( $(this).attr('flavor_name') + " - " + $(this).attr('product_name')  ) 
					}
					markerItem.productList.push(productItem);
					markerItem.productQuickContent += (productItem.product_description + "<br />\n");
				}); //each item
						map.markerDataArray.push(markerItem); 
	        }); //each marker
	    for (x in map.markerDataArray)	{
			map.markerObjectArray[x] = (new LocationResult(map,map.markerDataArray[x]));
		}	   
	map.buildResultsDisplayList();
	});  
		
};


// LocationResult is a  class representing a single Local Search result returned by the Google AJAX Search API.
    
function LocationResult(map,result) {
	var me = this;
	me.map_ = map;
	me.result_ = result;
	me.name = result.name;
	me.address = result.address;
	me.lat = result.lat;
	me.lng = result.lng;
	me.productDescription = result.productQuickContent;
	me.phone = result.phone;
	me.website_url = result.website_url;
	me.photo_url = result.photo_url;
	me.html_ = me.html(); //+ me.name;
	me.position_ = new google.maps.LatLng(parseFloat(me.lat),
	                               parseFloat(me.lng));
	me.marker_ = me.marker();
	me.markerListenerRef = google.maps.event.addListener(me.marker_, "click", function() {     me.select();      });  
	
}

LocationResult.prototype.marker = function() {
	var me = this;
	
	if (me.marker_) return me.marker_;
	var marker = me.marker_ = new google.maps.Marker({
		position: me.position_,
		map: me.map_.map, 
		icon: me.map_.iconUrl,
		title: (me.map_.markerDataArray[x].name  + " -  " + me.map_.markerDataArray[x].address)
	});
	return marker;
};

mapObject.prototype.clearMarkers = function() {
	for (x in this.markerObjectArray)
		{
			google.maps.event.removeListener(this.markerObjectArray[x].markerListenerRef); //remove eventListeners for markers
			this.markerObjectArray[x].marker_.setMap();		 //remove markers from map
			
		}		
	this.markerObjectArray.length = 0 ;
	this.markerDataArray.length = 0 ;
	return (1);
};
    
LocationResult.prototype.select = function() {
	var me = this;
	map = me.map_;
	map.infowindow.setContent(this.html(true));
	map. infowindow.open(map.map, this.marker());
	map.map.setCenter( me.position_ );          
	//alert("SELECT: chaiMap.smallWindow" + chaiMap.smallWindow);
	
	if(chaiMap.smallWindow == 1) { $("#searchColumn").hide();	$("#mapCanvas").show();  }
};

LocationResult.prototype.html = function() {
	var me = this;
	content = "<div class='infoWindow'>"; 
	content += "<div id='infoWindowTitle'>"+ me.name +"</div>";
	content += "<div id='infoWindowLeftcol'>";
	content += "<div class='infoWindowAddress'>"+ me.address +"</div>";
	content += "<div class='infoWindowAddress'>"+ me.phone +"</div>";
	if(me.website_url) {    content += "<div id='infoWindowAddress'><a href='"+ me.website_url +"' target='_blank'>"+ me.website_url +"</a></div>";}
	content += "<div id='infoWindowDetail'>"+ me.productDescription +"</div>";
	content += "</div>"; //leftcol
	if(me.photo_url) {    content += "<div id='infoWindowRtcol'><img src = '"+ me.photo_url  +"' width=100 border=0></div>";}
	content += "</div>"; //infoWindow
	return (content);
};

mapObject.prototype.buildResultsDisplayList = function() {
		me = this;
		strResultsString="<div id='resultsTitle'>Chai Locations<div id='resultsSummary'>"+ me.markerDataArray.length +" locations found in search</div></div>";
		markerCount = 0;
		for (x in me.markerDataArray)
		{
			strResultsString +="<div class='resultItem'><a href='javascript: me.markerObjectArray[" +markerCount  + "].select();'>"; //selectMarker(id) no id- add one or just use count
			strResultsString += "<div class='resultItemName'>" + me.markerObjectArray[x].name + '</div>';
			strResultsString += "<div class='resultItemAddress'>" + me.markerObjectArray[x].address + '</div>';
			strResultsString += "</a></div>";
			markerCount++;
		} 
		$("#searchResultsList").hide().html(strResultsString).slideDown(500);
		
}
	
mapObject.prototype.initWMC = function() {

 	this.locationArray = this.parseFormValues(); 
}

