// lokola.js
// author Martin Svihla

FastInit.addOnLoad(loadAll);

var map;
var mapcenter;

var lat;
var lon;
var zoom;

var letters = new Array();

var baseurl = "http://www.lokola.cz";

var texts = new Array();

var zooms = new Array();
var places = new Array();
var markers = new Array();
var markersSel = new Array();
var placesConfirmed = new Array();

var votes_to_confirm_place;

var runnerPlaces = new Array('107','166','226','284','342','400','458');

var homeDeleted = false;
var officeDeleted = false;

var whatDeleted = false;
var whereDeleted = false;

function showAndHide(id, slide) {
	var element = document.getElementById(id);
	if (element.style.display == 'block') {
		element.style.display = 'none';
	} else {
		element.style.display = 'block';
	}
}


function loadAll(event) {

	if ($('mapa')) {
		loadMap();
	}

	if ($('spinner1')) {
		var mapOffset = Element.getHeight('topdiv');
		$('spinner1').setStyle('top: ' + (mapOffset + 332) + 'px');
		var windowWidth = (document.viewport.getWidth());
		$('spinner1').setStyle('left: ' + ((windowWidth / 2) + 57) + 'px');
		$('spinner1').hide();
	}
	if ($('spinner2')) {
		var mapOffset = Element.getHeight('topdiv');
		var mapHeight = Element.getHeight('mapa');
		$('spinner2').setStyle('top: '+(mapOffset+380+mapHeight)+'px');
		$('spinner2').hide();
	}
	if ($('spinner3')) {
		var offset = Element.positionedOffset('google');
		$('spinner3').setStyle('top: '+(offset['top']+30)+'px');
		$('spinner3').hide();
	}
//if ($('PlacesWhat')) {
//	$('PlacesWhat').focus();
//}

	
}





function highlightWhereButton() {
	clearWhereButtons();
	if ($('wherediv')) $('wherediv').addClassName('item-a2');
	if ($('wherediv2')) $('wherediv2').addClassName('item-a2');
}

function highlightHomeButton() {
	clearWhereButtons();
	if ($('wherediv')) $('homediv').removeClassName('item2').addClassName('item-a2');
	if ($('wherediv2')) $('homediv2').removeClassName('item2').addClassName('item-a2');
}

function highlightOfficeButton() {
	clearWhereButtons();
	if ($('wherediv')) $('officediv').removeClassName('item2').addClassName('item-a2');
	if ($('wherediv2')) $('officediv2').removeClassName('item2').addClassName('item-a2');
}

function clearWhereButtons() {
	if ($('wherediv')) {
		$('wherediv').removeClassName('item-a2').addClassName('item2');
		$('homediv').removeClassName('item-a2').addClassName('item2');
		$('officediv').removeClassName('item-a2').addClassName('item2');
	}
	if ($('wherediv2')) {
		$('wherediv2').removeClassName('item-a2').addClassName('item2');
		$('homediv2').removeClassName('item-a2').addClassName('item2');
		$('officediv2').removeClassName('item-a2').addClassName('item2');
	}
}

function pressHomeButton(homeString) {
	if (homeDeleted) {
		//alert('del');
		homeDeleted = false;


		new Ajax.Updater('homediv', baseurl+'search/deleteHome', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'homediv']});
		new Ajax.Updater('homediv2',baseurl+'search/deleteHome', {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'homediv2']});
		highlightWhereButton();
	} else {
		if ($('PlacesWhere')) {
			$('PlacesWhere').clear();
			$('PlacesWhere').value = homeString;
		}
		if ($('PlacesWhere2')) {
			$('PlacesWhere2').clear();
			$('PlacesWhere2').value = homeString;
		}
		highlightHomeButton();
	}
}

function pressOfficeButton(officeString) {
	if (officeDeleted) {
		//alert('del');
		officeDeleted = false;
		new Ajax.Updater('officediv', baseurl + 'search/deleteOffice',
							{asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'officediv']});
		new Ajax.Updater('officediv2', baseurl + 'search/deleteOffice',
							{asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'officediv2']});
		highlightWhereButton();
	} else {
		if ($('PlacesWhere')) {
			$('PlacesWhere').clear();
			$('PlacesWhere').value = officeString;
		}
		if ($('PlacesWhere2')) {
			$('PlacesWhere2').clear();
			$('PlacesWhere2').value = officeString;
		}
		highlightOfficeButton();
	}
}

function showGoogleSpinner() {
	var offset = $('google').positionedOffset();
	var topoff = offset['top']+50;
	$('spinner3').setStyle({
		top:topoff+'px'
	});
	$('spinner3').show();
}

