var map,
	smallMap,
	geocoder = null,
	directionsRenderer = null,
	directionsService = null,
	infowindow = null,
	
	globalDistributorsMarkers = [],
	fluster,
	distrlogo,
	popup,
	routeToMarker = null,
	resultsPrintPageLink = '',
	resultsRoutePageLink = '';
	
var mapCenterLatLng = ['48.3794330', '31.1655800'];
	defaultZoom = 5,
	cityZoom = 11,
	maxZoom = 16;
var isIE6 = ($.browser.msie && parseInt($.browser.version) == 6);

function sendRequest(request, callback)
{
	$.ajax({
		type: "POST",
		url: EEHttp + "action.php",
		data: request,
		dataType: "json",
		success: function(response) {
			if (callback != "") {
				eval(callback);
			}
		}
	});
}

function citySearch(value, callback, type)
{
	callback = callback || "";
	geocoder.geocode({'address': "Украина, " + decodeURIComponent(value)}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			map.setCenter(results[0].geometry.location);
			map.setZoom(cityZoom);
		} else {
		}
	});

	var strAjaxMessage = "action=get_distributors_list&filter=city&value=" + encodeURIComponent(value) + "&language=" + language+'&type='+type;
	sendRequest(strAjaxMessage, callback);
}

function companySearch(value, callback, type)
{
	var strAjaxMessage = "action=get_distributors_list&filter=company&value=" + encodeURIComponent(value) + "&language=" + language+'&type='+type;
	sendRequest(strAjaxMessage, callback);
}

function idSearch(value, callback, type)
{
	var strAjaxMessage = "action=get_distributors_list&filter=record_id&value=" + encodeURIComponent(value) + "&language=" + language+'&type='+type;
	sendRequest(strAjaxMessage, callback);
}

function displayAllDistributors(filter, type)
{
	if (filter && filter.filter != '')
	{
		$('#' + filter.filter + '-label-container').show().siblings('div[id$="-label-container"]').hide();
		$('#' + filter.filter + '-label').html(filter.value);		
		eval(filter.filter + 'Search("' + encodeURIComponent(filter.value) + '", "setMarkers(response, true);' + (filter.filter != 'id' ? 'buildSearchResults(response);' : '') + '", '+type+');');
	} else if (filter) {
		var strAjaxMessage = "action=get_distributors_list&language=" + language+"&type="+type;
		sendRequest(strAjaxMessage, "setMarkers(response);");
	}
}

function getFilterFromURL()
{
	var filter = {'filter': '', 'value': ''};
	if (getParam('id') != '') {
		filter.filter = 'id';
		filter.value = getParam('id');
	} else if (getParam('company') != '') {
		filter.filter = 'company';
		filter.value = getParam('company');
	} else if (getParam('city') != '') {
		filter.filter = 'city';
		filter.value = getParam('city');
	}
	return filter;
}

function onCityChange()
{
	infowindow.close();
	var value = $(this).val();
	$(this).siblings("select").css("color","#999999").val("");
	$(this).css('color', value == '' ? '#999999' : '#000000');
	$('#city-label-container').show().siblings('#company-label-container').hide();
	var parent = $(this).parents('#search-box');
	if (parent.next('div').attr('id') == 'route-box') {
		return;
	}
	if (value == '') {
		initDistributorsMap(getFilterFromURL(), undefined, member_type);
	} else {
		initDistributorsMap(undefined, undefined, member_type);
		if (parent.length == 1 ) {
			$("#distributors-list-box").children(".middle-box-body").html('<div class="loader"></div>');
			$('#city-label').html(value);
			citySearch(value, "setMarkers(response, true); buildSearchResults(response);", member_type);
			$('#print-list-button-container').children('a').attr('href', getPrintLink(false, {'filter': 'city', 'value': value}));
		} else {
			citySearch(value, "setMarkers(response);", member_type);
		}
	}
}

