//flash
var uid = "_" + new Date().getTime();
var searchPath = "http://cache.travelersinsynch.com/findagent/v2/SearchWidget.swf";
var countryPath = "http://cache.travelersinsynch.com/findagent/v2/CountryView.swf";
//var searchPath = "/findagent/files/SearchWidget.swf";
//var countryPath = "/findagent/files/CountryView.swf";
var flashProxy = new FlashProxy(uid, '/findagent/js/JavaScriptFlashGateway.swf');
var sessionhash = null;
document.countryProxy = new FlashProxy(uid + "b", '/findagent/js/JavaScriptFlashGateway.swf');
if(commercial == 'true'){
	document.lastFilter = {filter_type: "product", filter_index: 0};
}else{
	document.lastFilter = {filter_type:"business", filter_index:0};
}
function initWindow(){
	if(flashProxy && document.countryProxy){
		var so = new SWFObject(searchPath, uid, "214", "420", "8.0.24", "#252525");
		so.setAttribute('redirectUrl','/findagent/no_flash.html')
		so.addParam("wmode", "transparent");
		so.addParam("allowScriptAccess", "always");
		so.addVariable("uid", uid);
		so.addVariable("commercial",commercial);		
		so.write("search");
		
		var so = new SWFObject(countryPath, uid + "b", "850", "445", "8.0.24", "#252525");
		so.setAttribute('redirectUrl','/findagent/no_flash.html')
		so.addParam("wmode", "transparent");
		so.addParam("allowScriptAccess", "always");
		so.addVariable("uid", uid + "b");
		so.addVariable("commercial",commercial);		
		if(readCookie('travelers')){
			so.addVariable("returning", true);		
		}else{
			createCookie('travelers',true,3);
		}
		so.write("country_view");
		if(readCookie('sessionhash')){
			sessionhash = readCookie('sessionhash');
		}
	}else{
		$("#country_view img,#search img").attr({ src: "/findagent/img/no_flash.gif"});
	}
}

//map functions
var map;
var centerLatitude = 39.16414104768742;
var centerLongitude = -94.482421875;
var startZoom = 4;
//map data
var existingMarkers = {'m':[],'s':[],'c':[]};
var resultsMarkers = {};
var cityList = new Array();
var resultsInBound = 0;
//flash event tracker
var map_events = [];
map_events['marker_clicked'] = 0;
map_events['city_clicked'] = 0;
map_events['form_search'] = false;
var newwindow = '';
//Create an icon for the clusters
var iconCluster = new GIcon();
iconCluster.image = "/findagent/img/cluster_icon.png";
iconCluster.iconSize = new GSize(27, 23);
iconCluster.iconAnchor = new GPoint(12, 20);
iconCluster.infoWindowAnchor = new GPoint(13, 1);

//create an icon for the pins
var iconSingle = new GIcon();
iconSingle.image = "/findagent/img/single_icon.png";
iconSingle.iconSize = new GSize(29, 23);
iconSingle.iconAnchor = new GPoint(12, 20);
iconSingle.infoWindowAnchor = new GPoint(13, 1);

//create an icon for the search results
iconResult = new GIcon();
iconResult.image = "/findagent/img/cluster_icon.png";
iconResult.iconSize = new GSize(27, 23);
iconResult.iconAnchor = new GPoint(12, 20);
iconResult.infoWindowAnchor = new GPoint(13, 1);

function init() {
	map = new GMap2(document.getElementById("map"));
	map.addControl(new GLargeMapControl(),new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(5,-60)));  
	map.setCenter(new GLatLng(centerLatitude, centerLongitude), startZoom);
	
	GEvent.addListener(map,'zoomend',function(){
		if(map.getZoom() <= 7 ){
			returnToCountry();
		}else if(map_events['marker_clicked'] == 0 && map_events['city_clicked'] == 0 && map_events['form_search']  == false){
			updateMarkers();
		}else{
			map_events['marker_clicked'] = 0;
		}
	});
	
	GEvent.addListener(map,'moveend',function(){
		if(map_events['marker_clicked'] == 0 && map_events['city_clicked'] == 0 && map_events['form_search']  == false){
			updateMarkers();
		}else{
			map_events['marker_clicked'] = 0;
		}
	});

	GEvent.addListener(map,'click',function(overlay,point){
		if(overlay){
			if(overlay.TravelersWindowInstance){
				$(".company").css({ width: overlay.TravelersWindowInstance.width_, display: "block" });
				$("#fromHere,#toHere,.url").bind('click',function(){
					if(overlay.TravelersWindowInstance.agent_){
						if($(this).attr('id')){
							popup(overlay.TravelersWindowInstance.agent_,$(this).attr('id'));
						}else{
							popup(overlay.TravelersWindowInstance.agent_,$(this).attr('class'));
						}
					}
					return false;
				});
			}
		}
		console.log(map.getBounds()+":"+map.getCenter());
	});
}

