/*
** Eurotravels CSS.
** All rights reserved.
**
** Created by Bil Software, www.bilsoftware.com, 2009
*/

function $(i){return document.getElementById(i);}

var IE = document.all ? true : false;
var IE6 = parseInt(navigator.appVersion.split('MSIE')[1]) == 6;
var IE67 = parseInt(navigator.appVersion.split('MSIE')[1]) <= 7;
var Opera = window.opera ? true : false;
var Chrome = navigator.userAgent.indexOf('Chrome') != -1;
var rating = 0;
var old_rating = 0;

function change(enable){
	for (var i = 1; i < arguments.length; ++i) {
		$(arguments[i]).disabled = !enable;
		if(IE){
			if(!enable) $(arguments[i]).className += ' disabled';
			else $(arguments[i]).className = $(arguments[i]).className.replace(' disabled', '');
		}
	}
}

function getMouseXY(e) {
	if(IE) {
		tempX = event.clientX + document.body.scrollLeft;
		tempY = event.clientY + document.body.scrollTop;
	} else {
		tempX = e.pageX;
		tempY = e.pageY;
	}
	return [Math.max(0, tempX), Math.max(0, tempY)];
}
function findPos(obj) {
	var curleft = curtop = 0;
	if(obj.offsetParent) {
		curleft = obj.offsetLeft;
		curtop = obj.offsetTop;
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		}
	}
	return [curleft, curtop];
}

