﻿/// <reference path="jquery-1.3.vsdoc.js" />
var result_html = "";
var zoom_for_accuracy = [17, 12, 8, 6, 4, 3, 1, 0, 0];
var close_st ="<span class='close'><a href='#section m' onclick='return closeResults();' style='float: right' id='qc_close'>" + '[Zamknij]' + "</a></span>";
var googlePlace = null;
var tagPlace = null;
var address = "";
var search_working_mode = "default";
var iGoogleResults=0;
var iTagResults = 0;
var arrResults = new Array();
var ITEMS_PER_PAGE = 5;
   
        	
$(document).ready(function(){
  $("input[name$='placeToFind']").keypress(function (e) {
      if (e.which == 13 ) {              
          showLocation();
          return false;  
      }    
  });
});

function googleResultHandler(lt, ln, zoom, city, street, house) {
    map.setCenter(new GLatLng(parseFloat(lt), parseFloat(ln)), zoom);
    if (search_working_mode == "upload") {
        createOwnMarker(new GLatLng(parseFloat(lt), parseFloat(ln)),getTypeFromGoogleSearch(city,street,house));
        selectPlace(city, street, house, lt, ln, false);
    }
    return false;
}
function tagResultHandler(id, lt, ln, city, street, house){
    var z = 13;
    map.setCenter(new GLatLng(parseFloat(lt), parseFloat(ln)), z);
    if(search_working_mode == "upload"){
        createOwnMarker(new GLatLng(parseFloat(lt),parseFloat(ln)),getTypeFromGoogleSearch(city,street,house));
        selectedMarker.id = id;
        selectPlace(city, street, house, lt, ln, true);
    }
}

function buildGoogleResultLink(placemark){ 
    googlePlace = placemark;       
    var a = googlePlace.address;        
    var point = googlePlace.Point;
    currLat = point.coordinates[1];
    currLng = point.coordinates[0];
    var acc = googlePlace.AddressDetails ? googlePlace.AddressDetails.Accuracy : 8;
    var z = 17 - zoom_for_accuracy[Math.max(Math.min(acc, 8), 0)];

    arrResults.push("<div class='result'><span class='location'><a href='#section_map' onclick=\"googleResultHandler(" + point.coordinates[1] + "," + point.coordinates[0] + "," + z +
        ",'"+getCity(googlePlace)+"','"+getStreet(googlePlace)+"','"+getHouseNumber(googlePlace)+"')\" > "
           + prepareSearchResultName(googlePlace)+ "</a></span></div>");
}
function prepareSearchResultName(googlePlace) {
    var sReturn = getAdministrativeArea(googlePlace);
    if (getCity(googlePlace) != "")
        sReturn += ", " + getCity(googlePlace);
    if (getStreet(googlePlace) != "")
        sReturn += ", " + getStreet(googlePlace);
    if (getHouseNumber(googlePlace) != "")
        sReturn += ", " + getHouseNumber(googlePlace);
   
   return sReturn;

}

// addAddressToMap() is called when the geocoder returns an
// answer.  
function addAddressToMap(response) {
  
  if (!response || response.Status.code != 200) {
  //no results
  } 
  else if(response.Placemark.length == 1)
  {
  //one place found
    buildGoogleResultLink(response.Placemark[0]);
    iGoogleResults++;        
  }
  else
  {
        for (var i=0; i<response.Placemark.length ;i++)
        {
            iGoogleResults++;
            buildGoogleResultLink(response.Placemark[i]);
        }
       
  }
  handleResults();
}

// showLocation() is called when you click on the Search button
// in the form.  It geocodes the address entered into the fomr
// and adds a marker to the map at that location.
function showLocation() {
      iGoogleResults =0;
      iTagResults = 0;
      closeResults();
      arrResults.length = 0;
      address = $('input[name$=placeToFind]').val();
      geocoder.getLocations(address, addAddressToMap);
      
      return false;
}

function closeResults()
{
    $("#results").hide("slow");
    clearResults()
    $("#datapager-div").hide();
    $("#tools").hide();
    return false;
}
function clearResults() {
    result_html = "";
    $("#results .result").remove();
    $("#qc_close").remove();
    return false;
}

