/* some config, may be changed by the theme*/
var ABOUT_BOX_SCROLL_BTN = "/images/big_scroll_btn.gif";
var MaxPagesShown = 12;
var MAX_PER_PAGE = 50;
var _uacct = "UA-1327111-7";
/* some variables */
var results = null; //the currently displayed results
var sid = 0;
var current_page = 1;
var last_search_string = '';
var last_search_category = -1;
var last_list_by = '';
var last_related_video_id = '';
var last_order = null;
var debug_last_search = '';

var hasFlashVersion = false;

/*var tr = null;
function search_input_key_pressed (event) {
	if (tr != null) clearTimeout(tr);
	tr = null;
	if (Event.getKey(event) != 13)
		tr = setTimeout('search()', 1000);
	else
		search();
}*/

function onSeachInputBlur () {
	this.onSearchInputChange();
	IEForceRedraw();
}

function onSeachInputFocus () {
	$('search_videos_text').style.display = 'none';
	IEForceRedraw();
}

function onSearchInputChange () {
	$('search_videos_text').style.display = ($('search_input').value == ''?'block':'none');
}
function searchInputClear() {
	$('search_input').value='';
	onSearchInputChange();
	$('search_input').focus();
	onSeachInputFocus();
}

function search (page, list_by, load_to_cache, keywords, videoID) {
	//console.info(arguments);
	/*if (tr != null) {
		clearTimeout(tr);
		tr = null;
	}*/
	if (!page) var page = 1;
	if (!list_by) var list_by = '';
	if (!load_to_cache) load_to_cache = false;

	if (keywords)
		var si = keywords;
	else
		var si = $('search_input').value;

	var sc = CategoriesChooser.selectedCategory.id;

	// detect URL entered: http://youtube.com/watch?v= and similar if list_by is ''
	if (list_by == '' || list_by == 'by_tag') {
		var RegExpr =  /(http\:\/\/)?.*youtube\.com\/watch\?v=([^&]{11}).*/;
		if (RegExpr.test(si) && !load_to_cache) {
			var ID = RegExpr.exec(si).last();
			rc.showLoadingAjax();
			openVideoById(ID);
			return false;
		}
		if (RegExpr_2.test(si) && !load_to_cache) {
			var ID = RegExpr_2.exec(si)[3];
			rc.showLoadingAjax();
			openVideoById(ID);
			return false;
		}
		var RegExpr_3 = /(http\:\/\/)?.*youtube\.com\/view_play_list\?p=(.+)/;
		if (RegExpr_3.test(si) && !load_to_cache) {
			var playlistID = RegExpr_3.exec(si).last();
			list_by = 'by_playlist';
		}
	}

	if (si.length < 1 && list_by == '') return false;

	if (sc > 0 && (list_by == '') || (list_by == 'by_tag'))
		list_by = 'by_category_and_tag';

	if (!load_to_cache) {
		rc.showLoadingAjax()
		if (si.length > 1 && list_by != 'standard_feed') {
			document.title = 'Search for ' + si + " | iDesktop.tv";
			PageFragment.set(si);
		} else {
			document.title = "iDesktop.tv";
			PageFragment.set('');
		}
	}

	sid ++;
	current_page = page;
	last_search_string = si;
	last_search_category =  sc;
	last_list_by = list_by;
	last_order = OrderChooser.selectedOrder.id;

	if (list_by == 'by_tag' || list_by == 'by_category_and_tag' ||
		list_by == 'user_uploads' || list_by == '') {
		OrderChooser.enable();
		if (!load_to_cache)
			urchinTracker('search/' + ( sc ? CategoriesChooser.selectedCategory.name + "/" : "" ) + si);
	} else {
		OrderChooser.disable();
		if (!load_to_cache)
			urchinTracker('list_' + last_list_by);
	}

	if (list_by == 'by_related' && videoID) {
		si = videoID;
		last_related_video_id = videoID;
	} else
		last_related_video_id = '';

	Hint.hide();

	switch(list_by) {
		case 'featured': document.title = "Featured Videos | iDesktop.tv"; break;
		case 'top_rated': document.title = "Top Rated Videos | iDesktop.tv"; break;
		case 'top_favorites': document.title = "Most Favored Videos | iDesktop.tv"; break;
		case 'most_viewed': document.title = "Most Viewed Videos | iDesktop.tv"; break;
		case 'most_popular': document.title = "Most Popular Videos | iDesktop.tv"; break;
		case 'most_recent': document.title = "Most Recent Videos | iDesktop.tv"; break;
		case 'most_discussed': document.title = "Most Discussed Videos | iDesktop.tv"; break;
		case 'most_responded': document.title = "Most Responded Videos | iDesktop.tv"; break;
		case 'recently_played': document.title = "My Last 50 Videos | iDesktop.tv"; break;
		case 'by_related': document.title = "Related to " + keywords + " | iDesktop.tv"; break;
		case 'user_favorites': document.title = "Favorite Videos of " + keywords + " | iDesktop.tv"; break;
		case 'user_uploads': document.title = "Videos by " + keywords + " | iDesktop.tv"; break;
	}

	var params = $H({keywords: si.replace(/\&|\?/g, ''),
		onlypublic: Settings.private_filter?1:0,
		ss: Settings.safe_search,
		sid:sid,
		page:page,
		list:list_by,
		category_id: sc,
		order:OrderChooser.selectedOrder.id,
		rpp: MAX_PER_PAGE,
		loadToCache: load_to_cache,
		playlist_id:playlistID});
	new Ajax.Request ('search.php?a=1', {
		method:'get',
		parameters: params.toQueryString(),
		onSuccess: result_handler
	});
	debug_last_search = params.toQueryString();

	this.onSearchInputChange();
	SavedSearches.update();

	//console.info('Search for ' + params.keywords + ' / ' + params.list + '/' + last_search_string + '/' + arguments.callee.caller.toString());

	return false;
}

