(function($){
  var map;
  var searcher;
  var searchControl;
  var GoogleLinks = new Array();
  var Markers = new Array();  
  var stores = new Array();
  var settings = new Array();
  var infoWindow;

  // Display the dafault Map
  $.fn.default_map = function(options) {
    settings = {
        divMap : 'gmapslivesearch-map'
    }
    $.extend( settings, options );
    
    return this.each(function() {
      loadGoogleJsapi();
      
      // Load Google Maps
      function loadMaps(){
        google.load("maps", "3",  {other_params:"sensor=false","callback": createDefaultMap}); 
      }
      
      // Load Google JSAPI
      function loadGoogleJsapi(){
        $.getScript('https://www.google.com/jsapi?key=' + settings.apiKey, function(data, textStatus){
          loadMaps();
        });
      }
      
      function createDefaultMap(){
        var latlng = new google.maps.LatLng(settings.default_latitude, settings.default_longitude);
        var myOptions = {
            zoom: parseInt(settings.default_zoom),
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById(settings.divMap), myOptions);
      }
    });
  }

  // Display the Map related to the search
  $.fn.buynow = function(options, callback) {
    settings = {
        apiKey          : 'ABQIAAAANfhoe0INRhmAE6PvohZqUxT2yXp_ZAY8_ufC3CFXhHIE1NvwkxTopbkOmnwf3iP4JAZtWKM2LGWOwg',
        searchString    : 'coffee',
        address         : '10010',
        divMap          : 'gmapslivesearch-map',
        divWrapper      : 'gmapslivesearch-wrapper',
        markerPath      : null,
        markerExtension : 'png',
        divStores       : 'gmapslivesearch-stores',
        directionsTxt   : 'Map & Directions',
        zoom            : 15,
        radius          : 1,
        strokeColor     : "#A6CE39",
        strokeOpacity   : 0.8,
        strokeWeight    : 2,
        fillColor       : "#D2E363",
        fillOpacity     : 0.35,
        generateCircle  : false
    };
    $.extend( settings, options );

    var buyNowObj = $(this);

    buyNowObj.css('visibility','hidden');

    return this.each(function() {
      loadGoogleJsapi();

      if ($('#gmapslivesearch-printresults').length > 0) {
        $('#gmapslivesearch-printresults').attr('href', 'http://maps.google.com/maps?pw=2&q=' + settings.searchString +
            ' : ' + settings.address);
      }

      // Load Google Maps
      function loadMaps(){
        google.load("maps", "3",  {other_params:"sensor=false","callback": loadSearch}); 
      }
      // Load Google Local Search
      function loadSearch(){
        google.load('search' , '1',  {"callback": getSearchResultsAndCreateMap}); 
      }
      // Load Google JSAPI
      function loadGoogleJsapi(){
        $.getScript('https://www.google.com/jsapi?key=' + settings.apiKey, function(data, textStatus){
          loadMaps();
        });
      }

      //Generates an info window with the given content.
      function createInfoWindow(content) {
        if (infoWindow == undefined) {
          infoWindow = new google.maps.InfoWindow({content: content});
        }
        else {
          infoWindow.setContent(content);
        }
        return infoWindow;
      }

      // Get Search Results
      function getSearchResultsAndCreateMap(){
        var mapContainer = document.getElementById(settings.divMap); // build the map div

        // We're ready to build our map...
        var myOptions = {
            zoom: settings.zoom,
            mapTypeControl: true,
            mapTypeControlOptions: {
          style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
        },
        navigationControl: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(mapContainer, myOptions);

        // So let's build the search control
        searchControl = new google.search.SearchControl();
        searchControl.setResultSetSize(google.search.Search.LARGE_RESULTSET);
        // Initialize a LocalSearch instance
        searcher = new google.search.LocalSearch(); // create the object
        // Set the map's center point and finish!
        // Create a SearcherOptions object to ensure we can see all results
        var options = new google.search.SearcherOptions(); // create the object
        options.setExpandMode(google.search.SearchControl.EXPAND_MODE_OPEN);
        // Add the searcher to the SearchControl
        searchControl.addSearcher(searcher , options);
        // Set the Local Search center point
        searcher.setCenterPoint(settings.address);
        // Specify search quer(ies)
        searcher.execute(settings.searchString);
        // Draw the control
        searchControl.draw(document.getElementById("searcher"));      
        document.getElementById("searcher").innerHTML = "";
        // Set searchComplete as the callback function when a search is complete.
        // The localSearch object will have results in it.
        searchControl.setSearchCompleteCallback(searcher , function() {
          stores = searcher.results;
          addMarkersAndListStores();
        });
      }

      // Create markers fot the resulting map.
      function createMarkers(result, index, image) {
        var markerLatLng = new google.maps.LatLng(parseFloat(result.lat), parseFloat(result.lng));
        var marker = new google.maps.Marker({
          position: markerLatLng,
          map: map,
          icon: image
        });
        var storeInfo = '';

        google.maps.event.addListener(marker, 'click', function() {
          marker.setZIndex(9999);
          storeInfo += "<div>";
          storeInfo += "<b>" + result.titleNoFormatting + "</b><br>";
          storeInfo += "<span class='GMap_Else'>" + result.streetAddress + "<br>" + result.city + ", " +
          result.region + "</span><br>";
          storeInfo += "<span class='Links'><a href='javascript:goGoogle("+ index +")' class='Links mapDirections' rel='"
          + index +"'>" + Drupal.t('Directions to here') + "</a>";
          storeInfo += "</div>";
          createInfoWindow(storeInfo);
          infoWindow.open(map, this);
          storeInfo = '';
        });

        return marker;
      }

      // Add Makers to the Map, and Create the list of stores.
      function addMarkersAndListStores(){
        var controlContainer = document.getElementById(settings.divStores); // build the control div
        var storeInfo = '';
        storesListHtml = "<ul>";
        for (var i = 0; i < stores.length; i++) {
          var result = stores[i]; // Get the specific result
          //Add directions link to this store to the array
          GoogleLinks[i] = result.ddUrlToHere;

          var image = settings.markerPath + (i + 1) + settings.markerExtension;

          Markers.push(createMarkers(result, i, image));
          //Add the store to the list                
          storesListHtml += "<li>";
          storesListHtml += " <div class='GMap_Info'>";
          storesListHtml += "  <div class='GMap_Title'>" + result.titleNoFormatting + "</div>";
          storesListHtml += "  <div class='GMap_Address'>" + result.streetAddress + "</div>";
          storesListHtml += "  <div class='GMap_City_And_Region'>" + result.city + ", " + result.region + "</div>";
          storesListHtml += "  <div class='GMap_Phone'>";
          try {
            for (var p = 0; p<result.phoneNumbers.length; p++) {
              if (result.phoneNumbers[p].type == "") {
                storesListHtml += "    <span>Phone:</span> " + result.phoneNumbers[p].number + "<br />";
              } else {
                storesListHtml += "    <span>" + result.phoneNumbers[p].type + ": </span>" +
                result.phoneNumbers[p].number + "<br />";
              }
            }
          } catch(err) {
          }

          storesListHtml += " </div>";
          storesListHtml += "  <div class='LocationFooter'><a href='" + result.ddUrlToHere +
          "' class='Links mapDirections' rel='"+ i +"'>" + settings.directionsTxt + "</a></div>";
          storesListHtml += " </div>";
          storesListHtml += " <a href='#" + settings.divWrapper + "' class='centerMap' rel='"+ i +"'><img src='" +
          image + "' border='0' class='imgnumber' /></a>";
          storesListHtml += "</li>";
        }
        storesListHtml += "</ul>";

        controlContainer.innerHTML = storesListHtml;
        if (settings.generateCircle) {
          var myCircle = new google.maps.Circle({
            center: Markers[Markers.length - 1].getPosition(),
            map: map,
            radius: settings.radius * 1600 ,
            strokeColor: settings.strokeColor,
            strokeOpacity: settings.strokeOpacity,
            strokeWeight: settings.strokeWeight,
            fillColor: settings.fillColor,
            fillOpacity: settings.fillOpacity
          });
          var myBounds = myCircle.getBounds();

          map.setCenter(Markers[Markers.length - 1].getPosition());
          generateCircle = false;
          map.fitBounds(myBounds);
          map.setZoom(map.getZoom() + 1);       

        }
        else {

          if(Markers.length == 0) {          
            $('div#' + settings.divMap).css('display','none');
            $('div#' + settings.divStores).append('<h3>' + Drupal.t('No results found.') + '</h3>');
          } else {
            markersbounds = new google.maps.LatLngBounds();
            for(i=0; i< Markers.length; i++){
              markersbounds.extend(Markers[i].getPosition());
            }

            map.fitBounds(markersbounds);
            map.setCenter(markersbounds.getCenter());
            if(map.getZoom() > 16){
             map.setZoom(16);              
            };  
          }

        }

        if (typeof callback == 'function') { // make sure the callback is a function
          callback.call(this); // brings the scope to the callback
        }

        $('div#gmapslivesearch-loader').hide();
        buyNowObj.css('visibility','visible');     

        /*$('.mapDirections', controlContainer).click(function() {
        openDirections($(this).attr('rel'));
      });*/

        $('.centerMap', controlContainer).click(function() {
          var currentMarker = Markers[$(this).attr('rel')];
          lat = currentMarker.position.lat();
          lng = currentMarker.position.lng();
          centerLocation(lat,lng);
          currentMarker.setZIndex(9999);
          google.maps.event.trigger(currentMarker, 'click');
          return false;
        });
      }
      // Center the Maker
      function centerLocation(Lat, Lng) {
        bounds = map.getBounds();
        center = bounds.getCenter();
        ne = bounds.getNorthEast();
        // r = radius of the earth in statute miles
        var r = 3963.0;  
        // Convert lat or lng from decimal degrees into radians (divide by 57.2958)
        var lat1 = center.lat() / 57.2958; 
        var lon1 = center.lng() / 57.2958;
        var lat2 = ne.lat() / 57.2958;
        var lon2 = ne.lng() / 57.2958;
        // distance = circle radius from center to Northeast corner of bounds
        var dis = r * Math.acos(Math.sin(lat1) * Math.sin(lat2) + 
            Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1));
        map.setCenter(new google.maps.LatLng(Lat, Lng), 13);
      }
      // Open Google Maps page with directions to the store address
      function openDirections(LinkId) {
        if (GoogleLinks[LinkId] != '') {
          window.open(GoogleLinks[LinkId]);
        }
      }
      // Open Google Maps page with all results to print.
      function printResultPage(){ 
        window.open("http://maps.google.com/maps?pw=2&q=" + settings.searchString + " : " + settings.address, 526,370);
      }
    });
  }
})(jQuery);

