var logged_in = false;
var user_name = '';
var user_email = '';
var current_theme = 'default';

function LogIn () {
	showLoginForm ();
}

function showLoginForm () {
	showBackground();
	//$('checking_account').style.display = 'none';
	$('checking_account').src = '/images/logo_boxes.gif';//preloader_logo.gif';
	$('login_dialog').style.display = 'block';
	$('login_dialog').getElementsByTagName('INPUT')[0].focus();
}

function hideLoginForm () {
	hideBackground();
	$('login_dialog').style.display = 'none';
	$('search_input').focus();
}

function checkAccount () {
	var user = $('login_user').value;
	var pass = $('login_pass').value;
	if (user.length < 3) {
		alert ('This is not valid username!');
		return;
	}
	if (pass.length < 3) {
		alert ('This is not valid password!');
		return;
	}
	var ytd_message = "Attention!\n" +
		"You are trying to log in with the beta testing account ytd. This account has been used by all our beta testers\n" +
		"We highly recommend you to create your own separate account so nobody else changes your playlists and favorites";
	if (user == 'ytd')
		if (!confirm(ytd_message)) return;
	//$('checking_account').style.display = 'block';
	$('checking_account').src = '/images/preloader_boxes.gif';// 'images/logo_boxes.gif';// 'images/preloader_circle.gif';
	var d = new Date();
	var t = d.getTimezoneOffset() / 60;
	var params = $H({user: user, pass:pass, t: t});
	new Ajax.Request ('check_login.php', {
		method: 'post',
		onSuccess: checkAccount_handler,
		parameters: params.toQueryString()
	});
}

function checkAccount_handler (ajaxResponse) {
	//$('checking_account').style.display = 'none';
	$('checking_account').src = '/images/logo_boxes.gif';//'images/preloader_logo.gif';
	var t = ajaxResponse.responseText;
	var jsonObj = null;
	eval ("jsonObj = " + t);
	if (jsonObj != null) {
		if (jsonObj.response = 'OK' && jsonObj.errorid == 0) {
			if (jsonObj.status == 'W') {
				alert ("Attention!\nYour email address is not confirmed!\n" +
					"You must confirm your email address or your account will be suspended\n" +
					"Please check your email inbox for confirmation details. Check the spam box too!\n" +
					"The email was sent to " + jsonObj.email);
			}
			//proceed with login
			logged_in = true;
			user_name = jsonObj.username;
			user_email = jsonObj.email;
			hideLoginForm();

			// update settings!
			ThemesChooser.updateTheme(jsonObj.theme);
			Settings.setPauseOnMinimize (jsonObj.pom_state?'on':'off', false);
			Settings.setDimOnPlay (jsonObj.dim_state?'on':'off', false);
			Settings.setPrivateFilter (jsonObj.private_filter?'on':'off', false);
			var ss = {'O':'off','M':'moderate','S':'strict'};
			Settings.setSafeSearchFilter (ss[jsonObj.safe_search], false);
			Slider.setValue (jsonObj.results_size);
			rc.resizeResults (jsonObj.results_size);

			urchinTracker('user/log_in');
			notifyLogin();
		} else {
			//wrong account
			if (jsonObj.errorid == 2)
				alert ('Username or password are wrong! Or both of them!');
			if (jsonObj.errorid == 1)
				alert ('Both username and password needed!');
			if (jsonObj.errorid == 3) {
				if (confirm("Ok, account is correct but not activated. Didn't you receive the email? Even in the spam/junk box?\n" +
					"If not - do you want us to resend it to the email address " + jsonObj.email + "?")) {
					resendActivationEmail ($('login_user').value);
				}
			}
		}
	} else {
		//error logging in
		alert ('Error logging in.');
	}
}

