$j(document).ready(function(){
MTVN.init();
});
MTVN = new function(){
this.pageTitle = document.title;
this.initArray = new Array();
this.version = 'charlie';
this.init = function(){
document.body.onmousedown = mouseDown;
if (typeof MTVN.Flux != 'undefined' && ((typeof(MTV) == "undefined" || typeof(MTV.Flux) == "undefined") || typeof(MTV.Flux.ucid) == "undefined")) MTVN.Flux.Widgets.loadAll();
MTVN.UI.initScrollingModules();
for(var i=0; i<MTVN.initArray.length; i++){
MTVN.initArray[i]();
}
return true;
}
this.resetPageTitle = function(){
document.title = MTVN.pageTitle;
}
mouseDown = function(e){
if (MTVN.UI.ModalWindow.isOpen) MTVN.UI.ModalWindow.mouseDownBody(e);
return true;
}
}
MTVN.Apps = new function(){}

MTVN.Constants = new function(){
this.playerChannelDomain = "vh1";
this.playerMediaHost = "http://media.mtvnservices.com";
this.playerBaseUrl = "/video/play.jhtml";	
}
MTVN.Ads = new function(){
this.additionalValues = "";
this.moreAdditionalValues = "";

this.dartSite = "";
this.sections = ""; // right now this is only ever set to vidzone from the player
this.adPageVals = "";
this.autoDcopt = "";

// this is mostly for the video player, ajaxed in values
this.handleAdditionalValues = function(){

if (MTVN.Ads.additionalValues.indexOf("content_id") == -1 
&& MTVN.Player && MTVN.Player.id != undefined)	{	
MTVN.Ads.additionalValues += "content_id=" + MTVN.Player.id + ";";
}

MTVN.Ads.additionalValues += MTVN.Ads.moreAdditionalValues;
}	

}

MTVN.Reporting = new function(){
this.dispatcherAttributes = "";

this.handleDispatcherAttributes = function(){
var attrs = MTVN.Reporting.dispatcherAttributes.split(";");
for (var i=0; i < attrs.length; i++) {

if(attrs[i]!=""){
var pair = attrs[i].split("=");	
dispatcher.setAttribute(pair[0],pair[1]);
}
}
}

this.reportIMX = function(tagUrl, protocol, params){
var imxTag = new Image();
if ((protocol=="flipbook" && !(document.referrer.indexOf("fid="+params) > -1)) || (protocol != 'flipbook')){
imxTag.src = tagUrl;
}
}

this.reportFluxView = function(tagUrl, protocol, params){
var fluxTag = new Image();
fluxTag.src = tagUrl;
}
}

MTVN.UI = new function(){
this.initScrollingModules = function(){
/* handle no max-height in IE 6 */
if(jQuery.browser.msie && jQuery.browser.version.substr(0,1)=="6"){
$j(".scroll-wrap").each(function(){
var sw = $j(this);
var olHeight = sw.children("ol:first").height();
if(olHeight < 370) sw.height("100%");
});
}
}
}

MTVN.UI.Overlay = new function(){
this.active = false;

this.init = function(){
$j("#container-outer").append('<div id="overlay"></div>');
$j("#modalWindow").remove().appendTo("#container-outer");
MTVN.UI.Overlay.active = true;
}

this.open = function(){
$j("#overlay").addClass("open");
$j("#overlay").height(document.body.offsetHeight + "px");
}

this.close = function(){
$j("#overlay").removeClass("open");
$j("#overlay").height("0px");
}
}

MTVN.UI.ModalWindow = new function(){
var modalWindowId = "modalWindow";
var currentLocationId = "";
this.ignoreMouseDownBody = false;
this.isOpen = false;

this.open = function(requestUrl, locationId){
currentLocationId = locationId;

$j.get(requestUrl, function(data){
MTVN.UI.Overlay.open();
$j("#dialogContainer").empty().append(data);
MTVN.UI.ModalWindow.updateLocation();
});
}

this.updateLocation = function(){
var mwElement = document.getElementById(modalWindowId);
var mwLeft = 0;
var mwTop = 0;
var mwWidth = $j(mwElement).width();
var bodyWidth = document.body.offsetWidth;

$j("#" + modalWindowId).removeClass("hide");

var wrap = document.getElementById("wrap");
var wrapX = $j("#wrap").offset().left;	
var wrapWidth = wrap.offsetWidth;
var wrapThird = Math.round(wrapWidth/3);
var warpHeight = wrap.offsetHeight;	

if(!currentLocationId){
// defaults to centered position
if(MTVN.UI.Overlay.active){
mwLeft = Math.round(bodyWidth/2 - mwWidth/2);
}
else{
mwLeft = Math.round(bodyWidth/2 - mwWidth/2); // centered for 446px-wide modal window
}	
mwTop = Math.round(((document.documentElement.clientHeight - mwElement.offsetHeight)/2) + ($j('html').scrollTop() || $j('body').scrollTop())) - 30; // 30 pixel cheat	
}
else{
//positioning relative to an element

var locElement = document.getElementById(currentLocationId);

var locLeft = $j("#" + currentLocationId).offset().left - wrapX;	//left position relative to wrap instead of the window left
var locTop = $j("#" + currentLocationId).offset().top;

if(locLeft < wrapThird){ mwLeft = wrapX -20; }
else if(locLeft > wrapThird && locLeft < (wrapThird * 2)){ Math.round(bodyWidth/2 - mwWidth/2); }
else{ 
//mwLeft = (wrapX + wrapWidth - mwWidth + 20) ; 
mwLeft = Math.round(bodyWidth/2 - mwWidth/2 - 200) ;
}

if(locTop < 350) {
//mwTop = locTop - (mwElement.offsetHeight + 1);
mwTop = locTop + 20;
}
else {
mwTop = locTop - 350;

}

}

mwElement.style.left = mwLeft + "px";
mwElement.style.top = mwTop + "px";

MTVN.UI.ModalWindow.isOpen = true;
}

this.close = function(){
var mwElement = document.getElementById(modalWindowId);
mwElement.style.left = "-9999px";
MTVN.UI.Overlay.close();
currentLocationId="";
this.isOpen = false;
}

this.mouseDown = function(e){
this.ignoreMouseDownBody = true;
return true;
}

this.mouseDownBody = function(e){
if (!this.ignoreMouseDownBody){
this.close();
}
this.ignoreMouseDownBody = false;
return true;
}
}