function onCompanyChange()
{
	infowindow.close();
	var value = $(this).val();
	$(this).siblings("select").css("color","#999999").val("");
	$(this).css('color', value == '' ? '#999999' : '#000000');
	$('#company-label-container').show().siblings('#city-label-container').hide();
	var parent = $(this).parents('#search-box');
	if (parent.next('div').attr('id') == 'route-box') {
		return;
	}
	if (value == '') {
		initDistributorsMap(getFilterFromURL(), undefined, member_type);
	} else {
		initDistributorsMap(undefined, undefined, member_type);
		if (parent.length == 1) {
			$("#distributors-list-box").children(".middle-box-body").html('<div class="loader"></div>');
			$('#city-label').html("");
			companySearch(value, "setMarkers(response, true); buildSearchResults(response);", member_type);
			$('#print-list-button-container').children('a').attr('href', getPrintLink(false, {'filter': 'company', 'value': value}));
		} else {
			companySearch(value, "setMarkers(response);", member_type);
		}
	}
}

function onSearchClick()
{
	var company = $("#company :selected").attr("value");
	var city = $("#city :selected").attr("value");
	
	if (city != '' || company != '') {
		window.location = resultsPageLink + (adminTemplate == 'yes' ? '&' : '?') + (city != '' ? 'city=' + encodeURIComponent(city) : 'company=' + encodeURIComponent(company))+'&type='+member_type;
	}
}

function debug(object)
{
	msg = '';
	for (p in object) {
		msg = msg + p + ', ';
	}
	
	return msg;
}

function getBounds(map) {
	var bounds = map.getBounds();
	
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();
	
	//alert(southWest.lat() + "," + southWest.lng());
	//alert(northEast.lat() + "," + northEast.lng());

	points = fluster.markers;
	for (var i = 0; i < points.length; i++) {
		currPoint = points[i].getPosition();
		if (!bounds.contains(currPoint)) {
			bounds.extend(currPoint);
		}
	}	
	return bounds;
}

function setMarkers(markers, noClusters)
{
	globalDistributorsMarkers = [];
	markersData = markers.results;
	for (var i=0; i<markersData.length; i++)
	{
		createMarker(map, markersData[i], markers.additional, noClusters);
	}
	// Initialize Fluster
	// This will set event handlers on the map and calculate clusters the first time.
	fluster.initialize();
	if (globalDistributorsMarkers.length == 1) {
		map.setCenter(globalDistributorsMarkers[0].position);
		map.setZoom(16);
	}
}

function removeMarkers()
{
	markers = globalDistributorsMarkers;
	for (var i=0; i<markers.length; i++)
	{
		markers[i].setMap(null);
	}
}

function createMarker(map, markerData, additional, noClusters)
{
	var myLatlng = new google.maps.LatLng(markerData.latitude, markerData.longitude)
	var markerPoint = new google.maps.Marker({
						position: myLatlng,
						//map: map,
						icon: distrlogo,
						title: markerData.company,
						id: markerData.record_id
					});
	var contentString = '<div id="marker' + globalDistributorsMarkers.length + '_' + markerData.record_id + '" class="info-window-content">'+
							'<h1>' + markerData.company + '</h1>'+
								'<table>'+
									'<tr><td colspan="2">' + markerData.city + ', ' + markerData.address + '</td></tr>'+
									(markerData.phone ? '<tr><td>' + additional.phoneTitle + ':</td><td>' + markerData.phone + '</td></tr>' : '')+
									(markerData.additional_phone ? '<tr><td>' + additional.additionalPhoneTitle + ':</td><td>' + markerData.additional_phone + '</td></tr>' : '')+
									(markerData.website ? '<tr><td colspan="2"><a target="_blank" href="' + markerData.website + '">' + markerData.website + '</a></td></tr>' : '')+
								'</table>'+
								'<div class="distributor-actions">' +
									'<span class="route-action">X ' + additional.routeTitle + '</span>' +
									'<a target="_blank" href="' + getPrintLink(markerData) + '" class="print-action">X ' + additional.printTitle + '</a>' +
								'</div>'
						'</div>';
	google.maps.event.addListener(markerPoint, 'click', function() {
		map.setCenter(markerPoint.position);
		if (map.getZoom() >= maxZoom) {
			infowindow.setContent(contentString);
			infowindow.open(map, markerPoint);
			$(".route-action").click(onRouteClick);
			$(".print-action").click(onPrintClick);
		} else {
			map.setZoom(maxZoom);
		}
	});
	if (!noClusters && fluster) {
		fluster.addMarker(markerPoint);
	} else {
		markerPoint.setMap(map);
	}
	
	globalDistributorsMarkers.push(markerPoint);
}

function getParam(name) {
	if (window.location.search == '') {
		return "";
	}
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp(regexS);
	var tmpURL = window.location.search;
	var results = regex.exec(tmpURL);
	
	if(results == null) {
		return "";
	} else {
		return decodeURIComponent(results[1]);
	}
}

