/////////////////////////////////////
//		Global Variables
/////////////////////////////////////
var domain_name = 'http://www.earthlust.com';
var drupal_root = '/cms';
var site_root = 'sites/all/themes/earthlust/';
var loader_image = domain_name + '/images/loader.gif';
var loader = '<div class="loader"><image src="' + loader_image + '" height="32" width="32" /></div>';


/////////////////////////////////////
//		Initialize page functions
/////////////////////////////////////
$(document).ready(function() {
	// preload loader
	jQuery ('<img src="' + loader_image + '" />');
	
	// Add the list of online retailers to the display area
	$('#zipcode_results').html($('#online_stores').html());

	// Set Zipcode search form to submit to the proper div on the page.
	$(".ajax_zipcodesearch").submit(function () {
		runZipSearch(this);
		return false;
	});
	
	// allow the online stores link to return that info to the results box
	//$('#onlinelink').live('click', function () {
	//	$('#zipcode_results').html($('#online_stores').html());
	//	pageTracker._trackPageview("/retailers.html?page=online_retailers");
	//	return false;
	//});
});

/////////////////////////////////////
//		Searching Functions
/////////////////////////////////////
function runZipSearch (e) {
	var thisAction = $(e).attr('action') + '?'; // set the page for the ajax call.
	var destination = 'zipcode_results'; // Set the destination for the results
	var zip = $('#' + $(e).attr('id') + '_zip').val();
	var distance = $('#' + $(e).attr('id') + '_distance').val();
	var viewString = '';
	var requestEnd = 'zip[search_units]=mile';
	$('#' + destination).html(loader); // put in the page loader icon.
	if (!zip || isNaN(zip) || zip.length < 5) {
		zip = '';
		zipString = '';
	} else {
		if (zip.length > 5) { zip = String(zip).substring(0,5); }
		zipString = 'zip[postal_code]=' + zip + '&';
	}
	$('#' + $(e).attr('id') + '_zip').val(zip); // Set the form to show what we actually used to search.
	if (!distance || isNaN(distance)) {
		distance = '';
		distanceString = '';
	} else {
		if (distance > 100) { distance = 100; }
		distanceString = 'zip[search_distance]=' + distance + '&';
	}
	thisAction = thisAction + zipString + distanceString + requestEnd;
	pageTracker._trackPageview("/retailers.html?zip=" + zip + "&range=" + distance);
	$.get(thisAction,null,function(data){
		data = data.replace(/^\s+|\s+$/g, '');
		if (!data) { // if no results, put in the list of online retailers.
			$('#' + destination).html('<h2>Search Results</h2><p>Sorry, there are no stores in your search range.<br />Please check out our <a href="/shop" title="Buy Online!">online shop</a>!</p><br />');
		} else {
			var thiscontent = '<h2>Search Results or <a href="/shop" title="Shop Online">Shop Online</a></h2>' + data;
			$('#' + destination).html(thiscontent);
		}
	});
}