


$(document).ready(function(){
	MTV.init();
});

MTV = new function(){
	this.initArray = new Array();
	this.version = 'charlie';

	this.init = function(){
		document.body.onmousedown = mouseDown;
		MTV.Events.addLinkEvents();
		MTV.Voting.init();

		for(var i=0; i<MTV.initArray.length; i++){
			MTV.initArray[i]();
		}

		//jQuery.isFunction()
		return true;
	}

	mouseDown = function(e){
		if (MTV.UI.ModalWindow.isOpen) MTV.UI.ModalWindow.mouseDownBody(e);
		return true;
	}
}

MTV.UI = new function(){}

MTV.UI.Overlay = new function(){
	this.active = false;
	
	this.init = function(){
		$j("#noFlash").append('<div id="overlay"></div>');
		$j("#modalWindow").remove().appendTo("#noFlash");
		MTV.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");
	}
}

MTV.UI.ModalWindow = new function(){
	var modalWindowId = "modalWindow";
	var currentLocationId = "";
	this.ignoreMouseDownBody = false;
	this.isOpen = false;

	this.open = function(requestUrl, locationId, xhrFormat){
		currentLocationId = locationId;
		
		if(xhrFormat=="jquery"){
			$j.get(requestUrl, function(data){
				MTV.UI.Overlay.open();
				$j("#dialogContainer").empty().append(data);
				MTV.UI.ModalWindow.updateLocation();
			});
		}
		else{
			MTV.Utils.requestTaconite(requestUrl, '','','', MTV.UI.ModalWindow.updateLocation);
		}
		//this.isOpen = true;
	}

	this.updateLocation = function(){
		var mwElement = document.getElementById(modalWindowId);
		var mwLeft = 0;
		var mwTop = 0;
		var mwWidth = 446;

		//MTV.Utils.makeVisible(modalWindowId);
		MTV.Utils.show(modalWindowId);

		if(!currentLocationId){
			// defaults to centered position
			if(MTV.UI.Overlay.active){
				var bodyWidth = document.body.offsetWidth;
				mwLeft = Math.round(bodyWidth/2 - mwWidth/2);
			}
			else{
				mwLeft = 257; // centered for 446px-wide modal window
			}	
			mwTop = Math.round(((document.documentElement.clientHeight - mwElement.offsetHeight)/2) + document.documentElement.scrollTop) - 30; // 30 pixel cheat	
		}
		else{
			//positioning relative to an element
			var locElement = document.getElementById(currentLocationId);

			var locLeft = MTV.Utils.findPosX(locElement) - MTV.Utils.findPosX(document.getElementById("wrap"));	//left position relative to wrap instead of the window left
			var locTop = MTV.Utils.findPosY(locElement);

			if(locLeft < 320){ mwLeft = -20; }
			else if(locLeft > 320 && locLeft < 640){ mwLeft = 257; }
			else{ mwLeft = 533; }

			//mwTop = locTop - (mwElement.offsetHeight + 1);
			mwTop = locTop + 20;
		}

		mwElement.style.left = mwLeft + "px";
		mwElement.style.top = mwTop + "px";

		MTV.UI.ModalWindow.isOpen = true;
	}

	this.close = function(){
		//MTV.Utils.makeInvisible(modalWindowId);
		//MTV.Utils.hide(modalWindowId);
		var mwElement = document.getElementById(modalWindowId);
		mwElement.style.left = "-9999px";
		MTV.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;
	}
}

MTV.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){
				if(t.className.indexOf('active') < 0){
					t.className = t.className + " active";
				}
			}
			else{
				if(t.className.indexOf('active') >= 0){
					t.className = t.className.substring(0, t.className.indexOf("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('showAlways') < 0){
				if(p.id == newActivePageId){
					MTV.Utils.show(p.id);
				}
				else{
					MTV.Utils.hide(p.id);
				}
			}
		}

	}
}

MTV.UI.MdlTab = new function(){
	this.open = function(obj){
		var li = $(obj).parent();
		var position = li.prevAll().length;

		li.addClass("active");
		li.siblings().removeClass("active");

		var mdl = li.parents(".mdl:first");

		var pages = (mdl.children("ol.lst").length >0) ? mdl.children("ol.lst") : mdl.children("div");
		pages.addClass("hide");
		pages.eq(position).removeClass("hide");
	}
}

MTV.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;
	}
}

