Element.addMethods({
  scrollTo: function(element, left, top){
    var element = $(element);
    if (arguments.length == 1){
      var pos = element.cumulativeOffset();
      window.scrollTo(pos[0], pos[1]);
    } else {
      element.scrollLeft = left;
      element.scrollTop  = top;
    }
    return element;
  }
});
Effect.Scroll = Class.create();
Object.extend(Object.extend(Effect.Scroll.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    if(!this.element) throw(Effect._elementDoesNotExistError);
    this.start(Object.extend({x: 0, y: 0}, arguments[1] || {}));
  },
  setup: function() {
    var scrollOffsets = (this.element == window) 
                ? document.viewport.getScrollOffsets() 
                : Element._returnOffset(this.element.scrollLeft, this.element.scrollTop) ;
    this.originalScrollLeft = scrollOffsets.left;
    this.originalScrollTop  = scrollOffsets.top;
  },
  update: function(pos) {
    this.element.scrollTo(Math.round(this.options.x * pos + this.originalScrollLeft), Math.round(this.options.y * pos + this.originalScrollTop));
  }
});


function init() {
	if ($$('html#map_page body').first()) setup_google_map()
	if ($$('html#home body').first()) swfobject.embedSWF("swf/intro.swf", "main", "950", "550", "9.0.0", "/swf/expressInstall.swf", { map_url: "/map", register_url: "/contact"});
	if ($$('html#gallery body').first()) setup_pretty_pictures()
}

function setup_google_map() {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(37.4419, -122.1419), 13);
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.addControl(new GScaleControl());
    map.setCenter(new GLatLng(51.07397837820157, -114.093017578125), 14);
    GEvent.addDomListener($('zoomer'), "click", function() {
      map.setCenter(new GLatLng(51.05866005502052, -114.08735275268555), 13);
    })
		add_xml_markers(map)
		draw_transit_path(map)
		draw_bike_paths(map)
		draw_neighborhood_outline(map)
	}
	Event.observe($$('html#map_page body').first(), 'unload', GUnload)
}

function get_icon_for_marker(type) {
	var x = new GIcon()
  x.image = "/images/map/marker-" + type + ".png";
  x.shadow = "/images/map/marker-shadow.png";
  x.iconSize = new GSize(11, 25);
	x.shadowSize = new GSize(19, 24);
	x.iconAnchor = new GPoint(6, 25);
	x.infoWindowAnchor = new GPoint(5, 1);

	switch(type) {
		case 'condi':
	    x.shadow = "/images/map/house-shadow.png";
	    x.iconSize = new GSize(17, 27);
	    // x.shadowSize = new GSize(29, 27);
	    x.shadowSize = new GSize(0, 0);
	    x.iconAnchor = new GPoint(9, 27);
			break
		case 'hold':
	    x.shadow = "/images/map/house-shadow.png";
	    x.iconSize = new GSize(17, 27);
	    // x.shadowSize = new GSize(29, 27);
	    x.shadowSize = new GSize(0, 0);
	    x.iconAnchor = new GPoint(9, 27);
		break
		case 'spechome':
	    x.shadow = "/images/map/house-shadow.png";
	    x.iconSize = new GSize(17, 27);
	    // x.shadowSize = new GSize(29, 27);
	    x.shadowSize = new GSize(0, 0);
	    x.iconAnchor = new GPoint(9, 27);
		break
		case 'house':
	    x.shadow = "/images/map/house-shadow.png";
	    x.iconSize = new GSize(17, 27);
	    // x.shadowSize = new GSize(29, 27);
	    x.shadowSize = new GSize(0, 0);
	    x.iconAnchor = new GPoint(9, 27);
			break
		case 'salescentre':
    	x.shadow = "/images/map/house-shadow.png";
    	x.iconSize = new GSize(17, 27);
	    // x.shadowSize = new GSize(29, 27);
	    x.shadowSize = new GSize(0, 0);
    	x.iconAnchor = new GPoint(9, 27);
			break
		case 'showhome':
			x.shadow = "/images/map/house-shadow.png";
			x.iconSize = new GSize(17, 27);
	    // x.shadowSize = new GSize(29, 27);
	    x.shadowSize = new GSize(0, 0);
			x.iconAnchor = new GPoint(9, 27);
			break
		case 'sold':
			x.shadow = "/images/map/house-shadow.png";
			x.iconSize = new GSize(17, 27);
	    // x.shadowSize = new GSize(29, 27);
	    x.shadowSize = new GSize(0, 0);
			x.iconAnchor = new GPoint(9, 27);
			break
		case 'train':
			x.iconSize = new GSize(19, 19);
			x.iconAnchor = new GPoint(0, 0);
			x.infoWindowAnchor = new GPoint(10, 1);
			break
		case 'bike':
			x.iconSize = new GSize(26, 26);
			x.iconAnchor = new GPoint(13, 13);
			x.infoWindowAnchor = new GPoint(13, 1);
			break

		// case 'restaurant':
		// case 'golf':
		// case 'school':
		// case 'bank':
		// case 'shopping':
		// case 'health':
		// case 'grocery':
		// case 'recreation':
		// case 'bike':
	}
	return x
}