function result_handler (response) {
	var json = response.responseText;
	var jsonObj = null;
	eval ('jsonObj = ' + json + '');
	if (!jsonObj) return;
	if (jsonObj.error) {
		rc.showError(jsonObj.error);
	}
	rc.showFavorites = false;
	if (jsonObj.sid == sid) {
		if (jsonObj.loadToCache)
			rc.ExtendCache_handler(jsonObj);
		else
			rc.loadResults(jsonObj);
	}
}

function OnLoadDocument () {
	if (typeof urchinTracker === "undefined") {
		window.urchinTracker = function () {};
	}
	urchinTracker();

	// check the user's browser and see if it supported!
	BrowserDetect.init();
	var supported = false;
	switch (BrowserDetect.browser) {
		case "Chrome": case "Firefox" : case "Safari": case "Camino": case "iCab": case "OmniWeb":
			supported = true; break;
		case "Explorer": supported = BrowserDetect.version >= 7; break;
		default: supported = false; break;
	}
	if (BrowserDetect.OS == 'IPhone/iPod')
		supported = false;
	if (!supported) {
		alert ("We are sorry to inform you that your browser is not in the list of supported ones.\n" +
			"You may experience problems using iDesktop.tv");
	}

	Hint.initialize('hint_container');
	ElementHint.initialize();
	Tray.initialize();
	CategoriesChooser.initialize();
	OrderChooser.initialize();
	dnd.initialize();
	Settings.initialize();
	mb = new MenuBar('menu_container');
	bc = new PlayersContainer('players_container', 'players_menu');
	ThemesChooser.initialize();
	Converter.initialize();
	Slider.initialize();
	rc = new ResultsContainer('results_container', 'player_chooser');
	SavedPlaylists.initialize();
	Favorites.initialize();
	EmbedPlayer.initialize();
	SavedSearches.initialize();
	UserLimits.initialize();

	OrderChooser.onChange = function () {search();};

	PageFragment.initialize();
	PageFragment.onChange = function () {
		if (last_list_by == 'by_related') return;
		$('search_input').value = PageFragment.get();
		search();
	}

	ElementHint.observe ($('register_user'), "Username", "<ul><li>You will use this to log in to iDesktop.tv</li><li>3-20 characters, letters, numbers and any other<br />characters are allowed</li></ul>");
	ElementHint.observe ($('register_check_user_available'), "Check availability", "You can check if the specified username is not already registered");
	ElementHint.observe ($('register_email'), "E-Mail address", "<ul><li>Provide valid email address.</li><li>Ex: yourname@yourdomain.com</li>" +
		"<li>We will send you verification email at the specified address</li><li>Only confirmed emails will be allowed access</li>" +
		"<li>We will never share your email with anyone</li></ul>");
	ElementHint.observe ($('register_pass'), "Password", "Please make sure it contains at least 6 characters<br />and you can remember it easily");

	var flashVersion = deconcept.SWFObjectUtil.getPlayerVersion();
	/*if (flashVersion.major == 0 && flashVersion.minor == 0 && flashVersion.rev == 0)
		hasFlashVersion = false;
	else*/
	hasFlashVersion = (flashVersion.versionIsValid({major:8, minor:0, rev:0}));

	check_login_onload();

	if (on_load_watch != '') {
		openVideoById(on_load_watch);
	} else if (on_load_playlist != '') {
		openPlaylistByHash(on_load_playlist);
	} else if (on_load_watch_embed) {
		if (on_load_watch_embed.feed) {
			search(1, "standard_feed", false, on_load_watch_embed.feed);
			if (on_load_playlist_sub)
				openVideoById(on_load_playlist_sub, false);
		} else if (on_load_watch_embed.channel) {
			OrderChooser.selectOrderById(1);
			search(1, "user_uploads", false, on_load_watch_embed.channel);
			if (on_load_playlist_sub)
				openVideoById(on_load_playlist_sub, false);
		} else if (on_load_watch_embed.keywords || on_load_watch_embed.list_by) {
			OrderChooser.selectOrderById(on_load_watch_embed.order_by);
			CategoriesChooser.selectCategoryById(on_load_watch_embed.category);
			$('search_input').value = on_load_watch_embed.keywords;
			search();
			if (on_load_playlist_sub)
				openVideoById(on_load_playlist_sub, false);
		} else
			bc.openSavedPlaylist({name:on_load_watch_embed_name, videos:on_load_watch_embed}, on_load_playlist_sub);
	} else if (on_load_watch_related) {
		show_videos_related(on_load_watch_related);
	} else if (on_load_watch_from) {
		show_videos_by_user (on_load_watch_from);
	}

	if (!on_load_watch && !on_load_watch_from && !on_load_watch_related && !on_load_watch_embed) {
		if (PageFragment.get() != '')
			PageFragment.onChange();
		else if ($('search_input').value.length < 1)
			search(1, "featured"); //search(1, 'popular');
		else if (last_list_by == '')
			search();
	}
	Event.observe(document, "mousedown", CloseAllMenus);
}

