// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

jQuery.fn.browserCheck = function() {
  min_supported_versions = {
    'firefox' : "3",
    'msie'    : '7',
    'chrome'  : '4',
    'safari'  : '3'
  };

  if ((min_supported_versions[$.browser.name] == null || $.browser.version < min_supported_versions[$.browser.name]) &&
      ($.cookie('browser-warning-displayed') != 'true')) {
    dialog = '<div class="unsupported-browser-dialog dialog">' +
             '<h3>Unsupported Browser</h3>' +
             '<p>You are using a browser or browser version that is not supported by this website. We recommend upgrading to the latest version of one of the following browsers in order to view ITVS.org as it is intended and to improve your experience on other websites.</p>' +
             '<ul>' +
             '<li><a class="a1" href="http://www.mozilla.com/en-US/firefox/firefox.html" target="_blank">Mozilla Firefox 3+</a></li>' +
             '<li><a class="a1" href="http://www.microsoft.com/windows/internet-explorer/" target="_blank">Microsoft Internet Explorer 7+</a></li>' +
             '<li><a class="a1" href="http://www.google.com/chrome/" target="_blank">Google Chrome 4+</a></li>' +
             '<li><a class="a1" href="http://www.apple.com/safari/" target="_blank">Apple Safari 3+</a></li>' +
             '</ul>' +
             '<button type="button" class="close">Continue</button>' +
             '</div>';

    $(this).append(dialog);

    $('.unsupported-browser-dialog').overlay({
      expose: {
        color: '#333',
        loadSpeed: 0,
        closeSpeed: 'normal',
        opacity: 0.8
      },
      closeOnClick: false,
      onClose : function() {
        $.cookie('browser-warning-displayed', 'true')
      }
    });
    $('.unsupported-browser-dialog').overlay().load();
  }
};

jQuery.fn.itvsOverlay = function(options) {
  settings = jQuery.extend({
  }, options);

  return this.each(function() {
    var target = $(this);

    var overlay = $(document.createElement('div'));
    overlay.addClass(target.attr('class'));
    target.removeAttr('class');
    overlay.addClass('transparency');
    target.wrap(overlay);

    if (this.tagName.toUpperCase() === "A") {
      target.closest("div").addClass("clickable").click(function() {
        if (target.attr("href") !== 'undefined' && target.attr("target") !== '_blank')
        {
          window.location = target.attr("href");
        }
      });
    }

    var background = $(document.createElement('div'));
    background.addClass('overlay-background');
    target.before(background);

    var content = $(document.createElement('div'));
    content.addClass('overlay-content');
    target.wrap(content);
  });
};

jQuery.fn.preload = function() {
  var img = new Image();
  $(this).each(function() {
    img.src = $(this).text();
  });
};

// TODO We're using the jquery.hint plugin for all of our other hints.  Let's refactor the one consumer of this custom helper to use jquery.hint instead.
jQuery.fn.inputHints = function(options) {

  var settings = $.extend({
    className : "input-hint"
  }, options);

  function setText($el) {
    $el.addClass(settings.className).val($el.attr('title'));
  }

  $(this).each(function() {
    setText($(this));
  });

  $(this).focus(function() {
    var $this = $(this);
    $this.removeClass(settings.className);
    if ($this.val() == $this.attr('title'))
    {
      $this.removeClass(settings.className).val('');
    }
  }).blur(function() {
    if ($(this).val() == '')
    {
      setText($(this));
    }
  });

  return this;
};