function set_cookie(name, value, expires, path, domain, secure){
	var today = new Date();
	today.setTime(today.getTime());
	
	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 createSlider(id, inputid, width, minValue, maxValue, decimalPlaces, unit, increment, defaultValue, drawRuler){
	var enabled = true;
	var drawSlider = id && $(id);
	$(inputid).onchange = function(){}
	if(drawSlider){
		/////////////////////RULER
		if(drawRuler){
			var ruler = document.createElement('div');
			ruler.style.width = (width + 12) + 'px';
			ruler.style.height = '15px';
			var rulerTimes = Math.round(width / 10);
			var maxWidth = 0;
			for(var i = 0; i < rulerTimes; ++i){
				var div = document.createElement('div');
				div.style.borderLeft = '1px solid black';
				div.style.width = '9px';
				if(i == 0 || i == rulerTimes - 1) div.style.height = '6px';
				else div.style.height = '4px';
				div.style.cssFloat = 'left';
				div.style.styleFloat = 'left';
				div.style.marginTop = '10px';
				if(IE6) div.style.fontSize = '1px';
				if(i == 0) {
					if(IE6) div.style.marginLeft = '3px';
					else div.style.marginLeft = '6px';
				}

				maxWidth += 10;
				ruler.appendChild(div);
			}
			maxWidth -= 5;
		} else maxWidth = width;
		
		////////////////////SLIDER
		var slider = document.createElement('div');
		slider.style.position = 'absolute';
		slider.style.width = '11px';
		slider.style.height = '21px';
		slider.style.background = "url('images/slider.png')";
		slider.style.marginLeft = '1px';
		//slider.style.marginLeft = '1px';
		if(IE67) slider.style.marginTop = '-7px';
		////////////////////BACKGROUND
		var bg = document.createElement('div');
		bg.style.border = '1px solid #9c9e9c';
		bg.style.marginTop = '7px';
		bg.style.width = (maxWidth + 6) + 'px';
		bg.style.height = '3px';
		if(IE6) bg.style.fontSize = '1px';
		////////////////////MAIN
		var mainContainer = document.createElement('div');
		mainContainer.style.width = (maxWidth + 12) + 'px';
		mainContainer.style.height = drawRuler ? '36px' : '22px';
		mainContainer.style.overflow = 'hidden';
		mainContainer.style.position = 'relative';
		if(IE67) mainContainer.style.paddingTop = '7px';
		
		mainContainer.appendChild(slider);
		mainContainer.appendChild(bg);
		this.slider = slider;
		if(drawRuler) mainContainer.appendChild(ruler);
		$(id).appendChild(mainContainer);
		////////////////////MAIN EVENTS
		function setSliderPos(mousePos, val){
			if(enabled){
				var parentPos = findPos(slider.parentNode);
				var parentWidth = slider.parentNode.offsetWidth;
				var pos = Math.min(Math.max(0, 
								   mousePos[0] - parentPos[0] - Math.round(slider.offsetWidth / 2)),  
								   parentWidth - slider.offsetWidth - 6);
				slider.style.left = pos + 'px';
				var percent = pos * 100 / (parentWidth - 17);
				var value = minValue + ((percent / 100) * (maxValue - minValue));
				var decPlacesPower = Math.pow(10, decimalPlaces);
				if(val) value = Math.min(Math.max(minValue, val), maxValue);
				
				value = (Math.round(value * decPlacesPower) / decPlacesPower);
				$(inputid).value = value + unit;
				$(inputid).onchange();
			}
		}
		this.setSliderPos = setSliderPos;
		mainContainer.ondragstart = function(){return false;}
		mainContainer.onselectstart = function(){return false;}
		mainContainer.onmousedown = function(e){
			document.onmousemove = function(e){ 
				setSliderPos(getMouseXY(e));
			}
			document.onmouseup = function(){ 
				document.onmousemove = null;
				document.onmouseup = null;
			}
			document.onmousemove(e);
		}
	}
	////////////////////INPUT
	var valueUp = document.createElement('div');
	var valueDown = document.createElement('div');
	valueUp.style.width = 	 valueDown.style.width = '14px';
	valueUp.style.height =   valueDown.style.height = '7px';
	valueUp.style.border = 	 valueDown.style.border = '1px solid #6b84c2';
	valueUp.style.position = valueDown.style.position = 'absolute';
	valueUp.style.right = 	 valueDown.style.right = IE6 ? '1px' : '2px';
	valueUp.style.cursor = 	 valueDown.style.cursor = 'pointer';
	valueUp.style.top = 	 valueDown.style.bottom = Chrome ? '4px': IE67 ? '3px' : '2px';
	
	if(IE6) valueUp.style.fontSize = valueDown.style.fontSize = '1px';
	
	valueUp.style.background = "#b6cefb url('images/arrows.gif') no-repeat 3px 0";
	valueDown.style.background = "#b6cefb url('images/arrows.gif') no-repeat 3px -7px";

	this.updateSlider = function(){
		var floatValue = parseFloat($(inputid).value.replace(/,/g, '.').replace(/[^\d\.\-]/g, ''));
		if(drawSlider){
			var parentPos = findPos(slider.parentNode);
			var parentWidth = slider.parentNode.offsetWidth;

			var percent = 100 * (floatValue - minValue) / (maxValue - minValue);
			var offsetLeft = ((percent * (parentWidth - 17)) / 100) + parentPos[0] + Math.round(slider.offsetWidth / 2);
			
			setSliderPos([offsetLeft, 0], floatValue);
		} else {
			var decPlacesPower = Math.pow(10, decimalPlaces);
			var value = Math.min(Math.max(minValue, floatValue), maxValue);
			
			value = (Math.round(value * decPlacesPower) / decPlacesPower);
			$(inputid).value = value + unit;
		}
	}
	$(inputid).onblur = this.updateSlider;
	
	valueUp.onclick = function(){
		if(enabled){
			var floatVal = parseFloat($(inputid).value.replace(/,/g, '.').replace(/[^\d\.\-]/g, ''));
			if(floatVal < maxValue) $(inputid).value = (floatVal + increment) + unit;
			$(inputid).onblur();
		}
	}
	valueDown.onclick = function(){
		if(enabled){
			var floatVal = parseFloat($(inputid).value.replace(/,/g, '.').replace(/[^\d\.\-]/g, ''));
			if(floatVal > minValue) $(inputid).value = (floatVal - increment) + unit;
			$(inputid).onblur();
		}
	}
	var inputContainer = $(inputid).parentNode;
	inputContainer.style.width = $(inputid).offsetWidth + 'px';
	inputContainer.style.position = 'relative';

	inputContainer.appendChild(valueUp);
	inputContainer.appendChild(valueDown);
	inputContainer.appendChild($(inputid));
	
	if($(inputid).value == ''){
		$(inputid).value = defaultValue + unit;
	}
	this.updateSlider();
	
	this.enable = function(){
		enabled = true;
		$(inputid).disabled = false;
		bg.style.background = '#ffffff';
		valueUp.style.backgroundColor = valueDown.style.backgroundColor = '#b6cefb';
		valueUp.style.border = valueDown.style.border = '1px solid #6b84c2';
		valueUp.style.cursor = valueDown.style.cursor = 'pointer';
	}
	this.disable = function(){
		enabled = false;
		$(inputid).disabled = true;
		bg.style.background = '#b9b9b9';
		valueUp.style.backgroundColor = valueDown.style.backgroundColor = '#b9b9b9';
		valueUp.style.border = valueDown.style.border = '1px solid #686868';
		valueUp.style.cursor = valueDown.style.cursor = 'default';
	}
	if(id) this.id = id;
	else this.id = inputid;
	
	return this;
}
var sliders = new Array();
function createSlider2(p){
	createSlider(p.elementId, p.formInputId, p.width, p.minValue, p.maxValue, p.decimalPlaces, p.unit, p.increment, p.defaultValue);
}
function adding_3_step_sliders(){
	//<div class="slider" id="animalsSlider"></div><div class="int"><input type="text" name="animals" id="animalsInput" /></div>
	if($('step3sliders')){
		var lis = $('step3sliders').getElementsByTagName('li');
		for(var l in lis){
			var li = lis[l];
			if(!li.childNodes) continue;
			var checkbox = li.getElementsByTagName('input')[0];
			var id = checkbox.id;
			var sliderDiv = document.createElement('div');
			var inputDiv = document.createElement('div');
			inputDiv.className = 'int';
			var input = document.createElement('input');
			sliderDiv.className = 'slider';
			sliderDiv.id = id + 'Slider';	
			
			input.id = id + 'Input';
			input.name = id + 'Value';
			input.type = 'text';
			inputDiv.appendChild(input);
			li.appendChild(sliderDiv);
			li.appendChild(inputDiv);

			checkbox.onclick = function(){changeSliderState(this.parentNode.parentNode.getElementsByTagName('div')[1].id, this.checked);}
			sliders.push(new createSlider(id + 'Slider', id + 'Input', 200, 0, 10, 1, ' km', 1, 10, false));
			changeSliderState(id + 'Slider', checkbox.checked);
		}
	}
}
function showHide(el, show){
	el.style.display = show ? '' : 'none'; 
}

function homepage_advanced_sliders(){
	if($('homepageAdvancedSliders')){
		var lis = $('homepageAdvancedSliders').getElementsByTagName('li');
		for(var l in lis){
			var li = lis[l];
			if(!li.childNodes) continue;
			var checkbox = li.getElementsByTagName('input')[0];
			var id = checkbox.id;
			
			var inputDiv = document.createElement('div');
			inputDiv.className = 'int';
			var input = document.createElement('input');
			
			var doText = document.createElement('small');
			doText.innerHTML = 'do';

			input.id = id + 'Input';
			input.name = id + 'Value';
			input.type = 'text';
			input.style.width = '60px';
			inputDiv.style.cssFloat = 'right';
			inputDiv.style.styleFloat = 'right';
			inputDiv.appendChild(input);

			li.appendChild(inputDiv);
			li.appendChild(doText);

			checkbox.onclick = function(){
				showHide(this.parentNode.parentNode.getElementsByTagName('div')[1], this.checked);
				showHide(this.parentNode.parentNode.getElementsByTagName('small')[0], this.checked);
			}
			sliders.push(new createSlider('', id + 'Input', 0, 0, 10, 1, ' km', 1, 10, false));
			//showHide($(id + 'Input').parentNode, checkbox.checked);
			checkbox.onclick();
		}
		var controller = new createSlider('homepageAdvancedMainSlider', 'homepageAdvancedMainInput', 180, 0, 10, 1, ' km', 1, 10, false);
		var _inputOnBlur = $('homepageAdvancedMainInput').onblur;
		$('homepageAdvancedMainInput').onblur = function(){
			_inputOnBlur();
			var value = this.value;
			for(var s in sliders){
				$(sliders[s].id).value = value;
				$(sliders[s].id).onblur();
			}
		}
		$('homepageAdvancedMainInput').onchange = function(){
			var value = this.value;
			for(var s in sliders){
				$(sliders[s].id).value = value;
				$(sliders[s].id).onblur();
			}
		}
	}
}

function changeSliderState(id, enabled){
	for(var s in sliders){
		if(sliders[s].id == id){
			if(enabled) sliders[s].enable();
			else sliders[s].disable();
		}
	}
}
function st(){
	if($('container')){
		$('container').onmousemove = rating_mousemove;
		$('container').onclick = rating_click;
		$('container').onmouseout = rating_mouseout;
		old_rating = parseFloat($('rating').style.width.replace('px','')) / 16;
	}
}
function getLeft(obj){
	var left = 0;
	do {
		left += obj.offsetLeft;
	} while (obj = obj.offsetParent);
	return left;
}
function getTop(obj){
	var top = 0;
	do {
		top += obj.offsetTop;
	} while (obj = obj.offsetParent);
	return top;
}

function request(plik){
	if(window.XMLHttpRequest) obj = new XMLHttpRequest();
	else if(window.ActiveXObject) obj = new ActiveXObject('Microsoft.XMLHTTP');
	else return false;

	obj.open('GET', plik, false);
	obj.send(null);
	
	if(obj.readyState == 4) return obj.responseText;
	else return false;
}

function rating_mousemove(ev){
	ev = ev || window.event;
	if(ev.pageX) var pos = ev.pageX;
	else var pos = ev.clientX + (document.documentElement.scrollLeft?document.documentElement.scrollLeft:document.body.scrollLeft);
	pos -= getLeft($('rating'));
	pos += 4;
	var rat = pos / 16;
	if(rat > 5 || rat <= 0) return;
	if(rat % 0.5 == 0){
		rating = rat;
		$('rating').style.width = pos + 'px';
	}
}
function rating_click(){
	location.hash = '';
	var loc = location.href.replace('#', '');
	
	if(rating <= 0) return;
	var sep = '&';
	if(loc.indexOf('?') == -1) sep = '?'; 
	var response = request(loc+sep+'rate='+rating);
	
	if(response.indexOf('|') != -1) {
		response = response.split('|');
		old_rating = parseFloat(response[0]);
		$('rating').style.width = (old_rating * 16) + 'px';
		rating = 0;
		alert(response[1]);
	}else alert(response);
}
function rating_mouseout(ev){
	ev = ev || window.event;
	if(ev.pageX) var posx = ev.pageX;
	else var posx = ev.clientX + (document.documentElement.scrollLeft?document.documentElement.scrollLeft:document.body.scrollLeft);
	
	if(ev.pageY) var posy = ev.pageY;
	else var posy = ev.clientY + (document.documentElement.scrollTop?document.documentElement.scrollTop:document.body.scrollTop);
	if(posx >= getLeft($('container')) + 80 || posx < getLeft($('container')) 
	|| posy >= getTop($('container'))  + 16 || posy < getTop($('container'))){
		$('rating').style.width = (old_rating * 16) + 'px';
		rating = 0;
	}
}

function Prepare(el, text){
	var tooltip, b, s, l;
	tooltip = document.createElement('span');
	tooltip.className = 'tooltip';
	tooltip.innerHTML = text;
	el.tooltip = tooltip;
	el.onmouseover = function(e){
		$('btc').appendChild(this.tooltip);
		Locate(e);
	}
	el.onmouseout = function(){
		if($('btc').childNodes.length > 0) $('btc').removeChild($('btc').firstChild);
	}
	el.onmousemove = Locate;
}

function Locate(e){
	var posx = 0, posy = 0;
	if(e == null) e = window.event;
	if(e.pageX || e.pageY){
		posx = e.pageX; 
		posy = e.pageY;
	}else if(e.clientX || e.clientY){
		if(document.documentElement.scrollTop){
			posx=e.clientX+document.documentElement.scrollLeft;
			posy=e.clientY+document.documentElement.scrollTop;
		} else {
			posx=e.clientX+document.body.scrollLeft;
			posy=e.clientY+document.body.scrollTop;
		}
	}
	$('btc').style.top = (posy + 8) + 'px';
	$('btc').style.zIndex = 999;
	$('btc').style.left = posx + 12/* - Math.round($('btc').offsetWidth / 2) */+ 'px';
}

function get_elements_by_class(cn, root){
	if(!root) root = document;
	var queue = new Array();
	queue.push(root);
	var ret = new Array();
	while(queue.length > 0){
		element = queue.pop();
		if(element.className && element.className.indexOf(cn) != -1) ret.push(element);
		if(element.childNodes != null){
			if(element.childNodes.length>0){
				for(i = 0;i < element.childNodes.length; i++){
					queue.push(element.childNodes[i]);
				}
			}
		}
	}
	return ret;
}

var p = 1.0009;
var a = 50;
var s = 0.00000001;
var fps = 25;
function setOpacity(el, op){
	if(op == 100) opacity = '1.0';
	else if(op < 10) opacity = '0.0' + op;
	else opacity = '0.' + op;
	el.style.filter = 'alpha(opacity=' + op + ')';
	el.style.KHTMLOpacity = opacity;
	el.style.MozOpacity = opacity;
	el.style.opacity = opacity;
} 
function inOutQuint(t, b, c, d) {if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;return c/2*((t-=2)*t*t*t*t + 2) + b;}
function slide(element, sourceHeight, targetHeight, sourceOpacity, targetOpacity, time, forceOneWay, elapsed){
   var back = false;
   if(!elapsed) {
       elapsed = 0;
       if(!forceOneWay){
       		back = Math.round(parseFloat($(element).style.height.replace('px',''))) == targetHeight;
	   		if($(element).offsetHeight > 0 && $(element).style.height == '') back = true;
	   }
	   $(element).style.display = /*back?'none':*/'block';

   }

   if(back){
       var tmp = sourceHeight;
       sourceHeight = targetHeight;
       targetHeight = tmp;
	   
       var tmp = sourceOpacity;
       sourceOpacity = targetOpacity;
       targetOpacity = tmp;
   }
   var destHeight = targetHeight - sourceHeight;
   var destOpacity = targetOpacity - sourceOpacity;
   
   var newHeight = inOutQuint(elapsed, sourceHeight, destHeight, time);
   var newOpacity = Math.round(inOutQuint(elapsed, sourceOpacity, destOpacity, time));
   if(elapsed <= time) {
       if($(element)) {
	       	$(element).style.height = newHeight + 'px';
	
			elapsed += 1000 / fps;
			setTimeout('slide(\''+element+'\', '+sourceHeight+', '+targetHeight+', '+sourceOpacity+', '+targetOpacity+', '+time+', '+forceOneWay+', '+elapsed+')', 1000 / fps);
	
			setOpacity($(element), newOpacity);
	   }
	   //window.scroll(0, 5000);
   } else {
       if($(element)) {
	       $(element).style.height = targetHeight + 'px';
	
		   $(element).style.display = Math.round(parseFloat($(element).style.height.replace('px',''))) == 0?'none':'block';
		   if(targetHeight == 0) $(element).style.display = 'none';
		   //setOpacity($(element), 100);
	   }
   }
}
function fade(element, sourceOpacity, targetOpacity, time, fade, elapsed){
	var back = fade == 'out';
	if(!elapsed) elapsed = 0;

	if(back){
		var tmp = sourceOpacity;
		sourceOpacity = targetOpacity;
		targetOpacity = tmp;
	}
	var destOpacity = targetOpacity - sourceOpacity;

	var newOpacity = Math.round(inOutQuint(elapsed, sourceOpacity, destOpacity, time));
	if(elapsed <= time) {
		setOpacity($(element), newOpacity);
		elapsed += 1000 / fps;
		setTimeout('fade(\''+element+'\', '+sourceOpacity+', '+targetOpacity+', '+time+', \''+fade+'\', '+elapsed+')', 1000 / fps);

	} else {
		//setOpacity($(element), 100);
	}
}

function execCmd(id, cmd, param) {
	switch(cmd){
		case 'link':
			var url = prompt('Podaj adres URL linku', 'http://');
			if(url != null && url != ''){
				 $(id + '_iframe').contentWindow.document.execCommand('CreateLink', false, url);
			}
		break;
		case 'img':
			var url = prompt('Podaj adres URL obrazka', 'http://');
			if(url != null && url != ''){
				 $(id + '_iframe').contentWindow.document.execCommand('InsertImage', false, url);
			}
		break;
		default: $(id + '_iframe').contentWindow.document.execCommand(cmd, false, param); break;
	}
	return false;
}
function strip_tags(str, allowed_tags) {
    var key = '', allowed = false;
    var matches = [];
    var allowed_array = [];
    var allowed_tag = '';
    var i = 0;
    var k = '';
    var html = '';
 
    var replacer = function (search, replace, str) {
        return str.split(search).join(replace);
    };
    if(allowed_tags) allowed_array = allowed_tags.match(/([a-zA-Z0-9]+)/gi);
 
    str += '';
    matches = str.match(/(<\/?[\S][^>]*>)/gi);
    for (key in matches) {
        if (isNaN(key)) continue;
        html = matches[key].toString();
        allowed = false;
        for (k in allowed_array) {
            allowed_tag = allowed_array[k];
            i = -1;
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) { i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) { i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}
            if (i == 0) {
                allowed = true;
                break;
            }
        }
        if (!allowed) str = replacer(html, "", str);
    }
 
    return str;
}

