
// ----------------------------- functions to show/hide the main menu --------------------------
//var mainmenu_visible = true;
//var mainmenu_width = 210;
//var mainmenu_effect_running = false;   // avoid another click to get in the way of the running effect
// //var omainmenu = document.getElementById('divMainMenu');

function init_hide_mainmenu() {
	hidingMainMenu();
}

// init the main menu state vars from the cookie
/*if (readCookie('radius_mainmenuhidden')=='1') {
	//setTimeout('init_hide_mainmenu()', 300);
	mainmenu_visible = false;
	mainmenu_width = 0;
}*/


function hidingMainMenu() {
	var omainmenu = document.getElementById('divMainMenu');
	if (mainmenu_width > 0) {
		mainmenu_width -= 20;
		if (mainmenu_width < 0) mainmenu_width = 0;
		omainmenu.style.width = mainmenu_width + 'px';
		omainmenu.style.marginLeft = -(210-mainmenu_width) + 'px';
		//document.getElementById('divMainArea').style.marginLeft = mainmenu_width + 'px';
		window.setTimeout("hidingMainMenu()", 15);
	} else {
		omainmenu.style.display = 'none';
		omainmenu.style.width = '0px';
		//document.getElementById('divMainArea').style.marginLeft = '0px';
		mainmenu_visible = false;
		mainmenu_effect_running = false;
		writeCookie('kau_mainmenuhidden', '1');
		
		document.getElementById('divMainAreaContainer').style.width = '100%';
	}
}
function showingMainMenu() {
	var omainmenu = document.getElementById('divMainMenu');
	if (mainmenu_width < 210) {
		mainmenu_width += 20;
		if (mainmenu_width > 210) mainmenu_width = 210;
		omainmenu.style.width = mainmenu_width + 'px';
		omainmenu.style.marginLeft = -(210-mainmenu_width) + 'px';
		//document.getElementById('divMainArea').style.marginLeft = mainmenu_width + 'px';
		window.setTimeout("showingMainMenu()", 15); // 15
	} else {
		omainmenu.style.width = '210px';
		omainmenu.style.marginLeft = '0px';
		//document.getElementById('divMainArea').style.marginLeft = '210px';
		mainmenu_visible = true;
		mainmenu_effect_running = false;
		writeCookie('kau_mainmenuhidden', '0');
		
		document.getElementById('divMainAreaContainer').style.width = GetPageClientWidth() - 252 + 'px';   // initially to prevent a bug in IE..
	}
}

function ShowHideMainMenu() {
	if (mainmenu_effect_running) return;
	
	mainmenu_effect_running = true;
	if (mainmenu_visible) {
		hidingMainMenu();
		//omainmenu.style.display = 'none';
		//omainmenu.style.width = '0px';
		//document.getElementById('divMainArea').style.marginLeft = '0px';
		//mainmenu_visible = false;
	} else {
		var omainmenu = document.getElementById('divMainMenu');
		omainmenu.style.display = 'block';
		document.getElementById('divMainAreaContainer').style.width = GetPageClientWidth() - 252 + 'px';
		showingMainMenu();
		//omainmenu.style.display = '';
		//omainmenu.style.width = '210px';
		//document.getElementById('divMainArea').style.marginLeft = '210px';
		//mainmenu_visible = true;
	}
}
// ------------------------------------------------------------------------------






function galleryshowimg(url) {
	document.getElementById('imgProfileBigger').src=url;
	document.getElementById('aProfileBigger').href=url.replace(/_thumb2/,'');
}

function contactsaboutchange() {
	var ind = document.getElementById('lstAbout').selectedIndex;
	document.getElementById('spanAboutOther').style.visibility = (ind==3)?'visible':'hidden';
}



function loginufocus(f, d) {
	var fref = document.getElementById(f);
	if (fref.value == d) {
		fref.value = '';
	}
}
function loginublur(f, d) {
	var fref = document.getElementById(f);
	if (fref.value == '') {
		fref.value = d;
	}
}
function loginpfocus(e) {
	if (!e) var e = window.event;   // IE
	var target;
	if (e.target) target = e.target;
	else if (e.srcElement) target = e.srcElement;
	
}
function loginpblur(e) {
	if (!e) var e = window.event;   // IE
	var target;
	if (e.target) target = e.target;
	else if (e.srcElement) target = e.srcElement;
	
}





//------------------------ functions to work with profile tooltips
var profiles_popup_data = new Array();   // set this array in a page: profiles_popup_data[user_id] = new Array('username','age','quarter',1[or 0])
var divProfilePreviewWidth = 168;
var divProfilePreviewHeight = 68;

function ShowProfilePopup(userid, event) {
	var x, y;
	
	var divpopup = document.getElementById('divProfilePopup');
	//var imgpage = document.getElementById(imgtag);
	//var imgPreviewProfileSrc = imgpage.src; //.replace(/_thumb.jpg/gi, '.gif');
	//var imgInprev = document.getElementById('imgProfilePreview');
	var divUsername = document.getElementById('divProfilePopupUsername');
	var divAge = document.getElementById('divProfilePopupAge');
	var divQuarter = document.getElementById('divProfilePopupQuarter');
	var divOnline = document.getElementById('divProfilePopupOnline');
	
	//imgInprev.src = imgPreviewProfileSrc;
	
	divUsername.innerHTML = profiles_popup_data[userid][0];
	divAge.innerHTML = 'на ' + profiles_popup_data[userid][1] + ' г.';
	divQuarter.innerHTML = 'кв. <strong>' + profiles_popup_data[userid][2] + '</strong>';
	divOnline.innerHTML = (profiles_popup_data[userid][3]) ? 'Онлайн' : 'Офлайн';
	divOnline.className = (profiles_popup_data[userid][3]) ? 'on' : 'off' ;
	
//	x = getRealLeft(imgtag);
//	y = getRealTop(imgtag);
//	x += document.getElementById(imgtag).width;
//	divprev.style.left = x+'px';
//	divprev.style.top = y+'px';
	var m_x = event.clientX+14;
	var m_y = event.clientY+14;
	
	if ( (divProfilePreviewWidth+6) > (GetPageClientWidth()-m_x) ) {
		m_x -= divProfilePreviewWidth;
		m_x -= 28;
	}
	if ( (divProfilePreviewHeight+6) > (GetPageClientHeight()-m_y) ) {
		m_y = GetPageClientHeight() - divProfilePreviewHeight - 6;
	}

	divpopup.style.left = m_x+'px';
	divpopup.style.top = m_y+GetIndexYOffset()+'px';
	
	divpopup.style.display = 'block';
}

function HideProfilePopup() {
	var divpopup = document.getElementById('divProfilePopup');
	//var imgInprev = document.getElementById('imgProfilePreview');
	var divUsername = document.getElementById('divProfilePopupUsername');
	var divAge = document.getElementById('divProfilePopupAge');
	var divQuarter = document.getElementById('divProfilePopupQuarter');
	var divOnline = document.getElementById('divProfilePopupOnline');
	
	//imgInprev.src = 'img/transp10x10.gif';
	divUsername.innerHTML = '';
	divAge.innerHTML = '';
	divQuarter.innerHTML = '';
	divOnline.innerHTML = '';
	divOnline.className = 'off';
	
	divpopup.style.display = 'none';
	divpopup.style.left = -500;
	divpopup.style.top = -500;
}

