var Adzone = Class.create();
Object.extend(Adzone, {
  Constant: {
    ITEM_COUNT: 4,
    KEYWORD_COUNT: 16
  },

  initialize: function() {
    setTimeout(function() {
      var id = parseInt(window.location.hash.replace('#', ''));
      if (id > 0) {
        Adzone.playVideo(id);
        setTimeout(function() {
          var swf = $(Adzone.State.swfId);
          if (swf.playbackStarted) {
            swf.playbackStarted(Adzone.State.currentVideoId);
          }
        }, 1500);
      }
    }, 1000);

    Adzone.State.originalTitle = document.title;
    Adzone.State.swfId = "adzone_swf";
    Adzone.writeSwf("/adzoneslider.swf?with-cb=9", "adzone_tabs", Adzone.State.swfId, {
      width: "920",
      height: "365"
    });
  },

  writeSwf: function(swf, id, swf_id, size) {
    size = size || {};
    var so = new SWFObject(
      swf,
      swf_id,
      size.width || "100%",
      size.height || "100%",
      "10.0.22"
    );
    so.addParam("allowScriptAccess", "always");
    VersionCheck.write(so, id);
  },

  Template: {
    Keyword: new Template(
      '<li> - <a href="http://search.twitter.com/search?q=#{search_text}" target="_blank">#{text}</a></li>'
    ),
    Tweet: new Template(
      '<div class="item">' +
        '<a href="http://twitter.com/#{user}" target="_blank"><img src="#{avatar_url}" border="0" class="avatar"/></a>' +
        '<p class="text">#{text}</p>' +
        '<p class="attribution">by ' +
          '<a href="#{link_url}" target="_blank">#{user}</a> at #{created_at}</p>' +
        '</div>'
    )
  },

  playVideo: function(id, title) {
    if (Adzone.State.playEvent) return;
    Adzone.State.playEvent = true;

    Adzone.Util.enablePlayer();
    Adzone.Util.enableVoting();
    Adzone.State.currentVideoId = id;
    Adzone.Util.updateUrlBar();
    Adzone.Util.beacon("start");

    $('sponsorship').hide();
    if (Adzone.State.canShowSponsorship && !$A(Adzone.State.excludedSponsorships).include(id)) {
      $('sponsorship').show();
      pingImage("http://tw.i.hulu.com/getElement?creativeid=11106&bId=165104&upid=86247895&ioid=11715&region=AU920x540&resp=REDIR&fr=1265570846830&upid=86247895&attr=[PId%2CCqXgpuZ3SE6j3NguIauDr7Or_th_uuNh][Content+Rating%2CNot+Rated][Genre%2COther][Site+Channel%2Cother][ChanType%2CPrimary][PlatformId%2C13896783][Content+Partner%2Cadvertising][Series%2Csuper+bowl+xliii+ads+%28SH011279810000%29][showdemo%2CMA25to54][showdemo%2CMA0up][Has+Computer+Guid%2Ctrue][Distribution+Partner%2CHulu][Distribution+Platform%2CHulu][Video+Ad+Model%2CMini][Pod%2C0][Player+Mode%2Csite][Operating+System%2CWindows][Operating+System%2CVista][Zip+Code%2C90064][State%2CCA][City%2CCA%2FLos+Angeles][DMA%2CLos+Angeles][Domain%2C][top_level_domain%2C][ISP%2CGlobal+Crossing][age%2C35-49][education%2CHigh+school][employ%2CEmployed+full-time+%2830%2B+hours%29][gender%2Cm][household%2Cno+children][income%2C50k-75k][marital%2CSingle%2C+living+with+domestic+partner][env%2Cprod][version%2C2]&podmode=0_1_1&ext=.xml");
      pingImage("http://ad.doubleclick.net/ad/N4390.hulu.comOX4350/B4220542.4;sz=1x1;ord=" + (new Date()).getTime());
    }

    VideoPlayerComponent.playVideo(id, "huluPlayer");
    Adzone.Util.embedScript("/adzone/ad_info/" + id);
  },

  Twitter: {
    updateKeyword: function() {
      $("loading-tweets").show();
      Adzone.Util.embedScript("/adzone/keywords/" + Adzone.State.currentVideoId);
    },

    refresh: function() {
      Adzone.Twitter.updateKeyword();
    }
  },

  Event: {
    newTopwords: function(results) {
      var brand = results.brand;

      Adzone.State.currentKeyword = brand.stripTags();
      $$('.current-keyword').each(function(el) {
        el.update(Adzone.State.currentKeyword);
      });

      var url = "http://search.twitter.com/search.json";
      url += "?callback=Adzone.Event.newTweets";
      url += "&lang=en";
      url += "&rpp=" + Adzone.Constant.ITEM_COUNT;
      url += "&q=" + encodeURIComponent(brand);
      Adzone.Util.embedScript(url);

      $("keywords").update(
        $A(results.lines).slice(0, Adzone.Constant.KEYWORD_COUNT).map(function (res) {
          return Adzone.Template.Keyword.evaluate({
            text: res,
            search_text: encodeURIComponent($A([brand, res]).uniq().join(' '))
          });
        }).join("")
      );
    },
    newTweets: function(results) {
      $("loading-tweets").hide();
      $("recent_tweets").update(
        $A(results.results).map(function (res) {
          return Adzone.Template.Tweet.evaluate({
            text: res.text.stripTags(),
            user: res.from_user,
            link_url: ["http://twitter.com/", res.from_user, "/statuses/", res.id].join(""),
            created_at: res.created_at.replace(/\s+\+[0-9]+$/, ''),
            avatar_url: res.profile_image_url
          });
        }).join("")
      );
    },
    videoInfoLoaded: function(info) {
      if (info) {
        Adzone.Util.updateWithTitle(info.title);
        $$(".duration").each(function (el) {
          el.update(info.duration);
        });
      }
    },
    votedUp: function(el) {
      if (Adzone.State.votingEnabled) {
        Adzone.Util.vote("up");
        Adzone.Util.disableVoting();
      }
    },
    votedDown: function(el) {
      if (Adzone.State.votingEnabled) {
        Adzone.Util.vote("down");
        Adzone.Util.disableVoting();
      }
    },
    videoComplete: function() {
      VideoPlayerComponent.close();
      try {
        var swf = $(Adzone.State.swfId);
        if (swf.playbackComplete) {
          swf.playbackComplete();
        }
      }
      catch(e) { }
    }
  },

  State: {
    excludedSponsorships: [50032727, 50032726, 50032725, 50032724, 50032723, 50032722, 50032730, 50032679],
    playerEnabled: false,
    votingEnabled: true,
    currentKeyword: "",
    currentVideoId: 0,
    originalTitle: "",
    canShowSponsorship: true
  },

  Util: {
    enablePlayer: function() {
      if (VideoPlayerComponent && !Adzone.State.playerEnabled) {
        Adzone.State.playerEnabled = true;
        Object.extend(VideoPlayerComponent.options, {
          width: 640,
          height: 368 + 83 + 20,
          showMetaData: false,
          playerWMode: "opaque",
          playerMode: "fixed-open"
        });
        if (navigator.userAgent.indexOf("MSIE") != -1) {
          VideoPlayerComponent.options.playerWMode = "window";
        }
        NewSite.updateObservers = function(type, data) {
          if (type == "videoStart") {
            Adzone.State.playEvent = false;
          }
          if (type == "theEnd") {
            setTimeout(function() {
              Adzone.Event.videoComplete();
            }, 1000);
          }
        };
        VideoPlayerComponent.initialize();
      } 
    },
    disableVoting: function() {
      return;
      $$(".thumb").each(function(el) {
        el.addClassName("disabled");
      });
      $$('.vote-info').each(function(el) { el.setStyle({visibility: "visible"}); });
      Element.show('disable-like');
      Element.show('disable-dislike');
      Element.hide('enable-like');
      Element.hide('enable-dislike');
      Adzone.State.votingEnabled = false;
    },
    enableVoting: function() {
      return;
      $$(".thumb").each(function(el) {
        el.removeClassName("disabled");
      });
      $$('.vote-info').each(function(el) { el.setStyle({visibility: "hidden"}); });
      Adzone.State.votingEnabled = true;
      Element.hide('disable-like');
      Element.hide('disable-dislike');
      Element.show('enable-like');
      Element.show('enable-dislike');
    },
    embedScript: function(url) {
      var body = $$("body");
      if (body) body = body[0];
      if (body) {
        var el = document.createElement("script");
        el.src = url;
        el.type = "text/javascript";
        body.appendChild(el);
      }
    },
    vote: function(direction) {
      Adzone.Util.beacon("vote", direction);
    },
    beacon: function(ev, vote) {
      var url = document.domain.indexOf("qa.hulu.com") != -1 || document.domain.indexOf("localhost") != -1 ? "track.qa" : "t";
      url = "http://" + url + ".hulu.com/beacon/v2/adgallery";
      url += "?event=" + ev;
      url += "&videoid=" + Adzone.State.currentVideoId;
      url += "&userid=" + Behaviors.getUserId();

      if (vote) {
        url += "&vote=" + (vote == "up" ? "1" : "0");
      }

      var pguid = $("pguid");
      url += "&computerguid=" + (pguid && pguid.getGUID ? pguid.getGUID() : "");
      url += "&cb=" + (new Date).getTime();
      pingImage(url);
    },
    updateUrlBar: function() {
      window.location.hash = '#' + Adzone.State.currentVideoId;
    },
    updateWithTitle: function(title) {
      if (title) {
        title = title.stripTags();

        //Adzone.Twitter.updateKeyword();
        $$('.current-title').each(function(el) {
          var a = el.up("a");
          if (a) {
            a.href = "/adzone/watch#" + Adzone.State.currentVideoId;
          }
          el.update(title);
        });
        Cufon.replace('h2.cufonable', { fontFamily: 'Futura' });
        document.title = Adzone.State.originalTitle + ' - ' + title;
      }
    }
  }
});
