$(document).ready(function(){
	$('#from, #to').keyup(function(){
		var val = this.value.replace(/(^\s+)|(\s+$)/g,'');
		if (val.length > 0){
			var self = this;
			if (window.hint_timer) clearTimeout(hint_timer);
		  hint_timer = setTimeout(function(){
				$('#hint').attr('target',self.id);
				var param = {val:val};
				switch (self.id){
					case 'from': param.to = $('#to').val(); break;
					case 'to': param.from = $('#from').val(); break;
				}
				$.getJSON('http://www.eastlines.ru/route/get_hint_list.php',param,function(data){
				  if (!data.length) {
            $('#hint').css('display','none');
						return;
					}
				  var hint = $('#hint');
				  hint[0].innerHTML = '';
					for (var i=data.length - 1;i>=0;i--) $("<div>"+data[i]+"</div>").appendTo(hint);

					$('#hint div').click(function(){
						$(self).val(this.innerHTML);
					});
					var pos = $(self).offset();
					hint.css({
						'display':'block',
						'top':pos.top + $(self).outerHeight(),
						'left':pos.left
					});
					$(document).click(function(){
						$('#hint').css('display','none');
						$(document).unbind('click');
					});
				});
			},10);
		} else {$('#hint').css('display','none');}
	});
	$('#go').click(function(){
		$('#show_hide').css('display','block');
// 		$('#show_hide').click();
		var param = {};
		param.from = $('#from').val().replace(/(^\s+)|(\s+$)/g,'');
		param.to = $('#to').val().replace(/(^\s+)|(\s+$)/g,'');
		$('#route_desc').val(param.from + ' - ' + param.to);
		$('#route_ttl b').text(param.from + ' - ' + param.to);
		$.getJSON('get_route.php',param,function(data){
		  $('#result').css('display','block');
		  if (data.error){
				$('#succ_res').css('display','none');
				$('#error').css('display','block').text(data.error);
				return;
			}
			$('#succ_res').css('display','block');
			$('#error').css('display','none');
		  var cfg = {
				showmap: $('#showmap')[0].checked,
				showpopulation: $('#showpopulation')[0].checked,
				showrange: $('#showrange')[0].checked,
				showtime: $('#showtime')[0].checked
			};
			if (!cfg.showmap) $('#map,#map_ttl').css('display','none');
			else{
				$('#map,#map_ttl').css('display','block');
				if (!window.gmap) {
					gmap = new GMap2(document.getElementById("map"));
					gmap.addControl(new GLargeMapControl());
				}
				gmap.clearOverlays();
			}
			var points = Array();
			var className;
			var total_time = 0, total_range = 0;
			var style_marker = {icon:{
			 	image:'/images/city_marker.png',
				 iconSize: new GSize(10,10),
				 iconAnchor: new GPoint(5,5),
				 infoWindowAnchor: new GPoint(5,5)
			}};
			var tbl = $('#route_tbl table');
      tbl.html('');
			var tr = '<tr><th>Пункт марштура</th>';
			if (cfg.showpopulation) tr += '<th>Население города</th>';
			tr += '<th>Расстояние от начала</th>';//'<th>Время в пути</th>';
			if (cfg.showrange) tr += '<th>Длина участка</th>';
			if (cfg.showtime) tr += '<th>Время участка</th>';
			tr += '</tr>';
			$(tr).appendTo(tbl);
			for (var i=data.length - 1; i>=0; i--){
        var citySize = "";
				switch (data[i].citysize) {
					case "0": citySize = " - ";
					case "1": citySize = "до 10 000 чел."; break;
					case "2": citySize = "до 50 000 чел."; break;
					case "3": citySize = "до 100 000 чел."; break;
					case "4": citySize = "до 500 000 чел."; break;
					case "5": citySize = "до 1 000 000 чел."; break;
					case "6": citySize = "более 1 000 000 чел."; break;
				}
				if ((cfg.showmap) && ( (i==0) || (i==data.length - 1) || ((data[i].x != '0') && (data[i].x != '-1') && (data[i].x != '-2') && (parseInt(data[i].citysize) > 1)))) {
						var point = new GLatLng(parseFloat(data[i].y), parseFloat(data[i].x));
						points.push(point);
						var marker = new GMarker(point,style_marker);
						marker.bindInfoWindowHtml('<b>'+ data[i].name + '</b><br />Численность: ' + citySize + '<br />Длина от начала пути: ' + data[i].range + ' км.<br />Время в пути: ' + data[i].time);
						gmap.addOverlay(marker);
					}
				(i%2) ? className = ' class="td_2n"': className = '';
// 				total_time += parseInt(data[i].time);
				
        var tr = "<tr"+className+"><td>"+data[i].name+"</td>";
				if (cfg.showpopulation) tr += '<td>'+citySize+'</td>';
				tr += '<td>'+total_range+' км</td>';//'<td>'+make_time(total_time)+'</td>';
				if (cfg.showrange) tr += '<td>'+data[i].range+'</td>';
				if (cfg.showtime) tr += '<td>'+s2t(data[i].range)+'</td>';
				tr += '</tr>';
				$(tr).appendTo(tbl);
				total_range += parseInt(data[i].range);
			}
			var info = $('#route_info span');
			info[0].innerHTML = total_range + ' км';
 			info[1].innerHTML = s2t(total_range);
      
 			var machtab = 5;
      if (cfg.showmap){
				var route = new GPolyline(points,'#f73923',3,1,{clickable:false,geodesic:false,mouseOutTolerance:20});
				if (total_range < 200) machtab = 8;
				else if (total_range < 300) machtab = 7;
				else if (total_range < 500) machtab = 6;

				gmap.addOverlay(route);
				var x0 = (points[0].x + points[points.length - 1].x)/2;
				var y0 = (points[0].y + points[points.length - 1].y)/2;
				var dp = 0.1;
				if (points[0].x > points[points.length - 1].x) {
					var x1 = points[points.length - 1].x - dp;
					var x2 = points[0].x + dp;
				}else{
          var x1 = points[0].x - dp;
          var x2 = points[points.length - 1].x + dp;
				}
				if (points[0].y > points[points.length - 1].y) {
					var y1 = points[points.length - 1].y - dp;
					var y2 = points[0].y + dp;
				}else{
          var y1 = points[0].y - dp;
          var y2 = points[points.length - 1].y + dp;
				}
				var bound = new GLatLngBounds(new GLatLng(y1, x1),new GLatLng(y2, x2));
				gmap.setCenter(new GLatLng(y0, x0), gmap.getBoundsZoomLevel(bound));
			}
		});
	});
	$('#show_hide').click(function(){
		if ($(this).hasClass('act')){
			this.className = '';
			$('span',this).text('показать');
			$('#route_req').css('display','none');
		}else{
			this.className = 'act';
			$('span',this).text('скрыть');
			$('#route_req').css('display','block');
		}
	});
	$('#send_order').click(function(){
	  var form = $('#order')[0];
		var param = {};
    param.fio = form.fio.value;
    param.phone = form.phone.value;
    param.mail = form.mail.value;
    param.route_desc = form.route_desc.value;
    param.cargo = form.cargo.value;
    $.getJSON('send_order.php',param,function(data){
      alert(data.status);
    });
  });

// 	$.getJSON('random_route.php',{},function(data){
// 		$('#from').val(data.cA);
// 		$('#to').val(data.cB);
// 		$('#go').click();
// 	});
	var get = parseGet();
	if (get.from && get.to){
		$('#from').val(get.from);
		$('#to').val(get.to);
		$('#go').click();
	}
});
function make_time(min,choice){
	var h = parseInt(min/60);
	var m = parseInt(min%60);
	if (choice){
		return h + ' час'+padej(h,'ов','','а') + ' ' + m + ' минут'+padej(m,'','а','ы');
	}else{
	  if (h < 10) h = '0' + h;
	  if (m < 10) m = '0' + m;
		return h+':'+m;
	}
}