function resendActivationEmail (user) {
	$('checking_account').src = '/images/preloader_boxes.gif';// 'images/logo_boxes.gif';//'images/preloader_circle.gif';
	var params = $H({user: user, resend_conf: 'y'});
	new Ajax.Request ('register_account.php', {
		method:'post',
		onSuccess: resendActivationEmail_handler,
		parameters: params.toQueryString()
	});
}
function resendActivationEmail_handler (ajaxResponse) {
	$('checking_account').src = '/images/logo_boxes.gif';//'images/preloader_logo.gif';
	var t = ajaxResponse.responseText;
	var jsonObj = null;
	eval ("jsonObj = " + t);
	if (jsonObj != null) {
		if (jsonObj.error == 0) {
			alert ('New confirmation email has been sent to ' + jsonObj.email);
		} else
			alert (jsonObj.response);
	} else {
		alert ('Error sending the email')
	}
}

function notifyLogin () {
	//tell the other objects that the user has logged in
	mb.userHasLoggedIn();
	SavedPlaylists.userHasLoggedIn();
	bc.userHasLoggedIn();
	$('my_last_played').style.display = 'inline';
	Favorites.userHasLoggedIn();
	Converter.userHasLoggedIn();
	EmbedPlayer.onUserLogIn();
	Settings.onUserLogIn();
	SavedSearches.onUserLoggedIn();
	UserLimits.onUserLoggedIn();
}

function notifyLogout () {
	mb.userHasLoggedOut();
	SavedPlaylists.userHasLoggedOut();
	bc.userHasLoggedOut();
	$('my_last_played').style.display = 'none';
	Favorites.userHasLoggedOut();
	Converter.userHasLoggedOut();
	EmbedPlayer.onUserLogOut();
	Settings.onUserLogOut();
	SavedSearches.onUserLoggedOut();
	UserLimits.onUserLoggedOut();
}

function Register () {
	showRegistrationForm ();
}

function showRegistrationForm () {
	showBackground();
	$('register_check_user_available').innerHTML = 'Check availability';
	//$('register_account').style.display = 'none';
	$('register_account').src = '/images/logo_boxes.gif';// 'images/preloader_logo.gif';
	$('register_user').value = $('register_email').value = $('register_pass').value = $('register_pass_2').value = '';
	$('register_account_agree').checked = false;
	$('register_dialog').style.display = 'block';
	$('register_dialog').getElementsByTagName('INPUT')[0].focus();
}

function hideRegistrationForm () {
	hideBackground();
	$('register_dialog').style.display = 'none';
	$('search_input').focus();
}

function showPayPlanSelectForm () {
	showBackground();
	$('select_pay_plan_dialog').style.display = 'block';
}
function hidePayPlanSelectForm () {
	hideBackground();
	$('select_pay_plan_dialog').style.display = 'none';
}

function checkRegister() {
	var user = $('register_user').value;
	var email = $('register_email').value;
	var pass = $('register_pass').value;
	var pass_confirm = $('register_pass_2').value;
	var agreed = $('register_account_agree').checked;
	var error = '';
	if (user.length < 3)
		error = "Your username is bit short don't you think? Try making it at least 3 characters long.";
	else if (user.length > 20)
		error = "What, is this an essay? Try making your username less than 20 characters.";
	else if (!email_filter.test(email))
		error = "Are you sure that's your email address?";
	else if (pass.length < 3)
		error = "Your password is bit short don't you think? Try making it at least 3 characters long.";
	else if (pass.length > 20)
		error = "What, is this an essay? Try making your password less than 20 characters.";
	else if (pass != pass_confirm)
		error = "Try checking your passwords - they don't match!";
	else if (!agreed)
		error = "You're going to need to agree with the terms and conditions and the privacy policy of iDesktop.tv before you can register!";

	if (!error == '') {
		alert ("Error: " + error);
		return;
	}
	//$('register_account').style.display = 'block';
	$('register_account').src = 'images/preloader_boxes.gif';// 'images/preloader_circle.gif';
	var params = $H({user:user, pass:pass, email:email});
	new Ajax.Request ('register_account.php',{
		method:'post',
		onSuccess: checkRegister_handler,
		parameters: params.toQueryString()
	});
}

