function SetCookie(cookieName,cookieValue,nDays) {
	var today = new Date();
	var expire = new Date();
	if (nDays==null || nDays==0) nDays=1;
	expire.setTime(today.getTime() + 3600000*24*nDays);
	document.cookie = cookieName+"="+encodeURIComponent(cookieValue)+";expires="+expire.toGMTString();
}


var Snapshots = new Class({

	initialize: function(player, totalPages) {
		this.currentPage = 0;
		this.player = player;
		this.totalPages = totalPages;
		
		this.scroll = new Tools.PageScroll('scrollWrapper', {
			wheelStops: false,
			duration: 1000,
			transition: Fx.Transitions.Expo.easeInOut
		});
		
		$('pageLink0').addClass('pagination-current');
		if (this.totalPages > 1) {
			$('pageLinkNext').addClass('pagination-link');
		}
		
		for (var i = 0; i < this.totalPages; i++) {
			$('pageLink'+i).onclick = this.toPage.bind(this, i);
		}
		
		$('pageLinkNext').onclick = this.next.bind(this);
		$('pageLinkPrevious').onclick = this.prev.bind(this);
		snapPrivacy();
	},
	
	toPage: function(page) {
		var url = '/profile/snapshotspage.do?player=' + this.player + '&page=' + page;
		this.scroll.toPage(page, {ajaxUrl: url, evalScripts: true, onComplete: this.onComplete.bind(this, page)});
	},
	
	onComplete: function(page) {
		var ctxlabel = "cs"+this.currentPage;
		var ctx = eval(ctxlabel);
		this.pauseAllAvatars(ctx);
		var ctxlabel = "cs"+page;
		var ctx = eval(ctxlabel);
		this.resumeAllAvatars(ctx);
		$('pageLink'+this.currentPage).removeClass('pagination-current');
		$('pageLink'+page).addClass('pagination-current');
		if (page == this.totalPages - 1) {
			$('pageLinkNext').removeClass('pagination-link');
		} else {
			$('pageLinkNext').addClass('pagination-link');
		}
		if (page == 0) {
			$('pageLinkPrevious').removeClass('pagination-link');
		} else {
			$('pageLinkPrevious').addClass('pagination-link');
		}
		this.currentPage = page;
		snapPrivacy();
	},
	
	prev: function(){
		if (this.currentPage > 0) {
			this.toPage(this.currentPage - 1);
		}
	},
	
	next: function(){
		if (this.currentPage < this.totalPages - 1) {
			this.toPage(this.currentPage + 1);
		}
	},
	
	pauseAllAvatars: function(context) {
		if (context != null) {
			var cl = context.length;
			for (var i = 0; i < cl; i++) {
				var ava = context[i];
				ava.wasPaused = ava.paused;
				ava.paused = 1;
			}
		}
	},
	
	resumeAllAvatars: function(context) {
		if (context!= null) {
			var cl = context.length;
			for (var i = 0; i < cl; i++) {
				var ava = context[i];
				if ($defined(ava.wasPaused)) {
					ava.paused = ava.wasPaused;
				}
			}
		}
	}

});

var snapPrivacy = function(){
	var checkboxes = $$('.snpashotChkbox');
	var url = '/profile/snapshotspage/privacy.do?snapshot='
	checkboxes.each(function(element){
		element.addEvent('click', function(){
			element.disabled = true;
			var privacy = '&privacy=' + element.checked;
			var newurl = url + element.id + privacy;
			var approveThis = new XHR({
				method: 'post',
				onSuccess: function(){
					//alert($('privacyUpdateSuccess').innerHTML);
					element.disabled = false;
				},
				onFailure: function()
				{
					 //alert($('privacyUpdateError').innerHTML);
					element.disabled = false;
					if (element.checked)
					{
						element.checked = false;
					}
					else
					{
						element.checked = true;
					}
				}
			}).send(newurl);
		});
	});
}