function MoveProfilePopup(event) {
	var divpopup = document.getElementById('divProfilePopup');
	//var imgInprev = document.getElementById('imgProfilePreview');
	var m_x = event.clientX+14;
	var m_y = event.clientY+14;
	
	if ( (divProfilePreviewWidth+24) > (GetPageClientWidth()-m_x) ) {
		m_x -= divProfilePreviewWidth;
		m_x -= 28;
	}
	if ( (divProfilePreviewHeight+6) > (GetPageClientHeight()-m_y) ) {
		m_y = GetPageClientHeight() - divProfilePreviewHeight - 6;
	}

	divpopup.style.left = m_x+'px';
	divpopup.style.top = m_y+GetIndexYOffset()+'px';
	
	return true;
}





var sitemainclock_colon = false;

function sitemainclock() {
	var daynames = ['Неделя','Понеделник','Вторник','Сряда','Четвъртък','Петък','Събота'];
	var monthnames = ['Януари','Февруари','Март','Април','Май','Юни','Юли','Август','Септември','Октомври','Ноември','Декември'];
	var d = new Date();
	var day = d.getDate();
	var mon = d.getMonth();
	var daynum = d.getDay();
	var h = d.getHours();
	var m = d.getMinutes();
	//var s = d.getSeconds();
	
	if (h<10) h='0'+h; else h=''+h;
	if (m<10) m='0'+m; else m=''+m;
	//if (s<10) s='0'+s; else s=''+s;
	var colon;
	
	if (sitemainclock_colon) {
		colon = '<span style="color:#A9B9A9">:</span>';
		sitemainclock_colon = false;
	} else {
		colon = ':';
		sitemainclock_colon = true;
	}
	
	var s = daynames[daynum]+' '+day+' '+monthnames[mon]+', '+h+colon+m;
	
	$jq("#divMainHeader2Left2").html(s);
}





//---------------------------------- TABS ROUTINES ------------------------------------
var current_tab = 1;   // remembers the currently selected tab so we can run the effects smoothly
var current_href = window.location.href;   // save current URL so we can # it when switching tabs
var ch_diezpos = current_href.lastIndexOf('#');
//var ch_tabpos = current_href.lastIndexOf('tab:');

function TabMenuSwitchShow() {
	if (current_tab>0) {   // if d==0 then there will be no active button
		$jq("#divTabContents_"+current_tab).fadeIn("fast");
		$jq("#TabMenuButton_"+current_tab).addClass("tabmenuact");
	}
}

function TabMenuSwitch(d) {
	var old_current_tab = current_tab;
	current_tab = d;
	if (current_tab == old_current_tab) return;
	$jq(".atabmenu").removeClass("tabmenuact");
	$jq(".atabmenu").blur();
	
	if (old_current_tab==0) {
		TabMenuSwitchShow();
	} else {
		$jq("#divTabContents_"+old_current_tab).fadeOut("fast", TabMenuSwitchShow);
	}
	
	// update URL
/*	if (ch_tabpos != -1) {   // remove tab:... section
		current_href = current_href.substr(0, ch_tabpos);
		if (current_href.substr(current_href.length-1, 1) == ',') {   // remove comma if present
			current_href = current_href.substr(0, current_href.length-1);
		}
		ch_tabpos = -1;
	} */
	if (ch_diezpos == -1) {
		window.location.href = current_href + '#' + d;
	} else {
		window.location.href = current_href.substr(0, ch_diezpos) + '#' + d;
	}
}








//---- return credits required for given days and weight
function DaysAndWeightToCredits(days, weight) {
	var perc = 5;   // discount percent from total credits if weight>1
	var daystocredits_maxdays = 30;   // maximum days the main array defines creadits for
	
	var credits = 0;
	
	var days_credits = 0;
	var i, alen;
	for (i=0,alen=radius_daystocredits.length; i<alen; ++i) {
		if (days==radius_daystocredits[i][0]) {
			days_credits = radius_daystocredits[i][1];
			break;
		}
	}
	if (days_credits == 0 && days > daystocredits_maxdays) {
		days_credits = Math.ceil(days * 1.45);
	}
	
	if (days_credits>0) {
		credits = days_credits;
		if (weight>1) {
			credits *= weight;
			if (perc>0) {
				credits -= Math.floor(credits * perc / 100);
			}
		}
	}
	
	return credits;
}








function _OK_Message_remove() {
	//var el1 = document.getElementById('divSavedSearchSaveStatusOkShadow');
	//el1.style.display = 'none';
	$jq("#divSavedSearchSaveStatusOkShadow").hide();
	$jq("#divSavedSearchSaveStatusOk").hide("explode", {}, 500);//, _savedsearchsave_OK_status_remove_end);
}

function OK_Message() {
	var el = document.getElementById('divSavedSearchSaveStatusOk');
	var el1 = document.getElementById('divSavedSearchSaveStatusOkShadow');
	el.style.left = parseInt((GetPageClientWidth()-120) / 2) + 'px';
	el.style.top = parseInt((GetPageClientHeight()-50) / 2) + GetIndexYOffset() + 'px';
	el1.style.left = parseInt((GetPageClientWidth()-120) / 2) + 5 + 'px';
	el1.style.top = parseInt((GetPageClientHeight()-50) / 2) + GetIndexYOffset() + 5 + 'px';
	el.style.display = 'block';
	el1.style.display = 'block';
	setTimeout("_OK_Message_remove()", 1000);
}








//------------------------------ SEARCH ROUTINES ------------------------------
var my_saved_searches = new Array();   // holds the details about my saved searches

function ClearSearchForm() {
	document.getElementById('s_q').value = '';
	document.getElementById('s_cat').selectedIndex = 0;
	document.getElementById('s_subcat').selectedIndex = 0;
	document.getElementById('s_region').selectedIndex = 0;
	document.getElementById('s_type').selectedIndex = 0;
	document.getElementById('s_pricefrom').value = '';
	document.getElementById('s_priceto').value = '';
	document.getElementById('hidSearchDateFrom').value = '';
	document.getElementById('hidSearchDateTo').value = '';
	document.getElementById('divSearchDatesFrontFrom').innerHTML = 'от ---';
	document.getElementById('divSearchDatesFrontTo').innerHTML = 'до ---';
	if (global_logged) document.getElementById('s_myonly').checked = false;
	document.getElementById('s_lastvisited').checked = false;
}

function OpenSearchDatesChooser() {
	var el = document.getElementById('divSearchDatesChooser');
	var el1 = document.getElementById('divSearchDatesChooserShadow');
	el.style.left = (getRealLeft('imgSearchDatesSmallDownArrow') - 52) + 'px';
	el.style.top = (getRealTop('imgSearchDatesSmallDownArrow') + 40) + 'px';
	el1.style.left = (getRealLeft('imgSearchDatesSmallDownArrow') - 47) + 'px';
	el1.style.top = (getRealTop('imgSearchDatesSmallDownArrow') + 45) + 'px';
	
	document.getElementById('txtSearchDateChooserFrom').value = document.getElementById('hidSearchDateFrom').value;
	document.getElementById('txtSearchDateChooserTo').value = document.getElementById('hidSearchDateTo').value;
	
	$jq("#divSearchDatesChooserShadow").slideDown("fast");
	$jq("#divSearchDatesChooser").slideDown("fast");
}

