// tl-distsearch.js -

// Global Variables
var map;
var routeMap = null;
var distData;
var geocoder = new GClientGeocoder(new GGeocodeCache());
var directions;
var directionsPanel;

// Create a base icon for all of our markers that specifies the
// shadow, icon dimensions, etc.
var baseIcon = new GIcon(G_DEFAULT_ICON);
baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(20, 34);
baseIcon.shadowSize = new GSize(37, 34);
baseIcon.iconAnchor = new GPoint(9, 34);
baseIcon.infoWindowAnchor = new GPoint(9, 2);

// Global Functions
$(document).ready(jquery_init);
function test(eventObject){
		alert("Clicked me3");

}

/*
 * Distributor clicked function, called when a distributor is clicked in the left sidebar.
 * It will expand the content of the distributor and hide the details of all others.
 */
function distClicked(eventObject){
		
	var clickedDist = this.id;
	$(".dist_detail").each(function(i){			
		if (this.parentNode.id == clickedDist){
			if(this.style.visibility == "visible"){
				// Set the appropriate active/unactive numbered graphic for the clicked distributor
				// Change the graphic to active
				var imgTag = $("#" + this.parentNode.id + " > div.dist_info_graphic > img");
				var srcValue = $(imgTag).attr("src");
				var baseImageName = srcValue.substring(0, srcValue.length-5);
				$(imgTag).attr("src", baseImageName + "B.png");
						
				$(this.parentNode).removeClass("selected_dist");

			} else {
				$(this.parentNode).addClass("selected_dist");
				// Change the graphic to active
				var imgTag = $("#" + this.parentNode.id + " > div.dist_info_graphic > img");
				var srcValue = $(imgTag).attr("src");
				var baseImageName = srcValue.substring(0, srcValue.length-5);
				$(imgTag).attr("src", baseImageName + "A.png");
			} 
			
			$(this).show("slow");
		} else {
			// Node other than the one clicked...
			
				// Change the graphic to active
				var imgTag = $("#" + this.parentNode.id + " > div.dist_info_graphic > img");
				var srcValue = $(imgTag).attr("src");
				var baseImageName = srcValue.substring(0, srcValue.length-5);
				$(imgTag).attr("src", baseImageName + "B.png");
			
			$(this.parentNode).removeClass("selected_dist");
			$(this).hide("slow");	
		}
	});  //end each
	
	// Pan to point in map
	var index = clickedDist.substring(clickedDist.lastIndexOf('_')+1, clickedDist.length)-1;
	var lat = distData[index].latitude;
	var lng = distData[index].longitude;
	map.panTo(new GLatLng(lat, lng));
}


/*
 * Initialize jquery
 */
function jquery_init(){
	initialize();
	// Hide the search results container on startup
//	$("#search_results_hdr").hide();
//	$("#search_results").hide();
	
	// Hide all detail content at start
/*	$(".dist_detail").each(function(i){
		$(this).hide();
	});
	*/
	// Add "Enter" key listener
	$('#address').keypress(function (e) {
    	if (e.which == 13) {
    		// Enter key pressed.
    		lookup();
      	}
    });
	
	// Register click event on dist_info content
	$(".dist_info").click(distClicked);  
}


function getDirections(count){

	showDirections();
	directionsPanel = document.getElementById("route");
			
	// Lazy initialization of route_map
	if (routeMap == null) {
		routeMap = new GMap2(document.getElementById("route_map"));
	}
	
	routeMap.clearOverlays();  // Remove last direction data
		
	directions = new GDirections(routeMap, directionsPanel);
	var fromLocation = document.getElementById("dirStartAdr_" + count).value;
	var index = count - 1;
	var toLocation = distData[index].googleAddressString;
		
	// Query follows this format: "from: 500 Memorial Drive, Cambridge, MA to: 4 Yawkey Way, Boston, MA 02215 (Fenway Park)"		
	var query="from: " + fromLocation + " to: " + toLocation;
	directions.load(query);
	$("#action_menu").show();
//	directions.load("from: 500 Memorial Drive, Cambridge, MA to: 4 Yawkey Way, Boston, MA 02215 (Fenway Park)");
}