function rgb2hex(s){
	s = s.replace('rgb(','').replace(')','').replace(/\s/g,'').split(',');
	var ret = '';
	for (var i = 0; i < 3; i++) ret += parseInt(s[i]).toString(16).replace(/^([\da-f])$/,"0$1");
	return '#' + ret;
}
function Xhtmlize(html){
	html = html.replace(/<(.*?)>/g, function(w){return w.toLowerCase();});
	html = html.replace(/(rgb\(\d+,\s?\d+,\s?\d+\))/g, rgb2hex);
	/*html = html.replace(/(<\/font>)/g, '</span>');
	html = html.replace(/font color=\"(.*?)\"/g, 'span style="color: $1"');
	html = html.replace(/<br>/gi, '<br />');
	html = html.replace(/<meta(.|\n)*<\/style>/gi, '');
	html = html.replace(/<script(.|\n)*<\/script>/gi, '');
	html = html.replace(/javascript:/gi, '');
	html = html.replace(/mso\-.*?\-/gi, '');
	html = html.replace(/ style=\"\"/gi, '');
	html = html.replace(/ class=\"msonormal\"/gi, '');
	html = html.replace(/<!\-?\-?\[if\s(.|\n)*?\]\-\->/gi, '');
	html = html.replace(/\n\n/gi, '\n');
	html = html.replace(/<(.*?)>/g, function(w){return w.toLowerCase();});*/
    //alert(html);
    html = strip_tags(html, '<b><strong><i><u><ol><ul><li><p><a><div><br><span><em>');
    html = html.replace(/javascript:/gi, '');    
    
	html = html.replace(/</g, '[[');
	html = html.replace(/>/g, ']]');
    
	
	return html;
}
function Xhtmlize2(html){
	html = html.replace(/<(.*?)>/g, function(w){return w.toLowerCase();});
	html = html.replace(/(rgb\(\d+,\s?\d+,\s?\d+\))/g, rgb2hex);
    html = strip_tags(html, '<b><strong><i><u><ol><ul><li><p><a><div><br><span><em>');
    html = html.replace(/javascript:/gi, '');    
	return html;
}
var textAreas = new Array();
function updateAllTextareas(){
	for(var i in textAreas){
		$(textAreas[i]).value = Xhtmlize($(textAreas[i] + '_iframe').contentWindow.document.body.innerHTML);
	}
}
function updateAllTextareas2(){
	/*for(var i in textAreas){
		$(textAreas[i]).value = Xhtmlize2($(textAreas[i] + '_iframe').contentWindow.document.body.innerHTML);
        $(textAreas[i] + '_iframe').contentWindow.document.body.innerHTML = $(textAreas[i]).value;
	}*/
}
function createButtons(id){
	var buttonsBG = document.createElement('div');
	//alert($(id).style.width);
	//buttonsBG.style.width = parseInt($(id).style.width.replace('px','')) - 7 + 'px'; 
	//buttonsBG.style.margin = $(id).style.margin;
	buttonsBG.className = 'icons';
	$(id).parentNode.appendChild(buttonsBG);

	var buttons2 = new Array();
	/*
	var select = document.createElement('select');
	for(var i = 1; i < 8; i++){
		var option = document.createElement('option');
		select.appendChild(option);
		buttons2.push(option);
	}
	buttons2[0].onclick = function(){return execCmd(id, 'fontSize', 1);}; buttons2[0].innerHTML = '8';
	buttons2[1].onclick = function(){return execCmd(id, 'fontSize', 2);}; buttons2[1].innerHTML = '10';
	buttons2[2].onclick = function(){return execCmd(id, 'fontSize', 3);}; buttons2[2].innerHTML = '11'; buttons2[2].selected = true;
	buttons2[3].onclick = function(){return execCmd(id, 'fontSize', 4);}; buttons2[3].innerHTML = '14';
	buttons2[4].onclick = function(){return execCmd(id, 'fontSize', 5);}; buttons2[4].innerHTML = '18';
	buttons2[5].onclick = function(){return execCmd(id, 'fontSize', 6);}; buttons2[5].innerHTML = '24';
	buttons2[6].onclick = function(){return execCmd(id, 'fontSize', 7);}; buttons2[6].innerHTML = '36';
	buttonsBG.appendChild(select);
	*/
	var buttons = [
		{title: 'Pogrubienie', text: 'B', id: 'bold'},
		{title: 'Pochylenie', text: 'I', id: 'italic'},
		{title: 'Podkreślenie', text: 'U', id: 'underline'},
		{title: 'Wyrównanie do lewej', text: '<-', id: 'justifyleft'},
		{title: 'Wyrównanie do środka', text: '-', id: 'justifycenter'},
		{title: 'Wyrównanie do prawej', text: '->', id: 'justifyright'},
		{title: 'Wyrównanie do obu stron', text: '<->', id: 'justifyfull'},
		{title: 'Wstaw listę numerowaną', text: 'ol', id: 'insertorderedlist'},
		{title: 'Wstaw listę punktowaną', text: 'ul', id: 'insertunorderedlist'},
		{title: 'Wstaw link', text: 'link', id: 'link'}
	];

	buttons2 = new Array();

	for(var i in buttons){
		var btn = document.createElement('button');
		btn.title = buttons[i].title;
		btn.className = buttons[i].id;
		btn.innerHTML = buttons[i].text;
		buttonsBG.appendChild(btn);
		buttons2.push(btn);
	}
	buttons2[0].onclick = function(){return execCmd(id, 'bold');};
	buttons2[1].onclick = function(){return execCmd(id, 'italic');};
	buttons2[2].onclick = function(){return execCmd(id, 'underline');};
	buttons2[3].onclick = function(){return execCmd(id, 'justifyleft');};
	buttons2[4].onclick = function(){return execCmd(id, 'justifycenter');};
	buttons2[5].onclick = function(){return execCmd(id, 'justifyright');};
	buttons2[6].onclick = function(){return execCmd(id, 'justifyfull');};
	buttons2[7].onclick = function(){return execCmd(id, 'insertorderedlist');};
	buttons2[8].onclick = function(){return execCmd(id, 'insertunorderedlist');};
	buttons2[9].onclick = function(){return execCmd(id, 'link');};

}
var updateInterval = 0;
function initWYSIWYG(id){
	if($(id)){
		createButtons(id);

		var iframe = document.createElement('iframe');
		iframe.id = id + '_iframe';
		iframe.style.marginTop = '0';
		$(id).style.display = 'none';
		$(id).parentNode.appendChild(iframe);
		textAreas.push(id);
        if(!updateInterval) updateInterval = setInterval('updateAllTextareas2()', 1000);


		var ifr_doc = $(id + '_iframe').contentWindow.document;
		ifr_doc.open();
		ifr_doc.write('<html><head></head><body style="padding: 15px;margin:0;font: 12px Tahoma; ">' + $(id).value + '</body></html>');
		ifr_doc.close();

		if(IE) ifr_doc.body.contentEditable = true;
		else ifr_doc.designMode = 'on';  
	}

}
//UPLOADER
function getDimensions(element) { 
	element = $(element); 
	var display = element.style.display; 
	if (display != 'none' && display != null) // Safari bug 
		return {width: element.offsetWidth, height: element.offsetHeight}; 
	
	var els = element.style; 
	var originalVisibility = els.visibility; 
	var originalPosition = els.position; 
	var originalDisplay = els.display; 
	els.visibility = 'hidden'; 
	els.position = 'absolute'; 
	els.display = 'block'; 
	var originalWidth = element.clientWidth; 
	var originalHeight = element.clientHeight; 
	els.display = originalDisplay; 
	els.position = originalPosition; 
	els.visibility = originalVisibility; 
	return {width: originalWidth, height: originalHeight}; 
}
function size_readable(size){
	c=0;
	format=new Array('B','KB','MB','GB','TB','PB','EB','ZB','YB');
	while((size/1024)>1 && c<8){
	    size/=1024;
	    c++;
	}
	size+='';
	if(size.indexOf('.')<=0 && c>1){
		size+=',00';
	}
	if(size.indexOf('.')>0){
		dk=size.substring(0,size.indexOf('.'));
		pk=size.substring(size.indexOf('.')+1,size.indexOf('.')+3);
		if(pk.length==1)pk+='0';
		size=dk+','+pk;
	}
	return size+' '+format[c];
}
function send(plik, post){
	if(window.XMLHttpRequest) obj = new XMLHttpRequest();
	else if(window.ActiveXObject) obj = new ActiveXObject('Microsoft.XMLHTTP');
	else return false;
	obj.open('POST', plik, false);
	obj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=utf-8');
	obj.send(post);
	if(obj.readyState == 4) return obj.responseText;
	else return false;
}
function UploadSetName(name){
	$('fileinput').value = name;
}
function UploadDelImage(id, divid, step2){
	if(step2){
		$(divid).innerHTML = '';
		$(divid).parentNode.removeChild($(divid));
		return false;
	}

    var isAdmin = document.location.href.indexOf('admin_edit') != -1;

	if(confirm('Czy na pewno chcesz usunąć to zdjęcie?')){
		var aid = /aid=(\d+)/i.exec(document.cookie);
		if($('acc_id')) aid = [0, $('acc_id').value];
		
		if(aid != null && parseInt(aid[1]) > 0){
            var uri = ($('acc_id')?'konto-ogloszenia.html?aid='+aid[1]+'&action=photos':'dodaj_nocleg.html');
            if(isAdmin) uri = 'index.php?load_standalone=admin_edit&mod=accomodations&id='+aid[1]+'&aid='+aid[1]+'&action=photos';
			var resp = send(uri, 'del=1&aid=' + aid[1] + '&id=' + id + '');
			//alert(resp);
			var h = getDimensions(divid).height;
			
			slide('photos', $('photos').offsetHeight, $('photos').offsetHeight - h, 100, 100, 800, true);
			slide(divid, h, 0, 100, 0, 800);
			
			if($('tooltip') && $('photos').getElementsByTagName('h4').length == 1) slide('tooltip', getDimensions('tooltip').height, 0, 100, 0, 800);
			
			$('picsleft').innerHTML = parseInt($('picsleft').innerHTML) + 1;
			
			var h4s = $('photos').getElementsByTagName('h4');
			var j = 1;
			for(var i = 0; i < h4s.length; ++i){
				if(h4s[i].parentNode.id == divid) continue;
				h4s[i].innerHTML = 'Zdjęcie ' + j + (j == 1?' <em style="float: none;">(GŁÓWNE)</em>' : '');
				j++;
			}
			
			setTimeout('UploadDelImage(\'\', \''+divid+'\', 1)', 1000);
		}
	}
	
	return false;
}
function UploadEditComplete(){
	$('flash_uploader').SetVariable('clearFile', 1);
	
	var user_acc = $('acc_id')?true:false;
	
	slide('edit', user_acc?320:500, 0, 100, 0, 800);
	setTimeout('$(\'edit\').style.display = \'none\';', 900);
	$('h4title').innerHTML = user_acc?'Zarządzanie zdjęciami':'Dodawanie zdjęć';
	$('picsleft').parentNode.style.display = '';
	if($('ttip')) $('ttip').style.display = '';
	$('description').value = '';
	$('submitPic').value = 'Wczytaj';
	$('submitPic').onclick = function(){StartUpload();};
	$('fileinput').value = '';
	
}