function createPlaceWindow(placeid) {
	var out = '<div class="bubbleFrame">';
	
	for (var i=0, len=places[placeid].length; i<len; i++) {
		out += '<div class="bubbleItem">';
		out += '<b>' + places[placeid][i]['name'] + '</b><br/>' +
		places[placeid][i]['address'] + '<br/>' +
		'<a href="' + baseurl + 'detail/'+places[placeid][i]['friendly_url'] + '">' + texts['Detail'] + '</a>';

		/*if (places[placeid][i]['confirmed'] < votes_to_confirm_place && placesConfirmed.indexOf(parseInt(places[placeid][i]['id'])) == -1) {
			out += '<br/><a href="" id="confirm-button-'+places[placeid][i]['id']+'" onclick="confirmPlace('+places[placeid][i]['id']+'); placesConfirmed.push('+places[placeid][i]['id']+'); this.hide(); $(\'thanks-'+places[placeid][i]['id']+'\').show(); return false;">'+ texts['Confirm place'] +'</a>'+
			'<span id="thanks-'+placeid+'" style="display: none;">'+texts['Thank you']+'</span>';

		}*/
		out += '</div>';
	}
	out += '</div>';
	return out;

}

function createPlaceWindowLogo(placeid) {
	var out = '<div class="bubbleFrame">';
	
	for (var i=0, len=places[placeid].length; i<len; i++) {
		out += '<div class="bubbleItem">';
		out += '<img class="bubbleLogo" src="/img/logos/big/'+places[placeid][i]['logo']+'" /><br/>';
		out += '<b>' + places[placeid][i]['name'] + '</b><br/>' +
		places[placeid][i]['address'] + '<br/>' +
		'<a href="' + baseurl + 'detail/'+places[placeid][i]['friendly_url'] + '">' + texts['Detail'] + '</a>';

		/*if (places[placeid][i]['confirmed'] < votes_to_confirm_place && placesConfirmed.indexOf(parseInt(places[placeid][i]['id'])) == -1) {
			out += '<br/><a href="" id="confirm-button-'+places[placeid][i]['id']+'" onclick="confirmPlace('+places[placeid][i]['id']+'); placesConfirmed.push('+places[placeid][i]['id']+'); this.hide(); $(\'thanks-'+places[placeid][i]['id']+'\').show(); return false;">'+ texts['Confirm place'] +'</a>'+
			'<span id="thanks-'+placeid+'" style="display: none;">'+texts['Thank you']+'</span>';

		}*/
		out += '</div>';
	}
	out += '</div>';
	return out;

}
function confirmPlace(placeid) {
	new Ajax.Updater('devnull', baseurl +'search/ajaxConfirmPlace/'+placeid,
	{
		asynchronous:true,
		evalScripts:true,
		onComplete:function(request, json) {
			$('confirm-button-'+placid).hide()
			},
		onLoading:function(request) {},
		requestHeaders:['X-Update', 'devnull']
		});
}
     
function importanceOrder (marker,b) {
	return GOverlay.getZIndex(marker.getPoint().lat()) + marker.importance*1000000;
}

function createPlaceMarker(point, placeid, selected) {
	var markerOptions;


	var letter = 'Dot';
	if (letters.length > placeid) {
		letter = letters[placeid];
	}
	var color = 'paleblue';


	if (places[placeid][0]['confirmed'] >= votes_to_confirm_place) {
		color = 'blue';
	}
	if (places[placeid][0]['premium'] > 0) {
		color = 'red';
	}


	if (selected) {
		color = 'red';
	}
	
	var ico = baseurl + 'img/icons/' + color + '_Marker' + letter + '.png';


	if (ico != '') {
		var blueIcon = new GIcon(G_DEFAULT_ICON);
		blueIcon.image = ico;
		//blueIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		blueIcon.iconSize = new GSize(19, 30);
		blueIcon.shadowSize = new GSize(0, 0);

		// Set up our GMarkerOptions object
		markerOptions = {
			icon:blueIcon,
			zIndexProcess:importanceOrder
		};
	//	fillStyle: new FillStyle({color: 0x223344, alpha: 0.8}),
	//  radius: 12,
	//  hasShadow: true
	//};
	}
	else
	{
		// Set up our GMarkerOptions object
		markerOptions = {
			zIndexProcess:importanceOrder
		};
	
	}


	var marker = new GMarker(point, markerOptions);
	marker.importance = places[placeid][0]['premium'];
	//if (selected) marker.openInfoWindowHtml(createPlaceWindow(placeid, baseurl));

	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(createPlaceWindow(placeid));
	});

	if (placeid!='') {
		GEvent.addListener(marker, "mouseover", function() {
			markers[placeid].hide();
			markersSel[placeid].show();
		});
		GEvent.addListener(marker, "mouseout", function() {
			markers[placeid].show();
			markersSel[placeid].hide();
		});
	}
	
	if (placeid!='' && $$('.result-'+placeid)) {
		GEvent.addListener(marker, "mouseover", function() {
			$$('.result-'+placeid).each(function (n) {
				n.addClassName('selected')
				});
		});
		GEvent.addListener(marker, "mouseout", function() {
			$$('.result-'+placeid).each(function (n) {
				n.removeClassName('selected')
				});
		});
	}

	return marker;
}