/*
 * initializing and loading the google map
 * create center point and mark it with a info window 
 * when you click on the marker
 */
function initialize() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
      	map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
	}
}

/*
 * set input field value to empty when user types in the input 
 */
function settext(fieldId){
	$(fieldId).attr("value", ""); 
}

 
function createMarker(item) {
	var point = new GLatLng(item.latitude, item.longitude);

	var customIcon = new GIcon(baseIcon);

	if (item.repairCenter == "Y") {
		customIcon.image = "/wcsstore/tl/catalog/images/en_US/dist_search/DotWrench.png";
	} else {
		customIcon.image = "/wcsstore/tl/catalog/images/en_US/dist_search/Dot.png";
	}
	markerOptions = { icon:customIcon };
	var marker = new GMarker(point, markerOptions);
	map.addOverlay(marker);
  	addClickEvent(marker, item);
}    

/*
 * adding an event listener for the marker to show up
 * info window when you click on the marker
 */
function addClickEvent(marker,item) { // Add a click listener to the markers
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(infoMessage(item));
	});
}
    

/*
 * creating a info message with a distributor address 
 * orgname,address,city,state,phone and website Url
 */
function infoMessage(item){
	infoMsg = "";
	if (item != null) {
		infoMsg = append(item.orgname, "<br />");
		infoMsg += append(item.address1, "<br />");
		infoMsg += append(item.address2, "<br />");
		infoMsg += append(item.city, ", ");
		infoMsg += append(item.state, " ");
		infoMsg += append(item.zipcode, "<br>");
		infoMsg += append(item.phone, "<br>");
		infoMsg += append(item.weburl, "<br>");
	}
 	return infoMsg;
}    
    
    
	
/*
 * get list of distributors in JSON format
 */	
function lookup(){
	$('#map_overlay').show();
	$("#searching").show();
//	$("#search_results").hide();
	$("#search_results_hdr").hide();
	
	var address = $("#address").attr("value");
	var distance = $("#distance").attr("value");
//	alert("Entered " + address);
	
	
	geocoder.getLatLng(address, function(point) {
		if (!point){
			// alert(address + " not found");
			$("#searching").hide();
			$("#no_geo_data").show();
		} else {
			
//			alert("Address:" + address + " lat=" + point.lat() + " lng=" + point.lng() + " distance=" + distance);
	
			$.getJSON("/webapp/wcs/stores/servlet/DistributorSearchCmd", { lat: point.lat(), lng: point.lng(), miles: distance }, 
				function(data){
					//alert("Got data");
 					// Location is null if no matching records are found.
					if(data[0].location == null) { 
						// No matching distributor information
						$("#no_matches").show();
						$("#searching").hide();
					} else {
						// Got some results
	         			distData = data; // Put results in global variable for other function access
          			
		          	  	// Set map center
				      	// Since data is ordered closest to farthest
				      	// Data element 0's latitude/longitude coordinates
				      	// will be the center
				      	
						//map.setCenter(new GLatLng(37.4419, -122.1419), 10);
						map.clearOverlays();
						map.setCenter(new GLatLng(data[0].latitude, data[0].longitude), 10);

						$('#search_results').html(""); // clear old results 
						for (var i = 0; i < data.length; i++) {
							createMarker(data[i]);
							buildDistSidebar(data[i], i);					
						}
						
						// Register click event for new distributors
						$(".dist_info").click(distClicked);
							
						// Hide all detail content at start
						$(".dist_detail").each(function(i){
							$(this).hide();
						});
						
						showSearchResults();
					} // end of if			   	
				});  // end function
			
		} // end else 
		
	}); // end geocoder
}


