/*
 * Map functions V2
 *  
 */

atty = {

	urlMap : 'javascript/search/?map',
	urlName : 'javascript/search/?name',

	init : function () {

		var tab = $("#attytab").tabs();


		if (GBrowserIsCompatible()){

			atty.bindSearch();

			var m = $("#map").length;

			if (m == 1){
				mapObj.init("map", "37.0625", "-95.677068");

				if ($('#q2').attr('value').length > 0) {
					tab.tabs('select', '#attytab-2');
					$('#search2').trigger('click');
				} else if ($('#q').attr('value').length > 0) {
					$('#search1').trigger('click');
				} else {
					mapObj.mapPrintMap(4);
				}

			}


		} else {

			alert ('Your browser is too old to use the features on this page. You will need to update to newer browser in order to use this page.');

		}
		
	},

	bindSearch : function (){

		$('#attytab-1').each(function(){
			var form =  $('form', $(this));

			form.bind("keypress", function(e) {
				if (e.keyCode == 13) {
					$('#search1').trigger('click');
				return false;
				}
			});

			var fid = form.attr('id');
			$('#search1').click(function(){
				var error = formTools.check(fid, 'search1Error');
				if (error == 0) atty.attyAJAX(atty.urlMap, fid, 1);
				return false;
			});
		});

		$('#attytab-2').each(function(){
			var form =  $('form', $(this));

			form.bind("keypress", function(e) {
				if (e.keyCode == 13) {
					$('#search2').trigger('click');
				return false;
				}
			});

			var fid = form.attr('id');
			$('#search2').click(function(){
				var error = formTools.check(fid, 'search2Error');
				if (error == 0) atty.attyAJAX(atty.urlName, fid, 2);
				return false;
			});
		});

	},

	buildMap : function(data, center){


		$('#map').css({ 'visibility' : 'visible', 'display' : 'block' });

		var js = $(data).find('js').text();
		var msg = $(data).find('msg').text();

		mapObj.mapClearOverlay();

		var list = "";
		$(data).find('content item').each(function(){
			list += $(this).find('html').text();

			var i = $(this).find('index').text();
			var lat = $(this).find('lat').text();
			var lon =  $(this).find('lon').text();
			var pop =  $(this).find('pop').text();

			mapObj.mapPlotMarker(lat, lon, 'new', i, pop);

		});

		if (center) mapObj.mapResetCenter();

		if (msg != "") $('.nosearch').html(msg);

		var sr = $('.searchResults');

		if (sr.find('#list').length){
			$('.searchResults #list').html(list);
		} else {
			$('.searchResults').append($('<div>').attr('id', "list").html(list));
		}

//		eval(js);
		jQuery.globalEval(js);

	},

	buildName : function (data){

		var js = $(data).find('js').text();
		var msg = $(data).find('msg').text();
		var con = $(data).find('content').text();

		$('.nosearch').html(msg);

		var sr = $('.searchResults');

		sr.find('#map').css({ 'display' : 'none' });

		if (sr.find('#list').length){
			$('.searchResults #list').html(con);
		} else {
			$('.searchResults').html($('<div>').attr('id', "list").html(con));
		}

	},

	loadNames : function(page){

//			loader.attach($('.board .bLoader'), "boardList", page);
//			if (!loader.inCache() || force){
//				$.get('?posts&'+page, function(d){
//					loader.cache("boardList", page, d);
//					$('.board .bLoader').html(d);
//					loader.remove("boardList");
//					$('.bLoader').trigger('refresh');
//				});
//			}

		$('#search2').each(function(){
			var fid = $(this).closest('form').attr('id');
			var error = formTools.check(fid, 'search1Error');
			if (error == 0) atty.attyAJAX(atty.urlName+"&"+page, fid, 2);
			return false;
		});
		return false;
	},

	attyAJAX : function(url, id, type){
		var sr = $('.searchResults');
		loader.attach(sr, "results", "0");
		$.post(url, $("#"+id).serialize(), function (data){
			switch (type){
				case 1:
					atty.buildMap(data, 1);
					break;
				case 2:
					atty.buildName(data);
					break;
			}
			loader.remove("results");
		}, "xml");
		return false;
	}

};

