﻿jQuery.fn.extend({
	silGoogleMap: function(options) {
		return this.each(function() {
			new jQuery.silGoogleMap(this, options);
		});
	}
});

jQuery.silGoogleMap = function(obj, opt) {

  var opt = opt || {};
  opt.zoom = opt.zoom || 16;
  opt.googleLatLngX = opt.googleLatLngX || 50.257564;
  opt.googleLatLngY = opt.googleLatLngY || 19.025488;
  opt.mainPoints = opt.mainPoints || {};
  opt.data = opt.data || "";
  opt.infoWindowHtml = opt.infoWindowHtml || "tekst";
  opt.otherPoints = opt.otherPoints || {};
  opt.route = opt.route || 1;
  opt.lang = opt.lang || 'pl';
  var $select = $(obj);
  
  var gdir, map , control;
  var tmp_id = $select.attr("id");
  
  var bicon = new Object();
  bicon.iconSize = new GSize(32, 32);
  bicon.iconAnchor = new GPoint(16, 32);
  bicon.infoWindowAnchor = new GPoint(11, 33);

  var gicons = new Object();
  gicons["blue_pin"] = new GIcon(bicon);
  gicons["green_pin"] = new GIcon(bicon);
  gicons["light_blue_pin"] = new GIcon(bicon);
  gicons["pink_pin"] = new GIcon(bicon);
  gicons["red_pin"] = new GIcon(bicon);
  
  gicons["blue_pin"].image = 'blue-pushpin.png';
  gicons["green_pin"].image = 'grn-pushpin.png';
  gicons["light_blue_pin"].image = 'ltblu-pushpin.png';
  gicons["pink_pin"].image = 'pink-pushpin.png';
  gicons["red_pin"].image = 'red-pushpin.png';



  function google_load() {
    if (GBrowserIsCompatible()) {
      
      if(opt.route == 1) {
        if(opt.lang=='en')
          $select.before("<div id=\"wrap_2_" + tmp_id + "\" style=\"padding-bottom:20px;\"><div style=\"float:left\">City<br/><input type=\"text\" size=\"18\" id=\"fromAddress_1_" + tmp_id + "\" class=\"form\"/></div><div style=\"float:left\">Street<br/><input type=\"text\" size=\"22\" id=\"fromAddress_2_" + tmp_id + "\" class=\"form\"/></div><div style=\"float:left\">House Number<br/><input type=\"text\" size=\"12\" id=\"fromAddress_3_" + tmp_id + "\" class=\"form\"/></div><div style=\"float:right;padding-top:12px;\"><input id=\"button_1" + tmp_id + "\" name=\"submit\" type=\"button\" value=\"Find route\"/></div></div><br/><br/>");
        else
          $select.before("<div id=\"wrap_2_" + tmp_id + "\" style=\"padding-bottom:20px;\"><div style=\"float:left\">Miasto<br/><input type=\"text\" size=\"18\" id=\"fromAddress_1_" + tmp_id + "\" class=\"form\"/></div><div style=\"float:left\">Ulica<br/><input type=\"text\" size=\"22\" id=\"fromAddress_2_" + tmp_id + "\" class=\"form\"/></div><div style=\"float:left\">Nr domu<br/><input type=\"text\" size=\"12\" id=\"fromAddress_3_" + tmp_id + "\" class=\"form\"/></div><div style=\"float:right;padding-top:12px;\"><input id=\"button_1" + tmp_id + "\" name=\"submit\" type=\"button\" value=\"Wyznacz trasę\"/></div></div><br/><br/>");
        $select.before("<div id=\"silGoogleMap_Error_" + tmp_id + "\"></div>");
        $select.after("<div align=\"center\" id=\"silGoogleMap_Route_" + tmp_id + "\" style=\"display:none\"></div>");
        document.getElementById("silGoogleMap_Route_" + tmp_id).innerHTML = "";
      }
      
      if(opt.route == 1) {
        $("#button_1" + tmp_id).click(function() {
          setDirections2(document.getElementById('fromAddress_1_' + tmp_id).value + ', ' + document.getElementById('fromAddress_2_' + tmp_id).value + ' ' + document.getElementById('fromAddress_3_' + tmp_id).value);
        });
      }
      
      map = new GMap2(document.getElementById(tmp_id));
      var mapControl = new GMapTypeControl();

      map.addControl(mapControl);
      map.addControl(new GLargeMapControl());
      map.removeMapType(G_HYBRID_MAP);

      
      map.setCenter(new GLatLng(opt.googleLatLngX, opt.googleLatLngY), opt.zoom);
      marker = new GMarker(new GLatLng(opt.googleLatLngX, opt.googleLatLngY));
      map.addOverlay(marker);
      marker.openInfoWindowHtml(opt.infoWindowHtml);

      if(opt.otherPoints) {
        jQuery.each(opt.otherPoints, function(i, val) {
          var tmp_opt = val.split("::");
          tmp_opt[0] = parseFloat(tmp_opt[0]);
          tmp_opt[1] = parseFloat(tmp_opt[1]);
          var point = new GLatLng(tmp_opt[0], tmp_opt[1]);
          var options = {icon:gicons[tmp_opt[2]]};
          marker = new GMarker(point, options);
          map.addOverlay(marker);
          
          GEvent.addListener(marker, "click", function() {
            this.openInfoWindowHtml(i);
          });
        });
      }
      
      if(opt.mainPoints.length) {
        jQuery.each(opt.mainPoints, function(i, val) {
          var tmp_mpt = val.split("::");
          tmp_mpt[0] = parseFloat(tmp_mpt[0]);
          tmp_mpt[1] = parseFloat(tmp_mpt[1]);
          var point = new GLatLng(tmp_mpt[0], tmp_mpt[1]);
          var options = {icon:gicons[tmp_mpt[2]]};
          main_markers = new GMarker(point, options);
          map.addOverlay(main_markers);
          
          $("#fromAddress_4_" + tmp_id).append("<option>" + i +"</option>");
          $("#fromAddress_4_" + tmp_id).children("option:last").val(tmp_mpt[0] + ", " + tmp_mpt[1]);

          GEvent.addListener(main_markers, "click", function() {
            this.openInfoWindowHtml(i);
          });
        });
      }
      
      map.setCenter(new GLatLng(opt.googleLatLngX, opt.googleLatLngY), opt.zoom);
      
      if(opt.data.length>0 && opt.data!=",  ") {
        setDirections(opt.data);
      }
    }
  }

  function setDirections(fromAddress) {
    if(opt.route) {
      if(opt.data){
        fromAddress = opt.data;
        opt.googleLatLng = opt.googleLatLngX + ", " + opt.googleLatLngY;
      }
      else{
        opt.googleLatLng = $("#fromAddress_4_" + tmp_id).val();
      }
      gdir.load("from: " + fromAddress + " to: @" + opt.googleLatLng);
    }
    else {
      gdir.load("from: " + fromAddress + " to: @" + opt.googleLatLngX + ", " + opt.googleLatLngY);
    }
    document.getElementById("silGoogleMap_Route_" + tmp_id).style.display = 'block';
    map.setCenter(new GLatLng(opt.googleLatLngX, opt.googleLatLngY), opt.zoom);
  }
  
  function setDirections2(fromAddress) {
      document.getElementById("silGoogleMap_Route_" + tmp_id).innerHTML = "";
      if(opt.route == 1){
      gdir = new GDirections(map, document.getElementById("silGoogleMap_Route_" + tmp_id));
      GEvent.addListener(gdir, "load", onGDirectionsLoad);
      GEvent.addListener(gdir, "error", handleErrors);
    }
    if(opt.route) {
      opt.googleLatLng = opt.googleLatLngX + ", " + opt.googleLatLngY;
      gdir.load("from: " + fromAddress + " to: @" + opt.googleLatLng);
    }
    else {
      gdir.load("from: " + fromAddress + " to: @" + opt.googleLatLngX + ", " + opt.googleLatLngY);
    }
    document.getElementById("silGoogleMap_Route_" + tmp_id).style.display = 'block';
    map.setCenter(new GLatLng(opt.googleLatLngX, opt.googleLatLngY), opt.zoom);
  }

  function onGDirectionsLoad(){
    document.getElementById("silGoogleMap_Error_" + tmp_id).style.display = 'none';
  }

  function handleErrors(){
    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS){
      if(opt.lang=='en')
        document.getElementById("silGoogleMap_Error_" + tmp_id).innerHTML = "Could not find your desired location.<br/>Tip: type the exact location of (e.g. Ruda Slaska, Niedurnego, 30)";
      else
        document.getElementById("silGoogleMap_Error_" + tmp_id).innerHTML = "Nie znaleziono zadanej lokalizacji.<br/>Wskazówka: Szukając opisz dokładnie lokalizację, np: Ruda Śląska, Niedurnego 30.";
      $("#silGoogleMap_Error_" + tmp_id).slideDown(1000);
    }
    else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
      alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
      alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_BAD_KEY)
      alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
    else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
      alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
    else {
      if(opt.lang=='en')
        document.getElementById("silGoogleMap_Error_" + tmp_id).innerHTML = "Desired location is outside the wide map.";
      else
        document.getElementById("silGoogleMap_Error_" + tmp_id).innerHTML = "Zadany punkt wyjściowy znajduje poza zasięgiem systemu.";
      $("#silGoogleMap_Error_" + tmp_id).slideDown(1000);
    }
  }

  google_load();
  
}
