/*
	© 2010 by Martin Teufel, OOP SOLUTIONS GmbH & Co. KG

  Don't remove these lines.

*/
 

 (function($) {
      oop.cmp = oop.cmp || {};
	    
	    var map,gdir,zoomLevel, addressMarker, zoomTimeout;
      var to_htmls = [];
      var from_htmls = [];
	    var geocoder = null;
	    var gmarkers = [];
	    var url = '/de-wGlobal/wGlobal/scripts/lib/api.php';
	    var zoomlevel_start = 10;
	    	    
	$.extend(oop.cmp, {
		google: {
			/**
			 * JS for component dealerlocator
			 *
			 * @param {String} c DOM Context
			 */
      
			init: function() {
        
				if ($("#map_container").length > 0) {
					
          map = new GMap2(document.getElementById("map_container"));
          map.setMapType( G_PHYSICAL_MAP );
          //map.setUIToDefault();
          $("#map_container").data('zoomlevel', 0);

          var ui = new GMapUIOptions();
          ui = {
            maptypes: {normal:true, physical:true},
            zoom: {scrollwheel:false},
            controls: {largemapcontrol3d:true},
            keyboard: true
          }
         
          map.setUI(ui);
          map.getPane(G_MAP_FLOAT_SHADOW_PANE).style.visibility="hidden";
          
          geocoder = new GClientGeocoder();

          oop.cmp.google.create_marker(lat, lon, html);
          oop.cmp.google.init_direction();
          
          oop.$('#map_container').delegate('div.haendler_info div.route a', 'click', function(){
            var id   = oop.$(this).attr('id');
            var href = oop.$(this).attr('href');
						oop.cmp.google.info_layer_direction(oop.cmp.google.sub_string(href, 1, href.length), id);
          });
          
          oop.$('#directions form.form_direction').submit(function(e){
            e.preventDefault();
						oop.cmp.google.get_direction();
          });
        }
			},
			get_direction: function(){
			  var opts = {};
        // ==== set the start and end locations ====
        var saddr = document.getElementById("saddr").value;
        var daddr = document.getElementById("daddr").value;
				gdir.load("from: "+saddr+" to: "+daddr, opts);

				map.closeInfoWindow();
				oop.$('#directions').addClass('ui-state-active');
        return false;
			},
      create_marker: function(lat, lon, address) {
        var point  = new GLatLng(lat, lon);
       
        var marker = new GMarker(point);
        map.setCenter(point, parseInt(10));
        //googleMarkerPoints[index] = marker;
        var i = (gmarkers === undefined) ? 0 : gmarkers.length;

                
        var html = '<div class="haendler_info">';
        html += address;
       
        var addr = address;

        html    += '</div>';

        GEvent.addListener(marker, 'click', function() {
          marker.openInfoWindowHtml(html);
          return false;
        });
        map.addOverlay(marker);
        return marker;
      },
      sub_string: function (str, from, to){
        var newString = str.substring(from, to);

        return newString;
      },
      is_int: function (input){
        return !isNaN(input)&&parseInt(input)==input;
      },
      get_url_param: function (url, name ){
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");

        var regexS = "[\\?&]"+name+"=([^&#]*)";
        var regex = new RegExp( regexS );
        var results = regex.exec( url );

        if ( results == null )
          return "";
        else
          return results[1];
      },
      log: function(text) {
        if (window.console && oop.debug) {
          console.log(text);
        }
      },
      init_direction: function(){
      // === create a GDirections Object ===
      gdir=new GDirections(map, document.getElementById("directions"));

      // === Array for decoding the failure codes ===
      var reasons=[];
      reasons[G_GEO_SUCCESS]            = "Success";
      reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
      reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
      reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
      reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
      reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
      reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";
      reasons[G_GEO_BAD_REQUEST]        = "A directions request could not be successfully parsed.";
      reasons[G_GEO_MISSING_QUERY]      = "No query was specified in the input.";
      reasons[G_GEO_UNKNOWN_DIRECTIONS] = "The GDirections object could not compute directions between the points.";

      // === catch Directions errors ===
      GEvent.addListener(gdir, "error", function() {
        var code = gdir.getStatus().code;
        var reason="Code "+code;
        if (reasons[code]) {
          reason = reasons[code]
        } 
				oop.$('#directions').addClass('ui-state-hide');
        alert("Failed to obtain directions, "+reason);
      });

      }
    }
	});
})(oop.$);