MTVN.UI.Tab = new function(){
this.open = function(obj){
var newActiveTabId = obj.parentNode.id;
var newActivePageId = newActiveTabId.substring(0, newActiveTabId.indexOf("Tab"));

var tab = document.getElementById(newActiveTabId);
var tabList = tab.parentNode;
var tabs = tabList.getElementsByTagName("li");

// set new active tab
for(var i=0; i < tabs.length; i++){
var t = tabs[i];

if(t.id == newActiveTabId){
$j(t).addClass("active");
}
else{
$j(t).removeClass("active");
}
}

// set new active page
var page = document.getElementById(newActivePageId);
if(page==null){
// Go to page given in anchor tag if page is null
window.location.href=obj.href;
}
else{
var pageList = page.parentNode;
var pages = pageList.childNodes;

for(var i=0; i < pages.length; i++){
var p = pages[i];

if(p.nodeName=="DIV" && p.className.indexOf('tab-content') >= 0){
if(p.id == newActivePageId){
$j(p).removeClass("hide");

if(p.className.indexOf('mobileWidget') >= 0){
var tabEvent = $j.Event("showtab");
$j(p).triggerHandler(tabEvent);
}
}
else{
$j(p).addClass("hide");
}
}
}
}
}

this.openAjax = function(obj, ajaxData, configParams){
var newActiveTabId = obj.parentNode.id;
var newActivePageId = newActiveTabId.substring(0, newActiveTabId.indexOf("Tab"));

var tab = document.getElementById(newActiveTabId);
var tabList = tab.parentNode;
var tabs = tabList.getElementsByTagName("li");
var containerHeight = 10;
var containerHeight2 = 0;

// set new active tab
for(var i=0; i < tabs.length; i++){
var t = tabs[i];
if(t.id == newActiveTabId) $j(t).addClass("active");
else $j(t).removeClass("active");
}

// set new active page
var page = document.getElementById(newActivePageId);
var pageList = page.parentNode;
var pages = pageList.childNodes;

for(var i=0; i < pages.length; i++){
var p = pages[i];
if(p.nodeName=="DIV" && p.className.indexOf('tab-content') >= 0 && p.className.indexOf('hide')== -1) { containerHeight2=$j(p).children("div").height(); containerHeight = $j(p).height();}
}

for(var i=0; i < pages.length; i++){
var p = pages[i];

if(p.nodeName=="DIV" && p.className.indexOf('tab-content') >= 0){
if(p.id == newActivePageId){
var container = $j(p);
if (container.is('.loaded')) {
container.removeClass("hide");
}else
{
container.css({'min-height': containerHeight});
//container.empty();
//container.children(".more-link.group").addClass("hide");

var tempStore = container.children(".more-link.group").remove();
container.prepend('<div class="ajax-loader"><img src="/sitewide/images/charlie/ajax-loader.gif" alt="Loading..."/></div>');
container.removeClass("hide");
$j.get(ajaxData, configParams, function(data){
container.empty();
container.children(".ajax-loader").remove();
container.prepend(data);
container.css({'min-height': '0px'});
//container.children(".more-link.group").removeClass("hide");
container.children(".more-link.group").css({'display': 'block'});
tempStore.appendTo(container);
container.addClass("loaded");
});
}
}
else{
$j(p).addClass("hide");
}
}
}

}
}

MTVN.UI.MdlTab = new function(){
this.open = function(obj){
var currentTabNavItem = $j(obj).parent();
var position = currentTabNavItem.prevAll().length;

currentTabNavItem.addClass("active");
currentTabNavItem.siblings().removeClass("active");

var mdl = currentTabNavItem.parents(".mdl:first");

var pages = (mdl.children("ol.lst").length >0) ? mdl.children("ol.lst") : mdl.children("div.tab-content");
pages.addClass("hide");
pages.eq(position).removeClass("hide");
}
}

