﻿/// <reference name="MicrosoftAjax.js"/>

/*
Description:
Contains javascript code for the LocationsRegister function.
*/
var ZOOM_LEVEL_1 = 3;
var ZOOM_LEVEL_2 = 7;
var ZOOM_LEVEL_3 = 10;
var ZOOM_LEVEL_5 = 14;
var geocoder = null;
var reasons = [];
var GoogleMapLocation = null;
var $locationListsContainer = null;
var tipRegisterMarker;
var searchLevel = 1;

Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(bindEventsForLocationRegister);

function bindRegisterLocationEvents()
{
    $("div.location-lists-container").slideDown("slow");
    $("div.panel-google-frame-and-text div.form-command-buttons-container").show();
    $("body.tipscommunity-tiptargetview a.adjust-map, body.tipscommunity-locationupdate a.adjust-map").hide();
    tipRegisterMarker.enableDragging(); 
}


$(document).ready
(
    function() {
        // Google map on location register
        if ($("div.google-map-location-register").length) {
            initializeGoogleMapLocationRegister();
        }

        // Register category list change handler turning corresponding textbox on/off
        $('div.tiptarget-create select').change
        (
            function() 
            {
                var 
                    value = $(this).val(),
                    isInitialValue = value == '-1',
                    $tipTargetLabelAndInput = $('div.tiptarget-create div.tiptarget-name input, div.tiptarget-create div.tiptarget-name label');
                    
                if (isInitialValue) 
                {
                    $tipTargetLabelAndInput.attr('disabled', 'disabled');
                }
                else 
                {
                    $tipTargetLabelAndInput.removeAttr('disabled');
                    $tipTargetLabelAndInput.val('');
                }
                $('div.tiptarget-create div.tiptarget-name input').get(0).TextBoxSearch.set_categoryIDs(isInitialValue ? null : value.toString());
            }
        );

        // Calculate overlay layer sizes on each wizard step
        $('div.wizard-step').each
        (
            function() {
                var 
                    $wizardStepDiv = $(this),
                    $overlayDiv = $wizardStepDiv.find('div.overlay');
                $overlayDiv.width($wizardStepDiv.width() - 10);
                $overlayDiv.height($wizardStepDiv.height() - 24);
            }
        );

        $("div.panel-google-frame-and-text div.form-command-buttons-container a.first").click(function() {
            $("div.panel-google-frame-and-text div.form-command-buttons-container").hide();
            $("div.location-lists-container").slideUp("slow");
            $("a.adjust-map").show();
            tipRegisterMarker.disableDragging();
            return false;
        });

        $("body.tipscommunity-tiptargetview a.adjust-map, body.tipscommunity-locationupdate a.adjust-map").click(function() {
            bindRegisterLocationEvents();
        });


        $("a.change-map").click(function() {
            $("div.location-lists-container").css("margin-top", "20px");
            bindRegisterLocationEvents();
        });
    }
);

// Put the marker on the map from a database hit
function setUpDBHit(searchString, latitude, longitude, address, countryNameCode, zoomLevel, accuracy)
{   
    hideGoogleHits();
    $("span#current-location").text(searchString);
    placeMarkerOnMap(latitude, longitude, zoomLevel, true);  
    GoogleMapLocation = new GoogleLocation(latitude, longitude, address, countryNameCode, null, zoomLevel);  
}

// Hides the error message
function hideErrorMessage()
{   
    $("span#google-error").html("").hide();
}

// Shows the error message
function showErrorMessage()
{   
    $("span#google-error").html(globalResourceTextInstance.tipsSearchNoResult).show();
    hideGoogleHits();
}

function hideGoogleHits()
{
    $("div#google-hits").fadeOut("slow");
}


