﻿/* Waypoint marker */

function addWaypointMarker(waypoint) {
    var exist = false;
    for (j=0;j<addedMarkers.length;j++) {
        if (addedMarkers[j] == waypoint.ID) {
            exist = true;
            break;
        }
    }
    if (!exist) {
        var markerMng = new GMarkerManager(map);
        var markersS = [];
        var markersL = [];
        var latlng = new GLatLng(waypoint.Lat,waypoint.Lng); 
        
        var iconS = getWaypointIcon(waypoint,'t');;
        
        var markerS = new GMarker(latlng, { title: waypoint.Name, icon:iconS});

        GEvent.addListener(markerS, "click", function() {
                var zoomLevel = map.getZoom();
                if (zoomLevel >= 12 && zoomLevel <= 14) {
                    map.closeExtInfoWindow();
                    markerS.openExtInfoWindow(
                        map,
                        "marker_window_general",
                        openWaypointDetails(waypoint.ID),
                        {beakOffset: 3}
                    );
                }
        });
        
        var iconL = getWaypointIcon(waypoint,'');
        if (waypoint.Popular)
            iconL = getWaypointIcon(waypoint,'s');
        else if (waypoint.New)
            iconL = getWaypointIcon(waypoint,'f');

        var markerL = new GMarker(latlng, { title: waypoint.Name, icon:iconL});

        GEvent.addListener(markerL, "click", function() {
                var zoomLevel = map.getZoom();
                if (zoomLevel >= 15) {
                    map.closeExtInfoWindow();
                    markerL.openExtInfoWindow(
                        map,
                        "marker_window_general",
                        openWaypointDetails(waypoint.ID),
                        {beakOffset: 3}
                    );
                }
        });
        
        markersS.push(markerS);
        markersL.push(markerL);
        markerMng.addMarkers(markersS, 12, 14);
        markerMng.addMarkers(markersL, 15, 17);
        markerMng.refresh();
        
        addedMarkersList[addedMarkers.length] = markerS;
        addedMarkers[addedMarkers.length] = waypoint.ID;
        
        addedMarkersList[addedMarkers.length] = markerL;
        addedMarkers[addedMarkers.length] = waypoint.ID;
    }
}

/* Waypoint details */
function navigateToCityOnMapOpenWindow(waypointID, lat, lng) {
    
    var zoomLevel = map.getZoom();
    
    if (zoomLevel >= 12 && zoomLevel <= 17) {
        
        map.closeExtInfoWindow();
        
        doOpenWaypointId = waypointID;
        
        moveZoom(lat, lng, zoomLevel);
    }
}

function openWaypointDialog(waypointId) {
    var zoomLevel = map.getZoom();
    var open = (zoomLevel >= 12 && zoomLevel <= 14) ? 1 : 2;
    var indexOpen = 0;
    
    for (k=0;k<addedMarkersList.length;k++) {

        if (addedMarkers[k] == waypointId) {

            indexOpen += 1;
            
            if (zoomLevel >= 12 && zoomLevel <= 17 && indexOpen == open) {
                
                map.closeExtInfoWindow();
                
                var lat = addedMarkersList[k].getLatLng().lat();
                var lng = addedMarkersList[k].getLatLng().lng();
                 
                moveZoom(lat, lng, zoomLevel);

                addedMarkersList[k].openExtInfoWindow(
                    map,
                    "marker_window_general",
                    openWaypointDetails(addedMarkers[k]),
                    {beakOffset: 3}
                );                
            }
        }
    }
}

function openWaypointDetails(id) {
    var html = '';
    html += '<div id="waypointWindow" name="waypointWindow" style="padding:3px;"><div style="height:250px;width:440px;text-align:center;vertical-align:middle;">&nbsp;<br />&nbsp;<br /><div class=\"loader\">Laddar</div></div></div>';
    setTimeout('loadWaypointDetailsContent(\'' + id + '\')',1000);
    return html;
}

function loadWaypointDetailsContent(id) {
    PageMethods.GetWaypointDetailsContent(id, loadWaypointDetailsContentReceiver);
}

function loadWaypointDetailsContentReceiver(response) {
    if (response) {
        var waypointWindow = document.getElementById('waypointWindow');
        waypointWindow.innerHTML = response;
        map.getExtInfoWindow().resize();
        
        if (document.getElementById('wpExecCmd') != null) {
            var execCmd = document.getElementById('wpExecCmd').value;
            eval(execCmd);
        }                
    }
}

function closeWaypointDetails() {
   map.closeExtInfoWindow();
}