MTVN.UI.RefreshPaginate = new function(){
this.submit = function(form){
var str = $j(form).text();
var maxPages = parseInt(str.substring(str.indexOf("of")+3, str.length));
var val = parseInt(form.page.value);
var baseUrl = form.baseUrl.value;

if(val > 0 && val <= maxPages){
var connector = (baseUrl.indexOf("?") >=0) ? "&" : "?";
var url = (val==1) ? baseUrl : baseUrl + connector + "page=" + val;
window.location.href = url;
}

return false;
}
}

MTVN.UI.AjaxPaginate = new function(){
this.page = function(obj, requestUrl, pageNum){
var paginationDiv = $j(obj).parent();
var container = paginationDiv.parent();
var params = {};
if(pageNum > 1) params.page = pageNum;

$j.get(requestUrl, params, function(data){
container.empty();
container.append(data);
});

}
}

MTVN.UI.Accordion = new function(){
var howMany = "";

this.init = function(){
// remove text nodes
$j("#accordion a.accord-link").each(function(){
for(var i=0; i<this.childNodes.length; i++){
if(this.childNodes[i].nodeType==3) this.removeChild(this.childNodes[i]);
}
});

$j("#accordion > div.accord-slat").bind("mouseenter", function(){ MTVN.UI.Accordion.activate(this); });
howMany = $j("#accordion > div.accord-slat").length;
MTVN.UI.Accordion.positionContent($j("#accordion > div.accord-over"));
}

this.activate = function(obj){
var active = $j(obj);
$j("#accordion > div.accord-slat").removeClass("accord-over");
active.addClass("accord-over");
MTVN.UI.Accordion.positionContent(active);
}

this.positionContent = function(active){
var position = active.prevAll().length + 1;
var gap = howMany - position;

var content = active.children(".accord-content"); // the active content box
var offsetLeft = MTVN.UI.Accordion.getOffsetLeft(active.get(0), active.get(0).offsetLeft); // left side of active item
var contentWidth = content.width() + 30;

var newLeft = (offsetLeft+133) - contentWidth/2;
var newRight = newLeft + contentWidth;

if(newRight > 950){
newLeft = 950 - contentWidth - (10*gap); // 10px for every item
}
else if(newLeft < 0){
newLeft = 10*position;
}

content.css("left", newLeft);
}

this.getOffsetLeft = function(element, offsetLeft){
if(element.offsetParent.className=="mdl mdl-main mdl-accordion"){
return offsetLeft;
}
else{
var parent = element.offsetParent;
var val = element.offsetLeft + parent.offsetLeft;
return MTVN.UI.Accordion.getOffsetLeft(parent, val);
}
}
}

MTVN.UI.InView = new function() {

var elements = [];
var positions = [];
var offsets = [];

var jwin = $j(window);

var init = function() {
jwin.bind("scroll resize", function() {
jwin.unbind("scroll resize");
setTimeout(function() {
checkElements();
}, 500);
});	
}

this.register = function(element, callback) {
var offsetLeft = 0;
var offsetTop = 0;
var elementOffset = element.offset();
if (elementOffset != null) {
offsetLeft = elementOffset.left;
offsetTop = elementOffset.top;
}

var coords = offsetLeft + "x" + offsetTop;
var offset = $j.grep(positions, function(n, i){
return (n == coords);
});
offsets.push(offset.length * 100);
positions.push(coords);

if(isInView(element, offset.length * 100)) {
callback();
} else {
elements.push(element);
element.one("inView", callback);
init();
}
}

var checkElements = function () {
var tempElements = [];
$j.each(elements, function(i) {
tempElements.push(this);
if (isInView(this, offsets[i])) {
this.trigger("inView");
tempElements.pop();
}
});
elements = tempElements;
if (elements.length > 0) {
init();
} 
}

var isInView = function(element, offset) {
var viewportHeight = jwin.height();
var docPos = jwin.scrollTop();
var elementOffsetTop = 0;
var elementOffset = element.offset();
if (elementOffset!=null) elementOffsetTop = element.offset().top;

var elPos = parseInt(elementOffsetTop) + offset;
return (elPos < viewportHeight + docPos);
}
}