var AvatarController = new Class({
	/** resumes the avatar **/
	resumeAvatar: function(avatar) {
		if (typeof avatar != 'undefined' && avatar != null) {
			if (typeof avatar.wasPaused != 'undefined') {
				avatar.paused = avatar.wasPaused;
			} else {
				avatar.paused = 0;
			}
			avatar.wasPausedCounter = 0;
		}
	},

	/** pauses the avatar **/
	pauseAvatar: function(avatar) {
		if (typeof avatar != 'undefined' && avatar != null) {
			if (typeof avatar.wasPausedCounter == 'undefined' || avatar.wasPausedCounter == 0) {
				avatar.wasPaused = avatar.paused;
				avatar.wasPausedCounter += 1;
			}
			avatar.paused = 1;
		}
	}
});

var InlineEditor = new Class({

	initialize: function(editbutton, content, form, field) {
		this.editbutton = $(editbutton);
		this.editButtonId = editbutton;
		this.content = $(content);
		this.form = $(form);
		this.field = $(field);
		if (this.editbutton != null && this.form != null && this.field != null && this.content != null) {
			this.editbutton.style.cursor = "pointer";
			this.editbutton.style.color = "#000099";
			this.editbutton.style.fontSize = "12px";
			this.editbutton.style.fontWeight = "bold";
			this.editbutton.addEvent('click', function(event) {
				new Event(event).stop();
				this.showForm();
			}.bind(this));
			this.editbutton.addEvent('mouseenter', function(event) {
				new Event(event).stop();
				this.editbutton.style.textDecoration="underline";
			}.bind(this));
			this.editbutton.addEvent('mouseleave', function(event) {
				new Event(event).stop();
				this.editbutton.style.textDecoration="none";
			}.bind(this));
			this.oldValue = this.field.defaultValue;
			var changeField = function(event) {
				new Event(event).stop();
				if (this.field.value != this.oldValue) {
					var url = this.form.action;
					var queryString = "newInfo=" + encodeURIComponent(this.field.value);
					new Ajax(url, {
						method: 'post',
						evalScripts: true,
						update: this.content,
						data: queryString,
						onComplete: this.hideForm.bind(this),
						onFailure: this.hideForm.bind(this)
					}).request();
					this.oldValue = this.field.value;
				} else {
					this.hideForm();
				}
			}.bind(this);
			this.field.addEvent('blur', changeField);
			this.form.addEvent('submit', function(event) {
				new Event(event).stop();
				this.field.blur();
			}.bind(this));
		}
	},
	
	hideForm: function() {
		this.form.addClass("miniQuote-hidden");
		this.editbutton.removeClass("miniQuote-hidden");
		this.content.removeClass("miniQuote-hidden");
		this.editbutton.style.textDecoration="none";
	},
	
	showForm: function () {
		this.field.value = this.oldValue;
		this.editbutton.addClass("miniQuote-hidden");
		this.content.addClass("miniQuote-hidden");
		this.form.removeClass("miniQuote-hidden");
		this.field.focus();
		//$('talkBubbleInput').select();
	}

});

/** 
A slider that does not change width. when 'hidden' it will look blank.
Also has two additional modes reverseHorizontal and reverseVertical. In these modesDifferent from Fx.Slide 
**/
Fx.ReverseSlide = Fx.Slide.extend({

	initialize: function(el, options){
		this.sign = 1;
		if(options['mode']!=null){
			if(options['mode']=='reverseHorizontal'){
				options['mode']='horizontal';
				this.sign = -1;
			}
			if(options['mode']=='reverseVertical'){
				options['mode']='vertical';
				this.sign = -1;
			}
		}
		this.parent(el, options);
		if(this.options['mode']=='vertical'){
			this.margin = 'margin-top';
			this.reverseMargin = 'margin-bottom';
			this.elementSize = this.element.getSize().size.y;
		}
		else{
			this.margin = 'margin-left';
			this.reverseMargin = 'margin-right';
			this.elementSize = this.element.getSize().size.x;
		}
	},
	
	
	slideOut: function(mode){
		return this.start([0,0], [this.sign*this.elementSize, 0]);
	},
	slideIn: function(mode){
		return this.start([this.sign*this.elementSize, 0], [0,0]);
	},
	hide: function(mode){
		this[mode || this.options.mode]();
		this.open = false;
		return this.set([this.sign*this.elementSize, 0]);
	},
	
	
	toggle: function(mode){
		if(this.element.getStyle("margin-right").toInt()==0){
			return this.slideOut(mode);
		}
		return this.slideIn(mode); 
	},
	
	
	increase: function(){
		try{
			this.element.setStyle(this.margin,        -this.now[0]);
			this.element.setStyle(this.reverseMargin,  this.now[0]);
		}
		catch(err){//some times the animation will start before the elements are fully defined. Just ignore these errors
			//alert("desc:"+err.description + "\nthis.element:"+this.element);
		}
	}

});

