function resizeMap() {
    $('#mapcontainer').css('width', $(window).width()-312);
}
resizeMap();
$(window).resize(function() { resizeMap(); });

var markers;
var wp_string = [];
var searchFromList = false;

var MAPFILES_URL = "http://www.google.com/mapfiles/";
var GGeoAddressAccuracy = {
  "0": "Ismeretlen hely",
  "1": "Ország szintű",
  "2": "Terület szintű (állam, tartomány, prefektúra, stb.) ",
  "3": "Kistérségi szintű (megye, önkormányzat, stb.)",
  "4": "Községszintű (város, falu)",
  "5": "Postai kód szintű (irányítószám)",
  "6": "Utcaszintű",
  "7": "Csomópont szintű",
  "8": "Cím szintű",
  "9": "Pontos találat"
}
var GShowGeoData = {
//	"Ország": "Country/CountryName",
//	"Régió/Megye": "Country/AdministrativeArea/AdministrativeAreaName",
	"Irányítószám": "Country/AdministrativeArea/Locality/PostalCode/PostalCodeNumber",
	"Település": "Country/AdministrativeArea/Locality/LocalityName",
	"Kerület": "Country/AdministrativeArea/Locality/DependentLocality/DependentLocalityName",
	"Utca": "Country/AdministrativeArea/Locality/DependentLocality/Thoroughfare/ThoroughfareName",
	"Utcanév": "Country/Thoroughfare/ThoroughfareName",
	"Cím": "Country/AdministrativeArea/Locality/Thoroughfare/ThoroughfareName" 
}
var GNotFound = "A megadott keresés nem értelmezhető.\nKérem használja a következő formátumok egyikét:\nBudapest, Montevideo u. 9.\nKilenc lyukú híd\n47.678982,18.886313";
var selected = null;
var reverseIcon = null;
var contextMenu = null;

var hintboxParams = {
    url: 'index.php/getAddress', 
    immediateList: true,
    matchHint: false,
    autoDimentions: true,
    minChars: 1,
    separator: '\n',
    useCache: false,
    ajax: false,
    delay: 500,
    callback: function(url, cbfunc){
        forwardGeocodeCallback(url, cbfunc);
    }
};

$(document).ready(function() {
    var route = $.cookie('map_route');
    if (route) route = route.split('&');
    if (!route) {
    	route = [];
    } else
    if (route[0] == '') route = [];
    var newroute = getUrlParam('route');
    if (newroute) route.push(newroute);
    var template = '<div class="routepoint" id="rp{letter}"><div class="route_tab">{letter}</div><input type="text" value="" style="width: 170px;" class="text" /><a href="javascript:void(0)" class="del"><img src="images/del.gif" title="Elem törlése" alt="Elem törlése" /></a></div>';
    
    if (map_route!='') {
    	route = map_route.split('|');
    	setTimeout(function() {$('a.run_route_calc').click()}, 1500);
    }
    
    if (route.length) {
	    for(var i=0; i<route.length; i++) {
	    	var letter = String.fromCharCode(65+i);
	    	var $item = $('#rp'+letter);
	    	if (!$item.length) {
	    		$('#routeItems').append( $.nano(template, {letter: letter}) );
	    		$item = $('#rp'+letter);
	    		$('#routeItems').find('input:last').hintbox(hintboxParams);
	    	}
	    	$item.find('input').val(unescape(route[i])).removeClass('empty');
	    }
    }
    
    if (map_markers!='') {
    	var markers = map_markers.split('|');
    	for(var i=0; i<markers.length; i++) {
    		var latlng = markers[i].split(',');
    		var icon = new GIcon(G_DEFAULT_ICON);
    		var latlng = new GLatLng(latlng[0], latlng[1]);
            var marker = new GMarker(latlng, { icon: icon } );
	        GEvent.addListener(marker, "click", function() {
			  var myHtml = "<h1>" + latlng + "</h1>";
			  map.openInfoWindowHtml(latlng, myHtml);
			});
            map.addOverlay(marker);
    	}
    }
    
    $('#routeItems').sortable({
        axis: 'y',
        items: '.routepoint', 
        handle: '.route_tab',
        update: function() {
        	//console.log($("#routeItems").sortable('serialize'));
        	$('#routeItems .routepoint').each( function(n) {
        		$(this)
        		  .attr('id', 'rp'+String.fromCharCode(65+n))
        		  .find('.route_tab').text(String.fromCharCode(65+n));
        	});
        }
    });
    
    //map.addControl(new UtilityControl());
    
});

