///<reference path="~/scripts/jquery.intellisense.js" />
///<reference path="~/scripts/true_core.js" />

//<![CDATA[

if (!window.CS) {
	Type.registerNamespace("CS");
}

if (!window.CS.Location) {

	CS.Location = function(p_el) {
		CS.Location.constructBase(this, [p_el]);
		this.initialize();
	}

	CS.Location.prototype = {
		initialize: function() {
			this._toAddress = '11,2777 23rd Avenue NE, Calgary, AB T1Y 7L6';
			this._latLng = new GLatLng(51.0718184, -113.9967517);
			this._map = new GMap2($('.js-mapHolder').get(0));
			this._map.addControl(new CS.ZoomControl());
			this._map.addControl(new CS.MapTypeControl());
			this._map.setCenter(this._latLng, 13);
			this._csIcon = new GIcon();
			this._csIcon.image = 'Content/art/map_cabinetSolutions.png';
			this._csIcon.iconSize = new GSize(49, 39);
			this._csIcon.iconAnchor = new GPoint(25, 39);
			this._csIcon.infoWindowAnchor = new GPoint(25, 39);

			this._startIcon = new GIcon();
			this._startIcon.image = 'Content/art/map_start.png';
			this._startIcon.iconSize = new GSize(49, 39);
			this._startIcon.iconAnchor = new GPoint(25, 39);

			var marker = new GMarker(this._latLng, { icon: this._csIcon });
			this._map.addOverlay(marker);

			this._directions = new GDirections(this._map);

			var self = this;
			GEvent.addListener(this._directions, 'load', function() { self._onDirections(); });
			GEvent.addListener(this._directions, 'error', function() { self._onDirectionsError(); });
			GEvent.addListener(this._directions, 'addoverlay', function() { self._onMapOverlay(); });

			this.jq.find(".js-directionsButton").click(function(p_e) {
				p_e.preventDefault();
				p_e.stopPropagation();
				self.getDirections($('.js-fromText', self.element).val());
			}).end();

			this.jq.find(".js-fromText").focus(function(p_e) {
				$(this).removeClass('inputDirections');
			})
			.blur(function(p_e) {
				if (this.valueOf == '') {
					$(this).addClass('inputDirections');
				}
			})
			.end();

			this._fromSearch();
		},
		dispose: function() {
			CS.Location.callBaseMethod(this, 'dispose');
		},
		handle_keydown: function(p_e) {
			if (p_e.keyCode == 13) {
				this.getDirections($('.js-fromText', this.element).val())
				p_e.preventDefault();
				p_e.stopPropagation();
			}
		},
		getFromAddress: function() {
			return this._fromAddress;
		},
		getDirections: function(p_from) {
			this._fromAddress = p_from;
			this._directions.load('from: ' + p_from + ' to: ' + this._toAddress, { getSteps: true });
		},
		_fromSearch: function() {
			var searchMatches = location.search.match(/from=([^&]*)/i);
			if (searchMatches) {
				var from = decodeURIComponent(searchMatches[1]);
				//console.log(from);
				this.jq.find(".js-fromText").val(from).trigger('focus').end();
				this.getDirections(from);
			}
		},
		_onDirections: function() {
			var self = this;
			var markup = (this._directions.getNumRoutes() != 1) ? '' : True.Template.parse($('#template_directions').html(), self);
			$('.js-directionsPane').html(markup);
			$('.js-openEmailModal').click(function(p_e) {
				var modalMarkup = True.Template.parse($('#template_directionModal').html(), self);
				var pop = $(modalMarkup);
				pop.find(".js-send").click(function() { self._sendDirections(pop) }).end();
				pop.jqm({ modal: true, toTop: true, onHide: function(p_e) { p_e.w.remove(); p_e.o.remove(); } }).jqmShow();
			});
			if (this._directions.getNumRoutes() != 1) {
				this._onDirectionsError();
			}
		},
		_onDirectionsError: function() {
			alert('We could not locate the address you entered. Please double check the street address you entered and make sure to include your city, province or state.');
		},
		_sendDirections: function(p_pop) {
			if (!this._sending) {
				this._sending = true;
				var self = this;
				var data = {};
				data.toEmail = $('.js-toEmail', p_pop).val();
				data.fromEmail = $('.js-fromEmail', p_pop).val();

				var invalid = 0;
				invalid += this._validateEmail(data.toEmail, '.js-validator-toEmail');
				invalid += this._validateEmail(data.fromEmail, '.js-validator-fromEmail');

				if (invalid > 0) {
					this._sending = false;
					return;
				}

				data.copySelf = $('.js-copySelf:checked', p_pop).length == 1;
				data.directions = True.Template.parse($('#template_directionsEmail').html(), self);
				data.directions = data.directions.replace(/(\<br\s*\/>|\n\s*|\n\t*)/gi, '\n');
				data.directions = data.directions.replace(/&nbsp;/gi, ' ');
				data.directions = data.directions.replace(/\<\/?[^\>]*>/gi, '');

				$.ajax({
					type: "POST",
					url: "AJAXService.asmx/SendDirections",
					data: $.toJSON(data),
					contentType: "application/json; charset=utf-8",
					dataType: "json",
					success: function(msg) {
						if (!msg.d) {
							alert("We're sorry, there was a problem sending your directions.");
						}
					},
					complete: function() {
						self._sending = false;
						p_pop.jqmHide();
					}
				});
			}
		},
		_validateEmail: function(p_email, p_validator) {
			var result = 0;
			if (p_email == '') {
				result = 1;
				$(p_validator).css('visibility', 'visible').html('Required field');
			}
			else {
				var regex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
				if (!regex.test(p_email)) {
					result = 1;
					$(p_validator).css('visibility', 'visible').html('Invalid email');
				}
				else {
					$(p_validator).css('visibility', 'hidden').html('');
				}
			}
			return result;
		},
		_getMapLink: function() {
			return "http://maps.google.com/maps?f=d&source=s_d&saddr=" + encodeURIComponent(this._fromAddress) + "&daddr=" + encodeURIComponent(this._toAddress) + "&hl=en&mra=ls"
		},
		_onMapOverlay: function() {
			var geoCount = this._directions.getNumGeocodes();
			var startMarker = this._directions.getMarker(0);
			var endMarker = this._directions.getMarker(geoCount - 1);
			startMarker.hide();
			endMarker.hide();
			if (this._startMarker) {
				this._map.removeOverlay(this._startMarker);
				this._startMarker = undefined;
			}
			this._startMarker = new GMarker(startMarker.getLatLng(), { icon: this._startIcon });
			this._map.addOverlay(this._startMarker);
			return true;
		}
	}

	CS.Location.register("CS.Location", True.Control);

}