// Taken from MTV's sitewide paginate.
MTVN.UI.Paginate = new function() {	
this.numVisiblePages;
this.firstVisiblePageNum = 1;
this.currentPositionIndex = 1;
this.currentPageNum = 1;
this.totalNumPages;
this.getPrev = function(obj,animate){
this.page(obj, 'prev', animate);
}

this.getNext = function(obj,animate){
this.page(obj, 'next', animate);
}

this.animatePagination = function(obj){
var pagenum = this.firstVisiblePageNum+this.currentPositionIndex-1;
//this.page2(obj, null, this.currentPageNum);

var mdl = $j(obj).parents('.mdl');

var paginationListoffsetParse = mdl.find(".paginationList").css("left");
if (paginationListoffsetParse == "auto") {paginationListoffsetParse = 0;}
var paginationListoffset = parseInt(paginationListoffsetParse);
var numberOffset = parseInt(mdl.find(".paginationList").children("#p" + this.currentPageNum).position().left);
//alert(mdl.find(".paginationList").children("#p" + this.currentPageNum).position().left);
if (-numberOffset > paginationListoffset) {
var moveOffset = paginationListoffset + numberOffset;
$j(mdl).find('.paginationList').animate({"left":'-='+moveOffset},{easing:"swing",duration:"slow",queue:true});
}

paginationListoffsetParse = mdl.find(".paginationList").css("left");
if (paginationListoffsetParse == "auto") {paginationListoffsetParse = 0;}
paginationListoffset = parseInt(paginationListoffsetParse);

numberOffset = parseInt(mdl.find(".paginationList").children("#p" + this.currentPageNum).position().left);
var containerWidth = parseInt(mdl.find(".paginationOverflowWidth").css("width"));
var numberWidth = parseInt(mdl.find(".paginationList").children("#p" + this.currentPageNum).width())+6;

if ( ((numberOffset + numberWidth) + paginationListoffset) > containerWidth){
var moveOffset = containerWidth - (numberOffset + numberWidth + paginationListoffset);
$j(mdl).find('.paginationList').animate({"left":'+='+moveOffset},{easing:"swing",duration:"slow",queue:true});
}

}

this.leftAction = function(obj){
if (this.currentPageNum>1){ this.currentPositionIndex--; this.currentPageNum--; this.page2(obj,null,this.currentPageNum); }
}

this.rightAction = function(obj){
if(this.currentPageNum < this.totalNumPages) {this.currentPageNum++; this.currentPositionIndex++; this.page2(obj, null,this.currentPageNum);}
}

this.get = function(mdl, requestPage){
var pagination = MTVN.UI.Paginate.Utils.findChild(mdl, 'pagination');
var pageCount = MTVN.UI.Paginate.Utils.findChild(pagination, 'sm');

var count = new Array();
count = pageCount.innerHTML.split(' ');

var total = count[2]*1;

var listCount = 0;
for(var i=0; i<mdl.childNodes.length; i++){
var child = mdl.childNodes[i];
if (child.nodeName=='OL' || (child.nodeName=='DIV' && child.className.indexOf('paginationGroup')>-1)){
listCount++;
if (listCount!=requestPage) MTVN.UI.Paginate.Utils.hide(child);
else MTVN.UI.Paginate.Utils.show(child);
}
}

var newPageCounter = requestPage + " of " + total;
pageCount.replaceChild(document.createTextNode(newPageCounter), pageCount.childNodes[0]);
}

this.page = function(obj, direction, animate){
var paginationDiv = $j(obj).parents('.pagination');
var mdl = $j(obj).parents('.mdl');
var pageCount = paginationDiv.find('.sm');

var count = new Array();
count = pageCount.html().split(' '); 
current = count[0]*1;
var total = count[2]*1;
var requestPage;

if(direction=='prev'){
if(current==1) requestPage = total;
else requestPage = current - 1;
}
else{
if(current==total) requestPage = 1;
else requestPage = current + 1;
}

if (animate) this.animateTransition($j(paginationDiv).parent().parent(),current,requestPage);
else this.staticTransition(mdl,current,requestPage);

var newPageCounter = requestPage + " of " + total;
pageCount.empty().append(newPageCounter);

if(requestPage == total) {
pageCount.parent().parent().removeClass("first").addClass("last");
} else if(requestPage == 1){
pageCount.parent().parent().removeClass("last").addClass("first");
} else {
pageCount.parent().parent().removeClass("last").removeClass("first");
}
}

// pagination in list format ( < 1 2 3 4 5 > )
this.page2 = function(obj, direction, newpage){

this.currentPageNum = newpage;
//this.currentPositionIndex = this.currentPageNum - this.firstVisiblePageNum + 1;	

var paginationDiv = $j(obj).parents('.pagination');
var mdl = $j(obj).parents('.mdl');
var current = parseInt(paginationDiv.find('.active').find('a').html());
var total = paginationDiv.find('p').length;

var requestPage;
if(direction=='prev'){
if(current==1) requestPage = total;
else requestPage = current - 1;
}
else if (direction=='next'){
if(current==total) requestPage = 1;
else requestPage = current + 1;

}
else requestPage=newpage;
requestPage=requestPage-1;
current=current-1;

paginationDiv.find('.active').removeClass('active');
$j(paginationDiv.find('p')[requestPage]).addClass('active');

this.animateTransition(mdl,current,requestPage);
if($j(".paginationList").children("p").length > 0) this.animatePagination(obj);
}

this.animateTransition = function(mdl,current,requestPage) {

var animation = function(){
var pagewidth = $j(mdl).find('.pages').find('ol').width()+10; 

var jumpto = (current-requestPage)*pagewidth; 

var thisJumpto = parseInt($j(mdl).find('.pages').css('left')) + jumpto;

$j(mdl).find('.pages').animate({"left": thisJumpto},{easing:"swing",duration:'slow'});

$j(this).dequeue();

}

$j(mdl).find('.pages').queue(animation);	

//$j(mdl).find('.pages').animate({"left":'+=' + jumpto},{easing:"swing",duration:"slow"});

//var pagewidth2 = $j(mdl).find('.paginationList').find('p').width()+6;
//var jumpto2 = (current-requestPage)*pagewidth2;
//alert(jumpto2);
//$j(mdl).find('.paginationList').animate({"left":'+='+jumpto2},{easing:"swing",duration:"slow"});
}

this.staticTransition = function(mdl,current,requestPage) { 
if (mdl.find('.paginationGroup').length>0) {
hideChild = $j(mdl.find('.paginationGroup')[current-1]);
showChild = $j(mdl.find('.paginationGroup')[requestPage-1]);
}
else {
hideChild = $j(mdl.find('ol')[current-1]); 
showChild = $j(mdl.find('ol')[requestPage-1]);
}
hideChild.addClass('hide');
showChild.removeClass('hide'); 
} 

}