$(window).unload(function() {
    if (map) {
        var route = [];
        var cookie_options = { path: '/' }
        var routepoints = $('#routeItems .routepoint').length;
        for(var i=0; i<routepoints; i++) {
        	var $input = $('#rp'+String.fromCharCode(65+i)).find('input');
        	if (!$input.hasClass('empty')) route.push(escape($input.val()));
        }
        $.cookie('map_route', route.join('&'), cookie_options);
    }
});

function run_search_address(that) {
    new search_address(that);
}

function search_address(that) {
	var searchAddress = this;
	this.searchfield = $(that).find('input.text');
	this.startbutton = $(that).find('a.button');
	
	this.startbutton.click( function() {
		searchFromList = false;
		return getLocations(searchAddress.searchfield.val());
	});
	this.searchfield.keypress( function(e) {
		if (e.keyCode != 13) return;
		$(this).blur();
		searchFromList = false;
		return getLocations($(this).val());
	});
}

function run_make_search(that) {
	new make_search(that);
}

function make_search(that) {
    var makeSearch = this;
    this.inputfield = $(that).parents('div.inputs').find('input.text');
    
    $(that).click(function() {
        makeSearch.inputfield.val( $(that).text() );
        searchFromList = false;
        return getLocations($(that).text());
    });	
}

function run_make_search_results(that) {
    var makeSearchRes = this;
    this.inputfield = $(that).parents('div.inputs').find('input.text');
    
    $(that).find('ol li a').live('click', function() {
        //makeSearchRes.inputfield.val( $(this).text() );
        searchFromList = true;
        return getLocations($(this).text());
    }); 
}

function run_full_map(that) {
	$('#search_results').slideUp();
	showHungary(function() {searchFromList = false; getLocations($('#cim').val())});
	return false;
}

function forwardGeocodeCallback(address, callback) {
  var geocoder = new GClientGeocoder();
//  geocoder.setViewport(map.getBounds());
  geocoder.getLocations(unescape(address), function(response) {
    var result = [];
    if (! response) {
        result.push('Nincs válasz.');
	} else {
	    if (response.Status.code == 200) {
            $.each(response.Placemark, function() {
                result.push(this.address);
            });
	    } else {
	    	result.push('Nincs találat.');
	    }
	}
	
    callback(result.join('\n'));
  });  
}


function run_generate_route(that){ 
	/*
	$(that).find('.routepoint').live('keyup', function(e,f) {
		if (f) e.keyCode = f.keyCode;
		if (e.type == 'keyup' && (e.keyCode == 13)) {
			var id = e.currentTarget.id;
            if (!$("#"+id).find('input').hasClass('empty')) {
	            geocoder.getLatLng($("#"+id).find('input').val(), function(point) {
	            	contextMenu.clickedPoint_ = point;
	            	contextMenu.fromSidebar = true;
	            	if (id.substr(2) == 'A' || id.substr(2) == 'B') {
	            	    contextMenu.searchDirs_(id.substr(2));
	            	} else {
	            		console.log(contextMenu.dirmarks_[id.charCodeAt(2)-65]);
	            		contextMenu.dirmarks_[id.charCodeAt(2)-65].setLatLng(point);
	            		//console.log(contextMenu.dirmarks_[id.charCodeAt(2)-65]);
	            		//contextMenu.makeDirMarker_(point, id.substr(2))
	            		
	            		contextMenu.getDirs_(contextMenu.dirmarks_);
	            	}
	            	contextMenu.fromSidebar = false;
	            });
            }
            return false;
		}
	});
	*/
	
	$(that).find('.routepoint .text').hintbox(hintboxParams);   

	
	$(that).find('.routepoint .del').live('click', function() {
          var num_routes = $("#routeItems").children().length;
          var i = $(this).parents('.routepoint').attr('id').charCodeAt(2)-65;
          $("#rp"+String.fromCharCode(65+i)).remove();
          for(var n=i+1; n<=num_routes; n++) {
            $("#rp"+String.fromCharCode(65+n))
                 .attr("id", "rp"+String.fromCharCode(64+n))
                 .find(".route_tab").text(String.fromCharCode(64+n));
          }
	});
	
	$(that).find('.routepoint input').live('keypress', function(e) {
		if (e.keyCode == '13') {
			var $nextPoint = $(e.target).closest('.routepoint').next();
			if ( $nextPoint.length == 0 ) { 
				setTimeout( function() { $('.run_route_calc').click(); }, 200);
			} else {
				$nextPoint.find('input').focus();
			}
		} else {
			
		}
	});
	
}