function padej(n,v0,v1,v2){
	var mod = n % 100;
	if ((mod >= 10) && (mod <=20)) return v0;
	else{
		mod = n % 10;
		if ((mod >= 2) && (mod <=4)) return v2;
		else if (mod == 1) return v1;
				 else return v0;
	}
}

function s2t(s){
	var h = parseInt(s/70);
	var d = parseInt(h/10);
	var t = '';
	if (d > 0) t += d + ' д. ';
	h = h - d*10;
	if (h > 0) t += h + ' ч. ';
	var m = parseInt((s%70)/7*6);
	if (m > 0) t += m + ' м. ';
	if (!t) t = 0;
	return t;
}

function parseGet(){
	var res = {}, tmp;
  var get = new String(window.location);
  if ((pos = get.indexOf('?')) !=-1){
		get = get.substr(++pos).split('&');
		for (var i = get.length -1; i>=0;i--) {
		  tmp = get[i].split('=');
			res[tmp[0]] = win2unicode(unescape(tmp[1]));
			res[tmp[0]] = res[tmp[0]].replace(/[+]/g," ");
		}
	}
	return res;
}

function win2unicode(str) {
   var charmap   = unescape(
      "%u0402%u0403%u201A%u0453%u201E%u2026%u2020%u2021%u20AC%u2030%u0409%u2039%u040A%u040C%u040B%u040F"+
      "%u0452%u2018%u2019%u201C%u201D%u2022%u2013%u2014%u0000%u2122%u0459%u203A%u045A%u045C%u045B%u045F"+
      "%u00A0%u040E%u045E%u0408%u00A4%u0490%u00A6%u00A7%u0401%u00A9%u0404%u00AB%u00AC%u00AD%u00AE%u0407"+
      "%u00B0%u00B1%u0406%u0456%u0491%u00B5%u00B6%u00B7%u0451%u2116%u0454%u00BB%u0458%u0405%u0455%u0457")
   var code2char = function(code) {
               if(code >= 0xC0 && code <= 0xFF) return String.fromCharCode(code - 0xC0 + 0x0410)
               if(code >= 0x80 && code <= 0xBF) return charmap.charAt(code - 0x80)
               return String.fromCharCode(code)
            }
   var res = ""
   for(var i = 0; i < str.length; i++) res = res + code2char(str.charCodeAt(i))
   return res
}