function CloseSearchDatesChooser() {
	$jq("#divSearchDatesChooser").slideUp("fast");
	$jq("#divSearchDatesChooserShadow").slideUp("fast");
}

function OpenCloseSearchDatesChooser() {
	var el = document.getElementById('divSearchDatesChooser');
	//var el1 = document.getElementById('divSearchDatesChooserShadow');
	if (el.style.display != 'block') {
		OpenSearchDatesChooser();
	} else {
		CloseSearchDatesChooser();
	}
}

function ClearSearchDatesChooserFields() {
	document.getElementById('txtSearchDateChooserFrom').value = '';
	document.getElementById('txtSearchDateChooserTo').value = '';
}

function SearchDatesChooserOK() {
	document.getElementById('txtSearchDateChooserFrom').value = trim(document.getElementById('txtSearchDateChooserFrom').value);
	document.getElementById('txtSearchDateChooserTo').value = trim(document.getElementById('txtSearchDateChooserTo').value);
	
	document.getElementById('hidSearchDateFrom').value = document.getElementById('txtSearchDateChooserFrom').value;
	document.getElementById('hidSearchDateTo').value = document.getElementById('txtSearchDateChooserTo').value;
	
	if (document.getElementById('txtSearchDateChooserFrom').value != '') {
		document.getElementById('divSearchDatesFrontFrom').innerHTML = 'от ' + document.getElementById('txtSearchDateChooserFrom').value;
	} else {
		document.getElementById('divSearchDatesFrontFrom').innerHTML = 'от ---';
	}
	
	if (document.getElementById('txtSearchDateChooserTo').value != '') {
		document.getElementById('divSearchDatesFrontTo').innerHTML = 'до ' + document.getElementById('txtSearchDateChooserTo').value;
	} else {
		document.getElementById('divSearchDatesFrontTo').innerHTML = 'до ---';
	}
	
	//OpenCloseSearchDatesChooser();
	$jq("#divSearchDatesChooser").hide();
	$jq("#divSearchDatesChooserShadow").hide();
}



// update the search form to reflect a saved search parameters
function SavedSearchChange() {
	var id = document.getElementById('ss_name').value;
	if (id<1) return;
	var i, sslen;
	for (i=0,sslen=my_saved_searches.length; i<sslen; i++) {
		if (my_saved_searches[i][0]==id) {
			document.getElementById('s_q').value = my_saved_searches[i][2];
			document.getElementById('hidSearchDateFrom').value = my_saved_searches[i][3];
			document.getElementById('hidSearchDateTo').value = my_saved_searches[i][4];
			document.getElementById('s_cat').value = my_saved_searches[i][5];
			document.getElementById('s_subcat').value = my_saved_searches[i][6];
			document.getElementById('s_region').value = my_saved_searches[i][7];
			document.getElementById('s_type').value = my_saved_searches[i][8];
			document.getElementById('s_pricefrom').value = my_saved_searches[i][9];
			document.getElementById('s_priceto').value = my_saved_searches[i][10];
			if (global_logged) document.getElementById('s_myonly').checked = ((my_saved_searches[i][11]=='1')?true:false);
			document.getElementById('s_lastvisited').checked = ((my_saved_searches[i][12]=='1')?true:false);
			
			if (my_saved_searches[i][3]=='') {
				document.getElementById('divSearchDatesFrontFrom').innerHTML = 'от ---';
			} else {
				document.getElementById('divSearchDatesFrontFrom').innerHTML = 'от ' + my_saved_searches[i][3];
			}
			
			if (my_saved_searches[i][4]=='') {
				document.getElementById('divSearchDatesFrontTo').innerHTML = 'до ---';
			} else {
				document.getElementById('divSearchDatesFrontTo').innerHTML = 'до ' + my_saved_searches[i][4];
			}
			
			break;
		}
	}
}


var _last_added_savedsearch_title = '';   // save the title between methods so we can add the title in the dropdown later

function _savedsearchsave_success(data, status) {
	var result = data.split(",");   // valid result is "CODE,id" where code is OK or some ERR and 'id' is 0 or the new saved search ID
	
	if (result[0]=="OK") {
		var id = result[1];
		// add it first to the current dropdown on page
		add_select_option("ss_name", _last_added_savedsearch_title, id);
		document.getElementById('ss_name').selectedIndex = document.getElementById('ss_name').options.length-1;   // select the new entry
		my_saved_searches[my_saved_searches.length] = new Array(
			''+id,
			_last_added_savedsearch_title,
			document.getElementById('s_q').value,
			trim(document.getElementById('hidSearchDateFrom').value),
			trim(document.getElementById('hidSearchDateTo').value),
			''+document.getElementById('s_cat').value,
			''+document.getElementById('s_subcat').value,
			''+document.getElementById('s_region').value,
			''+document.getElementById('s_type').value,
			document.getElementById('s_pricefrom').value,
			document.getElementById('s_priceto').value,
			((global_logged && document.getElementById('s_myonly').checked)?'1':'0'),
			((document.getElementById('s_lastvisited').checked)?'1':'0')
		);
		
		OK_Message();
	} else if (result[0]=="ERR_NAMEEXISTS") {
		alert('Заглавието, което сте въвели съществува за друго ваше запазено търсене!');
		//document.getElementById('btnSubmit').disabled = false;
	} else if (result[0]=="ERR_ISGUEST") {
		alert('Само регистрирани членове на Radius.bg могат да ползват функцията Запазени Търсения! Най-вероятно ви е изтекла сесията.');
	} else if (result[0]=="ERR_EMPTY") {
		alert('Всички параметри за търсене са празни!');
	} else {
		alert('Грешка при запазване на търсенето!');
		//document.getElementById('btnSubmit').disabled = false;
	}
	return false;
}

function _savedsearchsave_error(XMLHttpRequest, textStatus, errorThrown) {
	alert('Грешка: '+textStatus);
	//document.getElementById('btnSubmit').disabled = false;
	return false;
}

//function _savedsearchsave_OK_status_remove_end() {
//	var el = document.getElementById('divSavedSearchSaveStatusOk');
//	el.style.display = 'none';
//}