function bindEventsForLocationRegister()
{    
    if ($locationListsContainer == null)
    {
        // Initialize the location lists container variable
        $locationListsContainer = $('div.location-lists-container');
    }

    $locationListsContainer.find('input.find-adress-on-map').click
    (
        function (e)
        {
            e.preventDefault();
            putOnMap();            
        }
    );

    $locationListsContainer.find('select.country-drop').change
    (
        function()
        {
            if((this.selectedIndex != 0) && (this.selectedIndex != (this.length - 1)))   
            { 
                var location = eval('(' + $locationListsContainer.find("select.country-drop option:selected").val() + ')');   
                if(location.Position.Latitude != 0 && location.Position.Longitude != 0)
                {                 
                   setUpDBHit(location.Name, location.Position.Latitude, location.Position.Longitude, location.Address, location.CountryCode, ZOOM_LEVEL_1);                                                        
                }
                else
                {
                    showErrorMessage();
                }
            }
        }
    );   
     
    $locationListsContainer.find('select.geographical-area-drop').change
    (
        function()
        {
            if((this.selectedIndex != 0) && (this.selectedIndex != (this.length - 1)))   
            {    
                var location = eval('(' + $locationListsContainer.find("select.geographical-area-drop option:selected").val() + ')');   
                if(location.Position.Latitude != 0 && location.Position.Longitude != 0)
                {   
                    setUpDBHit(location.Name, location.Position.Latitude, location.Position.Longitude, location.Address, location.CountryCode, ZOOM_LEVEL_2);               
                }
                else
                {
                    showErrorMessage();
                }                   
            }
         }
     );     
     
    $locationListsContainer.find('select.city-location-drop').change
    (
        function()
        {
            if((this.selectedIndex != 0) && (this.selectedIndex != (this.length - 1))) 
            {           
                var location = eval('(' + $locationListsContainer.find("select.city-location-drop option:selected").val() + ')');   
                if(location.Position.Latitude != 0 && location.Position.Longitude != 0)
                {  
                    setUpDBHit(location.Name, location.Position.Latitude, location.Position.Longitude, location.Address, location.CountryCode, ZOOM_LEVEL_3);                 
                }
                else
                {
                    showErrorMessage();
                }                    
           }     
         }
     );

    $locationListsContainer.find('input.geographical-area').blur
    (
        function() {
            var countryText = $locationListsContainer.find("select.country-drop option:selected").text();
            var geoText = $locationListsContainer.find("input.geographical-area").val();
            if (geoText != "") {
                if (geoText.toLowerCase() == countryText.toLowerCase()) {
                    var errorMessage = String.format('{0} "{1}" {2}', globalResourceTextInstance.tipsPreErrorTextGeoCountry, geoText, globalResourceTextInstance.tipsSuErrorTextGeoCountry);
                    validateLocationHierarchy(errorMessage, "geo-error-box", "geographical-area");
                    return false;
                }
                else {
                    //var location = eval('(' + $locationListsContainer.find("select.country-drop option:selected").val() + ')');
                    
               //     TUI.TipsCommunity.Templates.AjaxHandlers.Google.CheckIfGeoNameIsCity(location.ID, geoText, temp, fail);
                    

                    hierarchyOk("geo-error-box", "geographical-area");
                    putOnMap();                    
                }
            }
            else {
                hierarchyOk("geo-error-box", "geographical-area");
                $locationListsContainer.find("input.geographical-area-latitude-hidden").val("");
                $locationListsContainer.find("input.geographical-area-longitude-hidden").val("");
            }
        }
    );

    $locationListsContainer.find('input.city').blur
    (
        function() {
            var countryText = $locationListsContainer.find("select.country-drop option:selected").text();
            var geoText = "";
            if ($locationListsContainer.find("input.geographical-area").val() == "") {
                geoText = $locationListsContainer.find("select.geographical-area-drop option:selected").text();
            }
            else {
                geoText = $locationListsContainer.find("input.geographical-area").val();
            }

            var cityText = $locationListsContainer.find("input.city").val();
            var errorMessage = "";
            if (cityText != "") {
                if (cityText.toLowerCase() == geoText.toLowerCase()) {
                    errorMessage = String.format('{0} "{1}" {2}', globalResourceTextInstance.tipsPreErrorTextGeoCountry, geoText, globalResourceTextInstance.tipsSuErrorTextCityGeo);
                    validateLocationHierarchy(errorMessage, "city-error-box", "city")
                }
                else if (cityText.toLowerCase() == countryText.toLowerCase()) {
                    errorMessage = String.format('{0} "{1}" {2}', globalResourceTextInstance.tipsPreErrorTextGeoCountry, countryText, globalResourceTextInstance.tipsSuErrorTextCityCountry);
                    validateLocationHierarchy(errorMessage, "city-error-box", "city");
                }
                else {

                    var ok = true;

                    $("select.geographical-area-drop option").each(function() {
                        if ($(this).text() == cityText) {
                            errorMessage = String.format(globalResourceTextInstance.tipsCitySameAsGeo, cityText, globalResourceTextInstance.tipsCityGeo);
                            validateLocationHierarchy(errorMessage, "city-error-box", "city")
                            ok = false;
                        }
                    });

                    if (ok) {
                        hierarchyOk("city-error-box", "city");
                        putOnMap();
                    }
                }
            }
            else {
                hierarchyOk("city-error-box", "city");
                $locationListsContainer.find("input.city-latitude-hidden").val("");
                $locationListsContainer.find("input.city-longitude-hidden").val("");
            }
        }
     );
     
    $("form").submit(function() 
    {    
          /* Update geodata to the hidden fields for the TipTarget location to be saved on postback */
          if(GoogleMapLocation != null)
          {         
            $locationListsContainer.find("input.latitude-hidden").val(GoogleMapLocation.Latitude);
            $locationListsContainer.find("input.longitude-hidden").val(GoogleMapLocation.Longitude);   
            $locationListsContainer.find("input.zoom-level-hidden").val(GoogleMapLocation.ZoomLevel);           
          }
          else
          {
            return;
          }
        }
    );
}
/*
function fail(callBack) {
    alert("fail");
}
*/
/*
function temp(callBack) {    
    if (callBack == true) {
        var errorMessage = String.format('{0} "{1}" {2}', globalResourceTextInstance.tipsPreErrorTextGeoCountry, "geoText", globalResourceTextInstance.tipsSuErrorTextGeoCountry);
        validateLocationHierarchy(errorMessage, "geo-error-box", "geographical-area");
    }
    else {
        alert("SnickSnack");
        hierarchyOk("geo-error-box", "geographical-area");
        putOnMap();
    }
}
*/

