function $(element_id) {
  	element = document.getElementById(element_id);
  	return element;
}

function Pop (a, elID)
{
	var outcome = document.getElementById(elID).style.display =
	document.getElementById(elID).style.display == "none"
	|| document.getElementById(elID).style.display == ""
	? "block" : "none";

	return false;
}

function popitup(url)
{
	var w = 530;
	var h = 400;
	var topPos = 50;
	var leftPos = (screen.width - w) / 2;

	newwindow=window.open(url,'name','left=' + leftPos + ',top=' + topPos + ',height=' + h + ',width=' + w + ',scrollbars=yes');
	if (window.focus) {newwindow.focus()}
	return false;
}

function syncHeights ()
{
	var mxHeight = 0;
	for (var i = 0; i < arguments.length; i ++)
	{
		mxHeight = Math.max(mxHeight, arguments[i].offsetHeight);
	}

	for (var i = 0; i < arguments.length; i ++)
	{
		setHeight(arguments[i], mxHeight);
	}
}

function setHeight(element, height)
{
	document.all
	?	element.style.height = height + "px"
	:	element.style.minHeight = height + "px";
}

function Collection(div_id, images)
{
    this.block_id        = div_id.split('-')[0];
    this.block_div_id    = div_id;
    this.el_image        = document.getElementById('image-collection-' + this.block_div_id);
    this.el_description  = document.getElementById('description-' + this.block_div_id);
    this.el_counter      = document.getElementById('collection-counter-' + this.block_div_id);
    this.images          = images;
    this.current_index   =  0;

    this.getNextImage = function()
    {
        var temp = new Image();
        var img = new Image();

        if(arguments.length)
        {
            switch (arguments[0])
            {
                case 'forward':
                    temp = this.images[this.current_index + 1] || this.images[0];
                    break;

                case 'back':
                    temp = this.images[this.current_index - 1] || this.images[this.images.length - 1];
                    break;
            }
        }
        else
        {
            temp = this.images[current_index + 1] || this.images[current_index];
        }

        img.src = temp.src;
        img.width = temp.width;
        img.height = temp.height;
        img.description = temp.description;
        img.key_index = temp.key_index;

        return img;
    };

    this.next_image      = this.getNextImage('forward');
    this.previous_image  = this.getNextImage('back');

    this.show = function(direction)
    {
        switch(direction)
        {
            case 'next':
                this.el_image.src             = this.next_image.src;
                this.el_image.width           = this.next_image.width;
                this.el_image.height          = this.next_image.height;
                this.current_index            = this.next_image.key_index;
                this.el_description.innerHTML = this.next_image.description;
                this.el_counter.innerHTML = this.current_index + 1 + '/' + this.images.length;
                break;

            case 'previous':
                this.el_image.src             = this.previous_image.src;
                this.el_image.width           = this.previous_image.width;
                this.el_image.height          = this.previous_image.height;
                this.current_index            = this.previous_image.key_index;
                this.el_description.innerHTML = this.previous_image.description;
                this.el_counter.innerHTML = this.current_index + 1 + '/' + this.images.length;
                break;
        }

        this.next_image     = this.getNextImage('forward');
        this.previous_image = this.getNextImage('back');

        return false;
    };

    this.onclick = function()
    {
		var w = 500;
		var h = 500;
		var topPos = (screen.height - h) / 2;
		var leftPos = (screen.width - w) / 2;

		newwindow=window.open(this.images[this.current_index].href,'name','left=' + leftPos + ',top=' + topPos + ',height=' + h + ',width=' + w + ',scrollbars=yes,resizable=yes');
		if (window.focus) {newwindow.focus()}
    	return false;
    }

}

function callme() {
	document.getElementById("ZG1").style.display="none";
	document.getElementById("ZG2").style.visibility="visible";
}


var panes = new Array();

function setupPanes(containerId, defaultTabId) {

  panes[containerId] = new Array();
  var maxHeight = 0; var maxWidth = 0;
  var container = document.getElementById(containerId);
  var paneContainer = container.getElementsByTagName("div")[0];
  var paneList = paneContainer.childNodes;
  for (var i=0; i < paneList.length; i++ ) {
    var pane = paneList[i];
    if (pane.nodeType != 1) continue;
    if (pane.offsetHeight > maxHeight) maxHeight = pane.offsetHeight;
    if (pane.offsetWidth  > maxWidth ) maxWidth  = pane.offsetWidth;
    panes[containerId][pane.id] = pane;
    pane.style.display = "none";
  }
    paneContainer.style.height = maxHeight + "px";
    paneContainer.style.width  = maxWidth + "px";
    document.getElementById(defaultTabId).onclick();
}