MTV.UI.Accordion = new function(){
	var howMany = "";

	this.init = function(){
		// remove text nodes
		$("#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]);
			}
		});

		$("#accordion > div.accord-slat").bind("mouseenter", function(){ MTV.UI.Accordion.activate(this); });
		howMany = $("#accordion > div.accord-slat").length;
		MTV.UI.Accordion.positionContent($("#accordion > div.accord-over"));
	}

	this.activate = function(obj){
		var active = $(obj);
		$("#accordion > div.accord-slat").removeClass("accord-over");
		active.addClass("accord-over");
		MTV.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 = MTV.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 MTV.UI.Accordion.getOffsetLeft(parent, val);
		}
	}
}

MTV.Content = new function(){}

MTV.Content.RSS = new function(){
	this.open = function(obj){
		var dataUrl = "/rss/xml/detail.jhtml?rssId=" + obj.id;
		MTV.UI.ModalWindow.open(dataUrl, obj.id);
	}
}

MTV.Voting = new function(){
	this.pc = "";

	this.init = function(){
		MTV.Voting.pc = new PlayerController("MTV.Voting.pc");
		MTV.Voting.pc.configUrl = MTV.Voting.Player.configUrl;

		var allDivs = document.getElementsByTagName("div");

		for (var i=0; i< allDivs.length; i++){
			switch(allDivs[i].className){
				case 'voting-player':
					if (MTV.Voting.Player.active){
						var playerUrl = "";
						var targetId = allDivs[i].id;
						var embedId = targetId + "Player";

						var vars = targetId.split(".");
						for (var j=0; j<vars.length; j++) {
						    var pair = vars[j].split(":");
							playerUrl = playerUrl + pair[0] + "=" + pair[1];
						    if(vars[j+1]) playerUrl += "&";
						}

						playerUrl += "&o=1";

						MTV.Voting.pc.write2(MTV.Voting.Player.configUrl, playerUrl, targetId, embedId, MTV.Voting.Player.width, MTV.Voting.Player.height, []);
					}
					break;
				case 'vote-btn':
					if (MTV.Voting.Button.active){
						var flashVars = "";
						var targetId = allDivs[i].id;
						var embedId = targetId + "Button";

						var vars = targetId.split(":"); //get pollId and value
						var pollId = vars[0];
						var value = vars[1];

						flashVars += "cogix=" + MTV.Voting.Button.cogix + "&amp;";
						flashVars += "pollid=" + pollId + "&amp;";
						flashVars += "answer" + "=" + value + "&amp;";
						flashVars += "validator=" + MTV.Voting.Button.validator + "&amp;";
						flashVars += "authClass=" + MTV.Voting.Button.authClass;

						var so = new SWFObject(MTV.Voting.Button.src, embedId, MTV.Voting.Button.width, MTV.Voting.Button.height, "9", "#000000");
						so.addParam("flashVars", flashVars);
						so.addParam("AllowScriptAccess", "sameDomain");
						so.addParam("wmode", "transparent");
						so.useExpressInstall('/sitewide/components/expressInstall/adobeExpressInstall.swf');
						so.write(targetId);
					}
					break;
				default: break;
			}
		}
	}
}

MTV.Voting.Player = new function(){
	this.active = false;
	this.configUrl = "";
	this.width = "240";
	this.height = "180";
}

MTV.Voting.Button = new function(){
	this.active = false;
	this.src = "/sitewide/components/buttons/vote/voteButton.swf";
	this.width = "75";
	this.height = "30";
	this.cogix = "polling-onair";
	this.validator= "timestamp|votes";
	this.authClass = "com.mtvnet.auth.dis.HashDigestInputStrategy1";
}



