$(document).ready(function() {
  try {
    $(".suggestion-date-separator").stickyHeaders();
  } catch (e) { /* NOP */ }
    
  $("DIV#category-select SELECT").bind("change", function() {
    if (this.selectedIndex != 0)
      window.location.href = this.value;
  });

  loadCanvasImageElements();

  $("DIV#tickets A.summary").click(function(e) {
    $("DIV#ticket-info").slideToggle();
    return false;
  })
  
  $("A.toggle-location").click(function(e) {
    showOverlay('location', $("#location-menu").clone());
    return false;
  });
  $("A.toggle-categories").click(function(e) {
    showOverlay('categories', $("#categories-menu").clone());
    return false;
  });

  function showOverlay(typeOrHash, content, closeCallback) {
    content = content || '';
    $("#default-title, #content, #footer.mobile").hide();
    var hash = (typeof(typeOrHash) === 'string') ? altMenuItems[typeOrHash] : typeOrHash;
    var closeStyle = hash['closeStyle'] || 'link';
    var closeText = hash['closeText'] || I18n.t('close');
    var a = $("<a href='#'></a>").attr('class', closeStyle).text(closeText).click(function(e) {
      closeCallback && closeCallback();
      $("DIV#overlay-container").hide(function(e) {
        $("DIV#overlay-container, DIV#alt-title").empty();
        $("#default-title, #content, #footer").show();
      });
    });
    $("DIV#alt-title").empty().append(hash.titleText).append(a);
    $("DIV#overlay-container").html(content).show();
  }

  $('TEXTAREA#bio').bind('keyup blur change paste', function() {
    var charsLeft = 140 - $(this).val().length;
    if(charsLeft < 0) {
      $('#bio-char-count').html('<span style="color: red">' + charsLeft + '</span>');
    } else {
      $('#bio-char-count').html(charsLeft + '');
    }
  }).change();
  
  $('#comment-form TEXTAREA.comment').bind('keyup blur change paste', function() {
    var charsLeft = 255 - $(this).val().length;
    var disableInput = false;
    if (charsLeft == 255) {
      $('#comment-char-count').html(charsLeft + '');
      disableInput = true;
    } else if (charsLeft < 0) {
      $('#comment-char-count').html('<span style="color: red">' + charsLeft + '</span>');
      disableInput = true;
    } else {
      $('#comment-char-count').html(charsLeft + '');
    }
    $('#comment-form INPUT[type=submit]').attr('disabled', disableInput);
  }).change();

  $("#close-unsupported-locations").click(function(ev) {
    $("#unsupported-locations").slideUp()
  })

  if ($("DIV#success")) {
    setTimeout(function() {
      $("DIV#success").animate({ backgroundColor: "#f3fff1" }, 1000)
    }, 2000);
  }

  $("DIV.avatar-container").hover(
    function() {
      $(this).find("A").fadeIn().css({cursor: 'pointer'});
    },
    function() {
      $(this).find("A").fadeOut();
    }
  )

  $("DIV.dropdown-container").click(function() {
    $(this).toggleClass("on");
    $(this).find("UL").toggle();
    // return false;
  });

  var overTimer, outTimer;
  $("DIV.dropdown-container").hover(
    function(e) {
      var div = $(this);
      clearTimeout(outTimer);
      overTimer = setTimeout(function() {
        div.addClass("on");
        div.find("UL").show();
      }, 300);
    },
    function(e) {
      var div = $(this);
      clearTimeout(overTimer);
      outTimer = setTimeout(function() {
        div.removeClass("on");
        div.find("UL").hide();
      }, 300);
    }
  );

  $("DIV.suggestion").hover(
    function(e) {
      var a = $("H3 A", $(this));
      // window.status = a.attr("href");
      a.addClass('on');
      $("A.remove-bookmark", $(this)).show();
      $("A.dashboard-link", $(this)).show();
    },
    function(e) {
      var a = $("H3 A", $(this));
      // window.status = '';
      a.removeClass('on');
      $("A.remove-bookmark", $(this)).hide();
      $("A.dashboard-link", $(this)).hide();
    }
  )

  $("DIV.bleh, A#bleh").click(function() {
    $(this).find("SPAN").css({'color': '#f0c', '-webkit-transform': 'rotate(31deg)'})
  });

  try { $("DIV.suggestion H3").ellipsis(); } catch (e) { /* NOP */ }
  $("DIV.suggestion H3 A, DIV.suggestion H5 A, DIV.suggestion DIV.venue A").click(function(ev) {
    ev.stopPropagation();
  });
  $("DIV.suggestion").click(function() {
    var a = $(this).find("H3 A");
    window.location = a.attr("href");
  });

  $("DIV.suggestion H5 A, DIV.suggestion DIV.venue A").hover( // Category link
    function(e) {
      var div = $(this).parents("DIV.suggestion")
      var a = $("H3 A", div);
      a.removeClass('on');
    },
    function(e) {
      var div = $(this).parents("DIV.suggestion");
      var a = $("H3 A", div);
      a.addClass('on');
    }
  );
  
  if (jQuery().popover) {
    $('#until-button').popover();
    $('.interesteds-button').popover();
    $('.goings-button').popover();
    $('.checkins-button').popover();
    $('.likes-button').popover();
  }
  
  $("A#mobile-tell-a-friend").click(function() {
    showOverlay('tell-a-friend');
    var suggestionId = $("DIV.suggestion-page").attr('data-id');
    var suggestionType = $("DIV.suggestion-page").attr('data-type');
    $.get("/share/new", { suggestion_id: suggestionId, suggestion_type: suggestionType }, function(data, textStatus) {
      $("#overlay-container").html(data);
      $('#share-container A.submit').click(mobileTellAFriendHandler);
      $('#share-container FORM').submit(mobileTellAFriendHandler);
    });
    return false;
  });

  $("A#until-button").live('click', function() {
    showOverlay({ titleText: $(this).attr('data-popover-header') });
    var untilURL = $(this).attr('data-popover-content-url');
    $.get(untilURL, {}, function(data, textStatus) {
      $("#overlay-container").hide().html(data).slideDown();
    });
    return false;
  });
  
  $("A.interesteds-button, A.goings-button, A.checkins-button, A.likes-button").live('click', function() {
    showOverlay({ titleText: $(this).attr('data-popover-header') });
    var reactionsURL = $(this).attr('data-popover-content-url');
    $.get(reactionsURL, {}, function(data, textStatus) {
      $("#overlay-container").hide().html(data).slideDown();
    });
    return false;
  });
  
  $('#checkin-toggle form.desktop').bind('click', function() {
      alert($(this).attr('data-message'));
      return false;
  });
  
  $("A#tell-a-friend").click(function() {
    $.blockUI({
      css: {
        border: 'none',
        width: '550px',
        left: '30%',
        top: '20%',
        cursor: null,
        '-webkit-border-radius': '10px',
        '-moz-border-radius': '10px'
      },
      overlayCSS: {
        opacity: '0.8',
        cursor: 'pointer'
      },
      message: "<p class='loading'><img src='/images/spinner.gif' /> "+I18n.t('loading')+"…</p>"
    });
    $('.blockOverlay').attr('title', 'Click to cancel').click($.unblockUI);
    var suggestionId = $("DIV.suggestion-page").attr('data-id');
    var suggestionType = $("DIV.suggestion-page").attr('data-type');
    $.get("/share/new", { suggestion_id: suggestionId, suggestion_type: suggestionType }, function(data, textStatus) {
        $('.blockPage').html(data);
        $("#share-container INPUT, #share-container TEXTAREA").keydown(function(e) {
          if (e.keyCode == 27 && e.shiftKey == false) { // escape
            $.unblockUI();
          }
        })
        $("INPUT[_placeholder]").blur(function() {
          if ($(this).val() == '') {
            $(this).val($(this).attr('_placeholder'))
            $(this).css({ color: '#999' })
          } else {
            $(this).css({ color: '#000' })
          }
        }).focus(function() {
          if ($(this).val() == $(this).attr('_placeholder')) {
            $(this).val('')
            $(this).css({ color: '#000' })
          }
        });
        tellAFriendDidLoadHandler();
      }
    )
  });

  function tellAFriendDidLoadHandler() {
    $('#share_to').select();
    $('#share-container A.cancel').click($.unblockUI);
    $('#share-container A.submit').click(tellAFriendHandler);
    $('#share-container FORM').submit(tellAFriendHandler);
  }

  function tellAFriendHandler(event) {
    var params = $("#share-container FORM").serialize()
    $.ajax({
      type: "POST",
      url: "/share",
      data: params,
      success: function(data, textStatus) {
        $('.blockPage').html(data);
        setTimeout($.unblockUI, 2000);
      },
      error: function(response, textStatus, errorThrown) {
        $('.blockPage').html(response.responseText);
        tellAFriendDidLoadHandler();
      }
    })
    event.preventDefault();
  }
  function mobileTellAFriendHandler(event) {
    var params = $("#share-container FORM").serialize()
    $.ajax({
      type: "POST",
      url: "/share",
      data: params,
      success: function(data, textStatus) {
        $('#share-container').html(data);
        setTimeout(closeTellAFriend, 2000);
      },
      error: function(response, textStatus, errorThrown) {
        $('#share-container').html(response.responseText);
        $('#share-container A.submit').click(mobileTellAFriendHandler);
        $('#share-container FORM').submit(mobileTellAFriendHandler);
      }
    })
    event.preventDefault();
  }

  $("A#mobile-check-in").live('click', function() {
    var xhr;
    showOverlay('check-ins',
      "<p id='check-in-locating'><img src='/images/spinner.gif' /> " + I18n.t("locating") + "</p>",
      function() {
        if (xhr && xhr.abort)
          xhr.abort();
      }
    );
    
    geolocate(
      function(geoInfo) {
        $("P#check-in-locating").remove();
        if (geoInfo) {
          xhr = $.get("/available_for_checkin", { 'lat': geoInfo.latitude, 'long': geoInfo.longitude }, function(data, textStatus) {
            $("#overlay-container").html(data);
          });
        } else {
          $("P#check-in-locating").remove();
          alert(I18n.t('unable_to_obtain_location'));
        }
      },
      function() {
        $("P#check-in-locating").remove();
        alert(I18n.t('unable_to_obtain_location'));
      }
    );
    return false;
  });

  $("A#mobile-change-location").live('click', function() {
    showOverlay('change-location', '', mobileLocationSelectDone);
    
    $.get("/location_select", {  }, function(data, textStatus) {
      $("#overlay-container").html(data);
      var location = $.cookie('location') ? $.cookie('location').split("|") : null      
      if (location)
        loadMap($('#location-select-map'), { latitude: location[0], longitude: location[1] })
      loadCanvasImageElements();
      $("#search-bar FORM").submit(function() {
        var sf = $("#location-search-field");
        var geocoderRequest = { language: $("html").attr("lang"),
              address: sf.val() == sf.attr('_placeholder') ? "" : sf.val() };
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode(geocoderRequest, showLocations);
        sf.blur();
        return false;
      });
      $("#location-search-field").bind('keyup blur change paste', function() {
        if ($(this).val() == '')
          $("A#clear-location-field").hide()
        else
          $("A#clear-location-field").show()
      });
      $("A#clear-location-field").click(function(event) {
        $("#location-search-field").focus().val('');
        $(this).hide();
        return false;
      });

      $("#locate-me").click(function() {
        var oldText = $("#location-search-field").val();
        $("#location-search-field").val(I18n.t('locating'));
        geolocate(
          function(geoInfo) {
            if (geoInfo) {
              loadMap($('#location-select-map'), geoInfo);
              // focus() sets text color to black, instead of grey placeholder
              $("#location-search-field").focus().val(geoInfo.address).select();
              updateLocationAttributes({ latitude: geoInfo.latitude,
                                         longitude: geoInfo.longitude,
                                         address: geoInfo.address,
                                         city: geoInfo.city });
            } else {
              $("#location-search-field").val(oldText).select();
              alert(I18n.t('unable_to_obtain_location'));
            }
          },
          function() {
            $("#location-search-field").val(oldText).select();
            alert(I18n.t('unable_to_obtain_location'));
          }
        );
        return false;
      });
      $("#location-search-field").val(location ? location[3] : '');
    });
    return false;
  });
  function mobileLocationSelectDone() {
    if ($('#location-select-map').attr("_latitude") != undefined) {
      var unblockFunction = function() {
        if (window.location.pathname == "/geolocate") {
          window.location = "/"
        } else {
          window.location.reload()
        }
      }
      if ($('#location-select-map').attr("_city") == undefined || $('#location-select-map').attr("_city") == '') {
        var latLng = new google.maps.LatLng(
                      parseFloat($('#location-select-map').attr("_latitude")),
                      parseFloat($('#location-select-map').attr("_longitude")));
        updateLocationSelectHint('checking-location');
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({ latLng: latLng }, function(locations, status) {
          $("DIV#location-select SPAN#checking-location").hide()
          if (status != google.maps.GeocoderStatus.OK) {
            // TODO What's the best way to handle this error?
          } else {
            var foundCity = false;
            var loc = locations[0];
            var cityName = getCityNameFromLocation(loc);
            if (cityName != '') {
              $('#location-select-map').attr("_city", cityName);
              foundCity = true;
            }
            if (foundCity) {
              setCookieAndUnblock(unblockFunction)
            } else {
              // TODO ????
            }
          }
        });
      } else {
        setCookieAndUnblock(unblockFunction)
      }
    }
  }
  $("A#change-location, A.change-location").click(function() {
    $.blockUI({
      css: {
        border: 'none',
        width: '550px',
        left: '30%',
        top: '20%',
        cursor: null,
        '-webkit-border-radius': '10px',
        '-moz-border-radius': '10px'
      },
      overlayCSS: {
        opacity: '0.8',
        cursor: 'pointer'
      },
      message: "<p class='loading'><img src='/images/spinner.gif' /> "+I18n.t('loading')+"…</p>"
    });
    $('.blockOverlay').attr('title', 'Click to cancel').click($.unblockUI);
    $.get("/location_select", {  }, function(data, textStatus) {
      $('.blockPage').html(data);
      var location = $.cookie('location') ? $.cookie('location').split("|") : null;
      $("#location-select A#location-cancel").click(function() {
        $.unblockUI();
        return false;
      });
      $("#location-select A#location-done").click(function() {
        if ($(this).hasClass('disabled')) {
          return false;
        }
        if ($('#location-select-map').attr("_latitude") == undefined) {
          $.unblockUI(); // Just close the lightbox and be done
        } else {
          var unblockFunction = function() {
            $.unblockUI({ onUnblock: 
              function() {
                if (window.location.pathname == "/geolocate") {
                  window.location = "/"
                } else {
                  window.location.reload()
                }
              }
            });
          }
          if ($('#location-select-map').attr("_city") == undefined || $('#location-select-map').attr("_city") == '') {
            var latLng = new google.maps.LatLng(
                          parseFloat($('#location-select-map').attr("_latitude")),
                          parseFloat($('#location-select-map').attr("_longitude")));
            updateLocationSelectHint('checking-location');
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({ latLng: latLng }, function(locations, status) {
              $("DIV#location-select SPAN#checking-location").hide()
              if (status != google.maps.GeocoderStatus.OK) {
                // TODO What's the best way to handle this error?
              } else {
                var foundCity = false;
                var loc = locations[0];
                var cityName = getCityNameFromLocation(loc);
                if (cityName != '') {
                  $('#location-select-map').attr("_city", cityName);
                  foundCity = true;
                }
                if (foundCity) {
                  setCookieAndUnblock(unblockFunction)
                } else {
                  // TODO ????
                }
              }
            });
          } else {
            setCookieAndUnblock(unblockFunction)
          }
        }
        return false;
      });

      $("#location-search-field").val(location ? location[3] : '').select()
      $("INPUT[_placeholder]").blur(function() {
        if ($(this).val() == '') {
          $(this).val($(this).attr('_placeholder'))
          $(this).css({ color: '#ccc' })
        } else {
          $(this).css({ color: '#000' })
        }
      }).focus(function() {
        if ($(this).val() == $(this).attr('_placeholder')) {
          $(this).val('')
          $(this).css({ color: '#000' })
        }
      });

      $('#location-search-field').keydown(function(e) {
        if (e.keyCode == 13) {
          var selectedLocation = $('.selected_location:first');
          if (selectedLocation.size() == 0) {
            $("#location-search-button").click();
            return false;
          } else {
            selectedLocation.click();
            return false;
          }
        } else if (e.keyCode == 9 && e.shiftKey == false) {
          $("#location-search-field").blur();
          $("#location-search-button").focus();
          return false;
        } else if (e.keyCode == 27 && e.shiftKey == false) { // escape
          var selectedLocation = $('.selected_location:first');
          if ($('#location-select DIV.locations-container').is(":visible")) {
            selectedLocation.removeClass("selected_location");
            $('#location-select DIV.locations-container').hide();
            $("#location-select-map.mobile").css('visibility', 'hidden');
          } else {
            $.unblockUI();
          }
          return false;          
        } else if (e.keyCode == 40) { // cursor down
          var selectedLocation = $('.selected_location:first');
          if (selectedLocation.size() == 0) {
            $('DIV.locations-container A.location:first').addClass("selected_location");
          } else {
            var nextLocation = selectedLocation.next();
            selectedLocation.removeClass("selected_location");
            nextLocation.addClass("selected_location");
          }
        } else if (e.keyCode == 38) { // cursor up
          var selectedLocation = $('.selected_location:first');
          if (selectedLocation.size() != 0) {
            var prevLocation = selectedLocation.prev();
            selectedLocation.removeClass("selected_location");
            prevLocation.addClass("selected_location");
          }
        } else {
          // if chars are being added to address field and a location is
          // selected, unselect it, otherwise when pressing enter instead
          // of searching for the new value, the selected location would
          // be, mmm... selected
          var selectedLocation = $('.selected_location:first');
          if (selectedLocation.size() > 0) {
            selectedLocation.removeClass("selected_location");
          }
        }
      });

      if (location)
        loadMap($('#location-select-map'), { latitude: location[0], longitude: location[1] })
        

      $('#location-search-button').click(function() {
        sf = $("#location-search-field");
        geocoderRequest = { language: $("html").attr("lang"),
              address: sf.val() == sf.attr('_placeholder') ? "" : sf.val() };
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode(geocoderRequest, showLocations);
        return false;
      });

      $("A#guess-location").click(function(e) {
        updateLocationSelectHint('locating');
        geolocate(
          function(geoInfo) {
            if (geoInfo) {
              loadMap($('#location-select-map'), geoInfo);
              // focus() sets text color to black, instead of grey placeholder
              $("#location-search-field").focus().val(geoInfo.address).select();
              updateLocationAttributes({ latitude: geoInfo.latitude,
                                         longitude: geoInfo.longitude,
                                         address: geoInfo.address,
                                         city: geoInfo.city });
            } else {
              alert(I18n.t('unable_to_obtain_location'));
            }
            updateLocationSelectHint('hint');
          },
          function() {
            $("#location-search-field").select();
            updateLocationSelectHint('hint');
            alert(I18n.t('unable_to_obtain_location'));
          }
        );
        return false;
      });
    });
    return false;
  });

  $("DIV#location-select A#current-location").click(function(event){
    $("DIV#location-select A#current-location").toggle();
    $("DIV#location-select A#location-search-button").toggle()
    $("DIV#location-select A.cancel").toggle();
    $("DIV#location-select INPUT#location-search-field").toggle().focus()
    // $("DIV#location-select INPUT#location-search-field").focus()
    event.preventDefault();
     });
  $("DIV#location-select A.cancel").click(function(event){
    $(this).toggle();
    $("DIV#location-select A#current-location").toggle();
    $("DIV#location-select A#location-search-button").toggle()
    $("DIV#location-select INPUT#location-search-field").toggle()
    $('#location-select DIV.locations-container').hide();
    $("#location-select-map.mobile").css('visibility', 'visible');
    event.preventDefault();
    });

  $("A.remove-bookmark").click(function(event) {
    if (confirm(I18n.t('are_you_sure_you_want_to_delete_this_bookmark'))) {
      var type = $(this).attr("type").toLowerCase() + "s"
      var root_div = $(this).parents("DIV.suggestion")
      var id = root_div.attr("data-id")

      $.ajax({
        type: "DELETE",
        data: null,
        url: "/"+type+"/"+id+"/bookmark",
        success: function(msg) {
          root_div.slideToggle(400)
        }
      })
    }
    return false;
  })

  $("A.bookmark_toggle").click(function(event) {
    var a = $(this)
    var type = a.attr('_suggestion_type')
    var id = a.attr('_suggestion_id')
    $("IMG#bookmark-spinner").show()
    if (a.hasClass('on')) { // Remove bookmark
      $.ajax({
        type: "DELETE",
        data: null,
        url: "/"+type+"/"+id+"/bookmark",
        success: function(data, textStatus) {
          a.text(I18n.t('bookmark'))
          a.removeClass("on")
          $("IMG#bookmark-spinner").hide()
        }
      })
    } else { // Add bookmark
      url = "/"+type+"/"+id+"/bookmark";
      $.ajax({
        type: "POST",
        data: null,
        url: "/"+type+"/"+id+"/bookmark",
        success: function(data, textStatus) {
          a.text(I18n.t('bookmarked'))
          a.addClass("on")
          $("IMG#bookmark-spinner").hide()
        }
      })
    }

    event.preventDefault();
    event.stopPropagation();
  });

  if ($("DIV#map-canvas-large").length > 0) {
    var canvas = $("DIV#map-canvas-large")
    var latitude = canvas.attr("_latitude");
    var longitude = canvas.attr("_longitude");
    var venueLatLng = new google.maps.LatLng(parseFloat(latitude), parseFloat(longitude));
    
    var location = $.cookie('location').split("|");
    var userLat = parseFloat(location[0]);
    var userLng = parseFloat(location[1]);
    var userLatLng = new google.maps.LatLng(userLat, userLng);

    var bounds = new google.maps.LatLngBounds(userLatLng, userLatLng);
    bounds.extend(venueLatLng);

    var mapOpts = {
      zoom: 15,
      center: bounds.getCenter(),
      disableDefaultUI: true,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    var map = new google.maps.Map(canvas.get(0), mapOpts);
    map.fitBounds(bounds);
    new google.maps.Marker({ map: map, position: venueLatLng});
    
    var locMarker = new google.maps.Marker({
        position: userLatLng,
        map: map,
        icon: '/images/location.png'
    });

    $("A#map-origin").click(function(event) {
      map.setZoom(15);
      map.panTo(userLatLng);
      return false;
    });
    
    $("A#map-destination").click(function(event) {
      map.setZoom(15);
      map.panTo(venueLatLng);
      return false;
    });
    
    $("A#toggle-map-interactivity").click(function() {
      $("DIV.blocker").toggle();
      $("CANVAS", this).toggle();
      return false;
    });
  };

  $("DIV#playimg #image-with-overlay, DIV#playimg #close-video A").click(function(event) {
    $(this).blur();
    var container = $("DIV#playimg")
    var overlay = $("DIV#playimg #image-container");
    var video = $("DIV#playimg #video-container");
    var imageHeight = parseInt(overlay.find("IMG:first-child").attr("height"))
    
    if (overlay.css("display") == "block") {
      var deltaString = (playImgVideoHeight > imageHeight ? "+=" : "-=") + Math.abs(playImgVideoHeight - imageHeight);
      overlay.fadeOut(function() {
        container.animate({height: deltaString});
        video.css({ visibility: 'visible', opacity: 1.0 });
        if (YT) {
          var playerVars = { };
          try {
            if (videoStart != undefined && videoStart)
              playerVars.start = videoStart;
          } catch (e) {
            /* NOP */
          }
          var player = new YT.Player('video-placeholder', {
            width: videoDimensions[0],
            height: videoDimensions[1],
            videoId: videoID,
            playerVars: playerVars,
            events: {
              'onReady': function(event) {
                event.target.playVideo();
              }
            }
          });
        }
      });
    } else {
      var deltaString = (playImgVideoHeight > imageHeight ? "-=" : "+=") + Math.abs(playImgVideoHeight - imageHeight);
      video.animate({opacity: 0.1}, 500, 'swing', function() {
        video.css('visibility', 'hidden');
        container.animate({height: deltaString}, {complete: function() {
          overlay.fadeIn(function() {
            $("DIV#playimg #video-placeholder").html('')
          });
        }});
      });
    }
    return false;
  });

  $("DIV#playimg #close-video A").hover(
    function() {
  	  $(this).find("IMG").attr("src", "/images/close_video_over.png");
  	},
  	function() {
  	  $(this).find("IMG").attr("src", "/images/close_video.png");
	  }
  );

  $("DIV#playimg #image-with-overlay").hover(
    function() {
  	  $(this).find("IMG#play-overlay").attr("src", "/images/video-indicator-overlay-over.png");
  	},
  	function() {
  	  $(this).find("IMG#play-overlay").attr("src", "/images/video-indicator-overlay.png");
	  }
  );

  // XAVI: commented out the lines below, I think they are not used
  // $("DIV.suggestion-page DIV#directions A").click(function(event) {
  //   var map = loadMap($("DIV#map-canvas-large"))
  //   if (!$(this).hasClass("on")) {
  //     var opts = { }
  //     opts.travelMode = $(this).attr('mode') == 'walking' ? G_TRAVEL_MODE_WALKING : G_TRAVEL_MODE_DRIVING;
  //     var directions = new GDirections(map)
  //     var latitude_s = 41.387238;
  //     var longitude_s = 2.19713;
  //     var waypoints = [latitude_s+","+longitude_s, latitude+","+longitude]
  //     directions.loadFromWaypoints(waypoints, opts)
  //   }
  //   $("DIV.suggestion-page DIV#directions A").removeClass("on")
  //   $(this).addClass("on")
  // });
  
});

function geocodePosition(pos) {
  var geocoder = new google.maps.Geocoder();
  geocoder.geocode({
    latLng: pos
  }, function(responses) {
    if (responses && responses.length > 0) {
      r = responses[0];
      updateMarkerAddress(r.formatted_address);
      // notice that the marker's coordinates are used, not the ones in the
      // geocoder's response, as these might be slightly different
      updateLocationAttributes({ latitude: pos.lat(),
                                 longitude: pos.lng(),
                                 address: r.formatted_address,
                                 city: getCityNameFromLocation(r) });
    } else {
      updateMarkerAddress('Cannot determine address at this location.');
    }
  });
}

function updateMarkerAddress(str) {
  $("#location-search-field").focus().val(str);
}

function updateLocationAttributes(loc) {
  $('#location-select-map').attr("_latitude", loc.latitude);
  $('#location-select-map').attr("_longitude", loc.longitude);
  $('#location-select-map').attr("_address", loc.address);
  $('#location-select-map').attr("_city", loc.city);
  $('#location-select A#location-done').removeClass('disabled')
}

function updateLocationSelectHint(cssId) {
  $('#location-select-hint div').hide();
  $('#' + cssId).show();
}

function loadMap(canvas, coords) {
  var latitude = coords ? coords.latitude : canvas.attr("_latitude");
  var longitude = coords ? coords.longitude : canvas.attr("_longitude");
  var mapOpts = {
    center: new google.maps.LatLng(parseFloat(latitude), parseFloat(longitude)),
    zoom: 15,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
    streetViewControl: false
  }
  var map = new google.maps.Map(canvas.get(0), mapOpts);
  var marker = new google.maps.Marker(
                    { position: new google.maps.LatLng(parseFloat(latitude),
                                                       parseFloat(longitude)),
                      map: map, draggable: true, icon: '/images/location.png' });
  google.maps.event.addListener(marker, 'dragstart', function() {
    // updateMarkerAddress(I18n.t('dragging'));
    updateLocationSelectHint('dragging');
  });
  google.maps.event.addListener(marker, 'drag', function() {
    //updateMarkerStatus('Dragging...');
  });
  google.maps.event.addListener(marker, 'dragend', function() {
    //updateMarkerStatus('Drag ended');
    geocodePosition(marker.getPosition());
    updateLocationSelectHint('hint');
  });
  return map;
}

function showLocations(responseLocations, status) {
  if (status != google.maps.GeocoderStatus.OK) {
    alert(I18n.t('sorry_we_were_unable_to_geocode_that_address'));
  } else {
    var validResults = $.grep(responseLocations, precisionIsCityLevelOrBetter) || [];

    var result_html = "";
    if (validResults.length == 0) {
      result_html = "<div class='no-locations'>" + I18n.t('please_enter_an_address_or_city') + "</div>";
    } else {
      for (i = 0; i < validResults.length; ++i) {
        place = validResults[i];
        result_html += '<a class="location">' + place.formatted_address + '</a>';
      }
    }
    //marker.openInfoWindowHtml(result_html);
    $("#location-select DIV.locations-container").html(result_html);
    // it seems that IE doesn't support CSS hover for elements different than links,
    // that's why jQuery is used for this
    //http://www.google.com/search?&q=ie+hover
    $(".location").hover(
      function () {
        $('.selected_location:first').removeClass("selected_location");
        $(this).addClass("selected_location");
      },
      function () {
        $(this).removeClass("selected_location");
      }
    );
    var locationDivs = $('#location-select DIV.locations-container .location');
    locationDivs.click(function() {
      var locationIndex = locationDivs.index(this);
      var loc = validResults[locationIndex];
      updateLocationAttributes({ latitude: loc.geometry.location.lat(),
                                 longitude: loc.geometry.location.lng(),
                                 address: loc.formatted_address,
                                 city: getCityNameFromLocation(loc) });
      // $('#location-select-map').attr("_latitude", loc.geometry.location.lat());
      // $('#location-select-map').attr("_longitude", loc.geometry.location.lng());
      // $('#location-select-map').attr("_address", loc.formatted_address);
      // $('#location-select-map').attr("_city", getCityNameFromLocation(loc));
      loadMap($('#location-select-map'));
      $('#location-select DIV.locations-container').hide();
      $("#location-select-map.mobile").css('visibility', 'visible');
      locationDivs.remove();
      $("#location-search-field").val(validResults[locationIndex].formatted_address);
    });
    $('#location-select DIV.locations-container').show();
    $("#location-select-map.mobile").css('visibility', 'hidden');
  }
}

function setCookieAndUnblock(unblockFunction) {
  var cookieStr = [
    $('#location-select-map').attr("_latitude"),
    $('#location-select-map').attr("_longitude"),
    '', // accuracy
    $('#location-select-map').attr("_address"),
    '', // geoname_city
    '', // geoname_id
    $('#location-select-map').attr("_city")
  ].join("|");
  var date = new Date();
  date.setTime(date.getTime() + 10*60*1000);
  $.cookie('location', cookieStr, { domain: window.location.hostname.replace(/^m\./i, ""), expires: date.toUTCString(), path: '/' });
  unblockFunction();
}

// http://sifent.com/blog/2009/05/28/rails-nested-forms-jquery/
function insertFields(link, method, content) {
  var newId = new Date().getTime();
  var regexp = new RegExp("new_" + method, "g")
  $(link).before(content.replace(regexp, newId));
}
 
function removeFields(link) {
  var hiddenField = $(link).prev("input[type=hidden]");
  if (hiddenField) {
    hiddenField.val('1');
  }
  $(link).closest(".fields").slideUp();
}

function loadCanvasImageElements() {
  $("CANVAS").each(function(i, canvas) {
    var canvasId = $(this).attr('id');
    canvasId && window[canvasId] && window[canvasId](canvas);
  });
}

function makeRemoteForm(selector) {
  $(selector).submit(function (){
    $.post($(this).attr('action'), $(this).serialize(), null, "script");
    return false;
  });
}