function run_route_calc(that) {
	$(that).click(function() {
		//$('#routeItems .routepoint input').trigger('keyup', {originalEvent: {type: 'keyup'}, keyCode: 13});
		$.each(contextMenu.dirmarks_, function() {
			contextMenu.map_.removeOverlay(this);
		});
		contextMenu.dirmarks_ = [];
		contextMenu.chosen = null;
        contextMenu.heremarks_ = [];
        contextMenu.letterindex_ = -1;
        if (contextMenu.gdir) contextMenu.gdir.clear();
        contextMenu.routes_ = null;
		
		var waypoints = [];
		wp_string = [];
		$.each( $('#routeItems .routepoint'), function(index, value) {
            wp_string[index] = $(value).find('input').val();
            
            geocoder.getLatLng($(value).find('input').val(), function(point) {
                var id = $(value).attr('id');

                if (point == null) {
                	alert('A következő helyet nem tudtuk értelmezni, kérem ellenőrizze: '+$(value).find('input').val());
                	return false;
                }
                waypoints[index] = point;

                if (waypoints.length == $('#routeItems .routepoint').length) {
                	contextMenu.gdir = new GDirections(contextMenu.map_, $('#directions')[0]);
                	var opts = {getPolyline: true, getSteps: true };
					if (contextMenu.opts_) {
					   opts.avoidHighways = contextMenu.opts_.avoidHighways;
					   opts.travelMode = contextMenu.opts_.travelMode;
					}
                	
					GEvent.addListener(contextMenu.gdir, "addoverlay", function() {
                		$('#summary')
                			.html('<div class="info"><strong>Teljes útvonal:</strong><br /><span>'+contextMenu.gdir.getSummaryHtml()+'</span></div>');
                	});
					GEvent.addListener(contextMenu.gdir, "error", function() {
                		var stat = contextMenu.gdir.getStatus();
                		$('#summary').html('');
                		alert('A megadott helyek közt sajnos nem tudunk útvonalat tervezni, kérem pontosítson!');
                	});
                	contextMenu.gdir.loadFromWaypoints(waypoints, opts);
                } 
            });
		});
		
		return false;
	});
}

function run_travelmode_change(that) {
	$(that).change(function() {
		var avhwy_disabled = ($(that).val() ==  'walk');
		$('#opt_avhwy').attr('disabled', avhwy_disabled ? 'disabled' : '');
		
		contextMenu.opts_.travelMode = avhwy_disabled ? G_TRAVEL_MODE_WALKING : G_TRAVEL_MODE_DRIVING;
	});
}

function run_new_point(that) {
	var template = '<div class="routepoint" id="rp{letter}"><div class="route_tab">{letter}</div><input type="text" value="" style="width: 170px;" class="text" /><a href="javascript:void(0)" class="del"><img src="images/del.gif" title="Elem törlése" alt="Elem törlése" /></a></div>';
	$(that).click(function() {
		$('#routeItems').append( $.nano(template, {letter: String.fromCharCode(65+$('#routeItems .routepoint').length)}) );
		$('#routeItems').find('input:last').hintbox(hintboxParams).focus();
	});
}

function run_addopt_avhwy(that) {
	$(that).click(function() {
		contextMenu.opts_.avoidHighways = $(this).attr('checked');
	});
}

function getLocations(query) {
	if (/\s*^\-?\d+(\.\d+)?\s*\,\s*\-?\d+(\.\d+)?\s*$/.test(query)) {
	    var latlng = parseLatLng(query);
        reverseGeocode(latlng);
	} else {
	    forwardGeocode(query);
	}

    return false;
}

function parseLatLng(value) {
  value.replace('/\s//g');
  var coords = value.split(',');
  var lat = parseFloat(coords[0]);
  var lng = parseFloat(coords[1]);
  if (isNaN(lat) || isNaN(lng)) {
    return null;
  } else {
    return new GLatLng(lat, lng);
  }
}

function forwardGeocode(address) {
  geocoder = initGeocoder();
  geocoder.getLocations(address, function(response) {
    showResponse(response, false);
  });  
}

function reverseGeocode(latlng) {
  map.clearOverlays();
  map.panTo(latlng);
  var marker = new GMarker(latlng, { 'icon': reverseIcon });
  GEvent.addListener(marker, "click", function() {
    var myHtml = "<h1>" + latlng + "</h1>";
    map.openInfoWindowHtml(latlng, myHtml);
  });
  map.addOverlay(marker);
}