MTVN.UI.Paginate.Utils = new function() {
this.show = function(element){
if (element!=null && element.className.indexOf('hide') >= 0){
element.className = element.className.substring(0, element.className.indexOf('hide'));
}
}

this.hide = function(element){
if (element!=null && element.className.indexOf('hide') < 0){
element.className = element.className + " hide";
}
}

// returns the first parent of a node with a given class
this.findParent = function(obj, parentClass){
var parent = obj.parentNode;
if (parent.className && parent.className.indexOf(parentClass) != -1)
return parent;
else return this.findParent(parent, parentClass);
}

// returns the first child of a node with a given class
this.findChild = function(obj, childClass){
var match;
for(var i=0; i<obj.childNodes.length; i++){
var child = obj.childNodes[i];
if (child.className && child.className==childClass)
match = child;
else if(child.childNodes && child.childNodes.length>0){
match = this.findChild(child, childClass);
}
if(match) return match;
}
}
}

MTVN.UI.GetCurrentServerTime = new function() {

this.date = function() {

return new InitCurrentTime().now;

}

this.raw = function() {

return new InitCurrentTime().rawTime;

}

}

$j(function() {
$j("a.dynLink").click(function (e) {
e.preventDefault();
});
});

$j(function() {
if($j("div.player-placeholder").length > 0) {
MTVN.LitePlayer.init();
MTVN.LitePlayer.applyClick();
}	
});

MTVN.LitePlayer = new function(){
this.imageServer = "mtv.mtvnimages.com";
this.videoUriPrefix = "mgid:uma:video:mtv.com:";
this.playlistUriPrefix = "mgid:uma:videolist:mtv.com:";
this.imageServerUri = "";
this.affilatedHost = "";

this.active = false;
this.playerUrl = "PLAYER_URL_NOT_SET";
this.configUrl = "CONFIG_URL_NOT_SET";
this.width = "240";
this.height = "211";
this.playerArgs = "";

var _this = this;
var initPlayer = function(){
$j("div.player-placeholder").each(function(i){
$this = $j(this);

var playerArgs = _this.playerArgs;
var flashVars;
var configParams = "";

if (this.id) {
configParams = this.id.replace(/\./g, "&").replace(/:/g,"=");
if( $this.attr("flashVars") ) {
configParams += '&' + $this.attr("flashVars");
}
} else {
if ($this.attr("flashVars").length > 0) {
configParams = $this.attr("flashVars");
}
}
if (playerArgs.length > 0) {
playerArgs += "&";
}	

playerArgs += configParams;	
var paramsFromId = {};
var params = configParams.split("&");
var uri;
var imageUri = "";
$j.each(params, function() {
var pair = this.split("=");
paramsFromId[pair[0]] = pair[1];
});

if(typeof paramsFromId.vid != "undefined") {
uri = _this.videoUriPrefix + paramsFromId.vid;
if(_this.imageServerUri != "") {
imageUri = _this.imageServerUri + paramsFromId.vid;
}
} else {
if (typeof paramsFromId.id != "undefined") {
uri = _this.playlistUriPrefix + paramsFromId.id;	
if(_this.imageServerUri != "") {
imageUri = _this.imageServerUri + paramsFromId.id;
}
}
}

if(imageUri == "") { imageUri = uri; }

if(typeof paramsFromId.freewheelId != "undefined") flashVars = "sid=" + paramsFromId.freewheelId + "&configParams=" + escape(playerArgs);
else flashVars = "configParams=" + escape(playerArgs);

var width = (typeof $this.attr("width") == 'undefined') ? _this.width: $this.attr("width");
var height = (typeof $this.attr("height") == 'undefined') ? _this.height: $this.attr("height");

this.innerHTML = _this.generatePreloadHTML("playerPlaceholder", width, height, uri, flashVars, imageUri.replace("videolist", "content"), paramsFromId.freewheelId);

// Fix for IE breaking when leaving a page where a player has been loaded with litePlayer
(function(){var s=function(){__flash__removeCallback=function(i,n){if(i)i[n]=null;};window.setTimeout(s,10);};s();})();
});
this.init = function(){};
}

this.init = initPlayer;

this.generatePreloadHTML = function(className, width, height, playerUri, flashVars, imageServerUri, freewheelId){

var playButtonCenterX = Math.floor(width / 2) - 46;
var playButtonCenterY = Math.floor(height / 2) - 36;

var controlBarTop = height - 31;

var html = '<div style="position: relative; width: ' + width + 'px; height: ' + height + 'px; cursor: pointer;" class="' + className + '" width="' + width + '" height="' + height + '"' + ((freewheelId != null) ? (' fwId="' + freewheelId + '"') : '') + ' id="' + playerUri + '" flashVars="' + flashVars + '">';

html += '<img style="position: absolute; top: ' + playButtonCenterY + 'px; left: ' + playButtonCenterX + 'px;" sr' +'c="'+ MTVN.LitePlayer.affilatedHost +'/global/music/player/images/bttn_play-big.png" />';

html += '<img src="http://' + _this.imageServer + '/uri/' + imageServerUri + '?height=' + controlBarTop + '&width=' + width + '" />';

html += '<img style="position: absolute; left: 0px; bottom:0px;" sr' + 'c="'+ MTVN.LitePlayer.affilatedHost + '/global/music/player/images/bttn_play.gif" />';

html += '<div style="position: absolute; left: 31px; bottom: 0px; width: ' + (width - 31) + 'px; height: 31px; background: url(' + MTVN.LitePlayer.affilatedHost + '/global/music/player/images/control-bar.gif) repeat-x top left"> </div>';

html += '</div>';

return html;
}

this.applyClick = function() {
var h = 0;
var w = 0;
var bgcolor = "#000000";
var hostname = window.location.href;

if (hostname.indexOf(".mtvi.com") > -1)
hostname = "http://media.mtvnservices-q.mtvi.com";
else 
hostname = "http://media.mtvnservices.com";

$j(".playerPlaceholder").one("click", function() {
var $this = $j(this);
var id = this.id;
var flashVars = $this.attr("flashVars");
var fwId = $this.attr("fwId");

if (h == 0){
h = $this.attr("height");
w = $this.attr("width");
}

if (fwId == null || fwId == "") {

if (typeof(freeWheelSSID) != 'undefined')
fwId = freeWheelSSID;
else 
fwId = "MTV_Videos";

}

var embed = "";
embed += '<embed src="' + hostname + '/'+id + '/cp~' + flashVars.replace("configParams=", "") +'"';
embed += 'type="application/x-shockwave-flash"';
embed += 'wmode="opaque"';
embed += 'name="'+id+'"';
embed += 'id="'+id+'"';
embed += 'width="'+w+'"';
embed += 'height="'+h+'"';
embed += 'bgcolor="'+bgcolor+'"';
embed += 'allowFullscreen="true"';
embed += 'flashVars="autoPlay=true' + '&sid=' + fwId + '"';
embed += 'allowScriptAccess="always">';
embed += '</embed>';

$this.html(embed);

});	
}
}

