var mapId = "map";
var serviceListId = "services-dt";
var brandId = "brand";
var serviceTypeMsgId = "service-type-msg";
var serviceMsgId = "service-msg";
var serviceResultPanel;
var serviceSearchResult;
var map;
var gLocalSearch;
var gCurrentResults = [];
var myPositionSelect;
var myPosition;
var serviceMarkers = new Array();
var serviceIcon = new GIcon();
var type;
var brand;
serviceIcon.image = 'images/partner-ico.gif';
serviceIcon.shadow = 'images/partner-ico-sh.png';
serviceIcon.iconSize = new GSize(44, 62);
serviceIcon.shadowSize = new GSize(74, 62);
serviceIcon.iconAnchor = new GPoint(22, 60);
serviceIcon.infoWindowAnchor = new GPoint(22, 60);

function addEvent(obj, event, funct) {
  if (obj.attachEvent) { //IE
    obj['e' + event + funct] = funct;
    obj['x' + event + funct] = function() {
      obj['e' + event + funct](window.event);
    }
    obj.attachEvent('on' + event, obj['x' + event + funct]);
  } else // other browser
    obj.addEventListener(event, funct, false);
}

function getObjectClass(obj) {
  if (obj && obj.constructor && obj.constructor.toString) {
    var arr = obj.constructor.toString().match(
      /function\s*(\w+)/);

    if (arr && arr.length == 2) {
      return arr[1];
    }
  }

  return undefined;
}

function setTypeForm(input) {
  if(input) {
    type = input.value;
    brand = null;
    loadBrandOptions(input.form);
  }
}

function setBrandForm(select) {
  if(select) {
    if(select.selectedIndex >= 0) {
      brand = select.options[select.selectedIndex].value;
      refreshServices();
    }
  }
}

function loadBrandOptions(form) {
  if(form && form.elements['brand']) {
    var brandEl = document.getElementById(brandId);
    if(brandEl) {
      brandEl.style.display = "none";
    }
    var select = form.elements['brand'];
    while(select.options.length > 0) {
      select.removeChild(select.options[select.options.length - 1]) ;
    }

    if(type) {
      
      // Define the callbacks for the asyncRequest
      var callbacks = {

        success : function (o) {

          // Process the JSON data returned from the server
          var brands = [];
          try {
            //brands = YAHOO.lang.JSON.parse(o.responseText);
            brands = eval('(' + o.responseText + ')');
          }
          catch (x) {
            alert("JSON Parse failed!");
            return;
          }

          //alert(brands);
          for(var i = 0; i < brands.length; i++) {
            var option = document.createElement("option");
            var textNode = document.createTextNode(brands[i].title);
            option.appendChild(textNode);
            option.value = brands[i].name;
            select.appendChild(option);
          }

          var serviceMsgEl = document.getElementById(serviceTypeMsgId);
          if(brands.length > 0) {
            brand = brands[0].name;
            //var brandEl = document.getElementById(brandId);
            if(brandEl) {
              brandEl.style.display = "block";
            }
            if(serviceMsgEl) {
              serviceMsgEl.style.display = "none";
            }
          } else {
            if(serviceMsgEl) {
              serviceMsgEl.style.display = "block";
            }
          }

          refreshServices();
          
        },

        failure : function (o) {
          if (!YAHOO.util.Connect.isCallInProgress(o)) {
            alert("Async call failed!");
            var serviceMsgEl = document.getElementById(serviceTypeMsgId);
            if(serviceMsgEl) {
              serviceMsgEl.style.display = "block";
            }
          }
        },

        timeout : 10000
      }
      YAHOO.util.Connect.initHeader("Pragma", "no-cache", true);
      YAHOO.util.Connect.initHeader("Cache-Control", "no-cache", true);
      YAHOO.util.Connect.asyncRequest('GET',"get/brands?company="+company+"&type="+type+"&localeTitle="+localeTitle, callbacks);
    }
  }
}

/*function LoadMapSearch() {
  var options = {};
  new GSmapSearchControl(
    document.getElementById("mapsearch"),             // container
    "Praha",   // center point
    options                                              // options
    );
}*/

