// Apply Plugins

$(function() {
  $(window).adaptive();
  $(window).mobilize();

  $('textarea').wysiwyg();
  $('#carousel').carousel();
  $('.welcome-splash').crossFader();
  $('.welcome-where-next').minHeighter(".box-content");
  $('.large-number').dialme();
  $('#map').maps();
  $('.translation_missing').translationMissing();

  if(Modernizr.geolocation) { // Only run on capable browsers.
    $("#welcome-finder-geolocate a.locate").geolocate(function(latitude, longitude) {
      var finder = $("#welcome-finder-form");
      var search = finder.find("form");
      var notice = finder.find(".notice");

      search.find('.string :input').val("");

      search.append($("<input type=\"hidden\" name=\"search[origin][]\" value=\"" + latitude + "\" />"));
      search.append($("<input type=\"hidden\" name=\"search[origin][]\" value=\"" + longitude + "\" />"));
      search.append($("<input type=\"hidden\" name=\"search[mapped]\" value=\"true\" />"));

      search.submit();
    });

    $.fn.analytics("UA-13105066-1");
  };
});

// Google Analytics plugin

(function($) {
  $.fn.analytics = function(code) {

    var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
    var gaURL = gaJsHost + 'google-analytics.com/ga.js';

    $.getScript(gaURL, function() {
      try {
        var pageTracker = _gat._getTracker(code);
        pageTracker._trackPageview();

      } catch(err) {}
    });
  };

})(jQuery);

// TranslationMissing plugin

(function($) {

  $.fn.translationMissing = function() {
    this.each(function() {
      var translation = $(this);
      var key = $(this).html().split(",").slice(1).join(".").replace(/ /g, '');
      var link = "/translations?search[likeness]=" + key;

      translation.css("color", "red");
      translation.css("cursor", "pointer");
      translation.html(key.replace(/\./g, " · "));

      translation.click(function() { document.location = link; });
    });
  };

})(jQuery);

// Dialme plugin

(function($) {
  $.fn.dialme = function() {

    this.each(function() {
      var body = $(document.body);
      var container = $(this);

      container.css("cursor", "pointer");

      container.click(function(ev) {
        var modal = $("<div id='dialme-modal'>" + container.html() + "</div>");

        modal.css("position", "fixed");
        modal.css("top", "1.5em");
        modal.css("z-index", "999999");
        modal.css("opacity", "0");
        modal.css("width", $(document).width() - 90);

        $("#dialme-modal").remove();
        body.prepend(modal);
        modal.animate({ opacity: 1 }, 240, "easeInSine");

        modal.click(hideDialme);
        $(document).keydown(escapeDialme);
      });
    });

    function hideDialme(e) {
      $(document).unbind("keydown", escapeDialme);
      $("#dialme-modal").fadeOut(function() { $("#dialme-modal").remove(); });
    };

    function escapeDialme(e) {
      if (e.keyCode == 27) { hideDialme(); }
    };
  };

})(jQuery);

// Google maps plugin.

(function($) {
  $.fn.maps = function() {

    this.each(function() {
      var map = $(this);

      var location = new google.maps.LatLng(map.attr("data-lat"), map.attr("data-lng"));
      var map = new google.maps.Map(document.getElementById(map.attr("id")), {
        scrollwheel: false,
        center: location,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        zoom: 14
      });

      var marker = new google.maps.Marker({
        position: location,
        map: map,
        icon: '/images/logo-graphic.png'
      });

      var info = new google.maps.InfoWindow({
        content: $("#map-overlay-info").html()
      });

      google.maps.event.addListener(marker, 'click', function() {
        info.open(map, marker);
      });
    });
  };

})(jQuery);

// Simple pulse plugin.

(function($) {
  $.fn.pulse = function(pulses) {
    for (var i = pulses; i > 0; i--) $(this).fadeOut().fadeIn();
  };

})(jQuery);

// HTML5 Geolocator plugin

(function($) {
  $.fn.geolocate = function(success) {
    if(Modernizr.geolocation) {
      var highAccuracy = true; 
      
      this.each(function() {
        var locatable = $(this);
        var waiting = locatable.attr("rel");

        locatable.click(function() {
          locatable.html(waiting);
          locatable.css("text-decoration", "none");
          locatable.pulse(3);

          navigator.geolocation.getCurrentPosition(function(position) {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;

            success(latitude, longitude);
          }, function() {}, { enableHighAccuracy: highAccuracy, maximumAge: 60000 });
        });
      });
    };
  };

})(jQuery);