mapObj = {

	init : function (id, lat, lon) {

		if (GBrowserIsCompatible()) {

			var body = document.getElementsByTagName('body');
			body[0].onunload = function () {
				GUnload();
			};

			this.id = id;
			this.lat = lat;
			this.lon = lon;
			this.dist = 8;
			this.map = new GMap2(document.getElementById(id));
			this.bounds = new GLatLngBounds();

			this.map.addControl(new GSmallMapControl());
//			this.map.setCenter(new GLatLng(this.lat, this.lon), this.dist);

			this.map.id = id;
			GEvent.addListener(this.map, "movestart", function() {
				if (document.getElementById(this.id + "1")) {
					var obj = document.getElementById(this.id + "1");
					var pObj = document.getElementById(this.id);
					pObj.removeChild(obj);
				}
			});
			GEvent.addListener(this.map, "zoomend", function() {
				if (document.getElementById(this.id + "1")) {
					var obj = document.getElementById(this.id + "1");
					var pObj = document.getElementById(this.id);
					pObj.removeChild(obj);
				}
			});

			GEvent.addListener(this.map, "dragend", function() {

				var zoom = mapObj.map.getZoom();
				if (zoom < 10) return;

				if (mapObj.loading) return;
				var center = mapObj.map.getCenter();
				var offset = mapObj.map.getBounds().getNorthEast();
				mapObj.loading = true;
				$.post(atty.urlMap, "lat="+center.lat()+"&lon="+center.lng()+"&yoff="+offset.lat()+"&xoff="+offset.lng(), function (data){
					atty.buildMap(data);
					mapObj.loading = false;
				}, "xml");

			});
		}
	},

	mapPrintMap : function (zoom) {
		this.mapPlaceCenter(this.lat, this.lon, zoom);
	},

	mapResetCenter : function (){
		var center = this.bounds.getCenter();
		this.mapPlaceCenter(center.lat(), center.lng());
	},

	mapPlaceCenter : function(lat, lon, zoom){
//		this.map.setCenter(new GLatLng(this.lat, this.lon), this.dist);
		var loc = new GLatLng(lat, lon);
		var icon = this.mapSetIcon("myloc", 0);
		var marker = new GMarker(loc, icon)
		this.bounds.extend(marker.getPoint());
		this.map.addOverlay(marker);
		if (zoom == undefined) {
			zoom = this.map.getBoundsZoomLevel(this.bounds);
			if (zoom > 14) zoom = 14;
		}

//		this.map.setZoom(zoom);
//		this.map.setCenter(this.bounds.getCenter());
		var center = this.bounds.getCenter();
		this.map.setCenter(new GLatLng(center.lat(), center.lng()), zoom);
	},

	mapPlotMarker : function (lat, lng, icon, id, info) {

		var obj = this.id;
		var loc = new GLatLng(lat, lng);
		var icon = this.mapSetIcon(icon, id);
		var marker = new GMarker(loc, icon);
		var bounds = this.map.getBounds();
		marker.width = parseInt(document.getElementById(this.id).style.width);
		marker.height = parseInt(document.getElementById(this.id).style.height);
		marker.mid = this.id;
		marker.map = this.map;
		marker.lid = id;
		marker.html = info;
		GEvent.addListener(marker, "mouseover", this.mapListenerBox);
		GEvent.addListener(marker, "mouseout", this.mapListenerBoxClose);
		GEvent.addListener(marker, "click", this.mapListenerLoad);

		this.bounds.extend(marker.getPoint());
		this.map.addOverlay(marker);
	},

	mapListenerBox : function () {

		var close_onclick = function () {
			var obj = document.getElementById(this.pid);
			obj.parentNode.removeChild(obj);
		};

		if (document.getElementById(this.mid + "1")) {
			var oldObj = document.getElementById(this.mid + "1");
			oldObj.parentNode.removeChild(oldObj);
		}

		var oldObj = document.getElementById(this.mid + "1");
		var bounds = this.map.getBounds();

		var right = bounds.getNorthEast().lng();
		var top = bounds.getNorthEast().lat();
		var left = bounds.getSouthWest().lng();
		var bottom = bounds.getSouthWest().lat();

		var lat = this.getPoint().lat();
		var lng = this.getPoint().lng();
		if (right > left) {
			var xOffset = Math.floor(( ( lng - left ) / ( right - left ) ) * this.width);
		} else {
			var l2 = 180 - left;
			if (lng < 0) {
				var lng2 = Number(l2) + 180 + Number(lng);
			} else {
				var lng2 = lng - left;
			}
			var tw = Number(l2) + 180 + Number(right);
			var xOffset = Math.floor(( lng2 / tw ) * this.width);
		}

		var yOffset = Math.floor(( ( lat - top ) / (bottom - top) ) * this.height);

		var obj = document.createElement("div");
		obj.style.position = "absolute";
		obj.style.top = (yOffset - 15) + "px";
		obj.style.left = (xOffset + 10) + "px";
		obj.style.width = "250px";
		obj.innerHTML = '<div style="border: 3px solid #555555; background-color: #eeeeee;">' + this.html + '</div>';
		obj.id = "mappopup";
		obj = mapObj.mapPNGConvert(obj);
		document.getElementById(this.mid).appendChild(obj);
	},

	mapListenerBoxClose : function () {
		var popup = document.getElementById("mappopup");
		if (popup) popup.parentNode.removeChild(popup);
	},

	mapListenerLoad : function () {

		for (var i = 0; i < 25; i++) {
			var obj = document.getElementById("r" + (i + 1));
			if (obj) {
				if (this.lid == i + 1) {
					obj.style.backgroundColor = "#e8edfd";
				} else {
					obj.style.backgroundColor = "#ffffff";
				}
			}
		}

		document.location.replace("#" + this.lid);

		return false;

	},

	mapClearOverlay : function () {
//		alert (this.map);
		if (this.map != undefined){
			this.map.clearOverlays();
			this.bounds = new GLatLngBounds();
		} else {
			var a = $('.attyinfo');
			a.before($('<div id="map">').css({ width: '759px', height: '400px' }));
			a.remove();
			mapObj.init("map", "37.0625", "-95.677068");
//			this.map.clearOverlays();
//			mapObj.mapPrintMap(4);
		}
	},

	mapSetDist : function (dist) {
		this.dist = dist;
	},

	mapSetIcon : function (schema, id) {

		// Create our "tiny" marker icon
		var icon = new GIcon();

		switch (schema) {
			case "myloc":
				icon.iconSize = new GSize(16, 15);
				icon.iconAnchor = new GPoint(8, 7);
				icon.infoWindowAnchor = new GPoint(8, 7);
				icon.image = "http://www.nacba.org/attorneyfinder/images/markers/myloc.png";
				break;
			case "new":
				icon.iconSize = new GSize(20, 20);
				icon.iconAnchor = new GPoint(10, 10);
				icon.infoWindowAnchor = new GPoint(10, 10);
				icon.image = "http://www.nacba.org/attorneyfinder/images/markers/new" + id + ".png";
				break;
		}

		return icon;
	},

	mapPNGConvert : function (info) {

		var arVersion = navigator.appVersion.split("MSIE");
		var version = parseFloat(arVersion[1]);

		if ((version >= 5.5) && (document.body.filters)) {

			var imgs = info.getElementsByTagName("img");

			for (var i = 0; i < imgs.length; i++) {
				var img = imgs[i];
				var imgName = img.src.toUpperCase();
				if (imgName.substring(imgName.length - 3, imgName.length) == "PNG") {
					var imgID = (img.id) ? "id='" + img.id + "' " : "";
					var imgClass = (img.className) ? "class='" + img.className + "' " : "";
					var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
					var imgStyle = "display:inline-block;" + img.style.cssText;
					if (img.align == "left") imgStyle = "float:left;" + imgStyle;
					if (img.align == "right") imgStyle = "float:right;" + imgStyle;
					if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle;
					var strNewHTML = "<span " + imgID + imgClass
							+ " style=\"" + "width:" + img.parentElement.width + "px; height:" + img.parentElement.height + "px;" + imgStyle + ";"
							+ "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
							+ "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>";
					img.outerHTML = strNewHTML;
					i = i - 1;
				}
			}
		}

		return info;
	},

	mapDirSimple : function (lat, lng, dirto) {
		if (GBrowserIsCompatible()) {
			var map = new GMap2(document.getElementById("minimap"));
			map.addControl(new GSmallMapControl());
			map.setCenter(new GLatLng(lat, lng), 15);
			if (dirto != false) {
				var directionsPanel = document.getElementById("directions");
				var directions = new GDirections(map, directionsPanel);
				directions.load(dirto);
			} else {
				var loc = new GLatLng(lat, lng);
				map.addOverlay(new GMarker(loc));
			}
		}
	}
};

$(function(){
	atty.init();
});
