﻿var dl = null;
function createDealerLocator() {

	var options = GetDLOptions();

	$(".dl-loading").width($("#map").width());

	var cookie = $.cookie("DealerSearch");
	if (cookie != null && cookie != "" && $("#dlSearchBox").attr("value") == "") {
		$("#dlSearchBox").attr("value", cookie);
	}

	if (options.loaded != null && typeof options.loaded == "function") {
		var func = options.loaded;
		options.loaded = function(dl) {
			func(dl);
			$(".dl-loading").remove();
		};
	}
	else {
		options.loaded = function(dl) {
			$(".dl-loading").remove();
		};
	}

	dl = new $.dealerLocator(options);
}

function GetDLOptions() {

	var setIcon = function(dealer, markers) {

		if (dealer.el == null)
			return;

		var url = G_DEFAULT_ICON.image;
		if (dealer.mapNumber <= dlDealerPerPage) {
			var letter = String.fromCharCode("A".charCodeAt(0) + dealer.mapNumber - 1);
			url = "http://www.google.com/mapfiles/marker" + letter + ".png";
		}
		dealer.el.find(".list-icon").attr("src", url);
	};

	var dlOptions = {
		renderDealer: renderDealer,
		renderDealerInfo: renderDealerInfo,
		dealerDetailsZoomLevel: dlDealersDetailsLevel,
		defaultMapZoom: dlDefaultMapZoom,
		minSearchResult: dlMinSearchResults,
		dealersPerPage: dlDealerPerPage,
		btnSubmitId: "dlSearchButton",
		defaultMapCenter: new GLatLng(dlDefaultMapCenterLat, dlDefaultMapCenterLng),
		inputId: "dlSearchBox",
		createMarkerIcon: createMarkerIcon,
		showDealersOnMap: true,
		dealersUrl: dlDimUrl,
		dealerUrl: dlDimDealerUrl,
		directionsUrl: (typeof dlDirectionsUrl == "undefined") ? "" : dlDirectionsUrl,
		dealerInfoRendered: function(dealer, el, markers) {},
		dealerRendered: function(dealer, el, markers) {
			setIcon(dealer, markers);
		},
		mapNumberChanged: setIcon,
		geoCodePrefix: (typeof dlSearchPrefix) != "undefined" ? dlSearchPrefix : "",
		brandId: dlBrandId,
		node: dlNodeId,
		dealerCssClass: "dl-dealer",
		dealerInfoCloseImg: "/static/common/as/img/ex.gif",
		filters: dlFilters,
		userFilters: dlUserFilters,
		userFiltersContainerId: "dl-filter",
		useClustering: dlUseClustering
	};

	return dlOptions;
}

function createDealerName(dealer) {
	if (!dealer.miniDealer.uniqueIdentifier)
		return dealer.miniDealer.n;

	return (dealer.miniDealer.n + ", " + formatAddress(dealer.miniDealer.uniqueIdentifier.Address,
			dealer.miniDealer.uniqueIdentifier.City, dealer.miniDealer.uniqueIdentifier.PostalCode,
			dealer.miniDealer.uniqueIdentifier.State)).replace(/\n/g, " ");
}

function formatAddress(streetaddress, city, zipcode, state, country) {
	return addressFormatString
		.replace("{$streetaddress}", streetaddress ? streetaddress : "")
		.replace("{$city}", city ? city : "")
		.replace("{$zipcode}", zipcode ? zipcode : "")
		.replace("{$state}", state ? state : "")
		.replace("{$country}", country ? country : "")
		.replace("{$postaladdress}\n", "");
}