MTVN.LitePlayer.Article = new function(){

this.init = function(){

var pphDivIdVal = $j(".player-placeholder").attr("id");
if (pphDivIdVal.match("^"+"id") == "id")
MTVN.LitePlayer.playerArgs = "instance=fullepisode";

else MTVN.LitePlayer.playerArgs = "instance=news";
var height = 223;
var width = 256;
var styling = {
'background-color': '#000000',
'height': height + 'px',
'width': width + 'px',
'float':'left',
'margin': '0px 10px 10px 0px',
'position' : 'relative',
'cursor' : 'pointer'
}
$j(".player-placeholder").
css(styling).
attr("height",height).
attr("width",width);

MTVN.LitePlayer.init();
}
}

MTVN.Community = new function(){
this.host = 'http://';
}

MTVN.Community.Widgets = function(){
this.errorLocation = '';
}

MTVN.Flux = new function(){}

MTVN.Flux.DAAPI = new function(){
this.initArray = new Array();
this.baseUrl = "http://daapi.flux.com/2.0/00001/JSON/87F6FFFF0099CB900002FFFFF687";

this.init = function(){
if(communityAccess){
jQuery.each(MTVN.Flux.DAAPI.initArray, function (i) {
if(jQuery.isFunction(MTVN.Flux.DAAPI.initArray[i])) MTVN.Flux.DAAPI.initArray[i]();
});

MTVN.Flux.DAAPI.Module.init();

//if(typeof FN!='undefined' && typeof FN.init=="function") FN.init();
}
}

this.sendRequest = function(feed, callback, params) {
var requestUrl = MTVN.Flux.DAAPI.baseUrl + feed;
Flux.Core.executeGetRequest(requestUrl, function(response){
callback(Sys.Serialization.JavaScriptSerializer.deserialize(response), params);
});
}
}