function swfTrace(msg, data){
	//console.log("SWF TRACE-- "+ msg, data);
}

function loadCities(callFrom){
	if(document.mute){
		var muteStatus = "true";
	}
	document.countryProxy.call("setCities", cityList, document.lastFilter, muteStatus);
	flashProxy.call("setCities", cityList);
}

function popup(agent,id){
	var daddr = '';
	var saddr = '';
	var url = '';
	if(id == "fromHere" || id == "toHere"){
		var address =  Url.encode(agent.address1+', '+agent.city+', '+agent.state+' '+agent.zip);
		if(id == "fromHere"){
			saddr = address;
		}else{
			daddr = address;
		}
		url = 'http://maps.google.com/maps?saddr='+saddr+'&daddr='+daddr;
	}else{
		url = agent.web.replace('http://','');
		url = 'http://'+url;
	}
	if(url.length > 0){
		window.open(url);
	}
	return false;
}
function updateMarkers(city) {
	//create the boundry for the data to provide
	//initial filtering
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	var getVars = 'ne=' + northEast.toUrlValue()
	+ '&sw=' + southWest.toUrlValue();
	var request_url = '';
	if(city != null){
		southWest = city.sw_lat+','+city.sw_lng;
		northEast = city.ne_lat+','+city.ne_lng;
		getVars = 'ne=' + northEast	+ '&sw=' + southWest;
	}
	
	//retrieve the points
	if(city == null){
		request_url = '/findagent/index.php/maps/createCluster/?'+getVars;
		request_url += '&sessionhash='+sessionhash;
	}else{
		request_url = '/findagent/index.php/maps/getCluster/'+city.id;
		request_url += '/?sessionhash='+sessionhash;
	}
	
	$.ajax({ 
	  type: "GET", 
	  dataType: "json",
	  url: request_url, 
	  success: function(points){
			plotMarkers(points,1);
			if(existingMarkers["s"].length > 0)
			{
				plotMarkers(existingMarkers["s"]);
			}
		}
	});
}

function plotMarkers(points,clear){
	resultsInBound = 0;
	var mapBounds = map.getBounds();
	if(clear){
		for (k in existingMarkers){
			for (i in existingMarkers[k]){
				//remove cluster and out of bound points
				if(!mapBounds.contains(existingMarkers[k][i].getPoint()) || k == "c" || k == "m"){
					if(k == "m" || k == "c"){
						existingMarkers[k][i].removeCounter();
						map.removeOverlay(existingMarkers[k][i]);
						delete existingMarkers[k][i];
					}
				}
			}
		}
	}
	var resultCount = 1;
	for (k in points) {
		var point = new GLatLng(points[k].lat,points[k].lng);
		var html = null;
		if(mapBounds.contains(point) || points[k].type == "s") {
			if((points[k].type == "m" && !existingMarkers["s"][points[k].agent.id]) || points[k].type == "s"){
				existingMarkers[points[k].type][points[k].agent.id] = createMarker(point,points[k].type,points[k].agent);
				if(points[k].type == "s"){
					if(mapBounds.contains(point)){
						resultsInBound++;
					}
					existingMarkers[points[k].type][points[k].agent.id].showResultFlag(resultCount);
					resultCount++;
				}
				map.addOverlay(existingMarkers[points[k].type][points[k].agent.id]);
			}else if(points[k].type == "c"){
				existingMarkers[points[k].type][k] = createMarker(point,points[k].type);
				existingMarkers[points[k].type][k].showCounter(points[k].cluster_count);
				map.addOverlay(existingMarkers[points[k].type][k]);
			}
		}
	}
}