MTV.Events = new function(){
	this.addLinkEvents = function(){
		var allLinks = document.getElementsByTagName("a");

		for (var i=0; i< allLinks.length; i++){
			switch(allLinks[i].className){
				case 'rssLink':
					allLinks[i].onclick = function(){
						MTV.Content.RSS.open(this);
						return false;
					}
					break;
				default: break;
			}
		}

		$('.user-send-message').each(function() {
			if(Flux.Context._isCommunityMember) {
				var user_display_name = Flux.Context._currentUserSettings.UserDisplayName;
				var community_landing = Flux.Context._communityLandingPage;
				var ucid = this.href.match(/\w+$/);
				this.href = community_landing + "profile/" + user_display_name + "/Messaging/Mail.aspx?recipient=" + ucid;
			}
			else {
				this.href = Flux.Context._signInUrl + "?returnPath=" + window.location.href;
			}
		});

	}

	// addEventSimple and removeEventSimple courtesy of quirksmode.org
	this.addEventSimple = function(obj,evt,fn) {
		if (obj.addEventListener)
			obj.addEventListener(evt,fn,false);
		else if (obj.attachEvent)
			obj.attachEvent('on'+evt,fn);
	}

	this.removeEventSimple = function(obj,evt,fn) {
		if (obj.removeEventListener)
			obj.removeEventListener(evt,fn,false);
		else if (obj.detachEvent)
			obj.detachEvent('on'+evt,fn);
	}
}

MTV.Community = new function(){
	this.host = 'http://community.mtv.com';
}

MTV.Community.Widgets = function(){
	this.errorLocation = '';
}







		
	


		
	
MTV.Flux = new function(){}

MTV.Flux.DAAPI = new function(){
	this.initArray = new Array();
	this.baseUrl = "http://daapiak-mtv.flux.com/2.0/00001/JSON/D3FCFFFF0002D51D0002FFFFFCD3";

	this.init = function(){
		jQuery.each(MTV.Flux.DAAPI.initArray, function (i) {
			if(jQuery.isFunction(MTV.Flux.DAAPI.initArray[i])) MTV.Flux.DAAPI.initArray[i]();
		});

		//if(typeof FN!='undefined' && typeof FN.init=="function") FN.init();
	}

	this.sendRequest = function(feed, callback, params) {
		var requestUrl = MTV.Flux.DAAPI.baseUrl + feed;
		Flux.Core.executeGetRequest(requestUrl, function(response){
			callback(Sys.Serialization.JavaScriptSerializer.deserialize(response), params);
		});
	}
}

MTV.Utils = new function(){
	this.show = function(id){
		var element = document.getElementById(id);
		if (element!=null && element.className.indexOf('hide') >= 0){
			element.className = element.className.substring(0, element.className.indexOf('hide'));
		}
	}

	this.hide = function(id){
		var element = document.getElementById(id);
		if (element!=null){
			element.className = element.className + " hide";
		}
	}

	this.makeVisible = function(id){
		var element = document.getElementById(id);
		if (element!=null && element.className.indexOf('hidden') >= 0){
			element.className = element.className.substring(0, element.className.indexOf('hidden'));
		}
	}

	this.makeInvisible = function(id){
		var element = document.getElementById(id);
		if (element!=null){
			element.className = element.className + " hidden";
		}
	}

	this.findPosX = function(obj){
		var curleft = 0;
		if(obj.offsetParent)
			while(1){
				curleft += obj.offsetLeft;
				if(!obj.offsetParent)
					break;
				obj = obj.offsetParent;
			}
		else if(obj.x)
			curleft += obj.x;
		return curleft;
	}

	this.findPosY = function(obj){
		var curtop = 0;
		if(obj.offsetParent)
			while(1){
				curtop += obj.offsetTop;
				if(!obj.offsetParent)
					break;
				obj = obj.offsetParent;
			}
		else if(obj.y)
			curtop += obj.y;
		return curtop;
	}

	this.requestTaconite = function(url, formElements, async, preRequest, postRequest){
		var ar = new AjaxRequest(url);
		if (formElements != undefined){
			for (var i=0; i < formElements.length; i++){
				ar.addNamedFormElements(formElements[i]);
			}
		}

		if (async!=null && async!=''){ ar.setAsync(async); }
		if (preRequest!=null && preRequest!=''){ ar.setPreRequest(preRequest); }
		if (postRequest!=null && postRequest!=''){ ar.setPostRequest(postRequest); }

		ar.sendRequest();
	}

}

// mimicks li:hover for IE, which doesn't support it
var hoverDebug = Array();
sfHover = function() {
	try
	{

		var sfEls = document.getElementById("nav").getElementsByTagName("LI");
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" sfhover";
			}
			sfEls[i].onmouseout=function() {
				this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
			}
		}
	}
	catch(err)
	{
		hoverDebug[0] = err;
	}
}
//if (window.attachEvent) window.attachEvent("onload", sfHover);