/* Edit waypoint */
function editWaypointDetails(waypointID) {
    var waypointWindow = document.getElementById('waypointWindow');
    waypointWindow.innerHTML = '<div style="height:250px;width:440px;text-align:center;vertical-align:middle;">&nbsp;<br />&nbsp;<br /><div class=\"loader\">Laddar</div></div>';
    PageMethods.GetWaypoint(waypointID, editWaypointDetailsReceiver);
}

function editWaypointDetailsReceiver(response) {
    if (response != null) {
        newWaypoint = response;
        loadNewWaypointForm(false);
    }        
}

/* New waypoint */
function initiateAddWaypoint() {

    if (addWaypoint) {

        map.closeExtInfoWindow();

        alert('Klicka på kartan där du vill lägga till en intressepunkt.\n\nFram till dess att du klickar på Sparaknappen kan du flytta intressepunkten genom att klicka, dra och släppa.');
        
        newWaypointListener = GEvent.bind(this.map, "click", this, function(marker,latlng) {
            if (newWaypointMarker == null) {

                if (latlng) {
                    addWaypoint = false;    
                
                    if (newWaypointMarker) {
                        map.removeOverlay(newWaypointMarker);
                    }
                
                    var newIcon = getNewWaypointIcon();
                    newWaypointMarker = new GMarker(latlng, {draggable: true, icon: newIcon});
                    
                    GEvent.addListener(newWaypointMarker, "dragstart", function() {
                      saveNewWaypointFormState();
                      map.closeExtInfoWindow();
                    });

                    GEvent.addListener(newWaypointMarker, "dragend", function() {
                        newWaypointMarker.openExtInfoWindow(
                            map,
                            "marker_window_general",
                            newWaypointForm(),
                            {beakOffset: 3}
                        );
                    });
                    
                    GEvent.addListener(newWaypointMarker, "click", function() {
                        newWaypointMarker.openExtInfoWindow(
                            map,
                            "marker_window_general",
                            newWaypointForm(),
                            {beakOffset: 3}
                        );
                    });
                    
                    map.addOverlay(newWaypointMarker);
     
                    newWaypointMarker.openExtInfoWindow(
                        map,
                        "marker_window_general",
                        newWaypointForm(),
                        {beakOffset: 3}
                    );
                    
                    GEvent.removeListener(newWaypointListener);    
                }
            } else {
                GEvent.removeListener(newWaypointListener);
                cancelNewWaypoint();
            }
        }); 
    }
}

var newWaypointAddressReceiverAttempts = 0;