var ErrorHandler = new Class({
	initialize: function(errorPageHtml) {
		this.errorPage = errorPageHtml;
	},
	
	showError: function(element) {
		if ($type(element) == 'string') {
			element = $(element);
		}
		
		if ($type(element) == 'element') {
			element.innerHTML = this.errorPage;
		}
	}
	
});

var RatingsTab = new Class({
	initialize: function (confirm, stats, currentUrl)
	{
		this.confirmTab = confirm;
		this.statsTab = stats;
		this.ratingsUrl = currentUrl;
	},

	show_confirm_div: function ()
	{
		$(this.confirmTab).style.display = "inline";
		$(this.statsTab).style.display = "none";
	},
	
	show_stats_div: function ()
	{
		$(this.statsTab).style.display = "inline";
		$(this.confirmTab).style.display = "none";
	},
	
	clear_stats_cancelled: function (){
		this.show_stats_div();
	},
	
	clear_stats_confirmed: function (){
		var options = {
						method: 'get',
						onSuccess: function(){},
						onFailure: function(){},
						update: "ratings"
					  };
					
		var ajaxRequest = new Ajax(this.ratingsUrl + "&clearStats=true", options);
		ajaxRequest.request();
	}
	
	
});

/** functions for badges **/
var BadgesTab = new Class({
	initialize: function (pageURL, favURL, currentPage, loadMainTabOnFavUpdate) {
		if(!$defined(loadMainTabOnFavUpdate) ){
			loadMainTabOnFavUpdate = true;
		}
		this.loadMainTabOnFavUpdate = loadMainTabOnFavUpdate;
		this.errorHandler = new ErrorHandler($('errorMessage').innerHTML);
		this.isLoading = false;
		this.pageURL = pageURL;
		this.favURL = favURL;
		this.curPage = currentPage;
		this.toPage = currentPage;
		var hash = window.location.hash;
		if(hash!=''){
			var savedPageNum = hash.substring(1);
			if(savedPageNum!=this.curPage){
				this.curPage = this.savedPageNum;
				this.goToPage(savedPageNum, null);
				return;
			}
		}
		if($defined( $('badgeTableBody') ))
			$('badgeTableBody').style.visibility = 'visible';
	},
	
	//error handler
	pageLoadFail: function (){
		if($defined( $('badgeTableBody') ))
			this.errorHandler.showError('badgeTableBody');
		this.updatePageState(this.curPage);
	},
	 
	pageLoadFromLeft: function (){
		if($defined( $('badgeTableBody') )){
			slide = new Fx.ReverseSlide('badgeTableBody', {mode: 'horizontal'});
			slide.hide();
			slide.slideIn();
			this.updatePageState(this.toPage);
		}
	},
	
	pageLoadFromRight: function (){
		if($defined( $('badgeTableBody') )){
			slide = new Fx.ReverseSlide('badgeTableBody', {mode: 'reverseHorizontal'});
			slide.hide();
			slide.slideIn();
		}
		this.updatePageState(this.toPage);
	},
	
	
	pageLoad: function(){
		this.updatePageState(this.toPage);
	},
	
	updateMiniIcon: function(){
		//update the mini icon on the top
		if( $defined( $('topMiniIcon') ) && $defined( $('favMiniIcon') ) ){
			$('topMiniIcon').src = $('favMiniIcon').src;
		}
	},
	
	
	updatePageState: function(page){
		if($defined( $('badgeTableBody') ))
			$('badgeTableBody').style.visibility = 'visible';
		clearTimeout(this.timeout);
		//save the page change to the fragment identifier to update url without refreshing the page
		window.location.hash = page;
		this.curPage = page;
		//set this object to accept new page requests
		this.isLoading = false;
	},
	
	setToLoading: function(elementName){
		if( !$defined( $("loadingImageDiv") ) || !$defined( $("loadingText") ) || !$defined( $("errorMessage") ) ){
			return;
		}
		if( !$defined(elementName) ){
			alert("element:"+elementName+" does not exist!")
			return;
		}

		//make the text feild the same height to prevent height jumping
		$('loadingText') .style.height = $(elementName).getSize().size.y+"px";
		$('errorMessage').style.height = $(elementName).getSize().size.y+"px";

		//put the loading bar on the page after a delay (only visible if on a slow connection)		
		$(elementName).style.visibility = 'hidden';
		$(elementName).innerHTML = $("loadingImageDiv").innerHTML;
		this.timeout = setTimeout ( "$('"+elementName+"').style.visibility = 'visible';", 2000 );
	},

	goToPage: function(page, newFavBadge, refreshParent){
		//prevent multiple clicks before load
		if(this.isLoading){
			return;
		}
		this.isLoading = true;
		
		//figure out how to load in the new div
		var loadingFunct;
		if(page<this.curPage)
			loadingFunct = function(){this.isLoading = false;this.pageLoadFromLeft();}.bind(this);
		else if(page>this.curPage)
			loadingFunct = function(){this.isLoading = false;this.pageLoadFromRight();}.bind(this);
		else
			loadingFunct = function(){this.isLoading = false;this.pageLoad();}.bind(this);
		this.toPage = page;
		
		//Set loading sections to display loading bar
		//var badgeFav = $("badgeFav");
		//var badgeTbl = $("theBadgesTable");
		var tmpRefreshParentParam = "";
		if ($defined(refreshParent) && refreshParent)
			tmpRefreshParentParam = "&refreshParent=true";

		//load the parts that need to be refreshed
		if(newFavBadge!=null){
			//move user to top of page so they can see favorite badge
			//only needed for popup as in full profile favorite badge remains in the list
			window.scrollTo(0,0);
			if(this.loadMainTabOnFavUpdate){
				this.setToLoading("badgeFav");
				this.loadToElement(this.favURL +"&setFav="+newFavBadge, $("badgeFav"), this.updateMiniIcon, this.pageLoadFail.bind(this));
				this.setToLoading("badgeTableBody");			
				this.loadToElement(this.pageURL+"&setFav="+newFavBadge+"&page="+this.toPage+tmpRefreshParentParam, $("theBadgesTable"), loadingFunct, this.pageLoadFail.bind(this));
				
			}
			else{
				this.setToLoading("badgeFav");
				this.loadToElement(this.favURL +"&setFav="+newFavBadge, $("badgeFav"), 
					function(){this.isLoading = false; this.updateMiniIcon();}.bind(this), this.pageLoadFail.bind(this));
			}
		} 
		else{
			this.setToLoading("badgeTableBody");
			this.loadToElement(this.pageURL+"&page="+this.toPage+tmpRefreshParentParam, $("theBadgesTable"), loadingFunct, this.pageLoadFail.bind(this));
		}
		
	},
	
	fadeElement: function(timeout, elStr){
		clearTimeout(timeout);
		$(elStr).style.visibility = 'visible';
		timeout = setTimeout ( "$('"+elStr+"').style.visibility='hidden'", 1000 );
	},
	
	showShortError: function(timeout, elStr){
		clearTimeout(timeout);
		$(elStr).innerHTML = $('iconOptionsErrorMsg').innerHTML;
		$(elStr).style.visibility = 'visible';
		timeout = setTimeout ( "$('"+elStr+"').style.visibility='hidden'", 1000 );
	},
	
	setShowAvatar: function(showAvatar){
		this.elStr = 'showVerification';
		this.loadToElement('/account/profile/popup/iconsettings.do?showAvatar='+showAvatar,
						$('showVerification'),
						function(){
							this.fadeElement(this.showAvatarTimer,'showVerification');
						}.bind(this),
						function(){
							this.showShortError(this.showAvatarTimer,'showVerification');
						}.bind(this));
	},
	
	setHideIcon: function(hide){
		this.elStr = 'hideVerification';
		this.loadToElement('/account/profile/popup/iconsettings.do?hideiconsinfree='+hide,
						$('hideVerification'),
						function(){
							this.fadeElement(this.hideIconTimer,'hideVerification');
						}.bind(this),
						function(){
							this.showShortError(this.hideIconTimer,'hideVerification');
						}.bind(this));
	},
	
	loadToElement: function (url, element, onSuccess, onFail){
		var options = {
						method: 'get',
						onSuccess: onSuccess,
						onFailure: onFail,
						update: element
					  };
		var ajaxRequest = new Ajax(url, options);
		ajaxRequest.request();
	}
});//end BadgesTab