function showPane(paneId, activeTab) {
  
    for (var con in panes) {
    activeTab.blur();
    activeTab.className = "tab-active";
    if (panes[con][paneId] != null) { // tab and pane are members of this container
      var pane = document.getElementById(paneId);
      pane.style.display = "block";
      var container = document.getElementById(con);
      var tabs = container.getElementsByTagName("ul")[0];
      var tabList = tabs.getElementsByTagName("a")
      for (var i=0; i<tabList.length; i++ ) {
        var tab = tabList[i];
        if (tab != activeTab) tab.className = "tab-disabled";
      }
      for (var i in panes[con]) {
        var pane = panes[con][i];
        if (pane == undefined) continue;
        if (pane.id == paneId) continue;
        pane.style.display = "none"
      }
    }
  }
  return false;    
}


function toggle_region_selector(div_id)
{
	var div = document.getElementById(div_id);
	if (div.style.display == 'none') display = 'block';
	else display='none';
	div.style.display=display;
}

function Ajax(method,onComplete)
{
	this.requestobj = null;
	this.queryStringSeparator = "?";
	this.argumentSeparator = "&";
	this.method = method;
	this.URLString = '';
	this.failed = false;
	
	if (window.XMLHttpRequest)
	{
          // If IE7, Mozilla, Safari, etc: Use native object
          this.requestobj = new XMLHttpRequest()
	}
	else
	{
		if (window.ActiveXObject)
		{
          // ...otherwise, use the ActiveX control for IE5.x and IE6
          this.requestobj = new ActiveXObject("Microsoft.XMLHTTP");
        }
        else
        {
        	this.failed = true;
        }
	
	}
	
	
	if (this.failed)
	{
		alert('Failed to create AJAX object');
	}
	
	this.request = function(url,params)
	{
		
		this.urlString= url + this.queryStringSeparator + params;
		if (this.method == "GET") {
			totalurlstring = url + this.queryStringSeparator + params;
			this.requestobj.open(this.method, totalurlstring, true);
			
		} else {
			this.requestobj.open(this.method, url, true);
			try {
				this.requestobj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
			} catch (e) { }
			this.URLString=params;
		}
		this.requestobj.onreadystatechange = onComplete;
		
		this.requestobj.send(this.URLString);
	}
	
	
}

function add2notepad(ad_id)
{
	if ($('notepad_'+ad_id))
	{
		$('notepad_'+ad_id).src='/img/loading.gif';
	}
	ajax = new Ajax('GET', onComplete = function()
	{
		switch(ajax.requestobj.readyState)
		{
			case 4:
				if ($('notepad_'+ad_id))
				{
					$('notepad_'+ad_id).src='/img/i-notepad_red.gif';
				}
			break;
		}
	}
	);
	ajax.request('/post.php','action=add2notepad&ad_id='+ad_id);
}

function remove_from_notepad(ad_id)
{
	if (confirm('Сигурни ли сте ?')){
	ajax = new Ajax('GET', onComplete = function()
	{
		switch(ajax.requestobj.readyState)
		{
			case 4:
				var row = document.getElementById('row_'+ad_id);
				if (row)
				{
					row.style.display='none';
				}
			break;
		}
	}
	);
	ajax.request('/post.php','action=del_from_notepad&ad_id='+ad_id);
	}
}

function change_ad_status(ad_id)
{
	var row = document.getElementById('status_'+ad_id);
	var status;
	if (row.className == 'read'){
		status = 0;
	}
	else{
		status = 1;
	}
	
	ajax = new Ajax('GET', onComplete = function()
	{
		switch(ajax.requestobj.readyState)
		{
			case 4:
				var row = document.getElementById('status_'+ad_id);
				if (row)
				{
					if (row.className == 'read'){
						txt='Не';
						row.className='';
					}
					else{
						txt='Да';
						row.className='read';
					}
					row.innerHTML=txt;
				}
			break;
		}
	}
	);
	
	ajax.request('/post.php','action=mark_as_read&ad_id='+ad_id+'&status='+status);
}


