var maps = null;
var addressList = {
    avaible: [],
    zip: [],
    city: [],
    address: []
    };

function sortList(address_list_id) {
	$('#'+address_list_id).sortable({
        stop: function(event, ui) {
            var result = $('#'+address_list_id).sortable('toArray');
            var addressList_sortable = {
                avaible: [],
                zip: [],
                city: [],
                address: []
            };
            for ( i=0; i<result.length; i++ ) {
                var key = result[i].substring(5);
                addressList_sortable.zip[i]     = addressList.zip[key];
                addressList_sortable.city[i]    = addressList.city[key];
                addressList_sortable.address[i] = addressList.address[key];
                addressList_sortable.avaible[i] = addressList.avaible[key];
            }
            addressList = addressList_sortable;
            maps.needUpdate();
        }
    });
    $('#'+address_list_id).disableSelection();
}

function mapInit(parameters) {
    maps = new googleMaps( parameters.route_planner_map, parameters.route_planner_route );
    maps.needUpdate = function() {
        maps.generate(parameters.route_planner_distance, parameters.route_planner_address_list, parameters.route_planner_li);
    };
	if (parameters.route_custom_icon_enabled != 0) { customIcon = maps.createCustomIcon(parameters.route_custom_icon_image, parameters.route_custom_icon_width, parameters.route_custom_icon_height, parameters.route_custom_icon_aleft, parameters.route_custom_icon_atop); }
	
    if (parameters.route_largemapcontrol != 0) { maps.LargeMapControl(); }
    if (parameters.route_minimap != 0) { maps.MiniMap(); }
    if (parameters.route_addwheelsupport != 0) { maps.addWheelSupport(); }
	if (parameters.route_addpointmarker == 1) {
		maps.addPointMarker(maps.getPoint( parameters.route_lat, parameters.route_lon ), parameters.client_firm+'<br />'+parameters.client_address, parameters.route_infowindow_open );
		maps.setCenter( maps.getPoint( parameters.route_lat, parameters.route_lon ), 16);
	} else {
		maps.addAddressMarker( parameters.client_address, parameters.client_firm+'<br />'+parameters.client_address, parameters.route_infowindow_open );
		maps.setCenterAddress(parameters.client_address, 16);
	}
    maps.addList(parameters.route_planner_zip, parameters.route_planner_city, parameters.route_planner_address);
    setTimeout("maps.needUpdate()", 500);
}

function googleMaps( container, route ) {
    this.map         = null;
    this.geoCache    = null;
    this.geocoder    = null;
    this.directions  = null;
    this.lastPoint   = null;

    this.controls   = new Array();

    if ( GBrowserIsCompatible() ) {
        this.geoCache    = new GGeocodeCache();
        this.geoCoder    = new GClientGeocoder( this.geoCache );

        this.map = new GMap2(  document.getElementById( container ) );
		
        this.map.enableDoubleClickZoom();
        this.map.enableContinuousZoom();

        this.directions  = new GDirections(this.map, document.getElementById( route ));
    } else {
        alert('A böngésződ nem támogatja a Google Maps-hez szükséges funkciókat.');
    }
}

