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,w,h)
{
 if ( w === undefined ) {
      w = 530;
   }
 if ( h === undefined ) {
      h = 400;
   }
//	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 + ', status=no,resizable=no, alwaysRaised=yes,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";
}


//Tabs
var panes = new Array();

function setupPanes(containerId, defaultTabId) {
  // go through the DOM, find each tab-container
  // set up the panes array with named panes
  // find the max height, set tab-panes to that height
  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) {
  // make tab active class
  // hide other panes (siblings)
  // make pane visible
  
    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;    
}

//End tabs

function change_stat_pic(basename,pair,period,div_id)
{
	var name = basename+pair+'-'+period+'.png';
	var p = document.getElementById('stat_graphic-'+div_id);
	//alert(name)
	p.src=name;
}

function change_stat_tab(old,n)
{
	var old = document.getElementById(old);
	old.className='';
	n.className='active';
}

function update_element_content(element,content)
{
	
	$(element).innerHTML=content;
}




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 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" : "" );
}


  function SimpleTabs(options)
{
	this.tabs = options.tabs;
	this.tabNav = options.tabNav
	this.activeTab = 0;
	
	this.init = function()
	{
		//this.tabs[0];
	}
	
	this.toggle = function(index)
	{
		$(this.tabNav[this.activeTab]).className = '';
		$(this.tabNav[index]).className = 'active';
		
		$(this.tabs[this.activeTab]).style.display = 'none';
		$(this.tabs[index]).style.display = 'block';
		this.activeTab = index;
	}
}

function switchC(element,param, r, c) 
{


	
	if ( r === undefined ) {
alert("!!!");
   }

  var oTable = 	$(element);
  var rowItems = oTable.getElementsByTagName("tr");
  // alert (element + '   ' + rowItems.length  + ' *****' );
  var cellItems = rowItems[r].getElementsByTagName("td");

  var oCell = cellItems[c];

  var clr;
  if (param == 0) { clr = '#F0F0F0'; }
  if (param == 1) { clr = '#FFFFFF'; }

  oCell.bgColor = clr;
}


function cellFlash(e,r, c) 
{

  var tickInterval = 250;
  for (i = 0; i < 6; i+=2) {
    setTimeout('parent.switchC("' + e + '",0, ' + r + ', ' + c + ')', i*tickInterval);
    setTimeout('parent.switchC("' + e + '",1, ' + r + ', ' + c + ')', i*tickInterval + tickInterval);

  }
}


function httpGet(theUrl) { var xmlHttp = null;

    xmlHttp = new XMLHttpRequest(); 
    xmlHttp.open( "GET", theUrl, false ); 
    xmlHttp.send( null ); 
    return xmlHttp.responseText; 
}

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)

		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) 
		{

			//throw SyntaxError("invalid date");
}
		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
/*dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};
*/

dateFormat.i18n = {
	dayNames: [
		"Нед", "Пон", "Вто", "Сря", "Чет", "Пет", "Съб",
		"Неделя","Понеделник", "Вторник", "Сряда", "Четвъртък", "Петък", "Събота"
	],
	monthNames: [
		"Ян", "Фев", "Мар", "Апр", "Май", "Юни", "Юли", "Авг", "Сеп", "Окт", "Ное", "Дек",
				"Януари", "Февруари", "Март", "Април", "Май", "Юни", "Юли", "Август", "Септември", "Октомври", "Ноември", "Декември"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};