function register_check_availability () {
	var user = $('register_user').value;
	var error = '';
	if (user.length < 3)
		error = 'Username must be at least 3 characters long!';
	else if (user.length > 20)
		error = "Username can't be longer than 20 characters!";
	if (error) {
		alert (error);
		return;
	} else {
		$('register_check_user_available').innerHTML = 'Checking if this username is available...';
		window.lastUsernameCheckedAvailable = user;
		new Ajax.Request ('check_user_available.php', {
			method:'post',
			onSuccess: register_check_availability_handler,
			parameters: $H({user:user}).toQueryString()
		});
	}
}

function register_check_availability_handler (ajaxResponse) {
	var t = ajaxResponse.responseText;
	if (t == 'available')
		$('register_check_user_available').innerHTML = 'This username is available!';
	else
		$('register_check_user_available').innerHTML = 'Sorry, this username is taken.';
}

function register_check_set_unchecked () {
	if ($('register_user').value != window.lastUsernameCheckedAvailable)
		$('register_check_user_available').innerHTML = "Check availability";
}

function checkRegister_handler (ajaxResponse) {
	//$('register_account').style.display = 'none';
	$('register_account').src = '/images/logo_boxes.gif';// 'images/preloader_logo.gif';
	var t = ajaxResponse.responseText;
	var jsonObj = null;
	eval ("jsonObj = " + t);
	if (jsonObj) {
		if (jsonObj.error == 0) {
			urchinTracker('user/register');
			/*alert ("You have been successfully registered.\n\n" +
			"Your activation email has been sent to the address you provided.\n" +
			"Please check your email to complete the registration otherwise we won't let you log-in!");*/
			hideRegistrationForm();
			showRegisterSuccessBox($('register_email').value);
		} else {
			alert (jsonObj.response);
		}
	} else {
		alert ('Error registering');
	}
}
function showRegisterSuccessBox(email) {
	showBackground();
	email_domain = email.replace(/.+@/, '');
	email_domain_strip = email_domain.replace(/^([^.]+)\..+$/, '$1');
	var recognizedDomains = {
		"aol": ["http://sns.webmail.aol.com", "AOL"],
		"aim": ["http://mail.aim.com", "AIM"],
		"yahoo": ["http://login.yahoo.com/config/mail", "Yahoo!"],
		"hotmail": ["http://hotmail.com", "Hotmail"],
		"msn": ["http://hotmail.com", "MSN"],
		"live": ["http://login.live.com", "Live.com"],
		"web": ["http://web.de/fm/", "Web.de"],
		"gmx": ["http://gmx.net", "GMX"],
		"comcast": ["https://login.comcast.net/login?s=portal&continue=http://redir.comcast.net/redirect/webmail", "Comcast"],
		"att": ["http://webmail.att.net/", "at&t"],
		"sbcglobal": ["http://webmail.att.net/", "at&t"],
		"t-online": ["http://www.t-online.de/", " T Online"],
		"gmail": ["http://mail.google.com", "GMail"],
		"googlemail": ["http://mail.google.com", "GMail"],
		"rediffmail": ["http://rediff.com", "rediff.com"],
		"seznam": ["http://seznam.cz/", "Seznam"],
		"mac": ["http://mac.com", "Mobile Me"],
		"mobile": ["http://login.yahoo.com/config/mail", "Yahoo!"],
		"btinternet": ["http://login.yahoo.com/config/mail", "Yahoo!"]
	};

	if (email_domain_strip in recognizedDomains) {
		$('registration_success_link').href = recognizedDomains[email_domain_strip][0];
		$('registration_success_link').innerHTML = 'Go to ' + recognizedDomains[email_domain_strip][1] + ' now';
		$('resgistration_success_bl').style.display = '';
	} else
		$('resgistration_success_bl').style.display = 'none';
	$('registration_success_email').innerHTML = email;
	$('register_success_dialog').style.display = 'block';
}
function hideRegisterSuccessBox () {
	hideBackground();
	$('register_success_dialog').style.display='none';
}
//
function check_login_onload () {
	var d = new Date();
	var t = d.getTimezoneOffset() / 60;
	new Ajax.Request ('check_login_onload.php?t=' + t, {method: 'post',onSuccess: login_onload});
}