MTVN.Flux.DAAPI.Module = new function(){
var config; // the current config - a regular js object
var container; // the current container - a jquery object
var responses = new Array();	// stores DAAPI responses for a module until all tabs are loaded
var responseCounter = 0;

this.configs = new Array(); // queue of module configs

this.init = function(){
if(MTVN.Flux.DAAPI.Module.configs.length > 0){
config = MTVN.Flux.DAAPI.Module.configs.pop();
MTVN.Flux.DAAPI.Module.create();
}
}

this.create = function(){
if($j("#"+config.containerId).is("*")){
container = $j("#"+config.containerId);
for(var i=0; i < config.tabs.length; i++){
MTVN.Flux.DAAPI.sendRequest(config.tabs[i].url, MTVN.Flux.DAAPI.Module.loadData, {position:i});
}
}
else{
MTVN.Flux.DAAPI.Module.finish();
}
}

this.finish = function(){
responses = new Array();
responseCounter = 0;
MTVN.Flux.DAAPI.Module.init(); // start over for more module configs
}

/* ------------------ */

this.loadData = function(response, paramsObj){
responses[paramsObj.position] = response;
responseCounter++;

if(responseCounter == config.tabs.length){
MTVN.Flux.DAAPI.Module.build();
}
}

this.build = function(){
if(config.tabs.length > 1) container.append(MTVN.Flux.DAAPI.Module.buildTabNav());

for(var i=0; i<responses.length; i++){
var isFirst = (i==0) ? true : false;
container.append(MTVN.Flux.DAAPI.Module.buildTab(responses[i], isFirst));
}

MTVN.Flux.DAAPI.Module.finish();
}

this.buildTabNav = function(){
var ul = $j("<ul/>").addClass("mdl-nav group");

for(var x=0; x < config.tabs.length; x++){
var li = $j("<li/>");
if(x==0) li.addClass("active");

var a = $j("<a/>").attr("href", "#").append(config.tabs[x].title);
a.click(function(){
MTVN.UI.MdlTab.open(this);
return false;
});

li.append(a);
ul.append(li);
}
return ul;
}

this.buildTab = function(response, isFirst){
var items = response.Items;
var itemCounter = 0;

if(items.length > 0){
var tab = $j("<div/>").addClass("tab-content");
if(!isFirst) tab.addClass("hide");

for(var r=1; r <= config.rows; r++){
if(itemCounter < items.length){	
var olClass = "lst lst-photos";
if(config.columns==2) olClass += " lst-photos-two";
else if(config.columns==3) olClass += " lst-photos-three";
else if(config.columns==4) olClass += " lst-photos-four";
else if(config.columns==6) olClass += " lst-photos-six";

var list = $j("<ol/>").addClass(olClass);

for(var c=1; c <= config.columns; c++){
var isLast = (c==config.columns) ? true : false;
if(itemCounter < items.length){
list.append(MTVN.Flux.DAAPI.Module.buildItem(items[itemCounter],isLast));
itemCounter++;
}
}

tab.append(list);
}
}
return tab;
}
}

this.buildItem = function(Entry, isLast){	
var title = $j("<div/>").addClass("title2");
var titleLink = $j("<a/>").attr("href", Entry.DetailUrl);
titleLink.append($j("<img/>").attr("src", Entry.Thumbnails.Medium).addClass("thumb"));

var icon = "";
switch(Entry.Alias){
case "Video":
icon = $j("<span/>").addClass("icon icon-play").append("Video: ");
break;
default: break;
}

if(icon!=="") titleLink.append(icon);
titleLink.append(Entry.Title);
title.append(titleLink);

var li = $j("<li/>");	
if(isLast) li.addClass("last");
li.append(title);
li.append($j("<p/>").addClass("deck").append(Entry.Creator.Title));

var date = MTVN.Flux.DAAPI.Utils.formatDate(Entry.DateCreated);
li.append($j("<p/>").append($j("<span/>").addClass("posted").append("Posted " + date)));

return li;
}
}

MTVN.Flux.DAAPI.Utils = new function(){
this.formatDate = function(date){
var m = date.getMonth() + 1;
var d = date.getDate();
var y = date.getFullYear().toString().substr(2,2);

var formattedDate = m + "/" + d + "/" + y;

return formattedDate;
}
}

// included in ../mtvn.jhtml
// depends on community_flux.jhtml

// Flux Widget Proxy for MTVN
// 