//--- save search handler
function SavedSearchSave(logged) {
	if (!logged) {
		alert('Само регистрирани членове на Radius.bg могат да ползват функцията Запазени Търсения!');
		return;
	}
	
	// now get search parameters
	var s_datefrom = document.getElementById('hidSearchDateFrom').value;
	var s_dateto = document.getElementById('hidSearchDateTo').value;
	var s_q = document.getElementById('s_q').value;
	var s_cat = document.getElementById('s_cat').value;
	var s_subcat = document.getElementById('s_subcat').value;
	var s_region = document.getElementById('s_region').value;
	var s_type = document.getElementById('s_type').value;
	var s_pricefrom = document.getElementById('s_pricefrom').value;
	var s_priceto = document.getElementById('s_priceto').value;
	var s_myonly = ((global_logged && document.getElementById('s_myonly').checked)?'1':'0');
	var s_lastvisited = ((document.getElementById('s_lastvisited').checked)?'1':'0');
	
	// check if all parameters empty
	if (s_datefrom=='' && s_dateto=='' && s_q=='' && s_cat==0 && s_subcat==0 && s_region==0 && s_type==0 && s_pricefrom=='' && s_priceto=='' && s_myonly==0 && s_lastvisited==0) {
		alert('Всички параметри за търсене са празни!');
		return;
	}
	
	var save_name = prompt('Въведете заглавие, под което да се запази търсенето', '');
	if (save_name!=null) save_name = trim(save_name);
	
	if (save_name!=null && save_name!="") {
		_last_added_savedsearch_title = save_name;   // save it globally so we can use it later when adding the entry to the dropdown
		var save_name_enc = UrlCodec.encode(save_name);
		
		s_datefrom = UrlCodec.encode(s_datefrom);
		s_dateto = UrlCodec.encode(s_dateto);
		s_q = UrlCodec.encode(s_q);
		s_pricefrom = UrlCodec.encode(s_pricefrom);
		s_priceto = UrlCodec.encode(s_priceto);
		
		var urldata = "n="+save_name_enc+"&s_datefrom="+s_datefrom+"&s_dateto="+s_dateto+"&s_q="+s_q+"&s_cat="+s_cat+"&s_subcat="+s_subcat+"&s_region="+s_region+"&s_type="+s_type+"&s_pricefrom="+s_pricefrom+"&s_priceto="+s_priceto+"&s_myonly="+s_myonly+"&s_lastvisited="+s_lastvisited;
		
		$jq.ajax({
			url: global_app_path+"ajaxhandlers/savedsearch_save.php",
			async: false,
			cache: false,
			contentType: "text/plain",
			data: urldata,
			dataType: "text",
			timeout: 6000,
			success: _savedsearchsave_success,
			error: _savedsearchsave_error
		});
		
	}
}



function _savedsearchdelete_success(data, status) {
	var result = data.split(",");   // valid result is "CODE,ID" where code is OK or some ERR and 'ID' is the deleted ID
	
	if (result[0]=="OK") {
		var id = result[1];
		// delete it from dropdown
		remove_select_option("ss_name", id);
		document.getElementById('ss_name').selectedIndex = 0;
		
		OK_Message();
	} else if (result[0]=="ERR_INVALID") {
		alert('Невалидно или несъществуващо Запазено Търсене!');
	} else if (result[0]=="ERR_ISGUEST") {
		alert('Само регистрирани членове на Radius.bg могат да ползват функцията Запазени Търсения! Най-вероятно ви е изтекла сесията.');
	} else {
		alert('Грешка при изтриването на Запазеното Търсене!');
	}
	return false;
}

function _savedsearchdelete_error(XMLHttpRequest, textStatus, errorThrown) {
	alert('Грешка: '+textStatus);
	//document.getElementById('btnSubmit').disabled = false;
	return false;
}

//--- delete saved search handler
function SavedSearchDelete(logged) {
	if (!logged) {
		alert('Само регистрирани членове на Radius.bg могат да ползват функцията Запазени Търсения!');
		return;
	}
	
	var id = document.getElementById('ss_name').value;
	
	if (id==0) return;
	
	var confirm_delete = confirm('Потвърдете изтриването на запазеното търсене');
	if (confirm_delete) {
		$jq.ajax({
			url: global_app_path+"ajaxhandlers/savedsearch_delete.php",
			async: false,
			cache: false,
			contentType: "text/plain",
			data: "id="+id,
			dataType: "text",
			timeout: 6000,
			success: _savedsearchdelete_success,
			error: _savedsearchdelete_error
		});
	}
}


// called periodically to sync the frontpage Search Date labels from the hidden fields. Needed when the user navigates within browser history.
function SearchbarSyncDateLabels() {
	var el_datefrom = 'hidSearchDateFrom';
	var el_dateto = 'hidSearchDateTo';
	var front_datefrom = 'divSearchDatesFrontFrom';
	var front_dateto = 'divSearchDatesFrontTo';
	
	if ($jq("#"+el_datefrom).val()!='' && $jq("#"+front_datefrom).text()=='от ---') {
		$jq("#"+front_datefrom).text('от '+$jq("#"+el_datefrom).val());
	}
	if ($jq("#"+el_dateto).val()!='' && $jq("#"+front_dateto).text()=='до ---') {
		$jq("#"+front_dateto).text('до '+$jq("#"+el_dateto).val());
	}
}


// categories dropdown in search form changed - populate the subcategories dropdown with its subcats
function SearchFormCatChange() {
	emptySelectOptions('s_subcat');
	add_select_option('s_subcat', '---', '0');
	document.getElementById('s_subcat').selectedIndex = 0;
	var catid = document.getElementById('s_cat').value;
	if (catid>0) {
		for (var subcatid in radius_subcategories[catid]) {
			if (
				(typeof radius_subcategories[catid][subcatid] == "string" || typeof radius_subcategories[catid][subcatid] == "number") &&
				radius_subcategories[catid][subcatid].indexOf('function')!=0
			)   // ignore prototype added methods
				add_select_option('s_subcat', radius_subcategories[catid][subcatid], subcatid);
		}
	}
}


// subcategories dropdown click handler. Checks if dropdown empty but category selected. This can occur after the user used Back/Forward in the browser.
function SearchFormSubcatClick() {
	var s_cat = document.getElementById('s_cat');
	var s_subcat = document.getElementById('s_subcat');
	if (s_cat.selectedIndex>0 && s_subcat.options.length<=1) {
		SearchFormCatChange();
	}
}


//------- main search form submit handler
function OnSearchFormSubmit() {
	if (
		document.getElementById('s_q').value == '' &&
		document.getElementById('s_cat').selectedIndex == 0 &&
		document.getElementById('s_subcat').selectedIndex == 0 &&
		document.getElementById('s_region').selectedIndex == 0 &&
		document.getElementById('s_type').selectedIndex == 0 &&
		document.getElementById('s_pricefrom').value == '' &&
		document.getElementById('s_priceto').value == '' &&
		document.getElementById('hidSearchDateFrom').value == '' &&
		document.getElementById('hidSearchDateTo').value == '' &&
		((global_logged && !document.getElementById('s_myonly').checked) || !global_logged) &&
		!document.getElementById('s_lastvisited').checked
	) {
		alert('Всички полета за търсене са празни!');
		return false;
	}
	
	return true;
}








//------------------------------- FIXED SUBCATEGORIES ---------------------------------
//var openedFixedCats = new Array();   // defined in left column

//var _rememberFixedCatsTimeout;

function RememberFixedSubcatsState() {
	var fixedsubcats = document.getElementsByClassName('divFixedSubcategories', 'div');
	var catid;
	var state = '';
	var count = fixedsubcats.length;
	var i;
	var re = /divFixedSubcats_/;
	for (i=0; i<count; i++) {
		//if (document.getElementById(fixedsubcats[i].id).style.display!='none') {
		if ($jq("#"+fixedsubcats[i].id).css("display")!='none') {
			if (state!='') state += ',';
			catid = fixedsubcats[i].id.replace(re, '');
			state += catid;
		}
	}
	
	writeCookie('cookieRadiusOpenedFixedCats', state, 30);
	openedFixedCats = state.split(",");   // remember globally, we need this for some options
}