// mimicks li:hover for IE, which doesn't support it
var hover2Debug = Array();
sfHover2 = function() {
	try
	{

		var sfEls = document.getElementById("boxOffice-menu").getElementsByTagName("LI");
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" sfhover2";
			}
			sfEls[i].onmouseout=function() {
				this.className=this.className.replace(new RegExp(" sfhover2\\b"), "");
			}
		}
	}
	catch(err)
	{
		hover2Debug[0] = err;
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover2);

// for thumbnail view toggling
function vidExpand() {
	if(document.getElementById && document.createTextNode) {
		if(document.getElementById('vidclips')) {
			document.getElementById('vidclips').className='full';
			document.getElementById('linkExpand').className='hide';
			document.getElementById('linkCollapse').className='';
			document.getElementById('vid-toggle-bottom').className='vid-toggle';
			if (typeof tooltip.deactivate == "function") tooltip.deactivate(document.getElementById("vidclips"));
		}
	}
}

function vidCollapse() {
	if(document.getElementById && document.createTextNode) {
		if(document.getElementById('vidclips')) {
			document.getElementById('vidclips').className='simple';
			document.getElementById('linkCollapse').className='hide';
			document.getElementById('linkExpand').className='';
			document.getElementById('vid-toggle-bottom').className='hide';
			if (typeof tooltip.activate == "function") tooltip.activate(document.getElementById("vidclips"));
		}
	}
}


// for popups
function popupOpen(a){
	// close all popups first - so two cant be open at the same time
	var all = a.parentNode.parentNode.getElementsByTagName("div");
	for (var i=0; i<all.length; i++){
		if (all[i].className.indexOf(" open") > 0){
			all[i].className = all[i].className.substring(0, all[i].className.indexOf(" open"));
		}
	}
	
	var siblingDivs = a.parentNode.getElementsByTagName("div");
	for (var i=0; i<siblingDivs.length; i++){
		if (siblingDivs[i].className == "popup"){
			siblingDivs[i].className = siblingDivs[i].className + " open";
		}
	}
	//arcade iframe hazzard
	if (document.getElementById("game")) document.getElementById("game").className = document.getElementById("game").className + " hide";
}

function popupClose(a){
	var popup = a.parentNode.parentNode;
	var popupClass = popup.className;
	popup.className = popupClass.substring(0, popupClass.indexOf(" open"));
	//arcade iframe hazzard
	if (document.getElementById("game")) document.getElementById("game").className = document.getElementById("game").className.substring(0, document.getElementById("game").className.indexOf('hide'));
}

// for sidebar nav
function toggleSn(snid){
	if(document.getElementById(snid).className == 'active'){
		document.getElementById(snid).className = '';
	} else{
		document.getElementById(snid).className = 'active';
	}
}





// default search text

// event handler
function addEventToObject(obj,evt,func) {
	var oldhandler = obj[evt];
	obj[evt] = (typeof obj[evt] != 'function') ? func : function(){oldhandler();func();};
}

// lyrics box stuff
var Searchbox = {
	init : function()
		{
		var sBox = document.getElementById('search-lyrics');
		if (sBox)
			{
			addEventToObject(sBox,'onclick',Searchbox.click);
			addEventToObject(sBox,'onblur',Searchbox.blur);
			}	
		},
	click : function()
		{
		var sBox = document.getElementById('search-lyrics');
		if (sBox.value == 'Enter lyric, artist name or song title')
			{
			sBox.value = '';
			sBox.style.color = 'black';
			}
	  	},
	blur : function()
		{
		var sBox = document.getElementById('search-lyrics');
		if (sBox.value == '' || sBox.value == ' ') {sBox.value = 'Enter lyric, artist name or song title'; sBox.style.color = '#999999';}
		}
	};

// search box stuff
var Searchbar = {
	init : function()
		{
		var sBar = document.getElementById('searchmtv-text');
		if (sBar)
			{
			addEventToObject(sBar,'onclick',Searchbar.click);
			addEventToObject(sBar,'onblur',Searchbar.blur);
			}	
		},
	click : function()
		{
		var sBar = document.getElementById('searchmtv-text');
		if (sBar.value == 'Search')
			{
			sBar.value = '';
			}
	  	},
	blur : function()
		{
		var sBar = document.getElementById('searchmtv-text');
		if (sBar.value == '' || sBar.value == ' ') {sBar.value = 'Search';}
		}
	};

// add event onload
addEventToObject(window,'onload',Searchbox.init);
addEventToObject(window,'onload',Searchbar.init);