function UploadEditImage(id, divid){
	$('flash_uploader').SetVariable('clearFile', 1);
	var div = document.createElement('div');
	div.className = 'column';
	
	var user_acc = $('acc_id')?true:false;
	
	div.innerHTML = '<img src="'+$(divid).getElementsByTagName('img')[0].src.replace('_tn3', '_tn'+(user_acc?'2':'1'))+'" style="'+(user_acc?'width: 400px; height: 300px;':'width: 640px; height: 480px;')+'" alt="" />';
	$('edit').style.display = 'none';
	$('edit').innerHTML = '';
	$('edit').appendChild(div);
	$('h4title').innerHTML = 'Edycja zdjęcia';
	$('picsleft').parentNode.style.display = 'none';
	if($('ttip')) $('ttip').style.display = 'none';
	$('description').value = $(divid).getElementsByTagName('p')[0].innerHTML;
	$('submitPic').value = 'Zapisz';
	$('fileinput').value = '';
	
	slide('edit', 0, user_acc?320:500, 0, 100, 800);
    
    var isAdmin = document.location.href.indexOf('admin_edit') != -1;

	
	$('submitPic').onclick = function(){
		var aid = /aid=(\d+)/i.exec(document.cookie);
		if($('acc_id')) aid = [0, $('acc_id').value];
			
		if(aid != null && parseInt(aid[1]) > 0){
			if($('fileinput').value != ''){
				$('flash_uploader').SetVariable('desc', $('description').value);
				$('flash_uploader').SetVariable('editid', id);
				$('flash_uploader').SetVariable('aid', aid[1]);
				$('flash_uploader').SetVariable('upload', 1);
			} else {
			    var uri = (user_acc?'konto-ogloszenia.html?aid='+aid[1]+'&action=photos':'dodaj_nocleg.html');
                if(isAdmin) uri = 'index.php?load_standalone=admin_edit&mod=accomodations&id='+aid[1]+'&aid='+aid[1]+'&action=photos';
                
			    var resp = send(uri, 'edit=1&editid=' + id + '&aid=' + aid[1] + '&desc=' + $('description').value);
				//var resp = send();
				$(divid).getElementsByTagName('p')[0].innerHTML = $('description').value;
				
				UploadEditComplete();
			}
		} else {
			alert('Nie można pobrać id ogłoszenia!');
		}
	}
	return false;
}

