/*
*	Function pack to have a deal with Mapia interface
*/

// Dictionary: variances about ru/ua replics
var Dict = {
	lang: 'ru',
	defaultLang: 'ru',


	replics: {
		ru: {
			header:			'Вы искали',
			addresses:		'адреса',
			show_all:		'Показать все найденное на карте',
			hide_all:		'Убрать все',
			empty_query:	'Ничего не найдено',
			back:			'Назад',
			forward:		'Вперёд',
			no_category:	'без категории',

			found_city:		[ 'Найден %n город', 'Найдено %n города', 'Найдено %n городов' ],
			found_station:	[ 'Найдена %n станция', 'Найдено %n станции', 'Найдено %n станций' ],
			found_street:	[ 'Найдена %n улица', 'Найдено %n улицы', 'Найдено %n улиц' ],
			found_object:	[ 'Найден %n объект', 'Найдено %n объекта', 'Найдено %n объектов' ]
		},


		ua: {
			header:			'Ви шукали',
			addresses:		'адреси',
			show_all:		'Показати все знайдене на карті',
			hide_all:		'Прибрати все',
			empty_query:	'Нічого не знайдено',
			back:			'Назад',
			forward:		'Уперед',
			no_category:	'без категорії',

			found_city:		[ 'Знайдене %n місто', 'Знайдено %n міста', 'Знайдено %n міст' ],
			found_station:	[ 'Знайдена %n станція', 'Знайдено %n станції', 'Знайдено %n станцій' ],
			found_street:	[ 'Знайдена %n вулиця', 'Знайдено %n вулиці', 'Знайдено %n вулиць' ],
			found_object:	[ 'Знайдений %n об\'єкт', 'Знайдено %n об\'єкта', 'Знайдено %n об\'єктів' ]
		}
	},


	// get the replic
	get : function(field, n) {
		var str = this.replics[this.lang][field];

		if ( $defined(n) ) {
			str = str[ n%10 == 1 && n%100 != 11 ? 0 : n%10 >= 2 && n%10 <= 4 && (n%100 < 10 || n%100 >= 20) ? 1 : 2 ];
			str = str.replace('%n', n);
		}

		return $pick(str, '');
	}
}


// toggle corresponsive markers on map by section. ids - array of sections
function updateLayer(box, ids) {
	if ( !map ) return false;

	if (box.checked) {
		map.loadMarkers(ids);
	} else {
		map.clearMarkers(ids);
	}

	refreshSections(box);
	//highlightAds(__CITY);
}


// toggle category tree
function exTree(el, img) {
	element = $(el); 
	var div = (img) ? element.getParent().getElement('.subcategory') : element.getParent().getParent().getElement('.subcategory');
	var img = (img) ? element : element.getParent().getParent().getElement('img');

	if( div.hasClass('hidden') ) {
		div.removeClass('hidden');
		img.setAttribute('src', __IMGS + 'minus.png');
	} else {
		div.addClass('hidden');
		img.setAttribute('src', __IMGS + 'plus.png');
	}
}


// mark all subcategory boxes as category box marked
function refreshSections(box) {
  $(box).getParent().getElements('input').each(function(sub){
		sub.checked = box.checked;
	});
}


// clear all boxes
function clearSection() {
	$('categories').getElements('input').each(function(sub){
		sub.checked = false;
	});
};


// swicth between categories and panoramas
function switchLeftColumnMode(control) {
	var content = $('content');
	var href = control.href.split('#')[1];

	if ( $('search_mode') ) delete $('search_mode').remove();

	if ( 'panoramas' === href && '30295' != __CITY /* not Kiev */ ) return false;

	if ( content._mode == href || (!content._mode && 'categoriestab' == href) ) {
		$(href+'_mode').removeClass('hidden');
		return false;
	}

	content._mode = href;

	content.getChildren().addClass('hidden');
	$(href+'_mode').removeClass('hidden');

	$('tabsContainer').getChildren().toggleClass('selected');

	map.clearAllMarkers();

	if ( 'panoramas' == href ) {
		map.loadPanoramas();
	}

	return false;
}

// callback to this-place-link
function hereLink() {
	var coords = map.getCenter();
	var zoom = map.getZoom();
	return 'http://'+document.location.host+'/map/?lat='+coords.lat+'&lon='+coords.lon+'&zoom='+zoom;
}