function newWaypointAddressReceiver(response) {

    //if (response != null)
    //    alert('JSON:\n' + YAHOO.lang.JSON.stringify(response));

    newWaypointAddressReceiverAttempts += 1;
    
    //alert('newWaypointAddressReceiver:' + newWaypointAddressReceiverAttempts);
    
    if (newWaypointAddressReceiverAttempts == 3) {
        alert('Systemet kunde tyvärr inte automatiskt bestämma vilken stad punkten du lagt till finns i.\n\nVänligen skriv in namnet på staden i det rödmarkerade fältet i formuläret.');
        //map.closeExtInfoWindow();
        loadNewWaypointForm(true);
        return;
    } else if (newWaypointAddressReceiverAttempts > 5) {
        alert('Systemet kunde tyvärr inte bestämma en exakt position på punkten.\n\nPunkten kan därför inte sparas.\n\n.Vänligen försök igen lite senare.');        
        cancelNewWaypoint();
        return;
    }
    
    var debug = '';
    
    var street = '';
    var city = '';
    var region = '';
    var country = '';
    var go = true;

    if (!response || response.Status.code != 200) {
        alert('Status:' + response.Status.code);
    } else {
        try {
            var placemark = getPlacemark(response); //response.Placemark[0];
            //alert('placemark:\n' + YAHOO.lang.JSON.stringify(placemark));
        
            // City
            if (placemark.AddressDetails !=null && placemark.AddressDetails.Country != null && placemark.AddressDetails.Country.AdministrativeArea != null && placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea != null && placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality != null && placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName != null) {
                city = placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
            } else if (placemark.AddressDetails != null && placemark.AddressDetails.Country != null && placemark.AddressDetails.Country.SubAdministrativeArea != null && placemark.AddressDetails.Country.SubAdministrativeArea.Locality != null && placemark.AddressDetails.Country.SubAdministrativeArea.Locality.LocalityName != null) {
                city = placemark.AddressDetails.Country.SubAdministrativeArea.Locality.LocalityName;
            } else if (placemark.AddressDetails != null && placemark.AddressDetails.Country != null && placemark.AddressDetails.Country.AdministrativeArea != null && placemark.AddressDetails.Country.AdministrativeArea.Locality != null && placemark.AddressDetails.Country.AdministrativeArea.Locality.LocalityName != null) {
                city = placemark.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
            } else if (placemark.AddressDetails != null && placemark.AddressDetails.Country != null && placemark.AddressDetails.Country.Locality != null && placemark.AddressDetails.Country.Locality.LocalityName != null) {
                city = placemark.AddressDetails.Country.Locality.LocalityName;
            }
            if (city != null && city.length > 0)
                newWaypoint.City.MapKey = city;
            else if (newWaypoint.State.CityName != null && newWaypoint.State.CityName.length > 0)
                newWaypoint.City.MapKey = newWaypoint.State.CityName;
            
            // Region
            if (placemark.AddressDetails != null && placemark.AddressDetails.Country != null && placemark.AddressDetails.Country.AdministrativeArea != null && placemark.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName != null) {
                region = placemark.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
            } else if (placemark.AddressDetails != null && placemark.AddressDetails.Country != null && placemark.AddressDetails.Country.SubAdministrativeArea != null && placemark.AddressDetails.Country.SubAdministrativeArea.SubAdministrativeAreaName != null) {
                region = placemark.AddressDetails.Country.SubAdministrativeArea.SubAdministrativeAreaName;
            } else if (placemark.AddressDetails != null && placemark.AddressDetails.Country != null && placemark.AddressDetails.Country.Locality != null && placemark.AddressDetails.Country.Locality.LocalityName != null) {
                region = placemark.AddressDetails.Country.Locality.LocalityName;
            }        
            if (region != null && region.length > 0)
                newWaypoint.City.Region.MapKey = region;
                
            // Country
            if (placemark.AddressDetails != null && placemark.AddressDetails.Country != null && placemark.AddressDetails.Country.CountryName != null)  {
                country = placemark.AddressDetails.Country.CountryName;
            } else if (placemark.address != null) {
                country = placemark.address.split(',')[placemark.address.split(',').length-1];            
            }
            if (country != null && country.length > 0)
                newWaypoint.City.Region.Country.MapKey = country;

            //alert('step1.\ncountry:' + newWaypoint.City.Region.Country.MapKey + '\nregion:' + newWaypoint.City.Region.MapKey  + '\ncity:' + newWaypoint.City.MapKey);

            if (newWaypoint.City.Region.MapKey.length == 0 || newWaypoint.City.MapKey.length == 0) {
                var address = '';
                
                if (newWaypoint.City.MapKey.length > 0 && placemark.AddressDetails.Country.CountryName != null) {
                    address = newWaypoint.City.MapKey + ', ' +  placemark.AddressDetails.Country.CountryName;
                } else if (newWaypoint.State.CityName != null && newWaypoint.State.CityName.length > 0 && placemark.AddressDetails.Country.CountryName != null) {
                    address = newWaypoint.State.CityName + ', ' +  placemark.AddressDetails.Country.CountryName;                
                } else if (placemark.AddressDetails.Country.PostalCode != null && placemark.AddressDetails.Country.PostalCode.PostalCodeNumber != null && placemark.AddressDetails.Country.CountryName != null) {
                    address = placemark.AddressDetails.Country.PostalCode.PostalCodeNumber + ', ' + placemark.AddressDetails.Country.CountryName;
                } 
                
                //alert('step 1:' + address);
                
                if (address.length > 0) {
                    //alert('go getLocations');
                    geocoder.getLocations(address, newWaypointAddressReceiver);
                    go = false;
                }
            }

        }
        catch(err) {
            debug += 'error:' + err.description + '\n\n';            
        }
    }

    if (go) {
        if (newWaypoint.City.MapKey.length > 0 && newWaypoint.City.Region.MapKey.length > 0 && newWaypoint.City.Region.Country.MapKey.length > 0) {
            var adr = newWaypoint.City.MapKey + ', ' + newWaypoint.City.Region.Country.MapKey;
            geocoder.getLocations(adr, newWaypointLocateCityReceiver);
        } else if (newWaypoint.City.MapKey.length > 0) {
            var adr = newWaypoint.City.MapKey;
            adr += (newWaypoint.City.Region.MapKey.length > 0 && newWaypoint.City.Region.MapKey != 'undefined') ? ', ' + newWaypoint.City.Region.MapKey : '';
            adr += (newWaypoint.City.Region.Country.MapKey.length > 0 && newWaypoint.City.Region.Country.MapKey != 'undefined') ? ', ' + newWaypoint.City.Region.Country.MapKey : '';
            
            //alert('step 1: ' + adr);
            //return;
            geocoder.getLocations(adr, newWaypointAddressReceiver);
        } else if (newWaypoint.City.MapKey.length <= 0) {
        
            //alert('step 2');
            newWaypointAddressReceiverAttempts = 2;
            newWaypointAddressReceiver(null);
        }

//        if (newWaypoint.City.MapKey.length <= 0 || newWaypoint.City.Region.MapKey.length <= 0 || newWaypoint.City.Region.Country.MapKey.length <= 0) {
//            alert('step 2\nCity:' + newWaypoint.City.MapKey + '\nRegion:' + newWaypoint.City.Region.MapKey + '\nCountry:' + newWaypoint.City.Region.Country.MapKey);
//            newWaypointAddressReceiverAttempts = 2;
//            newWaypointAddressReceiver(null);
            
            //return;
            //alert('Error 154.');
            //alert('#' + newWaypoint.City.MapKey + ', ' + newWaypoint.City.Region.Country.MapKey + '#');
//            //alert('Debug:\n' + debug);
//        } else {
//            var adr = newWaypoint.City.MapKey + ', ' + newWaypoint.City.Region.Country.MapKey;
//            alert('step 3:' + adr);
//            geocoder.getLocations(adr, newWaypointLocateCityReceiver);
//        }
    }
}

