// Search objects
Dealers.search = new Object();


// Search variables
Dealers.search.active = false;								// Specifies if a search is already running
Dealers.search.showing = false;								// Specifies if the search windows are already open


// Map Variables
var mapID = "map";												// Map element ID
var mapObject;														// Map object
var homePoint;														// Contains the map's home position
var point;															// Contains a specific point
var marker;															// Contains a specific marker
var listener;														// Contains a map listener for dealer selection
var geocoder;														// Contains the dealer geocoder

var selectedDealer = null;										// Specifies the selected delaer hash
var dealerPoints = new Array();								// Contains all dealer store positions
var dealerMarkers = new Array();								// Contains all dealer store markers
var dealerWindows = new Array();								// Contains all dealer information windows
var dealerMsgs = new Array();									// Contains all dealer information window content

var globalPoints = new Array();								// Contains all dealer store positions with numerical IDs


/**********************/
/*                    */
/*  Search Functions  */
/*                    */
/**********************/
// Submit a dealer search
Dealers.search.submit = function() {
	if(Dealers.search.active !== true) {
		// Hide error message
		Dealers.hide('dealer_error');
		
		// Set default error status
		var error = false;
		
		// Start values array
		var values = new Array();
			
		// Check through all checkboxes...
		for(var i = 0; i < document.getElementsByName('products').length; i++) {
			// Get current checkbox
			var cbox = document.getElementsByName('products');
			
			// If the checkbox is checked, add checkbox values to values array
			if(cbox[i].checked === true) { values[values.length] = cbox[i].value; }
		}
		
		// If a search has been provided, set error status to true
		if(!Dealers.input('zip')) { error = true; }
		
		// If there are no values, set error status to true
		if(!values.length) { error = true; }
		
		// If there are no errors...
		if(!error) {
			// Set search status to true
			Dealers.search.active = true;
			
			// Show loading icon
			Dealers.show('search_icon');
			
			// Create server request
			Dealers.search.server = Dealers.ajax.server("results.php", "post");
			
			// Begin parameters
			Dealers.search.server.params = "";
			
			// If a product number is set, add product number to parametersSet parameters
			if(Dealers.input('product_no')) { Dealers.search.server.params += "product="+Dealers.urlencode(Dealers.input('product_no'))+"&"; }
			
			// Resume parameters
			Dealers.search.server.params += "zip="+Dealers.urlencode(Dealers.input('zip'))+"&radius="+Dealers.urlencode(Dealers.input('radius'));
			
			// Begin adding code values to parameters
			Dealers.search.server.params += "&codes="+values.join(',');
			
			// Set finishing function...
			Dealers.search.server.finish = function() { 
				// Set search status to false
				Dealers.search.active = false; 
				
				// Set showing status to true
				Dealers.search.showing = true;
				
				// Hide loading icon
				Dealers.hide('search_icon'); 
			}
	
			// Submit form
			Dealers.ajax.send(Dealers.search.server);
		}
		
		// If there are errors...
		else { 
			// If no zip code is specified, set an error
			if(!Dealers.input('zip')) { Dealers.search.error("Please specify your zip code!", "zip"); }
			
			// Or if there are no product types specified, set an error
			else if(!values.length) { Dealers.search.error("Please specify at least one product type!"); }
		}
	}
}


// Close a dealer search
Dealers.search.close = function() {
	// Hide map
	Dealers.hide('map');
	
	// Hide result header
	Dealers.hide('result_header');
	
	// Hide results container
	Dealers.hide('results');
}


// Search all product types
Dealers.search.all = function() {
	// Check all checkboxes...
	for(var i = 0; i < document.getElementsByName('products').length; i++) {
		// Get current checkbox
		var cbox = document.getElementsByName('products');
		
		// Check the checkbox
		cbox[i].checked = true;
	}
}


// Set a search error
Dealers.search.error = function(msg, field) {
	// Set error message
	Dealers.content('dealer_error', msg);
	
	// Show error message
	Dealers.show('dealer_error');
	
	// If a field is specified, set focus to specified field
	if(field) { Dealers.focus(field); }
}

//This function takes a zip and runs the search for you
Dealers.init_load = function(zip) {
    //Ensure this does not run until DOM is loaded
    $(document).ready(function() {
        
        //Set the zip field value
        $("#zip").val(zip);
        
        //Set all products checked
        Dealers.search.all();

        //Submit the search
        Dealers.search.submit();
    })
}


/***************************/
/*                         */
/*  Dealer Tile Functions  */
/*                         */
/***************************/
// Set dealer to hover
function hoverDealer(hash) {
	// Set class to hover
	Dealers.object('dealer_'+hash).className = 'hover';

	// Return true;
	return true;
}


// Set dealer to idle
function idleDealer(hash) {
	// Set default class
	var newClass = '';
	
	// If this dealer is already selected, set class back to selected
	if(hash == selectedDealer) { newClass = 'selected'; }
	
	// Set class name
	Dealers.object('dealer_'+hash).className = newClass;
	
	// Return true
	return true;
}