function goGoogle(index) {
  jQuery('div#gmapslivesearch-stores ul li:eq('+ index +') a.mapDirections').trigger('click');
};
(function($){ 
  $(document).ready(function(){
    
    if (typeof(Drupal.settings.gmapslivesearch) != 'undefined'  && typeof(Drupal.settings.gmapslivesearch_input_data) != 'undefined') {

      function gmapsCallback(){
        if ($.browser.msie) {
          $("#gmapslivesearch-stores").jScrollPane({
            verticalDragMinHeight: 0,
            verticalDragMaxHeight: 0
          });
          Drupal.attachBehaviors($('#gmapslivesearch-map-results'));
          $('div.jspTrack').css('height', '440px');
        } else {
          $("#gmapslivesearch-stores").jScrollPane({
            verticalDragMinHeight: Drupal.settings.gmapslivesearch_results_scroll_js_drag_height,
            verticalDragMaxHeight: Drupal.settings.gmapslivesearch_results_scroll_js_drag_height
          });
          Drupal.attachBehaviors($('#gmapslivesearch-map-results'));
        }
      }

      $('#gmapslivesearch-map-results').buynow({
          'markerPath' : Drupal.settings.basePath + Drupal.settings.gmapslivesearh_map_bullet_folder,
          'markerExtension' : Drupal.settings.gmapslivesearh_map_bullet_extension,
          'generateCircle' : Drupal.settings.gmapslivesearch_input_data.gmapslivesearch_field_milessearch_within_enabled,
          'radius' : Drupal.settings.gmapslivesearch_input_data.gmapslivesearch_field_milessearch_within,
          'address' : Drupal.settings.gmapslivesearch_input_data.gmapslivesearch_field_address_to_search,
          'searchString': Drupal.settings.gmapslivesearch.gmapslivesearch_field_searchstring,
          'apiKey': Drupal.settings.gmapslivesearch.gmapslivesearch_field_googleapikey
        },
        gmapsCallback
      );
       
    }
    else if (Drupal.settings.gmapslivesearch_enabled_default_result == '1' && Drupal.settings.gmapslivesearch_default_result_latitude != '' && Drupal.settings.gmapslivesearch_default_result_longitude != ''){
      $('#gmapslivesearch-map-results').default_map({
        'default_latitude' : Drupal.settings.gmapslivesearch_default_result_latitude,
        'default_longitude' : Drupal.settings.gmapslivesearch_default_result_longitude,
        'default_zoom' : Drupal.settings.gmapslivesearch_default_result_zoom,
        'apiKey': Drupal.settings.gmapslivesearch_field_googleapikey
      });
    }
    
    //Behavior for search fields. Set the default text and remove it when field is on focus in case
    //user don't type anything get the default value and print on the field otherwise leave the input value.
    $('.gmapslivesearch-field-address-to-search').each(function(index, element){
      var default_text_field_address_to_search = Drupal.settings.gmapslivesearch_field_address_default_label;
      defaultValueFieldAddressToSearch($(element), default_text_field_address_to_search);
      $(element).focus(function() {
    	  $(element).css("font-style", "normal");
    	  clearValueFieldAddressToSearch($(element), default_text_field_address_to_search);
      });
      
      $(element).focusout(function() {
    	  defaultValueFieldAddressToSearch($(element), default_text_field_address_to_search);
      });
    });
    
    //FIND ONLINE form
    var find_online_form = $('form.gmapslivesearch-find-online-form');
    var find_online_select = $('select', find_online_form);
    var find_online_submit = $('a.gmapslivesearch-goto-online-store', find_online_form);

    handleGoToStoreLink(find_online_submit, find_online_select);

    find_online_select.change(function() {
      var box_wrapper = $(this).closest('div.buy-online-box-wrapper');
      var find_online_submit = $('a.gmapslivesearch-goto-online-store', box_wrapper);
      handleGoToStoreLink(find_online_submit, this);
    });
    
    //BUY NOW form
    var buy_now_form = $('form#gmapslivesearch-buy-now-form');
    var buy_now_submit = $('a.gmapslivesearch-goto-online-store', buy_now_form);
    var buy_now_select = $('select.gmapslivesearch-field-stores-search', buy_now_form);

    handleGoToStoreLink(buy_now_submit, buy_now_select);
    
    if (Drupal.settings.gmapslivesearch_remove_buy_now_button){
      buy_now_submit.hide();
      var buy_now_link = $('.form-item-gmapslivesearch-field-stores-search li a:not(:first)', buy_now_form);
      buy_now_link.click(function(){
        buy_now_submit.click();
      });
    }
    
    buy_now_select.change(function() {
      handleGoToStoreLink(buy_now_submit, this);
      if (Drupal.settings.gmapslivesearch_remove_buy_now_button){
        buy_now_submit.click();
      }
    });
  });
  
  function handleGoToStoreLink(link, store_selected) {
    link.attr('href', $(':selected', store_selected).val());
    link.unbind('click');
   
    if ($(':selected', store_selected).val() == Drupal.settings.basePath || $(':selected', store_selected).val() == '') {
      link.click(function(){
        if (!Drupal.settings.gmapslivesearch_remove_buy_now_button){
          alert(Drupal.t('Please select a retailer.'));
        }
        return false;
      });
    }
    else {
      Drupal.attachBehaviors(link.parent());
    }
  }
  
  function defaultValueFieldAddressToSearch(element, default_text_field_address_to_search) {
    if (element.attr('value') == ''){
        element.attr('value', default_text_field_address_to_search);
        element.css("font-style", "italic");
    }
  }

  function clearValueFieldAddressToSearch(element, default_text_field_address_to_search) {

    if (element.attr('value') == default_text_field_address_to_search) {
          element.attr('value', '');
    }
  }
  
})(jQuery);
;