// InputDefault
var InputDefault = {
	prop	: '_default',
	classes	: { empty : 'example' },

	init	: function() {
		$$('input['+this.prop+']').each(function(input) {
			input.addEvents({

				focus : function() {
					if ( this.hasClass(InputDefault.classes.empty) ) {
						this.removeClass(InputDefault.classes.empty);
						this.value = '';
					}
				},

				blur : function() {
					if ( '' === this.value || this.getProperty(InputDefault.prop) === this.value ) {
						this.addClass(InputDefault.classes.empty);
						this.value = this.getProperty(InputDefault.prop);
					}
				}

			});

			input.fireEvent('blur');
		});
	}
}


// search management object
var Search = {

	query	: '',
	result	: {},
	elems	: { content : 'content', result : 'search_results_mode' },
	page	: 1,
	perPage	: 10,


	process : function(result) {
		result.features.filter(function(val) { return (val['title_' + Dict.lang] || val.title_ru);  });
		result.empty = 0 === (result.addresses.length + result.categories.length + result.cities.length + result.features.length + result.stations.length + result.streets.length);
		this.result = result;

		var content = $(this.elems.content);
		var container = $(this.elems.result);

		var citiesHTML = '', stationsHTML = '', streetsHTML = '', featuresHTML = '', pagerHTML = '';

		if ( !result.empty ) {
			// render cities
			if ( 0 < result.cities.length ) {
				citiesHTML = '<div id="search_bar_title">' + Dict.get('found_city', result.cities.length) + '</div><div id="city_results"><ul>';

				result.cities.each(function(item) {
					citiesHTML += '<li><a href="#" onclick="map.showOverlay('+ item.id +', \'City\'); return false;">'+ item['title_' + Dict.lang] +'</a></li>';
				});

				citiesHTML += '</ul></div>';
			}


			// render stations
			if ( 0 < result.stations.length ) {
				stationsHTML = '<div id="search_bar_title">' + Dict.get('found_station', result.stations.length) + '</div><div id="category_results"><ul>';

				result.stations.each(function(item) {
					stationsHTML += '<li><a href="#" onclick="map.showOverlay('+ item.id +', \'Station\'); return false;">'+ item['title_' + Dict.lang] +'</a></li>';
				});

				stationsHTML += '</ul></div>';
			}


			// render streets & addresses
			if ( 0 < result.streets.length ) {
				streetsHTML = '<div id="search_bar_title">' + Dict.get('found_street', result.streets.length) + '</div><div id="street_results"><ul>';

				result.streets.each(function(item) {
					streetsHTML += '<li><a href="#" onclick="map.showOverlay('+ item.id +', \'Street\'); return false;">'+ item[Dict.lang] +'</a>';

					// addresses
					streetsHTML += ' <a onclick="$(\'street_' + item.id + '_buildings\').toggleClass(\'hidden\'); return false;" href="#"><span class="small_text">' + Dict.get('addresses') + '</span><img src="' + __IMGS + 'next.png" /></a>';
					streetsHTML += '<div style="" id="street_' + item.id + '_buildings" class="buildings_info hidden"><div class="t"></div><div class="m"><ul class="street_buildings_list">';

					var streetAddresses = result.addresses_dict['street_'+item.id].sort(function(a, b) {
						a = isNaN(a[Dict.lang].toInt()) ? 0 : a[Dict.lang].toInt() ;
						b = isNaN(b[Dict.lang].toInt()) ? 0 : b[Dict.lang].toInt() ;
						return a - b;
					});

					streetAddresses.each(function(addr) {
						streetsHTML += '<li><a onclick="map.showOverlay(' + addr.id + ', \'Address\'); return false;" href="#">' + addr[Dict.lang] + '</a></li>';
					});

					streetsHTML += '</ul><div class="clear"/></div></div><div class="b"></div></div></li>';
				});

				streetsHTML += '</ul></div>';
			}


			// render features
			if ( 0 < result.features.length ) {
				result.features = result.features.sort(function(a, b) {
					return a['title_' + Dict.lang] < b['title_' + Dict.lang] ? -1 : 1 ;
				});

				featuresHTML = '<div id="search_bar_title">' + Dict.get('found_object', result.features.length) + '</div>';
				featuresHTML += '<div><small><a onclick="map.searchMarkers(\'' + this.query + '\', 30295); return false;" href="#">' + Dict.get('show_all') + '</a></small>';
				featuresHTML += '<span style="position: relative; right: 0pt; float: right;"><a onclick="map.clearAllMarkers(); return false;" href="#"><small>' + Dict.get('hide_all') + '</small></a></span><div style="clear: both;"></div></div>';
				featuresHTML += '<div id="feature_results"><ul>';

				result.features.slice(0, this.perPage).each(function(item) {
					featuresHTML += '<li>\
						<a href="#" onclick="map.showOverlay('+ item.id +', \'Feature\'); return false;">' +
						(null == item['title_' + Dict.lang] ? item.title_ru : item['title_' + Dict.lang]) +'</a> <small>(' +
						( item['category_' + Dict.lang] || item.category_ru || Dict.get('no_category')) + ') ' +
						( item['address_' + Dict.lang] || item.address_ru || '') + '</small></li>\
					';
				});

				featuresHTML += '</ul></div>';
			}


			// render pager
			if ( this.perPage < result.features.length ) {
				pagerHTML = '<div class="pagination"><a _href="javascript: Search.prevPage();">&laquo;&nbsp;' + Dict.get('back') + '</a> ';

				var i = 1;

				do {
					pagerHTML += '<a '+(this.page == i ? 'class="current" _' : '')+'href="javascript: Search.setPage('+i+');">'+ i +'</a> ';
				} while ( (i++ * this.perPage) < result.features.length );

				pagerHTML += '<a href="javascript: Search.nextPage();">' + Dict.get('forward') + '&nbsp;&raquo;</a></div>';
			}
		}

		// output
		container.setHTML(
			'<div id="search_results">' +
			'<div id="search_bar_title">' + Dict.get('header') + ': &laquo;' + this.query + '&raquo;</div>' +
			(!result.empty ? citiesHTML + stationsHTML + streetsHTML + featuresHTML + pagerHTML : Dict.get('empty_query')) +
			'</div>'
		);

		this.setPage(1);
		content.getChildren().addClass('hidden');
		container.removeClass('hidden');
	},


	setPage : function(number) {
		var pager = $E('.pagination', this.elems.result);
		if ( !pager ) return true;

		var elems = pager.getElements('a');

		var
			old = elems[this.page],
			fresh = elems[number],
			prev = elems[0],
			next = elems.getLast()
		;


		// switch feature page
		var featuresHTML = '';

		this.result.features.slice((number - 1) * this.perPage, number * this.perPage).each(function(feature) {
			featuresHTML += '<li>\
				<a href="#" onclick="map.showOverlay('+ feature.id +', \'Feature\'); return false;">' +
				(null == feature['title_' + Dict.lang] ? feature.title_ru : feature['title_' + Dict.lang]) +'</a> <small>(' +
				( feature['category_' + Dict.lang] || feature.category_ru || Dict.get('no_category')) + ') ' +
				( feature['address_' + Dict.lang] || feature.address_ru || '') + '</small></li>\
			';
		});

		$('feature_results').getFirst().setHTML(featuresHTML);


		// pager highlight
		old.setProperty('href', old.getProperty('_href')).removeClass('current');
		fresh.setProperty('_href', fresh.getProperty('href')).removeProperty('href').addClass('current');

		if ( 1 === number )
			prev.setProperty('_href', prev.getProperty('href')).removeProperty('href');
		else if ( null === prev.getProperty('href') )
			prev.setProperty('href', prev.getProperty('_href'));

		if ( number === (elems.length - 2) )
			next.setProperty('_href', next.getProperty('href')).removeProperty('href');
		else if ( null === next.getProperty('href') )
			next.setProperty('href', next.getProperty('_href'));


		this.page = number;
	},


	prevPage : function() {
		this.setPage(this.page - 1);
	},


	nextPage : function() {
		this.setPage(this.page + 1);
	},


	error : function(error) {
	},


	find : function(term) {
		this.query = term;
		map.searchAll(term, __CITIES[__CITY].name, 'Search.process', 'Search.error');
		return false;
	}

}