function ShowHideFixedSubcats(catid) {
	//if (_rememberFixedCatsTimeout) clearTimeout(_rememberFixedCatsTimeout);
	if (global_menu_cats_closeothers==1 && $jq("#divFixedSubcats_"+catid).css('display')=='none') {
		$jq(".divFixedSubcategories").slideUp("fast", RememberFixedSubcatsState);
	}
	$jq("#divFixedSubcats_"+catid).slideToggle("fast", RememberFixedSubcatsState);
	//_rememberFixedCatsTimeout = setTimeout("RememberFixedSubcatsState()", 150);
}


function ExpandCategoriesTree() {
	//if (_rememberFixedCatsTimeout) clearTimeout(_rememberFixedCatsTimeout);
	$jq(".divFixedSubcategories").slideDown("fast", RememberFixedSubcatsState);
	//_rememberFixedCatsTimeout = setTimeout("RememberFixedSubcatsState()", 150);
}

function CollapseCategoriesTree() {
	//if (_rememberFixedCatsTimeout) clearTimeout(_rememberFixedCatsTimeout);
	$jq(".divFixedSubcategories").slideUp("fast", RememberFixedSubcatsState);
	//_rememberFixedCatsTimeout = setTimeout("RememberFixedSubcatsState()", 150);
}









//--------------------------------- DYNAMIC SUBCATEGORIES SUBMENUS -------------------------------
var timer_begin_subcats_show;
var timer_begin_subcats_hide;

function MenuDynamicSubcatsMouseOver() {
	if (timer_begin_subcats_hide) clearTimeout(timer_begin_subcats_hide);
}

function MenuDynamicSubcatsMouseOut() {
	StartMenuHideDynamicSubcats(0);
}


function MenuShowDynamicSubcats(catid) {
	if (timer_begin_subcats_hide) clearTimeout(timer_begin_subcats_hide);
	var divsubcat = document.getElementById('divMenuDynamicSubcats_'+catid);
	var divsubcatsshadow = document.getElementById('divMenuDynamicSubcategoriesShadow');
	
	var divh = $jq("#divMenuDynamicSubcats_"+catid).height();
	$jq("#divMenuDynamicSubcategoriesShadow").height(divh+1);
	var top = $jq("#aButtonMainCatMenu_"+catid).offset().top - 24;
	
	var yOffset = GetIndexYOffset();
	var clientHeight = GetPageClientHeight();
	if ((top+divh+6) > (yOffset+clientHeight)) {
		top = yOffset + clientHeight - divh - 6;
	}
	if (top < yOffset) {
		top = yOffset+1;
	}
	
	divsubcat.style.top = top + 'px';
	divsubcatsshadow.style.top = top + 4 + 'px';
	
	$jq("#divMenuDynamicSubcats_"+catid).show();
	$jq("#divMenuDynamicSubcategoriesShadow").show();
}


function MenuHideDynamicSubcats(catid) {   // catid actually not needed
	//$jq("#divMenuDynamicSubcats_"+catid).hide();
	MenuDynamicSubcatsHideAll();
}


function MenuDynamicSubcatsHideAll() {
	$jq(".divMenuDynamicSubcategories").hide();
	$jq("#divMenuDynamicSubcategoriesShadow").hide();
}


function StartMenuShowDynamicSubcats(catid) {
	if (global_menu_cats_showdynamicsubcats==1) return;
	if (global_menu_cats_showdynamicsubcats==2) {
		var len = openedFixedCats.length;
		for (var i=0; i<len; i++) {
			if (openedFixedCats[i]==catid) return;
		}
	}
	
	if (timer_begin_subcats_hide) {
		clearTimeout(timer_begin_subcats_hide);
		MenuDynamicSubcatsHideAll();
	}
	timer_begin_subcats_show = setTimeout('MenuShowDynamicSubcats('+catid+')', 80);
}


function StartMenuHideDynamicSubcats(catid) {   // catid actually not needed
	if (timer_begin_subcats_show) clearTimeout(timer_begin_subcats_show);
	timer_begin_subcats_hide = setTimeout('MenuHideDynamicSubcats('+catid+')', 250);
}


function SubcatMenuClick(url) {
	MenuDynamicSubcatsHideAll();
	document.location = url;
}








//--------------------------------- POPUP FULL LIST OF CATEGORIES AND SUBCATEGORIES -------------------------------
var timer_begin_fulllist_show;
var timer_begin_fulllist_hide;

function CatsFullListMouseOver() {
	if (timer_begin_fulllist_hide) clearTimeout(timer_begin_fulllist_hide);
}

function CatsFullListMouseOut() {
	StartCatsFullListHide();
}

function CatsFullListShow() {
	if (timer_begin_fulllist_hide) clearTimeout(timer_begin_fulllist_hide);
	var divlist = document.getElementById('divCatsFullPopup');
	var divlistshadow = document.getElementById('divCatsFullShadowPopup');
	
	var divh = $jq("#divCatsFullPopup").height();
	$jq("#divCatsFullShadowPopup").height(divh+1);
	var top = $jq("#imgHoverShowAllCats").offset().top - 24;
	
	var yOffset = GetIndexYOffset();
	var clientHeight = GetPageClientHeight();
	if ((top+divh+4) > (yOffset+clientHeight)) {
		top = yOffset + clientHeight - divh - 4;
	}
	if (top < yOffset) {
		top = yOffset+1;
	}
	
	//divlist.style.top = top + 'px';
	$jq("#divCatsFullPopup").css("top", top).show();
	//divsubcatsshadow.style.top = top + 4 + 'px';
	$jq("#divCatsFullShadowPopup").css("top", top+4).show();
	
	//$jq("#divMenuDynamicSubcats_"+catid).show();
	//$jq("#divMenuDynamicSubcategoriesShadow").show();
}

function CatsFullListHide() {
	$jq("#divCatsFullPopup").hide();
	$jq("#divCatsFullShadowPopup").hide();
}

function StartCatsFullListShow() {
	if (timer_begin_fulllist_hide) {
		clearTimeout(timer_begin_fulllist_hide);
		//MenuDynamicSubcatsHideAll();
	}
	timer_begin_fulllist_show = setTimeout('CatsFullListShow()', 80);
}

function StartCatsFullListHide() {
	if (timer_begin_fulllist_show) clearTimeout(timer_begin_fulllist_show);
	timer_begin_fulllist_hide = setTimeout('CatsFullListHide()', 250);
}








//--------------------------------- POPUP SORT BY IN LISTING -------------------------------
var timer_begin_listsort_show;
var timer_begin_listsort_hide;

function DialogListingSortMouseOver() {
	if (timer_begin_listsort_hide) clearTimeout(timer_begin_listsort_hide);
}

function DialogListingSortMouseOut() {
	StartDialogListingSortHide();
}