/* 
 * Generate the following HTML:
 *
 * 	<div id="dist_info_1" class="dist_info"><!--  Dynamic results are here -->
		<div class="dist_name">Dad's Parts</div>
		<div  class="dist_info_graphic">
			<img border="0" src="<c:out value="${jspStoreImgDir}/catalog/images/${locale}/dist_search/1ButtonB.png" />" />
		</div>
		<div class="dist_clear"></div>
		<div class="dist_detail">
			738 Boat Road<br/>
			Harrisburg, PA 17110<br />
			717-555-1212<br />
			www.parents.com<br />
			
			<div class="direct_form">								
				<div class="label dir_label"><fmt:message key="dsp_PROMPT_DRIVE_DIR" bundle="${storeText}" /></div>
				<input type="text" name="startAdr" class="startAdr" value="<fmt:message key="dsp_PROMPT_DRIVE_ADR" bundle="${storeText}" />" />
				<a href="javascript:getDirections()" style="border: 0px" ><img style="border: 0px" src="<c:out value="${jspStoreImgDir}/catalog/images/${locale}/dist_search/Go.png" />" /></a>							
			</div>
		</div>
	</div>
 */		
function buildDistSidebar(dist, count){
	var id = count + 1;
	var currentContent = $('#search_results').html();
	var content = '<div id="dist_info_' + id + '" class="dist_info">\n';
	content += '   <div class="dist_name">' + dist.orgname + '</div>\n';
	content += '   <div  class="dist_info_graphic">\n';
	content += '      <img border="0" src="' + image_dir + id + 'ButtonB.png" />\n';
	content += '   </div>\n';
	content += '   <div class="dist_clear"></div>\n';
	content += '   <div class="dist_detail">\n';
	content += '      ' + append(dist.address1, "<br />\n");
	content += '      ' + append(dist.address2, "<br />\n");
	content += '      ' + append(dist.city, ", ");
	content += '      ' + append(dist.state, " ");
	content += '      ' + append(dist.zipcode, "<br>\n");
	content += '      ' + append(dist.phone, "<br>\n");
	content += '      ' + append(dist.weburl, "<br>\n");	
	content += '      <div class="direct_form">\n';
	content += '          <div class="label dir_label">' + directions_prompt + '</div>\n';
	content += '          <input type="text" id="dirStartAdr_' + id + '" class="startAdr" value="' + drive_addr_prompt + '" onfocus="javaScript:this.select();" />\n';
	content += '          <a href="javascript:getDirections(' + id + ');" style="border: 0px" ><img style="border: 0px" src="' + image_dir + 'Go.png" /></a>\n';
	content += '      </div>\n';
	content += '   </div>\n';  // end .dist_detail
	content += '</div>\n';
	
	$('#search_results').html(currentContent + content);
	
	// Add "Enter" key listener
	$(".startAdr").keypress(function (e) {
    	if (e.which == 13) {
    		// Enter key pressed.
    		var id = e.target.id;
    		var count = id.substring(id.indexOf('_')+1, id.length);
    		getDirections(count);
      	}
    });
}
		
/*
 * Append non-null, and defined data to result list
 */
function append(data, suffix){
	var result = "";
	var t = typeof(data);
	if(t == "undefined") {
		alert("Undefined data");
	} else {
		if ((data != null) && (data.length > 0)) {
			result = (data + suffix);
		}
	}
	return result;		
}

/*
 * Hide the no matches window
 */
function closeMessage(id){
	$("#"+id).hide();
}

/*
 * Print current page
 */        
function printMe(){
	window.print();
}

/*
 * Show the search results content and hide the driving directions content
 */
function showSearchResults(){
	$("#action_menu").hide();
	$("#searching").hide();		
	
	$('#route_map').hide();
	$("#route_container").hide();
	$("#route").html("");  // clear contents for next call

	$('#map_overlay').hide();
	$("#search_results").show();
	$("#search_results").addClass("search_results");
	$("#search_results").removeClass("search_results_empty");
	$("#search_results_hdr").show();
	$('#map_container').show();
	$("#map_dist_content").show();
}

/*
 * Show the driving directions content and hide the search results content
 */
function showDirections(){
	$("#action_menu").show();
	
	$('#route_map').show();
	$("#route_container").show();
	$("#search_results").hide();
	$("#search_results_hdr").hide();
	$('#map_container').hide();
	$("#map_dist_content").hide();
}