// pathfinding
function DestinationView(containerId, destination, icon) {
  this.container = $(containerId);
  this.container.setStyle('position', 'relative');
  this.destination = destination;
  this.icon = icon;
  this.render();
}

DestinationView.prototype.setIcon = function(icon) {
  this.iconElement.src = (icon || DestinationView.destinationIcons[0]);
}

DestinationView.prototype.getIcon = function() {
  return this.icon;
}

DestinationView.prototype.setDestination = function(destination) {
	this.destination = destination;
	this.inputElement.value = (destination.title || '');
}

DestinationView.prototype.getDestination = function() {
  return this.destination;
}

DestinationView.prototype.render = function() {
	this.container.innerHTML = "<img src='" + __IMGS + (this.icon || DestinationView.destinationIcons[0]) + "' /> <input type='text' value='" + (this.destination.title || "") + "' /> <a href='#' class='remove'><img src='" + __IMGS + "cross.png' /></a><a style='position:absolute;right:0px;top:16px;z-index:2;' class='switch hidden' href='#'><img src='" + __IMGS + "switch_icon.png' /></a>"
	this.iconElement = this.container.getElement('img');
	this.removeElement = this.container.getElement('.remove');
	this.inputElement = this.container.getElement('input');
	this.switchElement = this.container.getElement('.switch');

	this.inputElement.addEvent('focus', function(event){ this.inputHasFocus = true}.bindWithEvent(this));
	this.inputElement.addEvent('blur', function(event){this.inputHasFocus = false}.bindWithEvent(this));
	this.inputElement.addEvent('change', this.inputChange.bindWithEvent(this));

	var _this = this;

	this.inputElement.addEvent('keyup', (function(evt) {
		if ( 'enter' == evt.key ) {
			try {
				evt.stop();
				this.inputHasFocus = false;
				this.inputElement.fireEvent('change');
				this.inputElement.form.fireEvent('submit');
			} catch(e) { ; }
		}
	}).bindWithEvent(this));
}