function getDistributorNo(value) {
	var regexS = "[a-z]*([0-9]+)_([0-9]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(value);
	if(results == null) {
		return "";
	} else {
		return [results[1], results[2]];
	}
}

function buildSearchResults(response)
{
	var result = '';
	results = response.results;
	for (var i=0; i<results.length; i++)
	{
		result = result +
				'<div id="distributor' + i + '_' + results[i].record_id + '" class="small-box">' +
					'<div class="small-box-head"><span>' + results[i].company + '</span></div>' +
					'<div class="small-box-body">' +
						'<p>' + results[i].address + '</p>' +
						'<p>' + results[i].city + '</p>' +
						'<p>' + results[i].postcode + '</p>' +
						'<p>' + response.additional.phoneTitle + ': ' + results[i].phone + '</p>' +
						(results[i].additional_phone != '' ?
						'<p>' + response.additional.additionalPhoneTitle + ': ' + results[i].additional_phone + '</p>'
						: ''
						) +
						'<div class="distributor-actions">' +
							'<p><span class="location-action">X ' + response.additional.locationTitle + '</span></p>' +
							'<p><span class="route-action">X ' + response.additional.routeTitle + '</span></p>' +
							'<p><a target="_blank" href="' + getPrintLink(results[i]) + '" class="print-action">X ' + response.additional.printTitle + '</a></p>' +
						'</div>' +
					'</div>' +
				'</div>';
	}
	$("#distributors-list-box").children(".middle-box-body").html(result);
	
	$(".route-action").click(onRouteClick);
	$(".location-action").click(onLocationClick);
	$(".print-action").click(onPrintClick);
}

function initDistributorsMap(filter, dontInitMarkers, type)
{

	if (geocoder == null) {
		geocoder = new google.maps.Geocoder();
	}
	if (directionsRenderer == null) {
		directionsRenderer = new google.maps.DirectionsRenderer();
	}
	if (directionsService == null) {
		directionsService = new google.maps.DirectionsService();
	}
	if (infowindow == null) {
		infowindow = new google.maps.InfoWindow({'maxWidth': 300});
	}
	
	var mapCenter = new google.maps.LatLng(mapCenterLatLng[0], mapCenterLatLng[1]);
		
	//Create an icon specifies the images used to display a GMarker on the map
	var myOptions = {
					zoom: defaultZoom,
					center: mapCenter,
					mapTypeId: google.maps.MapTypeId.ROADMAP,
					scaleControl: false
				};
	if ((isIE6 && !map) || !isIE6) {
		map = new google.maps.Map(document.getElementById("map-box"), myOptions);
	}
	distrlogo = new google.maps.MarkerImage(EEHttp + 'img/marker15.gif',
			new google.maps.Size(15, 15),
			new google.maps.Point(0, 0),
			new google.maps.Point(7, 7)
		);
	/*google.maps.event.addListener(map, 'tilesloaded', function() {
		var div = $('#map-box > div:first > div:first > div:nth-child(4)').children();
		if (div.length > 0) {
			for (var i=0; i < div.length; i++) {
				background_image = $(div[i]).css('background-image').replace('url(','').replace(')','');
				//$(div[i]).css('background-image', '');
				$(div[i]).html('<img src="' + background_image + '" width="15" height="15" />');
			}
		}
	});*/
	if (!dontInitMarkers) {
		fluster = new Fluster2(map);
		fluster.styles = {
			0: {image: EEHttp + 'img/marker20.gif', textColor: '#CA202E', width: 20, height: 20}
		};
		displayAllDistributors(filter, type);
	}
}

function onRouteClick() {
	infowindow.close();
	var id = $($(this).parents('div.info-window-content,div.small-box')[0]).attr('id');
	params = getDistributorNo(id);
	routeToMarker = globalDistributorsMarkers[parseInt(params[0])];
	popup.show();
	$('#route-start-point').focus();
}