MTVN.Flux.Widgets = new function(){

// you can turn off widgets globally by setting this to false or
// on locally by calling MTVN.Flux.Widgets.enabled = false;
this.enabled = true;

this.create=function(name, options){

if (!(Flux && typeof Flux.createWidget == "function") || !this.enabled) {
return;
}

options = this.getOptionsByName(name, options);
var widgetName = this.getWidgetNameByName(name);
Flux.createWidget(widgetName, options);
}

this.loadAllAttempted = false;
this.loadAll=function() {
if (!MTVN.Flux.Widgets.loadAllAttempted) {
$j(".fluxWidget:not(.delay-load)").each( function() {
MTVN.Flux.Widgets.loadEach(this);
});
MTVN.Flux.Widgets.loadAllAttempted = true;
}
}

this.loadEach = function(el) {
try{
var jsonText = "";
var code = $j(el).find("code");
if (code.get(0).firstChild && code.get(0).firstChild.nodeType == 8) {
jsonText = code.get(0).firstChild.nodeValue;
}

if (jsonText.length > 0 && ($j(el).parent().attr("id").indexOf("scriptPopupWidget_") == -1 || $j("#playerContainer").is("*") || el.toString().indexOf("#ModuleVideoList_") > -1)) {
var obj = eval("(" + jsonText + ")");
$j(el).empty().removeClass("hide");
if (typeof(MTV) != "undefined" && typeof(MTV.Flux) != "undefined" && typeof(MTV.Flux.ucid) != "undefined") {
if (!(MTV.Flux.ucid == "0ABEFFFF01F364840002FFFFBE0A" && obj.args.containerId == "wQuickMenu"))
if (!(MTV.Flux.ucid == "D3FCFFFF0002D51D0002FFFFFCD3" && obj.args.containerId == "wQuickMenu2"))
MTVN.Flux.Widgets.create(obj.widget, obj.args);
}
else
MTVN.Flux.Widgets.create(obj.widget, obj.args);
}
}catch(e){}
}

// set default options based on the name parameter
// passed to the create method
this.getOptionsByName=function(name, options)
{
switch(name) {
case 'Share2' :
var opts = {};
opts.elements = [
{ id: 'Facebook', placeholder: 'service1Element'},
{ id: 'Twitter', placeholder: 'service2Element'},
{ id: 'StumbleUpon', placeholder: 'service3Element'},
{ id: 'More', placeholder: 'moreElement'}
];
opts.overlayElements = [
{ id: 'FeedTab', visible: false },
{ id: 'GroupsTab', visible: false},
{ id: 'OtherTab', visible: true, elements: [
{ id: 'Facebook', visible: true },
{ id: 'Twitter', visible: true },
{ id: 'StumbleUpon', visible: true },
{ id: 'Digg', visible: true },
{ id: 'MySpace', visible: true },
{ id: 'Blogger', visible: true },
{ id: 'GoogleBuzz', visible: true },
{ id: 'Yahoo', visible: true },
{ id: 'Orkut', visible: true },	
{ id: 'Hyves', visible: true }
]
}	
];

return $j.extend(opts, options);
break;
case 'Share' :
var opts = {}
opts.size = 'small';
opts.items = [
{ id: 'share', title: 'Share' },
{ id: 'addToFavorites', title: 'Favorite' }
];
return $j.extend(opts, options);
break;
case 'Rate' : 
var opts = {};
opts.size = 'small';

var ratings_title = 'Rate this';

if (options['ratings_title'] != null){
ratings_title = ratings_title + ' ' + options['ratings_title'];
}

opts.items = [
{ id: 'rate', title: ratings_title }
]; 

return $j.extend(opts, options);
break; 

case 'Statistics' :

var opts = {}
opts.size = 'small';

if ( options.hide_titles ) {
opts.items = [
{ id: 'viewCount', title: '' },
{ id: 'commentCount', title: ''},
{ id: 'contentRating', title: { thumbsUpTitle: '', thumbsDownTitle: '' }} 
];
} else {
opts.items = [
{ id: 'viewCount', title: 'Views' },
{ id: 'commentCount', title: 'Comments'},
{ id: 'contentRating', title: { thumbsUpTitle: 'Rating', thumbsDownTitle: 'Rating' }} 
];
}

if (!options.hide_ratings) {
var ratings_title = options.hide_titles ? '' : 'Rate ' + options['ratings_title'];
options['ratings_title'] = null;
options['hide_ratings'] = null;
opts.items.push({ id: 'rate', title: ratings_title });
}

return $j.extend(opts, options);
break;
case 'Usage' :
var opts = {};
opts.layout = 'horizontal';
opts.size = 'small';
opts.items = [
{ id: 'commentCount', title: 'comments' },
{ id: 'contentRating', title: { thumbsUpTitle: 'Rating', thumbsDownTitle: 'Rating' }} 
];
return $j.extend(opts, options);
break;
case 'Rating' :
var opts = {};
opts.layout = 'horizontal';
opts.size = 'small';
opts.items = [
{ id: 'commentCount', title: 'Comments' },
{ id: 'contentRating', title: { thumbsUpTitle: 'Rating', thumbsDownTitle: 'Rating' }},
{ id: 'rate' },
{ id: 'share', title: 'Share' },
{ id: 'addToFavorites', title: 'Favorite' }
];
return $j.extend(opts, options);
break;
case 'QuickMenu' :
var opts = {};
opts.showFBConnectButton = true;
return $j.extend(opts, options);
break;
default :
return options;
break;
}
}

this.getWidgetNameByName=function(name)
{
switch(name) {
case 'Rating' :
case 'Rate' :
case 'Usage' :
case 'Statistics' :
case 'Share' :
return 'ContentAction';
break;
case 'Share2' :
return 'Share';
break;
default :
return name;
break;
}
}
};

MTVN.Flux.widgetDelayLoad = function(arg) {
if ((typeof(MTV) == "undefined" || typeof(MTV.Flux) == "undefined") || typeof(MTV.Flux.ucid) == "undefined" || arg == "load") {
$j('.fluxWidget.delay-load').each(function(){
var widget = $j(this);

MTVN.UI.InView.register(widget, function() {
MTVN.Flux.Widgets.loadEach(widget);
});	
});
}
}

if (typeof(excludefluxWidgetLoadCall) == "undefined") $j(MTVN.Flux.widgetDelayLoad);

MTVN.Utils = {}

MTVN.Utils.Cookies = new function(){
this.create = function(name,value,days){
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
} else {
var expires = "";
}
document.cookie = name+"="+value+expires+"; path=/";
}

this.read = function(name){
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}

this.erase = function(name){
MTVN.Utils.Cookies.create(name,"",-1);
}
}

MTVN.Utils.addSponsoredOverlay = function(imgPath, imgId, width, height, divSelector, trackingCode) {
var imgSrc = imgPath;
$j("#page-header h1").attr("style", "height: 30px;").empty();
$j("<img/>").attr({"id":imgId, "src":imgSrc, "border": 0, "width":width, "height":height}).prependTo(divSelector);
if (trackingCode != null)
$j("<img/>").attr({"src":trackingCode, "border": 0, "width": 1, "height": 1}).appendTo("#page-header");
}