function createMarker(point, html, ico, id, selected) {
        
	// Create a lettered icon for this point using our icon class
	//var letter = String.fromCharCode("A".charCodeAt(0) + index);
	//var letteredIcon = new GIcon(baseIcon); // new GIcon(baseIcon);
	//letteredIcon.image = ico; // ICON

	var markerOptions;

	// Set up our GMarkerOptions object
	//markerOptions = { icon:letteredIcon };
          
	//var blueIcon = new GIcon(G_DEFAULT_ICON);
		
	if (ico != '') {
		var blueIcon = new GIcon(G_DEFAULT_ICON);
		blueIcon.image = ico;
		//blueIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		//blueIcon.iconSize = new GSize(34, 34);
		//blueIcon.shadowSize = new GSize(34, 34);

		// Set up our GMarkerOptions object
		markerOptions = {
			icon:blueIcon
		};
	//	fillStyle: new FillStyle({color: 0x223344, alpha: 0.8}),
	//  radius: 12,
	//  hasShadow: true
	//};
	}

	  
	var marker = new GMarker(point, markerOptions);
	if (selected) marker.openInfoWindowHtml("<span style='font-size: 10px;'> " + html + "</span>");
							
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml("<span style='font-size: 10px;'> " + html + "</span>");
	});
	  
	if (id!='') {
		GEvent.addListener(marker, "mouseover", function() {
			markers[id].hide();
			markersSel[id].show();
		});
		GEvent.addListener(marker, "mouseout", function() {
			markers[id].show();
			markersSel[id].hide();
		});
	}
	if (id!='' && $('result-'+id)) {
		GEvent.addListener(marker, "mouseover", function() {
			$('result-'+id).addClassName('selected');
		});
		GEvent.addListener(marker, "mouseout", function() {
			$('result-'+id).removeClassName('selected');
		});
	}
          
	return marker;
}

function createCentralMarker(point, html) {
        
	// Create a lettered icon for this point using our icon class
	//var letter = String.fromCharCode("A".charCodeAt(0) + index);
	//var letteredIcon = new GIcon(baseIcon); // new GIcon(baseIcon);
	//letteredIcon.image = ico; // ICON

	var markerOptions;

	// Set up our GMarkerOptions object
	//markerOptions = { icon:letteredIcon };
          
	//var blueIcon = new GIcon(G_DEFAULT_ICON);
		
	
		var blueIcon = new GIcon(G_DEFAULT_ICON);
		blueIcon.image = baseurl+'img/dd-start.png';
		blueIcon.iconSize = new GSize(19, 19);
		blueIcon.shadowSize = new GSize(0, 0);
		blueIcon.iconAnchor = new GPoint(9, 9);

		// Set up our GMarkerOptions object
		markerOptions = {
			icon:blueIcon,
			draggable: true,
			title: "Táhni pro změnu pozice",
		};

	

	  
	var marker = new GMarker(point, markerOptions);
/*	var div = document.createElement('div');
	div.id = 'dragdiv';
	document.getElementById('mapa').appendChild(div);
	var k = document.getElementById('dragdiv');*/
	
	GEvent.addListener(marker, "dragstart", function() {	
		//jQuery('.mapa-search').append(jQuery('#dragdiv'));
	});
	
	GEvent.addListener(marker, "drag", function() {
	/*	document.onmousemove = function(event){
			k.style.top = event.clientY+'px';
			k.style.left = event.clientX+'px';
		}*/
	});
	
	GEvent.addListener(marker, "dragend", function() {
	//	document.onmousemove = function(){};
		$('kde').value = marker.getPoint().toUrlValue();
		reloadPlaces();	
		//window.location = 'http://localhost:8888/LOKOLALH/?range='+range+'&showall='+showall+'&what='+what+'&where='+marker.getPoint().toUrlValue();
		//marker.openInfoWindowHtml("<span style='font-size: 10px;'> " + html + marker.getPoint() + "</span>");
	});
	  
	
          
	return marker;
}