function save_search_filter(name,filter_data,notify)
{
	var filter_name = encodeURIComponent(document.getElementById(name).value);
	var filter_data = encodeURIComponent(filter_data);
	
	if (!filter_name) return false;
	
	ajax = new Ajax('POST', onComplete = function()
	{
		switch(ajax.requestobj.readyState)
		{
			case 4:
				document.getElementById('save_filter_p').style.display='none';
				document.getElementById('ErrorContainer').innerHTML='<b>Филтъра е запазен</b>';
				
			break;
		}
	}
	);
	var n = notify.checked?1:0;
	ajax.request('/post.php','action=save_search_filter&name='+filter_name+'&filter_data='+filter_data+'&notify='+n);
}

function del_filter(id)
{
	if (confirm('Сигурни ли сте ?')){
	ajax = new Ajax('GET', onComplete = function()
	{
		switch(ajax.requestobj.readyState)
		{
			case 4:
				//alert('OK')
				document.getElementById(id).style.display='none';
			break;
		}
	}
	);
	ajax.request('/post.php','action=del_filter&id='+id);
	}
}


function del_ad(id)
{
	if (confirm('Сигурни ли сте ?')){
	ajax = new Ajax('GET', onComplete = function()
	{
		switch(ajax.requestobj.readyState)
		{
			case 4:
				//alert('OK')
				document.getElementById('row_'+id).style.display='none';
			break;
		}
	}
	);
	ajax.request('/post.php','action=del_ad&ad_id='+id);
	}
}

function load_pic_preview(pic_id,ext,w,h)
{
	
	var img = document.getElementById('pic_preview');
	if (img)
	{
		img.src=pic_id+'_med.'+ext;
		pic_preview_file=pic_id+'_big.'+ext;
	}
	pic_width = w;
	pic_height = h;
}


function get_direct_children(section_id,lvl)
{
		
		loading = document.createElement('span');
		loading.setAttribute('id','loading_msg');
		loading.innerHTML='<img src="/img/loading.gif">Моля изчкайте...';
		$('subsections').appendChild(loading);
		
		var ajax = new Ajax('GET',onComplete=function()
			{
				switch (ajax.requestobj.readyState) {
						case 4:
							
							xml = ajax.requestobj.responseXML;
							xmlroot = ajax.requestobj.responseXML.documentElement;
							++lvl;
							
							
							document.getElementById('subsections').removeChild($('loading_msg'));
							for (i=lvl;i<maxlevel;i++)
							{
								var sec_id='section_'+i;
								document.getElementById('subsections').removeChild(document.getElementById(sec_id));
							}
							
							maxlevel=lvl+1;
							var option_count = xmlroot.getElementsByTagName('option').length-1;
							if (!option_count || option_count<0)
							{
								maxlevel--;
								return;
							}
							var select = document.createElement('select');
							var sec_id='section_'+lvl;
							select.setAttribute('id',sec_id);
							
							//select.setAttribute('onchange','get_direct_children(this.value,'+(lvl)+')');
							select.onchange = function(){
								get_direct_children(this.value,lvl)
							}
							
							select.setAttribute('name','section_id['+lvl+']');
							
							var op = document.createElement('option');
							op.setAttribute('value','');
							var txt = document.createTextNode('Изберете');
							op.appendChild(txt);
							select.appendChild(op);
							
							for (i=1;i<=option_count;i++)
							{
								var op_txt = xmlroot.getElementsByTagName('option')[i].firstChild.data;
								var op_val = xmlroot.getElementsByTagName('option')[i].getAttribute('value');
								var op = document.createElement('option');
								op.setAttribute('value',op_val);
								var txt = document.createTextNode(op_txt);
								op.appendChild(txt);
								select.appendChild(op);
							}
							
							if (document.getElementById(sec_id))
							{
								document.getElementById('subsections').replaceChild(select,document.getElementById(sec_id))
								
							}
							else
							{
								document.getElementById('subsections').appendChild(select);
							}
							
							break;
					}
			}
		);
		
		ajax.request('post.php','action=get_direct_children&section_id='+section_id);
}