function UploadComplete(response, edit){

	fade('progresscontainer', 100, 0, 800, 'in');
	$('description').disabled = false;
	$('fileinput').value = '';
	$('description').value = '';
	$('submitPic').disabled = false;
	//alert(response);
	
	var user_acc = $('acc_id')?true:false;
	
	if(response == 'NO_PICS_LEFT') {
		alert('Nie możesz dodać więcej zdjęć!');
		return;
	}
	var values = response.split(';##;');
	if(values.length < 3){
		alert('Wystąpił błąd - ' + response);
		return;
	}
	
	if(edit){
		$('tmpid' + values[0]).getElementsByTagName('img')[0].src = values[1];
		$('tmpid' + values[0]).getElementsByTagName('p')[0].innerHTML = values[2];
		
		UploadEditComplete();
		return;
	}
	
	var nr = $('photos').getElementsByTagName('h4').length + 1;
	var tmpid = 'tmpid' + values[0];
	var div = document.createElement('div');
	div.style.display = 'none';
	div.style.overflow = 'hidden'; 
	div.id = tmpid;
	
	var html =  '<h4>Zdjęcie ' + nr + (nr == 1?' <em style="float: none;">(GŁÓWNE)</em>':'')+'</h4>'+
				'<div class="image">'+
				'	<div class="column">'+
				'    	<img src="'+values[1]+'" alt="" />'+
				'    </div>'+
				'    <div class="column">'+
				'    	<p>'+values[2]+'</p>'+
				'        <a href="#" onclick="return UploadEditImage('+values[0]+', \''+tmpid+'\');" class="edit">edytuj zdjęcie</a>'+
				'        <a href="#" onclick="return UploadDelImage('+values[0]+', \''+tmpid+'\');" class="delete">usuń zdjęcie</a>'+
				'    </div>'+
				'</div>'+
				'<span class="br"></span>'+
				'<span class="spc"></span>';
	div.innerHTML = html;
	
	var photos_height = $('photos').offsetHeight;
	
	$('photos').appendChild(div);
	$('picsleft').innerHTML = parseInt($('picsleft').innerHTML) - 1;
	
	var h = getDimensions(tmpid).height;

	//if(!user_acc) 
	slide('photos', photos_height, photos_height + h, 100, 100, 800, true);
	slide(tmpid, 0, h, 0, 100, 800);
	if($('tooltip') && nr == 1) slide('tooltip', 0, getDimensions('tooltip').height, 0, 100, 800);
}
function StartUpload(){
	if(parseInt($('picsleft').innerHTML) == 0){
		alert('Nie możesz dodać więcej zdjęć!');
		return;
	}
	
	$('flash_uploader').SetVariable('desc', $('description').value);
	var aid = /aid=(\d+)/i.exec(document.cookie);
	
	if($('acc_id')) aid = [0, $('acc_id').value];
	
	if(aid != null && parseInt(aid[1]) > 0){
		//var type = /type=(\d+)/i.exec(document.cookie);
		//if($('type_id')) type = [0,$('type_id').value];
		//if(type != null && parseInt(type[1]) >= 0) 
		$('flash_uploader').SetVariable('type', 0); 
		
		$('flash_uploader').SetVariable('aid', aid[1]);
		$('flash_uploader').SetVariable('upload', 1);
	} else {
		alert('Nie można pobrać id ogłoszenia!');
	}
	return;
}
function UploadStart(){
	$('progress').style.width = '0px';
	$('submitPic').disabled = true;
	$('description').disabled = true;
	
	fade('progresscontainer', 0, 100, 800, 'in');
}
function UploadProgress(procent,przeslane,calosc,predkosc,name){
	$('progress').style.width = procent + '%';
	$('fileinput').value = name + ' - ' + procent + '%' + ' (' + size_readable(predkosc) + '/s)';
}
var photo_size = '2';
var currentPhoto = 0;
var img = new Image();
img.src = 'http://www.eurotravels.pl/img/loading.gif';
function waitFor(element, tn, name){
	if(!img.complete){
		setTimeout('waitFor(\'' + element + '\', \'' + tn + '\', \'' + name + '\')', 250);
	} else {
		setOpacity($(element), 0);
		$(element).parentNode.style.textAlign = '';
		$(element).style.marginTop = '5px';
		$(element).style.marginBottom = '0';
		$(element).src = 'http://www.eurotravels.pl/img/upload/' + tn + '_tn'+photo_size+'.jpg';
		$('photodesc').innerHTML = name;
		//$(element).width = 362;
		chn(element, tn, name, 0, 1);
	}
}
function galleryNext(){
	if(currentPhoto+1 >= $('gallery').getElementsByTagName('img').length){
		$('photo_next').className = 'inactive';
		return false;
	}
	$('photo_next').className = '';
	$('photo_previous').className = '';
	if(currentPhoto+2 >= $('gallery').getElementsByTagName('img').length) $('photo_next').className = 'inactive';

	$('gallery').getElementsByTagName('img')[++currentPhoto].onclick();
	$('actual').innerHTML = currentPhoto+1;
	
}
function galleryPrev(){
	if(currentPhoto <= 0){
		$('photo_previous').className = 'inactive';
		return false;
	}
	$('photo_previous').className = '';
	$('photo_next').className = '';
	if(currentPhoto <= 1) $('photo_previous').className = 'inactive';

	$('gallery').getElementsByTagName('img')[--currentPhoto].onclick();
	$('actual').innerHTML = currentPhoto+1;

	
}
function chn2(element, tn, name, no) {
	photo_size = '1';
	currentPhoto = no-1;
	
	$('photo_previous').className = '';
	$('photo_next').className = '';
	if(no <= 1) $('photo_previous').className = 'inactive';
	if(no >= $('gallery').getElementsByTagName('img').length) $('photo_next').className = 'inactive';
	
	$('actual').innerHTML = no;
	return chn(element, tn, name);
}
function chn1(element, tn, name, op, f) {
	photo_size = '2';
	return chn(element, tn, name, op, f);
}
function chn99(element, tn) {
	$(element).href = tn;	
}
function chn(element, tn, name, op, f) {
	if(f == null) f = 0;
	if(op == null) op = 100;
	if(name == '') name = '&nbsp;';
	if(f == 0){
		if(op > 0){
			setOpacity($(element), op);
			op -= 10;
			setTimeout('chn(\'' + element + '\', \'' + tn + '\', \'' + name + '\', ' + op + ', 0)', 30);
			return;
		}
	} else {
		if(op <= 100){
			setOpacity($(element), op);
			op += 10;
			setTimeout('chn(\'' + element + '\', \'' + tn + '\', \'' + name + '\', ' + op + ', 1)', 30);
			return;
		} else return;
	}
	img = new Image();
	img.src = 'http://www.eurotravels.pl/img/upload/' + tn + '_tn'+photo_size+'.jpg';
	if(!img.complete){
		$(element).parentNode.style.textAlign = 'center';
		$(element).src = 'http://www.eurotravels.pl/img/loading.gif';
		
		if(photo_size == '2'){
			$(element).style.marginTop = '145px';
			$(element).style.marginBottom = '128px';
		} else {
			$(element).style.marginTop = '235px';
			$(element).style.marginBottom = '218px';
		}
		//$(element).width = 32;
		//$(element).style.width = 32;
		setOpacity($(element), 100);
	}
	waitFor(element, tn, name);
}
function fade(element, op, f) {
	if(navigator.userAgent.indexOf('MSIE') != -1){
		if(f == 0) $(element).style.display = 'none';
		else $(element).style.display = 'block';
		return;
	}
	if(f == 0){
		if(op >= 0){
			setOpacity($(element), op);
			op -= 10;
			setTimeout('fade(\'' + element + '\', ' + op + ', 0)', 30);
		}else $(element).style.display = 'none';
	} else {
		if(op <= 100){
			$(element).style.display = 'block';
			setOpacity($(element), op);
			op += 10;
			setTimeout('fade(\'' + element + '\', ' + op + ', 1)', 30);
		}
	}
}
function scroller(){
	var startPos = 10;
    var scrollCursor = startPos;
    var speed = 3;
    var timeoutID = 0;
	var right_visible = true;
	var left_visible = false;
	var element = $('gallery_parent');
	if(!element) return;
	childNodeWidth = 0;

	
	if(element.childNodes[1]) childNodeWidth = element.childNodes[1].offsetWidth;
	else childNodeWidth = element.childNodes[0].offsetWidth;

	$('scroll_left').style.display = 'none';
	$('scroll_right').style.display = '';
	
	if(childNodeWidth < element.parentNode.offsetWidth){
		$('scroll_left').style.display = 'none';
		$('scroll_right').style.display = 'none';
		return;
	}

	element.style.left = startPos+'px';
	$('scroll_left').onmouseover = function() { scrollLeft();};
	$('scroll_left').onmouseout = function() { clearTimeout(timeoutID);};
	$('scroll_right').onmouseover = function() { scrollRight();};
	$('scroll_right').onmouseout = function() { clearTimeout(timeoutID);};

	scrollRight = function() {
        if (element) {
        	
            scrollCursor -= speed;
			if(scrollCursor < -(childNodeWidth - element.parentNode.offsetWidth)) {
				if(right_visible) {
					fade('scroll_right', 100, 0);
					right_visible = false;
				}
				return;
			}
			if(!left_visible){
				fade('scroll_left', 0, 1);
				left_visible = true;
			}
			
			//alert(element.tagName);
			element.style.left = scrollCursor+'px';
            timeoutID = setTimeout('scrollRight()', 20);
        }
    }
	scrollLeft = function() {
        if (element) {
			scrollCursor = (scrollCursor + speed) > startPos ? startPos : scrollCursor + speed;
			if(scrollCursor + speed > startPos){
				if(left_visible) {
					fade('scroll_left', 100, 0);
					left_visible = false;
				}
				return;
			}
			if(!right_visible){
				fade('scroll_right', 0, 1);
				right_visible = true;
			}
            element.style.left = scrollCursor+'px';
            timeoutID = setTimeout('scrollLeft()', 20);
        }
    }
}


function changeBookingStatus(el, aid, date){
	el.className = request('konto-ogloszenia.html?aid=' + aid + '&action=bookings&option=changeStatus&date='+date);
}