function validateLocationHierarchy(errorMessage, errorBoxId, senderElementClass)
{
    $locationListsContainer.find("p#" + errorBoxId).text(errorMessage).fadeIn("slow");
    $locationListsContainer.find("input." + senderElementClass).css("background", "transparent url(/TipsCommunity/Includes/Images/Forms/textbox-normal-background-error.gif) no-repeat scroll left top");
    $(".form-command-buttons-container input.image").attr("disabled","disabled");
}

function hierarchyOk(errorBoxId, senderElementClass)
{
    $locationListsContainer.find("p#" + errorBoxId).fadeOut("slow");
    $locationListsContainer.find("input." + senderElementClass).css("background", "transparent url(/TipsCommunity/Includes/Images/Forms/textbox-normal-background.gif) no-repeat scroll left top");
    $(".form-command-buttons-container input.image").removeAttr("disabled");
}

function putOnMap()
{
    map.enableDragging();        
     
    var searchString = $locationListsContainer.find("select.country-drop option:selected").text();        
        
    var zoomLevel = ZOOM_LEVEL_2;
    
    
    if($locationListsContainer.find("input.geographical-area").val() != "")
    {
        searchString += ", " + $locationListsContainer.find("input.geographical-area").val();  
        searchLevel = 1;                       
    }
    else if($locationListsContainer.find("select.geographical-area-drop").css("display") != "none")
    {
        if($locationListsContainer.find("select.geographical-area-drop").val() != globalResourceTextInstance.tipsLocationGeographicalAreaTipsVoluntary)
        { 
            searchString += ", " + $locationListsContainer.find("select.geographical-area-drop option:selected").text();
            searchLevel = 1;
        }
    }
    
    if($locationListsContainer.find("input.city").val() != "")
    {       
        searchString += ", " + $locationListsContainer.find("input.city").val();
        zoomLevel = ZOOM_LEVEL_3;   
        searchLevel = 2;                                             
    }
    else if($locationListsContainer.find("select.city-location-drop").css("display") != "none")
    {
        if($locationListsContainer.find("select.city-location-drop").val() != globalResourceTextInstance.tipsPreselectedText)
        {
            var location = eval('(' + $locationListsContainer.find("select.city-location-drop option:selected").val() + ')');   
            searchString += ", " + location.Name;
            zoomLevel = ZOOM_LEVEL_3;      
            searchLevel = 2;                              
        }
     }         
    
    if($locationListsContainer.find("input.address-location-text").val() != "")
    {
        searchString += ", " + $locationListsContainer.find("input.address-location-text").val();                
        zoomLevel = ZOOM_LEVEL_5; 
        searchLevel = 3;              
    }
    
    SetGoogleMapsPosition(searchString, zoomLevel, searchLevel);
    $("span#current-location").text(searchString);     
}