googleMaps.prototype = {

	needUpdate: function() {},

    //Az egér görgőjével lehessen zoomolni
    addWheelSupport: function() {
        this.map.enableScrollWheelZoom();
        function wheelevent(e) {
            if (!e){
                e = window.event
            }

            if (e.preventDefault){
                e.preventDefault()
            }
        
            e.returnValue = false;
        }
        GEvent.addDomListener(this.map.getContainer(), "DOMMouseScroll", wheelevent);
        this.map.getContainer().onmousewheel = wheelevent; 
    },

    //Infó ablak létrehozása a megadott ponton
    createInfoWindow: function( point, text, opened, customIcon ) {
		this.lastPoint = point;
		
		if ( customIcon !== null ) {
            markerOptions = { icon:customIcon };
        } else {
            markerOptions = {};
        }
		
		var marker = new GMarker( point, markerOptions );
        this.map.addOverlay( marker );

        if ( opened ) {
            marker.openInfoWindowHtml( text );
        } else {
            GEvent.addListener(marker, "mouseover", function() {
                marker.openInfoWindowHtml(text);
            });
        }
    },
	
	//Egyéni marker
	createCustomIcon: function(url, width, height, aLeft, aTop) {

        if ( aLeft == null ) {
            aLeft = 0;
        }

        if ( aTop == null ) {
            aTop = height;
        }

        var tempIcon = new GIcon(G_DEFAULT_ICON);
        tempIcon.image = url;
        tempIcon.iconSize = new GSize(width, height);
        tempIcon.shadow = '';
        tempIcon.iconAnchor = new GPoint(aLeft, aTop);
        return tempIcon;
    },

    //Nyilak + Zoom (+-) + Zoom csúszka
    LargeMapControl: function() {
        this.map.addControl(new GLargeMapControl());
    },

    //Nyilak + Zoom (+-)
    SmallMapControl: function() {
        this.map.addControl(new GSmallMapControl());
    },

    //Zoom (+-)
    SmallZoomControl: function() {
        this.map.addControl(new GSmallZoomControl());
    },

    //Kicsi térkép a jobb alsó sarokba
    MiniMap: function() {
        this.map.addControl(new GOverviewMapControl());
    },

    //Címhez tartozó koordináták lekérése és callback(point, args) -nak átadás
    getAddressPoint: function( address, callback ) {
        var args = arguments;
        this.geoCoder.getLatLng( address, function(point) { if (!point) {alert(address + " nem található"); } else { callback( point, args );} } );
    },

    //Címhez infó ablak készítése
    addAddressMarker: function( address, text, opened, customIcon ) {
        this.getAddressPoint( address, this._addMarker, text, opened, customIcon, this );
    },
   
    //Ponthoz infó ablak készítése
	addPointMarker: function( point, text, opened, customIcon ) {
        this.createInfoWindow( point, text, opened, customIcon );
    },

    //Térkép középpontjának és Zoom értékének beállítása
    setCenter: function( point, zoom ) {
        this.map.setCenter(point, zoom);
    },

    //Térkép középpontjának és Zoom értékének beállítása cím alapján
    setCenterAddress: function( address, zoom ) {
        this.getAddressPoint( address, function( point, args ) { args[3].setCenter(point, args[2]); }, zoom, this );
    },

    //Cím koordinátáinak kiiratása a firebug konzolra
    consolePoint: function( address ) {
        this.getAddressPoint( address, function( point ) { console.log(point.toString(), point); } );
    },

    //Google Pont létrehozása
    getPoint: function( cX, cY ) {
        return new GLatLng( cX, cY );
    },

    //Bogyókák törlése
    clearMarkers: function() {
        this.map.clearOverlays();
    },
	
    getDirections: function(args, distance) {
        var obj = this;
        GEvent.addListener(this.directions, "load", function() {
            var dist = 0;
            for (i=0; i<obj.directions.getNumRoutes(); i++ )
            {
                dist += obj.directions.getRoute(i).getDistance().meters;
				dist_km = Math.round(dist/100)/10;
				dist_km = dist_km+' km';
            }
            document.getElementById(distance).innerHTML = dist_km;        
        });

        this.directions.clear();
        this.directions.loadFromWaypoints(args,{getPolyline:true,getSteps:true});
    },

    _addMarker: function( point, args ) {
        args[5].createInfoWindow( point, args[2], args[3], args[4] );
    },

    /**
     * Több útvonal megadása
     */
    clearUL: function(ul)
    {
        var ul = document.getElementById(ul);
        while ( ul.childNodes.length != 0 ) {
            ul.removeChild(ul.childNodes[0]);
        }
    },

    addLI: function(i, name, distance, ul_, li_ )
    {
		if ( name == '' ) return false;
        var ul = document.getElementById(ul_);
        var li = document.createElement(li_);
        li.innerHTML = name+' <a href="#" onclick="maps.del('+i+', \''+distance+'\', \''+ul_+'\', \''+li_+'\' );">x</a>';
        li.id = 'addr_'+i;
        ul.appendChild(li);
        return true;
    },
	
	checkAddress: function( address, callback ) {
        var args = arguments;
        this.geoCoder.getLatLng( address, function(point) { if (!point) {alert(address + " nem található"); } else { callback( point, args );} } );
    },

    addList: function(z, c, a, from)
    {
		var address_ =  z+' '+c+' '+a;
		var found = false;

		this.geoCoder.getLatLng( address_, function(point) {
			if (!point) {
				alert(address_ + " nem található");
			} else {
				for ( var i=0; i<addressList.zip.length; i++ ) {
					if ( addressList.avaible[i] == 0 ) continue;
					if ( addressList.zip[i] == z && addressList.city[i] == c && addressList.address[i] == a ) {
						found = true;
						break;
					}
				}
				
				if ( from ) {
					addressList.avaible.reverse();
					addressList.zip.reverse();
					addressList.city.reverse();
					addressList.address.reverse();
				}

				addressList.avaible.push(1);
				addressList.zip.push(z);
				addressList.city.push(c);
				addressList.address.push(a);

				if ( from ) {
					addressList.avaible.reverse();
					addressList.zip.reverse();
					addressList.city.reverse();
					addressList.address.reverse();
				}
				maps.needUpdate();
			
			}
		});
				
		return false;
    },
	
    add: function(zip, city, address, distance, ul, li, from)
    {
        var z = document.getElementById(zip);
        if ( z.value == '' ) return false;

        var c = document.getElementById(city);
        if ( c.value == '' ) return false;

        var a = document.getElementById(address);
        if ( a.value == '' ) return false;

        var found = this.addList(z.value, c.value, a.value, from);
		
        if ( !found ) {
            maps.generate(distance, ul, li);
        }
    },
	
	reverse: function(distance, ul, li)
    {
		addressList.avaible.reverse();
		addressList.zip.reverse();
		addressList.city.reverse();
		addressList.address.reverse();
		maps.generate(distance, ul, li);
        return false;
    },

	del: function(i, distance, ul, li)
    {
		addressList.avaible[i] = 0;
        maps.generate(distance, ul, li);
    },

    generate: function(distance, ul, li)
    {
		this.clearUL(ul);
        var a = [];
        for ( var i=0; i<addressList.avaible.length; i++ ) {
            if ( addressList.avaible[i] == 0 ) continue;

            var addr = addressList.zip[i]+' '+addressList.city[i]+', '+addressList.address[i];
            if ( this.addLI(i, addr, distance, ul, li) ) {
                a.push(addr);
            }
        }

        maps.getDirections(a, distance);
    }
}