function changeBookingStatusAdmin(el, aid, date){
	el.className = request('?load_standalone=admin_edit&mod=accomodations&id=' + aid + '&aid=' + aid + '&action=bookings&option=changeStatus&date=' + date);
}
function changePromotedStatus(el, aid, date){
	if(el.className == 'green'){
		$('days_left').innerHTML++;
		el.className = '';
		$('form_dates').value += date + ',';
	} else if(el.className == 'red'){
		$('days_left').innerHTML++;
		el.className = '';
		$('form_dates').value = $('form_dates').value.replace(date + ',', '');
	} else {
		if($('days_left').innerHTML > 0){
			el.className = 'red';

			$('form_dates').value += date + ',';
			
			$('days_left').innerHTML--;
		}else alert('Brak dni do wykorzystania');
	}
}

function saveMapLocation(aid, lat, lng){
	return request('konto-ogloszenia.html?aid=' + aid + '&action=map&option=changeLoc&lat='+escape(lat)+'&lng='+escape(lng));
}
function saveMapLocationAdmin(aid, lat, lng){
    return request('?load_standalone=admin_edit&mod=accomodations&id=' + aid + '&aid=' + aid + '&action=map&option=changeLoc&lat='+escape(lat)+'&lng='+escape(lng));
}
function clearFacilitiesCookie(){
	set_cookie('ids1', '');
	set_cookie('ids2', '');
	set_cookie('distances', '');
	var input = document.createElement('input');
	input.name='cookie';
	input.value='1';
	input.type='hidden';
	$('search_foorm').appendChild(input);

}
function saveFacilitiesCookie(form, distances, submit, third){
	var elems = form.getElementsByTagName('input');
	var ids = '';
	var distancesValues = '';
	for(var elem in elems){
		var el = elems[elem];
		if(el.type == 'checkbox' && el.checked) {
			if(ids.indexOf(el.name + ',') != -1) continue;
			
			ids += el.name + ',';
			//set_cookie('f1_'+i, 'true');
			if(distances && form[el.name+'Input']) {
				var floatVal = parseFloat(form[el.name+'Input'].value.replace(/,/g, '.').replace(/[^\d\.\-]/g, ''));
				
				distancesValues += floatVal + ',';
				//alert(distancesValues);
				//set_cookie(el.name+'Value', form[el.name+'Input'].value);
			}
		}
	}
 
	if(distances){
		set_cookie('ids2', ids);
		saveFacilitiesCookie($('facilities_form'), null, submit, true);
		set_cookie('distances', distancesValues);
	} else if(!third) {
		set_cookie('ids1', ids);
		set_cookie('ids2', '');
		set_cookie('distances', '');
	} else {
		set_cookie('ids1', ids);
	}
	var input = document.createElement('input');
	input.name='cookie';
	input.value='1';
	input.type='hidden';
	$('search_foorm').appendChild(input);

	if(submit) {
	   if($('city') && $('city').value != '') $('search_foorm').submit();
       else {
            if(document.location.href.indexOf('?') != -1) document.location.href += '&cookie=1';
            else {
                $('city').style.border = '1px solid red';
                return false;
            }
       }
    }
}


function searchAdvTowns(elem, uri){
    var items = elem.getElementsByTagName('input');
    var names = '';
    for(var i in items){
        if(items[i].checked){
            var parts = items[i].getAttribute('name').split('_');
            parts.splice(0, 2);
            
            
            var name = parts.join('_');
            
            if((',' + names).indexOf(',' + name + ',') == -1)
                names += name + ',';
        }
    }
    names = names.replace(/,$/g, '');
    if(!names) names = '__';
    
    document.location.href = uri.replace('jstownsreplace', names);
    
}

function externalLinks()
{
	if (!document.getElementsByTagName) return;
	
	var anchors = document.getElementsByTagName("a");
	
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		var relvalue = anchor.getAttribute("rel");
		
		if (anchor.getAttribute("href")) {
			var external = /external/;
			var relvalue = anchor.getAttribute("rel");
			if (external.test(relvalue)) { anchor.target = "_blank"; }
		}
	}
}


//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/*  Prototype JavaScript framework
 *  (c) 2005 Sam Stephenson <sam@conio.net>
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://prototype.conio.net/
/*--------------------------------------------------------------------------*/

//note: modified & stripped down version of prototype, to be used with moo.fx by mad4milk (http://moofx.mad4milk.net).

var Class = {
	create: function() {
		return function() {
			this.initialize.apply(this, arguments);
		}
	}
}

Object.extend = function(destination, source) {
	for (property in source) destination[property] = source[property];
	return destination;
}

Function.prototype.bind = function(object) {
	var __method = this;
	return function() {
		return __method.apply(object, arguments);
	}
}

Function.prototype.bindAsEventListener = function(object) {
var __method = this;
	return function(event) {
		__method.call(object, event || window.event);
	}
}

function $() {
	if (arguments.length == 1) return get$(arguments[0]);
	var elements = [];
	$c(arguments).each(function(el){
		elements.push(get$(el));
	});
	return elements;

	function get$(el){
		if (typeof el == 'string') el = document.getElementById(el);
		return el;
	}
}

if (!window.Element) var Element = new Object();

Object.extend(Element, {
	remove: function(element) {
		element = $(element);
		element.parentNode.removeChild(element);
	},

	hasClassName: function(element, className) {
		element = $(element);
		if (!element) return;
		var hasClass = false;
		element.className.split(' ').each(function(cn){
			if (cn == className) hasClass = true;
		});
		return hasClass;
	},

	addClassName: function(element, className) {
		element = $(element);
		Element.removeClassName(element, className);
		element.className += ' ' + className;
	},
  
	removeClassName: function(element, className) {
		element = $(element);
		if (!element) return;
		var newClassName = '';
		element.className.split(' ').each(function(cn, i){
			if (cn != className){
				if (i > 0) newClassName += ' ';
				newClassName += cn;
			}
		});
		element.className = newClassName;
	},

	cleanWhitespace: function(element) {
		element = $(element);
		$c(element.childNodes).each(function(node){
			if (node.nodeType == 3 && !/\S/.test(node.nodeValue)) Element.remove(node);
		});
	},

	find: function(element, what) {
		element = $(element)[what];
		while (element.nodeType != 1) element = element[what];
		return element;
	}
});

var Position = {
	cumulativeOffset: function(element) {
		var valueT = 0, valueL = 0;
		do {
			valueT += element.offsetTop  || 0;
			valueL += element.offsetLeft || 0;
			element = element.offsetParent;
		} while (element);
		return [valueL, valueT];
	}
};

document.getElementsByClassName = function(className) {
	var children = document.getElementsByTagName('*') || document.all;
	var elements = [];
	$c(children).each(function(child){
		if (Element.hasClassName(child, className)) elements.push(child);
	});  
	return elements;
}

//useful array functions
Array.prototype.iterate = function(func){
	for(var i=0;i<this.length;i++) func(this[i], i);
}
if (!Array.prototype.each) Array.prototype.each = Array.prototype.iterate;

function $c(array){
	var nArray = [];
	for (var i=0;i<array.length;i++) nArray.push(array[i]);
	return nArray;
}

/*
moo.fx, simple effects library built with prototype.js (http://prototype.conio.net).
by Valerio Proietti (http://mad4milk.net) MIT-style LICENSE.
for more info (http://moofx.mad4milk.net).
Sunday, March 05, 2006
v 1.2.3
*/

var fx = new Object();
//base
fx.Base = function(){};
fx.Base.prototype = {
	setOptions: function(options) {
	this.options = {
		duration: 500,
		onComplete: '',
		transition: fx.sinoidal
	}
	Object.extend(this.options, options || {});
	},

	step: function() {
		var time  = (new Date).getTime();
		if (time >= this.options.duration+this.startTime) {
			this.now = this.to;
			clearInterval (this.timer);
			this.timer = null;
			if (this.options.onComplete) setTimeout(this.options.onComplete.bind(this), 10);
		}
		else {
			var Tpos = (time - this.startTime) / (this.options.duration);
			this.now = this.options.transition(Tpos) * (this.to-this.from) + this.from;
		}
		this.increase();
	},

	custom: function(from, to) {
		if (this.timer != null) return;
		this.from = from;
		this.to = to;
		this.startTime = (new Date).getTime();
		this.timer = setInterval (this.step.bind(this), 13);
	},

	hide: function() {
		this.now = 0;
		this.increase();
	},

	clearTimer: function() {
		clearInterval(this.timer);
		this.timer = null;
	}
}

//stretchers
fx.Layout = Class.create();
fx.Layout.prototype = Object.extend(new fx.Base(), {
	initialize: function(el, options) {
		this.el = $(el);
		this.el.style.overflow = "hidden";
		this.iniWidth = this.el.offsetWidth;
		this.iniHeight = this.el.offsetHeight;
		this.setOptions(options);
	}
});

fx.Height = Class.create();
Object.extend(Object.extend(fx.Height.prototype, fx.Layout.prototype), {	
	increase: function() {
		this.el.style.height = this.now + "px";
	},

	toggle: function() {
		if (this.el.offsetHeight > 0) this.custom(this.el.offsetHeight, 0);
		else this.custom(0, this.el.scrollHeight);
	}
});

fx.Width = Class.create();
Object.extend(Object.extend(fx.Width.prototype, fx.Layout.prototype), {	
	increase: function() {
		this.el.style.width = this.now + "px";
	},

	toggle: function(){
		if (this.el.offsetWidth > 0) this.custom(this.el.offsetWidth, 0);
		else this.custom(0, this.iniWidth);
	}
});