function createMarker(point, type, agent) {
	//create the marker with the appropriate icon
	if(type=='c') {
		var marker = new GMarker(point,{icon:iconCluster,clickable:true});
	} else if(type == 's'){
		var marker = new GMarker(point,{icon:iconResult,clickable:true});
	}else {
		var marker = new GMarker(point,{icon:iconSingle,clickable:true});
	}
	if((type == "m" || type == "s") && agent != null){
		GEvent.addListener(marker, 'click',function(){
			var markerAgent = agent;
			map_events['marker_clicked'] = 1;
			marker.openTravelersWindow(markerAgent);
		});
	}else if(type == "c"){
		GEvent.addListener(marker, 'click',function(){
			zoomOnCluster(point);
		});

	}
	return marker;
}

function clearExistingResults(){
	for (i in existingMarkers["s"])
	{
		existingMarkers["s"][i].removeResultFlag();
		map.removeOverlay(existingMarkers["s"][i]);
		existingMarkers["s"][i].closeTravelersWindow();
		delete existingMarkers["s"][i];
	}
}

function zoomOnCluster(point)
{
	var zoom_level = map.getZoom();
	zoom_level++;
	map_events['marker_clicked'] = 1;
	map.setCenter(point,zoom_level);
}

function zoomOnAgent(point)
{
	map.getInfoWindow().remove();
	if(existingMarkers["s"][point.id]){
		map_events['marker_clicked'] = 1;
		map.setCenter(existingMarkers["s"][point.id].getPoint(),13);
		GEvent.trigger(existingMarkers["s"][point.id], "click"); 
	}
}

function setFilter(params){
	search_params = searchParamsToUrl(params);	
	// TO IMPLEMENT:
	// 1. Send AJAX call to set filter for all future returned clusters and cities
	// 2. Add AJAX call to returnToCountry() to reset filter to default
	document.lastFilter = params;
	var request_url = '/findagent/index.php/maps/setFilter/?'+search_params.substr(1);
	request_url += '&sessionhash='+sessionhash;
	$.getJSON(request_url,function(results){
		updateMarkers();
		});
	flashProxy.call("synchForm", params);
}

function findByRadius(params){
	search_params = searchParamsToUrl(params);
	//reset search results
	clearExistingResults();
	map.clearOverlays();
	var request_url = '/findagent/index.php/maps/getAgentsByRadius/?'+search_params.substr(1);
	request_url += '&sessionhash='+sessionhash;
	$.getJSON(request_url,function(results){
		if(results.error){
			results2 = {status: 400,data:[results.error]}
		}else{
			if(results.request.reqlat.length > 0 && results.request.reqlng.length >0){
				map_events['form_search'] = true;
				var zoom_level;
				if(Number(params.distance) <= 10){
					zoom_level = 13;
				}else if (Number(params.distance) > 10 && Number(params.distance) <= 20){
					zoom_level = 12;
				}else{
					zoom_level = 11;
				}
				map.setCenter(new GLatLng(parseFloat(results.request.reqlat), parseFloat(results.request.reqlng)),zoom_level);
				plotMarkers(results.points,1);
				if(resultsInBound > 0){
					map.setCenter(new GLatLng(parseFloat(results.request.reqlat), parseFloat(results.request.reqlng)),zoom_level);
				}else{
					var point = {"id":Number(results.points[0].agent.id)};
					zoomOnAgent(point)
				}
				map_events['form_search'] = false;
			}
			results2 = {status: 200,data:[]}
			for(i in results.points){
				results.points[i].agent.address = results.points[i].agent.address1 +' '+results.points[i].agent.address2;
				results2.data[i] = results.points[i].agent;
			}
		}
		$("#country_view:visible").hide();
		$("#refresh_control:hidden").show();
		$("#map_control:hidden").show();
		flashProxy.call("showResults",results2);		
		delete results;
		delete results2;
	});
}
		