function addCircleTools(map, hereyouare, circleRadius, rLng, rLat) {
	var sel = $('RangesRanges');
	var range = sel.getValue();

	if (range<6) {
		

		var icon = new GIcon(G_DEFAULT_ICON);
		icon.image = baseurl+'img/map-inc-right.png';
		icon.iconSize = new GSize(14, 12);
		icon.shadowSize = new GSize(0, 0);
		icon.iconAnchor = new GPoint(0, 5);
		markerOptions = {icon:icon};
		var incR = new GMarker(new GLatLng(hereyouare.lat(), hereyouare.lng() + (rLng)), markerOptions);
		map.addOverlay(incR);

		var icon2 = new GIcon(G_DEFAULT_ICON);
		icon2.image = baseurl + 'img/map-inc-left.png';
		icon2.iconSize = new GSize(14, 12);
		icon2.shadowSize = new GSize(0, 0);
		icon2.iconAnchor = new GPoint(15, 5);
		markerOptions = {icon:icon2};
		var incL = new GMarker(new GLatLng(hereyouare.lat(), hereyouare.lng() - (rLng)), markerOptions);
		map.addOverlay(incL);
		
		var icon3 = new GIcon(G_DEFAULT_ICON);
		icon3.image = baseurl + 'img/map-inc-up.png';
		icon3.iconSize = new GSize(12, 14);
		icon3.shadowSize = new GSize(0, 0);
		icon3.iconAnchor = new GPoint(4, 15);
		markerOptions = {icon:icon3};
		var incU = new GMarker(new GLatLng(hereyouare.lat() + (rLat), hereyouare.lng()), markerOptions);
		map.addOverlay(incU);

		var icon4 = new GIcon(G_DEFAULT_ICON);
		icon4.image = baseurl + 'img/map-inc-down.png';
		icon4.iconSize = new GSize(12, 14);
		icon4.shadowSize = new GSize(0, 0);
		icon4.iconAnchor = new GPoint(4, -2);
		markerOptions = {icon:icon4};
		var incD = new GMarker(new GLatLng(hereyouare.lat() - (rLat), hereyouare.lng()), markerOptions);
		map.addOverlay(incD);

		GEvent.addListener(incR, "click", function() {
			$('RangesRanges').value=Number(range)+1;
			updateRanges();				
		});
		GEvent.addListener(incL, "click", function() {
			$('RangesRanges').value=Number(range)+1;
			updateRanges();				
		});
		GEvent.addListener(incU, "click", function() {
			$('RangesRanges').value=Number(range)+1;
			updateRanges();
		});
		GEvent.addListener(incD, "click", function() {
			$('RangesRanges').value=Number(range)+1;
			updateRanges();
		});
		
	}

	if (range>0) {
		var icon = new GIcon(G_DEFAULT_ICON);
		icon.image = baseurl+'img/map-dec-right.png';
		icon.iconSize = new GSize(14, 12);
		icon.shadowSize = new GSize(0, 0);
		icon.iconAnchor = new GPoint(17, 5);
		markerOptions = {icon:icon};
		var decR = new GMarker(new GLatLng(hereyouare.lat(), hereyouare.lng() + (rLng)), markerOptions);
		map.addOverlay(decR);

		var icon2 = new GIcon(G_DEFAULT_ICON);
		icon2.image = baseurl+'img/map-dec-left.png';
		icon2.iconSize = new GSize(14, 12);
		icon2.shadowSize = new GSize(0, 0);
		icon2.iconAnchor = new GPoint(-2, 5);
		markerOptions = {icon:icon2};
		var decL = new GMarker(new GLatLng(hereyouare.lat(), hereyouare.lng() - (rLng)), markerOptions);
		map.addOverlay(decL);

		var icon3 = new GIcon(G_DEFAULT_ICON);
		icon3.image = baseurl + 'img/map-dec-up.png';
		icon3.iconSize = new GSize(12, 14);
		icon3.shadowSize = new GSize(0, 0);
		icon3.iconAnchor = new GPoint(4, -2);
		markerOptions = {icon:icon3};
		var decU = new GMarker(new GLatLng(hereyouare.lat() + (rLat), hereyouare.lng()), markerOptions);
		map.addOverlay(decU);

		var icon4 = new GIcon(G_DEFAULT_ICON);
		icon4.image = baseurl + 'img/map-dec-down.png';
		icon4.iconSize = new GSize(12, 14);
		icon4.shadowSize = new GSize(0, 0);
		icon4.iconAnchor = new GPoint(4, 15);
		markerOptions = {icon:icon4};
		var decD = new GMarker(new GLatLng(hereyouare.lat() - (rLat), hereyouare.lng()), markerOptions);
		map.addOverlay(decD);

		GEvent.addListener(decR, "click", function() {
			$('RangesRanges').value=Number(range)-1;
			updateRanges();
		});
		GEvent.addListener(decL, "click", function() {
			$('RangesRanges').value=Number(range)-1;
			updateRanges();
		});
		GEvent.addListener(decU, "click", function() {
			$('RangesRanges').value=Number(range)-1;
			updateRanges();
		});
		GEvent.addListener(decD, "click", function() {
			$('RangesRanges').value=Number(range)-1;
			updateRanges();
		});
	}
	
}