function populateExtended(dealer) {

	if (!dealer.extendedPopulated) {
		$(dealer.extendedDealer.p).each(function() {

			if (this.ProgId == dlProperyNames.Website)
				dealer.Website = getPropertyValue(this.Values);
			else if (this.ProgId == dlProperyNames.Email)
				dealer.Email = getPropertyValue(this.Values);
			else if (this.ProgId == dlProperyNames.PhoneShop)
				dealer.Phone = getPropertyValue(this.Values);
			else if (this.ProgId == dlProperyNames.PhoneOffice)
				dealer.StorePhone = getPropertyValue(this.Values);
			else if (this.ProgId == dlProperyNames.PhoneService)
				dealer.ServicePhone = getPropertyValue(this.Values);
			else if (this.ProgId == dlProperyNames.Fax)
				dealer.Fax = getPropertyValue(this.Values);
			else if (this.ProgId == dlProperyNames.Presentation)
				dealer.Presentation = getPropertyValue(this.Values);
			else if (this.ProgId == dlProperyNames.OpenHours)
				dealer.OpenHours = getPropertyValue(this.Values);
			else if (this.ProgId == dlProperyNames.Exposure)
				dealer.ExposeUrl = getPropertyValue(this.Values);

			dealer.extendedPopulated = true;
		});

		if (dealer.StorePhone != null && dealer.StorePhone != "")
			dealer.Phone = dealer.Phone + ", " + dealer.StorePhone;

		if (dealer.PhoneService != null && dealer.PhoneService != "")
			dealer.Phone = dealer.Phone + ", " + dealer.PhoneService;
	}
}

function getPropertyValue(values) {

	var defaultValue = null;
	for (var i = 0; i < values.length; i++) {
		if (this.BrandAlias == dlBrandId)
			return values[i].Value;
		if (this.BrandAlias == null)
			defaultValue = values[i].Value;
	}
	return defaultValue;
}

function createTooltipIcons(dealer) {

    var tips = '<div class="matching-filters">';

    $(dlUserFilters).each(function(i, filter) {

        if (!filter.userMatchFilter(dealer))
            return;

        if (!filter.icon || filter.icon == '')
            return;

        tips += '<img class="filter-icon" src="' + filter.icon + '" title="' + filter.label + '" />';
    });

    tips += '</div>';

    return tips;
}


function renderDealer(dealer, el, markers) {

	if (el) {

		populateExtended(dealer);

		var content = $('<img class="list-icon png"/><h2>'
			+ dealer.miniDealer.n + '</h2><p class="address">'
			+ dealer.extendedDealer.a.Address + '<br/>'
			+ dealer.extendedDealer.a.PostalCode + '<br/>'
			+ dealer.extendedDealer.a.City + '<br/>'
			+ '</p>'
			+ ((dealer.Email != undefined && dealer.Email != null && dealer.Email != "") ? '<a href="mailto:' + dealer.Email + '" class="email">' + dealer.Email + '</a>' : '')
			+ ((dealer.Phone != undefined && dealer.Phone != null && dealer.Phone != "") ? '<p class="phone">' + dealer.Phone + '</p>' : '')
			+ '<a class="more-info level2-link">' + dlTxtMoreInfo + '</a>'
			+ createTooltipIcons(dealer)
			);

		el.hover(function() {
			$(this).addClass("dealer-hover");
		}, function() {
			$(this).removeClass("dealer-hover");
		}).addClass("dl-dealer").append(content);

		el.find(".email").click(function(e) {
			e.stopPropagation();
		});
	}
}