// Mobile view plugin

(function($) {
  $.fn.mobilize = function() {
    var userAgent = navigator.userAgent.toLowerCase();
    var re = /(IEMobile|Windows CE|NetFront|PlayStation|PLAYSTATION|like Mac OS X|MIDP|UP\.Browser|Symbian|Nintendo|Android)/;
    if(re.test(userAgent)) { $('body').addClass("mobile adaptive-small"); }

    return this;
  };

})(jQuery);

// Adaptive Layout Plugin

(function($) {
  $.fn.adaptive = function() {
    var wndow = $(this);
    var body = $("body");
    var mediumThreshold = 970;
    var smallThreshold = 860;

    var resized = function() {
      var width = body.width();

      if(width > mediumThreshold) { body.addClass("adaptive-full").removeClass('adaptive-medium adaptive-small'); }
      if(width <= mediumThreshold) { body.addClass("adaptive-medium").removeClass('adaptive-full adaptive-small'); }
      if(width <= smallThreshold) { body.addClass("adaptive-small").removeClass('adaptive-medium adaptive-full'); }
    };

    wndow.resize(resized);
    resized();

    return this;
  };

})(jQuery);

// Min Height Plugin.

(function($) {
  $.fn.minHeighter = function(resizeSelector) {
    var resizeMe = $(this).find(resizeSelector);
    var maxHeight = 0;

    resizeMe.delay(1000).each(function() {
      var box = $(this);
      var height = box.height();
      if(height > maxHeight) { maxHeight = height; }
    });

    resizeMe.css("min-height", maxHeight);

    return this;
  };

})(jQuery);

// Image prefetch and crossfader Plugin

(function($) {
  $.fn.crossFader = function() {
    var slideSpeed = 9000;
    var fadeSpeed = 900;

    this.each(function() {
      var $$ = $(this);
      var position = 0;
      var bottoms = $$.find("img.bottom");
      var urls = new Array(bottoms.attr('src'));
      $$.append('<div class="welcome-model-rotating"><img class="inner top" /></div>');
      var tops = $$.find("img.top");

      $$.attr('data-model-images', function(i, data) {
        if(data === undefined) { return; }

        var images = data.split(/;/);

        $(images).each(function() {
          var image = new Image();

          $(image).load(function() {
            urls.push($(this).attr('src'));
          }).attr('src', this);
        });
      });

      var timer = function() {
        showNext(position);
        position += 1;
        if(position > (urls.length - 1)) { position = 0; }
      };

      var showNext = function(index) {
        var url = urls[index];

        if(index % 2 === 0) {
          tops.attr('src', url).animate({ opacity: 1 }, fadeSpeed, "easeOutSine");
        } else {
          bottoms.attr('src', url);
          tops.animate({ opacity: 0 }, fadeSpeed, "easeInSine");
        }
      };

      var timerId = setInterval(timer, slideSpeed);
    });

    return this;
  };

})(jQuery);

// Carousel Plugin

(function($) {
  $.fn.carousel = function() {

    this.each(function() {
      var $$ = $(this);
      var models = $$.find(".models");

      var shift = 850;
      var time = 290;
      var ease = "easeOutSine";

      // Give the carousel models the correct width
      var modelsCount = models.find("li").size();
      var modelsWidth = (modelsCount * (175 + 42));
      models.css("width", modelsWidth);

      // Scroll the selected element to the middle
      var selected = $$.find(".selected").attr("class").split(" ");
      var modelIndex = $.grep(selected, function(val) { return val != "selected"; })[0];
      var modelOffset = modelIndex * (175 + 42);
      var middledOffset = modelOffset - ($$.width() / 2) + ((175 + 42) / 2);

      if(modelOffset > ($$.width() / 2)) {
        $$.find("ul").animate({ left: -middledOffset + "px" }, time, ease);
      }

      $$.find("#right").click(function() {
        var newPos = models.position().left - shift;

        if (models.width() + newPos < $$.width()) {
          newPos = $$.width() - models.width();
        }

        models.animate({ left: newPos + "px" }, time, ease);
      });

      $$.find("#left").click(function() {
        var newPos = models.position().left + shift;
        if (newPos > 0) newPos = 0;

        models.animate({ left: newPos + "px" }, time, ease);
      });
    });

    return this;
  };

})(jQuery);