// Cross browser detect internet browser name and version
var Browser = {
	userAgent : navigator.userAgent,
	appName : navigator.appName,

	IE : !!(window.attachEvent && !window.opera),
	OP : !!window.opera,
	FF : navigator.userAgent.indexOf("Gecko") > -1 && navigator.userAgent.indexOf("KHTML") == (-1) && navigator.userAgent.indexOf("Firefox") > 0,
	NN : navigator.appName == "Netscape",
	SF : navigator.userAgent.indexOf("Safari") > 0,
	Gecko : navigator.userAgent.indexOf("Gecko") > -1 && navigator.userAgent.indexOf("KHTML") == (-1),

	// Get name
	getBrowserName : function() {
		if(this.IE) { return "IE"; }
		else if(this.OP) { return "OP"; }
		else if(this.FF) { return "FF"; }
		else if(this.SF) { return "SF"; }
		else if(this.Gecko) { return "GK"; }
		return false;
	},
	// IE version
	getIEVersion : function() {
		if(this.IE) {
			var IEVer = this.userAgent.substring(this.userAgent.indexOf("MSIE ", 0));
			IEVer = IEVer.substring(5, IEVer.indexOf(";"));
			return parseFloat(IEVer);
		} else {
			return false;
		}
	}
};

// get Window height
function getWindowHeight() {
	if (self.innerHeight)
	return self.innerHeight; // browsers
	else if (document.documentElement && document.documentElement.clientHeight)
	return document.documentElement.clientHeight;
	else if (document.body)
	return document.body.clientHeight; // other IE
	return false;
}

// get Body height
function getBodyHeight() {
	if (window.innerHeight && window.scrollMaxY)
	return window.innerHeight + window.scrollMaxY;
	else if (document.body.scrollHeight > document.body.offsetHeight)
	return document.body.scrollHeight;
	else
	return document.body.offsetHeight;
	return false;
}

// get Body scroll
function getBodyScroll() {
	if (self.pageYOffset)
	return self.pageYOffset; // browsers
	else if (document.documentElement && document.documentElement.scrollTop)
	return document.documentElement.scrollTop; // strict mode IE6
	else if (document.body)
	return document.body.scrollTop; // other IE
	return false;
}

// fade in-out with opacity

// image fading
var d=document,imgs=new Array(),zInterval=null,current=0,pause=false;
function images_fade(){
	if(!d.getElementById||!d.createElement||!d.getElementById('imageContainer'))return;
	imgs=d.getElementById('imageContainer').getElementsByTagName('img');
	for(i=1;i<imgs.length;i++)imgs[i].xOpacity=0;
		imgs[0].style.display="block";
		imgs[0].xOpacity=.99;
		setTimeout(so_xfade,4500);
}

// Gets the computed style of any object.
function getStyle(el,styleProp){
	var x = document.getElementById(el);
	if (x.currentStyle)
	var y = x.currentStyle[styleProp];
	else if (window.getComputedStyle)
	var y = document.defaultView.getComputedStyle(x,null).getPropertyValue(styleProp);
	return y;
}

// Implement setAttribute (especially with style) for IE
function rzCC(s){
	// retrieving-css-styles-via-javascript/
	for(var exp=/-([a-z])/;
	exp.test(s);
	s=s.replace(exp,RegExp.$1.toUpperCase()));
	return s;
}

function _setStyle(element, declaration){
	if (declaration.charAt(declaration.length-1)==';')
	declaration = declaration.slice(0, -1);
	var k,v;
	var splitted = declaration.split(';');
	for (var i=0, len=splitted.length; i<len; i++){
		k = rzCC(splitted[i].split(':')[0]);
		v = splitted[i].split(':')[1];
		eval("element.style."+k+"='"+v+"'");
	}
}

