




//to disable community, uncomment the following line, and flush the cache on this file
/*
SetCookieUtil("cCommunityAccess", "false");
*/

//to re-enable community, uncomment the following line and flush the cache on this file
/* */

var today = new Date();
var oneDay = new Date(today.getTime() + 24 * 60 *60 * 1000);
var oneWeek = new Date(today.getTime() + 24 * 60 *60 * 1000 * 7);
var oneYear = new Date(today.getTime() + 24 * 60 *60 * 1000 * 365);

//Mapping function to VH1 -------------------------------------------
function GetCookieUtil(name){
	return System.cookie.get(name);
}

function SetCookieUtil(name,value,expires){
	return System.cookie.set(name,value,expires);
}
//-------------------------------------------------------------------


if (GetCookieUtil("cCommunityAccess")=="false"){ SetCookieUtil("cCommunityAccess", ""); }

SetCookieUtil("cCommunityPhase", "2");  // enable phase 2

function injectFluxWidget(widgetName, options, version){
	var showWidget = "false";
	
	// use old comments2 for now until we're ready for threaded comments
	if (widgetName=="Comments3" && GetCookieUtil("cCommunityComments")=="true"){
		showWidget = "true"; 
		if (GetCookieUtil("cCommunityPhase")=="2"){
			options.displayUserName = true;
			options.itemsCount = 10;
			if (version=="charlie") options.customize = {markupUrl: '/sitewide/flux/widgets/comments2_fullep.js',scriptUrl:'/sitewide/flux/widgets/comments2_overrides.js'};
			else options.customize = {markupUrl: '/sitewide/flux/widgets/comments2.js',scriptUrl:'/sitewide/flux/widgets/comments2_overrides.js'};
//			options.customize = {markupUrl: '/sitewide/flux/widgets/comments2.js',scriptUrl:'/sitewide/flux/widgets/comments2_overrides.js'};
//			options.customize = {markupUrl: '/sitewide/community/widget/comments/comments2.html',scriptUrl:'/sitewide/flux/widgets/comments2_overrides.js'};
		}
	}
	
	version="";	
	
	if (widgetName=="Comments2" && GetCookieUtil("cCommunityComments")=="true"){ 	
		showWidget = "true"; 
		if (GetCookieUtil("cCommunityPhase")=="2"){
			options.displayUserName = true;
			switch(version){
				case 'charlie': options.customize = {markupUrl: '/sitewide/community/widgets/comments/charlie.html', scriptUrl:'/sitewide/community/widgets/comments/charlie.js'}; break;
				default: options.customize = {markupUrl: '/sitewide/flux/widgets/comments2.js'}; 
			}
		}
	}
	if (widgetName=="Rating" && GetCookieUtil("cCommunityRating")=="true"){
		System.out.println('Rating Widget');
		showWidget = "true";
		switch(version){
			case 'charlie': options.customize = {markupUrl: '/sitewide/community/widgets/rating/charlie.html', scriptUrl:'/sitewide/community/widgets/rating/charlie.js'}; break;
			default: ; 				
		}
	 }
	if (widgetName=="Usage" && GetCookieUtil("cCommunityUsage")=="true"){ showWidget = "true"; }
	if (widgetName=="QuickMenu" && GetCookieUtil("cCommunityPhase")=="2"){ 
		showWidget = "true"; 
		widgetName = "QuickMenu2";
		options.customize = {markupUrl: '/sitewide/community/widgets/CustomQuickMenu2.js'};
	}
	if (widgetName=="ContentAction" && GetCookieUtil("cCommunityPhase")=="2"){ 
		showWidget = "true";
		switch(version){
			case 'charlie': 
				widgetName = "ContentAction2";
				options.accessKey = "a0d6e609-b22c-4272-b2a6-a3192f648fed";
				options.showAddToMyProfileButton = true;
				options.customize = {markupUrl: '/sitewide/community/widgets/addToProfile/charlie.html', scriptUrl: '/sitewide/community/widgets/addToProfile/charlie.js'};	
			default: ;
		}		
	}
	
	if (showWidget=="true" && GetCookieUtil("cCommunityAccess")=="true"){
		if (Flux && Flux.Utils.WidgetsLoader) {
			if (widgetName=="Comments3") widgetName="Comments2";
			Flux.Utils.WidgetsLoader.createWidget(widgetName, options);
		}
	}
}