function login_onload (ajaxResponse) {
	var t = ajaxResponse.responseText;
	var jsonObj = null;
	eval ("jsonObj = " + t);
	if (jsonObj != null && jsonObj.errorid == 0) {
		if (jsonObj.status == 'W') {
			alert ("Attention!\nYour email address is not confirmed!\n" +
				"You must confirm your email address or your account will be suspended\n" +
				"Please check your email inbox for confirmation details. Check the spam box too!\n" +
				"The email was sent to " + jsonObj.email);
		}
		user_name = jsonObj.username;
		user_email = jsonObj.email;
		onl_settheme = jsonObj.theme;
		onl_pom_state = jsonObj.pom_state;
		Settings.setPauseOnMinimize (jsonObj.pom_state?'on':'off', false);
		onl_dim_state = jsonObj.dim_state;
		Settings.setDimOnPlay (jsonObj.dim_state?'on':'off', false);
		Settings.setPrivateFilter (jsonObj.private_filter?'on':'off', false);
		var ss = {'O':'off','M':'moderate','S':'strict'};
		Settings.setSafeSearchFilter (ss[jsonObj.safe_search], false);
		Slider.setValue (jsonObj.results_size);
		rc.resizeResults (jsonObj.results_size, false);
		logged_in = true;
		notifyLogin();
		ThemesChooser.updateTheme(jsonObj.theme);
	}
}

function LogOut () {
	new Ajax.Request ('logout.php', {method: 'post',onSuccess: LogOut_handler});
	logged_in = false;
	user_name = null;
	user_email = null;
	notifyLogout();
}

function LogOut_handler () {
	//Delete_Cookie ('YouTubeDesktop');
	urchinTracker('user/log_out');
	Cookies.remove('iDesktop')
	ThemesChooser.updateTheme('default');
}
///////////////////////////////
function showLoginOrRegisterForm () {
	showBackground();
	$('login_or_register_dialog').style.display = 'block';
}
function hideLoginOrRegisterForm () {
	hideBackground();
	$('login_or_register_dialog').style.display = '';
}
function LORClickLogin () {
	hideLoginOrRegisterForm();
	showLoginForm();
}
function LORClickRegister () {
	hideLoginOrRegisterForm();
	//showRegistrationForm();
	showPayPlanSelectForm();
}

function delete_account(){
	if (!logged_in) {
		alert ("You must be logged in to delete your account!");
		return false;
	} else {
		window.open("/delete_account.php", "deleteaccount");
		Settings.closeBox();
	}
}