function load() {
  if (GBrowserIsCompatible()) {

    // Create and Center a Map
    map = new GMap2(document.getElementById(mapId));
    map.setCenter(new GLatLng(centerLat, centerLng), 8);
    //map.enableScrollWheelZoom();
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());

    var options = {
    //resultList : document.getElementById("searchwell"),
    //onMarkersSetCallback : markersSet,
    //suppressInitialResultSelection : false,
    //suppressZoomToBounds : true
    };

    // Initialize the local searcher
    gLocalSearch = new google.search.LocalSearch(options);
    gLocalSearch.setCenterPoint(map);
    gLocalSearch.setResultSetSize(google.search.Search.LARGE_RESULTSET);
    gLocalSearch.setSearchCompleteCallback(null, OnLocalSearch);



    serviceResultPanel = new YAHOO.widget.Panel("services-panel", {
      visible:false,
      draggable:false,
      close:false
    } );
    serviceResultPanel.setHeader(text['services-header']);
    serviceResultPanel.render();

    serviceSearchResult = new YAHOO.widget.Panel(serviceMsgId+"Panel", {
      visible:false,
      draggable:false,
      close:false
    } );
    serviceSearchResult.setHeader(text['search-result']); 
    serviceSearchResult.setBody(text['search-no-result']); 
    serviceSearchResult.render(serviceMsgId);
    
  }
}

// Cancel the form submission, executing an AJAX Search API search.
function startSearch(value) {
  gLocalSearch.execute(value + " " + country);
  return false;
}

// Called when Local Search results are returned, we clear the old
// results and load the new ones.
function OnLocalSearch() {
  if (!gLocalSearch.results) return;
  var searchWell = document.getElementById("searchwell");

  // Clear the map and the old search well
  clearMarkers();
  searchWell.innerHTML = "";
  for (var i = 0; i < gCurrentResults.length; i++) {
    //if (!gCurrentResults[i].selected()) {
    map.removeOverlay(gCurrentResults[i].marker());
  //}
  }

  myPosition = null;
  gCurrentResults = [];
  if(gLocalSearch.results.length > 1) {
    var form = document.createElement("form");
    var label = document.createElement("label");
    label.setAttribute("for", "my-position-select");
    label.innerHTML = text['select-your-position'];
    myPositionSelect = document.createElement("select");
    myPositionSelect.id = "my-position-select";
    myPositionSelect.name = "my-position-select";
    myPositionSelect.className = "my-position-select";
    var option = document.createElement("option");
    var textNode = document.createTextNode(text['founded-postions']);
    option.appendChild(textNode);
    myPositionSelect.appendChild(option);
    myPositionSelect.onchange  = function () {
      if(this.selectedIndex > 0) {
        //alert(this.selectedIndex);
        var result = gCurrentResults[this.selectedIndex - 1];
        if(result) {
          map.closeInfoWindow();
          var searchwell = document.getElementById("searchwell");
          result.resultNode_ = result.resultHtml();
          searchwell.innerHTML = "";
          searchwell.appendChild(result.resultNode_);
          map.addOverlay(result.marker(G_DEFAULT_ICON));
          setMyPosition(result);
        }
      }
    }

    form.appendChild(label);
    form.appendChild(myPositionSelect);
    document.getElementById("searchwell").appendChild(form);
    for (i = 0; i < gLocalSearch.results.length; i++) {
      //alert(getObjectClass(gLocalSearch.results[i]));
      gCurrentResults.push(new LocalResult(gLocalSearch.results[i]));
    }
  } else if(gLocalSearch.results.length == 1) {
    var myPos = new LocalResult(gLocalSearch.results[0]);
    gCurrentResults.push(myPos);
    setMyPosition(myPos);
  }

// move the map to the first result
/*if(gLocalSearch.results.length > 0) {
    var first = gLocalSearch.results[0];
    map.panTo(new google.maps.LatLng(first.lat, first.lng));
  }*/
}

