//
// jquery.dealerLocator.js
// Copyright (c) Connect Group Ltd. All rights reserved.
//
// $Id: jquery.dealerLocator.js 463 2010-01-27 11:08:00Z paul $
//

jQuery(function($) {
	// The key for the preferred dealer cookie
	var cookieKey = 'LR_PREF_DEALER_ID';

	// The various elements that make up the dealer locator functionality
	var elements = {
		back: $('div.dealer-search-block a.back-results', this.search),
		dropdown: $('div#find-dealer-dropdown'),
		filter: $('div.dealer-search-block form fieldset.filter', this.search),
		loading: $('<div class="dealer-loading"></div>'),
		search: $('div.dealer-search-block', this.dropdown)
	};

	// The HTML generated by a call to the dealer locator service.
	// This is used for the "Back to dealer results" link on the dealer information panel.
	var resultsHtml;
	
	//
	// beginAction(action)
	// Begins an action by preparing the drop down.
	// PARAMS
	//  action: The action to be performed.
	//
	function beginAction(action) {
		elements.loading.fadeIn(500, function() {
			elements.filter.hide();
			elements.back.hide();
			action();
		});
	}

	//
	// Initializes and submits a query for data.
	// PARAMS
	//  page: The page of results to be shown.
	//
	function beginQuery(page) {
		var form = $('form', elements.search);

		var request = {
			url: form.attr('action'),
			method: 'POST',
			page: (page != undefined) ? page : 1
		};

		if ($('fieldset.dealer-search select#internationallocation', form).length == 1) {
			request.internationallocation = $('fieldset.dealer-search select#internationallocation', form).val();
		} else {
			request.text = $('fieldset.dealer-search input#namepostcode', form).val();
		}

		if ($('fieldset.filter', form).length == 1) {
			var fieldset = $('fieldset.filter ol', form);
			request.radius = $('li select#distance', fieldset).val();
			request.service = $('li select#services', fieldset).val();
		}

		queryService(request, renderResults);
	}

	//
	// endAction()
	// Ends the current action.
	//
	function endAction() {
		var height = 0;
		elements.dropdown.children('div:not(.dealer-loading)').each(function() {
			height += $(this).height();
		});
		height += 10; // Add tuning

		elements.dropdown.animate({ "height": height + 'px' }, function() {
			$('div.dealer-results-block, div.dealer-details-block').show();
			elements.loading.fadeOut(1000);
		});
	}

	//
	// getParameterByName(url, name)
	// Gets the value of a query string parameter with the specified name from the specified URL.
	// PARAMS
	//  url: The URL.
	//  name: The name of the query string parameter whose value is to be returned.
	// RETURNS
	// A value for the query string parameter with the specified name, otherwise an empty string if 
	// no parameter with the specified name exists.
	//
	function getParameterByName(url, name) {
		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var pattern = "[\\?&]" + name + "=([^&#]*)";
		var results = new RegExp(pattern).exec(url);
		return (results != null) ? results[1] : '';
	}

	//
	// queryService(request, success)
	// Queries the dealer locator service.
	// PARAMS
	//  request: The dealer locator service request.
	//  success: The JavaScript function that will be called after the dealer locator service request 
	//           has been processed successfully.
	//
	function queryService(request, success) {
		var data = {}
		if (request.method == 'POST') {
			data = { radius: request.radius, service: request.service, page: request.page };
			if (request.internationallocation != undefined) {
				data.internationallocation = request.internationallocation;
			} else {
				data.text = request.text;
			}
		}

		beginAction(function() {
			$.ajax({
				url: request.url,
				type: request.method,
				data: data,
				dataType: 'html',
				success: function(data) {
					success(data);
				}
			});
		});
	}

	//
	// renderDealerDetails(data)
	// Renders the details about a specific dealer.
	// PARAMS
	//  data: The HTML returned by the dealer locator service.
	//
	function renderDealerDetails(data) {
		replacePanel(data);

		elements.back.show();

		$('div.dealer-details-block div.details-block div.left-col ul.cta-links:first', elements.dropdown).each(function() {
			var listItem = $('<li class="prefdealer"></li>');

			var preferredDealerId = $.cookie(cookieKey);
			if (preferredDealerId == null || preferredDealerId != dealerConfig.id) {
				var link = $('<a href="#">' + dealerConfig.text.setPreferredDealer + '</a>');
				link.click(function(e) {
					e.preventDefault();
					$.cookie(cookieKey, dealerConfig.id, { path: '/', expires: 365 });
					$(this).parent().empty().append($('<span>' + dealerConfig.text.preferredDealer + '</span>'));
					return false;
				});
				listItem.append(link);

			} else {
				listItem.append($('<span>' + dealerConfig.text.preferredDealer + '</span>'));
			}

			$(this).append(listItem);
		});

		$('div.dealer-details-block div.google-map-holder').each(function() {
			$(this).empty().append('<div id="google-map" style="height:100%;width:100%"></div>');
			$('div.dealer-details-block div.google-map-holder div#google-map').each(function() {
				var location = new MMLocation(new MMLatLon(dealerConfig.position.lat, dealerConfig.position.lon));

				var mapViewer = MMFactory.createViewer(this);
				mapViewer.addWidget(new MMSmallPanZoomWidget());
				mapViewer.createMarker(location, { 'inert': 'true' }); 
				mapViewer.goToPosition(location, 15);
			});
		});

		endAction();
	}

	//
	// renderResults(data)
	// Renders the results from the dealer locator service.
	// PARAMS
	//  data: The HTML returned by the dealer locator service.
	//
	function renderResults(data) {
		replacePanel(data);

		if ($('div.dealer-results-block table#multiple-matches').length == 0) {
			elements.filter.show();
		}

		$('div.dealer-results-block table:not(#multiple-matches) tbody tr td a', elements.dropdown).click(function(e) {
			e.preventDefault();
			queryService({ url: $(this).attr('href'), method: 'GET' }, renderDealerDetails);
			return false;
		});

		$('div.dealer-results-block table#multiple-matches tbody tr td a', elements.dropdown).click(function(e) {
			e.preventDefault();
			queryService({ url: $(this).attr('href'), method: 'GET' }, renderResults);
			return false;
		});

		$('div.dealer-results-block div.pagination dl dd a', elements.dropdown).click(function(e) {
			e.preventDefault();
			queryService({ url: $(this).attr('href'), method: 'GET' }, renderResults);
			return false;
		});

		resultsHtml = data;

		endAction();
	}

	//
	// replacePanel(data)
	// Replaces the current panel with the specified HTML.
	// PARAMS
	//  data: The HTML that will replace the current panel.
	//
	function replacePanel(data) {
		$('div.dealer-results-block, div.dealer-details-block').remove();
		elements.search.after(data);
		refreshCufon();
	}

	// Hide unneeded initial elements
	elements.back.hide();
	elements.filter.hide();
	elements.loading.hide();

	// Add the loading panel to the drop down
	elements.search.after(elements.loading);

	// Initialise the search form submit button
	$('form', elements.search).submit(function(e) {
		e.preventDefault();
		beginQuery();
		return false;
	});
		
	// Initialise the back button
	elements.back.click(function(e) {
		e.preventDefault();

		beginAction(function() {
			renderResults(resultsHtml);
		});

		return false;
	});
});