function add_xml_markers(map, mgr) {
	GDownloadUrl("/markers.cgi", function(data, responseCode) {
	if(responseCode == 200)
	{
		var xml = GXml.parse(data)
		var markers = xml.documentElement.getElementsByTagName("marker")
		var markerGroups = {
			'restaurant': [],
			'golf': [],
			'school': [],
			'bank': [],
			'shopping': [],
			'health': [],
			'grocery': [],
			'recreation': [],
			'train': [],
			'salescentre': [],
			'house': [],
			'showhome': [],
			'bike': [],
			'lot': [],
			'spechome': []
		}
		$A(markers).each(function(m){
			point = new GLatLng(parseFloat(m.getAttribute("lat")), parseFloat(m.getAttribute("lng")))
			marker = new LabeledMarker(point, { icon: get_icon_for_marker(m.getAttribute("type")),  labelText: m.getAttribute("label"), labelOffset: new GSize(-6, -10)} )
			marker.address = m.getAttribute("address")
			marker.name = m.getAttribute("name")
			marker.website = m.getAttribute("website")
			map.addOverlay(marker)
			if (m.getAttribute("show") != '1') { marker.hide() }
			type = m.getAttribute("type")
			if (type == 'sold') type = 'house'
			if (type == 'condi') type = 'house'
			if (type == 'hold') type = 'house'
			if (type == 'spechome') type = 'house'
			// marker.img = m.getAttribute("img")
			marker.type = type
			marker.img = ''
			if ((type == 'hold') || (type == 'house') || (type == 'salescentre') || (type == 'showhome')) {
				if (m.getAttribute("img") != '') marker.img = "/" + m.getAttribute("img") 
			} else {
				if (m.getAttribute("img") != '') marker.img = "/images/map/map-content/"  + m.getAttribute("img") + ".jpg"
			}

			if(markerGroups[type] != null)
			{
				markerGroups[type].push(marker)
				GEvent.addListener(marker, 'click', function() {
					html = '<table style="margin:0; padding:0; width:360px; height:130px"><tbody><tr>'
					if (this.img != '') html += '<td style="vertical-align:top; text-aling:left; padding:0 5px; font:normal 12px/18px Arial, Helvetica, sans-serif"><img src="' + this.img + '" alt="' + this.img + '" /></td>'
					html += '<td width="290px" style="vertical-align:top; text-aling:left; padding:0 5px; font:normal 12px/18px Arial, Helvetica, sans-serif"><h3 style="font:bold 14px/18px Helvetica, Arial, sans-serif; text-align:left">' + this.name + '</h3><p> ' + this.address + '<br / >Calgary Alberta</p>'
					if (this.website != null) html += '<p><a href="' + this.website + '">Visit ' + (this.type == 'house' ? 'Listing' : 'Website') + '</a></p>'
					html += '</td></tr></tbody></table>'
					this.openInfoWindowHtml(html)
				})
			}
			else
				alert(type);
		})
		$$('#main-sidebar input[type=checkbox]').each(function(check) {
			Event.observe(check, 'click', function(e) {
//alert(markerGroups[this.value]);
				if (markerGroups[this.value] != null && markerGroups[this.value].length > 0)
				{
					if( markerGroups[this.value].first().isHidden()) {
						markerGroups[this.value].each(function(marker){ marker.show() })
					} else {
						markerGroups[this.value].each(function(marker){ marker.hide() })
					}
				}
			})
		})
	}
	else
		alert("Data request timed out.  Please try again later.");
	})
	
	
}