// Don't call this before the image is loaded
jQuery.fn.unwrapTextAroundImage = function() {

  function getChildNodes(node){
    var nodes = [];
    $.each(node.childNodes, function(){
      // accept only element nodes and text nodes
      if(this.nodeType === 1 || this.nodeType === 3) {
        nodes.push(this);
      }
    });
    return nodes;
  }

  this.each(function() {
    var $img = $(this);
    var $parent = $(this).parent();
    var $container = $parent.parent();

    if (getChildNodes($parent[0]).length == 1) {
      return;
    }

    $container.addClass("clearfix");

    $img.remove();
    $parent.before($img);

    var $wrapper = $('<div>').addClass('nowrap').css('float', 'left');
    $img.wrap($wrapper);

    var container_offset_bottom = $container.offset().top + $container.outerHeight();
    var container_padding_bottom = parseInt($container.css('padding-bottom'));
    var image_offset_bottom = $img.offset().top + $img.height();
    var calculated_height = $img.height() + container_offset_bottom - image_offset_bottom - (container_padding_bottom / 2);
    $img.parent().height(Math.max($img.height(), calculated_height));
  });

  return this;
};

// Don't call this before the image is loaded
jQuery.fn.captionImage = function() {
  this.each(function() {
    var $img = $(this);
    var title = $img.attr('title');
    if (title) {
      var $caption = $('<div>').addClass('caption').width($img.width()).html(title);
      $img.after($caption);
    }
  });

  return this;
};

$.fn.reverse = [].reverse;

jQuery.fn.reZindex = function(options) {
  if (!$.browser.msie)
  {
    return
  }

  var settings = $.extend({
    start : 2000,
    toggle_static_on_hover : false
  }, options);

  var zIndexNumber = settings.start;
  $(this).each(function() {
    var css = {zIndex : zIndexNumber};
    if (settings.toggle_static_on_hover)
    {
      css = $.extend(css, {position : "static"})
    }
    $(this).css(css);
    zIndexNumber -= 10;
  });
  if (settings.toggle_static_on_hover)
  {
    $(this).hover(function() {
      $(this).css("position", "relative")
    }, function() {
      $(this).css("position", "static")
    })
  }
};

ITVS = {
  CDN_URL : null,

  cdn : function(path) {
    return this.CDN_URL + path;
  }
};

function showPlayer(imageUrl, clipUrl) {
  $("#current-video").videoPlayer({
    canvas : {
      backgroundColor: 'transparent',
      backgroundGradient: 'none'
    },
    playlist : [
      {
        url : imageUrl,
        autoPlay : true
      },
      {
        url : "mp4:itvs.org/" + clipUrl,
        autoPlay : false
      }
    ]
  });
}


/* Analytics Helpers */

function trackExternalLink(url) {
  if ("undefined" != typeof _gaq) {
    //    alert("trackExternalLink: " + url);
    _gaq.push(['_trackEvent', 'External Link', url]);
  }
}

//function trackDownloadLink(url) {
//  if ("undefined" != typeof _gaq) {
////    alert("trackDownloadLink: " + url);
//    _gaq.push(['_trackEvent', 'Download Link', url]);
//  }
//}

function trackVideoEvent(eventName, videoName) {
  if ("undefined" != typeof _gaq) {
    if (videoName.substring(videoName.length - 3) == "jpg") return;

    videoName = videoName.substring(videoName.lastIndexOf('/') + 1);
    //    alert("trackVideoEvent: " + eventName + ", " + videoName);
    _gaq.push(['_trackEvent', 'Video', eventName, videoName]);
  }
}

function trackFilmPhotoEvent(imageName) {
  if ("undefined" != typeof _gaq) {
    imageName = imageName.substring(imageName.lastIndexOf('/') + 1);
    //    alert("trackFilmPhotoEvent: " + imageName);
    _gaq.push(['_trackEvent', 'Film Photo', 'Viewed', imageName]);
  }
}

if (!Array.prototype.indexOf) {
  Array.prototype.indexOf = function (obj, fromIndex) {
    if (fromIndex == null) {
        fromIndex = 0;
    } else if (fromIndex < 0) {
        fromIndex = Math.max(0, this.length + fromIndex);
    }
    for (var i = fromIndex, j = this.length; i < j; i++) {
        if (this[i] === obj)
            return i;
    }
    return -1;
  };
}