function CloseAllMenus(event) {
	// first - check if the event is for any of the menus

	// check if top menu
	var el = Event.element(event);

	while (el && el.parentNode && el.className != 'drop_menu')
		el = el.parentNode;

	if (el.className && el.className == 'drop_menu') {
		var el = Event.element(event);
		if (el.onclick)
			el.onclick(event)
		else if (el.parentNode.onclick)
			el.parentNode.onclick(event);
	}

	//check categories chooser
	var el = Event.element(event);
	if (el.parentNode && el.parentNode.id == 'categories_chooser_container') {
		if (el.onclick) el.onclick(event);
	}
	// check order by chooser
	var el = Event.element(event);
	if (el.parentNode && el.parentNode.id == 'order_by_chooser_container') {
		if (el.onclick) el.onclick(event);
	}
	// check saved searches chooser
	var el = Event.element(event);
	if (el.className == 'saved_search' || (el.parentNode && Element.hasClassName(el.parentNode,'saved_search')))
		if (el.onclick) {
			return; // no need to continue! The other menus should be closed anyway :)
			el.onclick(event);
			Event.stop(event);
		}

	// check tray popup menu
	var el = Event.element(event);
	if (Element.hasClassName(el, 'popup_menu_item') ||
		(el.parentNode && el.parentNode.className && Element.hasClassName(el.parentNode, 'popup_menu_item')) ||
		(Element.hasClassName(el, 'tray_item')) ) {
		if (el.onclick) el.onclick(event);
	}
	var el = Event.element(event);
	if (Element.hasClassName (el, 'me') && el.parentNode && Element.hasClassName (el.parentNode, 'playlist_menu_dropdown')) {
		var obs = Event.getObserver (el, 'click');
		if (obs) obs(event);
	}
	var el = Event.element(event);
	if (el.parentNode && el.parentNode.parentNode && el.parentNode.parentNode.id == 'user_limits_info_box' && el.tagName == 'A')
		return;
	mb.closeAllMenus();
	Tray.closeAllMenus();
	CategoriesChooser.closeAllMenus();
	OrderChooser.closeAllMenus();
	bc.closePlayerMenus();
	SavedSearches.hideDropDown();
	UserLimits.hideUserInfoBox();
}