function prepareResults(response)
{
    $.each(response.Photos, function(i, item) {
        iTagResults++;
        tagPlace = item;
        var street = "";
        if (item.street != null)
            street = item.street;
        var house = "";
        if (item.house != null)
            house = item.house;

        var sTagResult = "<li><a href=\"#\" onclick=\"tagResultHandler(" + item.placeId + "," + item.lat + "," + item.lng;
        sTagResult += ",'" + item.locality + "','" + street + "','" + house + "'); closeResults(); return false;\">";
        sTagResult += item.title + ", ";
        sTagResult += item.locality + " ";
        if (item.street != null) {
            sTagResult += item.street + " ";
            if (item.house != null)
                sTagResult += item.house;
        }

        if (item.tags)
            sTagResult += ", Tagi: " + item.tags;
        sTagResult += "</a></li>";

        arrResults.push(sTagResult);
    });

      handleResults();

}
function handleResults() {
    if (iGoogleResults + iTagResults == 0) {
        $("#results").html('Nie możemy znaleźć <em>%slider</em>.'.replace("%slider", $('input[name$=placeToFind]').val()) + close_st).show("slow");
        $("#qc_close").click(function() { $(this).parent().hide('normal'); return false; });
    }
    else if (iGoogleResults + iTagResults == 1) {
        if (iTagResults > 0) {
            var street = "";
            if (tagPlace.street != null)
                street = tagPlace.street;
            var house = "";
            if (tagPlace.house != null)
                house = tagPlace.house;

            tagResultHandler(tagPlace.placeId, tagPlace.lat, tagPlace.lng, tagPlace.city, street, house);
        }
        else {
            var point = googlePlace.Point;
            var acc = googlePlace.AddressDetails ? googlePlace.AddressDetails.Accuracy : 8;
            var z = 17 - zoom_for_accuracy[Math.max(Math.min(acc, 8), 0)];

            googleResultHandler(point.coordinates[1], point.coordinates[0], z,
                    getCity(googlePlace), getStreet(googlePlace), getHouseNumber(googlePlace));
        }
    }
    else {
        paginateResults();
        $("#results").show("slow");
        $("#tools").show();
        $("#datapager-div").show();
        $("#qc_close").click(function() { $(this).parent().hide('normal'); return false; });
    }
}
function getGoogleNextPage(page_index, jq) {
    clearResults();
    for (var i = page_index * ITEMS_PER_PAGE; (i < page_index * ITEMS_PER_PAGE + ITEMS_PER_PAGE) && i<arrResults.length; i++) {
        result_html += arrResults[i];
    }
    $("#results").prepend(result_html);
    $("#tools").append(close_st);
    return false;
}
function paginateResults() {
    $("#datapager-div").pagination(iGoogleResults + iTagResults, {
        items_per_page: ITEMS_PER_PAGE,
        next_text: '→',
        prev_text: '←',
        next_show_always: false,
        prev_show_always: false,
        prev_class: "previous",
        current_class: 'active',
        next_class: "next",
        ending_class: "total",
        ellipse_class: "separator",
        num_display_entries: 5,
        callback: getGoogleNextPage
        }
    );
}

function getAdministrativeArea(place)
{
    if (place.AddressDetails.Country != null && place.AddressDetails.Country.AdministrativeArea!= null)
    {
        return place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
    }
    return "";
}
function getCity(place) {
    if (place.AddressDetails.Country != null && place.AddressDetails.Country.AdministrativeArea != null && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea != null && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality != null) {
        return place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
    }
    return "";
}
function getStreet(place)
{
    if (place.AddressDetails.Country != null && place.AddressDetails.Country.AdministrativeArea!= null && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea!=null &&
        place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality!= null && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare!=null)
    {
        var str = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
        if (gotNum(str))
        {
            return str.substring(0,str.lastIndexOf(' ')); 
        }
        else
        {
            return str;
        }
    }
    return "";
}
function getHouseNumber(place)
{
    if (place.AddressDetails.Country != null && place.AddressDetails.Country.AdministrativeArea!= null && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea!=null &&
        place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality!= null && place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare!=null)
    {
        var str = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
        if (gotNum(str))
        {
            return str.substring(str.lastIndexOf(' ')+1,str.length); 
        }
        else
        {
            return "";
        }
    }
    return "";
}
function gotNum(str)
{
    return /\d/.test(str);
}