function reverseGeocode_orig(latlng) {
  geocoder = initGeocoder();
  geocoder.getLocations(latlng, function(response) {
    showResponse(response, true);
  });
  map.panTo(latlng);
  map.addOverlay(new GMarker(latlng, { 'icon': reverseIcon })); 
}

function initGeocoder(query) {
  selected = null;
  map.clearOverlays();
  var geocoder = new GClientGeocoder();
  geocoder.setViewport(map.getBounds());
  return geocoder;
}


function showResponse(response, reverse) { 
  if (! response) {
    alert(GNotFound);
  } else {
/*
    document.getElementById("requestQuery").innerHTML = response.name;
    document.getElementById("statusValue").innerHTML = response.Status.code;
    document.getElementById("statusConstant").innerHTML = GGeoStatusCode[response.Status.code];
    document.getElementById("statusDescription").innerHTML = GGeoStatusDescription[response.Status.code];

    document.getElementById("responseInfo").style.display = "block";    
    document.getElementById("responseStatus").style.display = "block";
*/  
    if (response.Status.code == 200) {
    	if (!searchFromList) {
	    	$('#search_examples').hide();
	    	var html = '';
	    	if (response.Placemark.length>1) {
		    	var resList = [];
		    	$.each(response.Placemark, function() {
		    		resList.push(this.address);
		    	});
		    	
		    	html = '<h4>Erre gondolt?</h4><ol><li><a href="javascript:void(0);" class="result">'+resList.join('</a></li><li><a href="javascript:void(0);" class="result">')+'</a></li></ol>';
	    	} else {
	            html = '<ol><li><a href="javascript:void(0);" class="result">'+response.Placemark[0].address+'</a></li></ol>';
	            plotMatchesOnMap(response, reverse);
	    	}
	    	html += '<a href="javascript:void(0)" onclick="run_full_map(this)">Keresés újra Magyarország egész területén</a>';
	    	$('#search_results').html( html ).slideDown();
    	} else {
    		plotMatchesOnMap(response, reverse);
    	}
    } else {
    	$('#search_examples').show();
    	$('#search_results').hide();
//      document.getElementById("responseCount").style.display = "none";
//      document.getElementById("matches").style.display = "none";
//      document.getElementById("query").value = "";
      if (!reverse) {
        alert(GNotFound);
        showHungary();
      }
    }
  }
}

function plotMatchesOnMap(response, reverse) {
  var resultCount = response.Placemark.length;
  
  info      = new Array(resultCount);
  details   = new Array(resultCount);
  markers   = new Array(resultCount);
//  polylines = new Array(resultCount);
  bounds    = new Array(resultCount);
  
  var icons   = new Array(resultCount);
  var latlngs = new Array(resultCount);
  
  var infoListHtml = "";
  
  for (var i = 0; i < resultCount; i++) {
    icons[i] = new GIcon(G_DEFAULT_ICON);
    icons[i].image = MAPFILES_URL + "marker" + String.fromCharCode(65 + i) + ".png";
    latlngs[i] = new GLatLng(response.Placemark[i].Point.coordinates[1],
                             response.Placemark[i].Point.coordinates[0]);
    markers[i] = new GMarker(latlngs[i], { icon: icons[i] } );
//    polylines[i] = getPolyline(response.Placemark[i]);
    bounds[i] = getBounds(response.Placemark[i]);
    info[i] = getInfoHtml(response.Placemark[i]);
    details[i] = getAddressDetailHtml(response.Placemark[i]);
    
    infoListHtml += getInfoListItem(i, icons[i].image, info[i]);
  }
/*  
  document.getElementById("matches").innerHTML = infoListHtml;
  document.getElementById("p0").style.border = "none";
  document.getElementById("matches").style.display = "block";
*/  
  if (! reverse) {
    zoomToBounds(bounds, map);
  }
    
  for (var i = 0; i < resultCount; i++) {
    map.addOverlay(markers[i]);
    addInfoWindowListener(i, markers[i], details[i]);
  }
  
  GEvent.trigger(markers[0], "click");
}

function getInfoListItem(i, iconUrl, info) {
  var html  = '<a onclick="selectMarker(' + i + ')">';
      html += '<div class="info" id="p' + i + '">';
      html += '<table><tr valign="top">';
      html += '<td style="padding: 2px"><img src="' + iconUrl + '"/></td>';
      html += '<td style="padding: 2px">' + info + '</td>';
      html += '</tr></table>';
      html += '</div></a>';
  return html;
}

function selectMarker(n) {
  GEvent.trigger(markers[n], "click");
}