function setMyPosition(myPos) {
  if(!myPos) {
    return;
  }
  myPosition = myPos;
  var lat = parseFloat(myPosition.result.lat);
  var lng = parseFloat(myPosition.result.lng);

  // Define the callbacks for the asyncRequest
  var callbacks = {

    success : function (o) {

      // Process the JSON data returned from the server
      var services = [];
      try {
        //services = YAHOO.lang.JSON.parse(o.responseText);
        services = eval('(' + o.responseText + ')');
      }
      catch (x) {
        alert("JSON Parse failed!");
        return;
      }
      if(services.length == 0) {
        serviceResultPanel.hide();
        serviceSearchResult.show();
        return;
      } else {
        serviceSearchResult.hide();
      }

      var serviceDS = new YAHOO.util.LocalDataSource(services);
      var serviceCols = [
      {
        key:"title",
        label:text['title']
      },
      {
        key:"street",
        label:text['street']
      },
      {
        key:"city",
        label:text['city']
      },
      {
        key:"zip",
        label:text['zip'],
        width:45
      },
      {
        key:"phone",
        label:text['phone']
      },
      {
        key:"gps",
        label:"GPS"
      },
      {
        key:"types",
        label:text['type']
      }

      ];

      this.rowClick = function (event) {
        var service = serviceMarkers[this.getTrIndex(event.target)];
        if(service) {
          service.bublina();
        }
        window.location = "#top";
      }

      this.serviceTable = new YAHOO.widget.DataTable(serviceListId, serviceCols, serviceDS, {
        selectionMode:"single",
        scrollable:false
      });
      //this.serviceTable.setColumnWidth("zip", 45);
      this.serviceTable.subscribe("rowMouseoverEvent", this.serviceTable.onEventHighlightRow);
      this.serviceTable.subscribe("rowMouseoutEvent", this.serviceTable.onEventUnhighlightRow);
      this.serviceTable.subscribe("rowClickEvent", this.rowClick);
      
      setServices(services);
    },

    failure : function (o) {
      if (!YAHOO.util.Connect.isCallInProgress(o)) {
        alert("Async call failed!");
      }
    },

    timeout : 10000
  }
  if(type && brand) {
    YAHOO.util.Connect.initHeader("Pragma", "no-cache", true);
    YAHOO.util.Connect.initHeader("Cache-Control", "no-cache", true);
    YAHOO.util.Connect.asyncRequest('GET',"get/services?company="+company+"&lat="+lat+"&lng="+lng+"&type="+type+"&brand="+brand+"&localeTitle="+localeTitle, callbacks);
  } else {
    map.setCenter(new GLatLng(lat, lng));
    var serviceMsgEl = document.getElementById(serviceTypeMsgId);
    if(serviceMsgEl) {
      serviceMsgEl.style.display = "block";
    }
  }
}

// A class representing a single Local Search result returned by the
// Google AJAX Search API.
function LocalResult(result, index) {
  this.result = result;
  var searchwell = document.getElementById("searchwell");
  if(gLocalSearch.results.length == 1) {
    this.resultNode_ = this.resultHtml();
    searchwell.appendChild(this.resultNode_);
    map.addOverlay(this.marker(G_DEFAULT_ICON));
  } else if(gLocalSearch.results.length > 1) {
    this.resultNode_ = this.optionHtml(index);
    myPositionSelect.appendChild(this.resultNode_);
  }
}

// Returns the GMap marker for this result, creating it with the given
// icon if it has not already been created.
LocalResult.prototype.marker = function(opt_icon) {
  if (this.marker_) return this.marker_;
  var marker = new google.maps.Marker(new google.maps.LatLng(parseFloat(this.result.lat),
    parseFloat(this.result.lng)),
  opt_icon);
  GEvent.bind(marker, "click", this, function() {
    marker.openInfoWindow(this.markerHtml());
  });
  this.marker_ = marker;
  return marker;
}

// "Saves" this result if it has not already been saved
/*LocalResult.prototype.select = function() {
  if (!this.selected()) {
    this.selected_ = true;

    // Remove the old marker and add the new marker
    map.removeOverlay(this.marker());
    this.marker = null;
    map.addOverlay(this.marker(G_DEFAULT_ICON));

    // Add our result to the saved set
    document.getElementById("selected").appendChild(this.markerHtml());

    // Remove the old search result from the search well
    this.resultNode_.parentNode.removeChild(this.resultNode_);
  }
}*/

// Returns the HTML we display for a result before it has been "saved"
LocalResult.prototype.resultHtml = function() {
  var container = document.createElement("div");
  var html = '<div class="myplace">';
  html += '<div>'+text['your-position']+'</div>';
  html += '<div><strong>'+this.result.streetAddress+'</strong></div>';
  html += '<div>'+this.result.city+'</div>';
  html += '<div>'+this.result.country+'</div>';
  html += '</div>';
  container.innerHTML = html;
  GEvent.bindDom(container, "click", this, function() {
    map.closeInfoWindow();
    this.marker_.openInfoWindow(this.markerHtml());
  });
  return container;
}