function mywait(msecs) {
	var start = new Date().getTime();
	var cur = start
	while(cur - start < msecs) {
		cur = new Date().getTime();
	}
}


function showOnMap(id, scroll) {
	if (scroll) {
		$$('body').first().removeClassName('height100p');
		new Effect.ScrollTo('top-of-search-box', { duration: 2.0, afterFinish: function() {
																showPointOnMap(id);
																$$('body').first().addClassName('height100p');
																}
		} );
	} else {

		showPointOnMap(id);
	}
}


function showCentreOnMap() {
		$$('body').first().removeClassName('height100p');
		new Effect.ScrollTo('top-of-search-box', { duration: 1.0, afterFinish: function() {
																map.setCenter(mapcenter)
																$$('body').first().addClassName('height100p');
																}
		} );
}


function showPointOnMap(id) {
	map.setCenter(mapcenter);
	map.panTo(markers[id].getLatLng());
	markers[id].openInfoWindowHtml( createPlaceWindow(id));
}


function sendPublicEditForm(direction) {
	if (direction) $('direction').value = direction;
	new Ajax.Updater('formdiv',baseurl+'places/ajax_add_wizard', {
		asynchronous:true,
		evalScripts:true,
		parameters:Form.serialize('edit_form'),
		requestHeaders:['X-Update', 'formdiv']
		});
}



function uploadLogo() {
	//if (direction) $('direction').value = direction;
	new Ajax.Updater('logodiv',baseurl+'places/ajax_upload_logo', {
		asynchronous:true,
		evalScripts:true,
		parameters:Form.serialize('edit_form'),
		requestHeaders:['X-Update', 'logodiv']
		});
}
		
		
function startUpload() {
	// make something useful before submit (onStart)
	return true;
}

function completeUpload(response) {
	// make something useful after (onComplete)
	document.getElementById('nr').innerHTML = parseInt(document.getElementById('nr').innerHTML) + 1;
	document.getElementById('r').innerHTML = response;
}

function runnerClick(runnerId) {
	document.getElementById('runner' + runnerId).className="active" 
	//$('#runner3').addClass('active');

	//$('runnerImg').setStyle({'left': runnerPlaces[runnerId] +'px'});
	$('RangesRanges').value = runnerId;
	//alert($('RangesRanges').getValue());
	updateRanges();
	return false;
}

function safeScrollTo(elementId) {
	if ($(elementId)) {
		$$('body').first().removeClassName('height100p'); 
		new Effect.ScrollTo(elementId);
		$$('body').first().addClassName('height100p');
	}
}


// ----------------

/**
 * Pouzivam bez-konfliktni zapis (moznost pouzivat zaroven s jinymi frameworky)
 */
/*
jQuery(document).ready(function(){

	if (jQuery('#range0')) {
		var runner = jQuery('#map-settings p img');
		var places = new Array('107','166','226','284','342','400','458');

		var range1 = jQuery('#range0');
		var range2 = jQuery('#range1');
		var range3 = jQuery('#range2');
		var range4 = jQuery('#range3');
		var range5 = jQuery('#range4');
		var range6 = jQuery('#range5');
		var range7 = jQuery('#range6');

		range1.click(function(){ runner.css('left', places[0] + 'px') })
		range2.click(function(){ runner.css('left', places[1] + 'px') })
		range3.click(function(){ runner.css('left', places[2] + 'px') })
		range4.click(function(){ runner.css('left', places[3] + 'px') })
		range5.click(function(){ runner.css('left', places[4] + 'px') })
		range6.click(function(){ runner.css('left', places[5] + 'px') })
		range7.click(function(){ runner.css('left', places[6] + 'px') })

		jQuery('#map-settings ul li a').bind('click', function(){ return false })
	}
});
*/