var _openVideoById_searchRelated;
function openVideoById (ID, searchRelated) {
	if (arguments.length == 1) var searchRelated = true;
	_openVideoById_searchRelated = searchRelated;
	//we have to request the rest of the data for this video!
	var params = $H({id:ID})
	new Ajax.Request('get_details.php', {
		method:'get',
		parameters: params.toQueryString(),
		onSuccess:openVideoById_handler
	})
}

function openVideoById_handler (ajaxResponse) {
	var rt = ajaxResponse.responseText;
	var jsonObj = null;
	eval ("jsonObj = " + rt);
	if (jsonObj == null || jsonObj.error) return;
	if (_openVideoById_searchRelated)
		search(1,'by_related',false, jsonObj.title, jsonObj.id);
	bc.openVideo(jsonObj);
}

function openPlaylistByHash (hash) {
	var params = $H({p:hash})
	new Ajax.Request('get_playlist.php', {
		method:'get',
		parameters: params.toQueryString(),
		onSuccess:openPlaylistByHash_handler
	})
}

function openPlaylistByHash_handler (ajaxResponse) {
	var rt = ajaxResponse.responseText;
	var jsonObj = null;
	eval ("jsonObj = " + rt);
	if (jsonObj == null || jsonObj.error) return;
	if (on_load_playlist_sub)
		bc.openSavedPlaylist (jsonObj, on_load_playlist_sub);
	else
		bc.openSavedPlaylist(jsonObj);
	search(1,'',false, jsonObj.name);
}

function show_videos_by_user(username) {
	search(1, 'user_uploads', false, username);
}
function show_favorites_of_user(username) {
	search(1, 'user_favorites', false, username);
}
function show_videos_related (id, title) {
	search(1, 'by_related', false, arguments.length == 1 ? id : title, id);
}

function show_download_dialog() {
	$('download_dialog').style.display='block';
}

function dl_check_url(url) {
	if (url.length < 1) {
		alert ('Enter url of video at Youtube!');
		return false;
	}
	var RegExpr = /(http\:\/\/)?(www\.)?youtube.com\/watch\?v=(.+)/;
	if (!RegExpr.test(url)) {
		alert ('This is not valid url from Youtube!');
		return false;
	}

	return RegExpr.exec(url)[3];
}

function dl_as_flv() {
	var url = $('download_dialog_input').value;

	var id = dl_check_url(url);
	if (id == false) return;

	window.open('download_flv.php?id=' + id);
}

function dl_as_exe() {
	var url = $('download_dialog_input').value;

	var id = dl_check_url(url);
	if (id == false) return;

	Converter.startDownload(id, url);
	close_dl();
}

function close_dl() {
	$('download_dialog').style.display='none';
}

//////

function showBackground() {
	$('background').style.display = 'block';
	bc.pauseAllPlayers();
	bc.hideAllFlashObjects();
	Hint.hide();
	IEForceRedraw();
	/*if (isIE8)
		$('results_container').style.display = 'none';*/
}

function hideBackground() {
	$('background').style.display = 'none';
	bc.unpauseAllPlayers();
	bc.unhideAllFlashObjects();
	ElementHint.forceHide();// just in case, ok?
	/*if (isIE8)
		$('results_container').style.display = '';*/
}

function isBackgroundVisible () {
	return $('background').style.display == 'block';
}

function IEForceRedraw () {
	if (isIE)
		setTimeout("IEForceRedraw_h()", 20);
}

function IEForceRedraw_h () {
	//rc.fixResultsVisibility();
	$('m_top').style.width = ($('m_top').style.width?'':'100%');
	$('m_1').style.width = ($('m_1').style.width?'':'100%');
	$('m_2').style.width = ($('m_2').style.width?'':'100%');
	$('m_3').style.width = ($('m_3').style.width?'':'100%');
	$('m_bottom_links').style.width = ($('m_bottom_links').style.width?'':'100%');
	$('results_container').style.top = ($('results_container').style.top?'':'95px');
	$('m_bottom').style.width = ($('m_bottom').style.width?'':'100%');
}