DestinationView.prototype.inputChange = function(event) {
	this.destination = { title : this.inputElement.value, fix_title : true };
}

function PathfindingView(containerId, pt) {
	this.base = EventManager;
	this.base();
	this.container = $(containerId);
	this.destinationViews = [];
	this.pt = pt;

	this.form = this.container.getElement('form');
	this.destinationsContainer = this.container.getElement('.destinations');
	this.addLink = this.container.getElement('.add_destination');
	this.removeAllLink = this.container.getElement('.remove_all');

	this.addLink.addEvent('click', function(event){this.appendDestinationView({}); event.stop();}.bindWithEvent(this));
	this.removeAllLink.addEvent('click', function(event){this.pt.removeAll(); event.stop();}.bindWithEvent(this));
	this.form.addEvent('submit', this.onFormSubmit.bindWithEvent(this));

	this.pt.addEventListener('destinationsChanged', this.update.bind(this));
	this.pt.addEventListener('routingErrors', this.onRoutingErrors.bind(this));
	this.pt.addEventListener('lengthChanged', this.lengthChangeHandler.bind(this));
	
  (2).times(function(n){this.appendDestinationView({})}.bind(this));
}

PathfindingView.prototype = new EventManager();

PathfindingView.prototype.lengthChangeHandler = function(event) {
  this.container.getElement('.pathLength').innerHTML = event.length.toString();
}

PathfindingView.prototype.appendDestinationView = function(destination) {
	var c = document.createElement('div');
	this.destinationsContainer.appendChild(c);
	var d = new DestinationView(c, destination, PathfindingView.destinationIcons[this.destinationViews.length])
	var index = this.destinationViews.length;
	this.destinationViews.push(d);

	d.removeElement.addEvent('click', function(event, i){
		this.pt.removeDestination(i);
		event.stop();
	}.bindWithEvent(this, index));

	d.switchElement.addEvent('click', function(event, i){
		this.pt.moveDestination(i, i+1);
		event.stop();
	}.bindWithEvent(this, index));
}


PathfindingView.prototype.onFormSubmit = function(event) {
	event.stop();
	var dests = []

	this.destinationViews.each(function(dv){
		if(dv.destination && (dv.destination.loc || dv.destination.title)){
			if (!dv.destination.loc && dv.destination.title) {
				dv.destination.city = __CITIES[__CITY].name;
			}
			dests.push(dv.destination);
		}
	});
  
	pt.findRoute(dests);

	return false;
}

PathfindingView.prototype.onRoutingErrors = function(event) {
  this.container.getElement('.errors').innerHTML = event.errors;
}