// Select a dealer
function selectDealer(hash, runMap) {
	// Retrieve list object
	var obj = Dealers.object('dealer_'+hash);
	
	// If object exists...
	if(obj) {
		// If this dealer is already selected...
		if(hash == selectedDealer) {
			// Clear selected dealer
			selectedDealer = null;
			
			// Clear selected class
			obj.className = '';
			
			// If selection should affect the map...
			if(runMap == true) {
				// Close info window
				mapObject.closeInfoWindow();
				
				// Return to original position
				mapObject.returnToSavedPosition();
				
				// Stop waiting for the information window to close
				GEvent.removeListener(listener);
			}
			
			// Return true
			return true;
		}
		
		// If this dealer isn't selected...
		else {
			// If a dealer is already selected...
			if(selectedDealer) {
				// Try to clear selected dealer
				try { 
					Dealers.object("dealer_"+selectedDealer).className = ''; 
					
					// If selection should affect the map...
					if(runMap == true) {
						// Close info window
						mapObject.closeInfoWindow();
						
						// Return to original position
						mapObject.returnToSavedPosition();
						
						// Stop waiting for the information window to close
						GEvent.removeListener(listener);
					}
				}
				
				// Catch failed attempts
				catch(err) { }
			}

			// Set current dealer to selected
			selectedDealer = hash;
			
			// Set class to selected
			obj.className = 'selected';
			
			// If selection should affect the map...
			if(runMap == true) {
				// Pan to store marker
				mapObject.panTo(dealerPoints[hash]);
				
				// Open information window
				dealerWindows[hash] = mapObject.openInfoWindowHtml(dealerPoints[hash], dealerMsgs[hash]);
				
				// Wait for information window to close
				listener = GEvent.addListener(mapObject, "infowindowclose", function() { 
					// Return to original position
					mapObject.returnToSavedPosition();
					
					// If a dealer is selected, deselect dealer from dealer list
					if(selectedDealer) { selectDealer(hash, false); }
					
					// Stop waiting for the information window to close
					GEvent.removeListener(listener);
				});
			}
			
			// Return true
			return true;
		}		
	}
	
	// If object doesn't exist, return false
	else { return false; }
}




/*******************/
/*                 */
/*  Map Functions  */
/*                 */
/*******************/
// Add a dealer to the map
function addDealer(hash, lat, long, msg) {
	// Set default return value
	var r = false;
	
	// If browser is compatible with the Google Maps API...
	if(GBrowserIsCompatible()) {
		// Set return value to true
		r = true;
		
		// Retrieve dealer point
		point = new GLatLng(lat, long);
		
		// Add dealer point to points
		globalPoints[globalPoints.length] = point;
		dealerPoints[hash] = point;
		
		// Create marker
		dealerMarkers[hash] = new GMarker(point, spotIconOptions);
		
		// Add marker to the map
		mapObject.addOverlay(dealerMarkers[hash]);
		
		// Set dealer message
		dealerMsgs[hash] = '<div class="dealer_info">'+msg+'</div>';
		
		// Wait for mouse clicks on the marker
		GEvent.addListener(dealerMarkers[hash], "click", function() {
			// Pan to store marker
			mapObject.panTo(dealerPoints[hash]);
			
			// Open information window
			dealerWindows[hash] = mapObject.openInfoWindowHtml(dealerPoints[hash], dealerMsgs[hash]);
			
			// Select dealer from dealer list
			selectDealer(hash, false);
			
			// Wait for information window to close
			listener = GEvent.addListener(mapObject, "infowindowclose", function() { 
				// Return to original position
				mapObject.returnToSavedPosition();
				
				// If a dealer is selected, deselect dealer from dealer list
				if(selectedDealer) { selectDealer(hash, false); }
				
				// Stop waiting for the information window to close
				GEvent.removeListener(listener);
			});
		});
	}
	
	// Send return value
	return r;
}


// Get map bounds
function mapBounds() {
	// Create bounds data
	var bounds = new GLatLngBounds();
	
	// For every dealer point, extend bounds data
	for (var i=0; i< globalPoints.length; i++) { bounds.extend(globalPoints[i]); }
	
	// Set zoom to display all dealers
	mapObject.setZoom(mapObject.getBoundsZoomLevel(bounds));
	
	// Set map to the center of all dealers
	mapObject.setCenter(bounds.getCenter());
	
	// Save centered position
	mapObject.savePosition();
}


// Google© Maps Creater
function createMap(lat, long) {
	// Set default return value
	var r = false;
	
	// If browser is compatible with the Google Maps API...
	if(GBrowserIsCompatible()) {
		// Set return to true
		r = true;
		
		// Create a new map
		mapObject = new GMap2(document.getElementById(mapID));

		// Add map controls
		mapObject.addControl(new GLargeMapControl());			// Position control
		mapObject.addControl(new GScaleControl());				// Distance scale display
		mapObject.addControl(new GMapTypeControl());				// Map type control
		
		// Create global points array
		globalPoints = new Array();
	
		// Create map home
		homePoint = new GLatLng(lat, long);
		
		// Set map to map home
		mapObject.setCenter(homePoint);
		
		// Create marker icon
		var spotIcon = new GIcon();
		spotIcon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
		spotIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
		spotIcon.iconSize = new GSize(12, 20);
		spotIcon.shadowSize = new GSize(22, 20);
		spotIcon.iconAnchor = new GPoint(6, 20);
		spotIcon.infoWindowAnchor = new GPoint(5, 1);
		spotIconOptions = { icon:spotIcon };
		
		// Create a geocoder
		geocoder = new GClientGeocoder();
	}
	
	// Send return value
	return r;
}