function getPlacemark(response) {
    var index = 0;
    var highestAccuracy = 0;
    for (i=0;i<response.Placemark.length;i++) {
        var placemark = response.Placemark[i];
        if (placemark.AddressDetails != null && placemark.AddressDetails.Accuracy != null) {
            if (placemark.AddressDetails.Accuracy > highestAccuracy) {
                highestAccuracy = placemark.AddressDetails.Accuracy;
                index = i;
            }
        }
        //alert('placemark:\n' + YAHOO.lang.JSON.stringify(placemark));
    }    
    
    return response.Placemark[index];
}

function newWaypointLocateCityReceiver(response) {
    //alert('newWaypointLocateCityReceiver');
    if (!response || response.Status.code != 200) {
        alert('Error 122');
    } else {
        placemark = response.Placemark[0];
        newWaypoint.City.IconLat = placemark.Point.coordinates[1];
        newWaypoint.City.IconLng = placemark.Point.coordinates[0];
        
        geocoder.getLocations(newWaypoint.City.Region.MapKey + ', ' + newWaypoint.City.Region.Country.MapKey, newWaypointLocateRegionReceiver);
    }
}

function newWaypointLocateRegionReceiver(response) {
    //alert('newWaypointLocateRegionReceiver');
    if (!response || response.Status.code != 200) {
        alert('Error 123');
    } else {
        placemark = response.Placemark[0];
        newWaypoint.City.Region.IconLat = placemark.Point.coordinates[1];
        newWaypoint.City.Region.IconLng = placemark.Point.coordinates[0];
        
        geocoder.getLocations(newWaypoint.City.Region.Country.MapKey, newWaypointLocateCountryReceiver);
    }
}

function newWaypointLocateCountryReceiver(response) {
    //alert('newWaypointLocateCountryReceiver');
    if (!response || response.Status.code != 200) {
        alert('Error 124');
    } else {
        placemark = response.Placemark[0];
        newWaypoint.City.Region.Country.IconLat = placemark.Point.coordinates[1];
        newWaypoint.City.Region.Country.IconLng = placemark.Point.coordinates[0];
    }
    
    newWaypointSaveDB();
}

/* Waypoint save */
function newWaypointSaveDB() {
    PageMethods.InsertWaypoint(newWaypoint,newWaypointSaveDBReceiver);
}

function newWaypointSaveDBReceiver(response) {
    //alert('newWaypointSaveDBReceiver');
    map.closeExtInfoWindow();
    newWaypoint = null;
    if (newWaypointMarker != null) {
        map.removeOverlay(newWaypointMarker);
        newWaypointMarker = null;
    }
    mapMoveEnd();
    addWaypoint = true;
    if (newWaypointListener != null) {
        GEvent.removeListener(newWaypointListener);
    }
    if (response && response.length > 0) {
        alert('Tack för ditt bidrag.\n\nDin ändring kommer att synas på en gång och inom kort att granskas av en av våra redaktörer.');    
    } else {
        alert('Error 125');
    }
    
    newWaypointAddressReceiverAttempts = 0;
}

/* Waypoint Form */
function newWaypointForm() {
    var html = '';
    
    html += '<div id="waypointWindow" name="waypointWindow" style="padding:3px;"><div style="height:250px;width:440px;text-align:center;vertical-align:middle;">&nbsp;<br />&nbsp;<br /><div class=\"loader\">Laddar</div></div></div>';
    
    setTimeout('loadNewWaypointForm(false)',1000);
    
    return html;
}
        
