var setLoggedIn, setLoggedOut;
var Behaviors = Class.create();
  
Object.extend(Behaviors, {
  _s: 'I%8Ev%7D%B7%F7%01%11%A2%F8%21160%21k%A1%82%03%7FU%C5%C6%DB%1B%E0%153%2113%21%2112%21%DA%F8v%EF%E1%90s%80%2133%21%04%17%F4%29%3E%E0%B6.%98%3BT%2133%21D%AC%B3%D2Z%1EL%A2%10%E8%B5%F0X%1D%A2%3DfG%FDeZ%08%16%97%FE%1A%92%C6%FA%A6%DA%C7o%CD%03@%2C%F6%BF%1A%5E%FF%CF%29t%C2w%3F%D4%14%8B%AB%2111%21%064%D2%B4%FA%AA%81%84%C4lj%3A%DF+%CCwNB%DA%12%C6%C2%E0%E8l%81%CE%8BO%97%EB%7D%E2%D4%7FqLm_p%12%9EU%9E%04%C4%18Bpd%A7%28%84J%83%E6%7E%C4%F8%CD4T%3Fo%9C%EA%D7%B5Vp%1B%D2%9A%16F%E4%E8%B4N%9E%D4%2133%21L%C3+f%7B%23%FD%2133%21%AE%DBy%C6%F8%97PpB%CB%F9%04%EB%E4%2C%B4%18%C23%DEZ%80%82c%7Bsf%A4%ECc%26sg%3E%FDF%B4%A9%81%87%F7%B6%3Ca%F5%23%3B%FE%A6w%C3%AC%06%3A%B5%E0%DC%7E9%DA%96%7C%ECaqI%DA%D8%19%11%5E%CAsh%B2m%DBI%A2x%82%A2%9EU0%99%D7%B3%0E%02y%AA%AA*%1Df%9Dq8%FC/Yr%B9%BA%60%B6%98%9D%10LG%3A%FC%A1%14F%C7%BE5v%7F%D3*%B7%2139%21',

  toggleFirstDescendant: function(cssRule) {
    $$(cssRule).each(this.toggleFirstDescendantForSingle);
  },

  toggleFirstDescendantForSingle: function(el) {
    var target = el.down('a');

    // add in the play button if it's not there already
    if (!/play/.test(target.className)) {
      new Insertion.Top(el,
        '<a href="' + target.href + '" class="play" style="visibility:hidden;">' +
        '<img src="/images/btn-play-big.png" border="0">' +
        '</a>');
      var play = el.down('a.play');
      if (play) {
        Event.observe(el, "mouseover", toggle_visible.bind(el, play));
        Event.observe(el, "mouseout", toggle_invisible.bind(el, play));
        Event.observe(el.firstDescendant(), "click", target.onclick);
      }
    }
  },
  
  toggleCurrentSeason: function(currentSeason){
    var cssRule = ".popular-filter-nav li.season-list";
    var currentElementId = "season-" + currentSeason;

    $$(cssRule).each(function(el){
      if( el.id == currentElementId ){
        Element.addClassName( el, "current" );
      } else {
        Element.removeClassName( el, "current" );
      }
    });
  },
  
  applyActivatable: function() {
    $$('.activatable').each(function(el) {
      // TODO: should do the same for mouseover...
      Event.observe(el, "mouseover", function() { Element.addClassName(el, 'active'); });
      Event.observe(el, "mouseout", function(ev) { 
        // Don't process this event if called from child elements.
        // http://www.quirksmode.org/js/events_mouse.html#mouseover
        var tg = ev.srcElement;
        var reltg = (ev.relatedTarget) ? ev.relatedTarget : ev.toElement;
        
        // If the element moved to is a child of the activatable, return.
        if (reltg && (reltg.up('div.item') == el)) return;
        
        if (tg && reltg) {
          while (reltg != tg && reltg.nodeName != 'BODY')
            reltg = reltg.parentNode;
          if (reltg == tg) return;
        }
          
        Element.removeClassName(el, 'active'); 
      });
      el.removeClassName('activatable');
    });
  },

  applySifr: function() {
    this.siff({sSelector:"h2.home", sColor:"#B2B2B2"});
    this.siff({sSelector:"h2.filter-label", sColor:"#666666"});
    this.siff({sSelector:"div.disabled h3.channel-filter-label", sColor:"#eeeeee"});
    this.siff({sSelector:"h2.pagetitle", sColor:"#444444", sTextAlign:"center"});
    this.siff({sSelector:"h2", sColor:"#444444"});
    this.siff({sSelector:"h3.reviews", sColor:"#bdbdbd"});
    this.siff({sSelector:"h3.topics", sColor:"#bdbdbd"});
    this.siff({sSelector:"h3.most-subscribed-title", sColor:"#666666"});
    this.siff({sSelector:"h5", sColor:"#444444"});
    this.siff({sSelector:"h6", sColor:"#eeeeee"});

    // fix all sifr replacements from replacing the title (IE bug)
    $$('.sIFR-flash').each(TitleHack.fixOnFocus);
  },

  siff: function(attrs) {
    if (typeof(sIFR) == "function") {
      sIFR.replaceElement(
        named(Object.extend({
          sFlashSrc:"/futura.swf",
          sColor:"#AEAEAE",
          sLinkColor:"#bdbdbd",
          sBgColor:"#FFFFFF",
          sHoverColor:"#4d4d4d",
          sWmode:"transparent",
          nPaddingTop:0,
          nPaddingBottom:0,
          sFlashVars:"&offsetTop=0"
        }, attrs))
      );
    }
  },

  setLoggedIn: function() {
    var uid = Behaviors.getUserId();
    var uname = Behaviors.getUsername();
    var sid = Behaviors.getCookie('_hulu_session_id');

    if (sid && uid && uname) {
      if (setLoggedIn) setLoggedIn();

      var el = $('welcome-username');
      if (el) {
        uname = uname.substring(0,20).gsub(/\+/,' ');
        if (uname != "null" && uname != "undefined")
          el.update("Welcome " + uname );
      }

      FloatingLoginForm.hide();

      Nav.loggedIn();
      Behaviors.resetPlaylistLinks();
      Behaviors.loggedIn = true;
    }
    else {
      Behaviors.setLoggedOut();
    }
  },

  setLoggedOut: function(explicit_logout) {
    if (explicit_logout) SocialFeed.loggedOut();
    if (setLoggedOut) setLoggedOut();
    Behaviors.loggedIn = false;
    Nav.loggedOut();
    FloatingLoginForm.hide();
    VideoRating.reenableAll();
    Behaviors.resetPlaylistLinks();
  },

  afterLogin: function() {
    Element.hide($('popup_frame')); // why?
    this.setLoggedIn();
    Menu.hideAll();
  },

  afterLogout: function() {
    Element.hide($('popup_frame')); // why?
    this.setLoggedOut();
    this.resetPlaylistLinks();
    Menu.hideAll();
  },

  loggedIn: false,

  onLoad: function() {
    this.toggleFirstDescendant(".play-button-hover");
    this.applyActivatable();
    this.applySifr();
    CheckboxPlus.applyCheckboxBehaviors();
  },

  // Playlist functions
  playlistInvalid: true,
  refreshingPlaylist: false,

  addToPlaylistComplete: function(el, response) {
    el = $(el);
    var text = '';
    var textEl = $(el.id + '-text');

    if (/Added/.test(response)) {
      Menu.hideAll();
      Behaviors.playlistInvalid = true;
      el.hide();
      text = response;
    }
    else {
      el.addClassName('logged-out-hide');
      text = '<span class="logged-in-remove">' + response + '</span>';
    }

    textEl.update(text);
    textEl.show();
  },
  
  resetPlaylistLinks: function() {
    $$('.logged-in-remove').each(function(el) {
      el.parentNode.removeChild(el);
    });

    $$('.logged-out-hide').each(function(el) {
      el.removeClassName('logged-out-hide');
    });

    $$('.playlist-link').each(function(el) {
      if (/-text$/.test(el.id)) {
        el.hide();
      }
      else {
        el.show();
      }
    });
  },

  onSubscribeSuccess: function(el) {
    el = el.up('span');
    if (!el) return;

    if (Behaviors.loggedIn) {
      Behaviors.updateLoggedInAction(el,
        '<img class="logged-in-remove" src="/images/icon-check.gif" height="16" width="16" title="You have subscribed to this title" />');
    }
    else {
      Behaviors.updateLoggedInAction(el,
        '<img class="logged-in-remove" src="/images/icon-warning.gif" height="16" width="16" title="Please login first before subscribing to this title" />');
      alert("Please login first before subscribing to this title");
    }
  },

  onQueueSuccess: function(el) {
    el = el.up('span');
    if (!el) return;

    if (Behaviors.loggedIn) {
      Behaviors.updateLoggedInAction(el,
        '<img class="logged-in-remove" src="/images/icon-check.gif" height="16" width="16" title="You have queued this video" />');
      Menu.hideAll();
      Behaviors.playlistInvalid = true;
    }
    else {
      Behaviors.updateLoggedInAction(el,
        '<img class="logged-in-remove" src="/images/icon-warning.gif" height="16" width="16" title="Please login first before queuing this video" />');
      alert("Please login first before queuing this video");
    }
  },

  updateLoggedInAction: function(el, html) {
    var a = el.down('a');
    if (a && !a.hasClassName('logged-out-hide')) {
      a.addClassName('logged-out-hide');
      new Insertion.Bottom(el, html);
    }
  },

  getCookie: function(name) {
    var value = null;
    if (typeof(document.cookie) != 'undefined') {
      $A(document.cookie.split(';')).each(function(v) {
        var kv = v.split('=');
        if (name.toLowerCase() == kv[0].toLowerCase().strip()) {
          value = kv[1].strip();
          throw $break;
        }
      });
    }
    return value;
  },

  getUsername: function() {
    return Utf8.decode(unescape(Behaviors.getCookie('_hulu_uname')));
  },

  getUserId: function() {
    var value = Behaviors.getCookie('_hulu_uid');
    return value ? parseInt(value) : -1;
  },

  isLoggedIn: function() {
    return Behaviors.getUserId() > 0;
  }
});

// from http://www.webtoolkit.info/javascript-utf8.html
var Utf8 = {
  decode: function (utftext) {
    var string = "";
    var i = 0;
    var c = c1 = c2 = 0;
 
    while ( i < utftext.length ) {
      c = utftext.charCodeAt(i);
      if (c < 128) {
        string += String.fromCharCode(c);
        i++;
      }
      else if((c > 191) && (c < 224)) {
        c2 = utftext.charCodeAt(i+1);
        string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
        i += 2;
      }
      else {
        c2 = utftext.charCodeAt(i+1);
        c3 = utftext.charCodeAt(i+2);
        string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
        i += 3;
      }
 
    }
    return string;
  }
};


Ajax.Responders.register({
  onComplete: function() {
    Behaviors.onLoad();
  }
});