var Guestbook = new Class({

	initialize: function(player, totalPages) {
		this.currentPage = 0;
		this.player = player;
		this.totalPages = totalPages;

		this.scroll = new Tools.PageScroll('scrollWrapper', {
			wheelStops: false,
			duration: 1000,
			mode: 'vertical',
			transition: Fx.Transitions.Expo.easeInOut
		});

		$('pageLink0').addClass('pagination-current');
		if (this.totalPages > 1) {
			$('pageLinkNext').addClass('pagination-link');
		}

		for (var i = 0; i < this.totalPages; i++) {
			$('pageLink'+i).onclick = this.toPage.bind(this, i);
		}

		$('pageLinkNext').onclick = this.next.bind(this);
		$('pageLinkPrevious').onclick = this.prev.bind(this);
	},

	toPage: function(page) {
		var url = '/profile/guestbookviewpage.do?player=' + this.player + '&page=' + page;
		this.scroll.toPage(page, {ajaxUrl: url, evalScripts: true, onComplete: this.onComplete.bind(this, page)});
	},
	
	addElementToCurrentPage: function(element)
	{
		this.scroll.addToCurrentDiv(element);    
	},


	onComplete: function(page) {
		//var ctxlabel = "cs"+this.currentPage;
		//var ctx = eval(ctxlabel);
		//this.pauseAllAvatars(ctx);
		//var ctxlabel = "cs"+page;
		//var ctx = eval(ctxlabel);
		//this.resumeAllAvatars(ctx);
		$('pageLink'+this.currentPage).removeClass('pagination-current');
		$('pageLink'+page).addClass('pagination-current');
		if (page == this.totalPages - 1) {
			$('pageLinkNext').removeClass('pagination-link');
		} else {
			$('pageLinkNext').addClass('pagination-link');
		}
		if (page == 0) {
			$('pageLinkPrevious').removeClass('pagination-link');
		} else {
			$('pageLinkPrevious').addClass('pagination-link');
		}
		this.currentPage = page;
		
		
		
		
	},

	prev: function(){
		if (this.currentPage > 0) {
			this.toPage(this.currentPage - 1);
		}
		//alert(this.currentPage)
		// TODO: first page onload is not page 0
	},

	next: function(){
		if (this.currentPage < this.totalPages - 1) {
			this.toPage(this.currentPage + 1);
		}
	},

	pauseAllAvatars: function(context) {
		if (context != null) {
			var cl = context.length;
			for (var i = 0; i < cl; i++) {
				var ava = context[i];
				ava.wasPaused = ava.paused;
				ava.paused = 1;
			}
		}
	},

	resumeAllAvatars: function(context) {
		if (context!= null) {
			var cl = context.length;
			for (var i = 0; i < cl; i++) {
				var ava = context[i];
				if ($defined(ava.wasPaused)) {
					ava.paused = ava.wasPaused;
				}
			}
		}
	}

});