function DialogListingSortShow() {
	if (timer_begin_listsort_hide) clearTimeout(timer_begin_listsort_hide);
	var divpopup = document.getElementById('divDialogListingSort');
	//var divlistshadow = document.getElementById('divDialogListingSortShadow');
	
	var divh = $jq("#divDialogListingSort").height();
	//$jq("#divDialogListingSortShadow").height(divh+1);
	var top = $jq("#imgListingSortCurrent").offset().top + 14;
	var left = $jq("#imgListingSortCurrent").offset().left - 112;
	
	var yOffset = GetIndexYOffset();
	var clientHeight = GetPageClientHeight();
	if ((top+divh+4) > (yOffset+clientHeight)) {
		top = yOffset + clientHeight - divh - 4;
	}
	if (top < yOffset) {
		top = yOffset+1;
	}
	
	//divlist.style.top = top + 'px';
	$jq("#divDialogListingSort").css("top", top).css("left", left).show();
	//divsubcatsshadow.style.top = top + 4 + 'px';
	//$jq("#divCatsFullShadowPopup").css("top", top+4).show();
}

function DialogListingSortHide() {
	$jq("#divDialogListingSort").hide();
	//$jq("#divDialogListingSortShadow").hide();
}

function StartDialogListingSortShow() {
	if (timer_begin_listsort_hide) {
		clearTimeout(timer_begin_listsort_hide);
		//MenuDynamicSubcatsHideAll();
	}
	timer_begin_listsort_show = setTimeout('DialogListingSortShow()', 50);
}

function StartDialogListingSortHide() {
	if (timer_begin_listsort_show) clearTimeout(timer_begin_listsort_show);
	timer_begin_listsort_hide = setTimeout('DialogListingSortHide()', 250);
}








//--------------------------------- TOOLTIPS -------------------------------
var timer_begin_tooltip_BL_show;
var timer_begin_tooltip_BL_hide;

function TooltipBottomLeftShow(s, elid, yOffset) {
	if (timer_begin_tooltip_BL_hide) clearTimeout(timer_begin_tooltip_BL_hide);
	
	$jq("#divTooltipBottomLeftContent").html(s);
	var top = $jq("#"+elid).offset().top + yOffset;
	
	$jq("#divTooltipBottomLeft").css("top", top);
	$jq("#divTooltipBottomLeft").css("left", $jq("#"+elid).offset().left - $jq("#divTooltipBottomLeft").width() + 7);
	
	$jq("#divTooltipBottomLeft").show();
}

function TooltipBottomLeftHide() {
	$jq("#divTooltipBottomLeft").hide();
}

// Params: the string, the element ID the tooltip will anchor to, and Y offset ti dusokace the tooltip
function BeginShowTooltipBottomLeft(s, elid, yOffset) {
	if (timer_begin_tooltip_BL_hide) {
		clearTimeout(timer_begin_tooltip_BL_hide);
		TooltipBottomLeftHide();
	}
	timer_begin_tooltip_BL_show = setTimeout('TooltipBottomLeftShow("'+s+'", "'+elid+'", '+yOffset+')', 100);
}

function BeginHideTooltipBottomLeft() {
	if (timer_begin_tooltip_BL_show) clearTimeout(timer_begin_tooltip_BL_show);
	//timer_begin_tooltip_BL_hide = setTimeout('TooltipBottomLeftHide()', 200);
	TooltipBottomLeftHide();
}



function ShowHideRegisterWhyTooltip(a) {
	var divh = $jq("#divRegisterWhy").height()+10;   // incl. the padding and border
	var top = $jq(a).offset().top+20;
	
	// check if the tooltip will expand beyond the bottom edge of the window
	var yOffset = GetIndexYOffset();
	var clientHeight = GetPageClientHeight();
	if ((top+divh+4) > (yOffset+clientHeight)) {
		top = yOffset + clientHeight - divh - 4;
	}
	if (top < yOffset) {   // ensure the top of the tooltip is visible
		top = yOffset+1;
	}
	
	$jq("#divRegisterWhy").css("top", top);
	$jq("#divRegisterWhy").css("left", $jq(a).offset().left-4);
	$jq("#divRegisterWhy").slideToggle("fast");
}









//------------------------------------------ REGISTER PAGE
var reg_curr_imgpath = '';   // updated by template to current images path

function RegAccTypeLabelClick(t) {
	if (t=='personal') {
		SetChkOn('reg_acc_type_pers');
		$jq("#divRegFirmDetails").hide("fast");
	} else {
		SetChkOn('reg_acc_type_firm');
		$jq("#divRegFirmDetails").show("fast");
	}
	return false;
}


function RegAccTypeRadClick(e) {
	if (e.id=='reg_acc_type_pers') {
		$jq("#divRegFirmDetails").hide("fast");
	} else {
		$jq("#divRegFirmDetails").show("fast");
	}
}


function _checkusernameavailable_success(data, status) {
	var result = data.split(",");   // valid result is "CODE,id" where code is OK or some ERR and 'id' is a placeholder
	
	if (result[0]=="OK") {
		//var id = result[1];
		$jq("#divRegUsernameAvailability").html('<img src="'+reg_curr_imgpath+'icon_check.gif" alt="свободно" title="свободно" />');
		$jq("#divRegUsernameAvailability").show("medium");
	} else if (result[0]=="ERR_EXISTS") {
		$jq("#divRegUsernameAvailability").html('<img src="'+reg_curr_imgpath+'icon_nocheck.gif" alt="заето" title="заето" />');
		$jq("#divRegUsernameAvailability").show("medium");
	} else {
		$jq("#divRegUsernameAvailability").html('<img src="'+reg_curr_imgpath+'icon_nocheck.gif" alt="невалидно" title="невалидно" />');
		$jq("#divRegUsernameAvailability").show("medium");
		//alert('Грешка при проверката!');
	}
	return false;
}

function _checkusernameavailable_error(XMLHttpRequest, textStatus, errorThrown) {
	alert('Грешка: '+textStatus);
	//document.getElementById('btnSubmit').disabled = false;
	return false;
}


//------ check username availability handler
function CheckUsernameIsAvailable(imgpath) {
	reg_curr_imgpath = imgpath;   // make current img path available globally
	// now get search parameters
	var reg_username = trim(document.getElementById('reg_username').value);
	if (reg_username.length<3) {
		return;
	}
	
	$jq("#divRegUsernameAvailability").html('');
	$jq("#divRegUsernameAvailability").hide("medium");
	var reg_username_enc = UrlCodec.encode(reg_username);
	
	$jq.ajax({
		url: global_app_path+"ajaxhandlers/checkusernameavailable.php",
		async: false,
		cache: false,
		contentType: "text/plain",
		data: "u="+reg_username_enc,
		dataType: "text",
		timeout: 4000,
		success: _checkusernameavailable_success,
		error: _checkusernameavailable_error
	});
		
}



