(function(jQuery){
	// jQuery plugin for drag&drop
	var isMouseDown = false;
	var currentElement = null;
	var dropCallbacks = {};
	var dragCallbacks = {};
	var lastMouseY;
	var lastElemTop;
	var dragStatus = {};	
	$.getMousePosition = function(e){
		var posy = 0;
		if (!e) var e = window.event;
		if (e.pageX || e.pageY) {
			posy = e.pageY;
		}
		else if (e.clientX || e.clientY) {
			posy = e.clientY + document.body.scrollTop  + document.documentElement.scrollTop;
		}
		return { 'y': posy };
	};
	$.updatePosition = function(e) {
		var pos = $.getMousePosition(e);
		var spanY = (pos.y - lastMouseY);
		var posy = lastElemTop + spanY
		if(posy<0) posy=0;
		if(posy>($("#content").height()-47)) posy=$("#content").height()-47;
		$(currentElement).css("top",posy);
	};
	$(document).mousemove(function(e){
		if(isMouseDown && dragStatus[currentElement.id] == 'on'){
			$.updatePosition(e);
			if(dragCallbacks[currentElement.id] != undefined){
				dragCallbacks[currentElement.id](e, currentElement);
			}
			return false;
		}
	});
	$(document).mouseup(function(e){
		if(isMouseDown && dragStatus[currentElement.id] == 'on'){
			isMouseDown = false;
			if(dropCallbacks[currentElement.id] != undefined){
				dropCallbacks[currentElement.id](e, currentElement);
			}
			return false;
		}
	});
	$.fn.ondrag = function(callback){
		return this.each(function(){
			dragCallbacks[this.id] = callback;
		});
	};
	$.fn.drag = function(allowBubbling){
		return this.each(function(){
			if(undefined == this.id || !this.id.length) this.id = "drag"+(new Date().getTime());
			dragStatus[this.id] = "on";
			$(this).css("cursor", "s-resize");
			$(this).mousedown(function(e){
				$(this).css("position", "absolute");
				$(this).css("z-index", "10000");
				isMouseDown    = true;
				currentElement = this;
				var pos    = $.getMousePosition(e);
				lastMouseY = pos.y;
				lastElemTop  = this.offsetTop;
				$.updatePosition(e);
				return allowBubbling ? true : false;
			});
		});
	};
    // jQuery extension for making clip css property animations
    jQuery.fx.step.clip=function(fx){if(fx.state==0){var aRE=/rect\(([0-9]{1,})(px)[,]? ([0-9]{1,})(px)[,]? ([0-9]{1,})(px)[,]? ([0-9]{1,})(px)\)/;fx.start=aRE.exec(fx.elem.style.clip.replace(/[, ]+/g,' '));fx.end=aRE.exec(fx.end.replace(/,/g,''));}var sarr=new Array(),earr=new Array(),spos=fx.start.length,epos=fx.end.length,emOffset=fx.start[ss+1]=='em' ? (parseInt(jQuery(fx.elem).css('fontSize'))*1.333*parseInt(fx.start[ss])) : 1;for(var ss=1;ss<spos;ss+=2){sarr.push(parseInt(emOffset*fx.start[ss]));}for(var es=1;es<epos;es+=2){earr.push(parseInt(emOffset*fx.end[es]));}fx.elem.style.clip='rect('+parseInt((fx.pos*(earr[0]-sarr[0]))+sarr[0])+'px '+parseInt((fx.pos*(earr[1]-sarr[1]))+sarr[1])+'px '+parseInt((fx.pos*(earr[2]-sarr[2]))+sarr[2])+'px '+parseInt((fx.pos*(earr[3]-sarr[3]))+sarr[3])+'px)';};
    // jQuery extension for making fancy easing
    jQuery.extend( jQuery.easing,
	{
		easeInQuart: function (x, t, b, c, d) {
			return c*(t/=d)*t*t*t + b;
		},
		easeOutQuart: function (x, t, b, c, d) {
			return -c * ((t=t/d-1)*t*t*t - 1) + b;
		},
		easeInOutQuart: function (x, t, b, c, d) {
			if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
			return -c/2 * ((t-=2)*t*t*t - 2) + b;
		},
		easeInQuint: function (x, t, b, c, d) {
			return c*(t/=d)*t*t*t*t + b;
		},
		easeOutQuint: function (x, t, b, c, d) {
			return c*((t=t/d-1)*t*t*t*t + 1) + b;
		},
		easeInOutQuint: function (x, 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;
		},
		easeInElastic: function (x, t, b, c, d) {
			var s=1.70158;var p=0;var a=c;
			if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
			if (a < Math.abs(c)) { a=c; var s=p/4; }
			else var s = p/(2*Math.PI) * Math.asin (c/a);
			return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		},
		easeOutElastic: function (x, t, b, c, d) {
			var s=1.70158;var p=0;var a=c;
			if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
			if (a < Math.abs(c)) { a=c; var s=p/4; }
			else var s = p/(2*Math.PI) * Math.asin (c/a);
			return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
		},
		easeInOutElastic: function (x, t, b, c, d) {
			var s=1.70158;var p=0;var a=c;
			if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
			if (a < Math.abs(c)) { a=c; var s=p/4; }
			else var s = p/(2*Math.PI) * Math.asin (c/a);
			if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
			return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
		},
		easeInBack: function (x, t, b, c, d, s) {
			if (s == undefined) s = 1.70158;
			return c*(t/=d)*t*((s+1)*t - s) + b;
		},
		easeOutBack: function (x, t, b, c, d, s) {
			if (s == undefined) s = 1.70158;
			return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
		},
		easeInOutBack: function (x, t, b, c, d, s) {
			if (s == undefined) s = 1.70158; 
			if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
			return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
		}
	});
    // jQuery modification for setting visibility:hidden for zero-opacity elements
    jQuery.fx.step.opacity=function(fx){
        jQuery.attr(fx.elem.style,'opacity',fx.now);
		if(jQuery.browser.msie&&fx.now==1) jQuery.attr(fx.elem.style,'filter','');
        if(fx.now>0) jQuery.attr(fx.elem.style,'visibility','visible');
        else jQuery.attr(fx.elem.style,'visibility','hidden');
    };
})(jQuery);
// functions and objects using native JS - blazing fast but less compatible implementation
function id(id){
    return document.getElementById(id);
}
function tag(tag,parent){
    if(parent==null) parent=document;
    return parent.getElementsByTagName(tag);
}
function attr(el,attr){
    for(prop in attr){
        el.setAttribute(prop,attr[prop]);
    }
    return el;
}
function load(srcs,callback,calleach){
    if(srcs!=null&&srcs.length>0){
        var j=0;
        var imgs=[];
        for(var i=0;i<srcs.length;i++){
            imgs[i]=new Image();
            imgs[i].onload=function(){
                if(++j==srcs.length&&callback!=null) callback();
                if(calleach!=null) calleach(j,srcs.length);
            };
            imgs[i].src='layout/images/'+srcs[i];
        }
    } else callback();
}
// site variables, dom shortcuts and other
_lang = {'pl':['Gry','Teatr','Kabaret','Media','Filmy','Bajki','Reklamy','O nas','Cel','Źródła','Pomogli nam'],'en':['Games','Theater','Cabaret','Media','Movies','Animations','Commercials','About','Purpose','Sources','Helped us']};
_fx = {ps:[[0,-360],[0,-180],[140,60],[280,-180],[280,-360]],m:[2,3,4,0,1],a:0,is_a:false}
_query = ['pl','site','default'];
_dom = [];
_tabs = [];
// system core functions for retriving data, handling events and managing history using jQuery
function _history(){
    var query,i=window.location.href.indexOf('?q=')+3;
    if(i<3) i=window.location.href.indexOf('#')+1;
    if(i>1) query=window.location.href.substring(i);
    if(query!=null&&query!=_query.join('/')){
        window.location='index.php'+'#'+query.split('&',1);
        _render(query);
        if(id(_query[1])){
			$(attr(id(_query[1]),{'class':'active'}).firstChild).css({opacity:1,clip:'rect(0px, 128px, 67px, 0px)'});
		}
    }
}
function _render(query){
    last=_query;
    _query=query.split('/');
    window.location.hash='#'+_query.join('/');
    _dom[2].fadeTo(400,0);
	_dom[6].fadeTo(600,0);
    _dom[7].fadeTo(600,0);
    _dom[8].fadeTo(600,0,function(){
        _dom[2].animate({height:Math.max($(window).height()-345,315)},600,'easeInOutQuart',function(){
            $.getJSON('system/'+_query[0]+'.'+_query[1]+'.'+_query[2]+'.json?cache='+(new Date).getTime(),function(site,status){
                // insert subsite content
                document.title=site.title;
                attr(document.body,{'class':_query[1]});
				_dom[6][0].innerHTML=site.additions[0];
                _dom[7][0].innerHTML=site.foreword;
                _dom[9][0].innerHTML=site.content[0];
                _tabs = [site.content,site.additions];
                // fade polygons if necessary
                if(site.polygon!=_fx.a) _dom[0].children().fadeTo(300,0,function(){$(this).remove()});
                new load(site.load,function(){
                    // rotate polygons
                    if(site.polygon!=_fx.a){
                        _dom[0][site.polygon].appendChild($(attr(new Image(),{src:'layout/images/poly-img-'+site.polygon+'.png'})).css('opacity',0).fadeTo(400,1)[0]);
                        for(n=site.polygon-_fx.a,dif=(n<0) ? 1 : -1,n=Math.abs(n),j=0;j<n;j++){
                            _dom[0].each(function(i){
                                _fx.m[i]+=dif;
                                _fx.m[i]=(_fx.m[i]>4) ? 0 : (_fx.m[i]<0) ? 4 : _fx.m[i];
                                $(this).animate({top:_fx.ps[_fx.m[i]][0],left:_fx.ps[_fx.m[i]][1]},300,'linear');
                            });
                        }
                        _fx.a=site.polygon;
                    }
					
					//additional code specific for sites
                    // insert tabs
					attr(_dom[2][0],{'class':_query[2]+' '+_query[0]}).innerHTML='';
					for(var i in site.tabs){
						tab=site.tabs[i].split('|');
						_dom[2][0].innerHTML += '<a'+(tab[3]!=null ? ' ref="'+tab[3]+'"' : '')+' style="background-position:-'+tab[1]+'px -15px;" href="?q='+_query.join('/',3)+'/'+(++i).toString()+'"><span style="background-position:-'+tab[1]+'px 0px;width:'+tab[2]+'px;"> </span></a>';
					}
					// make tabs events
					$(_dom[2][0].childNodes).each(function(i){
						$(this).hover(function(){
							$(this.firstChild).fadeTo(200,1)
						},function(){
							if(!$(this).is('.active')) $(this.firstChild).fadeTo(200,0)
						}).click(function(){
							$(this).addClass('active').siblings().removeClass('active').children('span').fadeTo(100,0);
							_dom[6].fadeTo(400,0);
							_dom[8].fadeTo(400,0,function(){
								_dom[6][0].innerHTML=_tabs[1][i]
								_dom[9][0].innerHTML=_tabs[0][i];
								$(window).resize();
								// make galleries
								$("#photo").css({opacity:0,display:'block'});
								$("#close").click(function(){
									$("#close").fadeOut(100);
									$("#photo").animate({opacity:0,height:0,width:0,marginTop:0,marginLeft:0},300,function(){$("#container").empty()});
								})
								$("#gallery a").css({opacity:0,left:'-200px'}).click(function(){
									descr=$(this).attr('ref');
									$("body").add("#gallery a").css('cursor','wait');
									$(new Image()).load(function(){
										h=this.height,w=this.width;
										$("#container").html(this).append('<div>'+descr+'</div>');
										$("#photo").animate({opacity:1,height:h,width:w,marginTop:-h/2,marginLeft:-w/2},300);
										$("#close").fadeIn(100);
										$("body").add("#gallery a").css('cursor','default');
									})[0].src=this.href;
									return false;
								}).parent().hover(function(){$(this.firstChild).animate({left:20,opacity:1},200,'easeOutElastic')},function(){$(this.firstChild).animate({left:0,opacity:0.7},200,'easeOutElastic')});
								_dom[6].fadeTo(400,1);
								_dom[8].fadeTo(400,1);
								$("#gallery a").each(function(i){
									$(this).animate({top:0},50*i).animate({opacity:0.7,left:0},300,'easeOutBack');
								});
							});
							$(new Image()).load(function(){
								_dom[0][_fx.a].appendChild($(this).css('opacity',0)[0]);
								$(this).animate({opacity:1},300,'linear');
								$(_dom[0][_fx.a].firstChild).animate({opacity:0},300,'linear',function(){$(this).remove()});
							})[0].src='layout/images/'+(this.getAttribute('ref')==null ? 'poly-img-'+_fx.a+'.png' : this.getAttribute('ref'));
							return false;
						});
					});
					// make image map
					bub=$(id('bubble'));
					bub.hover(function(){
						clearTimeout(_fx.bub)
					},function(){
						_fx.bub=setTimeout(function(){
						   bub.fadeOut(200)
						},300)
					});
					$("#map area").hover(function(){
						clearTimeout(_fx.bub);
						data=this.alt.replace(/\[a=([^\[]+)\]([^\[]+)\[a\]/g,"<a href=\"$1\">$2</a>").split('|',3);
						pos=this.coords.split(',',2);
						bub.animate({left:(pos[0]>470 ? pos[0]-145 : pos[0]),top:(pos[1]>157 ? pos[1]-125 : pos[1])},200);
						attr(bub[0],{'class':data[0]}).childNodes[1].innerHTML='<span>'+data[1]+'</span>'+data[2];
						bub.fadeIn(200);
					},function(){
						_fx.bub=setTimeout(function(){
							bub.fadeOut(200)
						},300)
					}).click(function(){
						return false
					});
					// set the shit for language
                    if(last[0]!=_query[0]){
                        _dom[3].each(function(i){this.src='layout/images/menu-'+_query[0]+'-'+(4-i)+'-h.png'});
                        attr(_dom[1][0],{'class':_query[0]});
                    }
                    // rollup the shit
					_dom[2].animate({height:15},600,'easeInOutQuart',function(){
						$(_dom[2][0].childNodes).eq(0).click()
						$(window).resize();
						_dom[6].fadeTo(600,1);
                        _dom[7].fadeTo(600,1);
                        _dom[8].fadeTo(600,1);
						_dom[2].fadeTo(400,1);
                    });
                });
				// links (refreshing href's values and descriptions)
                _dom[5].each(function(){this.href='?q='+this.id+'/'+_query[1]+'/'+_query[2]});
                _dom[4].each(function(i){this.setAttribute('href','?q='+_query[0]+'/'+this.parentNode.id+'/'+this.id);this.innerHTML=_lang[_query[0]][i];});
				_dom[10][0].setAttribute('href','?q='+_query[0]+'/site/default');
            });
        });
    },600);
}

// DOM ready event
$(document).ready(function(){
    if(typeof(window['unsupported']) == "undefined"){
		// set preloader
		document.body.innerHTML += '<div id="preloader"><div class="wrap"><span id="percent">%</span><div id="bar"><div></div></div></div></div>';
		new load([
			'bkg-1.jpg','bkg-2.jpg','polygon.png',
			'bkg-camera.png','bkg-camera-up.png',
			'flag-en.png','flag-pl.png','flag-menu.png',
			'poly-img-0.png','bkg-grad-0.png',
			'poly-img-1.png','bkg-grad-1.png',
			'poly-img-2.png','bkg-grad-2.png',
			'poly-img-3.png','bkg-grad-3.png',
			'poly-img-4.png','bkg-grad-4.png',
			'menu-pl-1.png','menu-pl-1-h.png',
			'menu-pl-2.png','menu-pl-2-h.png',
			'menu-pl-3.png','menu-pl-3-h.png',
			'menu-pl-4.png','menu-pl-4-h.png',
			'motto-pl.png','logo-pl.png',
			'menu-en-1.png','menu-en-1-h.png',
			'menu-en-2.png','menu-en-2-h.png',
			'menu-en-3.png','menu-en-3-h.png',
			'menu-en-4.png','menu-en-4-h.png',
			'motto-en.png','logo-en.png'
		],function(){
			setTimeout(function(){$(id('preloader')).fadeTo(200,0,function(){$(this).remove()})},200);
			// history module init
			setInterval(_history,600);
		},function(c,n){
			id('bar').firstChild.style['width'] = parseInt(c/n*312).toString()+'px';
			id('percent').innerHTML = parseInt(c/n*100).toString()+'%';
		});
		// DOM helper object
		_dom = [
			$(tag('div',id('polygons'))), //0
			$(id('header')), //1
			$(id('tabs')), //2
			$(tag('img',id('menu'))), //3
			$(tag('a',id('menu'))), //4
			$(tag('a',id('flags'))), //5
			$(id('additions')), //6
			$(id('foreword')), //7
			$(id('content')), //8
			$(id('wrapper')), //9
			$(id('motto')) //10
		];
		// disable css pseudo-animations
		$('body').removeClass('animate');
		// global "live" event listeners
		$("a[href^='http://']").live('click',function(){
			window.open(this.getAttribute('href'));
			return false;
		});
		// click events
		$("#header a").click(function(){
			_render(this.getAttribute('href').substring(3));
			return false;
		});
		// language flags
		_dom[5].mouseenter(function(){$(this.firstChild).fadeTo(400,1)}).mouseleave(function(){$(this.firstChild).fadeTo(400,0)}).each(function(){$(this.firstChild).css('opacity',0)});
		// menu items
		$(id('menu').childNodes).mouseenter(function(){
			$(this).css('overflow','visible').children('a').each(function(i,el){
				clearTimeout($(this).data('delay'));
				$(this).css({opacity:0,left:'-40px'}).data('delay',setTimeout(function(){$(el).animate({left:0,opacity:1},500,'easeInOutQuint')},(1+i)*100));
			});
			$(this.firstChild).stop().animate({opacity:1,clip:'rect(0px, 128px, 67px, 0px)'},300);
		}).mouseleave(function(){
			$(this).children('a').each(function(i,el){
				clearTimeout($(this).data('delay'));
				$(this).data('delay',setTimeout(function(){$(el).animate({left:40,opacity:0},500,'easeInOutQuint')},(3-i)*100));
			});
			if(!$(this).is('.active')) $(this.firstChild).stop().animate({opacity:0,clip:'rect(22px, 120px, 54px, 8px)'},300);
		}).children('img').css({opacity:0,clip:'rect(22px, 120px, 54px, 8px)'});
		// submenu items
		_dom[4].hover(function(){$(this).animate({left:7},200)},function(){$(this).animate({left:0},200)}).click(function(event){
			$(this.parentNode).addClass('active').siblings().removeClass('active').children('img').animate({opacity:0,clip:'rect(22px, 120px, 54px, 8px)'},300);
			if(!jQuery.browser.msie) $(this.parentNode).trigger('mouseleave')
		});
		// motto click
		_dom[10].click(function(){_dom[3].fadeTo(200,0)});
		// scrollers
		_dom[8].css('overflow','hidden');
		_dom[9].css('position','relative');
		_dom[11]=jQuery('<div id="scr"></div>');
		_dom[11].drag().ondrag(function(e){
			oy = (375-e.pageY)/_dom[8].height();
			if(oy<-1) oy=-1;
			if(oy>0) oy=0;
			d = _dom[9].height()>_dom[8].height() ? _dom[9].height()-_dom[8].height()+20 : 0;
			_dom[9].css('top',oy*d);
		});
		_dom[8][0].appendChild(_dom[11][0]);
		$(window).resize(function(){
			if(_dom[8].height()<_dom[9].height()) _dom[11].css({display:'block',top:'0px'});
			else _dom[11].css('display','none');
			_dom[9].css('top','0px');
		});
		// ajax error handling
		$.ajaxSetup({error:function(){
			_dom[7].html('<p>'+(_query[0]=='pl' ? 'Wystąpił nieoczekiwany błąd. Prosimy spróbować ponownie.' : 'An unexpected error occured. Please try later.')+'</p>');
			_dom[8].animate({marginTop:0},400,function(){
				_dom[8].css('height','auto');
				_dom[7].fadeTo(600,1);
				_dom[9].fadeTo(600,1);
			});
		}});
	}
});