// Fading gallery on home page
function so_xfade(){
	var cOpacity;
	var nIndex;
	var nOpacity;

	cOpacity=imgs[current].xOpacity;
	nIndex=imgs[current+1]?current+1:0;
	nOpacity=imgs[nIndex].xOpacity;
	cOpacity-=.01;
	nOpacity+=.01;
	imgs[nIndex].style.display="block";
	imgs[current].xOpacity=cOpacity;
	imgs[nIndex].xOpacity=nOpacity;
	setOpacity(imgs[current]);
	setOpacity(imgs[nIndex]);
		if(cOpacity<=0){imgs[current].style.display="none";
		current=nIndex;
		setTimeout(so_xfade,4500);
		}
		else{
			setTimeout(so_xfade,25);
		}
function setOpacity(obj){
	if(obj.xOpacity>.99){
		obj.xOpacity=.99;
		return;
	}
	// IE/Win
	obj.style.filter="alpha(opacity="+(obj.xOpacity*100)+")";
	// Safari<1.2, Konqueror
	obj.style.KHTMLOpacity = obj.xOpacity;
	// Older Mozilla and Firefox
	obj.style.MozOpacity=obj.xOpacity;
	// Safari 1.2, newer Firefox and Mozilla, CSS3
	obj.style.opacity=obj.xOpacity;
	}
}

// Clear inputs on focus including double click
function init(){
	var inp=document.getElementsByTagName('input');
	for(var i=0;i<inp.length;i++){
		if(inp[i].type=='text'){
		inp[i].setAttribute('rel',inp[i].defaultValue)
		inp[i].onfocus=function(){
			if(this.value==this.getAttribute('rel')){this.value='';}
				else{return false;}
			}
		inp[i].onblur=function(){
			if(this.value==''){this.value=this.getAttribute('rel');}
				else{
					return false;
					}
		}
		inp[i].ondblclick=function(){this.value=this.getAttribute('rel')}
}}}
if(document.childNodes){window.onload=init}

// add and remove event
function addEvent( obj, type, fn )
{
	if (obj.addEventListener)
		obj.addEventListener( type, fn, false );
	else if (obj.attachEvent)
	{
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	}
}

function removeEvent( obj, type, fn )
{
	if (obj.removeEventListener)
		obj.removeEventListener( type, fn, false );
	else if (obj.detachEvent)
	{
		obj.detachEvent( "on"+type, obj[type+fn] );
		obj[type+fn] = null;
		obj["e"+type+fn] = null;
	}
}

// text zoom
function textSize(size)
{
	var theContainer = document.getElementById("main");
	var increment = 0.1
	var currentSize = parseFloat(document.getElementById("main").style.fontSize);

	if (!currentSize)
	{
		currentSize = 1;
	}

	if (size == "smaller")
	{
		theContainer.style.fontSize = (currentSize - increment) + "em";
	}
	else
	{
		theContainer.style.fontSize = (currentSize + increment) + "em";
	}

	return true;
}

// apple to text-increase and text-decrease
function textplus() {
	tp = document.getElementById('text-increase');
	if(!tp) return;
	tp.onclick = function() {
		textSize('bigger');
		return false;
	};
}
function textminus() {
	tm = document.getElementById('text-decrease');
	if(!tm) return;
	tm.onclick = function() {
		textSize('smaller');
		return false;
	};
}

/*
JSTarget function by Roger Johansson, www.456bereastreet.com
*/
var JSTarget = {
	init: function(att,val,warning) {
		if(!d.getElementById||!d.createElement) return;
		if (document.getElementById && document.createElement && document.appendChild) {
			var strAtt = ((typeof att == 'undefined') || (att == null)) ? 'class' : att;
			var strVal = ((typeof val == 'undefined') || (val == null)) ? 'non-html' : val;
			var strWarning = ((typeof warning == 'undefined') || (warning == null)) ? ' (opens in a new window)' : warning;
			var oWarning;
			var arrLinks = document.getElementsByTagName('a');
			var oLink;
			var oRegExp = new RegExp("(^|\\s)" + strVal + "(\\s|$)");
			for (var i = 0; i < arrLinks.length; i++) {
				oLink = arrLinks[i];
				if ((strAtt == 'class') && (oRegExp.test(oLink.className)) || (oRegExp.test(oLink.getAttribute(strAtt)))) {
					oWarning = document.createElement("em");
					oWarning.appendChild(document.createTextNode(strWarning));
					oLink.appendChild(oWarning);
					oLink.onclick = JSTarget.openWin;
				}
			}
			oWarning = null;
		}
	},
	openWin: function(e) {
		var event = (!e) ? window.event : e;
		if (event.shiftKey || event.altKey || event.ctrlKey || event.metaKey) return true;
		else {
		    var oWin = window.open(this.getAttribute('href'), '_blank');
			if (oWin) {
				if (oWin.focus) oWin.focus();
				return false;
			}
			oWin = null;
			return true;
		}
	}
};