function RegGeneratePassword() {
	var pass = '';
	var i;
	var pos1 = GenerateRandomNumber(1,10);
	var pos2;
	do {
		pos2 = GenerateRandomNumber(1,10);
	} while (pos2==pos1);
	
	var char1code = GenerateRandomNumber(0,25);
	var char2code = GenerateRandomNumber(0,25);
	var char1 = String.fromCharCode("a".charCodeAt(0) + char1code);
	var char2 = String.fromCharCode("A".charCodeAt(0) + char2code);
	
	if (pos2<pos1) {
		var tmp = pos1;
		pos1 = pos2;
		pos2 = tmp;
	}
	
	if (pos1>1) {
		pass += GenerateRandomNumber(10*(pos1-2), Math.pow(10, pos1-1)-1);
	}
	pass += char1;
	if (pos2>(pos1+1)) {
		pass += GenerateRandomNumber(10*(pos2-pos1-2), Math.pow(10, pos2-pos1-1)-1);
	}
	pass += char2;
	if (pos2<10) {
		pass += GenerateRandomNumber(10*(10-pos2-1), Math.pow(10, 10-pos2)-1);
	}
	
	//pass = GenerateRandomNumber(10000000,99999999);
	
	document.getElementById('reg_password1').value = pass;
	document.getElementById('reg_password2').value = pass;
	alert('Генерирана парола (моля запомнете я): '+pass+'\r\nТя ще ви бъде изпратена и на Email-a.');
}


function RegisterFormSubmit() {
	document.getElementById('reg_username').value = trim(document.getElementById('reg_username').value);
	document.getElementById('reg_email').value = trim(document.getElementById('reg_email').value);
	document.getElementById('reg_password1').value = trim(document.getElementById('reg_password1').value);
	document.getElementById('reg_password2').value = trim(document.getElementById('reg_password2').value);
	document.getElementById('reg_company_name').value = trim(document.getElementById('reg_company_name').value);
	document.getElementById('reg_captcha').value = trim(document.getElementById('reg_captcha').value);
	
	if (
		document.getElementById('reg_username').value.length < 3 ||
		document.getElementById('reg_email').value.length < 6 ||
		document.getElementById('reg_password1').value.length < 6 ||
		(document.getElementById('reg_acc_type_firm').checked && document.getElementById('reg_company_name').value.length < 2) ||
		document.getElementById('reg_captcha').value.length < 6
	) {
		alert('Непопълнени задължителни полета!');
		return false;
	}
	
	if (document.getElementById('reg_password1').value != document.getElementById('reg_password2').value) {
		alert('Паролите от двете полета не съвпадат!');
		return false;
	}
	
	return true;
}








//------------------------------ functions for add/remove files to upload

var fileinputs_sets_count = 0;   // incremented by 1 with each new set detected. Keeps track the count of the next array.
var fileinputs_indextoname = new Array();   // each element is array(ID, typeIdentName). ID is incremented by 1 for each new set of inputs
var fileinputs_count = new Array();
var fileinputs_last = new Array();   // hold the last ever ID used for input fields names. Necessary for unique tag names.

function TableAddRow(tableID) { 
	// pass every cell content as a further arg
	var table = document.getElementById(tableID);
	
	if (arguments.length > 1) {
		var row = table.insertRow(table.rows.length);
		if (document.getElementById) {
			for (var i = 1; i < arguments.length; i++) {
				var cell = row.insertCell(i - 1);
				//if (i == 1) cell.style.textAlign = 'right';
				cell.innerHTML = arguments[i];
			}
		}
	}
}

// removes a zero-based row number from a table with id
function TableRemoveRow(tableID, rowNum) {
	var tbl = document.getElementById(tableID);
	tbl.deleteRow(rowNum);   // zero based
}

function AddFiles_renumber(t) {   // renumber (compact) the numbering label for file fields after add or remove field
	var class_span_numbering = 'span_num_f_add_' + t;
	var i;
	var indexof_instance = -1;   // get here the index in the count and lastID arrays for our "t" set of files
	
	for (i=0; i<fileinputs_indextoname.length; i++) {
		if (fileinputs_indextoname[i][1]==t) {
			indexof_instance = fileinputs_indextoname[i][0];
			break;
		}
	}
	
	if (indexof_instance!=-1) {
		var labels = document.getElementsByClassName(class_span_numbering, 'span');
		for (i=0; i<labels.length; i++) {
			labels[i].innerHTML = (i+1);
		}
	}
}


// t identifies which set of fields to control, if there is more than one set of files to upload on page
// num is the total allowed number of files
// if a third argument is given it is the rel attribute of already displayed items (files) that subtract from the total allowed files to upload
function AddFiles_add(t,num) {
	var tableID = 'tableAddfiles_'+t;
	var class_span_numbering = 'span_num_f_add_' + t;
	var input_name_prefix = 'f_add_' + t + '_';
	var i;
	var indexof_instance = -1;   // get here the index in the count and lastID arrays for our "t" set of files
	var existing_items = 0;   // already existing (uploaded) files. This will subtract from total allowed number
	
	for (i=0; i<fileinputs_indextoname.length; i++) {
		if (fileinputs_indextoname[i][1]==t) {
			indexof_instance = fileinputs_indextoname[i][0];
			break;
		}
	}
	if (indexof_instance==-1) {
		fileinputs_indextoname[fileinputs_sets_count] = new Array(fileinputs_sets_count, t);
		fileinputs_count[fileinputs_sets_count] = 0;   // start with 0 fields. Gets decremented when removing rows from table.
		fileinputs_last[fileinputs_sets_count] = 0;   // this doesn't get decremented when removing rows from table
		
		indexof_instance = fileinputs_sets_count;
		fileinputs_sets_count++;
	}
	// now we have the index in count and lastID arrays of this inputs set, in indexof_instance
	
	
	if (!global_logged && fileinputs_count[indexof_instance]>=1) {
		alert('Като нерегистриран потребител (гост) можете да качите само 1 снимка!\r\nРегистрираните потребители могат да качват до 10 снимки към обява.');
		return;
	}
	
	// check for third argument (the rel marked tags that subtract from total allowed number of files to upload)
	if (arguments.length>2) {
		existing_items = $jq("*[rel='"+arguments[2]+"']").length;
	}
	
	if (fileinputs_count[indexof_instance] >= (num-existing_items)) {
		alert('Можете да качите максимум '+num+' снимки!');
		return;
	}
	
	fileinputs_count[indexof_instance]++;
	fileinputs_last[indexof_instance]++;
	var cell1 = '<span class="'+class_span_numbering+'">'+fileinputs_count[indexof_instance]+'</span>. <input type="file" name="'+input_name_prefix+fileinputs_last[indexof_instance]+'" id="'+input_name_prefix+fileinputs_last[indexof_instance]+'" /> <img src="'+global_img_path+'icon_delete.gif" alt="премахни" title="премахни" class="imgAddFilesRemovable_'+t+'" id="imgAddFilesRemovable_'+t+'_'+fileinputs_last[indexof_instance]+'" style="cursor:pointer" onclick="AddFiles_remove(\''+t+'\', '+fileinputs_last[indexof_instance]+');" />';
	
	TableAddRow(tableID, cell1);
	//AddFiles_renumber(t);
}