function renderDealerInfo(dealer, el, markers) {

	if (el) {

		populateExtended(dealer);

		$(".dealer-info").remove();

		if (dl.defaults.directionsUrl == null)
			dl.defaults.directionsUrl = "";
			
		var directionsUrl = dl.defaults.directionsUrl + (dl.defaults.directionsUrl.indexOf("?") >= 0 ? "&" : "?") + "to=" + encodeURI(dealer.miniDealer.n).replace("&", "%26");

		var input = $("#dlSearchBox");
		if (input.attr("value") != "" && input.attr("value") != dealer.miniDealer.n) {
			directionsUrl += "&from=" + encodeURI(input.attr("value") || "").replace("&", "%26");
		}

		var content = $('<img class="dealer-info-close png" src="'
		+ dl.defaults.dealerInfoCloseImg + '"" /><h2>'
		+ dealer.miniDealer.n + '</h2>'
		+ createTooltipIcons(dealer)
		+ ((dealer.Presentation != undefined && dealer.Presentation != null && dealer.Presentation != "") ? '<p class="presentation">' + dealer.Presentation + '</p>' : '')
		+ '<h3 class="dealer-info-adress">'
		+ dlTxtAdress + '</h3><p class="dealer-info-adress"></p>'
		+ (dl.defaults.directionsUrl != "" ? '<a class="directions level2-link" href="'+ directionsUrl + '">'+ dlTxtGetDirections + '</a>' : "")
		+ '<h3 class="dealer-info-contact">'
		
		+ dlTxtContactInfo + '</h3>'
		+ ((dealer.Phone != undefined && dealer.Phone != null && dealer.Phone != "") ? '<div><b>' + dlTxtPhone + '</b></div><div>' + dealer.Phone + '</div>' : '')
		+ ((dealer.Fax != undefined && dealer.Fax != null && dealer.Fax != "" && typeof (dlTxtFax) != "undefined") ? '<div><b>' + dlTxtFax + '</b></div><div>' + dealer.Fax + '</div>' : '')
		+ ((dealer.Email != undefined && dealer.Email != null && dealer.Email != "") ? '<div><b>' + dlTxtEmail + '</b></div><div><a href="mailto:' + dealer.Email + '">' + dealer.Email + '</a></td></div>' : '')
		+ ((dealer.Website != undefined && dealer.Website != null && dealer.Website != "") ? '<div><b>' + dlTxtHomepage + '</b></div><div><a href="' + dealer.Website + '" target="_blank">' + dealer.Website + '</a></div>' : '')
		+ '<div>'
		+ ((dealer.OpenHours != undefined && dealer.OpenHours != null && dealer.OpenHours != "") ? '<h3 class="dealer-info-open">' + dlTxtOpenHours + '</h3><p class="open-hours">' + dealer.OpenHours + '</p>' : '</div>'));

		el.append(content).addClass("dealer-info");

		el.find(".dealer-info-close").click(function() {
			el.remove();
		});
		if (dealer.el != null)
			el.append(dealer.el.find(".list-icon").clone());

		var addressText = formatAddress(dealer.extendedDealer.a.Address,
			dealer.extendedDealer.a.City, dealer.extendedDealer.a.PostalCode,
			dealer.extendedDealer.a.State);
		el.find("p.dealer-info-adress").html(addressText.replace(/\n/g, "<br/>"));

	}
}

function createMarkerIcon(dealer, markers) {

	if (dealer.mapNumber > dlDealerPerPage)
		return G_DEFAULT_ICON;
	
	var letter = String.fromCharCode("A".charCodeAt(0) + dealer.mapNumber - 1);
	var url = "http://www.google.com/mapfiles/marker" + letter + ".png";

	return new GIcon(G_DEFAULT_ICON, url);
}

function createDrivingDirections() {

	var ddOpt = {
		dealerDetailsZoomLevel: dlDealersDetailsLevel,
		defaultMapZoom: dlDefaultMapZoom,
		defaultMapCenter: new GLatLng(dlDefaultMapCenterLat, dlDefaultMapCenterLng),
		submit: $("#dlSearchButton"),
		result: $("#dl-result"),
		fromInput: $("#dlFrom"),
		toInput: $("#dlTo"),
		dealersUrl: dlDimUrl,
		dealerUrl: dlDimDealerUrl,
		brandId: dlBrandId,
		node: dlNodeId,
		from: querySt("from"),
		to: querySt("to"),
		geoCodePrefix: (typeof dlSearchPrefix) != "undefined" ? dlSearchPrefix : ""
	};
	
	if((typeof ddTxtResultHeadline) != "undefined")
		ddOpt.txtHeadline = ddTxtResultHeadline;
		
	if((typeof ddTxtError) != "undefined")
		ddOpt.txtError = ddTxtError;

	dd = new $.drivingDirections(ddOpt);
}

function querySt(ji) {
	hu = window.location.search.substring(1);
	gy = hu.split("&");
	for (i = 0; i < gy.length; i++) {
		ft = gy[i].split("=");
		if (ft[0] == ji) {
			return Url.decode(ft[1]);
		}
	}
}

/**
*
*  URL encode / decode
*  http://www.webtoolkit.info/
*
**/

var Url = {

	// public method for url encoding
	encode: function(string) {
		return escape(this._utf8_encode(string));
	},

	// public method for url decoding
	decode: function(string) {
		return this._utf8_decode(unescape(string));
	},

	// private method for UTF-8 encoding
	_utf8_encode: function(string) {
		string = string.replace(/\r\n/g, "\n");
		var utftext = "";

		for (var n = 0; n < string.length; n++) {

			var c = string.charCodeAt(n);

			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if ((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}

		}

		return utftext;
	},

	// private method for UTF-8 decoding
	_utf8_decode: function(utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;

		while (i < utftext.length) {

			c = utftext.charCodeAt(i);

			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if ((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i + 1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i + 1);
				c3 = utftext.charCodeAt(i + 2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}

		}

		return string;
	}
}