// Sets upp the Google map for Register Location
function initializeGoogleMapLocationRegister()
{
    map = new GMap2($('div.google-map div.map-container').get(0));
    var lat = $(".latitude-hidden").val().replace(/,/,".");
    var lng = $(".longitude-hidden").val().replace(/,/,".");
    var zoom = parseInt($(".zoom-level-hidden").val());
    if((lat != "") && (lng != ""))
    {
        placeMarkerOnMap(lat, lng, zoom, false);  
        map.setCenter(new GLatLng(lat, lng), zoom);         
    }
    else
    {
        map.setCenter(new GLatLng(50.332795, -9.064442), 1);  
        tipRegisterMarker = new GMarker(new GLatLng(50.332795, -9.064442),{draggable: false});
        map.addOverlay(tipRegisterMarker);
    }

    map.enableDoubleClickZoom();    
    
    
    map.setMapType(G_PHYSICAL_MAP);    
    var smallZoomControl, mapTypeControl;
    GEvent.addListener(map, 'mouseover', function() { 
        smallZoomControl = new GSmallZoomControl(); 
        mapTypeControl = new GMapTypeControl();
        map.addMapType(G_PHYSICAL_MAP); 
        map.addControl(mapTypeControl);    
        map.addControl(smallZoomControl);
    });
    GEvent.addListener(map, 'mouseout', function() {                
        map.removeControl(smallZoomControl);
        map.removeControl(mapTypeControl);
    });    
    
    
    
    setupGeocoder(); 
}

// Places the marker on the map
function placeMarkerOnMap(lat, lng, zoomLevel, draggable)
{
    hideErrorMessage();
    var point = new GLatLng(lat,lng);
    map.setCenter(point,zoomLevel); 
    map.clearOverlays();  
    if(typeof(currentTipCategoryID) != 'undefined')
       tipRegisterMarker = newCategoryMarker(new GLatLng(lat, lng), currentLocation.Name, currentLocation.Url, GetCategoryMarker(currentTipCategoryID), true) 
    else
        tipRegisterMarker = new GMarker(new GLatLng(lat, lng),{draggable: true});
          
    
    
    if(draggable == false)
        tipRegisterMarker.disableDragging();
    
    GEvent.addListener(tipRegisterMarker, "dragend", function() {
	    var point = tipRegisterMarker.getLatLng();   	    
        GoogleMapLocation = new GoogleLocation((point.toUrlValue().split(",")[0]), (point.toUrlValue().split(",")[1]), null, null, null, zoomLevel);                
    }); 
    map.addOverlay(tipRegisterMarker);    
}
//######################## Location Register page ########################// 



// Places the marker on Google Maps in Register Location 
function placeMarkerCreateLocation(lat,lng, address, countryNameCode, accuracy, zoomLevel) 
{        
    var point = new GLatLng(lat,lng);
    map.setCenter(point,zoomLevel); 
    map.clearOverlays();        
    tipRegisterMarker = new GMarker(new GLatLng(lat, lng),{draggable: true});
    GoogleMapLocation = new GoogleLocation(lat,lng, address,countryNameCode, accuracy, zoomLevel);     
    GEvent.addListener(tipRegisterMarker, "dragend", setSubLocationPosition); 
    GEvent.addListener(tipRegisterMarker, "dragend", function() {
        var point = tipRegisterMarker.getLatLng();   
           GoogleMapLocation = new GoogleLocation((point.toUrlValue().split(",")[0]), (point.toUrlValue().split(",")[1]), address, countryNameCode, accuracy, zoomLevel);                
	}); 
     map.addOverlay(tipRegisterMarker); 
}

