(function($) {
  function communicationToolsAttach(context) {
    $('#communication_tools_share_link', context).click(function(e){
      e.preventDefault();
    
      $('#communication_tools_overlay_iframe').remove();
      $('#communication_tools_overlay').remove();

      appendOverlayToBody();

      $('#communication_tools_overlay').dialog({
        title: Drupal.t('Email to a Friend'),
        draggable: false,
        modal: true,
        resizable: false,
        height: 380,
        width: 617,
        dialogClass: 'send_to_a_friend',
        create: function(event, ui) {
          var src = $('#communication_tools_share_link').attr('href');
          $('#communication_tools_overlay').append(getIFrameHTML(src));

          var preloaderImageSrc = Drupal.settings.communication_tools_preloader_image_path;
          $('div.ui-dialog.send_to_a_friend').append('<img id="communication_tools_preloader" src="' + preloaderImageSrc + '">');
          
          Drupal.attachBehaviors($(event.target).parents().filter('.ui-dialog.send_to_a_friend'));
          
          //$(event.target).css({display: 'none'});
        },
        close: function(event, ui) { 
          // fix for scrollbars in IE
          if ( $.browser.msie ) {
            $('body').css('overflow', 'auto');
          }
        }
      });

      return false;
    });
  }

  function appendOverlayToBody() {
    $('body').prepend(getOverlayHTML());
  }

  function getOverlayHTML() {
    return '<div id="communication_tools_overlay"></div>';
  }
  
  function getIFrameHTML(src) {
    var iframe = $('<iframe></iframe>')
      .attr({
        'id'                : 'communication_tools_overlay_iframe',
        'noresize'          : 'noresize',
        'frameborder'       : '0',
        'border'            : '0',
        'cellspacing'       : '0',
        'scrolling'         : 'no',
        'marginwidth'       : '0',
        'marginheight'      : '0',
        'allowtransparency' : true,
        'src'               : src
      })
      .css({
        'display' : 'none'
      })
      .load(function() {
        $('img#communication_tools_preloader').remove();
        $('#communication_tools_overlay').css({
          height: 'auto', padding: 0
        });

        $('#communication_tools_overlay_iframe').css({
          width: '100%',
          padding: '0',
          display: 'block'
        });
      }
    );
    
    return iframe;
  }


  Drupal.behaviors.communicationTools = {
    attach: function(context){
      communicationToolsAttach(context);
    }
  }

  function communicationToolsCloseOverlay(){
    parent.jQuery('a.ui-dialog-titlebar-close').click();
    return false;
  }

  function communicationToolsIframreAttach(context) {
    $('#edit-communication-tools-cancel-button').click(function(index){
      communicationToolsCloseOverlay();
    });
  }

  Drupal.behaviors.communicationToolsIframe = {
    attach: function(context){
      communicationToolsIframreAttach(context);
    }
  }

  function communicationToolsAttachCloseOverlay(){
    $(".com_tls_exit_overlay").click(function(){
      communicationToolsCloseOverlay();
    });
  }

  Drupal.behaviors.com_msg_close_overlay = {
    attach: function(){
      communicationToolsAttachCloseOverlay();
    }
  }
  
  $(document).ready(function(){
    if ($('a#communication_tools_print_link').length > 0) {
      $('a#communication_tools_print_link').click(function() {
        var printProperties = {};
        if (Drupal.settings.communication_tools.site_logo_print_path != '') {
          printProperties.logo = Drupal.settings.communication_tools.site_logo_print_path;
        }
        
        $('div#content').printElement(printProperties);
        return false;
      });
    }
  });
  
})(jQuery);
;
/// <reference path="http://code.jquery.com/jquery-1.4.1-vsdoc.js" />
/*
* Print Element Plugin 1.2
*
* Copyright (c) 2010 Erik Zaadi
*
* Inspired by PrintArea (http://plugins.jquery.com/project/PrintArea) and
* http://stackoverflow.com/questions/472951/how-do-i-print-an-iframe-from-javascript-in-safari-chrome
*
*  Home Page : http://projects.erikzaadi/jQueryPlugins/jQuery.printElement 
*  Issues (bug reporting) : http://github.com/erikzaadi/jQueryPlugins/issues/labels/printElement
*  jQuery plugin page : http://plugins.jquery.com/project/printElement 
*  
*  Thanks to David B (http://github.com/ungenio) and icgJohn (http://www.blogger.com/profile/11881116857076484100)
*  For their great contributions!
* 
* Dual licensed under the MIT and GPL licenses:
*   http://www.opensource.org/licenses/mit-license.php
*   http://www.gnu.org/licenses/gpl.html
*   
*   Note, Iframe Printing is not supported in Opera and Chrome 3.0, a popup window will be shown instead
*/
; (function (window, undefined) {
    var document = window["document"];
    var $ = window["jQuery"];
    $.fn["printElement"] = function (options) {
        var mainOptions = $.extend({}, $.fn["printElement"]["defaults"], options);
        //iframe mode is not supported for opera and chrome 3.0 (it prints the entire page).
        //http://www.google.com/support/forum/p/Webmasters/thread?tid=2cb0f08dce8821c3&hl=en
        if (mainOptions["printMode"] == 'iframe') {
            if ($.browser.opera || (/chrome/.test(navigator.userAgent.toLowerCase())))
                mainOptions["printMode"] = 'popup';
        }
        //Remove previously printed iframe if exists
        $("[id^='printElement_']").remove();

        return this.each(function () {
            //Support Metadata Plug-in if available
            var opts = $.meta ? $.extend({}, mainOptions, $(this).data()) : mainOptions;
            _printElement($(this), opts);
        });
    };
    $.fn["printElement"]["defaults"] = {
        "printMode": 'iframe', //Usage : iframe / popup
        "pageTitle": '', //Print Page Title
        "overrideElementCSS": null,
        /* Can be one of the following 3 options:
        * 1 : boolean (pass true for stripping all css linked)
        * 2 : array of $.fn.printElement.cssElement (s)
        * 3 : array of strings with paths to alternate css files (optimized for print)
        */
        "printBodyOptions": {
            "styleToAdd": 'padding:10px;margin:10px;', //style attributes to add to the body of print document
            "classNameToAdd": '' //css class to add to the body of print document
        },
        "leaveOpen": false, // in case of popup, leave the print page open or not
        "iframeElementOptions": {
            "styleToAdd": 'border:none;position:absolute;width:0px;height:0px;bottom:0px;left:0px;', //style attributes to add to the iframe element
            "classNameToAdd": '' //css class to add to the iframe element
        }
    };
    $.fn["printElement"]["cssElement"] = {
        "href": '',
        "media": ''
    };
    function _printElement(element, opts) {
        //Create markup to be printed
        var html = _getMarkup(element, opts);

        var popupOrIframe = null;
        var documentToWriteTo = null;
        if (opts["printMode"].toLowerCase() == 'popup') {
            popupOrIframe = window.open('about:blank', 'printElementWindow', 'width=650,height=440,scrollbars=yes');
            documentToWriteTo = popupOrIframe.document;
        }
        else {
            //The random ID is to overcome a safari bug http://www.cjboco.com.sharedcopy.com/post.cfm/442dc92cd1c0ca10a5c35210b8166882.html
            var printElementID = "printElement_" + (Math.round(Math.random() * 99999)).toString();
            //Native creation of the element is faster..
            var iframe = document.createElement('IFRAME');
            $(iframe).attr({
                style: opts["iframeElementOptions"]["styleToAdd"],
                id: printElementID,
                className: opts["iframeElementOptions"]["classNameToAdd"],
                frameBorder: 0,
                scrolling: 'no',
                src: 'about:blank'
            });
            document.body.appendChild(iframe);
            documentToWriteTo = (iframe.contentWindow || iframe.contentDocument);
            if (documentToWriteTo.document)
                documentToWriteTo = documentToWriteTo.document;
            iframe = document.frames ? document.frames[printElementID] : document.getElementById(printElementID);
            popupOrIframe = iframe.contentWindow || iframe;
        }
        focus();
        documentToWriteTo.open();
        documentToWriteTo.write(html);
        documentToWriteTo.close();
        _callPrint(popupOrIframe);
    };

    function _callPrint(element) {
        if (element && element["printPage"])
            element["printPage"]();
        else
            setTimeout(function () {
                _callPrint(element);
            }, 50);
    }

    function _getElementHTMLIncludingFormElements(element) {
        var $element = $(element);
        //Radiobuttons and checkboxes
        $(":checked", $element).each(function () {
            this.setAttribute('checked', 'checked');
        });
        //simple text inputs
        $("input[type='text']", $element).each(function () {
            this.setAttribute('value', $(this).val());
        });
        $("select", $element).each(function () {
            var $select = $(this);
            $("option", $select).each(function () {
                if ($select.val() == $(this).val())
                    this.setAttribute('selected', 'selected');
            });
        });
        $("textarea", $element).each(function () {
            //Thanks http://blog.ekini.net/2009/02/24/jquery-getting-the-latest-textvalue-inside-a-textarea/
            var value = $(this).attr('value');
            //fix for issue 7 (http://plugins.jquery.com/node/13503 and http://github.com/erikzaadi/jQueryPlugins/issues#issue/7)
            if ($.browser.mozilla && this.firstChild)
                this.firstChild.textContent = value;
            else
                this.innerHTML = value;
        });
        
        //http://dbj.org/dbj/?p=91
        var elementHtml = $('<div></div>').append($element.clone()).html();
        return elementHtml;
    }
    
    function remove_cufon(selector) {
      $(selector).html( cufon_text(selector) );
      return true;
    }

    function cufon_text(selector) {
      var g = '';
      $(selector +' cufon cufontext').each(function() {
        g = g + $(this).html();
      }); 
      return $.trim(g);
    }

    function _getBaseHref() {
        var port = (window.location.port) ? ':' + window.location.port : '';
        return window.location.protocol + '//' + window.location.hostname + port + window.location.pathname;
    }

    function _getMarkup(element, opts) {
        var $element = $(element);

        var elementHtml = _getElementHTMLIncludingFormElements(element);

        var html = new Array();
        html.push('<html><head><title>' + opts["pageTitle"] + '</title>');
        if (opts["overrideElementCSS"]) {
            if (opts["overrideElementCSS"].length > 0) {
                for (var x = 0; x < opts["overrideElementCSS"].length; x++) {
                    var current = opts["overrideElementCSS"][x];
                    if (typeof (current) == 'string')
                        html.push('<link type="text/css" rel="stylesheet" href="' + current + '" >');
                    else
                        html.push('<link type="text/css" rel="stylesheet" href="' + current["href"] + '" media="' + current["media"] + '" >');
                }
            }
        }
        else {
            $("link", document).filter(function () {
                return $(this).attr("rel").toLowerCase() == "stylesheet";
            }).each(function () {
                html.push('<link type="text/css" rel="stylesheet" href="' + $(this).attr("href") + '" media="' + $(this).attr('media') + '" >');
            });
        }
        //Ensure that relative links work
        html.push('<base href="' + _getBaseHref() + '" />');
        html.push('</head><body style="' + opts["printBodyOptions"]["styleToAdd"] + '" class="' + opts["printBodyOptions"]["classNameToAdd"] + '">');
        if(opts["logo"] != undefined) {
          html.push('<div><img src="' + opts["logo"] + '" /></div>');
        }
        
        html.push('<div class="' + $element.attr('class') + '">' + elementHtml + '</div>');
        html.push('<script type="text/javascript">function printPage(){focus();setTimeout("print()",1000);' + ((!$.browser.webkit && !$.browser.opera && !opts["leaveOpen"] && opts["printMode"].toLowerCase() == 'popup') ? 'close();' : '') + '}</script>');
        html.push('</body></html>');
        
        return html.join('');
    };
})(window);
;
(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);
;