// Photo gallery
// use class ipopup for links
// split in one category by name from rel

// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.org
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;
}

function hideImagePopup(invoker) {
	// remove layer & layer childs
	var layer = document.getElementById('ipopup');
	while (layer.firstChild) {
		layer.removeChild(layer.firstChild);
	}
	layer.parentNode.removeChild(layer);
	// remove mask
	var mask = document.getElementById('ipopup-mask');
	mask.parentNode.removeChild(mask);
	// show selects
	var selects = document.getElementsByTagName("select");
	if (selects) {
		for (var i = 0; i < selects.length; i++){
			selects[i].style.visibility = 'visible';
		}
	}

	// focus on invoker link
	if (invoker){
		invoker.focus();
	}
	return false;
}

function calculateHeight(windowHeight, bodyHeight) {
	if (bodyHeight > windowHeight){
		return bodyHeight + 'px';
	}
	else{
		return windowHeight + 'px';
	}
	return false;
}

function showImagePopup(invoker) {
	if(!document.getElementById || !document.createTextNode){ return false; }

	// returns current invoker from gallery array
	function getCurrentFromGallery(invoker) {
		var current = 0;
		for (var i = 0; i < gallery[rel].length; i++) {
			if (gallery[rel][i] == invoker){
				current = i;
			}
		}
		return current;
	}

	// checking if any ipopup is allready opened
	if (document.getElementById('ipopup')) {
		hideImagePopup();
	}

	// invoker properties
	var imageHref = invoker.getAttribute('href');
	var rel = invoker.getAttribute('rel');

	// calculate height
	// get som einformation about page and window size in array: pageWidth,pageHeight,windowWidth,windowHeight
	var wh = getPageSize();

	var windowHeight = getWindowHeight();
	var bodyHeight = getBodyHeight();
	var bodyScroll = getBodyScroll();
	var heightCalculated = calculateHeight(windowHeight, bodyHeight);

	// hide selects (IE6 bug)
	var isIE = this.Browser.getIEVersion();
	if(isIE == 6){
		var selects = document.getElementsByTagName("select");
		for (var i = 0; i < selects.length; i++){
			selects[i].style.visibility = 'hidden';
		}
	}

	// create mask & layer
	var mask = document.createElement('div');
	mask.setAttribute('id','ipopup-mask');
	mask.style.height = heightCalculated;
	document.body.appendChild(mask);
	var layer = document.createElement('div'); // redundant layer (solution for IE6 DXImageTransform+links bug)
	layer.setAttribute('id','ipopup');
	layer.style.height = heightCalculated;
	var loaderImageOffset = 60; // offset for loader background image (layer background)

	var offsetTop = Math.ceil(windowHeight / 2) - loaderImageOffset + bodyScroll;
	layer.style.backgroundPosition = '50% ' + offsetTop + 'px';
	document.body.appendChild(layer);

	// main image preloader
	var imagePreload = new Image();
	imagePreload.onload = function() {

		// create container
		var container = document.createElement('div');
		container.setAttribute('id', 'ipopup-container');
		layer.appendChild(container);

		// create main photo
		var image = document.createElement('img');
		image.setAttribute('id', 'ipopup-image');
		image.setAttribute('src', imageHref);
		image.setAttribute('alt', '');
		image.onclick = function() {
			return hideImagePopup(invoker);
		};

		// Fit image to window size
		var ratio = Math.min(wh[2]/(imagePreload.width),wh[3]/(imagePreload.height));
		if(ratio < 1){
			var w = (Math.round(imagePreload.width*ratio)-40);
			var h = (Math.round(imagePreload.height*ratio)-40);

			// set new size for image
			image.width = w;
			image.height = h;

			// set new size for image container
			var nwidth = 'width:'+w+'px';

			// set style attribute for non-IE browser
			if(isIE === false){
				container.setAttribute('style', nwidth);
			}
			// only for IE version; we can not use above code, because IE don't understand it
			else{
				_setStyle(container, nwidth);
			}
		}
		else{
			// set style attribute for non-IE browser
			if(isIE === false){
				container.setAttribute('style', 'width:'+imagePreload.width+'px');
			}
			// only for IE version; we can not use above code, because IE don't understand it
			else{
				_setStyle(container, 'width:'+imagePreload.width+'px');
			}
		}

		// make sure that container is not bigger then window
		// vertical centering container image - calculate offset
		var offsetTop;
		var margintop;

		offsetTop = (Math.ceil((windowHeight - image.height) / 2))-10;
		//alert(windowHeight+' '+image.height+' '+offsetTop);
		if (offsetTop < 0){
			offsetTop = 0;
		}
		margintop = bodyScroll + offsetTop + 'px';
		container.style.marginTop = margintop;

		// show main image
		container.appendChild(image);

		// Get padding of image container, if set
		var padding = getStyle('ipopup-container','padding');
		//alert(padding);

		// create close button
		var close = document.createElement('a');
		close.setAttribute('id', 'ipopup-close');
		close.setAttribute('href', '#');
		close.onclick = function() {
			return hideImagePopup(invoker);
		};
		var txt = document.createTextNode('Zamknij');
		close.appendChild(txt);
		container.appendChild(close);
		close.focus();
		if (rel) {
			// create next/prev buttons for gallery
			var current = getCurrentFromGallery(invoker);
			if (current > 0) {
				var prev = document.createElement('a');
				prev.setAttribute('id', 'ipopup-prev');
				prev.setAttribute('href', '#');
				prev.onclick = function() {
					return showImagePopup(gallery[rel][current-1]);
				};
				var txtprev = document.createTextNode('← Poprzedni');
				prev.appendChild(txtprev);
				container.appendChild(prev);
			}
			if (current < (gallery[rel].length - 1)) {
				var next = document.createElement('a');
				next.setAttribute('id', 'ipopup-next');
				next.setAttribute('href', '#');
				next.onclick = function() {
					return showImagePopup(gallery[rel][current+1]);
				};
				var txtnext = document.createTextNode('Następny →');
				next.appendChild(txtnext);
				container.appendChild(next);
			}
		}
		// calculate mask height - again!
		windowHeight = getWindowHeight();	bodyHeight = getBodyHeight();	bodyScroll = getBodyScroll();
		heightCalculated = calculateHeight(windowHeight, bodyHeight);
		mask.style.height = heightCalculated;

	};
	imagePreload.src = imageHref;

	return false;
}

var gallery = [];
function initImagePopup(nextText,prevText,closeText) {
	var invokers = document.getElementsByTagName("a");
	var count = 0, countRels = 0;
	var rels = [];

	/* checking rel attributes for gallery array */
	function checkRels(rel, rels) {
		var exists = false;
		for (var i = 0; i < rels.length; i++) {
			if (rel == rels[i]){
				exists = true;
			}
		}
		return exists;
	}

	/* get all anchors with speciefied class name */
	for (var i = 0; i < invokers.length; i++) {
		if (invokers[i].className.indexOf("ipopup") != -1) {
			var rel = invokers[i].getAttribute('rel');
			if (rel) {
				// creating two-dimensional gallery array
				if (!checkRels(rel, rels)) {
					gallery[rel] = [];
					rels[countRels] = rel;
					countRels++;
					count = 0;
				}
				gallery[rel][count] = invokers[i];
				count++;
			}
			invokers[i].onclick = function() {
				return showImagePopup(this);
			};
		}
	}

}

addEvent(window, 'load', function(){
	textplus();
	textminus();
	images_fade();
	JSTarget.init("rel","external"," (nowe okno)"+String.fromCharCode(8599));
	initImagePopup(); // make nice gallery for images
});

