var standardFeedsStrings = {'featured':'Featured', "top_rated":"Top rated", "top_favorites":"Top favored",
		"most_viewed":"Most viewed", "most_popular":"Most popular", "most_recent":"Most recent",
		"most_discussed":"Most discussed", "most_linked":"Most linked", "most_responded":"Most responded"};
var EmbeddedPlayer = Class.create();
EmbeddedPlayer.prototype = {
	initialize: function (jsonObj, number) {
		Object.extend(this, TemplatedElement);
		this.jsonObj = jsonObj;
		this._buildFromTemplate('template_embedded_player_list_item');
		this.elementOrd.innerHTML = number + '. ';
		this.elementName.innerHTML = jsonObj.player_name;
		if (number%2 == 0) Element.addClassName (this.element, 'even');
		if (this.jsonObj.description)
			this.elementDescription.innerHTML = this.jsonObj.description;
		else
			this.elementDescription.style.display = 'none';
		//this.elementType.innerHTML = ''

		switch (this.jsonObj.type) {
			case 1: this.elementType.innerHTML = 'Fixed box in the page'; break;
			case 2: this.elementType.innerHTML = 'Popout box in the page'; break;
			case 3: this.elementType.innerHTML = 'Video wall'; break;
			case 4: this.elementType.innerHTML = 'Videos list box'; break;
			case 5: this.elementType.innerHTML = 'Horizontal box'; break;
			case 6:
				this.elementType.innerHTML = 'Flash only player';
				this.elementPlaylistType.style.visibility = 'hidden';
				break;
		}

		this.elementPlaylistType.innerHTML = 'Playlist - ';
		switch (this.jsonObj.playlist_type) {
			case 1: this.elementPlaylistType.innerHTML += 'vertical'; break;
			case 2: this.elementPlaylistType.innerHTML += 'listbox'; break;
			case 3: this.elementPlaylistType.innerHTML += 'videowall'; break;
		}
		switch (this.jsonObj.ds) {
			case EmbedPlayer.EMBED_SAVED_LIST:
				var pll = SavedPlaylists.getListById(this.jsonObj.jsonObj.id)
				if (!pll) {
					this.errors = true;
					this.elementDS.innerHTML = 'Broken playlist!';
					SavedPlaylists.onLoadRecheckPlayers.push(this);
				} else {
					this.jsonObj.jsonObj.name = pll.name;
					this.elementDS.innerHTML = pll.videos.length + ' videos from "' + pll.name + '" playlist';
				}
				//this.elementDS.innerHTML = 'Saved playlist: "' + this.jsonObj.jsonObj.name + '"';
				break;
			case EmbedPlayer.EMBED_RUNTIME_LIST:
				this.elementDS.innerHTML = this.jsonObj.jsonObj.length + " videos embedded from player";
				break;
			case EmbedPlayer.EMBED_SEARCH_RESULTS:
				/*if (this.jsonObj.jsonObj.keywords == '')
					this.elementDS.innerHTML = this.jsonObj.jsonObj.resultsCount + ' featured videos';
				else*/
				this.elementDS.innerHTML = this.jsonObj.jsonObj.resultsCount + ' results for search term "' + this.jsonObj.jsonObj.keywords + '"';
				break;
			case EmbedPlayer.EMBED_FAVORITES:
				this.elementDS.innerHTML = 'Favorite videos';
				break;
			case EmbedPlayer.EMBED_USER_CHANNEL:
				this.elementDS.innerHTML = 'User/Channel: ' + this.jsonObj.jsonObj.channel;
				break;
			case EmbedPlayer.EMBED_STANDARD_FEED:
				this.elementDS.innerHTML = standardFeedsStrings[this.jsonObj.jsonObj.feed] + ' YouTube videos ';
				break;
			case EmbedPlayer.EMBED_SINGLE_VIDEO:
				this.elementDS.innerHTML = 'Single video: ' + this.jsonObj.jsonObj.title;
				break;
			case EmbedPlayer.EMBED_EXTERNAL_PLAYLIST:
				this.elementDS.innerHTML = 'External playlist: ' + this.jsonObj.external_playlist_url;
				this.epElement = document.createElement ('div');
				this.epElement.className = 'ep_details';
				var t = '<span class="lch">Last checked: ';

				if (this.jsonObj.external_playlist_lastupdate) {
					var d = new Date(this.jsonObj.external_playlist_lastupdate);
					t += d.getFullYear() + '-' + toTwoDigits(1 + d.getMonth()) + '-' + toTwoDigits(d.getDate()) + ' ' + toTwoDigits(d.getHours()) + ':' + toTwoDigits(d.getMinutes()) ;
				} else
					t += 'unknown';
				t += '</span>'
				this.epElement.innerHTML = t;
				if (this.jsonObj.external_playlist_nextupdate) {
					var d = new Date(this.jsonObj.external_playlist_nextupdate);
					this.epElement.innerHTML += '<span class="nch">Next update: ' + d.getFullYear() + '-' + toTwoDigits(1 + d.getMonth()) + '-' + toTwoDigits(d.getDate()) + ' ' + toTwoDigits(d.getHours()) + ':' + toTwoDigits(d.getMinutes()) + '</span>';
				}

				this.epElement.innerHTML += '<div class="actions"><a href="/embed/' + this.jsonObj.hash + '/playlist-updates-log.html" target="_blank">Updates log</a> . ' +
					'<a href="/embed/' + this.jsonObj.hash + '/update-playlist.html" target="_blank">Update now</a> . </div>' ;
				this.elementDescription.parentNode.insertBefore(this.epElement, this.elementDescription);
				break;
			case EmbedPlayer.EMBED_YOUTUBE_PLAYLIST:
				this.elementDS.innerHTML = 'Youtube Playlist';
				break;
		}
		this.filterText = this.jsonObj.player_name.toLowerCase() + ' ' + this.jsonObj.description.toLowerCase() + ' ' +
			 this.elementType.innerHTML.toLowerCase() + ' ' + this.elementDS.innerHTML.toLowerCase();
		this.parentElement = $('embedded_players');
		this.parentElement.appendChild(this.element);
	},
	recheckPlaylist: function () {
		if (this.jsonObj.ds == EmbedPlayer.EMBED_SAVED_LIST) {
			var pll = SavedPlaylists.getListById(this.jsonObj.jsonObj.id)
			if (pll) {
				this.jsonObj.jsonObj.name = pll.name;
				this.elementDS.innerHTML = pll.videos.length + ' videos from "' + pll.name + '" playlist';
			}
		}
	},
	remove : function () {
		if (this.element.parentNode == this.parentElement)
			this.parentElement.removeChild(this.element);
	},
	open: function () {
		window.open('/embed/' + this.jsonObj.hash + '/preview-player.html', '');
	},
	edit: function () {
		EmbedPlayer.editPlayer(this);
	},
	copy: function () {
		EmbedPlayer.copyPlayer(this);
	},
	deletePlayer: function () {
		EmbedPlayer.deletePlayer(this);
	},
	getCode: function () {
		EmbedPlayer.getCode(this.jsonObj);
	},
	filter: function (keywords) {
		var matches = true;
		var haystack = this.filterText;
		for (var i = 0, n = keywords.length; i < n; i ++) {
			var kw = keywords[i];
			if (haystack.indexOf(kw) == -1) {
				matches = false;
				break;
			}
		}
		this.filtered = !matches;
		this.element.style.display = this.filtered?'none':'block';
	}
}