PathfindingView.prototype.update = function(event) {
		if(event.result){
		this.container.getElement('.errors').innerHTML = '';
	}

	var destinations = event.destinations;

	var dvlen = this.destinationViews.length;
	var dlen = destinations.length;
	var i;

	for(i=0;i<dlen; i++) {
		if(i < dvlen) {
			this.destinationViews[i].setDestination(destinations[i]);
		} else {
			this.appendDestinationView(destinations[i])
		}

		this.destinationViews[i].switchElement[ i==dlen-1 ? 'addClass' : 'removeClass' ]('hidden');
	}

	if(dvlen > dlen)
	{

	for(i=dlen; i<dvlen; i++)
	{
	  if(i < 2)
	  {
		this.destinationViews[i].setDestination({});
		this.destinationViews[i].switchElement.addClass('hidden');
	  }
	  else
	  {
		this.destinationsContainer.removeChild(this.destinationViews[i].container);
	  }
	}

	var remainDestinations = Math.max(dlen, 2); 
	this.destinationViews.splice(remainDestinations, this.destinationViews.length - remainDestinations);
	} 
}

PathfindingView.destinationIcons = ['mapia_78.gif', 'mapia_80.gif', 'mapia_82.gif', 'mapia_84.gif', 'E.png', 'mapia_86.gif', 'mapia_88.gif'];


// cities list with titles and coords
var
	__CITIES = {
		'29890': {'zoom': 12, 'lat': 47.85022, 'name': 'Запорожье', 'lon': 35.15302},
		'30332': {'zoom': 11, 'lat': 48.4677, 'name': 'Днепропетровск', 'lon': 35.01769},
		'27020': {'zoom': 12, 'lat': 46.45686, 'name': 'Одесса', 'lon': 30.73434},
		'29819': {'zoom': 13, 'lat': 48.9179, 'name': 'Ивано-Франковск', 'lon': 24.72623},
		'30420': {'zoom': 13, 'lat': 44.59199, 'name': 'Севастополь', 'lon': 33.54006},
		'282': {'zoom': 12, 'lat': 47.97992, 'name': 'Донецк', 'lon': 37.77788},
		'329': {'zoom': 12, 'lat': 49.42349, 'name': 'Черкассы', 'lon': 32.05258},
		'168': {'zoom': 14, 'lat': 44.50093, 'name': 'Ялта', 'lon': 34.15785},
		'129': {'zoom': 12, 'lat': 49.83496, 'name': 'Львов', 'lon': 24.01374},
		'27443': {'zoom': 12, 'lat': 49.98233, 'name': 'Харьков', 'lon': 36.2696},
		'30295': {'zoom': 11, 'lat': 50.45399, 'name': 'Киев', 'lon': 30.50382},
		'335': {'zoom': 12, 'lat': 46.94547, 'name': 'Николаев', 'lon': 32.00775}
	},

	__CITY = '30295'
;

function highlightAds(city) {
	city = parseInt(city);

	$('ad_categories').getElements('span').each(function(span) {
		category = bigmir_categories[span.getFirst().value];
		span[
			category.cities.contains(city) && (null === category.parent_id || $('category_' + category.parent_id).checked)
			? 'removeClass'
			: 'addClass'
		]('hidden');
	});
}

var bigmir_categories = {};


// body onLoad callback
function bodyOnLoad() {

	/*var container = $('ad_categories');
	var tpl = container.getElement('span').remove();

	mapia_categories.each(function(ad_category) {
		tpl.clone()
			.getFirst().setProperties({
				'id' : 'category_'+ ad_category.id,
				'name' : 'ad_category_'+ ad_category.id,
				'data-id' : ad_category.id,
				'value' : ad_category.id
			}).getNext().setProperty('for', 'category_' + ad_category.id)
			.getFirst().setProperties({
				'alt' : 'Mapia_category_0'+ ad_category.id,
				'src' : 'http://mapia.ua'+ ad_category.icon
			}).getParent().getParent().inject(container.getFirst())
		;

		bigmir_categories[ad_category.id] = ad_category;
	});

	highlightAds(__CITY);

	$$('#ad_categories input').addEvent('click', function(evt) {
		evt = new Event(evt);

		var element = evt.target;
		var select = false;

		if (element.checked) {
			select = true;
		};

		// clear all categories
		$$('#ad_categories input').each(function(input) {
			input.checked = false;
			updateLayer(input, [parseInt(input.getProperty('data-id'))]);
		});

		// mark
		element.checked = select;
		updateLayer(element, [parseInt(element.getProperty('data-id'))]);
	});*/
}


// hacks
function updateCheckboxes() { ; }
function error() { ; }