var _vodpod_namespace = {};

(function() {
  var embed = null;
  var v = _vodpod_namespace;

  function debug() {
    if (typeof(console) != "undefined") {
      if (arguments.length > 1) {
        console.log(arguments);
      } else {
        console.log(arguments[0]);
      }
    }
  }
  v.debug = debug;
  
  function getAllByClassName(node, klass, tagType) {
    tagType = tagType || "*";
    var elt = null;
    if (node.getElementsByClassName) {
      return node.getElementsByClassName(klass);
    } else {
      var elts = node.getElementsByTagName(tagType);
      var result = [];
      for (var i = 0; i < elts.length; i++ ){
        if (elts[i].className.indexOf(klass) >= 0) {
          result.push(elts[i]);
        }
      }
      return result;
    }
    return [];
  }
  v.getAllByClassName = getAllByClassName;

  function find_head_link(name) {
    try {
      var items = document.getElementsByTagName("HEAD")[0].getElementsByTagName("LINK");
      for (var i =0; i < items.length; i++ ){
        if (items[i].rel == name) {
          return items[i].href;
        }
      }
    } catch(e) { alert(e.message);}

    return null;
  }
  v.find_head_link = find_head_link;

  function vodpod_share(data) {
      window.open('http://vodpod.com/savevideo/popup?context=direct&p=' + encodeURIComponent(data.link) + '&embed=' + encodeURIComponent(data.embed) +
                      '&t=' + encodeURIComponent(data.title), 'vodpod_share','toolbar=0,status=0,resizable=1,width=540,height=560');
  }

  function embed_from_src(flash_src) {
    return '<embed src="' + flash_src + '" type="application/x-shockwave-flash" allowfullscreen="true" width="400" height="320"><embed>';
  }
  _vodpod_namespace.embed_from_src = embed_from_src;

  function pull_embed_from_element(elt) {
    var result = null;
    if (typeof(elt) != 'undefined') {
      if (elt.tagName == 'DIV') {
        result = elt.innerHTML;
      } else if (elt.tagName == 'INPUT' || elt.tagName == 'TEXTAREA') {
        result = elt.value;
      } else if (elt.tagName == 'EMBED' || elt.tagName == 'OBJECT' || elt.tagName == 'IFRAME') {
        if (typeof(elt.outerHTML) != 'undefined') {
          result = elt.outerHTML;
        } else {
          var m = elt.parentNode.innerHTML.match(new RegExp('<' + elt.tagName + '.*?>', "i"));
          if (m) {
            var res = m[0];
            if (!res.match(/\/>$/)) {
              res = res + "</" + res.match(new RegExp('^<(' + elt.tagName + ')','i'))[1] + ">";
            }
            result = res;
          }
        }
      }
    }
    if (result && (result.match(/&lt;(embed|object|iframe)/i) || result.match(/%3C(embed|object|iframe)/i))) {
      result = unescape(result);
    }
    return result;
  }
  _vodpod_namespace.pull_embed_from_element = pull_embed_from_element;

  // Returns the hash {embed: ..., link: ..., title: ...} by examining the attributes of the
  // indicated button and returning the right video metadata.
  function extract_button_data(link) {
    // Get the title and url first
    var title;
    if (link.attributes['data-title']) {
      title = link.attributes['data-title'].value;
    } else {
      title = document.title;
    }
    var url;
    if (link.attributes['data-link']) {
      url = link.attributes['data-link'].value;
    } else {
      url = document.location.href;
    }
    // Now get the embed code
    var embed = null;
    if (link.attributes['data-embed']) {
      debug("Embed from data-embed");
      embed = link.attributes['data-embed'].value;
    } else if (typeof(vodpod_embed_code) != 'undefined' && vodpod_embed_code) {
      debug("Embed from vodpod_embed_code");
      embed = vodpod_embed_code;
    } else if (link.attributes['data-id']) {
      debug("Embed from data-id");
      var eelt = document.getElementById(link.attributes['data-id'].value);
      embed = pull_embed_from_element(eelt);
    } else if (link.attributes['data-class']) {
      debug("Embed from data-class");
      var eelt = getAllByClassName(document, link.attributes['data-class'].value);
      if (eelt.length > 0) {
        embed = pull_embed_from_element(eelt[0]);
      }
    } else if (link.attributes['data-facebook']) {
      debug("Embed facebook");
      embed = find_head_link('video_src') || find_head_link('og:video');
      if (embed) {
        embed = embed_from_src(embed);
      }
    } else if (link.attributes['data-oembed']) {
      debug("Embed from oembed");
      embed = "oembed:" + link.attributes['data-oembed'].value;
    }
    return {embed: embed, link:url, title: title};
  }
  v.extract_button_data = extract_button_data;

  v.setup_done = false;

  function draw_button(link) {
    debug(link);
    var style1 = 'display:inline-block !important;width:74px !important;height:0 !important;padding-top:20px !important;overflow:hidden !important;background-image:url(\'http://assets.vodpod.com/images/molt/common/btn-vodpod-gray.png\') !important;border:none !important;cursor:pointer !important;';
    var style2 = 'display:inline-block !important;width:74px !important;height:0 !important;padding-top:20px !important;overflow:hidden !important;background-image:url(\'http://assets.vodpod.com/images/molt/common/btn-vodpod-orange.png\') !important;border:none !important;cursor:pointer !important;';
    if (link.className.indexOf('orange') >= 0) {
      link.style.cssText = style2;
    } else {
      link.style.cssText = style1;
    }
    link.onmouseover = function() {
      this.style.backgroundPosition='0 -20px';
    }
    link.onmouseout = function() {
      this.style.backgroundPosition='0 0';
    }
  }
  _vodpod_namespace.draw_button = draw_button;
  
  function vodpod_setup(force) {
    if (v.setup_done && !force) {
      return;
    }
    debug("Vodpod share_video setup");
    
    setup_done = true;
    var links = getAllByClassName(document, "vodpod-share-button", "a");
    for (var i = 0; i < links.length; i++) {
      link = links[i];
      draw_button(link);
      var share_function = function() {
        var data = extract_button_data(link);
        vodpod_share(data);
        return false;
      }
      if (link.addEventListener) {
        link.addEventListener("click", share_function, false);
      } else if (link.attachEvent) {
        link.attachEvent("onclick", share_function);
      } else {
        link.onclick = share_function;
      }
    }
  }
  v.vodpod_setup = vodpod_setup;

  debug("Setting up load events");
  
  // onReady code copied from jQuery
  if ( document.readyState == 'loaded' || document.readyState == 'complete') {
    vodpod_setup();
  } else if ( document.addEventListener ) {
    // Use the handy event callback
    document.addEventListener( "DOMContentLoaded", vodpod_setup, false );

    // A fallback to window.onload, that will always work
    window.addEventListener( "load", vodpod_setup, false );

  // If IE event model is used
  } else if ( document.attachEvent ) {
    // ensure firing before onload,
    // maybe late but safe also for iframes
    document.attachEvent("onreadystatechange", vodpod_setup);

    // A fallback to window.onload, that will always work
    window.attachEvent( "onload", vodpod_setup );
  }

})();