function zoomToBounds(bounds, map) {
  var b = new GLatLngBounds();

  for (var i = 0; i < markers.length; i++) {
    b.extend(bounds[i].getSouthWest());
    b.extend(bounds[i].getNorthEast());
  }

  var center = b.getCenter();
  var zoom   = map.getBoundsZoomLevel(b);
  map.setCenter(center, zoom);
}

function addInfoWindowListener(i, marker, details) {
  GEvent.addListener(marker, "click", function() {
    if (selected != null) {
//      document.getElementById('p' + selected).style.backgroundColor = "white";
//      map.removeOverlay(polylines[selected]);
    }
    var zoomDelta = map.getBoundsZoomLevel(bounds[i]) - map.getZoom();
    if (zoomDelta < 0 || zoomDelta > 5) {
      map.setZoom(map.getBoundsZoomLevel(bounds[i]));
    }
    marker.openInfoWindowHtml(details);
    if (! map.getBounds().containsBounds(bounds[i])) {
      map.zoomOut();
      map.panTo(bounds[i].getCenter());
    }
//    map.addOverlay(polylines[i]);
//    document.getElementById('p' + i).style.backgroundColor = "#eeeeff";
//    document.getElementById('matches').scrollTop = document.getElementById('p' + i).offsetTop - document.getElementById('matches').offsetTop;
    selected = i;
  });
}

/*
function getPolyline(placemark) {
  var ne = new GLatLng(placemark.ExtendedData.LatLonBox.north, placemark.ExtendedData.LatLonBox.east);
  var se = new GLatLng(placemark.ExtendedData.LatLonBox.south, placemark.ExtendedData.LatLonBox.east);
  var sw = new GLatLng(placemark.ExtendedData.LatLonBox.south, placemark.ExtendedData.LatLonBox.west);
  var nw = new GLatLng(placemark.ExtendedData.LatLonBox.north, placemark.ExtendedData.LatLonBox.west);
  var polyline = new GPolyline([ne, se, sw, nw, ne], '#ff0000', 2, 1.0);
  return polyline;
}
*/

function getBounds(placemark) {
  var ne = new GLatLng(placemark.ExtendedData.LatLonBox.north, placemark.ExtendedData.LatLonBox.east);
  var sw = new GLatLng(placemark.ExtendedData.LatLonBox.south, placemark.ExtendedData.LatLonBox.west);
  var bounds = new GLatLngBounds(sw, ne);
  return bounds;
}

function getInfoHtml(placemark) {
  var html  = '<table class="tabContent">';
      html += tr('Address', placemark.address);
      html += tr('Coordinates', latlngtxt(placemark.Point.coordinates));
      html += tr('Bounds', boundstxt(placemark.ExtendedData.LatLonBox));
      html += tr('Accuracy', accuracytxt(placemark.AddressDetails.Accuracy));
      html += '</table>';
  return html;
}

function getAddressDetailHtml(placemark) {
  return html = '<table class="tabContent">' + getAddressDetailDt(placemark.AddressDetails, placemark) + '</table>';
}

function getAddressDetailDt(feature, placemark) {
  var html = '';
  for (var key in GShowGeoData) {
  	var path = GShowGeoData[key].split('/');
  	var data = feature;
  	for(var p in path) {
  		if (typeof data == 'object') {
  			data = data[path[p]];
  		} else {
  			data = 0;
  		}
  	}
  	if(data) html += tr(key, data);
  }
//  html += tr('Találat pontossága', GGeoAddressAccuracy[feature['Accuracy']]);
  if (html == '') {
  	html = '<h2>'+placemark.address+'</h2>('+placemark.Point.coordinates+')';
  }
  /*
  for (var key in feature) {
    if (feature[key] instanceof Array) {
      html += tr(key, feature[key][0]);
    } else if (feature[key] instanceof Object) {
      html += getAddressDetailDt(feature[key]);
    } else {
      html += tr(key, feature[key]);
    }
  }
  */
  return html;
}

function tr(key, value) {
  return '<tr><td style="text-align: right; vertical-align: top; white-space: nowrap;">' + key + ':</td><td style="font-weight: bold; white-space: nowrap;">' + value + '</td></tr>';
}

function latlngtxt(coordinates) {
  return '(' + coordinates[1] + ', ' + coordinates[0] + ')';
}

function boundstxt(latlonbox) {
  return latlngtxt([latlonbox.west, latlonbox.south]) + ' - ' + latlngtxt([latlonbox.east, latlonbox.north]);
}

function accuracytxt(accuracy) {
  return accuracy + ' - ' + GGeoAddressAccuracy[accuracy];
}