//fader
fx.Opacity = Class.create();
fx.Opacity.prototype = Object.extend(new fx.Base(), {
	initialize: function(el, options) {
		this.el = $(el);
		this.now = 1;
		this.increase();
		this.setOptions(options);
	},

	increase: function() {
		if (this.now == 1 && (/Firefox/.test(navigator.userAgent))) this.now = 0.9999;
		this.setOpacity(this.now);
	},
	
	setOpacity: function(opacity) {
		if (opacity == 0 && this.el.style.visibility != "hidden") this.el.style.visibility = "hidden";
		else if (this.el.style.visibility != "visible") this.el.style.visibility = "visible";
		if (window.ActiveXObject) this.el.style.filter = "alpha(opacity=" + opacity*100 + ")";
		this.el.style.opacity = opacity;
	},

	toggle: function() {
		if (this.now > 0) this.custom(1, 0);
		else this.custom(0, 1);
	}
});

//transitions
fx.sinoidal = function(pos){
	return ((-Math.cos(pos*Math.PI)/2) + 0.5);
	//this transition is from script.aculo.us
}
fx.linear = function(pos){
	return pos;
}
fx.cubic = function(pos){
	return Math.pow(pos, 3);
}
fx.circ = function(pos){
	return Math.sqrt(pos);
}

// -----------------------------------------------------------------------------------
//
//	Litebox v1.0
//	A combined effort between detrate and gannon
//	07/03/06
//
//	Source edited from Lightbox v2.02
//	by Lokesh Dhakar - http://www.huddletogether.com
//
//	For more information on this script, visit:
//	http://doknowevil.net/litebox
//
//	Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
//	
//	Credit also due to those who have helped, inspired, and made their code available to the public.
//	Including: Scott Upton(uptonic.com), Peter-Paul Koch(quirksmode.org), Thomas Fuchs(mir.aculo.us), and others.
//
// -----------------------------------------------------------------------------------

//
//	Configuration
//
var fileLoadingImage = "../images/loading.gif";		
var fileBottomNavCloseImage = "../images/closelabel.gif";
var resizeSpeed = 6;	// controls the speed of the image resizing (1=slowest and 10=fastest)
var borderSize = 10;	//if you adjust the padding in the CSS, you will need to update this variable

// -----------------------------------------------------------------------------------

//
//	Global Variables
//
var imageArray = new Array;
var activeImage;

if(resizeSpeed > 10){ resizeSpeed = 10;}
if(resizeSpeed < 1){ resizeSpeed = 1;}
resizeDuration = (11 - resizeSpeed) * 100;

// -----------------------------------------------------------------------------------

//
//	Additional methods for Element added by SU, Couloir
//	- further additions by Lokesh Dhakar (huddletogether.com)
//
Object.extend(Element, {
	hide: function() {
		for (var i = 0; i < arguments.length; i++) {
			var element = $(arguments[i]);
			element.style.display = 'none';
		}
	},
	show: function() {
		for (var i = 0; i < arguments.length; i++) {
			var element = $(arguments[i]);
			element.style.display = '';
		}
	},
	getWidth: function(element) {
	   	element = $(element);
	   	return element.offsetWidth; 
	},
	setWidth: function(element,w) {
	   	element = $(element);
		element.style.width = w +"px";
	},
	getHeight: function(element) {
		element = $(element);
		return element.offsetHeight;
	},
	setHeight: function(element,h) {
   		element = $(element);
		element.style.height = h +"px";
	},
	setTop: function(element,t) {
	   	element = $(element);
		element.style.top = t +"px";
	},
	setSrc: function(element,src) {
		element = $(element);
		element.src = src; 
	},
	setInnerHTML: function(element,content) {
		element = $(element);
		element.innerHTML = content;
	}
});

// -----------------------------------------------------------------------------------

//
//	Extending built-in Array object
//
Array.prototype.removeDuplicates = function () {
	for(i = 1; i < this.length; i++){
		if(this[i][0] == this[i-1][0]){
			this.splice(i,1);
		}
	}
}

Array.prototype.empty = function () {
	for(i = 0; i <= this.length; i++){
		this.shift();
	}
}

// -----------------------------------------------------------------------------------
//
//	Structuring of code inspired by Scott Upton (http://www.uptonic.com/)
//
var Lightbox = Class.create();