function getsubregions(region_id,subregion_id)
{
	
	if (region_id != '' ){
		
		loading = document.createElement('span');
		loading.setAttribute('id','loading_msg1');
		loading.innerHTML='<img src="/img/loading.gif">Моля изчкайте...';
		$('subregion_div').appendChild(loading);
		var ajax = new Ajax('GET',onComplete=function()
		{
			switch (ajax.requestobj.readyState) {
				case 4:
					$('subregion_div').removeChild($('loading_msg1'));
					$('subregion_div').innerHTML=ajax.requestobj.responseText;
					break;
			}
		}
		);
		ajax.request('post.php','action=getsubregions&region_id='+region_id+"&subregion_id="+subregion_id);
	}
}

function del_pic(pic_id)
{
	document.getElementById('msgBox').innerHTML='';
	var ajax = new Ajax('GET',onComplete=function()
		{
			switch(ajax.requestobj.readyState)
			{
				case 4:
					//alert(ajax.requestobj.responseText);
					document.getElementById('pic_'+pic_id).style.display='none';
					//max_photos+=1;
					document.getElementById('msgBox').innerHTML='Снимката е изтрита';
					document.getElementById('photo_fields').style.display='block';
				break;
			}
		}
	);
	ajax.request('/del_picture.php','pic_id='+pic_id);
}

function toggle_filter_notify(id,notify)
{
	var element = $('filter_notify_'+id);
	
	loading = document.createElement('span');
	loading.setAttribute('id','loading_msg');
	loading.innerHTML='<img src="/img/loading.gif">';
	
	element.appendChild(loading);
	switch(notify)
	{
		case true:
			html='Да'
		break;
		case false:
			html='Не'
		break;
	}
	ajax = new Ajax('GET', onComplete = function()
	{
		switch(ajax.requestobj.readyState)
		{
			case 4:
				element.removeChild($('loading_msg'));
				element.onclick =  function()
				{
					toggle_filter_notify(id,!notify);
				}
				element.innerHTML=html;
			break;
		}
	}
	);
	ajax.request('/post.php','action=toggle_filter_notify&id='+id+'&notify='+(notify?1:0));
}


function pop_pic(url)
{
	//var w = 530;
	//var h = 400;
	var h =pic_height+20;
	var w =pic_width+20;
	if (h > 600) h = 600;
	if (w > 900) w = 900;
	var topPos = 50;
	var leftPos = (screen.width - w) / 2;

	newwindow=window.open('/show_pic.php?pic='+escape(url),'name','left=' + leftPos + ',top=' + topPos + ',height=' + h + ',width=' + w + ',scrollbars=yes,resizable=yes');
	if (window.focus) {newwindow.focus()}
	return false;
}


function get_districts(city_id,district,selectID,lang)
{
	//document.getElementById('msgBox').innerHTML='';
	var ajax = new Ajax('GET',onComplete=function()
		{
			switch(ajax.requestobj.readyState)
			{
				case 4:
					xml = ajax.requestobj.responseXML;
					xmlroot = ajax.requestobj.responseXML.documentElement;
					var district_count = xmlroot.getElementsByTagName('district').length-1;
					var select = document.getElementById(selectID);
					select.options.length=0;
					
					var op = document.createElement('option');
					/*op.setAttribute('value',9999);
					var txt = document.createTextNode('Всички');
					op.appendChild(txt);
					select.appendChild(op);*/
						
					for (i=0;i<=district_count;i++)
					{
						var op_txt = xmlroot.getElementsByTagName('district')[i].firstChild.data;
						var op_val = xmlroot.getElementsByTagName('district')[i].getAttribute('value');
						var op = document.createElement('option');
						if (district == op_val)
						{
							op.setAttribute('selected',true);
						}
						//console.log(op_val+':'+xmlroot.getElementsByTagName('district')[i].firstChild.data);
						op.setAttribute('value',op_val);
						var txt = document.createTextNode(op_txt);
						op.appendChild(txt);
						select.appendChild(op);
						select.disabled=false;
					}
				break;
			}
		}
	);
	ajax.request('/ajax_server.php','action=get_districts&city_id='+city_id+'&district='+district+'&lang='+lang);
}

function hideNotStandardBanner(divHide, divShow)
{
  document.getElementById(divHide).style.display="none";
  document.getElementById(divShow).style.display="block";
}

function Set_Cookie( name, value, expires, path, domain, secure )
{
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime( today.getTime() );
	
	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if ( expires )
	{
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	
	document.cookie = name + "=" +escape( value ) +
	( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
	( ( path ) ? ";path=" + path : "" ) +
	( ( domain ) ? ";domain=" + domain : "" ) +
	( ( secure ) ? ";secure" : "" );
}