LocalResult.prototype.optionHtml = function(index) {
  var option = document.createElement("option");
  var textNode = document.createTextNode(this.result.streetAddress + " " + this.result.city + " " + this.result.country);
  option.appendChild(textNode);
  option.value = index;
  return option;
}

// Returns the HTML we display for a result after it has been "saved"
LocalResult.prototype.markerHtml = function() {
  var html = '<div class="bublina">';
  html += '<div>'+text['your-position']+'</div>';
  html += '<div><strong>'+this.result.streetAddress+'</strong></div>';
  html += '<div>'+this.result.city+'</div>';
  html += '<div>'+this.result.country+'</div>';
  html += '</div>';
  return html;
}

function refreshServices() {
  clearMarkers();
  setMyPosition(myPosition);
}

function clearMarkers() {
  for(var i = 0; i < serviceMarkers.length; i++) {
    map.removeOverlay(serviceMarkers[i].marker);
  }
  serviceMarkers = new Array();
  var serviceList = document.getElementById(serviceListId);
  if(serviceList) {
    serviceList.innerHTML = "";
  }
  serviceResultPanel.hide();
}

function setServices(services) {
  //clearMarkers();
  if(!myPosition) {
    return;
  }

  for(var s = 0; s < services.length; s++) {
    new ServiceMarker(services[s]);
  }

  if(serviceMarkers.length > 0) {
    serviceResultPanel.show();
    var bounds = new GLatLngBounds();
    bounds.extend(myPosition.marker_.getLatLng());
    for (var i = 0; (i < serviceMarkers.length) && (i < 3); i++) {
      bounds.extend(serviceMarkers[i].latlng);
    }
    var number = map.getBoundsZoomLevel(bounds);
    map.setZoom(number);
    map.setCenter(bounds.getCenter());
  }
  myPosition.marker_.openInfoWindow(myPosition.markerHtml());
}

function ServiceMarker(service) {
  this.service = service;
  this.latlng = new GLatLng(service.lat, service.lng);
  this.marker = new GMarker(this.latlng, serviceIcon);
  this.lat = service.lat;
  this.lng = service.lng;

  map.addOverlay(this.marker);
  serviceMarkers[serviceMarkers.length] = this;
  
  GEvent.bind(this.marker, 'click', this, this.bublina);

}

ServiceMarker.prototype.bublina = function() {
  //alert("bublina: " + this.title + getObjectClass(this.marker));
  var html = '';
  if(this.service.www) {
    html = '<strong><a href="'+this.service.www+'" target="_blank">'+this.service.title+'</a></strong>';
  } else {
    html = '<strong>'+this.service.title+'</strong>';
  }
  html += '<div class="bublina">';
  html += '<div>'+this.service.street+'</div>';
  html += '<div>'+this.service.zip+' '+this.service.city+'</div>';
  html += '<div>'+text['phone']+': '+this.service.phone+'</div>';
  if(this.service.phone2) {
    html += '<div>'+text['phone']+': '+this.service.phone2+'</div>';
  }
  if(this.service.types && this.service.types.length > 0) {
    html += '<div>'+text['type']+': ';
    for(var t = 0; t < this.service.types.length; t++) {
      if(t == 0) {
        html += this.service.types[t];
      } else {
        html += ' \u2013'+this.service.types[t];
      }
    }
    html += '</div>';
  }
  if (myPosition && myPosition.result.ddUrlFromHere && myPosition.result.ddUrlFromHere != null) {
    html += '<div><a href="'+myPosition.result.ddUrlFromHere+'&hl='+lang+'&daddr=@'+this.lat+','+this.lng+'" target="_blank">'+text['navigate']+'</a></div>';
  }
  html += '</div>';
  this.marker.openInfoWindowHtml(html);
}

function markersSet(markers) {
  // note: markers is an array of LocalResult
  for(var i = 0; i < markers.length; i++) {
    var marker = markers[i].marker;
    var userPos = new UserPosition(markers[i].result);
    GEvent.bind(marker, 'infowindowopen', userPos, userPos.selectPosition);
  }
}