var EmbedPlayer = {
	listBoxMarginLeft: -350, listBoxMarginTop: -270,
	elementMarginLeft : -375, elementMarginTop: -300, // these are for the moving
	listOrderedBy : 'date',

	initialize: function () {
		this.element = $('embed_player');
		this.listBox = $('embed_players_list');
		this.formDiv = $('embed_player_form_div');
		this.form = $('embed_player_form');
		this.elementHeader = $('embed_videos_header');
		/*this.elementHeader.onmousedown = this.onStartMove.bindAsEventListener(this);
		$('embed_players_heading').onmousedown = this.onStartMoveList.bindAsEventListener(this);
		$('embed_players_resizer').onmousedown = this.onStartResizeList.bindAsEventListener(this);*/
		this.listBoxContent = $('embedded_players');
		this.listBoxScrollContainer = $('embed_players_list_scrollbar');
		this.inputs = {
			saved_playlist: $ST(this.form.saved_playlist),
			embed_type: $RB(this.form.embed_type), // radio buttons
			data_source_type: this.form.data_source_type,
			data_source: $RB(this.form.data_source),
			standard_feed: $ST(this.form.standard_feed),
			standard_feed_videos_count: this.form.standard_feed_videos_count,
			playlist_type: $RB(this.form.playlist_type), // radio
			only_public: this.form.only_public,
			mark_private: this.form.mark_private,
			email_on_delete: this.form.email_on_delete,
			reverse_playlist: this.form.reverse_playlist,

			size: $ST(this.form.size),
			width: this.form.width, // this.form.getElementsByName('width'),
			height:this.form.height, //.getElementsByName('height'),
			listbox_width: this.form.listbox_width, // this.form.getElementsByName('width'),
			listbox_height: this.form.listbox_height, //.getElementsByName('height'),
			player_placement: this.form.player_placement,
			playlist_enabled:this.form.playlist_enabled, //getElementsByName('playlist_enabled'),
			playlist_visible:this.form.playlist_visible, //getElementsByName('playlist_visible'),
			info_enabled:this.form.info_enabled, //getElementsByName('info_enabled'),
			info_visible:this.form.info_visible, //getElementsByName('info_visible')
			autostart: this.form.autostart,
			theme:$ST(this.form.theme),
			player_name: this.form.player_name,
			playlist_name: this.form.playlist_name,
			description: this.form.description,
			videos_count: this.form.videos_count,
			channel_videos_count: this.form.channel_videos_count,
			jsonObj: this.form.jsonObj,
			new_playlist_name: this.form.new_playlist_name,

			external_playlist_url: this.form.external_playlist_url,
			external_playlist_interval: this.form.external_playlist_interval,

			//show_download_button: this.form.show_download_button,
			show_url_button: this.form.show_url_button,
			show_youtube_button: this.form.show_youtube_button,
			show_rating: this.form.show_rating,
			show_addthis_button: this.form.show_addthis_button,
			addthis_username: this.form.addthis_username,
			show_title: this.form.show_title,
			uploader_in_title: this.form.uploader_in_title,
			video_name_in_title: this.form.video_name_in_title,

			player_title_bar_image_url: this.form.player_title_bar_image_url,
			player_title_bar_image_align: $ST(this.form.player_title_bar_image_align),
			player_title_bar_back: $ST(this.form.player_title_bar_back),
			player_title_bar_background: this.form.player_title_bar_background,
			player_title_bar_font: this.form.player_title_bar_font,

			player_info_back_sel: $ST(this.form.player_info_back_sel),
			player_info_btn_back_sel: $ST(this.form.player_info_btn_back_sel),
			player_info_btn_color_sel: $ST(this.form.player_info_btn_color_sel),
			player_info_panel_back: this.form.player_info_panel_back,
			player_info_panel_font: this.form.player_info_panel_font,
			player_info_panel_buttons_back: this.form.player_info_panel_buttons_back,
			player_info_panel_buttons_color: this.form.player_info_panel_buttons_color,

			max_logo_width: this.form.max_logo_width,
			player_logo_url: this.form.player_logo_url,
			repeat: this.form.repeat,
			shuffle: this.form.shuffle,
			thumbnails_size: $ST(this.form.thumbnails_size),
			thumbs_rows: this.form.thumbs_rows,
			thumbs_cols: this.form.thumbs_cols,
			thumb_text_box_size: this.form.thumb_text_box_size,

			thumbnail_text_show: (this.form.thumbnail_text_show),
			thumbnail_text: (this.form.thumbnail_text),
			thumbnail_text_sel: $ST(this.form.thumbnail_text_sel),

			thumb_show_title: this.form.thumb_show_title,
			thumb_show_author: this.form.thumb_show_author,
			thumb_show_rating: this.form.thumb_show_rating,
			thumb_show_length: this.form.thumb_show_length,
			thumb_show_description: this.form.thumb_show_description,
			thumb_show_views: this.form.thumb_show_views,
			thumb_show_labels: this.form.thumb_show_labels,
			thumb_text_cut_title_two_lines: this.form.thumb_text_cut_title_two_lines,
			thumbs_text_box_padding: this.form.thumbs_text_box_padding,

			background_color_transparent: this.form.background_color_transparent,
			alt_background_color_transparent: this.form.alt_background_color_transparent,
			use_alt_background_color: this.form.use_alt_background_color,

			//emb_background_color_transparent: this.form.emb_background_color_transparent,
			embed_background: this.form.embed_background,
			emb_background_sel: $RB(this.form.emb_background_sel),

			prev_next_button_style: $ST(this.form.prev_next_button_style),
			show_prev_next_buttons: this.form.show_prev_next_buttons,

			popout_button_text: this.form.popout_button_text,
			popout_button_type: $RB(this.form.popout_button_type),
			popout_box_button: this.form.popout_box_button,

			pll_width: this.form.pll_width,
			pll_thumb_size: $ST(this.form.pll_thumb_size),
			pll_thumb_width: this.form.pll_thumb_width,
			pll_thumb_height: this.form.pll_thumb_height,
			pll_columns: this.form.pll_columns,

			pll_thumbnail_text: this.form.pll_thumbnail_text,
			pll_thumbnail_text_show: this.form.pll_thumbnail_text_show,
			pll_thumbnail_text_sel: $ST(this.form.pll_thumbnail_text_sel),

			pll_thumb_text_box_size: this.form.pll_thumb_text_box_size,
			pll_text_box_padding: this.form.pll_text_box_padding,

			pll_thumb_show_title: this.form.pll_thumb_show_title,
			pll_thumb_show_author: this.form.pll_thumb_show_author,
			pll_thumb_show_rating: this.form.pll_thumb_show_rating,
			pll_thumb_show_length: this.form.pll_thumb_show_length,
			pll_thumb_show_description: this.form.pll_thumb_show_description,
			pll_thumb_show_views: this.form.pll_thumb_show_views,
			pll_thumb_show_labels: this.form.pll_thumb_show_labels,

			pll_title_cut_two_lines: this.form.pll_title_cut_two_lines,

			pll_background_color_transparent: this.form.pll_background_color_transparent,
			pll_alt_background_color_transparent: this.form.pll_alt_background_color_transparent,
			pll_use_alt_background_color: this.form.pll_use_alt_background_color,
			pll_show_play_controls: this.form.pll_show_play_controls,

			pll_thumb_buttons: this.form.pll_thumb_buttons,
			pll_thumb_buttons_show: this.form.pll_thumb_buttons_show,
			pll_thumb_buttons_sel: $ST(this.form.pll_thumb_buttons_sel),


			pll_show_hint: this.form.pll_show_hint,
			pll_hint_show_title: this.form.pll_hint_show_title,
			pll_hint_show_author: this.form.pll_hint_show_author,
			pll_hint_show_length: this.form.pll_hint_show_length,
			pll_hint_show_views: this.form.pll_hint_show_views,
			pll_hint_show_rating: this.form.pll_hint_show_rating,
			pll_hint_show_votes: this.form.pll_hint_show_votes,

			pll_playlist_logo_link: this.form.pll_playlist_logo_link,
			pll_playlist_logo_placement: $RB(this.form.pll_playlist_logo_placement),
			pll_show_prev_next_buttons: this.form.pll_show_prev_next_buttons,

			/// ADS
			pre_roll_list: this.form.pre_roll_list,
			pre_roll_ad: this.form.pre_roll_ad,
			pre_roll_ad_show: this.form.pre_roll_ad_show,
			pre_roll_playlist: $ST(this.form.pre_roll_playlist),
			pre_roll_video_r: $RB(this.form.pre_roll_video_r),
			pre_roll_video_sel: $ST(this.form.pre_roll_video_sel),

			mid_roll_list: this.form.mid_roll_list,
			mid_roll_ad: this.form.mid_roll_ad,
			mid_roll_ad_show: this.form.mid_roll_ad_show,
			mid_roll_playlist: $ST(this.form.mid_roll_playlist),
			mid_roll_video_r: $RB(this.form.mid_roll_video_r),
			mid_roll_video_sel: $ST(this.form.mid_roll_video_sel),
			mid_roll_show_every: this.form.mid_roll_show_every,

			post_roll_list: this.form.post_roll_list,
			post_roll_ad: this.form.post_roll_ad,
			post_roll_ad_show: this.form.post_roll_ad_show,
			post_roll_playlist: $ST(this.form.post_roll_playlist),
			post_roll_video_r: $RB(this.form.post_roll_video_r),
			post_roll_video_sel: $ST(this.form.post_roll_video_sel),

			ads_caption: this.form.ads_caption,
			ads_disable_controls: this.form.ads_disable_controls,

			ga_id: this.form.ga_id,
			ga_page_url: this.form.ga_page_url,
			ga_events_category: this.form.ga_events_category
		}

		this.imagesSelector = new TImagesSelector ();
		this.imagesSelector.onBoxShow = this.onImagesSelectorBoxShow.bind(this);
		this.imagesSelector.onBoxHide = this.onImagesSelectorBoxHide.bind(this);
		this.imagesSelector.attachSelector ('embed_playlist_logo_current_new', {name: 'playlist_logo', inputName: 'pll_playlist_logo_id', boxTitle: 'Select Playlist Logo', maxImageHeight:18, scaledWidthInputName: 'pll_playlist_logo_width', scaledHeightInputName: 'pll_playlist_logo_height',
			onChange: function (image) { $('emb_playlist_logo_link_tr').style.display = (image?'':'none'); },
			onClickDisabled: function () { UserLimits.showLimitExceededMessage(UserLimits.ua_set_custom_branding); } });
		this.imagesSelector.attachSelector ('embed_custom_player_logo_new', {name: 'player_logo', inputName: 'player_logo_id', boxTitle: 'Select Player Logo', maxImageHeight:24, maxImageWidth:'auto', scaledWidthInputName: 'player_logo_width', scaledHeightInputName: 'player_logo_height',
			onChange: function (image) { $('emb_player_custom_logo_link_tr').style.display = (image?'':'none'); },
			onClickDisabled: function () { UserLimits.showLimitExceededMessage(UserLimits.ua_remove_idesktop_branding); } });
		this.imagesSelector.attachSelector ('embed_player_background_image', {name: 'player_background', inputName: 'player_background_image_id', boxTitle: 'Select Player Background Image', maxImageHeight:'auto', maxImageWidth:'auto'});
		this.imagesSelector.attachSelector ('embed_title_bar_logo', {name: 'title_logo', inputName: 'player_title_bar_image_id', boxTitle: 'Select Title Bar Logo', maxImageHeight:29, maxImageWidth:'auto', scaledWidthInputName: 'player_title_bar_image_width', scaledHeightInputName: 'player_title_bar_image_height',
			onChange: function (image, sw, sh) {
				$('embed_title_bar_logo_aligned_td1').style.display = EmbedPlayer.inputs.player_title_bar_image_align.style.display =
				$('embed_title_bar_logo_tr3').style.display = $('embed_title_bar_logo_tr2').style.display = (image?'':'none');
				if (image) $('title_bar_logo_size').innerHTML = sw + "x" + sh;
			},
			onClickDisabled: function () { UserLimits.showLimitExceededMessage(UserLimits.ua_set_custom_branding); }});
		this.imagesSelector.attachSelector ('embed_popout_btn_image', {name: 'popout_button', inputName: 'popout_button_image', boxTitle: 'Select popout box button', maxImageHeight:'auto', maxImageWidth:'auto'});
		this.imagesSelector.attachSelector ('emd_background_image_select', {name: 'embed_background_image', inputName: 'embed_background_image', boxTitle: 'Select box embed background', maxImageHeight:'auto', maxImageWidth:'auto'});
		this.imagesSelector.attachSelector ('autostart_off_preimage', {name: 'autostart_preimage', inputName: 'autostart_preimage_id', boxTitle: 'Select image to show before starting', maxImageHeight:'auto', maxImageWidth:'auto'});
		this.codeDiv = $('embed_player_code_div');
		this.codeArea = $('embed_player_code');
		this.inputs.playlist_enabled.onclick = this.inputs.playlist_visible.onclick =
			this.inputs.info_enabled.onclick = this.inputs.info_visible.onclick =
			this.inputs.width.onchange = this.inputs.height.onchange =
			/*this.inputs.show_download_button.onclick =*/ this.inputs.show_url_button.onclick = this.inputs.show_rating.onclick =
			this.inputs.show_youtube_button.onclick = this.updateEmbeddedPlayerExample.bindAsEventListener(this);
		this.inputs.show_addthis_button.onclick = this.onShowAddthisChange.bind(this);
		this.inputs.embed_type.setOnChangeHandler (this.onEmbedTypeChange.bindAsEventListener(this));
		this.inputs.data_source.setOnChangeHandler (this.onDataSourceChange.bindAsEventListener(this));
		this.inputs.only_public.onclick = this.onShowOnlyPublicChange.bindAsEventListener(this);
		this.inputs.show_title.onclick = this.onShowTitleChange.bindAsEventListener(this);

		this.playerTitleBackgroundColorPicker = new TColorPicker ('embed_title_bar_background_color', {defaultColor:'000000', inputName:'embed_player_title_bar_background_color'});
		this.inputs.player_title_bar_back.onchange = this.onPlayerTitleBarBackgroundChange.bind(this);

		this.playerTitleFontPicker = new TFontPicker ('embed_player_title_bar_font', {inputName: 'player_title_bar_font', titleText: 'Player title bar font settings'});

		this.infoPanelBackgroundColor = new TColorPicker ('embed_player_info_back', {defaultColor: 'FFFFFF', input_name: 'dummy_player_info_back'});
		this.infoPanelFont = new TFontPicker ('embed_player_info_font', {inputName: 'player_info_panel_font', titleText: 'Info panel font settings'});
		this.infoPanelButtonBackgroundColor = new TColorPicker ('embed_player_info_btn_back', {defaultColor: '000000', input_name: 'dummy_player_info_btn_back'});
		this.infoPanelButtonFontColor = new TColorPicker ('embed_player_info_btn_color', {input_name: 'dummy_player_info_btn_color', defaultColor:'FFFFFF'});

		this.inputs.player_info_back_sel.onchange = this.onPlayerInfoPanelBackgroundSelectChange.bind(this);
		this.inputs.player_info_btn_back_sel.onchange = this.onPlayerInfoPanelTabButtonBackgroundChange.bind(this);
		this.inputs.player_info_btn_color_sel.onchange = this.onPlayerInfoPanelTabButtonFontColorChange.bind(this);

		this.inputs.thumbnails_size.onchange = this.recalculateListboxSizes.bindAsEventListener(this, "thumbs");
		this.inputs.thumbnail_text_sel.onchange = this.inputs.thumbnail_text_show.onclick = this.recalculateListboxSizes.bindAsEventListener(this, "textbox_size");
		this.inputs.thumb_text_box_size.onchange = this.recalculateListboxSizes.bindAsEventListener(this, "textbox_size");
		this.inputs.thumbs_rows.onchange = this.inputs.thumbs_cols.onchange = this.recalculateListboxSizes.bindAsEventListener(this, "rowscols");
		this.inputs.listbox_width.onchange = this.inputs.listbox_height.onchange = this.recalculateListboxSizes.bindAsEventListener(this, "outer");

		this.inputs.pll_width.onchange = this.recalculatePlaylistSizes.bindAsEventListener(this, 'playlist');
		this.inputs.pll_thumb_size.onchange = this.recalculatePlaylistSizes.bindAsEventListener(this, 'thumbs');
		this.inputs.pll_columns.onchange = this.recalculatePlaylistSizes.bindAsEventListener(this, 'columns');
		this.inputs.pll_thumbnail_text_sel.onchange = this.inputs.pll_thumbnail_text_show.onclick =
			this.recalculatePlaylistSizes.bindAsEventListener(this, 'textbox_pos');
		this.inputs.pll_thumb_text_box_size.onchange = this.recalculatePlaylistSizes.bindAsEventListener(this, 'textbox_size');
		this.inputs.pll_show_play_controls.onclick = this.recalculatePlaylistSizes.bindAsEventListener(this, '');

		this.inputs.show_prev_next_buttons.onclick = this.onPrevNextButtonsShowhideClick.bindAsEventListener(this);

		$('embed_player_size_custom').style.display = 'none';

		this.form.embed_search_category.innerHTML = '';
		// fill categories in the data source form
		for (var i = 0; i < AvailableCategories.length; i ++) {
			var opt = document.createElement('option');
			opt.value = AvailableCategories[i].id;
			opt.innerHTML = AvailableCategories[i].name;
			this.form.embed_search_category.appendChild(opt);
		}

		this.embeddedPlayers = new Array ();

		this.sortList(Cookies.getValue('cplsb', 'date'), false);

		this.scroll = new Scrollbar (this.listBoxContent, this.listBoxScrollContainer);
		//this.textColorPicker = new TColorPicker('embed_text_color', {defaultColor:'000000', inputName: 'text_color'});
		//this.titleColorPicker = new TColorPicker('embed_title_style_color', {defaultColor:'000000', inputName: 'title_color'});
		this.backgroundColorPicker = new TColorPicker('embed_background_color', {defaultColor:'F0F0F0', inputName: 'background_color'});
		this.altBackgroundColorPicker = new TColorPicker('embed_second_background_color', {defaultColor:'F0F0F0', inputName: 'alt_background_color'});

		this.embBackgroundColorPicker = new TColorPicker ('emb_background_color_select', {defaultColor: 'FFFFFF', inputName: 'emb_background_color'});

		this.titleFontPicker = new TFontPicker ('embed_title_font_selector', {inputName: 'title_font', titleText: 'Video title font settings'});
		this.textFontPicker = new TFontPicker ('embed_text_font_selector', {inputName: 'text_font', titleText: 'Font settings'});
		this.labelsFontPicker = new TFontPicker ('embed_labels_font_selector', {inputName: 'labels_font', titleText: 'Labels font settings'});
		Element.addClassName (this.backgroundColorPicker.element, 'back');
		Element.addClassName (this.altBackgroundColorPicker.element, 'back2');

		this.backgroundColorPicker.onColorChanged = this.altBackgroundColorPicker.onColorChanged = this.titleFontPicker.onChange =
			this.textFontPicker.onChange = this.labelsFontPicker.onChange = this.inputs.background_color_transparent.onclick =
			this.inputs.thumbs_text_box_padding.onchange = this.inputs.thumb_text_cut_title_two_lines.onclick =
			this.inputs.thumb_show_title.onclick = this.inputs.thumb_show_author.onclick =
			this.inputs.thumb_show_rating.onclick = this.inputs.thumb_show_length.onclick =
			this.inputs.thumb_show_description.onclick = this.inputs.thumb_show_views.onclick =
			this.inputs.thumb_show_labels.onclick = this.inputs.use_alt_background_color.onclick = this.updateFontsExample.bind(this);

		this.pllBackgroundColorPicker = new TColorPicker('embed_pll_background_color', {defaultColor:'F0F0F0', inputName: 'pll_background_color'});
		this.pllAltBackgroundColorPicker = new TColorPicker('embed_pll_alt_background_color', {defaultColor:'F0F0F0', inputName: 'pll_alt_background_color'});
		this.pllThumbsBackgroundColorPicker = new TColorPicker('embed_pll_thumbs_background_color', {defaultColor:'595b65', inputName:'pll_thumb_background'});

		this.pllTitleFontPicker = new TFontPicker ('embed_pll_title_font', {inputName: 'pll_title_font', titleText: 'Title font settings'});
		this.pllTextFontPicker = new TFontPicker ('embed_pll_text_font', {inputName: 'pll_text_font', titleText: 'Font settings'});
		this.pllLabelsFontPicker = new TFontPicker ('embed_pll_labels_font', {inputName: 'pll_labels_font', titleText: 'Labels font settings'});
		this.pllBackgroundColorPicker.onColorChanged = this.pllAltBackgroundColorPicker.onColorChanged = this.pllTitleFontPicker.onChange =
			this.pllTextFontPicker.onChange = this.pllLabelsFontPicker.onChange = this.inputs.pll_background_color_transparent.onclick =
			this.inputs.pll_text_box_padding.onchange = this.inputs.pll_thumb_show_title.onclick = this.inputs.pll_thumb_show_author.onclick =
			this.inputs.pll_thumb_show_rating.onclick = this.inputs.pll_thumb_show_length.onclick = this.inputs.pll_thumb_show_description.onclick =
			this.inputs.pll_thumb_show_views.onclick = 	this.inputs.pll_thumb_show_labels.onclick = this.inputs.pll_title_cut_two_lines.onclick =
			this.inputs.pll_use_alt_background_color.onclick = this.updatePlaylistFontsExample.bind(this);
		this.inputs.pll_show_hint.onclick = this.onPllShowHintClick.bindAsEventListener(this);

		this.inputs.pll_thumb_buttons_show.onclick = this.onThumbnailControlsClick.bindAsEventListener(this);

		// some ads stuff
		this.inputs.pre_roll_playlist.onchange = this.onPrerollListChange.bindAsEventListener(this);
		//this.inputs.pre_roll_ad_show.onclick = this.onPrerollShowChange.bindAsEventListener(this);
		this.inputs.mid_roll_playlist.onchange = this.onMidrollListChange.bindAsEventListener(this);
		//this.inputs.mid_roll_ad_show.onclick = this.onMidrollShowChange.bindAsEventListener(this);
		this.inputs.post_roll_playlist.onchange = this.onPostrollListChange.bindAsEventListener(this);
		//this.inputs.post_roll_ad_show.onclick = this.onPostrollShowChange.bindAsEventListener(this);

		// load the themes select box
		this.inputs.theme.innerHTML = '';
		this.inputs.prev_next_button_style.innerHTML = '';
		for (var i = 0, n = ThemesChooser.themes.length; i < n; i ++) {
			if (ThemesChooser.themes[i].filesName) {
				var opt = document.createElement ('option');
				opt.innerHTML = opt.value = ThemesChooser.themes[i].name;
				this.inputs.theme.appendChild(opt);
				this.inputs.prev_next_button_style.appendChild(opt.cloneNode(true));
			} else {
				var optgr = document.createElement ('optgroup');
				optgr.label = ThemesChooser.themes[i].name;
				for (var j = 0, k = ThemesChooser.themes[i].subthemes.length; j < k; j ++) {
					var opt = document.createElement ('option');
					opt.value = ThemesChooser.themes[i].subthemes[j].name;
					opt.innerHTML = ThemesChooser.themes[i].subthemes[j].name;
					optgr.appendChild(opt);
				}
				this.inputs.theme.appendChild(optgr);
				this.inputs.prev_next_button_style.appendChild(optgr.cloneNode(true));
			}
		}

		//this.inputs.prev_next_button_style.innerHTML = this.inputs.theme.innerHTML;

		/*var s = Cookies.getValue ('emb_box_s', '');
		if (s != '') {
			var ch = s.split(',');
			this.listBox.style.width = parseInt(ch[0]) + "px";
			var nh = parseInt(ch[1]);
			this.listBox.style.height = nh + "px";
			this.listBoxScrollContainer.style.height = this.listBoxContent.style.height = (nh-100) + "px";
			this.listBox.style.left = parseInt(ch[2]) + "px";
			this.listBox.style.top = parseInt(ch[3]) + "px";
		}*/

		this.tabDS = $('embed_tab_ds');
		this.tabGeneral = $('embed_tab_general');
		this.tabTypeDetails = $('embed_tab_type_details');
		this.tabPlayer = $('embed_tab_player');
		this.tabPlaylist = $('embed_tab_playlist');
		this.tabAds = $('embed_tab_ads');
		this.tabTracking = $('embed_tab_tracking');
		this.tabGeneral.style.display = this.tabTypeDetails.style.display = this.tabPlayer.style.display = this.tabPlaylist.style.display = this.tabAds.style.display = this.tabTracking.style.display = 'none';
	},

	EMBED_SAVED_LIST: 1,
	EMBED_RUNTIME_LIST: 2,
	EMBED_SEARCH_RESULTS: 3,
	EMBED_FAVORITES: 4,
	EMBED_USER_CHANNEL: 5,
	EMBED_STANDARD_FEED: 6,
	EMBED_SINGLE_VIDEO: 7,
	EMBED_EXTERNAL_PLAYLIST: 8,
	EMBED_YOUTUBE_PLAYLIST: 9,

	open: function (type, jsonObj) {
		if (!user_name) {
			//alert ('You have to register or log in to embed videos!');
			showLoginOrRegisterForm();
			return;
		}

		if (!UserLimits.isUserAllowedTo(UserLimits.ua_create_custom_player, true))
			return false;

		showBackground();

		this.edittedPlayer = null;
		this.formDiv.style.display = '';
		this.showTab('DS');

	// default the options
		this.inputs.videos_count.value = '10';
		this.inputs.channel_videos_count.value = '10';
		this.codeDiv.style.display = 'none';
		this.element.style.display = 'block';
		this.codeArea.value = '';

		this.inputs.only_public.checked = true;
		this.inputs.mark_private.checked = true;
		this.inputs.email_on_delete.checked = true;
		this.inputs.reverse_playlist.checked = false;

		this.inputs.player_name.value = '';
		this.inputs.playlist_name.value = '';
		this.inputs.description.value = '';
		this.inputs.size.selectedIndex = 2;
		this.inputs.listbox_width.value = '264';
		this.inputs.listbox_height.value = '326';
		this.inputs.thumbs_rows.value = '3';
		this.inputs.thumbs_cols.value = '2';
		this.inputs.thumbs_text_box_padding.value = 3;
		this.inputs.player_placement.selectedIndex = 0;
		this.inputs.thumbnails_size.selectedIndex = 2;
		this.inputs.embed_type.setSelected(1);
		this.onEmbedTypeChange();
		this.inputs.playlist_type.setSelected(1);
		this.inputs.new_playlist_name.value = '';
		this.inputs.standard_feed.setSelected ('featured');
		this.inputs.standard_feed_videos_count.value = '10';

		this.form.youtube_playlist_url.value = '';
		this.inputs.external_playlist_url.value = '';
		this.inputs.external_playlist_interval.value = '360';

		this.inputs.playlist_enabled.checked = true;
		this.inputs.info_enabled.checked = false;
		this.inputs.playlist_visible.checked = false;
		this.inputs.info_visible.checked = false;
		this.inputs.autostart.checked = false;

		this.inputs.repeat.checked = false;
		this.inputs.shuffle.checked = false;

		this.inputs.show_title.checked = true;
		this.inputs.uploader_in_title.checked = false;
		this.inputs.video_name_in_title.checked = true;

		//this.inputs.show_download_button.checked = true;
		this.inputs.show_url_button.checked = true;
		this.inputs.show_youtube_button.checked = true;
		this.inputs.show_rating.checked = true;
		this.inputs.show_addthis_button.checked = true;
		this.inputs.addthis_username.value = '';
		this.onShowAddthisChange();

		this.form.show_more_tab.checked = true;
		this.form.show_related_tab.checked = true;
		this.form.show_description_tab.checked = true;
		this.form.show_comments_tab.checked = true;
		this.form.show_profile_tab.checked = true;

		this.inputs.thumbnail_text_show.checked = false;
		this.inputs.thumbnail_text_sel.setSelected('R');
		this.getThumbTextPosition();

		this.inputs.thumb_show_title.checked = true;
		this.inputs.thumb_show_author.checked = false;
		this.inputs.thumb_show_rating.checked = false;
		this.inputs.thumb_show_length.checked = true;
		this.inputs.thumb_show_description.checked = false;
		this.inputs.thumb_show_views.checked = false;
		this.inputs.thumb_show_labels.checked = true;
		this.inputs.thumb_text_cut_title_two_lines.checked = false;
		this.inputs.thumb_text_box_size.value = '100';

		this.backgroundColorPicker.setColor (this.backgroundColorPicker.defaultColor);
		this.inputs.background_color_transparent.checked = false;
		this.altBackgroundColorPicker.setColor (this.altBackgroundColorPicker.defaultColor);
		this.inputs.alt_background_color_transparent.checked = false;
		this.titleFontPicker.setDefaults();
		this.textFontPicker.setDefaults();
		this.labelsFontPicker.setDefaults();

		//this.inputs.theme.setSelected(current_theme);
		this.inputs.theme.selectedIndex = 0;
		this.imagesSelector.setOptions('player_background', {selectedImage: ''});

		this.form.player_logo_url.value = 'http://www.idesktop.tv/';
		this.form.theme.selectedIndex = 0;

		this.form.hash.value = "";
		this.inputs.data_source_type.value = this.dataSourceType = type;

		this.imagesSelector.setOptions('player_logo', {selectedImage: ''});
		this.imagesSelector.setOptions('title_logo', {selectedImage: ''});
		this.inputs.player_title_bar_image_align.setSelected('R');
		this.inputs.player_title_bar_image_url.value = "http://www.idesktop.tv/";
		this.inputs.player_title_bar_back.setSelected('H');
		this.onPlayerTitleBarBackgroundChange();
		this.playerTitleFontPicker.setEmpty();

		this.inputs.player_info_back_sel.setSelected ('T');
		this.inputs.player_info_btn_back_sel.setSelected ('H');
		this.inputs.player_info_btn_color_sel.setSelected ('H');
		this.infoPanelBackgroundColor.setColor(this.infoPanelBackgroundColor.defaultColor);
		this.infoPanelFont.setEmpty();
		this.infoPanelButtonBackgroundColor.setColor(this.infoPanelButtonBackgroundColor.defaultColor);
		this.infoPanelButtonFontColor.setColor(this.infoPanelButtonFontColor.defaultColor);

		this.onPlayerInfoPanelBackgroundSelectChange();
		this.onPlayerInfoPanelTabButtonBackgroundChange();
		this.onPlayerInfoPanelTabButtonFontColorChange();

		this.embBackgroundColorPicker.setColor(this.embBackgroundColorPicker.defaultColor);
		this.imagesSelector.setOptions('embed_background_image', {selectedImage: ''});
		this.imagesSelector.setOptions('autostart_preimage', {selectedImage: ''});
		this.inputs.emb_background_sel.setSelected('T');

		//this.inputs.prev_next_button_style.setSelected(current_theme);
		this.inputs.prev_next_button_style.selectedIndex = 0;
		this.inputs.show_prev_next_buttons.checked = true;

		this.inputs.popout_button_type.setSelected ('T');
		this.inputs.popout_button_text.value = 'Open player';
		this.imagesSelector.setOptions('popout_button', {selectedImage: ''});

	/* playlist settings defaults */
		this.inputs.pll_width.value = 140;
		this.inputs.pll_thumb_size.setSelected ("130x100");
		this.inputs.pll_thumb_width.value = 130;
		this.inputs.pll_thumb_height.value = 100;
		this.inputs.pll_columns.value = 1;

		this.inputs.pll_thumbnail_text_show.checked = false;
		this.inputs.pll_thumbnail_text_sel.setSelected ('R');
		this.getPlaylistThumbTextPosition();

		this.inputs.pll_thumb_text_box_size.value = 60;
		this.inputs.pll_text_box_padding.value = 3;

		this.inputs.pll_thumb_show_title.checked = true;
		this.inputs.pll_thumb_show_author.checked = false;
		this.inputs.pll_thumb_show_rating.checked = false;
		this.inputs.pll_thumb_show_length.checked = true;
		this.inputs.pll_thumb_show_description.checked = false;
		this.inputs.pll_thumb_show_views.checked = false;
		this.inputs.pll_thumb_show_labels.checked = true;

		this.pllTitleFontPicker.setDefaults();
		this.pllTextFontPicker.setDefaults();
		this.pllLabelsFontPicker.setDefaults();

		this.inputs.pll_background_color_transparent.checked = false;
		this.pllBackgroundColorPicker.setColor (this.pllBackgroundColorPicker.defaultColor);
		this.inputs.pll_alt_background_color_transparent.checked = false;
		this.pllAltBackgroundColorPicker.setColor (this.pllAltBackgroundColorPicker.defaultColor);

		this.inputs.pll_use_alt_background_color.checked = false;
		this.inputs.pll_show_play_controls.checked = true;

		this.inputs.pll_thumb_buttons_show.checked = false;
		this.inputs.pll_thumb_buttons_sel.setSelected ('TL');
		this.onThumbnailControlsClick();
		
		this.pllThumbsBackgroundColorPicker.setColor (this.pllThumbsBackgroundColorPicker.defaultColor);

		this.inputs.pll_show_hint.checked = true;
		this.inputs.pll_hint_show_title.checked = true;
		this.inputs.pll_hint_show_author.checked = true;
		this.inputs.pll_hint_show_length.checked = true;
		this.inputs.pll_hint_show_views.checked = true;
		this.inputs.pll_hint_show_rating.checked = true;
		this.inputs.pll_hint_show_votes.checked = true;

		this.inputs.pll_title_cut_two_lines.checked = true;

		this.imagesSelector.setOptions('playlist_logo', {selectedImage: ''});
		this.inputs.pll_playlist_logo_link.value = 'http://www.idesktop.tv/';
		this.inputs.pll_playlist_logo_placement.setSelected ('R');
		this.inputs.pll_show_prev_next_buttons.checked = true;

		if (type == this.EMBED_SAVED_LIST) {
			this.jsonArr = {};
			this.playlistID = jsonObj.id;
			this.fillDSSelectors();
			this.inputs.data_source.setSelected (type);
			this.inputs.saved_playlist.setSelected(jsonObj.id);
			$('embed_vs_type_2').style.display = 'none';
		} else
		if (type == this.EMBED_RUNTIME_LIST) {
			this.jsonArr = jsonObj;
			this.fillDSSelectors();
			$('embed_vs_type_2').style.display = '';
		} else
		if (type == this.EMBED_SINGLE_VIDEO) {
			this.jsonArr = jsonObj;
			this.fillDSSelectors();
			$('embed_vs_type_2').style.display = 'none';
			//$('embed_single_video_title').innerHTML = jsonObj.title;
			this.form.embed_single_video_url.value = 'http://www.idesktop.tv/?watch=' + jsonObj.id;
		} else {
			type = this.EMBED_STANDARD_FEED;
			this.fillDSSelectors();
			this.jsonArr = {feed:'favorites',count:10};
			$('embed_vs_type_2').style.display = 'none';
		}
		$('embed_vs_type_2_sep').style.display = $('embed_vs_type_2').style.display;

		this.inputs.data_source.setSelected (type);
	/* advertisement settings */
		this.inputs.pre_roll_ad_show.checked = false;
		this.inputs.pre_roll_video_r.setSelected ('R');
		this.onPrerollShowChange();
		this.inputs.mid_roll_ad_show.checked = false;
		this.inputs.mid_roll_video_r.setSelected ('R');
		this.inputs.mid_roll_show_every.value = '1';
		this.onMidrollShowChange();
		this.inputs.post_roll_ad_show.checked = false;
		this.inputs.post_roll_video_r.setSelected ('R');
		this.onPostrollShowChange();
		this.onSizeChange(); // just in case ;)
		this.onShowTitleChange();
		this.getEmbedTypeID();

		this.inputs.ads_caption.value = '';
		this.inputs.ads_disable_controls.checked = true;

		this.inputs.ga_id.value = '';
		this.inputs.ga_page_url.value = '';
		this.inputs.ga_events_category.value = '';

		this.getEmbedPlaylistTypeID();
		this.recalculatePlaylistSizes();
		this.onDataSourceChange();
		this.onShowOnlyPublicChange();

		this.onAutostartChange();

		if (this.listOpened)
			this.listBox.style.display = '';

		this.setUserPayPlanLimits();
	},
	getEmbedTypeID: function ()  {
		var res = parseInt(this.inputs.embed_type.getSelected());
		$('embed_listbox_size_selectors').style.display = (res == 3 || res == 4 || res == 5?'':'none');
		$('embed_thumbnail_text_position').style.display = (res == 3 || res == 4?'':'none');
		$('embed_thumbnail_text_selectors').style.display = (res == 3 || res == 4 || res == 5?'':'none');
		$('embed_player_placement_selector').style.display = (res != 1 && res != 6?'':'none');
		$('embed_fixedbox_autostart_selector').style.display = (res == 1 || res == 6?'':'none');
		$('autostart_off_preimage_option').style.display = ((res != 1 && res != 6) || this.form.autostart.checked?'none':'');
		$('embed_alt_background_color_selection').style.display = (res == 3 || res == 4?'':'none');
		$('embed_box_buttons').style.display = (res == 3 || res == 5?'':'none');
		$('embed_show_prev_next_buttons').style.display = (res == 3 || res == 5?'':'none');
		$('embed_prev_next_button_show_inp_lbl').style.display = (res == 3?'':'none');
		$('embed_playlist_type_selectors').style.display = (res != 6?'':'none');
		$('embed_player_playlist_options_select').style.display = (res != 6?'':'none');
		$('embed_player_info_options_select').style.display = (res != 6?'':'none');
		$('embed_player_title_bar_select').style.display = (res != 6?'':'none');
		$('embed_player_buttons_select').style.display = (res != 6?'':'none');
		$('embed_player_custom_logo_select').style.display = (res != 6?'':'none');
		$('embed_player_theme_select_bi1').style.display = $('embed_player_theme_select_bi2').style.display = (res != 6?'':'none');

		if (res == 5) {
			this.inputs.show_prev_next_buttons.checked = true;
			$('embed_prev_next_buttons_style_tr').style.display = '';
		}
		if (res == 6)
			$('embed_info_tabs_cbs').style.display = $('embed_info_btns_sel').style.display = 'none';
		else {
			$('embed_info_tabs_cbs').style.display = $('embed_info_btns_sel').style.display = ((this.inputs.info_enabled.checked || this.inputs.info_visible.checked)?'':'none');
		}

		$('embed_popuout_button').style.display = (res == 2?'':'none');
		$('embed_box_design').style.display = (res == 3 || res == 4 || res == 5?'':'none');
		if (res == 4) {
			$('embed_listbox_colums').style.display = 'none';
			$('embed_listbox_rows').style.display = '';
			this.inputs.thumbs_cols.value = '1';
			$('embed_listbox_height').style.display = '';
		} else if (res == 5) {
			this.inputs.thumbnail_text_sel.setSelected ('R');
			$('embed_listbox_colums').style.display = 'none';
			$('embed_listbox_rows').style.display = 'none';
			$('embed_listbox_height').style.display = 'none';
			this.inputs.thumbs_cols.value = '1';
			this.inputs.thumbs_rows.value = '1';
		} else {
			$('embed_listbox_colums').style.display = '';
			$('embed_listbox_rows').style.display = '';
			$('embed_listbox_height').style.display = '';
		}
		$('embed_listbox_height_label').style.display = $('embed_listbox_height').style.display;
		$('embed_listbox_colums_label').style.display = $('embed_listbox_colums').style.display;
		$('embed_listbox_rows_label').style.display = $('embed_listbox_rows').style.display;
		//$('embed_player_type_select_example').src = "/images/embed_form_examples/player_" + res + ".gif";
		this.fixGeneralPreviewImages();

		if (arguments.length == 0) this.recalculateListboxSizes();

		this._embedSettingsTabDisabled = false;
		this._playlistSettingsTabDisabled = false;
		switch (res) {
			case 1: this._embedSettingsTabDisabled = true; break;
			case 2:	$('embed_settings_tab_header').innerHTML = 'popout box settings';  break;
			case 3:
				$('embed_type_label_box_width').innerHTML = 'Wall';
				$('embed_type_label_box_background').innerHTML = 'Wall';
				$('embed_settings_tab_header').innerHTML = 'video wall settings';
				break;
			case 4:
				$('embed_type_label_box_width').innerHTML = 'List box';
				$('embed_type_label_box_background').innerHTML = 'List box';
				$('embed_settings_tab_header').innerHTML = 'list box settings';
				break;
			case 5:
				$('embed_type_label_box_width').innerHTML = 'Horizontal box';
				$('embed_type_label_box_background').innerHTML = 'Horizontal box';
				$('embed_settings_tab_header').innerHTML = 'horizontal box settings';
				break;
			case 6:
				this._embedSettingsTabDisabled = true;
				this._playlistSettingsTabDisabled = true;
				break;

		}

		$('embed_settings_tab_header_separator').style.display = $('embed_settings_tab_header').style.display = (this._embedSettingsTabDisabled?'none':'');
		$('embed_settings_playlist_tab_header').style.display = (this._playlistSettingsTabDisabled?'none':'');

		return res;
	},
	fillDSSelectors: function () {
		this.form.data_source[0].checked = true;
		if (!this.jsonArr) this.jsonArr = {keywords:'', channel:'', category: 0, order_by: 0};
		this.form.embed_search_keyword.value = this.jsonArr.keywords || '';
		this.form.embed_search_user_channel.value = this.jsonArr.channel || '';
		this.form.embed_single_video_url.value = '';
		$('check_user_channel_name_button').innerHTML = 'check name';
		$('check_single_video_url_button').innerHTML = 'check URL';
		for (var i = 0; i < this.form.embed_search_category.options.length; i ++)
			if (this.form.embed_search_category.options[i].value == this.jsonArr.category) {
				this.form.embed_search_category.options[i].selected = true;
				break;
			}
		for (var i = 0; i < this.form.embed_search_order_by.options.length; i ++)
			if (this.form.embed_search_order_by.options[i].value == this.jsonArr.order_by) {
				this.form.embed_search_order_by.options[i].selected = true;
				break;
			}
		// fill playlists
		this.inputs.saved_playlist.innerHTML = '';
		this.inputs.pre_roll_playlist.innerHTML = '';
		this.inputs.mid_roll_playlist.innerHTML = '';
		this.inputs.post_roll_playlist.innerHTML = '';
		if (SavedPlaylists.playlists.length > 0) {
			for (var i = 0; i < SavedPlaylists.playlists.length; i ++) {
				var opt = document.createElement('option');
				opt.value = SavedPlaylists.playlists[i].jsonObj.id;
				opt.innerHTML = SavedPlaylists.playlists[i].jsonObj.name + ' (' + SavedPlaylists.playlists[i].jsonObj.videos.length + ')';
				this.inputs.saved_playlist.appendChild(opt);

				var opt1 = opt.cloneNode(true);
				this.inputs.pre_roll_playlist.appendChild(opt1);
				var opt2 = opt.cloneNode(true);
				this.inputs.mid_roll_playlist.appendChild(opt2);
				var opt3 = opt.cloneNode(true);
				this.inputs.post_roll_playlist.appendChild(opt3);
			}

			/*this.inputs.mid_roll_playlist.innerHTML =
				this.inputs.pre_roll_playlist.innerHTML =
				this.inputs.post_roll_playlist.innerHTML =
				this.inputs.saved_playlist.innerHTML;*/

			this.inputs.pre_roll_playlist.selectedIndex = 0;
			this.inputs.mid_roll_playlist.selectedIndex = 0;
			this.inputs.post_roll_playlist.selectedIndex = 0;
		}
		var opt = this.inputs.data_source.getOptionWithValue(this.EMBED_SAVED_LIST);
		opt.disabled = this.inputs.saved_playlist.disabled =
			this.inputs.pre_roll_ad_show.disabled = this.inputs.mid_roll_ad_show.disabled =
			this.inputs.post_roll_ad_show.disabled = (SavedPlaylists.playlists.length > 0?false:true);
		$('embed_tab_ads_no_playlists_message').style.display = SavedPlaylists.playlists.length > 0?'none':'block';

		this.onPrerollListChange();
		this.onMidrollListChange();
		this.onPostrollListChange();
	},

	close: function () {
		hideBackground();
		this.element.style.display = 'none';
		if (this.listOpened) {
			if (this._updatePlayersList)
				this.openList(this.listOrderedBy, true);
			else {
				showBackground();
				this.listBox.style.display = 'block';
			}
		} else
			this.loadEmbeddedPlayers();
	},
	onClickOK: function () {
		var params = {};
		var ds = parseInt(this.inputs.data_source.getSelected());
		this.inputs.data_source_type.value = this.dataSourceType = ds;
		var videosCount;
		switch (ds) {
			case this.EMBED_SEARCH_RESULTS: {
				var kw = this.form.embed_search_keyword.value;
				if (!kw) {
					this.showTab('DS');
					alert ('Please enter keywords to search for');
					return false;
				}
				var vc = parseInt(this.inputs.videos_count.value);
				if (vc < 1 || vc > 50 || this.inputs.videos_count.value == '') {
					this.showTab('DS');
					alert ('Please enter valid number between 0 and 50 for videos count');
					return false;
				}
				this.jsonArr = {keywords: this.form.embed_search_keyword.value,
					list_by: (this.form.embed_search_category.value == 0?'by_tag':'by_category_and_tag'),
					order_by: this.form.embed_search_order_by.value,
					category: this.form.embed_search_category.value}
				videosCount = this.form.videos_count.value;
				break;
			}
			case this.EMBED_SAVED_LIST: {
				this.jsonArr = {};
				this.playlistID = this.form.saved_playlist.options[this.form.saved_playlist.selectedIndex].value;
				if (!this.edittedPlayer || this.edittedPlayer.jsonObj.ds != ds) {
					this.inputs.playlist_name.value = SavedPlaylists.getListById(this.form.saved_playlist.options[this.form.saved_playlist.selectedIndex].value).name;
				}
				videosCount = SavedPlaylists.getListById(this.form.saved_playlist.options[this.form.saved_playlist.selectedIndex].value).videos.length;
				break;
			}
			case this.EMBED_FAVORITES: {
				this.jsonArr = {};
				this.inputs.playlist_name.value = 'My Favorites';
				videosCount = Favorites.favorites.length;
				break;
			}
			case this.EMBED_RUNTIME_LIST: {
				this.inputs.playlist_name.value = '';
				videosCount = this.jsonArr.length;
				break;
			}
			case this.EMBED_USER_CHANNEL: {
				if (!this.form.embed_search_user_channel.value) {
					this.showTab('DS');
					alert ('Please enter name of user or channel!');
					return false;
				}
				var vc = parseInt(this.inputs.channel_videos_count.value);
				if (vc < 1 || vc > 50 || this.inputs.channel_videos_count.value == '') {
					this.showTab('DS');
					alert ('Please enter enter valid number from 1 to 50 for videos count!');
					return false;
				}
				this.jsonArr = {channel: this.form.embed_search_user_channel.value, resultsCount: this.inputs.channel_videos_count.value};
				break;
			}
			case this.EMBED_STANDARD_FEED: {
				var vc = parseInt(this.inputs.standard_feed_videos_count.value);
				if (vc < 1 || vc > 50 ||  this.inputs.standard_feed_videos_count.value == '') {
					this.showTab('DS');
					alert ('Please enter valid number between 0 and 50 for videos count');
					return false;
				}
				this.jsonArr = {feed: this.inputs.standard_feed.getSelected(), count:this.inputs.standard_feed_videos_count.value};
				break;
			}
			case this.EMBED_SINGLE_VIDEO: {
				var id = this.getSingleVideoID();
				if (!id) {
					alert ('Please enter valid YouTube video ID!')
					this.showTab('DS');
					return false;
				}
				// Why? Because jsonArr might contain the rest of the information about the video, not just the ID
				if (this.jsonArr.id != id)
					this.jsonArr = {id: id};
				break;
			}
			case this.EMBED_EXTERNAL_PLAYLIST: {
				if (!this.inputs.external_playlist_url.value) {
					this.showTab('DS');
					alert ('Please enter XML playlist location!');
					return false;
				}
				if (!this.inputs.external_playlist_interval.value) {
					this.showTab('DS');
					alert ('Please select interval to update the playlist!');
					return false;
				}
				if (!parseInt(this.inputs.external_playlist_interval.value)) {
					this.showTab('DS');
					alert ('Please eter valid interval of playlist update!');
					return false;
				}
				if (parseInt(this.inputs.external_playlist_interval.value) < 30) {
					this.showTab('DS');
					alert ('The playlist update interval cannot be less than 30 minutes!');
					return false;
				}
				this.jsonArr = {};
				break;
			}
			case this.EMBED_YOUTUBE_PLAYLIST:
				var url = this.form.youtube_playlist_url.value;
				if (!url) {
					this.showTab('DS');
					alert ('Please enter YouTube Playlist URL!');
					return false;
				}
				var regex = /youtube.*\/view_play_list\?p=(.{16})(&.*)?/;
				var chunk;
				if (! regex.test(url)) {
					var regex2 = /youtube.*\/user\/[^\/]*#[a-z]\/[a-z]\/(.{16})/; // */
					if (! regex2.test(url)) {
						this.showTab('DS');
						alert ('The specified YouTube Playlist URL is not valid');
						return false;
					} else {
						chunk = regex2.exec(url);
					}
				} else 
					chunk = regex.exec(url);
				var id = chunk[1];
				this.jsonArr = {id: id};
				break;
			default : {
				this.showTab('DS');
				alert ('Please select videos to embed');
				return false;
			}
		}

		if (!this.isSizeMenuCustom()) {
			var a = this.inputs.size.getSelected().split("x");
			this.inputs.width.value = parseInt(a[0]);
			this.inputs.height.value = parseInt(a[1]);
		}

		params.embed_type = this.getEmbedTypeID();

		var pw = parseInt(this.inputs.width.value);
		var ph = parseInt(this.inputs.height.value);
		if (this.inputs.width.value == '' || this.inputs.height.value == '') {
			this.showTab ('Player');
			alert ("Please enter player size");
			return false;
		}
		var minHeight = 150;
		if (params.embed_type < 6) {
			if (this.inputs.info_enabled.checked || this.inputs.info_visible.checked) {
				minHeight = 250;
				// check the selected info panels
				if (!this.isPlayerBigEnoughForInfoPanel()) {
					alert ("Player size is too small to fit the selected info panel options\nPlease increase the player width");
					return false;
				}
			}
		}
		if (pw < 150 || ph < minHeight) {
			this.showTab ('Player');
			alert ("Player size is too small. Please increase it\nMinimum allowed is 150 by 150");
			return false;
		}
		if (pw > 2500 || ph > 2000) {
			this.showTab ('Player');
			alert ("Player size is too large. Please decrease it\nMaximum allowed is 2500 by 2000");
			return false;
		}
		if (this.inputs.show_addthis_button.checked && (pw < 320 || ph < 380)) {
			this.showTab('Player');
			alert("Player size is too small to use AddThis button. Must be at least 320px wide and 380px high.\n" +
				"Please increase the player size or turn off the AddThis button");
			return false;
		}

		var w = this.updateMaximumLogoSize();
		var minNeededWidth = UserLimits.isUserAllowedTo(UserLimits.ua_remove_idesktop_branding) ? 0 : 28;
		if (w < minNeededWidth) { // in which case there is simply not enough space for the buttons
			this.showTab ('Player');
			alert ("Player size is too small to fit all the selected buttons!\nPlease increase the player width");
			return false;
		}


		if (!params.embed_type) {
			this.showTab('General');
			alert ('Please select embed type!');
			return false;
		}
		if (this.inputs.player_name.value == '') {
			this.showTab('General');
			alert ('Please specify a name for the player!');
			return false;
		}
		if (!this.form.show_description_tab.checked && !this.form.show_comments_tab.checked && !this.form.show_profile_tab.checked &&
			//!this.form.show_more_tab.checked && !this.form.show_related_tab.checked &&
			(this.form.info_enabled.checked || this.form.info_visible.checked)) {
				this.showTab('Player');
				alert ('Please, selected at least one tab (comments, description or profile) for the info panel or hide and disable it!');
				return false;
			}

		if (params.embed_type == 3) { // check sizes!
			var ss = this.recalculateListboxSizes();
			if (ss.r < 1 || ss.c < 1) {
				this.showTab('TypeDetails');
				alert ("The selected size for the video wall is too small to contain thumbnail of a video!\n" +
					"Please select smaller thumbnail size, increase the box size or increase the rows/columns count.");
				return false;
			}
		} else if (params.embed_type == 4) { // check sizes!
			var ss = this.recalculateListboxSizes();
			if (ss.r < 1) {
				this.showTab('TypeDetails');
				alert ("The selected size for the list box is too small to contain thumbnail of a video!\n" +
					"Please select smaller size for the video thumbnails, increase the box size or increase the rows count.");
				return false;
			}
		}
		if (params.embed_type == 2) {
			var pbt = this.inputs.popout_button_type.getSelected();
			if (pbt == 'I') {
				if (!this.imagesSelector.getSelected('popout_button')) {
					alert ('Please, enter popout button image!');
					this.showTab ('TypeDetails');
					return false;
				}
			} else if (pbt == 'T') {
				if (this.inputs.popout_button_text.value == '') {
					this.showTab ('TypeDetails');
					alert ('Please, enter popout button text!');
					return false;
				}
			}
		}
		if (this.form.previewmode.value != 'true' && this.edittedPlayer && this.edittedPlayer.jsonObj.type != this.getEmbedTypeID()) {
			if (!confirm("Are you sure you want to change the embed type?\n" +
				"Changing the embed type requires modification of the embed code, otherwise it may not work!")) {
					return false;
				}
		}

		var jsonString;
		if (this.dataSourceType == this.EMBED_SAVED_LIST) {
			jsonString = '{id: ' + this.playlistID + '}';
		} else if (this.dataSourceType == this.EMBED_SEARCH_RESULTS) {
			var jsonObj = this.jsonArr;
			delete (jsonObj.videos);
			jsonObj.resultsCount = this.inputs.videos_count.value;
			jsonString = $toString(jsonObj);
		} else if (this.dataSourceType == this.EMBED_RUNTIME_LIST) {
			var jsonArr = new Array();
			var ispreview = (this.form.previewmode.value == 'true');
			for (var i = 0; i < this.jsonArr.length; i ++) {
				this.jsonArr[i].comments = null;
				this.jsonArr[i].comments_count = null;
				if (ispreview)
					jsonArr.push(VideoToJSONString(this.jsonArr[i]));
				else
					jsonArr.push(this.jsonArr[i].id + '|' + (this.jsonArr[i].isprivate?'1':'0') + '|' + VideoToJSONString(this.jsonArr[i]));
			}
			// we need somehow to post the separate jsonObj-ects for each video so the PHP script can store them acordingly...
			//jsonString = '[' + jsonArr.join(',') + ']';
			jsonString = jsonArr.join("\n");

		} else if (this.dataSourceType == this.EMBED_FAVORITES) {
			jsonString = '{}';
		} else if (this.dataSourceType == this.EMBED_USER_CHANNEL) {
			var jsonObj = this.jsonArr;
			delete (jsonObj.videos);
			jsonString = $toString(jsonObj);
		} else if (this.dataSourceType == this.EMBED_STANDARD_FEED) {
			var jsonObj = this.jsonArr;
			delete (jsonObj.videos);
			jsonString = $toString(jsonObj);
		} else if (this.dataSourceType == this.EMBED_SINGLE_VIDEO) {
			jsonString = $toString(this.jsonArr);
		} else if (this.dataSourceType == this.EMBED_EXTERNAL_PLAYLIST) {
			jsonString = "{}";
			if (!UserLimits.isUserAllowedTo(UserLimits.ua_set_external_playlist, false)) {
				alert ('Warning: You have selected External Playlist as source of the videos for the player. ' +
						'You will be allowed to play around with it – save, edit and preview the player, but ' +
						'you cannot publish it. The player will load only from your account. ' + "\n\n" +
						'The External Playlist feature is fully available only for Business Max users!');
			}
		} else if (this.dataSourceType == this.EMBED_YOUTUBE_PLAYLIST) {
			jsonString = $toString(this.jsonArr);
		}

		this.inputs.player_title_bar_background.value = (this.inputs.player_title_bar_back.getSelected() != 'C'?this.inputs.player_title_bar_back.getSelected(): this.playerTitleBackgroundColorPicker.currentColor);

		this.inputs.player_info_panel_back.value = (this.inputs.player_info_back_sel.getSelected() != 'C' ? this.inputs.player_info_back_sel.getSelected() : this.infoPanelBackgroundColor.currentColor );
		this.inputs.player_info_panel_buttons_back.value = (this.inputs.player_info_btn_back_sel.getSelected() != 'C' ? this.inputs.player_info_btn_back_sel.getSelected() : this.infoPanelButtonBackgroundColor.currentColor);
		this.inputs.player_info_panel_buttons_color.value = (this.inputs.player_info_btn_color_sel.getSelected() != 'C' ? this.inputs.player_info_btn_color_sel.getSelected() : this.infoPanelButtonFontColor.currentColor );

		this.inputs.popout_box_button.value = (this.inputs.popout_button_type.getSelected() == 'T'? 'T' + this.inputs.popout_button_text.value : 'I' + this.imagesSelector.getSelected('popout_button'));

		this.inputs.pll_thumb_buttons.value = (this.inputs.pll_thumb_buttons_show.checked?this.inputs.pll_thumb_buttons_sel.getSelected():'N');

		this.inputs.pll_thumbnail_text.value = this.getPlaylistThumbTextPosition();

		switch (this.inputs.emb_background_sel.getSelected()) {
			case 'T' : this.inputs.embed_background.value = 'T'; break;
			case 'C' :
				this.inputs.embed_background.value = 'C' + this.embBackgroundColorPicker.currentColor;
				break;
			case 'I' :
				var img = this.imagesSelector.getSelected ('embed_background_image');
				if (!img)  {
					alert ('Please select image for the box background');
					return false;
				}
				this.inputs.embed_background.value = 'I' + img;
				break;
			default:
				alert ('Please select box background!');
				return false;
		}

		// ADS
		this.inputs.pre_roll_list.value = this.inputs.pre_roll_ad_show.checked ? this.inputs.pre_roll_playlist.getSelected() : '';
		this.inputs.pre_roll_ad.value = this.inputs.pre_roll_video_r.getSelected() == 'R' ? '' : this.inputs.pre_roll_video_sel.getSelected();
		this.inputs.mid_roll_list.value = this.inputs.mid_roll_ad_show.checked ? this.inputs.mid_roll_playlist.getSelected() : '';
		this.inputs.mid_roll_ad.value = this.inputs.mid_roll_video_r.getSelected() == 'R' ? '' : this.inputs.mid_roll_video_sel.getSelected();
		this.inputs.post_roll_list.value = this.inputs.post_roll_ad_show.checked ? this.inputs.post_roll_playlist.getSelected() : '';
		this.inputs.post_roll_ad.value = this.inputs.post_roll_video_r.getSelected() == 'R' ? '' : this.inputs.post_roll_video_sel.getSelected();

		this.inputs.jsonObj.value = jsonString;

		$('saving_embedded_player').style.display = 'block';
		return true;
	},

	onPlayerSaved: function (response) {
		var t = response;
		$('saving_embedded_player').style.display = '';
		if (this.edittedPlayer)
			this.elementHeader.innerHTML = 'Edit custom player - ';
		else
			this.elementHeader.innerHTML = 'Create custom player - ';
		this.elementHeader.innerHTML += 'Get the code of your player';

		if (!t.error) {
			t.code = t.code.replace(/&lt;/g, "<").replace(/&gt;/g, ">");
			this.codeArea.value = t.code;
			this.lph = t.h;
			this.formDiv.style.display = 'none';
			this.codeDiv.style.display = 'block';
			this._updatePlayersList = true;
			if (this.dataSourceType == this.EMBED_RUNTIME_LIST)
				SavedPlaylists.loadPlaylists();
		} else {
			if (t.errorID == 2)
				this.showTab('General');
			else if (t.errorID == 3 || t.errorID == 4)
				this.showTab('DS');
			alert (t.error);
		}
	},

	onSizeChange: function () {
		$('embed_player_size_custom').style.display = (this.isSizeMenuCustom()?'':'none');
		this.updateEmbeddedPlayerExample();
	},
	updateEmbeddedPlayerExample: function () {
		this.updateMaximumLogoSize();
		this.recalculatePlaylistSizes(null, 'player');

		$('embed_info_tabs_cbs').style.display = $('embed_info_btns_sel').style.display =
			((this.inputs.info_enabled.checked || this.inputs.info_visible.checked) && this.inputs.embed_type.getSelected() != 6?'':'none');
	},
	getPlayerWidth: function () {
		if (this.isSizeMenuCustom())
			return parseInt(this.inputs.width.value);
		else {
			var a = this.inputs.size.getSelected().split("x");
			return parseInt(a[0]);
		}
	},
	getPlayerHeight: function () {
		if (this.isSizeMenuCustom())
			return parseInt(this.inputs.height.value);
		else {
			var a = this.inputs.size.getSelected().split("x");
			return parseInt(a[1]);
		}
	},
	isPlayerBigEnoughForInfoPanel: function () {
		if (this.inputs.info_enabled.checked || this.inputs.info_visible.checked) {
			var infoPanelWidth = 17;  // right padding!
			if (this.form.show_more_tab.checked) infoPanelWidth += 41;
			if (this.form.show_related_tab.checked) infoPanelWidth += 53;
			if (this.form.show_description_tab.checked) infoPanelWidth += 71;
			if (this.form.show_comments_tab.checked) infoPanelWidth += 110;
			if (this.form.show_profile_tab.checked) infoPanelWidth += 47;
			if (infoPanelWidth == 0) return true;
			var w = this.getPlayerWidth();
			// in w we build the maximum size
			//w -= (this.inputs.playlist_enabled.checked?PLAYLIST_ELEMENT_OPEN_WIDTH:PLAYLIST_ELEMENT_CLOSED_WIDTH);
			if (this.inputs.playlist_enabled.checked || this.inputs.playlist_visible.checked) {
				var playlist_type = this.getEmbedPlaylistTypeID("prevent recursion parameter");
				var playlist_width = parseInt(this.inputs.pll_width.value);
				if (playlist_type == 1) w -= 172;
				if (playlist_type == 2) w -= playlist_width + 58;
				if (playlist_type == 3) w -= playlist_width + 43;
			}
			return (infoPanelWidth < w);
		} else return true;
	},
	updateMaximumLogoSize: function () {
		var w = this.getPlayerWidth();
		// in w we build the maximum size
		//w -= (this.inputs.playlist_enabled.checked?PLAYLIST_ELEMENT_OPEN_WIDTH:PLAYLIST_ELEMENT_CLOSED_WIDTH);
		if (this.inputs.playlist_enabled.checked || this.inputs.playlist_visible.checked) {
			var playlist_type = this.getEmbedPlaylistTypeID("prevent recursion parameter");
			var playlist_width = parseInt(this.inputs.pll_width.value);
			if (playlist_type == 1) w -= 172;
			if (playlist_type == 2) w -= playlist_width + 58;
			if (playlist_type == 3) w -= playlist_width + 43;
		}/* else
			w -= PLAYLIST_ELEMENT_CLOSED_WIDTH;*/

		if (this.inputs.info_enabled.checked)
			w -= (69 + 19); // info button + info panel resize button
		else if (this.inputs.info_visible.checked)
			w -= 19; // just the info panel resize button
		//if (this.inputs.show_download_button.checked) w -= 29;
		if (this.inputs.show_url_button.checked) w -= 29;
		if (this.inputs.show_youtube_button.checked) w -= 52;
		if (this.inputs.show_rating.checked) w -= 55;
		if (this.inputs.show_addthis_button.checked) w -= 38;
		w -= 10; // player padding
		var show_w = Math.max(w, 0);
		$('max_player_logo_size').innerHTML = show_w + ' x 24';
		this.inputs.max_logo_width.value = show_w;
		this.imagesSelector.setOptions('player_logo', {maxImageWidth: show_w});
		return w;
	},
	isSizeMenuCustom: function () {
		return (this.inputs.size.getSelected() == 'custom');
	},

	/* edit*/
	sortList: function (orderBy, load) {
		if (arguments.length == 1)
			var load = true;
		if (this.listOrderedBy != orderBy) {
			Element.removeClassName ($('embed_list_sort_name'), 'current');
			Element.removeClassName ($('embed_list_sort_date'), 'current');
			Element.removeClassName ($('embed_list_sort_type'), 'current');

			switch (orderBy) {
				case 'name' : Element.addClassName ($('embed_list_sort_name'), 'current'); break;
				case 'date'	: Element.addClassName ($('embed_list_sort_date'), 'current'); break;
				case 'type'	: Element.addClassName ($('embed_list_sort_type'), 'current'); break;
			}
			Cookies.setValue('cplsb', orderBy);
			this.listOrderedBy = orderBy;
			if (load)
				this.openList (this.listOrderedBy, true);
		}
	},
	onUserLogOut: function () {
		this.clearPlayersList();
		this.imagesSelector.clearImages();
	},

	onUserLogIn: function () {
		this.loadEmbeddedPlayers();
	},

	openList: function (orderBy, forceReload) {
		if (!user_name) {
			alert ('You must log in first!');
			return false;
		}
		//if (listOpened && this.listOrderedBy == orderBy) return;
		showBackground();
		this.listOpened = true;
		this.listBox.style.display = 'block';
		if (arguments.length == 0)
			var orderBy = this.listOrderedBy || 'date';
		if (arguments.length == 1)
			var forceReload = false;
		if (this.listOrderedBy != orderBy || forceReload) {
			this.listOrderedBy = orderBy;
			this.loadEmbeddedPlayers();
		}
		this.scroll.update();
		if (!this.imagesSelector.imagesLoaded)
			this.imagesSelector.loadImages();
	},
	loadEmbeddedPlayers: function () {
		$('loading_embedded_players').style.display = 'block';
		this.clearPlayersList();
		new Ajax.Request ('/get_embedded_players.php?order=' + this.listOrderedBy, {method:'post', onSuccess: this.loadEmbeddedPlayers_handler.bind(this)});
	},
	loadEmbeddedPlayers_handler: function (ajaxRequest) {
		$('loading_embedded_players').style.display = 'none';
		//$('custom_players_search').value = '';
		var t = ajaxRequest.responseText;
		var jsonArr;
		eval ('jsonArr = ' + t);
		if (jsonArr.error > 0) {
			return;
		}
		if (jsonArr) {
			if (jsonArr.length == 0) {
				$('embedded_players').innerHTML = '<div id="embedded_players_no_msg">No custom players here!<br />Would you like to <span onclick="embedSearchResults()">create</span> one?</div>';
			} else {
				var j = 1;
				for (var i = 0; i < jsonArr.length; i ++) {
					var pl = new EmbeddedPlayer(jsonArr[i], j);
					//if (!pl.errors) j++;
					j++;
					this.embeddedPlayers.push(pl);
				}
				Element.addClassName (this.embeddedPlayers[0].element, 'first');
			}
			$('custom_players_count').innerHTML = jsonArr.length;
			$('custom_players_search_container').style.display = (jsonArr.length > 2?'':'none');
		}
		this.filter();
		this.scroll.update();
		this._updatePlayersList = false;
	},

	filter: function () {
		var kw = $('custom_players_search').value;
		var kws = kw.replace(/\s+/g, ' ').replace(/^\s*/, '').replace(/\s*$/, '').toLowerCase().split(' ');
		var i = 0, n = this.embeddedPlayers.length;
		for (i = 0; i < n; i ++) {
			this.embeddedPlayers[i].filter(kws);
			Element.removeClassName(this.embeddedPlayers[i].element, 'first');
		}
		// find the first NOT filtered!
		i = 0;
		while (i < n) {
			if (!this.embeddedPlayers[i].filtered) {
				Element.addClassName(this.embeddedPlayers[i].element, 'first');
				break;
			}
			i ++
		}
		if (i == n) { // all lists are filtered!
			/// then what?
		}
		this.scroll.update();
	},
	closeList: function () {
		hideBackground();
		this.listOpened = false;
		this.listBox.style.display = 'none';
	},
	clearPlayersList: function () {
		for (var i = 0; i < this.embeddedPlayers.length; i ++) {
			this.embeddedPlayers[i].remove();
		}
		this.embeddedPlayers.length = 0;
		$('embedded_players').innerHTML = '';
	},
	deletePlayer: function (player) {
		if (confirm ("Are you sure you want to delete this player?")) {
			$('loading_embedded_players').style.display = 'block';
			new Ajax.Request ('/embed_player_delete.php', {method:'post',
				parameters: $H({hash: player.jsonObj.hash}).toQueryString(),
				onSuccess: this.deletePlayer_handler.bind(this)});
			this.clearPlayersList();
		}
	},
	deletePlayer_handler: function () {
		EmbedPlayer.openList(this.listOrderedBy, true);
	},
	playerWithNameExists: function (n) {
		for (var i = 0; i <this.embeddedPlayers.length; i ++)
			if (this.embeddedPlayers[i].jsonObj.player_name == n)
				return true;
		return false;
	},
	copyPlayer: function (pl) {
		if (!UserLimits.isUserAllowedTo(UserLimits.ua_create_custom_player, true))
			return false;
		var n = 'Copy of ' + pl.jsonObj.player_name;
		var over = false;
		while (!over) {
			n = prompt ("Name of the new player?", n);
			if (!n)
				over = true;
			else
				if (this.playerWithNameExists(n)) {
					alert ('There already is a player with that name');
					over = false;
				} else
					over = true;
		}
		if (n) {
			$('loading_embedded_players').style.display = 'block';
			new Ajax.Request ('/embed_player_copy.php?id=' + pl.jsonObj.id + '&n=' + n, {method:'post', onSuccess: this.copyPlayer_handler.bind(this)});
			this.clearPlayersList();
		}
	},
	copyPlayer_handler: function () {
		$('loading_embedded_players').style.display = 'none';
		EmbedPlayer.openList(this.listOrderedBy, true);
	},
	editPlayer: function (player) {
		if (!user_name) {
			alert ('You have to register or log in to embed videos!');
			return;
		}

		this.edittedPlayer = player;

		showBackground();
		this.codeDiv.style.display = 'none';
		this.codeArea.value = '';

		$('embed_vs_type_2_sep').style.display = $('embed_vs_type_2').style.display = 'none';

		this.inputs.player_name.value = this.edittedPlayer.jsonObj.player_name;
		this.inputs.playlist_name.value = this.edittedPlayer.jsonObj.playlist_name;
		this.inputs.description.value = this.edittedPlayer.jsonObj.description;
		var s = this.edittedPlayer.jsonObj.width + 'x' + this.edittedPlayer.jsonObj.height;
		var sizeCustom = (this.inputs.size.setSelected (s) === false);

		if (sizeCustom) {
			this.inputs.size.selectedIndex = this.inputs.size.options.length-1;
			$('embed_player_size_custom').style.display = '';
			this.inputs.width.value = this.edittedPlayer.jsonObj.width;
			this.inputs.height.value = this.edittedPlayer.jsonObj.height;
		}

		this.inputs.data_source_type.value = this.dataSourceType = this.edittedPlayer.jsonObj.ds;
		this.inputs.standard_feed.setSelected ('featured');
		var videosCount;
		switch (this.dataSourceType) {
			case this.EMBED_SAVED_LIST:
				this.playlistID = this.edittedPlayer.jsonObj.jsonObj.id;
				this.jsonArr = {keywords:'', category:0, order_by:0};
				this.fillDSSelectors();
				for (var i = 0, n = this.form.saved_playlist.options.length; i < n; i ++)
					if (this.form.saved_playlist.options[i].value == this.edittedPlayer.jsonObj.jsonObj.id) {
						this.form.saved_playlist.selectedIndex = i;
						break;
					}
				videosCount = SavedPlaylists.getListById(this.form.saved_playlist.options[this.form.saved_playlist.selectedIndex].value).videos.length;
				break;
			case this.EMBED_RUNTIME_LIST:
				this.jsonArr = this.edittedPlayer.jsonObj.jsonObj;
				Object.extend (this.jsonArr, {keywords:'', category:0, order_by:0});
				this.fillDSSelectors();
				videosCount = this.jsonArr.resultsCount;
				break;
			case this.EMBED_SEARCH_RESULTS:
				this.jsonArr = this.edittedPlayer.jsonObj.jsonObj;
				this.fillDSSelectors();
				videosCount = this.jsonArr.resultsCount;
				break;
			case this.EMBED_FAVORITES:
				this.jsonArr = {keywords:'', category:0, order_by:0};
				this.fillDSSelectors();
				videosCount = Favorites.favorites.length;
				break;
			case this.EMBED_USER_CHANNEL:
				this.jsonArr = this.edittedPlayer.jsonObj.jsonObj;
				this.fillDSSelectors();
				break;
			case this.EMBED_STANDARD_FEED:
				this.fillDSSelectors();
				this.jsonArr = this.edittedPlayer.jsonObj.jsonObj;
				this.inputs.standard_feed.setSelected (this.jsonArr.feed);
				this.inputs.standard_feed_videos_count.value = this.jsonArr.count;
				break;
			case this.EMBED_SINGLE_VIDEO:
				this.jsonArr = this.edittedPlayer.jsonObj.jsonObj;
				//$('embed_single_video_title').innerHTML = this.jsonArr.title;
				this.form.embed_single_video_url.value = 'http://www.idesktop.tv/?watch=' + this.jsonArr.id;
				break;
			case this.EMBED_EXTERNAL_PLAYLIST:
				this.jsonArr = {};
				this.fillDSSelectors();
				break;
			case this.EMBED_YOUTUBE_PLAYLIST:
				this.jsonArr = {};
				this.form.youtube_playlist_url.value = 'http://www.youtube.com/view_play_list?p=' + this.edittedPlayer.jsonObj.jsonObj.id;
				this.fillDSSelectors();
				break;
			default:
				alert ('Error on site!');
				return;
		}

		this.form.external_playlist_url.value = this.edittedPlayer.jsonObj.external_playlist_url;
		this.form.external_playlist_interval.value = this.edittedPlayer.jsonObj.external_playlist_interval;

		// data source radio button
		this.inputs.data_source.setSelected(this.edittedPlayer.jsonObj.ds);
		this.inputs.only_public.checked = this.edittedPlayer.jsonObj.only_public;
		this.inputs.mark_private.checked = this.edittedPlayer.jsonObj.mark_private;
		this.inputs.email_on_delete.checked = this.edittedPlayer.jsonObj.email_on_delete;
		this.inputs.reverse_playlist.checked = this.edittedPlayer.jsonObj.reverse_playlist;

		this.inputs.embed_type.setSelected (this.edittedPlayer.jsonObj.type);
		this.onEmbedTypeChange();

		this.inputs.playlist_type.setSelected(this.edittedPlayer.jsonObj.playlist_type);

		this.inputs.theme.setSelected(this.edittedPlayer.jsonObj.theme);
		this.imagesSelector.setOptions('player_background', {selectedImage: this.edittedPlayer.jsonObj.player_background_image_id});
		this.imagesSelector.setOptions('title_logo', {selectedImage: this.edittedPlayer.jsonObj.player_title_bar_image_id});

		this.inputs.player_title_bar_image_align.setSelected (this.edittedPlayer.jsonObj.player_title_bar_image_align);
		this.inputs.player_title_bar_image_url.value = this.edittedPlayer.jsonObj.player_title_bar_image_url;

		this.playerTitleBackgroundColorPicker.setColor(this.playerTitleBackgroundColorPicker.defaultColor);
		switch (this.edittedPlayer.jsonObj.player_title_bar_background) {
			case 'H': this.inputs.player_title_bar_back.setSelected('H'); break;
			case 'T': this.inputs.player_title_bar_back.setSelected('T'); break;
			default :
				this.inputs.player_title_bar_back.setSelected('C');
				this.playerTitleBackgroundColorPicker.setColor(this.edittedPlayer.jsonObj.player_title_bar_background);
				break;
		}
		this.onPlayerTitleBarBackgroundChange();

		if (this.edittedPlayer.jsonObj.player_title_bar_font) {
			this.playerTitleFontPicker.setStyle(this.edittedPlayer.jsonObj.player_title_bar_font);
		} else {
			this.playerTitleFontPicker.setEmpty();
		}

		if (this.edittedPlayer.jsonObj.player_info_panel_back != 'T') {
			this.inputs.player_info_back_sel.setSelected ('C');
			this.infoPanelBackgroundColor.setColor(this.edittedPlayer.jsonObj.player_info_panel_back);
		} else {
			this.inputs.player_info_back_sel.setSelected ('T');
			this.infoPanelBackgroundColor.setColor(this.infoPanelBackgroundColor.defaultColor);
		}
		this.onPlayerInfoPanelBackgroundSelectChange();

		if (this.edittedPlayer.jsonObj.player_info_panel_font) {
			this.infoPanelFont.setStyle(this.edittedPlayer.jsonObj.player_info_panel_font);
		} else {
			this.infoPanelFont.setEmpty();
		}

		switch (this.edittedPlayer.jsonObj.player_info_panel_buttons_back) {
			case 'T':
			case 'H':
				this.inputs.player_info_btn_back_sel.setSelected (this.edittedPlayer.jsonObj.player_info_panel_buttons_back);
				this.infoPanelButtonBackgroundColor.setColor(this.infoPanelButtonBackgroundColor.defaultColor);
				break;
			default :
				this.inputs.player_info_btn_back_sel.setSelected ('C');
				this.infoPanelButtonBackgroundColor.setColor(this.edittedPlayer.jsonObj.player_info_panel_buttons_back);
				break;
		}
		this.onPlayerInfoPanelTabButtonBackgroundChange();

		if (this.edittedPlayer.jsonObj.player_info_panel_buttons_color != 'H') {
			this.inputs.player_info_btn_color_sel.setSelected ('C');
			this.infoPanelButtonFontColor.setColor(this.edittedPlayer.jsonObj.player_info_panel_buttons_color);
		} else {
			this.inputs.player_info_btn_color_sel.setSelected ('H');
			this.infoPanelButtonFontColor.setColor(this.infoPanelButtonFontColor.defaultColor);
		}
		this.onPlayerInfoPanelTabButtonFontColorChange();

		var s = this.edittedPlayer.jsonObj.thumbs_width + 'x' + this.edittedPlayer.jsonObj.thumbs_height;
		this.inputs.thumbnails_size.setSelected(s);

		this.inputs.listbox_width.value = this.edittedPlayer.jsonObj.listbox_width;
		this.inputs.listbox_height.value = this.edittedPlayer.jsonObj.listbox_height;
		this.form.thumbs_width.value = this.edittedPlayer.jsonObj.thumbs_width;
		this.form.thumbs_height.value = this.edittedPlayer.jsonObj.thumbs_height;
		this.form.thumbs_rows.value = this.edittedPlayer.jsonObj.thumbs_rows;
		this.form.thumbs_cols.value = this.edittedPlayer.jsonObj.thumbs_cols;
		this.inputs.thumbs_text_box_padding.value = this.edittedPlayer.jsonObj.thumbs_text_box_padding;

		for (var i = 0, n = this.inputs.player_placement.options.length; i < n; i ++)
			if (this.inputs.player_placement.options[i].value == this.edittedPlayer.jsonObj.player_placement) {
				this.inputs.player_placement.selectedIndex = i;
				break;
			}

		this.inputs.playlist_enabled.checked = this.edittedPlayer.jsonObj.playlist_enabled;
		this.inputs.playlist_visible.checked = this.edittedPlayer.jsonObj.playlist_visible;
		this.inputs.info_enabled.checked = this.edittedPlayer.jsonObj.info_enabled;
		this.inputs.info_visible.checked = this.edittedPlayer.jsonObj.info_visible;
		this.inputs.autostart.checked = this.edittedPlayer.jsonObj.autostart;
		this.imagesSelector.setOptions ('autostart_preimage', {selectedImage: this.edittedPlayer.jsonObj.autostart_preimage_id});

		this.inputs.repeat.checked = this.edittedPlayer.jsonObj.repeat;
		this.inputs.shuffle.checked = this.edittedPlayer.jsonObj.shuffle;

		this.inputs.uploader_in_title.checked = this.edittedPlayer.jsonObj.uploader_in_title;
		this.inputs.video_name_in_title.checked = this.edittedPlayer.jsonObj.video_name_in_title;

		//this.inputs.show_download_button.checked = this.edittedPlayer.jsonObj.show_download_button;
		this.inputs.show_url_button.checked = this.edittedPlayer.jsonObj.show_url_button;
		this.inputs.show_youtube_button.checked = this.edittedPlayer.jsonObj.show_youtube_button;
		this.inputs.show_rating.checked = this.edittedPlayer.jsonObj.show_rating;
		this.inputs.show_title.checked = this.edittedPlayer.jsonObj.show_title;
		this.inputs.show_addthis_button.checked = this.edittedPlayer.jsonObj.show_addthis_button;
		this.inputs.addthis_username.value = this.edittedPlayer.jsonObj.addthis_username;
		this.onShowAddthisChange();

		this.form.show_more_tab.checked = this.edittedPlayer.jsonObj.show_more_tab;
		this.form.show_related_tab.checked = this.edittedPlayer.jsonObj.show_related_tab;
		this.form.show_description_tab.checked = this.edittedPlayer.jsonObj.show_description_tab;
		this.form.show_comments_tab.checked = this.edittedPlayer.jsonObj.show_comments_tab;
		this.form.show_profile_tab.checked = this.edittedPlayer.jsonObj.show_profile_tab;

		this.inputs.videos_count.value = (this.edittedPlayer.jsonObj.jsonObj.resultsCount?this.edittedPlayer.jsonObj.jsonObj.resultsCount:10);
		this.inputs.channel_videos_count.value = (this.edittedPlayer.jsonObj.jsonObj.resultsCount?this.edittedPlayer.jsonObj.jsonObj.resultsCount:10);
		this.inputs.player_logo_url.value = this.edittedPlayer.jsonObj.player_logo_url;

		if (this.edittedPlayer.jsonObj.thumbnail_text == 'N')
			this.inputs.thumbnail_text_show.checked = false;
		else {
			this.inputs.thumbnail_text_show.checked = true;
			this.inputs.thumbnail_text_sel.setSelected (this.edittedPlayer.jsonObj.thumbnail_text);
		}
		this.getThumbTextPosition();

		this.inputs.thumb_show_title.checked = this.edittedPlayer.jsonObj.thumb_show_title;
		this.inputs.thumb_show_author.checked = this.edittedPlayer.jsonObj.thumb_show_author;
		this.inputs.thumb_show_rating.checked = this.edittedPlayer.jsonObj.thumb_show_rating;
		this.inputs.thumb_show_length.checked = this.edittedPlayer.jsonObj.thumb_show_length;
		this.inputs.thumb_show_description.checked = this.edittedPlayer.jsonObj.thumb_show_description;
		this.inputs.thumb_show_views.checked = this.edittedPlayer.jsonObj.thumb_show_views;
		this.inputs.thumb_show_labels.checked = this.edittedPlayer.jsonObj.thumb_show_labels;
		this.inputs.thumb_text_cut_title_two_lines.checked = this.edittedPlayer.jsonObj.thumb_text_cut_title_two_lines;
		this.inputs.thumb_text_box_size.value = this.edittedPlayer.jsonObj.thumb_text_box_size;

		this.inputs.background_color_transparent.checked = this.edittedPlayer.jsonObj.background_color_transparent;
		this.backgroundColorPicker.setColor(this.edittedPlayer.jsonObj.background_color);
		this.inputs.use_alt_background_color.checked = this.edittedPlayer.jsonObj.use_alt_background_color;
		this.inputs.alt_background_color_transparent.checked = this.edittedPlayer.jsonObj.alt_background_color_transparent;
		this.altBackgroundColorPicker.setColor(this.edittedPlayer.jsonObj.alt_background_color);
		
		this.pllThumbsBackgroundColorPicker.setColor(this.edittedPlayer.jsonObj.pll_thumb_background);

		this.titleFontPicker.setStyle(this.edittedPlayer.jsonObj.title_font);
		this.textFontPicker.setStyle(this.edittedPlayer.jsonObj.text_font);
		this.labelsFontPicker.setStyle(this.edittedPlayer.jsonObj.labels_font);

		this.imagesSelector.setOptions('player_logo', {selectedImage: this.edittedPlayer.jsonObj.player_logo_id});
		this.form.hash.value = this.edittedPlayer.jsonObj.hash;

		var emb_b = this.edittedPlayer.jsonObj.embed_background;
		this.inputs.emb_background_sel.setSelected (emb_b.charAt(0));
		switch (emb_b.charAt(0)) {
			case 'T':
				this.embBackgroundColorPicker.setColor(this.embBackgroundColorPicker.defaultColor);
				this.imagesSelector.setOptions('embed_background_image', {selectedImage: ''});
				break;
			case 'C':
				this.embBackgroundColorPicker.setColor(this.edittedPlayer.jsonObj.embed_background.slice(1));
				this.imagesSelector.setOptions('embed_background_image', {selectedImage: ''});
				break;
			case 'I':
				this.embBackgroundColorPicker.setColor(this.embBackgroundColorPicker.defaultColor);
				this.imagesSelector.setOptions('embed_background_image', {selectedImage: parseInt(this.edittedPlayer.jsonObj.embed_background.slice(1))});
				break;
		}
		//this.embBackgroundColorPicker.setColor(this.edittedPlayer.jsonObj.emb_background_color);
		//this.inputs.emb_background_color_transparent.checked = this.edittedPlayer.jsonObj.emb_background_color_transparent;


		this.inputs.prev_next_button_style.setSelected (this.edittedPlayer.jsonObj.prev_next_button_style);
		this.inputs.show_prev_next_buttons.checked = this.edittedPlayer.jsonObj.show_prev_next_buttons;

		this.inputs.popout_button_type.setSelected(this.edittedPlayer.jsonObj.popout_box_button.charAt(0));
		var btn = this.edittedPlayer.jsonObj.popout_box_button.slice(1);

		if (this.inputs.popout_button_type.getSelected() == 'T') {
			this.imagesSelector.setOptions('popout_button', {selectedImage: ''});
			this.inputs.popout_button_text.value = btn;
		} else {
			this.imagesSelector.setOptions('popout_button', {selectedImage: btn});
			this.inputs.popout_button_text.value = '';
		}

	/* load playlist settings */
		this.inputs.pll_width.value = this.edittedPlayer.jsonObj.pll_width;
		this.inputs.pll_thumb_size.setSelected (this.edittedPlayer.jsonObj.pll_thumb_width + 'x' + this.edittedPlayer.jsonObj.pll_thumb_height);
		this.inputs.pll_thumb_width.value = this.edittedPlayer.jsonObj.pll_thumb_width;
		this.inputs.pll_thumb_height.value = this.edittedPlayer.jsonObj.pll_thumb_height;
		this.inputs.pll_columns.value = this.edittedPlayer.jsonObj.pll_columns;
		//this.inputs.pll_thumbnail_text.setSelected(this.edittedPlayer.jsonObj.pll_thumbnail_text); ///
		if (this.edittedPlayer.jsonObj.pll_thumbnail_text == 'N') {
			this.inputs.pll_thumbnail_text_show.checked = false;
			this.inputs.pll_thumbnail_text_sel.setSelected ('R');
		} else {
			this.inputs.pll_thumbnail_text_show.checked = true;
			this.inputs.pll_thumbnail_text_sel.setSelected (this.edittedPlayer.jsonObj.pll_thumbnail_text);
		}
		this.inputs.pll_thumb_text_box_size.value = this.edittedPlayer.jsonObj.pll_thumb_text_box_size;
		this.inputs.pll_text_box_padding.value = this.edittedPlayer.jsonObj.pll_text_box_padding;

		this.inputs.pll_thumb_show_title.checked = this.edittedPlayer.jsonObj.pll_thumb_show_title;
		this.inputs.pll_thumb_show_author.checked = this.edittedPlayer.jsonObj.pll_thumb_show_author;
		this.inputs.pll_thumb_show_rating.checked = this.edittedPlayer.jsonObj.pll_thumb_show_rating;
		this.inputs.pll_thumb_show_length.checked = this.edittedPlayer.jsonObj.pll_thumb_show_length;
		this.inputs.pll_thumb_show_description.checked = this.edittedPlayer.jsonObj.pll_thumb_show_description;
		this.inputs.pll_thumb_show_views.checked = this.edittedPlayer.jsonObj.pll_thumb_show_views;
		this.inputs.pll_thumb_show_labels.checked = this.edittedPlayer.jsonObj.pll_thumb_show_labels;

		this.pllTitleFontPicker.setStyle(this.edittedPlayer.jsonObj.pll_title_font);
		this.pllTextFontPicker.setStyle(this.edittedPlayer.jsonObj.pll_text_font);
		this.pllLabelsFontPicker.setStyle(this.edittedPlayer.jsonObj.pll_labels_font);

		this.inputs.pll_background_color_transparent.checked = this.edittedPlayer.jsonObj.pll_background_color_transparent;
		this.pllBackgroundColorPicker.setColor (this.edittedPlayer.jsonObj.pll_background_color);
		this.inputs.pll_alt_background_color_transparent.checked = this.edittedPlayer.jsonObj.pll_alt_background_color_transparent;
		this.pllAltBackgroundColorPicker.setColor (this.edittedPlayer.jsonObj.pll_alt_background_color);

		this.inputs.pll_use_alt_background_color.checked = this.edittedPlayer.jsonObj.pll_use_alt_background_color;
		this.inputs.pll_show_play_controls.checked = this.edittedPlayer.jsonObj.pll_show_play_controls;

		if (this.edittedPlayer.jsonObj.pll_thumb_buttons == 'N') {
			this.inputs.pll_thumb_buttons_show.checked = false;
			this.inputs.pll_thumb_buttons_sel.setSelected ('TL');
		} else {
			this.inputs.pll_thumb_buttons_show.checked = true;
			this.inputs.pll_thumb_buttons_sel.setSelected (this.edittedPlayer.jsonObj.pll_thumb_buttons);
		}
		this.onThumbnailControlsClick();

		this.inputs.pll_show_hint.checked = this.edittedPlayer.jsonObj.pll_show_hint;
		this.onPllShowHintClick();
		this.inputs.pll_hint_show_title.checked = this.edittedPlayer.jsonObj.pll_hint_show_title;
		this.inputs.pll_hint_show_author.checked = this.edittedPlayer.jsonObj.pll_hint_show_author;
		this.inputs.pll_hint_show_length.checked = this.edittedPlayer.jsonObj.pll_hint_show_length;
		this.inputs.pll_hint_show_views.checked = this.edittedPlayer.jsonObj.pll_hint_show_views;
		this.inputs.pll_hint_show_rating.checked = this.edittedPlayer.jsonObj.pll_hint_show_rating;
		this.inputs.pll_hint_show_votes.checked = this.edittedPlayer.jsonObj.pll_hint_show_votes;

		this.inputs.pll_title_cut_two_lines.checked = this.edittedPlayer.jsonObj.pll_title_cut_two_lines;

		this.imagesSelector.setOptions('playlist_logo', {selectedImage: this.edittedPlayer.jsonObj.pll_playlist_logo_id});
		this.inputs.pll_playlist_logo_link.value = this.edittedPlayer.jsonObj.pll_playlist_logo_link;
		this.inputs.pll_playlist_logo_placement.setSelected (this.edittedPlayer.jsonObj.pll_playlist_logo_placement);
		this.inputs.pll_show_prev_next_buttons.checked = this.edittedPlayer.jsonObj.pll_show_prev_next_buttons;

	/* load ads settings */
		if (this.edittedPlayer.jsonObj.pre_roll_list) {
			this.inputs.pre_roll_ad_show.checked = true;
			this.inputs.pre_roll_playlist.setSelected(this.edittedPlayer.jsonObj.pre_roll_list);
		} else
			this.inputs.pre_roll_ad_show.checked = false;
		this.onPrerollShowChange();
		this.onPrerollListChange();
		if (this.edittedPlayer.jsonObj.pre_roll_ad) {
			this.inputs.pre_roll_video_r.setSelected ('V');
			this.inputs.pre_roll_video_sel.setSelected (this.edittedPlayer.jsonObj.pre_roll_ad);
		} else
			this.inputs.pre_roll_video_r.setSelected ('R');

		if (this.edittedPlayer.jsonObj.mid_roll_list) {
			this.inputs.mid_roll_ad_show.checked = true;
			this.inputs.mid_roll_playlist.setSelected(this.edittedPlayer.jsonObj.mid_roll_list);
		} else
			this.inputs.mid_roll_ad_show.checked = false;
		this.onMidrollShowChange();
		this.onMidrollListChange();
		if (this.edittedPlayer.jsonObj.mid_roll_ad) {
			this.inputs.mid_roll_video_r.setSelected ('V');
			this.inputs.mid_roll_video_sel.setSelected (this.edittedPlayer.jsonObj.mid_roll_ad);
		} else
			this.inputs.mid_roll_video_r.setSelected ('R');
		this.inputs.mid_roll_show_every.value = this.edittedPlayer.jsonObj.mid_roll_show_every;

		if (this.edittedPlayer.jsonObj.post_roll_list) {
			this.inputs.post_roll_ad_show.checked = true;
			this.inputs.post_roll_playlist.setSelected(this.edittedPlayer.jsonObj.post_roll_list);
		} else
			this.inputs.post_roll_ad_show.checked = false;
		this.onPostrollShowChange();
		this.onPostrollListChange();
		if (this.edittedPlayer.jsonObj.post_roll_ad) {
			this.inputs.post_roll_video_r.setSelected ('V');
			this.inputs.post_roll_video_sel.setSelected (this.edittedPlayer.jsonObj.post_roll_ad);
		} else
			this.inputs.post_roll_video_r.setSelected ('R');

		this.inputs.ads_caption.value = this.edittedPlayer.jsonObj.ads_caption;
		this.inputs.ads_disable_controls.checked = this.edittedPlayer.jsonObj.ads_disable_controls;

		this.inputs.ga_id.value = this.edittedPlayer.jsonObj.ga_id;
		this.inputs.ga_page_url.value = this.edittedPlayer.jsonObj.ga_page_url;
		this.inputs.ga_events_category.value = this.edittedPlayer.jsonObj.ga_events_category;

		this.element.style.display = 'block';
		this.listBox.style.display = '';
		this.formDiv.style.display = '';
		this.showTab('DS');
		//this.showListOnClose = true;

		this.onSizeChange(); // just in case ;)
		this.onShowTitleChange();
		this.getEmbedTypeID();
		this.onDataSourceChange();
		this.onShowOnlyPublicChange();
		this.onAutostartChange();

		this.setUserPayPlanLimits();
	},

	onPreviewPlayerSaved: function () {
		$('saving_embedded_player').style.display = '';
		window.open('/embed/preview/preview-player.html', 'previewplayer', '');
	},
	// this one is called when player has been saved already ;)
	previewLastPlayer: function () {
		window.open('/embed/' + this.lph + '/preview-player.html', '');
	},
	getThumbnailsSize: function () {
		var s = this.inputs.thumbnails_size.options[this.inputs.thumbnails_size.selectedIndex].value;
		var a = s.split("x");
		var w = parseInt(a[0]);
		var h = parseInt(a[1]);
		return {w:w,h:h};
	},
	recalculateListboxSizes: function (event, sender) {
		var et = this.getEmbedTypeID("prevent recursion parameter");
		var a = this.getThumbnailsSize();
		if (et == 1 || et == 2) {
			this.form.thumbs_width.value = 130;
			this.form.thumbs_height.value = 100;
			this.inputs.thumbs_rows.value = 1;
			this.inputs.thumbs_cols.value = 1;
			return;
		}
		var tw = a.w + 2, th = a.h + 2; // add margin of the videos!
		var selectedTextPosition = this.getThumbTextPosition();
		if (et == 5) selectedTextPosition = 'R';
		var iw = tw, ih = th;
		if (et == 3 || et == 4) {
			if (selectedTextPosition == 'L' || selectedTextPosition == 'R')
				iw += parseInt(this.inputs.thumb_text_box_size.value);
			else if (selectedTextPosition == 'B')
				ih += parseInt(this.inputs.thumb_text_box_size.value);
		} else if (et == 5 ) {
			iw += parseInt(this.inputs.thumb_text_box_size.value);
		}

		var r = parseInt(this.inputs.thumbs_rows.value), c = parseInt(this.inputs.thumbs_cols.value);
		var ow = parseInt(this.inputs.listbox_width.value), oh = parseInt(this.inputs.listbox_height.value);

		var ttbs = parseInt(this.inputs.thumb_text_box_size.value);

		if (arguments.length == 0) var sender = "";
		if (arguments.length == 0 && (et == 4 || et == 5)) sender = "thumbs";

		if (sender == "textbox_size") {
			if (et == 3) {
				if (this.inputs.show_prev_next_buttons.checked)
					oh -= 20;
				r = Math.floor (oh / ih);
				c = Math.floor (ow / iw);
				this.inputs.thumbs_rows.value = r;
				this.inputs.thumbs_cols.value = c;
			} else if (et == 4) {
				ow = iw + 20;
				oh = r * ih;
				this.inputs.thumbs_cols.value = 1;
				this.inputs.listbox_width.value = ow;
				this.inputs.listbox_height.value = oh;
			} else if (et == 5) {
				ow = iw + 38;
				this.inputs.listbox_width.value = ow;
			}
		} else if (sender == "outer" || sender == "") { // recalculate rows/cols, or the text box size
			if (et == 3 && this.inputs.show_prev_next_buttons.checked) oh -= 20;
			r = Math.floor (oh / ih);
			c = Math.floor (ow / iw);
			if (et == 4) {
				c = 1;
				if (selectedTextPosition == 'L' || selectedTextPosition == 'R')
					this.inputs.thumb_text_box_size.value = ow - tw - 20;

			} else if (et == 5)  {
				c = r = 1;
				iw = ow - 38;
				this.inputs.thumb_text_box_size.value = ow - tw - 38;
			}
			this.inputs.thumbs_rows.value = r;
			this.inputs.thumbs_cols.value = c;
		} else if (sender == "rowscols" || sender == "thumbs") { // recalculate outer size
			ow = c * iw;
			if (et == 4) ow += 20;
			if (et == 5) ow += 38;
			oh = r * ih;
			if (et == 3 && this.inputs.show_prev_next_buttons.checked) oh += 20;
			/*if (et == 4) ow = Math.max (iw, this.inputs.listbox_width.value);
			if (et == 5) { ow = Math.max (this.inputs.listbox_width.value, tw + 150); oh = th;}*/
			this.inputs.listbox_width.value = ow;
			this.inputs.listbox_height.value = oh;
		}

		var w = (selectedTextPosition == 'B' || selectedTextPosition == 'O'?tw:this.inputs.thumb_text_box_size.value);
		var h = Math.min(120, (selectedTextPosition == 'L' || selectedTextPosition == 'R'?th:this.inputs.thumb_text_box_size.value));

		$('embed_fonts_sample').style.width = w + "px";
		$('embed_fonts_sample').style.height = h + "px";
		$('embed_fonts_sample_in').style.width = w - 2 * this.inputs.thumbs_text_box_padding.value + "px";
		$('embed_fonts_sample_in').style.height = h - 2 * this.inputs.thumbs_text_box_padding.value + "px";

		this.form.thumbs_width.value = a.w;
		this.form.thumbs_height.value = a.h;
		if (arguments.length == 0)
			return {ow: ow, oh: oh, tw: tw, th: th, r: r, c: c};
	},
	onShowTitleChange: function () {
		$('embed_show_author_in_title_t').style.display = $('embed_show_video_title_t').style.display =
			this.form.uploader_in_title.style.display = this.form.video_name_in_title.style.display =
		/*$('embed_show_in_title').style.display =*/ $('embed_title_bar_logo_tr').style.display = $('embed_title_bar_style').style.display =
			(this.inputs.show_title.checked?'':'none');
	},
	updateFontsExample: function () {
		var w = parseInt($('embed_fonts_sample').style.width);
		var h = parseInt($('embed_fonts_sample').style.height);

		$('embed_fonts_sample_in').style.width = w - 2 * this.inputs.thumbs_text_box_padding.value + "px";
		$('embed_fonts_sample_in').style.height = h - 2 * this.inputs.thumbs_text_box_padding.value + "px";

		if (this.inputs.background_color_transparent.checked)
			$('embed_fonts_sample').style.backgroundColor = 'transparent';
		else
			$('embed_fonts_sample').style.backgroundColor = '#' + this.backgroundColorPicker.currentColor;
		$('embed_fonts_sample_in').style.margin = parseInt(this.inputs.thumbs_text_box_padding.value) + 'px';

		var labels = document.getElementsByClassName ('lb', $('embed_fonts_sample_in'));
		var showLabels = this.inputs.thumb_show_labels.checked;
		for (var i = 0; i < labels.length; i ++) {
			this.labelsFontPicker.applyStyles (labels[i]);
			labels[i].style.display = showLabels?'':'none';
		}

		$('embed_t_sample_title').style.height = (this.inputs.thumb_text_cut_title_two_lines.checked?this.titleFontPicker.lineHeightPicker.getSelected() * 2 + 2 + 'px':'auto');

		this.textFontPicker.applyStyles ($('embed_fonts_sample'));
		this.titleFontPicker.applyStyles ($('embed_t_sample_title'));

		// show/hide
		$('embed_t_sample_title').style.display = this.inputs.thumb_show_title.checked?'':'none';
		$('embed_t_sample_author').style.display = this.inputs.thumb_show_author.checked?'':'none';
		$('embed_t_sample_length').style.display = this.inputs.thumb_show_length.checked?'':'none';
		$('embed_t_sample_rating').style.display = this.inputs.thumb_show_rating.checked?'':'none';
		$('embed_t_sample_views').style.display = this.inputs.thumb_show_views.checked?'':'none';
		$('embed_t_sample_description').style.display = this.inputs.thumb_show_description.checked?'':'none';

		$('embed_thumbnail_title_style_selectors_1').style.display = $('embed_thumbnail_title_style_selectors_2').style.display = this.inputs.thumb_show_title.checked?'':'none';
		$('embed_thumbnail_labels_style_selector').style.display = showLabels?'':'none';

		$('embed_second_background_color').style.display = $('embed_second_background_color_tr_l').style.display =
			this.inputs.alt_background_color_transparent.style.display = this.inputs.use_alt_background_color.checked?'':'none';
	},
	getCode: function (jsonObj) {
		this.element.style.display = 'block';
		this.formDiv.style.display = 'none';
		this.codeDiv.style.display = 'block';
		$('saving_embedded_player').style.display = 'block';
		this.codeArea.value = '';
		if (this.listOpened)
			this.listBox.style.display = 'none';
		new Ajax.Request ('/embed_player_save.php?hash=' + jsonObj.hash + '&generate_code=true', {method:'get', onSuccess: this.getCode_handler.bind(this) });
	},
	getCode_handler: function (ajaxRequest) {
		$('saving_embedded_player').style.display = 'none';
		var t = ajaxRequest.responseText;
		var jsonObj;
		eval ('jsonObj = ' + t);
		if (jsonObj && jsonObj.code) {
			this.codeArea.value = jsonObj.code;
			this.lph = jsonObj.hash;
		} else {
			this.codeArea.value =  jsonObj.error || 'Error fetching code, please try again later!';
		}
	},
	getThumbTextPosition: function () {
		if (this.inputs.thumbnail_text_show.checked)
			res = this.inputs.thumbnail_text_sel.getSelected();
		else
			res = 'N';
		this.inputs.thumbnail_text.value = res;
		$('embed_thumbnail_text_subselectors').style.display = (res == 'N'?'none':'');
		$('embed_text_box_size_label').innerHTML = (res == 'L' || res == 'R'?'Textbox width:':'Textbox height:');
		return res; //
	},

/* playlist settings shits */
	getEmbedPlaylistTypeID: function () {
		var res = -1;
		for (var i = 0; i < this.inputs.playlist_type.length; i ++)
			if (this.inputs.playlist_type[i].checked)
				res = parseInt(this.inputs.playlist_type[i].value);
		$('embed_pll_sizes').style.display = (res != 1?'':'none');
		$('embed_pll_columns').style.display = this.inputs.pll_columns.style.display = (res == 3?'':'none');
		$('embed_pll_thumbs').style.display = (res != 1?'':'none');
		$('embed_pll_show_prev_next_buttons_tr').style.display = (res == 3?'':'none');
		$('embed_pll_thumbs_background_tr').style.display = (res == 1 ? '' : 'none');

		//$('embed_playlist_type_select_example').src = "/images/embed_form_examples/playlist_" + res +".gif";
		this.fixGeneralPreviewImages();

		if (res == 2) this.inputs.pll_columns.value = 1;

		if (arguments.length == 0) {
			this.updateMaximumLogoSize();
			this.recalculatePlaylistSizes();
		}
		return res;
	},
	getPlaylistThumbnailSize: function () {
		var s = this.inputs.pll_thumb_size.options[this.inputs.pll_thumb_size.selectedIndex].value;
		var a = s.split("x");
		var w = parseInt(a[0]);
		var h = parseInt(a[1]);
		return {w:w,h:h};
	},
	getPlaylistThumbTextPosition: function () {
		var pos;
		if (this.inputs.pll_thumbnail_text_show.checked)
			pos = this.inputs.pll_thumbnail_text_sel.getSelected();
		else
			pos = 'N';
		$('embed_pll_thumbs_subselectors').style.display = (pos == 'N'?'none':'');
		$('embed_pll_textbox_size_label').innerHTML = (pos == 'L' || pos == 'R'?'width':'height');
		return pos;
	},
	recalculatePlaylistSizes: function (event, sender) {
		// sender is: player, playlist, thumbs, columns, textbox_pos, textbox_size
		var ts = this.getPlaylistThumbnailSize();
		var playlist_type = this.getEmbedPlaylistTypeID("prevent recursion parameter");
		var thumb_width = this.inputs.pll_thumb_width.value = ts.w;
		var thumb_height = this.inputs.pll_thumb_height.value = ts.h;
		var textbox_size = parseInt(this.inputs.pll_thumb_text_box_size.value);
		var playlist_width = parseInt(this.inputs.pll_width.value);
		if (playlist_type == 1) playlist_width = 130;
		var player_width = this.getPlayerWidth();
		var columns = parseInt(this.inputs.pll_columns.value);

		var textbox_pos = this.getPlaylistThumbTextPosition(); // this will show/hide the inputs too

		var item_width = thumb_width, item_height = thumb_height;
		if (textbox_pos == 'L' || textbox_pos == 'R')
			item_width += textbox_size;
		else if (textbox_pos == 'B')
			item_height += textbox_size;
		else if (textbox_pos == 'O') {
			if (textbox_size > item_height) {
				textbox_size = item_height;
				this.inputs.pll_thumb_text_box_size.value = textbox_size;
			}
		}

		if (playlist_type == 2)
			this.inputs.pll_columns.value = 1;

		switch (sender) {
			case 'player': { // recalc .. rows?!
				 break;
			}
			case 'playlist': { // recalc columns or textbox width
				if (playlist_type == 2) { // listbox
					this.inputs.pll_thumb_text_box_size.value = textbox_size = playlist_width - thumb_width;
				} else if (playlist_type == 3) {
					this.inputs.pll_columns.value = Math.floor (playlist_width / (item_width + 2)); break;
				}
			}
			case 'thumbs': { // recalc columns
				if (playlist_type == 2) { // listbox
					this.inputs.pll_thumb_text_box_size.value = textbox_size = playlist_width - thumb_width;
				} else if (playlist_type == 3) {
					this.inputs.pll_columns.value = Math.floor (playlist_width / (item_width + 2)); break;
				}
			}
			case 'columns': { // recalc playlist size
				if (playlist_type == 3)
					this.inputs.pll_width.value = playlist_width =  columns * (item_width + 2); break;
			}
			case 'textbox_pos': { // recalc columns
				if (playlist_type == 2) { // listbox
					// recalculate the playlist width instead!
					//this.inputs.pll_thumb_text_box_size.value = textbox_size = playlist_width - thumb_width;
					this.inputs.pll_width.value = playlist_width = thumb_width + textbox_size;
				} else if (playlist_type == 3) {
					this.inputs.pll_columns.value = Math.floor (playlist_width / (item_width + 2)); break;
				}
			}
			case 'textbox_size': { // recalc columns
				if (playlist_type == 2) { // listbox
					this.inputs.pll_width.value = playlist_width = item_width;
				} else if (playlist_type == 3) {
					this.inputs.pll_columns.value = Math.floor (playlist_width / (item_width + 2)); break;
				}
			}
		}
		/* calculate maximum playlist logo width */
		var max_logo_width = playlist_width;
		if (playlist_type == 2 ) max_logo_width += 17; // the scroll bar
		if (this.inputs.pll_show_play_controls.checked)
			max_logo_width -= 89;
		this.imagesSelector.setOptions ('playlist_logo', {maxImageWidth: max_logo_width });
		$('embed_max_playlist_custom_logo_size').innerHTML = max_logo_width + 'x18';

		var w = (textbox_pos == 'B' || textbox_pos == 'O'?thumb_width:textbox_size);
		var h = Math.min (210, (textbox_pos == 'L' || textbox_pos == 'R'?thumb_height:textbox_size));

		$('embed_pll_playlis_fonts_sample').style.width = w + "px";
		$('embed_pll_playlis_fonts_sample').style.height = h + "px";
		$('embed_pll_playlis_fonts_sample_in').style.width = w - 2 * this.inputs.pll_text_box_padding.value + "px";
		$('embed_pll_playlis_fonts_sample_in').style.height = h - 2 * this.inputs.pll_text_box_padding.value + "px";

	},

	updatePlaylistFontsExample: function () {
		var w = parseInt($('embed_pll_playlis_fonts_sample').style.width);
		var h = parseInt($('embed_pll_playlis_fonts_sample').style.height);

		$('embed_pll_playlis_fonts_sample_in').style.width = w - 2 * this.inputs.pll_text_box_padding.value + "px";
		$('embed_pll_playlis_fonts_sample_in').style.height = h - 2 * this.inputs.pll_text_box_padding.value + "px";

		if (this.inputs.pll_background_color_transparent.checked)
			$('embed_pll_playlis_fonts_sample').style.backgroundColor = 'transparent';
		else
			$('embed_pll_playlis_fonts_sample').style.backgroundColor = '#' + this.pllBackgroundColorPicker.currentColor;
		$('embed_pll_playlis_fonts_sample_in').style.margin = parseInt(this.inputs.pll_text_box_padding.value) + 'px';

		var labels = document.getElementsByClassName ('lb', $('embed_pll_playlis_fonts_sample_in'));
		var showLabels = this.inputs.pll_thumb_show_labels.checked;
		for (var i = 0; i < labels.length; i ++) {
			this.pllLabelsFontPicker.applyStyles (labels[i]);
			labels[i].style.display = showLabels?'':'none';
		}

		$('embed_pll_playlis_sample_title').style.height = (this.inputs.pll_title_cut_two_lines.checked?this.pllTitleFontPicker.lineHeightPicker.getSelected() * 2 + 2 + 'px':'auto');

		this.pllTextFontPicker.applyStyles ($('embed_pll_playlis_fonts_sample'));
		this.pllTitleFontPicker.applyStyles ($('embed_pll_playlis_sample_title'));
		// show/hide
		$('embed_pll_playlis_sample_title').style.display = this.inputs.pll_thumb_show_title.checked?'':'none';
		$('embed_pll_playlist_sample_author').style.display = this.inputs.pll_thumb_show_author.checked?'':'none';
		$('embed_pll_playlist_sample_length').style.display = this.inputs.pll_thumb_show_length.checked?'':'none';
		$('embed_pll_playlist_sample_rating').style.display = this.inputs.pll_thumb_show_rating.checked?'':'none';
		$('embed_pll_playlist_sample_views').style.display = this.inputs.pll_thumb_show_views.checked?'':'none';
		$('embed_pll_playlist_sample_description').style.display = this.inputs.pll_thumb_show_description.checked?'':'none';

		$('embed_pll_labels_font_selector').style.display = showLabels?'':'none';
		$('embed_pll_title_font_selector_1').style.display = $('embed_pll_title_font_selector_2').style.display = this.inputs.pll_thumb_show_title.checked?'':'none';

		$('embed_pll_alt_background_color').style.display = $('embed_pll_alt_background_color_tr_l').style.display =
			this.inputs.pll_alt_background_color_transparent.style.display = this.inputs.pll_use_alt_background_color.checked?'':'none';
	},

	onPllShowHintClick: function ( ) {
		$('embed_pll_hint_elements').style.display = this.inputs.pll_show_hint.checked?'':'none';
	},

/* tabs */
	showTab: function (name) {
		if (!this['tab' + name]) return;
		if (this.currentTab) this.currentTab.style.display = 'none';
		Element.removeClassName ($('embed_tab_switches_ds'), 'current');
		Element.removeClassName ($('embed_tab_switches_general'), 'current');
		Element.removeClassName ($('embed_settings_tab_header'), 'current');
		Element.removeClassName ($('embed_tab_switches_player'), 'current');
		Element.removeClassName ($('embed_tab_switches_playlist'), 'current');
		Element.removeClassName ($('embed_tab_switches_ads'), 'current');
		Element.removeClassName ($('embed_tab_switches_tracking'), 'current');

		this.currentTab = this['tab' + name];
		this.currentTabName = name;
		this.currentTab.style.display = 'block';

		this.prevNextTabFix();

		if (this.edittedPlayer)
			this.elementHeader.innerHTML = 'EDIT PLAYER - ';
		else
			this.elementHeader.innerHTML = 'CREATE CUSTOM PLAYER - ';
		switch (this.currentTabName) {
			case 'DS':
				this.elementHeader.innerHTML += 'Choose the videos that will appear in the player';
				Element.addClassName ($('embed_tab_switches_ds'), 'current');
				break;
			case 'General':
				this.elementHeader.innerHTML += 'Enter your player name and the type of player';
				Element.addClassName ($('embed_tab_switches_general'), 'current');
				break;
			case 'TypeDetails': {
				var res = this.getEmbedTypeID();
				switch (res) {
					case 1: ; break;
					case 2:	this.elementHeader.innerHTML += 'Popout Box Settings';  break;
					case 3:	this.elementHeader.innerHTML += 'Video Wall Settings';  break;
					case 4:	this.elementHeader.innerHTML += 'List Box Settings';  break;
					case 5:	this.elementHeader.innerHTML += 'Horizontal Box Settings';  break;
				}
				Element.addClassName ($('embed_settings_tab_header'), 'current');
				break;
			}
			case 'Player':
				this.elementHeader.innerHTML += 'Player Settings';
				Element.addClassName ($('embed_tab_switches_player'), 'current');
				break;
			case 'Playlist':
				this.elementHeader.innerHTML += 'Playlist Settings';
				Element.addClassName ($('embed_tab_switches_playlist'), 'current');
				break;
			case 'Ads':
				this.elementHeader.innerHTML += 'Advertisement Settings';
				Element.addClassName ($('embed_tab_switches_ads'), 'current');
				break;
			case 'Tracking':
				this.elementHeader.innerHTML += 'Tracking Settings';
				Element.addClassName ($('embed_tab_switches_tracking'), 'current');
				break;
		}
	},
	showPrevTab: function () {
		switch (this.currentTabName) {
			case 'DS': break;
			case 'General': this.showTab('DS'); break;
			case 'TypeDetails': this.showTab ('General'); break;
			case 'Player': this.showTab (this._embedSettingsTabDisabled?'General':'TypeDetails'); break;
			case 'Playlist': this.showTab ('Player'); break;
			case 'Ads': this.showTab(this._playlistSettingsTabDisabled?'Player':'Playlist'); break;
			case 'Tracking': this.showTab ('Ads'); break;
		}
		this.prevNextTabFix();
	},
	showNextTab: function () {
		switch (this.currentTabName) {
			case 'DS': this.showTab ('General'); break;
			case 'General': this.showTab (this._embedSettingsTabDisabled?'Player':'TypeDetails'); break;
			case 'TypeDetails': this.showTab ('Player'); break;
			case 'Player': this.showTab(this._playlistSettingsTabDisabled?'Player':'Playlist'); break;
			case 'Playlist': this.showTab ('Ads'); break;
			case 'Ads':
				var embed_type = this.inputs.embed_type.getSelected();
				if (embed_type != 6)
					this.showTab ('Tracking');
				break;
			case 'Tracking': break;
		}
		this.prevNextTabFix();
	},
	prevNextTabFix: function () {
		$('embed_prev_tab_btn').style.display = (this.currentTabName == 'DS'?'none':'');
		var embed_type = this.inputs.embed_type.getSelected();
		if (embed_type == 6)
			$('embed_next_tab_btn').style.display = (this.currentTabName == 'Ads'?'none':'');
		else
			$('embed_next_tab_btn').style.display = (this.currentTabName == 'Tracking'?'none':'');
	},
	onPrevNextButtonsShowhideClick: function (event) {
		$('embed_prev_next_buttons_style_tr').style.display = this.inputs.show_prev_next_buttons.checked?'':'none';
		this.recalculateListboxSizes(event,  "rowscols");
	},
	onThumbnailControlsClick: function () {
		$('embed_pll_thumb_buttons_selector').style.display = this.inputs.pll_thumb_buttons_show.checked?'':'none';
	},

	onEmbedTypeChange: function (event) {
		var type = this.getEmbedTypeID();
		$('embed_tab_switches_tracking_holder').style.display = (type == 6 ? 'none' : '');
	},

	onDataSourceChange: function (event) {
		var res = this.inputs.data_source.getSelected();
		$('embed_tr_email_if_deleted').style.display = (res == this.EMBED_SAVED_LIST || res == this.EMBED_FAVORITES ? '' : 'none');
		$('embed_tr_reverse_playlist').style.display = (res == this.EMBED_EXTERNAL_PLAYLIST || res == this.EMBED_SINGLE_VIDEO ? 'none' : '');
		$('embed_tr_only_public_vids').style.display = (res == this.EMBED_EXTERNAL_PLAYLIST ? 'none' : '' );
		$('ccp_ds_standard_feed_sub').style.display = (res == this.EMBED_STANDARD_FEED ? '' : 'none');
		$('ccp_ds_search_sub_1').style.display = $('ccp_ds_search_sub_2').style.display = $('ccp_ds_search_sub_3').style.display =  (res == this.EMBED_SEARCH_RESULTS ? '' : 'none');
		$('ccp_ds_channel_sub').style.display = (res == this.EMBED_USER_CHANNEL ? '' : 'none');
		$('ccp_ds_external_sub').style.display = (res == this.EMBED_EXTERNAL_PLAYLIST ? '' : 'none');

		$('embed_tab_ads_container').style.display = (res == this.EMBED_EXTERNAL_PLAYLIST ? 'none' : '');
		$('embed_tab_ads_external_playlist_message').style.display = (res == this.EMBED_EXTERNAL_PLAYLIST ? '' : 'none');
		if (res == this.EMBED_EXTERNAL_PLAYLIST && !UserLimits.isUserAllowedTo(UserLimits.ua_set_external_playlist, false)) {
			if (arguments.length > 0) {
				//Event.stop(event);
				alert ('Warning: You have selected External Playlist as source of the videos for the player. ' +
						'You will be allowed to play around with it – save, edit and preview the player, but ' +
						'you cannot publish it. The player will load only from your account. ' + "\n\n" +
						'The External Playlist feature is fully available only for Business Max users!');
			}
			//return false;
		}
	},

	onShowOnlyPublicChange: function () {
		$('embed_tr_show_private_mark').style.display = this.inputs.only_public.checked ? 'none':'';
	},

	// ads functions
	getPlaylistVideosAsOptions: function (listid, select) {
		var pl = SavedPlaylists.getListById (listid);
		select.innerHTML = '';
		if (pl) {
			for (var i = 0, n = pl.videos.length; i < n; i ++) {
				var opt = document.createElement('option');
				opt.value = pl.videos[i].mid;
				opt.innerHTML = pl.videos[i].title;
				select.appendChild(opt);
			}
		}
	},
	onPrerollShowChange: function () {
		$('embed_pre_roll_ad_list_l').style.display = $('embed_pre_roll_ad_v1_tr').style.display =
			$('embed_pre_roll_ad_v2_tr').style.display = this.inputs.pre_roll_playlist.style.display =
			this.inputs.pre_roll_ad_show.checked?'':'none';
	},
	onPrerollListChange: function () {
		// build the videos select box
		var plid = this.inputs.pre_roll_playlist.getSelected();
		this.getPlaylistVideosAsOptions(plid, this.inputs.pre_roll_video_sel);
		this.inputs.pre_roll_video_sel.selectedIndex = 0;
	},

	onMidrollShowChange: function () {
		$('embed_mid_roll_ad_list_l').style.display = $('embed_mid_roll_ad_v1_tr').style.display =
			$('embed_mid_roll_ad_v2_tr').style.display = $('embed_mid_roll_ad_v3_tr').style.display =
			this.inputs.mid_roll_playlist.style.display =
			this.inputs.mid_roll_ad_show.checked?'':'none';
	},
	onMidrollListChange: function () {
		// build the videos select box
		var plid = this.inputs.mid_roll_playlist.getSelected();
		this.getPlaylistVideosAsOptions(plid, this.inputs.mid_roll_video_sel);
		this.inputs.mid_roll_video_sel.selectedIndex = 0;
	},

	onPostrollShowChange: function () {
		$('embed_post_roll_ad_list_l').style.display = $('embed_post_roll_ad_v1_tr').style.display =
			$('embed_post_roll_ad_v2_tr').style.display = this.inputs.post_roll_playlist.style.display =
			this.inputs.post_roll_ad_show.checked?'':'none';
	},
	onPostrollListChange: function () {
		// build the videos select box
		var plid = this.inputs.post_roll_playlist.getSelected();
		this.getPlaylistVideosAsOptions(plid, this.inputs.post_roll_video_sel);
		this.inputs.post_roll_video_sel.selectedIndex = 0;
	},

	getPlayersWithPlaylist: function (id) {
		var res = new Array();
		for (var i = 0, n = this.embeddedPlayers.length; i < n; i ++)
			if (this.embeddedPlayers[i].jsonObj.ds == EmbedPlayer.EMBED_SAVED_LIST && this.embeddedPlayers[i].jsonObj.jsonObj.id == id)
				res.push(this.embeddedPlayers[i].jsonObj);
		return res;
	},

	fixGeneralPreviewImages: function () {
		var et = this.inputs.embed_type.getSelected();
		var pt = this.inputs.playlist_type.getSelected();
		if (et == 1) { // fixed
			$('embed_player_type_select_example').className = 'emb_example fixedplayer' + pt;
			$('embed_playlist_type_select_example').style.display = 'none';
		} else if (et == 2) { //pop out
			$('embed_player_type_select_example').className = 'emb_example popoutplayer' + pt;
			$('embed_playlist_type_select_example').style.display = 'none';
		} else if (et == 3) { // video wall
			$('embed_player_type_select_example').className = 'emb_example videowall';
			$('embed_playlist_type_select_example').className = 'emb_example fixedplayer' + pt;
			$('embed_playlist_type_select_example').style.display = 'block';
		} else if (et == 4) { // list box
			$('embed_player_type_select_example').className = 'emb_example listbox';
			$('embed_playlist_type_select_example').className = 'emb_example fixedplayer' + pt;
			$('embed_playlist_type_select_example').style.display = 'block';
		} else if (et == 5) { // horizontal box
			$('embed_player_type_select_example').className = 'emb_example horizontal';
			$('embed_playlist_type_select_example').className = 'emb_example fixedplayer' + pt;
			$('embed_playlist_type_select_example').style.display = 'block';
		} else if (et == 6) { // flashonly
			$('embed_player_type_select_example').className = 'emb_example flashonly';
			$('embed_playlist_type_select_example').style.display = 'none';
		}
	},
	onImagesSelectorBoxShow: function () {
		this.element.style.display = 'none';
	},
	onImagesSelectorBoxHide: function () {
		this.element.style.display = 'block';
	},

	onAutostartChange: function () {
		var et = this.getEmbedTypeID();
		if (et == 1 || et == 6)
			$('autostart_off_preimage_option').style.display = this.form.autostart.checked?'none':'';
		else
			$('autostart_off_preimage_option').style.display = 'none';
	},

	createSimpleEmbed: function (jsonObj) {
		showBackground();
		var id = jsonObj.id;//.replace (/-/g,'_');
		this._currentSimpleEmbedVideo = jsonObj;
		$('create_simple_embed_dialog').style.display = 'block';
		$('simple_embed_code').value = '<div id="IDTVP_simple' + id + '" class="idesktop_tv_player idtv_simple' + id + '">iDesktop.tv</div>\n' +
				'<script type="text/javascript" src="http://' + CHOST + '/embed/simple' + id + '/complete.js?t=' + ThemesChooser.getCurrentThemeName() + '"></script>';
	},
	closeSimpleEmbed: function () {
		hideBackground();
		$('create_simple_embed_dialog').style.display = '';
		this._currentSimpleEmbedVideo= null;
	},
	extendSimpleEmbed: function () {
		if (!user_name) {
			this.closeSimpleEmbed();
			showLoginOrRegisterForm();
			return;
		}
		if (!UserLimits.isUserAllowedTo(UserLimits.ua_create_custom_player, true)) return false;
		var video = this._currentSimpleEmbedVideo;
		this.closeSimpleEmbed();
		this.open (EmbedPlayer.EMBED_SINGLE_VIDEO, video, null);
	},
	checkUserChannelName: function () {
		var name = this.form.embed_search_user_channel.value;
		if (!name)	 {
			alert ('Please enter username or channel name to check first!');
			return;
		}
		new Ajax.Request ('/check_user_channel_exists.php?name=' + name, {onSuccess: this.checkUserChannelName_handler.bind(this)});
		$('check_user_channel_name_button').innerHTML = 'Checking name...';
		$('check_user_channel_name_preloader').style.display = 'inline';
	},
	checkUserChannelName_handler: function (ajaxRequest) {
		$('check_user_channel_name_preloader').style.display = 'none';
		var jsonObj;
		eval ('jsonObj = ' + ajaxRequest.responseText);
		if (jsonObj && jsonObj.exists) {
			$('check_user_channel_name_button').innerHTML = 'Excellent, we\'ve found the channel!';
			this.form.embed_search_user_channel.value = jsonObj.name;
		} else {
			$('check_user_channel_name_button').innerHTML = 'Channel does not exist!';
		}
	},
	onUserChannelNameChange: function () {
		$('check_user_channel_name_button').innerHTML = 'check name';
	},

	checkYouTubePlaylistURL: function () {
		var url = this.form.youtube_playlist_url.value;
		var regex = /youtube.*\/view_play_list\?p=(.{16})(&.*)?/;
		var chunk;
		if (! regex.test(url)) {
			var regex2 = /youtube.*\/user\/[^\/]*#[a-z]\/[a-z]\/(.{16})/; // */
			if (! regex2.test(url)) {
				$('check_youtube_playlist_url').innerHTML = 'specified url is not valid';
				return;
			} else {
				chunk = regex2.exec(url);
			}
		} else 
			chunk = regex.exec(url);
		
		var id = chunk[1];
		new Ajax.Request ('/check_yt_playlist.php?plid=' + id, {onSuccess: this.checkYouTubePlaylistURL_handler.bind(this)});
		$('check_youtube_playlist_url').innerHTML = 'Checking url...';
		$('check_youtube_playlist_url_preloader').style.display = 'inline';
	},
	checkYouTubePlaylistURL_handler: function (ajaxRequest) {
		$('check_youtube_playlist_url_preloader').style.display = 'none';
		var jsonObj;
		eval ('jsonObj = ' + ajaxRequest.responseText);
		if (jsonObj.exists)
			$('check_youtube_playlist_url').innerHTML = 'Excellent, we\'ve found the playlist';
		else
			$('check_youtube_playlist_url').innerHTML = 'Playlist does not exist';
	},
	onYouTubePlaylistURL_change: function () {
		$('check_youtube_playlist_url').innerHTML = 'check playlist url';
	},

	getSingleVideoID: function () {
		var url = this.form.embed_single_video_url.value;
		var r = /(http\:\/\/)?.*youtube\.com\/watch\?v=([^&]{11}).*/;
		var r2 = /(http\:\/\/)?.*idesktop\.tv\/\?watch=([^&]{11}).*/;
		if (r.test(url))
			return r.exec(url).last();
		else if (r2.test(url))
			return r2.exec(url).last();
		else
			return false;
	},

	checkSingleVideoURL: function () {
		if (! this.form.embed_single_video_url.value) {
			$('check_single_video_url_button').innerHTML = 'Please enter a valid URL';
			return;
		}
		var id = this.getSingleVideoID();
		if (!id) {
			$('check_single_video_url_button').innerHTML = 'Wrong URL format';
		} else {
			$('check_single_video_url_button').innerHTML = 'Looking for video...';
			$('check_single_video_url_preloader').style.display = 'inline';
			new Ajax.Request ('/get_details.php?id=' + id + '&nocomments=1', {onSuccess: this.checkSingleVideoURL_handler.bind(this)});
		}
	},
	checkSingleVideoURL_handler: function (ajaxRequest) {
		$('check_single_video_url_preloader').style.display = 'none';
		var jsonObj;
		eval ('jsonObj = ' + ajaxRequest.responseText);
		if (jsonObj.error == 404)
			$('check_single_video_url_button').innerHTML = 'Video not found!';
		else if (jsonObj.isprivate)
			$('check_single_video_url_button').innerHTML = 'Video found but is private!';
		else
			$('check_single_video_url_button').innerHTML = 'Excellent, we\'ve found the video';

	},
	onSingleVideoURLChange: function () {
		$('check_single_video_url_button').innerHTML = 'Check if video exists';
	},

	setUserPayPlanLimits: function () {
		if (!UserLimits.isUserAllowedTo(UserLimits.ua_remove_idesktop_branding)) {
			this.imagesSelector.setOptions('player_logo', {enabled: false, disabledText: 'iDesktop.tv Logo' });
			this.inputs.player_logo_url.value = 'http://www.idesktop.tv/';
			$('emb_player_custom_logo_link_tr').style.display = '';
			this.inputs.player_logo_url.disabled = true;
		} else {
			this.imagesSelector.setOptions('player_logo', {enabled: true, disabledText: ''});
			this.inputs.player_logo_url.disabled = false;
		}
		var en = UserLimits.isUserAllowedTo(UserLimits.ua_set_custom_branding);
		this.imagesSelector.setOptions('title_logo', {enabled: en});
		this.imagesSelector.setOptions('playlist_logo', {enabled: en});

		/*this.inputs.pre_roll_ad_show.disabled = this.inputs.mid_roll_ad_show.disabled = this.inputs.post_roll_ad_show.disabled =
			UserLimits.isUserAllowedTo(UserLimits.ua_set_players_advertising)?false:true;*/
	},
	onAdvertisingCheckBoxClick: function () {
		return UserLimits.isUserAllowedTo(UserLimits.ua_set_players_advertising, true);
	},
	checkExternalPlaylist: function () {
		var url = this.inputs.external_playlist_url.value;
		window.open ('/developer/test-external-playlist.html?url=' + url);
	},
	onGAInputsFocus: function () {
		return UserLimits.isUserAllowedTo(UserLimits.ua_set_google_analytics, true);
	},

	onPlayerInfoPanelBackgroundSelectChange: function () {
		this.infoPanelBackgroundColor.element.style.visibility = this.inputs.player_info_back_sel.getSelected() == 'C' ? '' : 'hidden';
	},

	onPlayerInfoPanelTabButtonBackgroundChange: function () {
		this.infoPanelButtonBackgroundColor.element.style.visibility = this.inputs.player_info_btn_back_sel.getSelected() == 'C' ? '' : 'hidden';
	},

	onPlayerInfoPanelTabButtonFontColorChange: function () {
		this.infoPanelButtonFontColor.element.style.visibility = this.inputs.player_info_btn_color_sel.getSelected() == 'C' ? '' : 'hidden';
	},

	onPlayerTitleBarBackgroundChange: function () {
		this.playerTitleBackgroundColorPicker.element.style.visibility = this.inputs.player_title_bar_back.getSelected() == 'C' ? '' : 'hidden';
	},

	onShowAddthisChange: function () {
		$('embed_addthis_account_details').style.display = this.inputs.show_addthis_button.checked ? '' : 'none';
	}
}