function findByName(params){
	search_params = searchParamsToUrl(params);
	//reset search results
	clearExistingResults();
	$("#country_view:visible").hide();
	$("#refresh_control:hidden").show();
	$("#map_control:hidden").show();
	var request_url = '/findagent/index.php/maps/getAgentsByRadius/?'+search_params.substr(1);
	request_url += '&sessionhash='+sessionhash;
	$.getJSON(request_url,function(results){
		if(results.error){
			results2 = {status: 400,data:[results.error]}
		}else{
			if(results.request.reqlat.length > 0 && results.request.reqlng.length >0){
				var point = {"id":Number(results.points[0].agent.id)};
				plotMarkers(results.points,1);
				map_events['form_search'] = true;
				zoomOnAgent(point);
				map_events['form_search'] = false;
			}
			results2 = {status: 200,data:[]}
			for(i in results.points){
				results.points[i].agent.address = results.points[i].agent.address1 +' '+results.points[i].agent.address2;
				results2.data[i] = results.points[i].agent;
			}
		}
		flashProxy.call("showResults",results2);
		document.countryProxy.call("showResults", results2);
					
		delete results;
		delete results2;
	});
}

function showCity(params){
	clearExistingResults();
	$.getJSON('/findagent/index.php/cities/getCityView/?city='+params+'&sessionhash='+sessionhash,function(city){
		var zoom_level = Number(city.zoom_level);
		map_events['city_clicked'] = 1;
		map.setCenter(new GLatLng(city.center_lat, city.center_lng),zoom_level);
		$("#country_view:visible").hide();
		$("#refresh_control:hidden").show();
		$("#map_control:hidden").show();
		updateMarkers(city);
		map_events['city_clicked'] = 0;
		city = null;
	});	
}

function returnToCountry(){
	var html_ = '<img src="/findagent/img/loading.gif" border="0" alt="" usemap="#no_flash">';
	$("#country_view:hidden").empty().append(html_);
	$("#country_view:hidden").show();
	$("#refresh_control:visible").hide();
	$("#map_control:visible").hide();

	var uid = "_" + new Date().getTime();
	document.countryProxy = new FlashProxy(uid + "b", '/findagent/js/JavaScriptFlashGateway.swf');

	var so = new SWFObject(countryPath, uid + "b", "850", "445", "8", "#252525");
	so.addParam("wmode", "transparent");
	so.addParam("allowScriptAccess", "always");
	so.addVariable("uid", uid + "b");
	so.addVariable("commercial",commercial);		
	so.addVariable("refreshing", "true");
	if(readCookie('travelers')){
		so.addVariable("returning", true);		
	}else{
		createCookie('travelers',true,3);
	}
	so.write("country_view");
	flashProxy.call("reset");
}

function toggleMute(){
	if(document.mute){
		document.mute = false;
		document.countryProxy.call("unmute");
	}else{
		document.mute = true;
		document.countryProxy.call("mute");
	}
}

function searchParamsToUrl(params){
	var allowed_params = ["address","city","state","zip","distance","filter","name"];
	var search_params = '';
	var i;
	for(i in allowed_params)
	{
		if(allowed_params[i] in params){
			if(params[allowed_params[i]] != ''){
				search_params = search_params+"&"+allowed_params[i]+"="+params[allowed_params[i]];
			}
		}
	}
	return search_params;
}

$(document).ready(function () {
	$.ajax({ 
	  type: "GET", 
	  url: "/findagent/index.php/cities/getCities/", 
	  dataType : "json",
	  success: function(results){cityList = results},
	  complete : function(){initWindow(); init();} 
	});
	$("#MapTypeSatellite").bind('click',function(){
		if(map.getCurrentMapType() != "G_SATELLITE_MAP"){
			map.setMapType(G_SATELLITE_MAP);
			$(this).css("font-weight", "bold");
			$("#MapTypeStreet").css("font-weight", "normal");
		}
		return false;
	});
	$("#MapTypeStreet").bind('click',function(){
		if(map.getCurrentMapType() != "G_NORMAL_MAP"){
			map.setMapType(G_NORMAL_MAP);
			$(this).css("font-weight", "bold");
			$("#MapTypeSatellite").css("font-weight", "normal");
		}
		return false;
	});
	$("#Refresh").bind('click',function(){
		returnToCountry();
		return false;
	});
	$("#SoundToggle").bind('click',function(){
		toggleMute();
		return false;
	});
	document.mute = false;
	$("#refresh_control:visible").hide();
	$("#map_control:visible").hide();
	$(window).bind('unload', GUnload);
});