///////////////////////////////
var Settings = {
	safe_search: 'moderate',
	private_filter: true,

	initialize: function () {
		this.safeSearchFilterOptions = document.getElementsByClassName('option', 'safeSearchFilterOptions');
		this.privateFilterOptions = document.getElementsByClassName('option', 'privateFilterOptions');
		this.dimOnPlayOptions = document.getElementsByClassName('option', 'dimOnPlayOptions');
		this.pauseOnMinimizeOptions = document.getElementsByClassName('option', 'pauseOnMinimizeOptions');

		this.setPrivateFilter (Cookies.getValue('private_filter', 'true') != 'true'?'off':'on');
		this.setSafeSearchFilter (Cookies.getValue ('safe_search', 'moderate'));
	},

	openBox: function () {
		showBackground();
		$('settings_dialog').style.display = 'block';
	},
	closeBox: function () {
		hideBackground();
		$('settings_dialog').style.display = '';
	},
	onClickOK: function () {
		this.closeBox();
	},
	onSaved_handler: function (ajaxResponse) {
		this.closeBox();
	},
	onClickCancel: function () {
		this.closeBox();
	},
	onUserLogIn: function () {

	},
	onUserLogOut: function () {

	},

	setDimOnPlay: function (value, save) {
		if (arguments.length == 1) var save = true;
		for (var i = 0; i < this.dimOnPlayOptions.length; i ++)
			Element.removeClassName (this.dimOnPlayOptions[i], 'current');
		var sets = {'on':0,'off':1};
		Element.addClassName(this.dimOnPlayOptions[sets[value]], 'current');

		if (save) {
			Cookies.setValue('dim_state', ((value == 'on')?'true':'false'));
			if (user_name)
				new Ajax.Request('save_settings.php', {method:'post', parameters:'dim_state=' + (value == 'on'?'Y':'N')});
		}
		if (typeof bc != "undefined") bc.switchDimming(value); // may not have yet loaded!
	},
	setPauseOnMinimize: function (value, save) {
		if (arguments.length == 1) var save = true;
		for (var i = 0; i < this.pauseOnMinimizeOptions.length; i ++)
			Element.removeClassName (this.pauseOnMinimizeOptions[i], 'current');
		var sets = {'on':0,'off':1};
		Element.addClassName(this.pauseOnMinimizeOptions[sets[value]], 'current');

		if (save) {
			Cookies.setValue('pom_state', ((value == 'on')?'true':'false'));
			if (user_name)
				new Ajax.Request('save_settings.php', {method:'post', parameters:'pom_state=' + (value == 'on'?'Y':'N')});
		}
		if (typeof bc != "undefined") bc.switchPauseOnMinimize(value); // may not have yet loaded!
	},
	setPrivateFilter: function (value, save) {
		if (arguments.length == 1) var save = true;
		for (var i = 0; i < this.privateFilterOptions.length; i ++)
			Element.removeClassName (this.privateFilterOptions[i], 'current');
		var sets = {'on':0,'off':1};
		Element.addClassName(this.privateFilterOptions[sets[value]], 'current');

		if (save) {
			Cookies.setValue('private_filter', ((value == 'on')?'true':'false'));
			if (user_name)
				new Ajax.Request('save_settings.php', {method:'post', parameters:'private_filter=' + (value == 'on'?'Y':'N')});
		}
		this.private_filter = (value == 'on');
	},
	setSafeSearchFilter: function (value, save) {
		if (value == 'O') value = 'off';
		if (value == 'M') value = 'moderate';
		if (value == 'S') value = 'strict';
		if (arguments.length == 1) var save = true;
		for (var i = 0; i < this.safeSearchFilterOptions.length; i ++)
			Element.removeClassName (this.safeSearchFilterOptions[i], 'current');
		var sets = {'off':0,'moderate':1,'strict':2};
		Element.addClassName(this.safeSearchFilterOptions[sets[value]], 'current');

		var sets = {'off':'O', 'moderate':'M', 'strict':'S'};

		if (save) {
			Cookies.setValue('safe_search', (sets[value]));
			if (user_name)
				new Ajax.Request('save_settings.php', {method:'post', parameters:'safe_search=' + sets[value]});
		}
		this.safe_search = value;
	}
}