Lightbox.prototype = {
	
	// initialize()
	// Constructor runs on completion of the DOM loading. Loops through anchor tags looking for 
	// 'lightbox' references and applies onclick events to appropriate links. The 2nd section of
	// the function inserts html at the bottom of the page which is used to display the shadow 
	// overlay and the image container.
	//
	initialize: function() {
		if (!document.getElementsByTagName){ return; }
		var anchors = document.getElementsByTagName('a');

		// loop through all anchor tags
		for (var i=0; i<anchors.length; i++){
			var anchor = anchors[i];
			
			var relAttribute = String(anchor.getAttribute('rel'));
			
			// use the string.match() method to catch 'lightbox' references in the rel attribute
			if (anchor.getAttribute('href') && (relAttribute.toLowerCase().match('lightbox'))){
				anchor.onclick = function () {myLightbox.start(this); return false;}
			}
		}

		var objBody = document.getElementsByTagName("body").item(0);
		
		var objOverlay = document.createElement("div");
		objOverlay.setAttribute('id','overlay');
		objOverlay.onclick = function() { myLightbox.end(); return false; }
		objBody.appendChild(objOverlay);
		
		var objLightbox = document.createElement("div");
		objLightbox.setAttribute('id','lightbox');
		objLightbox.style.display = 'none';
		objBody.appendChild(objLightbox);
	
		var objOuterImageContainer = document.createElement("div");
		objOuterImageContainer.setAttribute('id','outerImageContainer');
		objLightbox.appendChild(objOuterImageContainer);

		var objImageContainer = document.createElement("div");
		objImageContainer.setAttribute('id','imageContainer');
		objOuterImageContainer.appendChild(objImageContainer);
	
		var objLightboxImage = document.createElement("img");
		objLightboxImage.setAttribute('id','lightboxImage');
		objImageContainer.appendChild(objLightboxImage);
	
		var objHoverNav = document.createElement("div");
		objHoverNav.setAttribute('id','hoverNav');
		objImageContainer.appendChild(objHoverNav);
	
		var objPrevLink = document.createElement("a");
		objPrevLink.setAttribute('id','prevLink');
		objPrevLink.setAttribute('href','#');
		objHoverNav.appendChild(objPrevLink);
		
		var objNextLink = document.createElement("a");
		objNextLink.setAttribute('id','nextLink');
		objNextLink.setAttribute('href','#');
		objHoverNav.appendChild(objNextLink);
	
		var objLoading = document.createElement("div");
		objLoading.setAttribute('id','loading');
		objImageContainer.appendChild(objLoading);
	
		var objLoadingLink = document.createElement("a");
		objLoadingLink.setAttribute('id','loadingLink');
		objLoadingLink.setAttribute('href','#');
		objLoadingLink.onclick = function() { myLightbox.end(); return false; }
		objLoading.appendChild(objLoadingLink);
	
		var objLoadingImage = document.createElement("img");
		objLoadingImage.setAttribute('src', fileLoadingImage);
		objLoadingLink.appendChild(objLoadingImage);

		var objImageDataContainer = document.createElement("div");
		objImageDataContainer.setAttribute('id','imageDataContainer');
		objImageDataContainer.className = 'clearfix';
		objLightbox.appendChild(objImageDataContainer);

		var objImageData = document.createElement("div");
		objImageData.setAttribute('id','imageData');
		objImageDataContainer.appendChild(objImageData);
	
		var objImageDetails = document.createElement("div");
		objImageDetails.setAttribute('id','imageDetails');
		objImageData.appendChild(objImageDetails);
	
		var objCaption = document.createElement("span");
		objCaption.setAttribute('id','caption');
		objImageDetails.appendChild(objCaption);
	
		var objNumberDisplay = document.createElement("span");
		objNumberDisplay.setAttribute('id','numberDisplay');
		objImageDetails.appendChild(objNumberDisplay);
		
		var objBottomNav = document.createElement("div");
		objBottomNav.setAttribute('id','bottomNav');
		objImageData.appendChild(objBottomNav);
	
		var objBottomNavCloseLink = document.createElement("a");
		objBottomNavCloseLink.setAttribute('id','bottomNavClose');
		objBottomNavCloseLink.setAttribute('href','#');
		objBottomNavCloseLink.onclick = function() { myLightbox.end(); return false; }
		objBottomNav.appendChild(objBottomNavCloseLink);
	
		var objBottomNavCloseImage = document.createElement("img");
		objBottomNavCloseImage.setAttribute('src', fileBottomNavCloseImage);
		objBottomNavCloseLink.appendChild(objBottomNavCloseImage);
		
		overlayEffect = new fx.Opacity(objOverlay, { duration: 300 });	
		overlayEffect.hide();
		
		imageEffect = new fx.Opacity(objLightboxImage, { duration: 350, onComplete: function() { imageDetailsEffect.custom(0,1); }});
		imageEffect.hide();
		
		imageDetailsEffect = new fx.Opacity('imageDataContainer', { duration: 400, onComplete: function() { navEffect.custom(0,1); }}); 
		imageDetailsEffect.hide();
		
		navEffect = new fx.Opacity('hoverNav', { duration: 100 });
		navEffect.hide();
	},
	
	//
	//	start()
	//	Display overlay and lightbox. If image is part of a set, add siblings to imageArray.
	//
	start: function(imageLink) {	

		hideSelectBoxes();

		// stretch overlay to fill page and fade in
		var arrayPageSize = getPageSize();
		Element.setHeight('overlay', arrayPageSize[1]);
		overlayEffect.custom(0,0.8);
		
		imageArray = [];
		imageNum = 0;		

		if (!document.getElementsByTagName){ return; }
		var anchors = document.getElementsByTagName('a');

		// if image is NOT part of a set..
		if((imageLink.getAttribute('rel') == 'lightbox')){
			// add single image to imageArray
			imageArray.push(new Array(imageLink.getAttribute('href'), imageLink.getAttribute('title')));			
		} else {
		// if image is part of a set..

			// loop through anchors, find other images in set, and add them to imageArray
			for (var i=0; i<anchors.length; i++){
				var anchor = anchors[i];
				if (anchor.getAttribute('href') && (anchor.getAttribute('rel') == imageLink.getAttribute('rel'))){
					imageArray.push(new Array(anchor.getAttribute('href'), anchor.getAttribute('title')));
				}
			}
			imageArray.removeDuplicates();
			while(imageArray[imageNum][0] != imageLink.getAttribute('href')) { imageNum++;}
		}

		// calculate top offset for the lightbox and display 
		var arrayPageSize = getPageSize();
		var arrayPageScroll = getPageScroll();
		var lightboxTop = arrayPageScroll[1] + (arrayPageSize[3] / 15);

		Element.setTop('lightbox', lightboxTop);
		Element.show('lightbox');
		this.changeImage(imageNum);
	},

	//
	//	changeImage()
	//	Hide most elements and preload image in preparation for resizing image container.
	//
	changeImage: function(imageNum) {
		
		activeImage = imageNum;	// update global var

		// hide elements during transition
		Element.show('loading');
		imageDetailsEffect.hide();
		imageEffect.hide();
		navEffect.hide();
		Element.hide('prevLink');
		Element.hide('nextLink');
		Element.hide('numberDisplay');
		
		imgPreloader = new Image();
		// once image is preloaded, resize image container
		imgPreloader.onload=function(){
			Element.setSrc('lightboxImage', imageArray[activeImage][0]);
			myLightbox.resizeImageContainer(imgPreloader.width, imgPreloader.height);
		}
		imgPreloader.src = imageArray[activeImage][0];
	},

	//
	//	resizeImageContainer()
	//
	resizeImageContainer: function( imgWidth, imgHeight) {

		// get current height and width
		this.wCur = Element.getWidth('outerImageContainer');
		this.hCur = Element.getHeight('outerImageContainer');

		// calculate size difference between new and old image, and resize if necessary
		wDiff = (this.wCur - borderSize * 2) - imgWidth;
		hDiff = (this.hCur - borderSize * 2) - imgHeight;
		
		// Resize the outerImageContainer very sexy like
		reHeight = new fx.Height('outerImageContainer', { duration: resizeDuration });
		reHeight.custom(Element.getHeight('outerImageContainer'),imgHeight+(borderSize*2)); 
		reWidth = new fx.Width('outerImageContainer', { duration: resizeDuration, onComplete: function() { imageEffect.custom(0,1); }});
		reWidth.custom(Element.getWidth('outerImageContainer'),imgWidth+(borderSize*2));

		// if new and old image are same size and no scaling transition is necessary, 
		// do a quick pause to prevent image flicker.
		if((hDiff == 0) && (wDiff == 0)){
			if (navigator.appVersion.indexOf("MSIE")!=-1){ pause(250); } else { pause(100);} 
		}

		Element.setHeight('prevLink', imgHeight);
		Element.setHeight('nextLink', imgHeight);
		Element.setWidth( 'imageDataContainer', imgWidth + (borderSize * 2));
		Element.setWidth( 'hoverNav', imgWidth + (borderSize * 2));
		
		this.showImage();
	},
	
	//
	//	showImage()
	//	Display image and begin preloading neighbors.
	//
	showImage: function(){
		Element.hide('loading');
		myLightbox.updateDetails(); 
		this.preloadNeighborImages();
	},

	//
	//	updateDetails()
	//	Display caption, image number, and bottom nav.
	//
	updateDetails: function() {

		Element.show('caption');
		Element.setInnerHTML( 'caption', imageArray[activeImage][1]);
		
		// if image is part of set display 'Image x of x' 
		if(imageArray.length > 1){
			Element.show('numberDisplay');
			Element.setInnerHTML( 'numberDisplay', "Kadr " + eval(activeImage + 1) + " z " + imageArray.length);
		}

		myLightbox.updateNav();
	},
	//
	//	updateNav()
	//	Display appropriate previous and next hover navigation.
	//
	updateNav: function() {

		// if not first image in set, display prev image button
		if(activeImage != 0){
			Element.show('prevLink');
			document.getElementById('prevLink').onclick = function() {
				myLightbox.changeImage(activeImage - 1); return false;
			}
		}

		// if not last image in set, display next image button
		if(activeImage != (imageArray.length - 1)){
			Element.show('nextLink');
			document.getElementById('nextLink').onclick = function() {
				myLightbox.changeImage(activeImage + 1); return false;
			}
		}
		
		this.enableKeyboardNav();
	},

	//
	//	enableKeyboardNav()
	//
	enableKeyboardNav: function() {
		document.onkeydown = this.keyboardAction; 
	},

	//
	//	disableKeyboardNav()
	//
	disableKeyboardNav: function() {
		document.onkeydown = '';
	},

	//
	//	keyboardAction()
	//
	keyboardAction: function(e) {
		if (e == null) { // ie
			keycode = event.keyCode;
		} else { // mozilla
			keycode = e.which;
		}

		key = String.fromCharCode(keycode).toLowerCase();
		
		if((key == 'x') || (key == 'o') || (key == 'c')){	// close lightbox
			myLightbox.end();
		} else if(key == 'p'){	// display previous image
			if(activeImage != 0){
				myLightbox.disableKeyboardNav();
				myLightbox.changeImage(activeImage - 1);
			}
		} else if(key == 'n'){	// display next image
			if(activeImage != (imageArray.length - 1)){
				myLightbox.disableKeyboardNav();
				myLightbox.changeImage(activeImage + 1);
			}
		}
	},

	//
	//	preloadNeighborImages()
	//	Preload previous and next images.
	//
	preloadNeighborImages: function(){

		if((imageArray.length - 1) > activeImage){
			preloadNextImage = new Image();
			preloadNextImage.src = imageArray[activeImage + 1][0];
		}
		if(activeImage > 0){
			preloadPrevImage = new Image();
			preloadPrevImage.src = imageArray[activeImage - 1][0];
		}
	
	},

	//
	//	end()
	//
	end: function() {
		this.disableKeyboardNav();
		Element.hide('lightbox');
		imageEffect.toggle();
		overlayEffect.custom(0.8,0);
		showSelectBoxes();
	}
}

// -----------------------------------------------------------------------------------

//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}

// -----------------------------------------------------------------------------------

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

// -----------------------------------------------------------------------------------

//
// getKey(key)
// Gets keycode. If 'x' is pressed then it hides the lightbox.
//
function getKey(e){
	if (e == null) { // ie
		keycode = event.keyCode;
	} else { // mozilla
		keycode = e.which;
	}
	key = String.fromCharCode(keycode).toLowerCase();
	
	if(key == 'x'){
	}
}

// -----------------------------------------------------------------------------------

//
// listenKey()
//
function listenKey () {	document.onkeypress = getKey; }

// ---------------------------------------------------

function showSelectBoxes(){
	selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}
}

// ---------------------------------------------------

function hideSelectBoxes(){
	selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "hidden";
	}
}

// ---------------------------------------------------

//
// pause(numberMillis)
// Pauses code execution for specified time. Uses busy code, not good.
// Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
//
function pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}
// ---------------------------------------------------

function initLightbox() { myLightbox = new Lightbox(); }

//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////



window.onload = function(){
	adding_3_step_sliders();
	homepage_advanced_sliders();
	st();
	scroller();
	
	initWYSIWYG('l_pol_desc');
	initWYSIWYG('l_eng_desc');
	initWYSIWYG('l_deu_desc');
	initWYSIWYG('l_rus_desc');
	initWYSIWYG('l_pol_prices');
	initWYSIWYG('l_eng_prices');
	initWYSIWYG('l_deu_prices');
	initWYSIWYG('l_rus_prices');
	
	var h = document.createElement('span');
	h.id = 'btc';
	h.setAttribute('id', 'btc');
	h.style.position = 'absolute';
	document.getElementsByTagName('body')[0].appendChild(h);

	
	var elems = get_elements_by_class('ov');
	for(var i = 0; i < elems.length; ++i){
	   Prepare(elems[i], elems[i].getAttribute('title'));
	   elems[i].setAttribute('title', '');
	}
	
	externalLinks();
	initLightbox();
}