function onLocationSubmit(event) {
	event.preventDefault();
	var filter = getFilterFromURL();
	var id = $($(this).parents('div.info-window-content,div.small-box')[0]).attr('id');
	params = getDistributorNo(id);
	var addressFrom;
//	addressFrom = $('#route-start-point').val();
	addressFrom = $(this).closest('form').children('input').val();

	addressTo = getParam('to').split(',');
	if (!routeToMarker || addressTo != '') {
		lat = addressTo[0];
		lng = addressTo[1];
		id = getParam('id');
	} else {
		lat = routeToMarker.position.lat();
		lng = routeToMarker.position.lng();
		id = routeToMarker.id;
	}
	if (addressFrom != '') {
		geocoder.geocode({'address': "Украина, " + addressFrom}, function(results, status) {
			if (status == google.maps.GeocoderStatus.OK) {
				window.location = 	resultsRoutePageLink + (adminTemplate == 'yes' ? '&' : '?') + 
									filter.filter + '=' + encodeURIComponent(filter.value) +
									'&from=' + encodeURIComponent(addressFrom) + 
									'&to=' + encodeURIComponent(lat + ',' + lng) +
									'&id=' + id;
			} else {
				alert("Пожалуйста проверьте правильность адреса");
			}
		});
	} else {
		alert("Пожалуйста проверьте правильность адреса");
	}
}

function buildRoute(addressFrom, addressTo) {
	directionTo = addressTo.split(',');
	routeTo = mapCenter = new google.maps.LatLng(directionTo[0], directionTo[1]);
	directionsRenderer.setMap(null);
	geocoder.geocode({'address': "Украина, " + addressFrom}, function(results, status) {
		if (status == google.maps.GeocoderStatus.OK) {
			directionsRenderer.setMap(map);
			directionsRenderer.setPanel($('#distributors-list-box > .middle-box-body')[0]);
			var request = {
				origin: results[0].geometry.location, 
				destination: routeTo,
				travelMode: google.maps.DirectionsTravelMode.DRIVING,
				unitSystem: google.maps.DirectionsUnitSystem.METRIC,
				provideRouteAlternatives: true
			};
			directionsService.route(request, function(response, status) {
				if (status == google.maps.DirectionsStatus.OK) {
					$('.loader').hide();
					$('#route-company-info').show();
					directionsRenderer.setDirections(response);
				} else {
					//alert('Error: ' + status);
				}
			});
		} else {
			alert("Пожалуйста проверьте правильность адреса");
		}
	});
	
	return false;
}

function onLocationClick() {
	var id = $($(this).parents('div.small-box')[0]).attr('id');
	params = getDistributorNo(id);
	routeToMarker = globalDistributorsMarkers[parseInt(params[0])];
	map.setZoom(maxZoom);
	google.maps.event.trigger(routeToMarker, 'click');
}

function getPrintLink(data, filter) {
	params = new Array();
	if (data) {
		params.push('id=' + data.record_id);
		params.push('city=' + encodeURIComponent(data.city));
		params.push('company=' + encodeURIComponent(data.company));
	}
	if (filter) {
		params.push(filter.filter + '=' + encodeURIComponent(filter.value));
	}
	return resultsPrintPageLink + (adminTemplate == 'yes' ? '&' : '?') + params.join('&');//(id ? 'id=' + id + '&' : '') + filter.filter + '=' + encodeURIComponent(filter.value);
}

function onPrintClick(event) {
	event.preventDefault();
	var left = parseInt(parseInt($(window).width())/2 - 335);
	var url = $(this).attr('href');
	newWindow = window.open(url, 'previewWindow', 'top=50, left=' + left + ', height=700, width=670, status=no, toolbar=no, menubar=no, location=no, scrollbars=yes');
	if (window.focus) {
		newWindow.focus()
	}
}

function onPrintButtonClick(event) {
	event.preventDefault();
	var div = $('#map-box > div:first > div:first > div:nth-child(4)').children().each(function () {
		background_image = $(this).css('background-image').replace('url(','').replace(')','');
		$(this).css('background-image', '');
		$(this).html('<img src="' + background_image + '" width="20" height="34" />');
	});
	window.print();
}

function onWindowCloseButtonClick(event) {
	event.preventDefault();
	window.close();
}

function initRoutePopup(id) {
	popup = new DanfossPopup($('#' + id).get(), {
		visible: false,
		centered: true,
		modal: true,
		width: 360
	});
	$(window).scroll(function () {
		popup.setCentered(popup);
	});
	$(window).resize(function () {
		popup.setCentered(popup);
	});
	$('#submit-button').click(onLocationSubmit);
	$("form#location-form").submit(onLocationSubmit);
}