var GuestbookPost = new Class({

	initialize: function(button, url, message, guestbook, postData, context) {
		//console.log(button + ' --- ' + url + ' --- ' + message + ' --- ' + container + ' --- ' + guestbook + ' --- ' + postData)
		this.button = $(button);
		this.message = $(message);
		this.guestbook = guestbook;
		this.blankDiv = new Element('div');
		this.context = context;

		var tempButton = this.button;
		this.button.addEvent('click', function(e) { 
			tempButton.disabled = true;
			var queryString = postData + "&message=" + encodeURIComponent(this.message.value);
			var postRequest = new Ajax(url, {
				method: 'post',
				evalScripts: true,
				update: $('tempMessage'),
				data: queryString,
				onComplete: this.onComplete.bind(this),

				onFailure: {}
			});
			postRequest.request();
			
		}.bind(this));
	},

	onComplete: function() {
		
		var blankDiv = $('tempMessage');
		var blankDivChildren = blankDiv.getChildren();
		var element = blankDiv.getElement('div');
		var newMessageDiv = $defined($(element));
		
		$('charsLeftNum').setHTML(500)
		
		var newAlert = new Element('div', {'class': 'commentAlert', 'id': 'newAlert'});
		newAlert.innerHTML = element.innerHTML;
		
		if($('newMessage') != null){
			var bgImg = 'url(/img/profile/alertGreen.gif)';
		}
		else{
			var bgImg = 'url(/img/profile/alertYellow.gif)';
		}
						
		newAlert.setStyles({
			'position': 'absolute',
			'background-image': bgImg,
			'opacity': 0,
			'top': 14,
			'right': 14,
			'text-align': 'center',
			'color': '#000',
			'font-weight': 'bold'
		});
					
		newAlert.inject('writeComment');
		var newAlertFade = new Fx.Style(newAlert, 'opacity').start(0,.9);

		(function(){newAlertFade.start(0)}).delay(2000);
		(function(){newAlert.remove()}).delay(3000);
		$('msgField').value = '';
		$('msgField').fireEvent('blur');
		
		if(this.guestbook != null){
			this.guestbook.toPage(0);	
			(function(){
				selectFunction();
				setDeletes();
				setOptionLinks();
				approveSingles();
			}).delay(500);	
		}	

		if(typeof OmnitureCustomLink=='function')
			OmnitureCustomLink('guestbook_post_' + this.context);

		if($defined(element.getNext())){
			if($defined($('commentStretchDiv'))){
				$('newMessage').getChildren().injectTop($('commentStretchDiv'));
				reInitGuestbook();
			}
			else{
				$('newMessage').getChildren().injectTop($('messages'));
			}
			
			if($defined($('noCommentsDiv'))){
				$('noCommentsDiv').remove();
			}
		}
	}

});