function clear_last_played() {
	if (!user_name) {
		alert ('You have to log in first!');
		return;
	}
	if (confirm ('Are you sure you want to delete the history of your last played videos?'))
		new Ajax.Request('clear_last_played.php', {});
}

function embedSearchResults () {
	if (rc.showFavorites) {
		EmbedPlayer.open(EmbedPlayer.EMBED_FAVORITES, {videos:Favorites.favorites}, null);
	} else {
		EmbedPlayer.open(EmbedPlayer.EMBED_SEARCH_RESULTS, {keywords: last_search_string, list_by: last_list_by,
			category: last_search_category, order_by: OrderChooser.selectedOrder.id}, null); /*  , videos: rc.getResultsJson(5)*/
	}
}

var PageFragment = {
	initialize: function () {
		this.oldFragment = this.get();
		this.timer = setInterval (this.checkForChange.bind(this), 1000);
	},
	checkForChange: function () {
		if (this.oldFragment != this.get()) {
			this.oldFragment = this.get();
			if (this.onChange) this.onChange();
		}
	},
	get: function () {
		var s = new String(document.location.href);
		var a = /.*#(.*)/.exec(s);
		if (a && a.length == 2)
			return decodeURI(a[1]);
		else
			return '';
	},
	set: function (text) {
		if (this.get() == '') { // the problem is that the url may end in #
			var s = new String(document.location.href);
			document.location = s.replace(/(.*)#/, '$1') + '#' + text;
		} else {
			var a = new String(document.location);
			document.location.href = a.replace(/(.*)(#.*)/, '$1#' + text);
		}
		this.oldFragment = text;
	}
}

function downloadFlashPlayer () {
	if (confirm("You do not have  Adobe Flash Player installed or version is too old\n" +
		"Without it you will not be able to view any videos!\n\n" +
		"Do you want to download and install it?")) {
			window.open ("http://www.macromedia.com/go/getflashplayer");
			return true;
		} else
			return false;
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent) || this.searchVersion(navigator.appVersion) || "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{string: navigator.userAgent,subString: "Chrome",identity: "Chrome"},
		{string: navigator.userAgent,subString: "OmniWeb",versionSearch: "OmniWeb/",identity: "OmniWeb"},
		{string: navigator.vendor,subString: "Apple",identity: "Safari",versionSearch: "Version"},
		{prop: window.opera,identity: "Opera"},
		{string: navigator.vendor,subString: "iCab",identity: "iCab"},
		{string: navigator.vendor,subString: "KDE",	identity: "Konqueror"},
		{string: navigator.userAgent,subString: "Firefox",identity: "Firefox"},
		{string: navigator.vendor,subString: "Camino",identity: "Camino"},
		// for newer Netscapes (6+)
		{string: navigator.userAgent,subString: "Netscape",identity: "Netscape"},
		{string: navigator.userAgent,subString: "MSIE",	identity: "Explorer",versionSearch: "MSIE"},
		{string: navigator.userAgent,subString: "Gecko",identity: "Mozilla",versionSearch: "rv"},
		// for older Netscapes (4-)
		{string: navigator.userAgent,subString: "Mozilla",identity: "Netscape",versionSearch: "Mozilla"}
	],
	dataOS : [{string: navigator.platform,subString: "Win",identity: "Windows"},
		{string: navigator.platform,subString: "Mac",identity: "Mac"},
		{string: navigator.userAgent,subString: "iPhone",identity: "iPhone/iPod"},
		{string: navigator.platform,subString: "Linux",identity: "Linux"}
	]
};

var SavedSearches = {
	itemHeight: 26,
	initialize: function () {
		this.element = $('user_searches_container');
		this.headElement = $('user_searches_head');
		this.dropDown = $('user_searches_dropdown');
		this.addBtn = $('user_searches_add_btn');
		this.headElement.onclick = this.switchDropDownElement.bindAsEventListener(this);
		this.addBtn.onclick = this.addSavedSearch.bindAsEventListener(this);
		this.noSearchesElement = document.createElement('div');
		this.noSearchesElement.innerHTML = 'You have no saved searches yet!';
		this.noSearchesElement.className = 'none';
		this.dropDown.appendChild (this.noSearchesElement);

		if ((BrowserDetect.browser == "Firefox" && BrowserDetect.version >= 3) || BrowserDetect.browser == "Chrome")
			$('search_container').style.cssFloat = 'right';
		this.miSearchFor = new SavedSearches.DDElement (this.dropDown, {title:'Search For'});
		this.miVideosBy = new SavedSearches.DDElement (this.dropDown, {title:'Videos By'});
		this.miRelatedTo = new SavedSearches.DDElement (this.dropDown, {title:'Related To'});
		this.miFavoritesOf = new SavedSearches.DDElement (this.dropDown, {title:'Favorites Of'});

		this.matchArray = {'':'miSearchFor', 'by_tag': 'miSearchFor', 'by_category_and_tag': 'miSearchFor',
			'user_uploads': 'miVideosBy', 'user_favorites': 'miFavoritesOf', 'by_related': 'miRelatedTo'};
		Event.observe(window, 'resize', this.onWindowResize.bind(this));
		this.onWindowResize();

		this.alertObject = new ElementHintFading ( {} );
		this.element.appendChild(this.alertObject.element);
	},
	onWindowResize: function () {
		var h = windowHeight();
		this.maxItemsBeforeScroll = Math.floor((h / 2) / this.itemHeight);
		this.updateCount();
	},
	onUserLoggedIn: function () {
		this.element.style.display = 'block';
		this.loadSearches();
	},
	onUserLoggedOut: function () {
		this.element.style.display = '';
		this.clearSearches();
	},

	showDropDown: function () {
		this.dropDown.style.display = 'block';
		//this.dropDown.style.left = Position.cumulativeOffset(this.element)[0] - 15 + "px";
		this.dropDown.style.left = (this.element.offsetLeft > 0 ? this.element.offsetLeft : this.element.parentNode.parentNode.offsetLeft) + 30 + "px";
		this.dropDownVisible = true;
	},
	hideDropDown: function () {
		this.dropDown.style.display = 'none';
		this.dropDownVisible = false;

		this.miSearchFor.hideDropDown();
		this.miVideosBy.hideDropDown();
		this.miRelatedTo.hideDropDown();
		this.miFavoritesOf.hideDropDown();
	},
	switchDropDownElement: function () {
		if (this.dropDownVisible) this.hideDropDown(); else this.showDropDown();
	},

	loadSearches: function () {
		new Ajax.Request ('/saved_searches_get.php', {onSuccess: this.loadSearches_handler.bind(this), method:'post'});
	},
	loadSearches_handler: function (ajaxRequest) {
		if (!this.savedSearches) this.savedSearches = new Array ();
		this.clearSearches();
		this.noSearchesElement.style.display = 'none';
		var jsonObj = null;
		eval ('jsonObj = ' + ajaxRequest.responseText);

		if (jsonObj && !jsonObj.error) {
			for (var i = 0; i < jsonObj.searches.length; i ++) {
				var ns = jsonObj.searches[i];
				switch (ns.list_by) {
					case '': case 'by_tag':
					case 'by_category_and_tag': ns.title = /*'Search for ' +*/ ns.keywords; break;
					case 'user_uploads': ns.title = /*'Videos by ' +*/ ns.keywords; break;
					case 'user_favorites': ns.title = /*'Favorites of ' +*/ ns.keywords; break;
					case 'by_related': {
						try {
							eval ('ns.video = ' + ns.keywords + ';');
						} catch (e) {};
						ns.title = /*'Related to video ' +*/ (ns.video.title || ''); break;
					}
				}
				this[this.matchArray[ns.list_by]].addSubElement(ns);
			}
			this.searchesCount = jsonObj.searches.length;
			this.updateCount();
		}
	},
	clearSearches: function () {
		this.hideDropDown();
		/*for (var i = 0; i < this.savedSearches.length; i ++) {
			this.savedSearches[i].element.onclick = null; // remove the function reference first, prevent memory leak!
			this.dropDown.removeChild (this.savedSearches[i].element);
		}
		this.savedSearches.length = 0; // then clear all
		this.dropDown.innerHTML = '';*/
		this.miSearchFor.clearSubElements();
		this.miVideosBy.clearSubElements();
		this.miRelatedTo.clearSubElements();
		this.miFavoritesOf.clearSubElements();
		this.searchesCount = 0;
	},
	addSavedSearch: function () {
		var params = {keywords: last_search_string, category: last_search_category, list_by: last_list_by, order: last_order};

		var cat;
		var compare;
		switch (params.list_by) {
			case '':
			case 'by_tag':
				cat = this.miSearchFor;
				compare = function (a, b) {return a.keywords == b.keywords && a.order == b.order; };
				break;
			case 'by_category_and_tag':
				cat = this.miSearchFor;
				compare = function (a, b) {return a.keywords == b.keywords && a.order == b.order && a.category == b.category; };
				break;
			case 'user_uploads':
				cat = this.miVideosBy;
				compare = function (a, b) { return a.keywords == b.keywords; };
				break;
			case 'user_favorites':
				cat = this.miFavoritesOf;
				compare = function (a, b) { return a.keywords == b.keywords; };
				break;
			case 'by_related':
				cat = this.miRelatedTo;
				compare = function (a, b) { return a.keywords == b.video.id; }; // attention here!!!
				break;
			default: return false;
		}
		var eq = false;
		for (var i = 0; i < cat.subElements.length; i ++) {
			if (compare (params, cat.subElements[i].options)) {
				alert('Search already exists, no need to add it again.');
				return;
			}
		}

		new Ajax.Request ('/saved_searches_add.php', {parameters: $H(params).toQueryString(), method:'post', onSuccess: this.addSavedSearch_handler.bind(this)});

	},
	addSavedSearch_handler: function (ajaxRequest) {
		var jsonObj;
		eval ('jsonObj = ' + ajaxRequest.responseText);
		this.alertObject.show(jsonObj.message);
		this.loadSearches();
	},
	onSSClick: function (ss) {
		this.loadSearch (ss);
		this.hideDropDown();
	},
	loadSearch: function (sso) {
		var ss = sso.options;
		if (ss.category)
			CategoriesChooser.selectCategoryById(ss.category);
		if (ss.order)
			OrderChooser.selectOrderById(ss.order);
		if (ss.list_by == '' || ss.list_by == 'by_tag' || ss.list_by == 'by_category_and_tag')
			$('search_input').value = ss.keywords;
		if (ss.list_by == 'by_related')
			search (0, ss.list_by, false, ss.video.id, ss.video.id);
		else
			search (0, ss.list_by, false, ss.keywords);
	},

	onDeleteSearchClick: function (sso) {
		if (!this.dropDownVisible) return;
		if (!confirm ("Are you sure you want to delete this saved search?")) {
			this.hideDropDown();
			IEForceRedraw();
			return;
		}
		this.hideDropDown();
		IEForceRedraw();
		new Ajax.Request ('/saved_searches_delete.php', {parameters: $H({id: sso.options.id}).toQueryString(), method:'post'});
		sso.deleted();
		this.searchesCount --;
		this.updateCount();
	},
	updateCount: function ( ) {
		//this.headElement.innerHTML = "Saved searches (" + this.savedSearches.length + ")";
		//this.headElement.innerHTML = "Quick Search";
		this.miSearchFor.setVisibility();
		this.miVideosBy.setVisibility();
		this.miRelatedTo.setVisibility();
		this.miFavoritesOf.setVisibility();
		this.noSearchesElement.style.display = (this.searchesCount == 0 ? 'block' : 'none');
	},
	update: function () {
		switch (last_list_by) {
			case '': case 'by_tag':
			case 'by_category_and_tag':
				/*this.headElement.innerHTML = 'Search for ' + last_search_string;
				this.element.style.display = '';
				break;*/
			case 'user_uploads':
				/*this.headElement.innerHTML = 'Videos by ' + last_search_string;
				this.element.style.display = '';
				break;*/
			case 'user_favorites':
				/*this.headElement.innerHTML = 'Favorites of ' + last_search_string;
				this.element.style.display = '';
				break;*/
			case 'by_related':
				/*this.headElement.innerHTML = 'Related to video ' + last_search_video_name; */
				this.addBtn.style.visibility = '';
				break;
			default:
				//this.headElement.innerHTML = 'Saved Searches';
				this.addBtn.style.visibility = 'hidden';
				break;
		}
	},
	clearSavedSearches: function () {
		if (!user_name) {
			alert ('You have to log in first!');
			return;
		}
		if (confirm ('Are you sure you want to delete all your saved quick searches?')) {
			new Ajax.Request('/saved_searches_clear.php', {});
			this.clearSearches();
			this.searchesCount = 0;
			this.updateCount();
		}
		IEForceRedraw();
	}
}

SavedSearches.DDElement = Class.create();
SavedSearches.DDElement.prototype = {
	initialize:function (container, options) {
		this.container = $(container);
		this.options = options;
		this.element = document.createElement('div');
		this.element.innerHTML = this.options.title;
		this.element.className = 'saved_search_head';
		this.element.onmouseover = this.onMouseOver.bindAsEventListener(this);
		this.element.onmouseout= this.onMouseOut.bindAsEventListener(this);
		this.container.appendChild(this.element);
		this.subContainerOut = document.createElement('div');
		this.subContainerOut.className = 'saved_search_dd';
		this.subContainer = document.createElement('div');
		this.subContainer.className = 'in';
		this.subContainerScroll = document.createElement('div');
		this.subContainerScroll.className = 'sb';
		this.scroll = new Scrollbar (this.subContainer, this.subContainerScroll);

		this.element.appendChild(this.subContainerOut);
		this.subContainerOut.appendChild (this.subContainer);
		this.subContainerOut.appendChild (this.subContainerScroll);
		this.subElements = new Array();
		this.needsUpdating = true;
	},
	onMouseOver: function () {
		this.showDropDown();
	},
	onMouseOut: function (event) {
		if (isIE) {
			var px = Event.pointerX(event);
			var py = Event.pointerY(event);
			if (Position.within(this.subContainerOut, px, py)) return;
		}
		this.hideDropDown();
	},
	hideDropDown: function () {
		this.subContainerOut.style.display = 'none';
	},
	showDropDown: function () {
		this.subContainerOut.style.display = 'block';
		if (this.scrollIsVisible && this.needsUpdating) {
			this.scroll.update();
			this.needsUpdating = false;
		}
	},
	addSubElement: function (options) {
		this.subElements.push (new SavedSearches.DDSubElement(this, options));
		this.needsUpdating = true;
	},
	clearSubElements: function () {
		for (var i = this.subElements.length - 1; i >=0; i --)
			this.subElements[i].remove();
		this.subElements.length = 0;
		this.needsUpdating = true;
	},
	hide: function () {
		this.element.style.display = 'none';
	},
	show: function () {
		this.element.style.display = '';
	},
	setVisibility: function () {
		if (this.subElements.length > 0) {
			this.show();
			Element.addClassName (this.subElements[0].element, 'first');
		} else
			this.hide();
		this.scrollIsVisible = (this.subElements.length > SavedSearches.maxItemsBeforeScroll);
		if (this.scrollIsVisible) {
			Element.addClassName (this.subContainerOut, 'with_scroll');
			this.subContainer.style.height = SavedSearches.maxItemsBeforeScroll * SavedSearches.itemHeight + 'px';
		} else {
			Element.removeClassName (this.subContainerOut, 'with_scroll');
			this.subContainer.style.height = 'auto';
		}
		this.needsUpdating = true;
	},
	removeSub: function (e) {
		this.subElements = this.subElements.without(e);
		e.remove();
		this.needsUpdating = true;
	}
}
SavedSearches.DDSubElement = Class.create();
SavedSearches.DDSubElement.prototype = {
	initialize: function (container, options) {
		this.options = options;
		this.container = container;
		this.element = document.createElement('div');
		this.element.className = 'saved_search';
		this.elementName = document.createElement ('span');
		this.elementName.innerHTML = this.options.title;
		this.elementName.onclick = SavedSearches.onSSClick.bind(SavedSearches, this);
		this.delBtn = document.createElement('div');
		this.delBtn.className = 'del';
		this.delBtn.onclick = SavedSearches.onDeleteSearchClick.bind(SavedSearches, this);
		this.container.subContainer.appendChild(this.element);
		this.element.appendChild(this.delBtn);
		this.element.appendChild(this.elementName);
	},
	remove: function () {
		this.container.subContainer.removeChild(this.element);
	},
	deleted: function () {
		this.container.removeSub(this);
	}
}