var UserLimits = {
	ua_create_custom_player: 1,
	ua_remove_idesktop_branding: 2,
	ua_set_custom_branding: 3,
	ua_set_players_advertising: 4,
	ua_download: 5,
	ua_download_advanced: 6,

	data: [],
	_get_limits_interval: null,

	initialize: function () {
		this._onLimitsReceived = this.onLimitsReceived.bind(this);
		this._getLimits = this.getLimits.bind(this);

		this.messages = {};
		this.messages[this.ua_create_custom_player] = {
			title: 'OOPS! Custom players limit exceeded',
			text : 'Unfortunately you have now created the <strong>Maximum</strong> amount of players for your plan.<br /><br />' +
					'To create more Custom Players you will need to upgrade.<br /><br />' +
					'Would you like to view the Custom Player plans?',
			yes_link: '/pricing-and-signup/custom-players-plan.html'};
		this.messages[this.ua_remove_idesktop_branding] = {
			title: 'OOPS! iDesktop.tv logo can\'t be removed',
			text : 'Nice try, but unfortunately your plan does not allow you to remove the iDesktop.tv player branding.<br /><br />' +
					'Please purchase a <strong>PRO</strong> or <strong>BUSINESS</strong> Custom Player Plan to remove the iDesktop.tv player branding.<br /><br />' +
					'Would you like to view the Custom Player plans?',
			yes_link: '/pricing-and-signup/custom-players-plan.html' };
		this.messages[this.ua_set_custom_branding] = {
			title: 'OOPS! Custom player branding not allowed',
			text : 'Nice try, but unfortunately your plan does not support Custom Player Branding.<br /><br />' +
					'Please purchase a <strong>PRO</strong> or <strong>BUSINESS</strong> Custom Player Plan to enable Custom Branding.<br /><br />' +
					'Would you like to view the Custom Player plans?',
			yes_link: '/pricing-and-signup/custom-players-plan.html'};
		this.messages[this.ua_set_players_advertising] = {
			title: 'OOPS! Custom players advertising is not allowed',
			text : 'Nice try, but unfortunately your plan does not support Custom Player Advertising.<br /><br />' +
					'Please purchase a <strong>PRO</strong> or <strong>BUSINESS</strong> Custom Player Plan to enable Custom Player Advertising.<br /><br />' +
					'Would you like to view the Custom Player plans?',
			yes_link: '/pricing-and-signup/custom-players-plan.html'};
		this.messages[this.ua_download] = {
			title: 'OOPS! Download limit has been exceeded',
			text : 'You have used up all of your download credits for today.<br /><br />' +
					'You can either wait until tomorrow or upgrade to get <strong>UNLIMITED</strong> downloads a month.<br /><br />' +
					'Would you like to view the Downloader Plan?',
			yes_link: '/pricing-and-signup/downloader-plan.html' };
		this.messages[this.ua_download_advanced] = {
			title: 'OOPS! MP3, WMA, AAC and HD downloads are not allowed',
			text : 'Nice try, but unfortunately your FREE account does not support MP3, WMA, AAC or HD downloading.<br /><br />' +
					'Please purchase the <strong>DOWNLOADER</strong> Plan to enable more downloading options.<br /><br />' +
					'Would you like to view the Downloader Plan?',
			yes_link: '/pricing-and-signup/downloader-plan.html' };
		this.dialog = $('limit_exceeded_dialog');
		this.dialogTitle = $('limit_exceeded_dialog_title');
		this.dialogBody = $('limit_exceeded_dialog_content');

		this.userInfoBox = $('user_limits_info_box');

		this.menu_upgrade_button = $('upgrade_head');
	},

	onUserLoggedIn: function () {
		this.startUpdateLimitsCycle();
	},
	startUpdateLimitsCycle: function () {
		if (this._get_limits_interval) return;
		this._get_limits_interval = setInterval (this._getLimits, 1000 * 60 * 5); // 5 minutes is just fine
		this.getLimits();
	},
	stopUpdateLimitsCycle: function () {
		if (this._get_limits_interval) {
			clearInterval (this._get_limits_interval);
			this._get_limits_interval = null;
		}
	},
	getLimits: function () {
		new Ajax.Request ('/get_current_user_limits.php', {onSuccess: this._onLimitsReceived, method:'post'});
	},
	onLimitsReceived: function (ajaxRequest) {
		var jsonObj = null;
		eval ('jsonObj = ' + ajaxRequest.responseText);
		if (jsonObj && !jsonObj.error) {
			this.data = jsonObj;
			if (this.data.pay_plan == 2 || this.data.pay_plan == 6) {
				this.menu_upgrade_button.style.display = 'none';
				Element.addClassName (this.userInfoBox, 'no_up_btn');
			} else {
				this.menu_upgrade_button.style.display ='inline';
				Element.removeClassName (this.userInfoBox, 'no_up_btn');
			}
		}
	},
	onUserLoggedOut: function () {
		this.data = [];
		this.stopUpdateLimitsCycle();
		this.menu_upgrade_button.style.display = 'none';
	},
	isUserAllowedTo: function (action, showError) {
		if (arguments.length == 1) var showError = false;
		var res = false;
		switch (action) {
			case this.ua_create_custom_player:
				if (this.data['limits']['custom_players'] == -1)
					res = true;
				else
					res = !!(this.data['limits']['custom_players'] > EmbedPlayer.embeddedPlayers.length);
				break;
			case this.ua_remove_idesktop_branding:
				res = !this.data['limits']['idesktop_branding'];
				break;
			case this.ua_set_custom_branding:
				res = this.data['limits']['custom_branding'];
				break;
			case this.ua_set_players_advertising:
				res = this.data['limits']['players_advertising'];
				break;
			case this.ua_download:
				if (this.data['limits']['daily_download_credits'] == -1)
					res = true;
				else if (this.data['user']['bonus_download_credits'] > 0 || this.data['user']['daily_download_credits'] > 0)
					res = true
				else
					res = false;
				break;
			case this.ua_download_advanced:
				res = this.data['limits']['advanced_downloads'];
				break;
			default:
				res = false;
		}
		if (!res && showError) {
			if (arguments.length == 3)
				this.showLimitExceededMessage (action, arguments[2]);
			else
				this.showLimitExceededMessage (action);
		}
		return res;
	},
	showLimitExceededMessage: function (action) {
		this.hideBackgroundOnClose = !isBackgroundVisible();
		showBackground();
		// depending on action we will show different text

		this.dialogTitle.innerHTML = this.messages[action].title;
		this.dialogBody.innerHTML = this.messages[action].text;
		this.currentYesLink = this.messages[action].yes_link;

		if (arguments.length == 2) {
			var d = arguments[1];
			this.dialogTitle.innerHTML = 'OOPS! ' + d + ' downloads are not allowed';
			this.dialogBody.innerHTML = 'Nice try, but unfortunately your FREE account does not support ' + d + ' downloading.<br /><br />' +
					'Please purchase the <strong>DOWNLOADER</strong> Plan to enable more downloading options.<br /><br />' +
					'Would you like to view the Downloader Plan?';
		}

		this.dialog.style.display = 'block';

		if ($('embed_player').style.display == 'block') {
			$('embed_player').style.display = 'none';
			this.showEmbedOnClose = true;
		} else
			this.showEmbedOnClose = false;
		if ($('create_simple_embed_dialog').style.display == 'block') {
			$('create_simple_embed_dialog').style.display = 'none';
			this.showEmbedSimpleOnClose = true;
		} else
			this.showEmbedSimpleOnClose = false;
		if ($('embed_players_list').style.display == 'block') {
			$('embed_players_list').style.display = 'none';
			this.showEmbedPlayersListOnClose = true;
		} else
			this.showEmbedPlayersListOnClose = false;
		if ($('download_formats_dialog').style.display == 'block') {
			$('download_formats_dialog').style.display = 'none';
			this.showDownloadFormatDialogOnClose = true;
		} else
			this.showDownloadFormatDialogOnClose = false;
	},
	closeLimitDialog: function () {
		if (this.hideBackgroundOnClose) hideBackground();
		this.dialog.style.display = 'none';
		if (this.showEmbedOnClose)
			$('embed_player').style.display = 'block';
		if (this.showEmbedSimpleOnClose)
			$('create_simple_embed_dialog').style.display = 'block';
		if (this.showEmbedPlayersListOnClose)
			$('embed_players_list').style.display = 'block';
		if (this.showDownloadFormatDialogOnClose)
			$('download_formats_dialog').style.display = 'block';
	},
	onClickUpgrade: function () {
		this.closeLimitDialog();
		window.open(this.currentYesLink);
	},
	takeDownloadCredit: function () {
		if (this.data['limits']['daily_download_credits'] == -1) return true;
		if (this.data['user']['bonus_download_credits'] > 0)
			this.data['user']['bonus_download_credits'] --;
		else
		if (this.data['user']['daily_download_credits'] > 0)
			this.data['user']['daily_download_credits'] --;
		else
			return false;
		return true;
	},
	userInfoBoxVisible: false,
	showUserInfoBox: function () {
		this.updateUserInfoBoxContent();
		this.userInfoBox.style.display = 'block';
		this.userInfoBoxVisible = true;
	},
	hideUserInfoBox: function () {
		this.userInfoBox.style.display = 'none';
		this.userInfoBoxVisible = false;
	},
	switchUserInfoBox: function () {
		if (this.userInfoBoxVisible)
			this.hideUserInfoBox();
		else
			this.showUserInfoBox();
	},
	updateUserInfoBoxContent: function () {
		var content = '';
		var names = ['', 'FREE', 'DOWNLOADER', 'BASIC', 'PRO', 'PREMIUM', 'MAX'];

		content = '<span class="l">Account Type:</span><span class="v">' + names[this.data.pay_plan];
		if (this.data.pay_plan != 2 && this.data.pay_plan != 6)
			content += ' <a href="/account-pay-plan.html" class="blue_link" target="_blank">Upgrade Now</a>';
		content += '</span><br /><br />';

		var names2 = ['', 'Free', 'Downloader', 'Custom Players Basic', 'Custom Players Pro', 'Custom Players Premium', 'Custom Players Max'];
		var statuses = {P:'pending',C:'cancelled',S:'suspended',E:'expired'};
		if (this.data.pending_plan.status == 'P')
			content += 'Your registration for iDesktop.tv ' + names2[this.data.pending_plan.id] + ' Plan is still pending. It may take up to 24 hours to activate!<br /><br />';
		else if (this.data.pending_plan.status == 'S')
			content += 'Your registration for iDesktop.tv ' + names2[this.data.pending_plan.id] + ' Plan is suspended!<br /><br />';
		else if (this.data.pending_plan.status == 'E' ) {
			content += 'Your registration for iDesktop.tv ' + names2[this.data.pending_plan.id] + ' Plan has expired due to failed payments!<br /><br />';
		}


		switch (this.data.pay_plan) {
			case 1:
				content += '<span class="l">Bonus Credits:</span> <span class="v">' + this.data.user.bonus_download_credits + ' left </span><br />' +
					'<span class="l">Daily Credits:</span> <span class="v">' + (this.data.user.bonus_download_credits > 0 ? 'Use Bonus First' : this.data.user.daily_download_credits + ' left today') + '</span><br /><br />' +
					'<span class="l">Custom Players:</span> <span class="v">' + EmbedPlayer.embeddedPlayers.length + ' / ' + this.data.limits.custom_players + '</span><br />' +
					//'<span class="l">Players Impressions:</span> <span class="v">' + this.data.user.custom_players_impressions + '</span><br /><br />' +
					'<span class="l">Playlists: </span> <span class="v">' + SavedPlaylists.playlists.length + '</span><br />' +
					'<span class="l">Favorites: </span> <span class="v">' + Favorites.favorites.length + '</span>';
				break;
			case 2:
				content += '<span class="l">Daily Credits:</span> <span class="v">Unlimited</span><br />' +
					//'<span class="l">No. of Downloads:</span> <span class="v"> - </span><br /><br />' +
					'<span class="l">Custom Players:</span> <span class="v">' + EmbedPlayer.embeddedPlayers.length + ' / ' + this.data.limits.custom_players + '</span><br />' +
					//'<span class="l">Players Impressions:</span> <span class="v">' + this.data.user.custom_players_impressions + '</span><br /><br />' +
					'<span class="l">Playlists: </span> <span class="v">' + SavedPlaylists.playlists.length + '</span><br />' +
					'<span class="l">Favorites: </span> <span class="v">' + Favorites.favorites.length + '</span>';
				break;
			case 3: case 4: case 5: case 6:
				content += '<span class="l">Custom Players:</span> <span class="v">' + EmbedPlayer.embeddedPlayers.length + (this.data.limits.custom_players > -1 ? ' / ' + this.data.limits.custom_players : '') + '</span><br />' +
					//'<span class="l">Players Impressions:</span> <span class="v">' + this.data.user.custom_players_impressions + '</span><br /><br />' +

					'<span class="l">Bonus Credits:</span> <span class="v">' + this.data.user.bonus_download_credits + ' left</span><br />' +
					'<span class="l">Daily Credits:</span> <span class="v">' + (this.data.user.bonus_download_credits > 0 ? 'Use Bonus First' : this.data.user.daily_download_credits + ' left today') + '</span><br /><br />' +

					'<span class="l">Playlists: </span> <span class="v">' + SavedPlaylists.playlists.length + '</span><br />' +
					'<span class="l">Favorites: </span> <span class="v">' + Favorites.favorites.length + '</span>';
				break;
		}
		this.userInfoBox.innerHTML = content;
	}
}