function gup(name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
  return "";
  else
  return results[1];
}

function draw_transit_path(map) {
	[
		["ocqvHriiwTfD{_E", "PP", '#FFAA11'],
		["g~pvHvhcwT?ufM", "PP", '#990088'],
		["qa|vHx{wwT\\qBlAkFvBaIbFuNlFkLbJcQxWsh@jRw^bG{GlDcFlJuTpRk^tJsKj_@eYrb@i\\rPcMhAoA|@aCd@wD\\w\\b@mAn@e@~AMnBGx@e@l@yANiECiGXaKrAqHn@{FDmEHqUPoBn@eBlGcLfAuD^}E^qGl@iC|@cBjAgAlAe@zHkBdGe@pTQhEKpAYvHoDtAUhKB`Ah@t@X|@DbAEn@[T_@Rq@Jq@DqCn@k~@bBceBTw@f@m@l@]l@Gn@Lp@TzVlRvBJ|P`@v@P|ATjh@~AvARrBj@xDtA\\BjL_BfDYv@@rJwAlAi@r@Qt@BbA\\|NrJhEdCv@PlIpA`BfAtBhBrChBtBl@rEZle@rDpb@pCpc@vD|^jCvCt@jFxBrl@n^pI~ElAd@dMtCzQtEdPnDtGx@rJZnKs@vLiAnJoAzNcBzWqDrTuDjh@kOdJqA~YgDxH[~Nb@vFv@~DxAvKvElL|EtJrD|BN~BWxBk@rEaAf\\_IzPoDzCUdEObRLdNBzMItMAnESdCa@|EcArFgBbBw@", "P@ACBE@@DACCGD@@AHBDFBC?DBEAADAC?AEABD?CAHACEB@DABEC@BDBAI?BBADB@KB?CF@B?ADA@@FB@BB@BGA@D?D@@BG?AAAGAC@FA@CBICDA@@ECDAGCBE@?@CGB??AF@C?A?EB@CAP", '#001166']
	].each(function(path) {
		polyline = new GPolyline.fromEncoded({
			points: path[0],
			levels: path[1],
			color: path[2],
			opacity: 0.9,
			weight: 4,
			zoomFactor: 32,
			numLevels: 4
		})
		map.addOverlay(polyline)
	})
}

function draw_bike_paths(map){
	[
		["a}xvHrsfwT~F?bAfBfCjFtBxD|DdCfG`D~ElKRxDrC|BhByAx@X|AfCdAj@vAZtAjBbCxDrAdAp@`AzAxDmAxJ`@~@v@^|@?pDpBFrAvC~CdAjDhChIgAfKuCfBwD|J@dE", "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB"],
		["}nvvHpfkwT`@|A@tH_@~AaEPeAdB}BT{AbB_@vEOhTeApBcDZ_@X?xF[|@eA?EtIPtCEtIyFrNkGfO", "BBBBBBBBBBBBBBBBBBBBB"], 
		["erwvHrrnwTgEkEyE}B", "BBB"], 
		["mxwvHflnwTyAqH", "BB"], 
		["qrwvH|qkwTBgEIwALWa@[`@g@c@Of@Onc@F?~C", "BBBBBBBBBB"], 
		["gsvvHnakwTz@c@NyAp@gBJsA`@{@^e@`@iAP{@v@aBb@wBHcAOy@g@mAaB_CsAK", "BBBBBBBBBBBBBBBB"], 
		["aovvHfsjwTx@Sz@b@x@V", "BBBB"], 
		["q{uvH|bjwTq@Lk@l@aCC", "BBBB"], 
		["_mvvHb_jwT`@aCaAsDFeDOsA`@y@|A?ZPfAbA", "BBBBBBBBB"], 
		["movvHvzhwTqACq@b@eAK", "BBBB"], 
		["qawvHlbiwTl@cB\\iBCkA{AcDeFeBw@eAc@{BFoBb@mCa@eBKaA`@cAhBc@Tg@T_A", "BBBBBBBBBBBBBBBB"], 
		["ebwvHnthwTZaB?_B`C{B^{Ah@E", "BBBBBB"], 
		["}~vvHr{hwTxBChD@", "BBB"]
	].each(function(path) {
		polyline = new GPolyline.fromEncoded({
			color: "#FF0000",
			weight: 3,
			points: path[0],
			levels: path[1],
			zoomFactor: 32,
			numLevels: 4
		})
		map.addOverlay(polyline)
	})
}