// CS.GControl
CS.GControl = function() {
};

CS.GControl.prototype = {
	_addButton: function(p_container, p_image, p_clickDelegate) {
		var anchor = document.createElement("a");
		$(anchor).attr("href", "javascript:;");
		$(anchor).html("<img src='Content/art/" + p_image + "' />");
		p_container.appendChild(anchor);

		GEvent.addDomListener(anchor, "click", p_clickDelegate);
	}
}

CS.GControl.register('CS.GControl', GControl);

// CS.ZoomControl
CS.ZoomControl = function() {
	CS.ZoomControl.constructBase(this, []);
};

CS.ZoomControl.prototype = {
	initialize: function(map) {
		var container = document.createElement("div");

		this._addButton(container, "map_buttonZoomOut.gif", function() { map.zoomOut(); return false; });
		this._addButton(container, "map_buttonZoomIn.gif", function() { map.zoomIn(); return false; });
		map.getContainer().appendChild(container);

		return container;
	},
	getDefaultPosition: function() {
		return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(4, 4));
	}
}

CS.ZoomControl.register('CS.ZoomControl', CS.GControl);

// CS.MapTypeControl
CS.MapTypeControl = function() {
	CS.MapTypeControl.constructBase(this, []);
};

CS.MapTypeControl.prototype = {
	initialize: function(map) {
		var container = document.createElement("div");

		this._addButton(container, "map_buttonMap.gif", function() { map.setMapType(G_NORMAL_MAP); return false; });
		this._addButton(container, "map_buttonSatellite.gif", function() { map.setMapType(G_SATELLITE_MAP); return false; });
		this._addButton(container, "map_buttonHybrid.gif", function() { map.setMapType(G_HYBRID_MAP); return false; });
		map.getContainer().appendChild(container);

		return container;
	},
	getDefaultPosition: function() {
		return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(4, 4));
	}
}

CS.MapTypeControl.register('CS.MapTypeControl', CS.GControl);

//]]>