function loadNewWaypointForm(showCityField) {
    PageMethods.GetWaypointForm(showCityField, loadNewWaypointFormReceiver);
}

function loadNewWaypointFormReceiver(response) {
    if (response) {
        var waypointWindow = document.getElementById('waypointWindow');
        waypointWindow.innerHTML = response;
        map.getExtInfoWindow().resize();
        initiateNewWaypoint();
    }
}

function initiateNewWaypoint() {
    if (newWaypoint == null) {
        PageMethods.GetWaypointNew(initiateNewWaypointForm);
    } else {
        initiateNewWaypointForm(null);            
    }
}

function initiateNewWaypointForm(response) {

    if (response) {
        newWaypoint = response;
    }

    if (newWaypoint.Lat.length <= 0)
        newWaypoint.Lat = newWaypointMarker.getLatLng().lat();
    if (newWaypoint.Lng.length <= 0)
        newWaypoint.Lng = newWaypointMarker.getLatLng().lng();
        
    if (newWaypoint.Name.length > 0) {
        document.getElementById('waypointFormName').value = newWaypoint.Name;
    }

    if (newWaypoint.Category.ID > -1) {
        var categoryObj = document.getElementById('waypointFormCategory');
        for (i=0;i<categoryObj.options.length;i++) {
            if (categoryObj.options[i].value == newWaypoint.Category.ID) {
                categoryObj.options[i].selected = true;
            }
        }
        
        if (newWaypoint.ID != null && newWaypoint.Category.Color.length > 0) {
            categoryObj.disabled = true;
            document.getElementById('waypointFormIcon').src = '/resources/images/mapicons/' + newWaypoint.Category.Color + '.png';
        }
    }

    if (newWaypoint.Description.length > 0) {
        document.getElementById('waypointFormDescription').value = newWaypoint.Description;
    }
    
    if (newWaypoint.State.CityName.length > 0) {
        if (document.getElementById('waypointFormCity') != null)
            document.getElementById('waypointFormCity').value = newWaypoint.State.CityName;
    }
    
    if (newWaypoint.State.Condition == 'true')
        document.getElementById('waypointFormCondition').checked = true;
    
}

function saveNewWaypointFormState() {

    //alert('saveNewWaypointFormState');

    if (newWaypoint) {
        newWaypoint.Name = document.getElementById('waypointFormName').value;
        newWaypoint.Category.ID = document.getElementById('waypointFormCategory').options[document.getElementById('waypointFormCategory').selectedIndex].value;
        newWaypoint.Description = document.getElementById('waypointFormDescription').value;
        newWaypoint.State.Condition = (document.getElementById('waypointFormCondition').checked) ? 'true' : 'false';        
        
        if (document.getElementById('waypointFormCity') != null)
            newWaypoint.State.CityName = document.getElementById('waypointFormCity').value;
    }
}

function cancelNewWaypoint() {
    map.closeExtInfoWindow();
    newWaypoint = null;
    map.removeOverlay(newWaypointMarker);
    newWaypointMarker = null;
    mapMoveEnd();
    addWaypoint = true;
    newWaypointAddressReceiverAttempts = 0;
}

function saveWaypointDetails() {
    
    //alert('saveWaypointDetails');
    
    saveNewWaypointFormState();
    
    if (newWaypoint.State.Condition != 'true') {
        alert('Innan du kan spara den nya punkten måste du godkänna våra vilkor.');
    } else {
        var waypointWindow = document.getElementById('waypointWindow');
        waypointWindow.innerHTML = '<div style="height:250px;width:440px;text-align:center;vertical-align:middle;">&nbsp;<br />&nbsp;<br /><div class=\"loader\">Sparar</div></div>';
        if (newWaypoint.ID.length > 0) {
            newWaypointSaveDB();
        } else {
            newWaypointAddressReceiverAttempts = 0;
            geocoder.getLocations(newWaypointMarker.getPoint(), newWaypointAddressReceiver);    
        }
    }
    return false;
}

function toggleCondition() {
    var conditionRow = document.getElementById('waypointFormConditionsRow');
    if (conditionRow.style.display=='block') {
        conditionRow.style.display='none';
    } else {
        conditionRow.style.display='block';
    }
    
    map.getExtInfoWindow().resize();
    return false;
}
/* Test */
function openWaypointDetailsCmd() {
    map.openInfoWindow(map.getCenter(), document.createTextNode("Hello, world"));
}