function draw_neighborhood_outline(map) {
	polyline = new GPolyline.fromEncoded({
		color: "#000000",
		weight: 2,
		opacity: 0.8,
		points: "kzwvH`vpwT?oUlEuLcCiDfA{BkCsDrZmv@{DG?kLhCDPaNtAYNeEnFQ?PD_OhFu@JqRvBE?gHrAKAoApDqBbBHCoEjAO@_C}AF?sB|AQA{D}AFAoH_BHDmAuA?@mGcBIAiBeCNB{B}C[G{Fm@oAUaBEqDqAHSmCqCD_@eE_EPI}BuCk@EoHcD?@aDuGEQaIsB??uPzEFIwCiA@?}W`nA?Fv|FkAGGrFO`D_@nBs@xAkF|DfAjGq[`U]lEeHGBzDub@`[",
		levels: "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB",
		zoomFactor: 32,
		numLevels: 4
	})
	map.addOverlay(polyline)
}

function setup_pretty_pictures(){
	$$('#gallery-thumbs ul li img').each(function(e) {
		Event.observe(e, 'click', swap_image);
	})
	
	$$('#controls a').each(function(e) {
		Event.observe(e, 'click', control_image);
	})	
	disable_control($("prev"))
		
	if($$('#gallery-thumbs ul li').length > 4){
		$('up').show()
		$('down').show()
	}else{
		$('up').hide()
		$('down').hide()
	}
	
	Event.observe('up', 'click', function(e){
		new Effect.Scroll($('list'), {y:-520, delay:0, duration:0.5})
	})
	
	Event.observe('down', 'click', function(e){
		new Effect.Scroll($('list'), {y:520, delay:0, duration:0.5})
	})
}

function image_change(n, width, i){
	$$('#frame img')[0].fade({ duration: 2.0})
	setTimeout(function(){$$('#frame img').first().src = "/images/gallery/" + n; $$('#frame img').first().width = width;  $$('#frame img').first().setAttribute('rel', i)}, 2000)
	setTimeout(function(){$('frame').morph('width:'+ width + 'px')}, 2500)
	setTimeout(function(){$$('#frame img').first().appear()}, 2900)
	
	enable_control($("next"))
	enable_control($("prev"))
	if(i >= $$('#gallery-thumbs ul li').length-1) disable_control($("next"))
	if(i <= 0) disable_control($("prev"))
}

function swap_image(e){
	var n = this.src.split('/').last()
	var width = (this.ancestors().first().className == "tall") ? 383 : 680
	if(n != $$('#frame img').first().src.split('/').last()){
		image_change(n, width, this.getAttribute('rel'))
	}
	$('title').innerHTML = this.getAttribute('alt')
}

function disable_control(element){
	element.stopObserving('click', control_image)
	element.morph("color:#EFEFEF;")
}

function enable_control(element){
	element.observe('click', control_image)
	element.morph("color:#9BB500;")
}

function control_image(e){
	var i = parseInt($$('#frame img').first().getAttribute('rel'))
	if(this.id == "prev"){
		if(!(i % 4)){
			new Effect.Scroll($('list'), {y:-520, delay:0, duration:0.5})
		}
		i--;
		$('title').innerHTML = $$('#gallery-thumbs ul li img')[i].getAttribute('alt')
	}else if (this.id == "next"){
		i++;
		if(!(i % 4)){
			new Effect.Scroll($('list'), {y:520, delay:0, duration:0.5})
		}
		$('title').innerHTML = $$('#gallery-thumbs ul li img')[i].getAttribute('alt')
	}
	var n = $$('#gallery-thumbs ul li img')[i].src.split('/').last()
	var width = ($$('#gallery-thumbs ul li img')[i].ancestors().first().className == "tall") ? 383 : 680
	image_change(n, width, i)
}

document.observe('dom:loaded', init)