function setSubLocationPosition()
{
    var point = tipRegisterMarker.getLatLng();    
    if(searchLevel == 1)
    {    
        $(".geographical-area-latitude-hidden").val(point.toUrlValue().split(",")[0]);
        $(".geographical-area-longitude-hidden").val(point.toUrlValue().split(",")[1]);                       
    }
    else if(searchLevel == 2)
    {
        $(".city-latitude-hidden").val(point.toUrlValue().split(",")[0]);
        $(".city-longitude-hidden").val(point.toUrlValue().split(",")[1]);   
    }
}


// ====== Geocoding ======
function SetGoogleMapsPosition(searchString, zoomLevel, searchLevel) 
{  
    var address = null;  
    var place = null;
    var p = null;
    var countryNameCode = null;
    var accuracy = null;
    var internalZoomLevel = null;
   
    // ====== Perform the Geocoding ======     
    geocoder.getLocations(searchString, function (result)
    {        
        map.clearOverlays(); 
        if (result.Status.code == G_GEO_SUCCESS) 
        {          
            internalZoomLevel = zoomLevel;
            hideErrorMessage();
                        
            // ===== If there was more than one result, "ask did you mean" on them all =====
            if (result.Placemark.length > 1) 
            {                          
                var htmlContent = "";       
                
                // Loop through the results
                for (var i=0; i<result.Placemark.length; i++) 
                {                            
                    p = result.Placemark[i].Point.coordinates;
                    address = result.Placemark[i].address;
                    countryNameCode = result.Placemark[i].AddressDetails.Country.CountryNameCode;  
                                              
                    htmlContent += "<li>"                                    
                                    +"<a href='javascript:void(0);' onmouseover='placeMarkerCreateLocation("+p[1]+" , "+p[0]+","+'"'+address+'","'+countryNameCode+'",'+accuracy+','+zoomLevel+");'>"
                                    + address 
                                    + "</a></li>";                
                }                
                $("div#google-hits").fadeIn("slow");                
                $("ul#multiple-result").html(htmlContent).find("a").click
                (
                    function()
                    {
                        $("div#google-hits").fadeOut("slow");
                        if($(".address-location-text").val() != "")
                        {      
                            var addressStr = $(this).text().split(",");
                            $(".address-location-text").val(addressStr[0]);
                        }
                    }
                );
           
              }
              // ===== If there was a single marker =====
              else 
              {
                place = result.Placemark[0]; 
                p = place.Point.coordinates;            
                address = place.address;
                countryNameCode = place.AddressDetails.Country.CountryNameCode;          
                accuracy = place.AddressDetails.Accuracy;      

                placeMarkerCreateLocation(p[1], p[0], address, countryNameCode, accuracy, zoomLevel);           
                
                if(searchLevel == 1)
                {    
                    $(".geographical-area-latitude-hidden").val(GoogleMapLocation.Latitude);
                    $(".geographical-area-longitude-hidden").val(GoogleMapLocation.Longitude);                       
                }
                else if(searchLevel == 2)
                {
                    $(".city-latitude-hidden").val(GoogleMapLocation.Latitude);
                    $(".city-longitude-hidden").val(GoogleMapLocation.Longitude);   
                }     
                          
              }   
            }
            // ====== Decode the error status ======
            else 
            {
            
                var searchStringArray = new Array();
                searchStringArray = searchString.split(",");
                
                if(searchStringArray.length == 4)
                {   
                    SetGoogleMapsPosition((searchStringArray[0] + "," + searchStringArray[1] + "," + searchStringArray[3]) , zoomLevel, searchLevel) 
                }
                else if(searchStringArray.length == 3)
                {
                    SetGoogleMapsPosition((searchStringArray[0] + searchStringArray[2]) , zoomLevel, searchLevel) 
                }
                /*
                else if(searchStringArray.length == 2)
                {
                 
                    
                }
                else if(searchStringArray.length == 1)
                {
                    alert("1");
                }
            */
     
                 showErrorMessage();
            
                var reason= "Code " + result.Status.code;
              
                if (reasons[result.Status.code]) 
                {
                    reason = reasons[result.Status.code]          
                }           
            
                if(result.Status.code == G_GEO_UNKNOWN_ADDRESS)                    
                {
                    if(GoogleMapLocation)
                        placeMarkerCreateLocation(GoogleMapLocation.Latitude, GoogleMapLocation.Longitude, GoogleMapLocation.Address, GoogleMapLocation.CountryNameCode, GoogleMapLocation.Accuracy, internalZoomLevel);                 
                }
                
                if(searchLevel == 1)
                {    
                    $(".geographical-area-latitude-hidden").val("");
                    $(".geographical-area-longitude-hidden").val("");   
                }
                else if(searchLevel == 2)
                {
                    $(".city-latitude-hidden").val("");
                    $(".city-longitude-hidden").val("");   
                }
                
                                               
            }
          }
        );
  }
  
 function setupGeocoder()
 {
    // ====== Create a Client Geocoder ======
    geocoder = new GClientGeocoder(); 

    // ====== Array for decoding the failure codes ======
    reasons[G_GEO_SUCCESS]            = "Success"; //(200) /* TODO: Hårdkodad javascript text */
    reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value."; //(601) /* TODO: Hårdkodad javascript text */
    reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address."; //(602)/* TODO: Hårdkodad javascript text */
    reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons."; //(603)  /* TODO: Hårdkodad javascript text */
    reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given"; //(610) /* TODO: Hårdkodad javascript text */
    reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded."; //(620) /* TODO: Hårdkodad javascript text */
    reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed."; //(500)  /* TODO: Hårdkodad javascript text */
 }


 // Google location class 
 function GoogleLocation(latitude, longitude, address, countrynamecode, accuracy, zoomLevel) {
     this.Latitude = latitude;
     this.Longitude = longitude;
     this.Address = address;
     this.CountryNameCode = countrynamecode;
     this.Accuracy = accuracy;
     this.ZoomLevel = zoomLevel;
 }

 function newCategoryMarker(markerLocation, name, url, markerImage, allowDraging) {
     var marker = new GMarker(markerLocation, { icon: getSmallMarker(markerImage, "/TipsCommunity/Includes/Images/Google/Markers/shadow.png"), draggable: allowDraging, title: name });

     if (url != "") {
         GEvent.addListener(marker, 'click', function() {
             location.href = url;
         });
     }

     return marker;
 }

 function getSmallMarker(imgUrl, shadowUrl) {
     var icon = new GIcon(G_DEFAULT_ICON);
     icon.image = imgUrl;
     icon.shadow = shadowUrl;
     icon.iconSize = new GSize(26, 28);
     icon.shadowSize = new GSize(26, 28);
     icon.iconAnchor = new GPoint(12, 22);
     return icon;
 }

 function GetCategoryMarker(categoryId) {
     var markerImage = "";
     if (categoryId == "8")
         markerImage = "/TipsCommunity/Includes/Images/Categories/small-bubble-black.png";
     else if (categoryId == "9")
         markerImage = "/TipsCommunity/Includes/Images/Categories/small-bubble-orange.png";
     else if (categoryId == "10")
         markerImage = "/TipsCommunity/Includes/Images/Categories/small-bubble-purple.png";
     else if (categoryId == "11")
         markerImage = "/TipsCommunity/Includes/Images/Categories/small-bubble-blue.png";
     else if (categoryId == "12")
         markerImage = "/TipsCommunity/Includes/Images/Categories/small-bubble-red.png";
     else if (categoryId == "13")
         markerImage = "/TipsCommunity/Includes/Images/Categories/small-bubble-green.png";
     else if (categoryId == "14")
         markerImage = "/TipsCommunity/Includes/Images/Categories/small-bubble-yellow.png";
     else if (categoryId == "24")
         markerImage = "/TipsCommunity/Includes/Images/Categories/small-bubble-light-blue.png";

     return markerImage;
 }
 
//######################## End Location Register page ########################// 