var initprofilegifts = function(player, profileGiftsURL, isPopup) {
	var ajaxRequest = new Ajax(profileGiftsURL, {
		method: 'post',
		evalScripts: true,
		data: 'player='+ player + '&isPopup=' + isPopup,
		update: $('giftscontainer'),

		onSuccess: function(){
			loadGift(player, 0, null, profileGiftsURL, isPopup);
			if($('giftscontainer') != null && $('giftscontainer').getStyle('display') != null){
				$('giftscontainer').setStyle('display', 'inline');
				$('giftsloading').setStyle('display', 'none');
			}
		},
		onFailure: function() {
			alert("error occurred");
		}
		}).request() ;
}

var pauseSlideShow = function(player, page,  profileGiftsURL, isPopup) {
	currentSlideShowState = 'PAUSE';
	loadGift(player, page, 'PAUSE', profileGiftsURL, isPopup);
}

var playSlideShow = function(player, page,  profileGiftsURL, isPopup) {
	currentSlideShowState = 'PLAY';
	loadGift(player, page, 'PLAY',  profileGiftsURL, isPopup);
}

var addFlashVar = function(so, name, value) {
	if(value)
		so.addVariable(name, value);
}

var loadGift = function(player, page, newslideshowstate, profileGiftsURL, isPopup) {
	currentSlideShowState = 'PAUSE';
	var queryStr = 'player='+ player+'&page=' + page;
	queryStr = queryStr + '&isPopup=' + isPopup;
	if (newslideshowstate != null)
	{
		queryStr = queryStr + '&slideshowstate=' + newslideshowstate;
	}
	var ajaxRequest = new Ajax(profileGiftsURL, {
		method: 'post',
		evalScripts: true,
		data: queryStr,
		update: $('giftscontainer'),

		onSuccess: function(){			
			var divs = $$('div#giftscontainer div.flashcontent');

			if(divs && divs.length==1){
				var div = divs[0];
				loadFlashMovie(div);
			}
			
			if($('giftscontainer') != null && $('giftscontainer').getStyle('display') != null){
				$('giftscontainer').setStyle('display', 'inline');
				$('giftsloading').setStyle('display', 'none');
			}
		},
		onFailure: function() {
			alert("error occurred");
		}
		}).request() ;
}