function fluxWidgetError(errorCode){
	if(typeof MTV!='undefined' && MTV.version=='charlie'){ 
		alert(errorCode + " " + MTV.Community.Widgets.errorLocation);
		
		var locationElement = document.getElementById(MTV.Community.Widgets.errorLocation);
		
		MTV.UI.ModalWindow.open('modalWindow');
		var modalWindow = document.getElementById("modalWindow");
		//modalWindow.style.position = 'absolute';
		
		var locLeft = MTV.Utils.findPosX(locationElement);
		var locTop = MTV.Utils.findPosY(locationElement);
		
		var newLeft = 0; 
		var newTop = 0;
		
		if(locLeft > 506){ newLeft = 506; }
		else{ newLeft = locLeft; }
		
		newTop = locTop - (modalWindow.offsetHeight + 5);
				
		modalWindow.style.left = newLeft + "px";
		modalWindow.style.top = locTop + "px";
		
		community.link(errorCode, MTV.version);
		
	}
	else community.open(errorCode);
}


function Community() {
	var fluxAuthTokenCookieName = 'RtxAuth2407';
	var communityHostname = 'http://community.vh1.com';	
	var onFinish = "";
	
	/* dialogue open and close */
	this.open = function(page){
	
		System.out.println('open('+page+')');
		if((page=="login" || page=="register") && GetCookieUtil("cCommunityAccess")!="true"){
			switch(page){
				case 'login': window.open('/sitewide/community/login/', 'loginPopUp', 'width=448,height=309,'); break;
				case 'register': window.open('/community/account/join.jhtml?serv=&amp;mtvparams=&amp;target=&amp;mesg=', 'loginPopUp', 'width=448,height=309,'); break;
				default: break;
			}
		}
		else{
			if (GetCookieUtil("cCommunityPhase")>=2 && (page=="register" || page=="login" || page=="join")){ 
				this.hostedPageLink(page);
			}
			else{
				overlayOpen();
				window.scrollTo(0,0);
				//this.link(page);
			}
		}
	}
	
	this.close = function(){
		overlayClose();
		this.link('clear');
	}
	
	this.finish = function(){
		this.close();		
		if (this.onFinish != undefined){
			switch(this.onFinish){
				case 'reload': window.location.reload(); break;
				default: window.location.href = this.onFinish; break;
			}
		}
	}
	
	/* links */
	this.hostedPageLink = function(page, id){
		var hostedPage = "/";
		switch(page){
			case 'discussion': hostedPage = '/-/Content/Discussions/DiscussionBoard.aspx?catId=' + id; break;
			case 'join': hostedPage = '/-/JoinInterim.aspx?returnPath=' + window.location.href; break;
			case 'login': hostedPage = '/-/SignUp.aspx?returnPath=' + window.location.href; break;
			case 'register': hostedPage = '/-/SignUp.aspx?returnPath=' + window.location.href; break;
			default: ;
		}		
		window.location.href=communityHostname + hostedPage;
	}
	
	this.link = function(page, version){
		if (GetCookieUtil("cCommunityPhase")>=2 && (page=="register" || page=="login" || page=="join")){ 
			this.hostedPageLink(page);
		}
		else{
			/* temporary iframe fix */
			this.hide(document.getElementById('communityUpload'));
		
			switch(page){
				case 'clear': submit('/sitewide/community/forms/clear.jhtml'); break;
				case 'join': submit('/sitewide/community/forms/join.jhtml'); break;
				case 'login': submit('/sitewide/community/forms/login.jhtml'); break;
				case 'loginFromReg': submit('/sitewide/community/forms/login.jhtml?event=loginFromRegLink'); break;
				case 'notJoined': submit('/sitewide/community/forms/error.jhtml?errorCode=' + page + '&phase=' + GetCookieUtil("cCommunityPhase") + '&version=' + version); break;
				case 'notLoggedIn': submit('/sitewide/community/forms/error.jhtml?errorCode=' + page + '&phase=' + GetCookieUtil("cCommunityPhase") + '&version=' + version); break;
				case 'notVerified':	submit('/sitewide/community/forms/error.jhtml?errorCode=' + page + '&phase=' + GetCookieUtil("cCommunityPhase") + '&version=' + version); break;
				case 'passwordReminder': submit('/sitewide/community/forms/passwordReminder.jhtml'); break;
				case 'problems': submit('/sitewide/community/forms/problems.jhtml'); break;
				case 'register': submit('/sitewide/community/forms/register.jhtml'); break;
				case 'sendValidation': submit('/sitewide/community/forms/sendValidation.jhtml'); break;
				case 'updateAccount': submit('/sitewide/community/forms/updateAccount.jhtml'); break;
				case 'updatePassword': submit('/sitewide/community/forms/updatePassword.jhtml'); break;
				case 'uploadPhoto': submit('/sitewide/community/forms/uploadPhoto.jhtml'); break;
				case 'uploadSuccess': submit('/sitewide/community/forms/updateAccount.jhtml?action=uploadSuccess'); break;
				case 'uploadSkip': submit('/sitewide/community/forms/welcome.jhtml?action=register&event=uploadSkip'); break;
				case 'quit': submit('/sitewide/community/forms/quit.jhtml'); break;
				case 'welcomeRegister': submit('/sitewide/community/forms/welcome.jhtml?action=register'); break;
				default: submit(page); 
			}
		}
	}
	
	
	/* form handlers */
	this.handle = function(form, elements){
		switch(form){
			case 'deactivate': submit('/sitewide/community/forms/do_deactivate.jhtml'); break;
			case 'join': submit('/sitewide/community/forms/do_join.jhtml', ['firstName', 'lastName', 'username', 'agreeToTerms']); break;
			case 'login': submit('/sitewide/community/forms/do_login.jhtml', ['loginName', 'password']); break;
			case 'logout': submit('/sitewide/community/forms/logout.jhtml'); break;
			case 'passwordReminder': submit('/sitewide/community/forms/do_passwordReminder.jhtml', ['email']); break;
			case 'register': submit('/sitewide/community/forms/do_register.jhtml', ['email', 'emailConfirm', 'password', 'passwordConfirm', 'loginName', 'firstName', 'lastName', 'birthDateMonth', 'birthDateDay', 'birthDateYear', 'postalCode', 'agreeToTerms']); break;
			case 'updateAccount': submit('/sitewide/community/forms/do_updateAccount.jhtml', elements); break;			
			case 'updatePassword': submit('/sitewide/community/forms/do_updatePassword.jhtml', ['currentPassword', 'newPassword', 'newPasswordConfirm']); break;
			case 'unjoin': submit('/sitewide/community/forms/do_unjoin.jhtml'); break;
			case 'sendValidation': submit('/sitewide/community/forms/do_sendValidation.jhtml', ['email']); break;
			default: ;
		}
	}
	
	this.updateWidgets = function(){
		submit('/sitewide/community/forms/updateWidgets.jhtml');
	}
	
	this.logout = function(){
		submit('/sitewide/community/includes/logout.jhtml');
	}
	
	this.pop = function(url, type){
		var features;
		if (type=='legal') features = "width=620,height=600,scrollbars";
		if (url=='faq'){
			url = "/sitewide/mtvinfo/social_project_faq.jhtml";
			features = "width=620,height=600,scrollbars";
		}
		if (url=='betaInvite'){
			url = "/community/invite/index.jhtml";
			features = "width=344,height=320,menubar=no,status=yes,scrollbars=no";
		}
		window.open(url, '', features);
	}
	
	/* utils */
	this.getQuickmenu = function(){
		if(GetCookieUtil("cCommunityPhase")=="2"){
			this.show(document.getElementById("quickmenu"));
		}
		else{ 
			if(GetCookieUtil("cCommunityAccess")=="true") this.loadMamabar();
			this.show(document.getElementById("mamabar"));
		}
	}
	
	this.loadMamabar = function(){
		submit('/sitewide/community/includes/mamabar.jhtml', [], false);
	}
	
	this.checkUsername = function(username){
		submit('/sitewide/community/forms/checkUsername.jhtml?loginName=' + username);
	}
	
	this.setBetaCookies = function(){
		SetCookieUtil('cCommunityAccess', 'true', oneYear);
		SetCookieUtil('cCommunityComments', 'true', oneYear);
		SetCookieUtil('cCommunityRating', 'true', oneYear);
		SetCookieUtil('cCommunityUsage', 'true', oneYear);
	}
	
	this.clearAuthCookie = function(){
		if (GetCookieUtil(fluxAuthTokenCookieName)!=null){
			var hostname = document.location.hostname;
			hostname = hostname.substring(hostname.indexOf('www.')+4, hostname.length);
			SetCookieUtil(fluxAuthTokenCookieName, '', '', '/', hostname);
		}
	}
	
	this.toggleFormFields = function(inputId, action){
		var input = document.getElementById(inputId);
		var open = document.getElementById(inputId + "Open");
		var closed = document.getElementById(inputId + "Closed");
		var parentForm = input.form;
				
		if (action == 'show'){
			/* toggle */
			show(open);
			hide(closed);
			
			/* show related fields */
			var x = parentForm.getElementsByTagName('tr');
			for (var i=0;i<x.length;i++){
				var tr = x[i];
				if (x[i].getAttribute('rel') == inputId){
					x[i].className = x[i].className.substring(0, x[i].className.indexOf('hide'));
				}
			}
		}
		if (action == 'hide'){
			/* toggle */
			show(closed);
			hide(open);
						
			/* hide related fields */
			var x = parentForm.getElementsByTagName('tr');
			for (var i=0;i<x.length;i++){
				if (x[i].getAttribute('rel') == inputId){
					x[i].className = x[i].className + " hide";
				}
			}
		}
	}
	
	this.show = function(element){
		show(element);
	}
	
	this.hide = function(element){
		hide(element);
	}
	
	function show(element){
		if (element!=null && element.className.indexOf('hide') >= 0){
			element.className = element.className.substring(0, element.className.indexOf('hide'));
		}
	}
	
	function hide(element){
		if (element!=null){
			element.className = element.className + " hide";
		}
	}
	
	function loadingOn(){
		var element = document.getElementById('communityLoading');
		if (element!=null && element.className.indexOf('hide') >= 0){
			element.className = element.className.substring(0, element.className.indexOf('hide'));
		}
	}
	
	function loadingOff(){
		var element = document.getElementById('communityLoading');
		if (element!=null){
			element.className = element.className + " hide";
		}
	}
	
	function submit(url, formElements, async){
		//System.out.println('url='+url);
		//System.out.println('formElements='+formElements);
		//System.out.println('async='+async);
		try{
	
		var ar = new AjaxRequest(url);
		
		}
		catch(e){
			// not logged in
			//alert('Please login to use this feature.');
			return;
		
		}
		if (formElements != undefined){
			for (var i=0; i < formElements.length; i++){
				ar.addNamedFormElements(formElements[i]); 
			}
		}
		
		if (async!=null){ ar.setAsync(async); }
		
		ar.setPreRequest(loadingOn);
		ar.sendRequest();
		ar.setPostRequest(loadingOff);
	}
	
	function overlayOpen(){
		
		//System.out.println('overlayOpen()');
		//if (document.getElementById("embeddedPlayer")) document.getElementById("embeddedPlayer").pausePlayer();
		if (document.getElementById("game")) hide(document.getElementById("game"));
		
		//if (document.getElementById("overlay") && document.getElementById("dialogue")){
		if (document.getElementById("overlay") && document.getElementById("dialog")){
			var pagesize = getPageSizeWithScroll();
			Page.show('overlay','dialog');
			Page.e('overlay').style.height = pagesize[1] + "px";
			//Page.e('dialog').style.top = '200px';
			//document.getElementById("overlay").className = "open";
			//System.out.println(document.body.offsetHeight + "px");
			//document.getElementById("overlay").style.height = 500 + "px";
			//document.getElementById("dialogue").className= "open";
			//System.out.println('height='+document.getElementById("overlay").style.height);
		}		
	}
	
	function getPageSizeWithScroll(){     
		if (window.innerHeight && window.scrollMaxY) {// Firefox         
			yWithScroll = window.innerHeight + window.scrollMaxY;         
			xWithScroll = window.innerWidth + window.scrollMaxX;     
		} 
		else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac         
			yWithScroll = document.body.scrollHeight;         
			xWithScroll = document.body.scrollWidth;     
		} 
		else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari         
			yWithScroll = document.body.offsetHeight;         
			xWithScroll = document.body.offsetWidth;       
		}     
		arrayPageSizeWithScroll = new Array(xWithScroll,yWithScroll);     
		//alert( 'The height is ' + yWithScroll + ' and the width is ' + xWithScroll );     
		
		return arrayPageSizeWithScroll; 
	} 
	
	function overlayClose(){
		if (document.getElementById("overlay")){
			Page.hide('overlay','dialog');
			//document.getElementById("overlay").className = "";
			//document.getElementById("overlay").style.height = "0px";
		}
		//document.getElementById("dialogue").className= "hide";
		//if (document.getElementById("game")) show(document.getElementById("game"));
	}
	
	this.setReportingVars = function(){
		var vars = "";
		var numkeys = 1;
		var keyvals = new Array(2);
		var keynames = new Array(2);
		
		/* PHASE 1
		keynames[0] = "siteFormat";		//prop31 - logged in
		keynames[1] = "betaUsage";		// prop34 - beta user	
		keyvals[0] = (GetCookieUtil(fluxAuthTokenCookieName) != null) ? 'community' : 'non-community';
		keyvals[1] = (GetCookieUtil('cCommunityAccess')=='true') ? 'community' : '';
		*/
		
		/* PHASE 2 */
		keynames[0] = "siteFormat";		//prop31 - logged in
		keyvals[0] = "not-logged-in";
		
		if (typeof Flux!='undefined' ) keyvals[0] = (Flux.Context.isUserAuthenticated()==true) ? 'logged-in' : 'not-logged-in';
		
		for (var i=0; i<numkeys; i++){
			if (keyvals[i].length != 0){
				vars = vars + keynames[i] + "=" + keyvals[i] + ";";
			}
		}
		return vars;
	}
		
	this.report = function(page, event){
		var regEvent;
		var pageName = 'community/dialogue/' + page + '.jhtml'; 
		
		dispatcher.setAttribute('pageName', pageName);
		dispatcher.setAttribute('hier2', pageName);
		dispatcher.setAttribute('channel', 'community');
		dispatcher.setAttribute('prop31', 'community');
		dispatcher.setAttribute('prop34', 'community');
		
		switch(page){
			case 'register': 
				regEvent='event2';										// register open
				this.setCampaignAttribute();
				break;
			case 'uploadPhoto': regEvent='event3'; break;				// register success
			case 'welcomeRegister': 
				if(event=='uploadSkip'){ regEvent='event5'; }			// upload skip
				else{ regEvent='event4'; }								// upload success
				break;
			case 'login':
				if(event=='loginFromRegLink'){ regEvent='event6'; }		// login open from registration link
				if(event=='loginFromRegSubmit'){ regEvent='event7'; }	// login open from registration submit
				break;				
			case 'join': regEvent='event8'; break;						// login success
			case 'welcomeJoin': regEvent='event9'; break;				// join success
			default: ;
		}
		
		if (regEvent!=null){
			dispatcher.setAttribute('eVar1', 'registration');
			dispatcher.setAttribute('events', regEvent); 	
		}
		
		dispatcher.sendCall();
		
		// clear attributes
		dispatcher.setAttribute('pageName', '');
		dispatcher.setAttribute('hier2', '');
		dispatcher.setAttribute('channel', '');
		dispatcher.setAttribute('prop31', '');
		dispatcher.setAttribute('prop34', '');
		dispatcher.setAttribute('eVar1', '');
		dispatcher.setAttribute('events', '');
	}
	
	this.setBetaLandingAttributes = function(){
		dispatcher.setAttribute('events','event1');
	}
	
	this.setCampaignAttribute = function(){
		var cmp = com.mtvi.util.queryStringToHash(top.location.search);
		if (cmp.source != undefined){
			dispatcher.setAttribute('campaign',cmp.source);
		}
	}
	
}
var community = new Community();

/* set beta cookies for all users */
community.setBetaCookies();


function toggleGuestbook(){
	community.setBetaCookies();
	community.loadMamabar();
	community.hide(document.getElementById('guestbookLegacy'));
	community.show(document.getElementById('guestbook'));
}