function AddFiles_remove(t, row) {   // "t" (look above), row - the table row identifier to match as the row to remove.
	var tableID = 'tableAddfiles_'+t;
	
	var i;  var j;
	var indexof_instance = -1;   // get here the index in the count and lastID arrays for our "t" set of files
	
	// check if the first invocation
	for (i=0; i<fileinputs_indextoname.length; i++) {
		if (fileinputs_indextoname[i][1]==t) {
			indexof_instance = fileinputs_indextoname[i][0];
			break;
		}
	}
	
	if (indexof_instance!=-1) {
		fileinputs_count[indexof_instance]--;   // start with 0 fields. Gets decremented when removing rows from table.
		//fileinputs_last[fileinputs_sets_count]
		
		var classRowToCycle = 'imgAddFilesRemovable_'+t;
		i = 0;
		imgs = document.getElementsByClassName(classRowToCycle, 'img');
		var rowID = -1;
		for (j=0; j<imgs.length; j++) {
			if (imgs[j].id == 'imgAddFilesRemovable_'+t+'_'+row) {   // search for this img ID and we will have the row number in i.
				rowID = i;
				break;
			}
			i++;
		}
		
		if (rowID!=-1) {
			TableRemoveRow(tableID, rowID);
			AddFiles_renumber(t);
		}
	}
}








//----------------------------------------- NEW ANNOUNCEMENT

// categories dropdown in search form changed - populate the subcategories dropdown with its subcats
function NewObiavaCatChange(ind) {
	emptySelectOptions('new_subcategory'+ind);
	var catid = document.getElementById('new_category'+ind).value;
	var subcatzerostr = '---';
	if (catid>0) {
		if (ind>1)
			subcatzerostr = '--- избери подкатегория '+ind+' ---';
		else
			subcatzerostr = '--- избери подкатегория ---';
	}
	add_select_option('new_subcategory'+ind, subcatzerostr, '0');
	document.getElementById('new_subcategory'+ind).selectedIndex = 0;
	
	//var subcat_test;
	if (catid>0) {
		for (var subcatid in radius_subcategories[catid]) {
			//subcattest = parseInt(subcatid);
			//if (!isNaN(subcattest) && subcatid>0)
			if (
				(typeof radius_subcategories[catid][subcatid] == "string" || typeof radius_subcategories[catid][subcatid] == "number") &&
				radius_subcategories[catid][subcatid].indexOf('function')!=0
			)   // ignore prototype added methods
				add_select_option('new_subcategory'+ind, radius_subcategories[catid][subcatid], subcatid);
		}
	}
}

// onchange event handler for days dropdown in new announcement page. Updates the Weight dropdown accordingly
function NewObiavaVIPDaysChange() {
	emptySelectOptions('new_vip_weight');
	var days = document.getElementById('new_vip_days').value;
	//add_select_option('new_vip_weight', '1', '1');
	//document.getElementById('new_vip_weight').selectedIndex = 0;
	
	if (days>0) {
		var weight = 1;
		while (DaysAndWeightToCredits(days, weight) <= global_acc_points) {
			add_select_option('new_vip_weight', weight, weight);
			weight++;
		}
		document.getElementById('new_vip_weight').selectedIndex = 0;
	}
	
	NewObiavaVIPWeightChange();
	
	if (days>0) {
		$jq("#divNEWOReqCredits").slideDown("medium");
	} else {
		$jq("#divNEWOReqCredits").slideUp("medium");
	}
}

// onchange event handler for weight dropdown in new announcement. Updates the required credits label.
function NewObiavaVIPWeightChange() {
	var required_credits = 0;
	var days = document.getElementById('new_vip_days').value;
	var weight = document.getElementById('new_vip_weight').value;
	
	if (days>0) required_credits = DaysAndWeightToCredits(days, weight);
	
	$jq("#spanNEWOReqCredits").text(required_credits);
}


function OpenHelpNewVIP() {
	alert('За да направите обявата VIP или да добавите VIP статус, изберете брой дни, през които ще е VIP.\r\nМожете да укажете и тежест на обявата за този период.\r\nОбявите с по-голяма тежест излизат по-напред в списъците, а най-тежките се виждат на най-видно място в сайта.\r\nИ за двете функции трябва да имате съответен брой кредити във вашия акаунт (минимум 60).');
	return false;
}

function OpenHelpNewCaptcha() {
	alert('Антибот защита.\r\nРегистрираните потребители не въвеждат такъв код.');
	return false;
}


function OpenCloseNewAdditionalCats() {
	if (!global_logged) {
		alert('Като нерегистриран потребител (гост) можете да укажете само една категория!');
		return false;
	}
	
	$jq("#divNewObiavaAdditionalCats").slideToggle("fast");
	return false;
}




function _getnewtextpreview_success(data, status) {
	//var result = data.split(",", 2);   // valid result is "CODE,text" where code is OK or some ERR and 'text' is the response html text
	var commapos = data.indexOf(',');
	var result = data.substr(0, commapos);
	var response = data.substr(commapos+1);
	
	if (result=="OK") {
		//var response = result[1];
		ShowCoverDiv();
		$jq("#divDialogObiavaPreviewText").html(response);
		var left = (GetPageClientWidth()/2 - 200);
		var top = (GetIndexYOffset() + GetPageClientHeight()/2 - 300);
		// check top
		if (top < GetIndexYOffset()) top = 10;
		if ((top+$jq("#divDialogObiavaPreview").height()) > (GetIndexYOffset()+GetPageClientHeight()))
			top = 10;
		
		$jq("#divDialogObiavaPreview").css({'left':left,'top':top}).fadeIn("medium");
	} else {
		alert('Грешка при превюто!');
	}
	
	return false;
}

function _getnewtextpreview_error(XMLHttpRequest, textStatus, errorThrown) {
	alert('Грешка: '+textStatus);
	return false;
}

//------------------------ gets a preview of the bbcoded text when composing a new announcement
function NewObiavaPreviewText() {
	var text = trim(document.getElementById('new_content').value);
	if (text.length<3) {
		return false;
	}
	//var text_enc = UrlCodec.encode(text);
	
	$jq.ajax({
		type: "POST",
		url: global_app_path+"ajaxhandlers/getnewtextpreview.php",
		async: false,
		cache: false,
		/* contentType: "text/plain", */
		data: "t="+text,
		dataType: "text",
		timeout: 4000,
		success: _getnewtextpreview_success,
		error: _getnewtextpreview_error
	});
	
	return false;
}

function CloseDialogObiavaPreview() {
	//var el = document.getElementById('divDialogBox');
	//el.style.left = -800+'px';
	//el.style.display = 'none';
	$jq("#divDialogObiavaPreview").hide();
	HideCoverDiv();
}











//----------------------------------------- HELP PAGE
function HelpQClick(n) {
	//$jq("#divHelpAnswer_"+n).slideToggle("fast", function() {$jq(".divHelpAnswer:not(#divHelpAnswer_"+n+")").slideUp("fast")});
	$jq(".divHelpAnswer:not(#divHelpAnswer_"+n+")").slideUp("fast");
	//$jq(".divHelpAnswer").slideUp("fast");
	$jq("#divHelpAnswer_"+n).slideToggle("fast");
}









function ToggleListByRegions() {
	var byregions_visible = $jq("#divMainListingByRegions").css("display") == "none";   // actually we are interested in the final property
	if (byregions_visible) byregions_visible = '1'; else byregions_visible = '0';
	$jq("#divMainListingByRegions").toggle();
	writeCookie('cookie_radius_byregions_visible', byregions_visible, 365, global_app_path);
}










