// DRY!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! EPIC FAIL!
var language = null;
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); };
function stripslashes (str) {
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Ates Goral (http://magnetiq.com)
    // +      fixed by: Mick@el
    // +   improved by: marrtins
    // +   bugfixed by: Onno Marsman
    // +   improved by: rezna
    // +   input by: Rick Waldron
    // +   reimplemented by: Brett Zamir (http://brett-zamir.me)
    // +   input by: Brant Messenger (http://www.brantmessenger.com/)
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: stripslashes('Kevin\'s code');
    // *     returns 1: "Kevin's code"
    // *     example 2: stripslashes('Kevin\\\'s code');
    // *     returns 2: "Kevin\'s code"
    return (str+'').replace(/\\(.?)/g, function (s, n1) {
        switch (n1) {
            case '\\':
                return '\\';
            case '0':
                return '\u0000';
            case '':
                return '';
            default:
                return n1;
        }
    });
}
// developer UA-15513598-1
// production UA-7542753-2

function defaults(element) {
    $(element).focus(function() {
        val = this.value;
        def = this.getAttribute('default');
        if (val == def) {
            this.value = '';
        }
    });
    $(element).blur(function() {
        val = this.value;
        def = this.getAttribute('default');
        if (val == def | val == '') {
            this.value = def;
        }
    });
    $(element).parents('form').submit(function() {
        $(element).focus();
    });
}

var cookie = {
    write: function(name, value, days) {
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            var expires = "; expires="+date.toGMTString();
        } else {
            var expires = "";
        }
        document.cookie = name+"="+value+expires+"; path=/";        
    },
    
    read: function(name) {
        var real = name + "=";
        var ca = document.cookie.split(';');
        for (var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(real) == 0) return c.substring(real.length,c.length);
        }
        return '';
    },
    
    erase: function(name) {
        cookie.write(name, '', -1);
    }
};


jQuery.effects||(function(n){n.effects={};n.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","color","outlineColor"],function(a,b){n.fx.step[b]=function(c){if(!c.colorInit){c.start=k(c.elem,b);c.end=l(c.end);c.colorInit=true;}c.elem.style[b]="rgb("+Math.max(Math.min(parseInt((c.pos*(c.end[0]-c.start[0]))+c.start[0],10),255),0)+","+Math.max(Math.min(parseInt((c.pos*(c.end[1]-c.start[1]))+c.start[1],10),255),0)+","+Math.max(Math.min(parseInt((c.pos*(c.end[2]-c.start[2]))+c.start[2],10),255),0)+")";};});function l(a){var b;if(a&&a.constructor==Array&&a.length==3){return a;}if(b=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(a)){return[parseInt(b[1],10),parseInt(b[2],10),parseInt(b[3],10)];}if(b=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(a)){return[parseFloat(b[1])*2.55,parseFloat(b[2])*2.55,parseFloat(b[3])*2.55];}if(b=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(a)){return[parseInt(b[1],16),parseInt(b[2],16),parseInt(b[3],16)];}if(b=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(a)){return[parseInt(b[1]+b[1],16),parseInt(b[2]+b[2],16),parseInt(b[3]+b[3],16)];}if(b=/rgba\(0, 0, 0, 0\)/.exec(a)){return t.transparent;}return t[n.trim(a).toLowerCase()];}function k(a,c){var b;do{b=n.curCSS(a,c);if(b!=""&&b!="transparent"||n.nodeName(a,"body")){break;}c="backgroundColor";}while(a=a.parentNode);return l(b);}var t={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]};var p=["add","remove","toggle"],r={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};function o(){var e=document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle,d={},b,a;if(e&&e.length&&e[0]&&e[e[0]]){var c=e.length;while(c--){b=e[c];if(typeof e[b]=="string"){a=b.replace(/\-(\w)/g,function(g,f){return f.toUpperCase();});d[a]=e[b];}}}else{for(b in e){if(typeof e[b]==="string"){d[b]=e[b];}}}return d;}function s(b){var c,a;for(c in b){a=b[c];if(a==null||n.isFunction(a)||c in r||(/scrollbar/).test(c)||(!(/color/i).test(c)&&isNaN(parseFloat(a)))){delete b[c];}}return b;}function m(c,a){var d={_:0},b;for(b in a){if(c[b]!=a[b]){d[b]=a[b];}}return d;}n.effects.animateClass=function(c,b,d,a){if(n.isFunction(d)){a=d;d=null;}return this.each(function(){var f=n(this),i=f.attr("style")||" ",e=s(o.call(this)),g,h=f.attr("className");n.each(p,function(v,j){if(c[j]){f[j+"Class"](c[j]);}});g=s(o.call(this));f.attr("className",h);f.animate(m(e,g),b,d,function(){n.each(p,function(v,j){if(c[j]){f[j+"Class"](c[j]);}});if(typeof f.attr("style")=="object"){f.attr("style").cssText="";f.attr("style").cssText=i;}else{f.attr("style",i);}if(a){a.apply(this,arguments);}});});};n.fn.extend({_addClass:n.fn.addClass,addClass:function(b,c,d,a){return c?n.effects.animateClass.apply(this,[{add:b},c,d,a]):this._addClass(b);},_removeClass:n.fn.removeClass,removeClass:function(b,c,d,a){return c?n.effects.animateClass.apply(this,[{remove:b},c,d,a]):this._removeClass(b);},_toggleClass:n.fn.toggleClass,toggleClass:function(a,b,c,d,e){if(typeof b=="boolean"||b===undefined){if(!c){return this._toggleClass(a,b);}else{return n.effects.animateClass.apply(this,[(b?{add:a}:{remove:a}),c,d,e]);}}else{return n.effects.animateClass.apply(this,[{toggle:a},b,c,d]);}},switchClass:function(c,a,b,d,e){return n.effects.animateClass.apply(this,[{add:a,remove:c},b,d,e]);}});n.extend(n.effects,{version:"1.8",save:function(b,a){for(var c=0;c<a.length;c++){if(a[c]!==null){b.data("ec.storage."+a[c],b[0].style[a[c]]);}}},restore:function(b,a){for(var c=0;c<a.length;c++){if(a[c]!==null){b.css(a[c],b.data("ec.storage."+a[c]));}}},setMode:function(b,a){if(a=="toggle"){a=b.is(":hidden")?"show":"hide";}return a;},getBaseline:function(b,a){var d,c;switch(b[0]){case"top":d=0;break;case"middle":d=0.5;break;case"bottom":d=1;break;default:d=b[0]/a.height;}switch(b[1]){case"left":c=0;break;case"center":c=0.5;break;case"right":c=1;break;default:c=b[1]/a.width;}return{x:c,y:d};},createWrapper:function(c){if(c.parent().is(".ui-effects-wrapper")){return c.parent();}var b={width:c.outerWidth(true),height:c.outerHeight(true),"float":c.css("float")},a=n("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0});c.wrap(a);a=c.parent();if(c.css("position")=="static"){a.css({position:"relative"});c.css({position:"relative"});}else{n.extend(b,{position:c.css("position"),zIndex:c.css("z-index")});n.each(["top","left","bottom","right"],function(e,d){b[d]=c.css(d);if(isNaN(parseInt(b[d],10))){b[d]="auto";}});c.css({position:"relative",top:0,left:0});}return a.css(b).show();},removeWrapper:function(a){if(a.parent().is(".ui-effects-wrapper")){return a.parent().replaceWith(a);}return a;},setTransition:function(b,d,c,a){a=a||{};n.each(d,function(e,f){unit=b.cssUnit(f);if(unit[0]>0){a[f]=unit[0]*c+unit[1];}});return a;}});function q(b,c,a,d){if(typeof b=="object"){d=c;a=null;c=b;b=c.effect;}if(n.isFunction(c)){d=c;a=null;c={};}if(n.isFunction(a)){d=a;a=null;}if(typeof c=="number"||n.fx.speeds[c]){d=a;a=c;c={};}c=c||{};a=a||c.duration;a=n.fx.off?0:typeof a=="number"?a:n.fx.speeds[a]||n.fx.speeds._default;d=d||c.complete;return[b,c,a,d];}n.fn.extend({effect:function(g,a,e,d){var b=q.apply(this,arguments),f={options:b[1],duration:b[2],callback:b[3]},c=n.effects[g];return c&&!n.fx.off?c.call(this,f):this;},_show:n.fn.show,show:function(a){if(!a||typeof a=="number"||n.fx.speeds[a]){return this._show.apply(this,arguments);}else{var b=q.apply(this,arguments);b[1].mode="show";return this.effect.apply(this,b);}},_hide:n.fn.hide,hide:function(a){if(!a||typeof a=="number"||n.fx.speeds[a]){return this._hide.apply(this,arguments);}else{var b=q.apply(this,arguments);b[1].mode="hide";return this.effect.apply(this,b);}},__toggle:n.fn.toggle,toggle:function(a){if(!a||typeof a=="number"||n.fx.speeds[a]||typeof a=="boolean"||n.isFunction(a)){return this.__toggle.apply(this,arguments);}else{var b=q.apply(this,arguments);b[1].mode="toggle";return this.effect.apply(this,b);}},cssUnit:function(c){var b=this.css(c),a=[];n.each(["em","px","%","pt"],function(e,d){if(b.indexOf(d)>0){a=[parseFloat(b),d];}});return a;}});n.easing.jswing=n.easing.swing;n.extend(n.easing,{def:"easeOutQuad",swing:function(b,a,c,d,e){return n.easing[n.easing.def](b,a,c,d,e);},easeInQuad:function(b,a,c,d,e){return d*(a/=e)*a+c;},easeOutQuad:function(b,a,c,d,e){return -d*(a/=e)*(a-2)+c;},easeInOutQuad:function(b,a,c,d,e){if((a/=e/2)<1){return d/2*a*a+c;}return -d/2*((--a)*(a-2)-1)+c;},easeInCubic:function(b,a,c,d,e){return d*(a/=e)*a*a+c;},easeOutCubic:function(b,a,c,d,e){return d*((a=a/e-1)*a*a+1)+c;},easeInOutCubic:function(b,a,c,d,e){if((a/=e/2)<1){return d/2*a*a*a+c;}return d/2*((a-=2)*a*a+2)+c;},easeInQuart:function(b,a,c,d,e){return d*(a/=e)*a*a*a+c;},easeOutQuart:function(b,a,c,d,e){return -d*((a=a/e-1)*a*a*a-1)+c;},easeInOutQuart:function(b,a,c,d,e){if((a/=e/2)<1){return d/2*a*a*a*a+c;}return -d/2*((a-=2)*a*a*a-2)+c;},easeInQuint:function(b,a,c,d,e){return d*(a/=e)*a*a*a*a+c;},easeOutQuint:function(b,a,c,d,e){return d*((a=a/e-1)*a*a*a*a+1)+c;},easeInOutQuint:function(b,a,c,d,e){if((a/=e/2)<1){return d/2*a*a*a*a*a+c;}return d/2*((a-=2)*a*a*a*a+2)+c;},easeInSine:function(b,a,c,d,e){return -d*Math.cos(a/e*(Math.PI/2))+d+c;},easeOutSine:function(b,a,c,d,e){return d*Math.sin(a/e*(Math.PI/2))+c;},easeInOutSine:function(b,a,c,d,e){return -d/2*(Math.cos(Math.PI*a/e)-1)+c;},easeInExpo:function(b,a,c,d,e){return(a==0)?c:d*Math.pow(2,10*(a/e-1))+c;},easeOutExpo:function(b,a,c,d,e){return(a==e)?c+d:d*(-Math.pow(2,-10*a/e)+1)+c;},easeInOutExpo:function(b,a,c,d,e){if(a==0){return c;}if(a==e){return c+d;}if((a/=e/2)<1){return d/2*Math.pow(2,10*(a-1))+c;}return d/2*(-Math.pow(2,-10*--a)+2)+c;},easeInCirc:function(b,a,c,d,e){return -d*(Math.sqrt(1-(a/=e)*a)-1)+c;},easeOutCirc:function(b,a,c,d,e){return d*Math.sqrt(1-(a=a/e-1)*a)+c;},easeInOutCirc:function(b,a,c,d,e){if((a/=e/2)<1){return -d/2*(Math.sqrt(1-a*a)-1)+c;}return d/2*(Math.sqrt(1-(a-=2)*a)+1)+c;},easeInElastic:function(b,h,c,d,e){var g=1.70158;var f=0;var a=d;if(h==0){return c;}if((h/=e)==1){return c+d;}if(!f){f=e*0.3;}if(a<Math.abs(d)){a=d;var g=f/4;}else{var g=f/(2*Math.PI)*Math.asin(d/a);}return -(a*Math.pow(2,10*(h-=1))*Math.sin((h*e-g)*(2*Math.PI)/f))+c;},easeOutElastic:function(b,h,c,d,e){var g=1.70158;var f=0;var a=d;if(h==0){return c;}if((h/=e)==1){return c+d;}if(!f){f=e*0.3;}if(a<Math.abs(d)){a=d;var g=f/4;}else{var g=f/(2*Math.PI)*Math.asin(d/a);}return a*Math.pow(2,-10*h)*Math.sin((h*e-g)*(2*Math.PI)/f)+d+c;},easeInOutElastic:function(b,h,c,d,e){var g=1.70158;var f=0;var a=d;if(h==0){return c;}if((h/=e/2)==2){return c+d;}if(!f){f=e*(0.3*1.5);}if(a<Math.abs(d)){a=d;var g=f/4;}else{var g=f/(2*Math.PI)*Math.asin(d/a);}if(h<1){return -0.5*(a*Math.pow(2,10*(h-=1))*Math.sin((h*e-g)*(2*Math.PI)/f))+c;}return a*Math.pow(2,-10*(h-=1))*Math.sin((h*e-g)*(2*Math.PI)/f)*0.5+d+c;},easeInBack:function(b,a,c,d,e,f){if(f==undefined){f=1.70158;}return d*(a/=e)*a*((f+1)*a-f)+c;},easeOutBack:function(b,a,c,d,e,f){if(f==undefined){f=1.70158;}return d*((a=a/e-1)*a*((f+1)*a+f)+1)+c;},easeInOutBack:function(b,a,c,d,e,f){if(f==undefined){f=1.70158;}if((a/=e/2)<1){return d/2*(a*a*(((f*=(1.525))+1)*a-f))+c;}return d/2*((a-=2)*a*(((f*=(1.525))+1)*a+f)+2)+c;},easeInBounce:function(b,a,c,d,e){return d-n.easing.easeOutBounce(b,e-a,0,d,e)+c;},easeOutBounce:function(b,a,c,d,e){if((a/=e)<(1/2.75)){return d*(7.5625*a*a)+c;}else{if(a<(2/2.75)){return d*(7.5625*(a-=(1.5/2.75))*a+0.75)+c;}else{if(a<(2.5/2.75)){return d*(7.5625*(a-=(2.25/2.75))*a+0.9375)+c;}else{return d*(7.5625*(a-=(2.625/2.75))*a+0.984375)+c;}}}},easeInOutBounce:function(b,a,c,d,e){if(a<e/2){return n.easing.easeInBounce(b,a*2,0,d,e)*0.5+c;}return n.easing.easeOutBounce(b,a*2-e,0,d,e)*0.5+d*0.5+c;}});})(jQuery);
(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);
(function(b) {
    var a = {
        getOptionValue: function(e, d, c) {
            if (b.isFunction(e)) {
                e = e.call(d, c);
            }
            return e;
        },
        getCategory: function() {
            return this.nodeName;
        },
        getAction: function(c) {
            return c.type;
        },
        getLabel: function() {
            var c = b(this);
            if (c.is("a")) {
                return c.attr("href");
            } else {
                if (c.is("input")) {
                    return c.val();
                } else {
                    if (c.attr("id")) {
                        return c.attr("id");
                    } else {
                        return c.text();
                    }
                }
            }
        }
    };
    b.expr[":"].external = function(c) {
        return (c.host && c.host !== location.host) === true;
    };
    b.fn.trackEvent = function(c) {
        var d = {
            eventType: "click",
            once: true,
            category: a.getCategory,
            action: a.getAction,
            label: a.getLabel,
            value: 1
        };
        if (c) {
            b.extend(d, c);
        }
        this.each(function(f) {
            var e = function(i) {
                var h = a.getOptionValue(d.category, this, i);
                var k = a.getOptionValue(d.action, this, i);
                var g = a.getOptionValue(d.label, this, i);
                var j = a.getOptionValue(d.value, this, i);
                var t = _gat._getTracker(customTracker);
                t._initData();
                t._trackEvent(h, k, g, parseInt(j));
            };
            if (d.once) {
                b(this).one(d.eventType, e);
            } else {
                b(this).bind(d.eventType, e);
            }
        });
        return this;
    };
})(jQuery);
(function(a){a.fn.center=function(b){var c={top:function(){return window.pageYOffset||document.documentElement&&document.documentElement.scrollTop||document.body.scrollTop;},height:function(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body.clientHeight;}};return this.each(function(e){if(e==0){var g=a(this);var d=g.height();var f=c.top()+(c.height()/2)-(d/2);g.css({position:"absolute",marginTop:"0",top:f});}});};})(jQuery);

function Pager(target) {
    var $target = jQuery(target + ' .content ul');
    var $count = jQuery(target + ' .count');
    var $pager = jQuery(target + ' .pager');
    var view = $target.parent().height();
    var count = 1;
    normal = $target.height() / view;
    fixed = parseInt(normal.toFixed(0));
    var delimeter = 0;
    if (normal > fixed) delimeter = fixed + 1;
    else delimeter = fixed;
    $count.attr('class', 'count ' + 'number-' + delimeter);

    function number(index) {
        jQuery(target + ' .index').attr('class', 'index ' + 'number-' + index)
    }
    bind();

    function bind() {
        $pager.find('a').bind('click', binded)
    }


    function unbind() {
        $pager.find('a').unbind('click', binded)
    }


    function active(action) {
        if (action == 'prev') if ((count) == 1) return false;
        if (action == 'next') if ((count) == delimeter) return false;
        return true
    }


    function move(action, $self) {
        $self.attr('class', '');
        if (action == 'prev') {
            count--;
            if (count == 1) $self.attr('class', 'prev-end')
        }
        if (action == 'next') {
            count++;
            if (count == delimeter) $self.attr('class', 'next-end')
        }
        position = (count - 1) * view;
        number(count);
        $target.animate({
            'marginTop': -position
        },
        300)
    }


    function binded() {
        var name = jQuery(this).attr('class');
        var $parent = jQuery(this).parent();
        switch (name) {
        case 'prev':
            if (active('prev')) move('prev', $parent);
            break;
        case 'next':
            if (active('next')) move('next', $parent)
        }
        return false
    }
}

function Loader(image, target) {
    var oimage = new Image();
    var ration;
    oimage.onload = function() {
        var width = oimage.width;
        var height = oimage.height;
        if (width > height) {
            if (width > 980) {
                height = height / (width / 980);
                width = 980
            }
        }
        if (height > width) {
            if (height > 500) {
                width = width / (height / 500);
                height = 500
            }
        }
        var $image = jQuery(target).find('.image');
        jQuery('#layer a').attr('href', image.href);
        $image.attr('title', image.title);
        var $source = jQuery('<img src="' + image.src + '" />');
        $source.attr('width', width).attr('height', height).appendTo($image);
        resize(width, height);
        oimage.onload = function() {}
    };
    oimage.src = image.src;

    function resize(wwidth, wheight) {
        var left = wwidth / 2;
        var top = wheight / 6;
        var top = ((wheight - 333)) / 2;
        jQuery(target).animate({
            width: wwidth,
            height: wheight + 0,
            marginLeft: -left,
            marginTop: -top,
            left: '50%',
            opacity: 1
        },
        300, function() {})
    }
}

function Close() {
    jQuery('#overlay, #layer a').click(function() {
        jQuery('#layer').fadeOut('120', function() {
            jQuery('#overlay').fadeOut('60', function() {
                jQuery('#layer').remove();
                jQuery('#overlay').remove()
            })
        });
        return false
    })
};

function CloseMediabox() {
    jQuery('#layer').fadeOut('120', function() {
        jQuery('#overlay').fadeOut('60', function() {
            jQuery('#layer').remove();
            jQuery('#overlay').remove()
        })
    });
    return false
}

function Windows() {
    var container = '#window';
    var overlay = '#overlay';
    var curent = this;
    this.handler;
    this.editor;
    this.closeAction;
    this.openAction;
    this.closeElement;
    this.openElement;
    this.init = function(content) {
        var values = {
            'height': jQuery('body').height(),
            'width': jQuery('body').width()
        };
        jQuery('<div id="overlay"></div>').animate({
            opacity: 0
        },
        0).prependTo('body').css(values).animate({
            opacity: 0.6
        },
        180, function() {
            jQuery(content).animate({
                opacity: 0
            },
            0).prependTo('body').animate({
                opacity: 1
            },
            260, function() {
                if (jQuery.browser.msie) this.style.removeAttribute('filter');
                curent.openAction();
                curent.prepareClose()
            }).center()
        })
    };
    this.open = function(element, request, action) {
        if (typeof action === 'function') {
            curent.openAction = function() {
                action()
            }
        } else {
            curent.openAction = function() {
                return true
            }
        }
        curent.requestAction = function() {
            request()
        };
        jQuery(element).live('click', function() {
            curent.openElement = this;
            return openEach(this)
        })
    };
    var openEach = function(element) {
        curent.handler = jQuery(element).attr('rel');
        curent.requestAction();
        return false
    };
    this.close = function(element, action) {
        if (typeof action === 'function') {
            curent.closeAction = function() {
                action()
            }
        } else {
            curent.closeAction = function() {
                return true
            }
        }
        curent.prepareClose = function() {
            jQuery(element + ', ' + overlay).bind('click', function() {
                curent.closeElement = this;
                return closeEach()
            })
        }
    };
    var closeEach = function() {
        curent.closeAction();
        jQuery(container).fadeOut(130, function() {
            jQuery(container).remove();
            jQuery(overlay).fadeOut(90, function() {
                jQuery(overlay).remove()
            })
        });
        return false
    };
    this.terminate = function() {
        closeEach()
    };
    this.projection = function() {
        curent.requestAction()
    }
}

function Layer(g) {
    var e = jQuery('<div id="layer"></div>');
    e.append('<div class="content"><a class="image" href="" title="" target="_blank"></a></div>');
    e.append('<div class="close"><a class="terminate" href="#"></a></div>');
    var f = {
        height: jQuery("body").height(),
        width: jQuery("body").width()
    };
    var h = {
        href: g.rel,
        src: g.src,
        title: g.title
    };
    jQuery('<div id="overlay"></div>').animate({
        opacity: 0
    },
    0).prependTo("body").css(f).animate({
        opacity: 0.3
    },
    180, function() {
        jQuery(e).animate({
            opacity: 0
        },
        0).prependTo("body").animate({
            opacity: 1
        },
        360, function() {
            new Loader(h, "#layer");
            Close();
        }).center();
    });
}

function strip_tags(b, c) {
    var f = "",
        d = false;
    var a = [];
    var g = [];
    var e = "";
    var j = 0;
    var i = "";
    var l = "";
    var h = function(m, k, n) {
        return n.split(m).join(k);
    };
    if (c) {
        g = c.match(/([a-zA-Z]+)/gi);
    }
    b += "";
    a = b.match(/(<\/?[\S][^>]*>)/gi);
    for (f in a) {
        if (isNaN(f)) {
            continue;
        }
        l = a[f].toString();
        d = false;
        for (i in g) {
            e = g[i];
            j = -1;
            if (j != 0) {
                j = l.toLowerCase().indexOf("<" + e + ">");
            }
            if (j != 0) {
                j = l.toLowerCase().indexOf("<" + e + " ");
            }
            if (j != 0) {
                j = l.toLowerCase().indexOf("</" + e);
            }
            if (j == 0) {
                d = true;
                break;
            }
        }
        if (!d) {
            b = h(l, "", b);
        }
    }
    return b;
}

var time = 300;

var errors = {
    'isEmpty': 'Pole wymagane nie może być puste.',
    'notSame': 'Wprowadzone wartości nie są takie same.',
    'notGreaterThan': 'Pole wymagane, musi być zaznaczone.',
    'emailExist': 'Ten adres już zarejestrowano.',
    'notAllowed': 'Wprowadzono nie dozwoloną wartość.',
    'notAlnum': 'Wprowadzono nie dozwoloną wartość.',
    'stringLengthTooShort': 'Wprowadzona wartość jest za krótka.',
    'stringLengthTooLong': 'Wprowadzona wartość jest za długa.',
    'emailAddressInvalidFormat': 'Nieprawidłowy adres e-mail.',
    'notRecognized': 'Nieprawidłowa nazwa konta lub hasło.',
    'emailNewsletterExists': 'Podany adres jest już w bazie.',
    'emailDontExists': 'Nie znaleziono pasującego użytkownika.',
    'invalidPostcode': 'Nieprawidłowy kod pocztowy.',
    'invalidNip': 'Nieprawidłowy numer nip.',
    'invalidPhone': 'Nieprawidłowy numer telefonu.'  
};

var message = {
    pl: {
        schortQuery: "Podana fraza jest za krótka.",
        closeEmptyRequest: "Podana fraza nie została odnaleziona. Spróbuj zmodyfikować swoje zapytanie.",
        searchError: "Podczas wyszukiwania wystąpił błąd. Spróbuj ponownie.",
        searchWorking: "Trwa wyszukiwanie"        
    },
    en: {
        schortQuery: "Search term is to short.",
        closeEmptyRequest: "Your search did not match any documents. Try different keywords.",
        searchError: "Your search did not match any documents. Try different keywords.",
        searchWorking: "Searching..."
    }
};

var searchAddress = "/services/livesearch.php";

var livesearch = {
    start: function() {
        this.construct();
        this.proced();
    },
    construct: function() {
        var b = $('<div id="livesearch-content"></div>');
        $('<div class="content"><div class="message"></div><div class="submit"></div></div>').appendTo(b);
        b.appendTo("#livesearch").hide(0);
    },
    proced: function() {
        var $container = $("#livesearch-content");
        var $query = $("#livesearch-query");
        var $results = $('<a href="/szukaj">zobacz wszystkie wyniki wyszukiwania</a>');
        var $message = $("#livesearch-content .message");
        var temporary = null;
        $results.appendTo("#livesearch-content .content .submit").hide();

        function messageStatus(data) {
            $message.find("span").remove();
            $results.hide();
            if (data) {
                data = eval("message." + data);
                if (data) {
                    var $proces = $(document.createElement("span")).text(data);
                    $proces.appendTo($message);
                }
            }
            return false;
        }

        function clickStatus(event) {
            var close = true;
            $(this).parents().map(function() {
                return this.id;
            }).each(function(e) {
                if (this == "livesearch") {
                    close = false;
                }
            });
            if (close == true) {
                closeSearch();
            }
            return close;
        }

        function suspendSearch() {
            if ($container.not(":visible")) {
                jQuery("#livesearch-query").attr("value", "");
                $container.find("dl").remove();
            }
        }

        function newLocation() {
            window.location = $(this).attr("href");
        }

        function openSearch() {
            $container.not(":visible").fadeIn(500).attr("visible", true);
            $("body").addClass("livesearch");
            $("*:not(#livesearch-content *, #livesearch-content)").bind('click', clickStatus);
            $("#livesearch-content .submit a").click(function() {
                $("form#livesearch").submit();
                return false;
            });
            
            $('form#livesearch').submit(function() {
                document.location.href = '/szukaj/' + $('#livesearch-query').val().toLowerCase() + '.html';
                return false;
            });
        }

        function closeSearch() {
            $(".livesearch *").unbind('click', clickStatus);
            $("body").removeClass("livesearch");
            $container.fadeOut(500).attr("visible", false);
        }

        $query.focus(function() {
            if ($container.not(":visible") && $(this).val().length > 0) {
                openSearch();
            }
        });

        function emptyRequest(response) {
            timeEmpty = setTimeout(function() {
                $container.find("dl").remove();
                if (response) {
                    messageStatus(response);
                }
            },
            300);
        }

        $query.bind("keyup", function(e) {
            var query = $(this).val();
            if (e.keyCode === 39 || e.keyCode === 37) {
                return false;
            }
            if (query.length == 0) {
                emptyRequest("schortQuery");
                return false;
            }
            if (query.length < 4) {
                emptyRequest("schortQuery");
                return false;
            }
            if (query === temporary) {
                return false;
            }
            clearTimeout(time);
            messageStatus("searchWorking");
            time = setTimeout(function() {
                jQuery.ajax({
                    url: searchAddress,
                    data: "search=" + query,
                    dataType: "json",
                    success: function(data) {
                        if (data.status == false) {
                            emptyRequest("closeEmptyRequest");
                        } else {
                            emptyRequest("closeDefault");
                            timeWrite = setTimeout(function() {
                                livesearch.parse(data.data);
                                $results.show();
                            },
                            300);
                        }
                    },
                    complete: function(request, status) {
                        switch (status) {
                        case "parsererror":
                            emptyRequest("closeEmptyRequest");
                            break;
                        case "error":
                            emptyRequest("searchError");
                            break;
                        }
                    }
                });
            },
            600);
            temporary = query;
            openSearch();
            return false;
        });
    },
    parse: function(data) {
        for (key in data) {
            var $content = $('<dl class="' + key + '"><dt></dt></dl>');
            var row = eval("data." + key);
            $.each(row, function(i, e) {
                var title = e.title.replace("<br />", "");
                var anchor = '<dd><a href="/artykul/' + e.id + '">';
                switch (key) {
                case "feuilletons":
                    anchor += "<span>" + e.title + "<em>" + e.author + '</em></span><img src="' + e.image + '" />';
                    break;
                case "opinions":
                    anchor += "<em>" + e.author + "</em><span>" + e.title + "</span>";
                    break;
                case "others":
                    anchor += "<span>" + title + "</span>";
                    break;
                }
                anchor += "</a></dd>";
                $(anchor).appendTo($content);
            });
            $content.insertBefore("#livesearch-content .content .message").fadeIn();
        }
    }
};

var mediaplayer = {
    image: function(f) {
        var d = jQuery('<div id="layer"></div>');
        d.append('<div class="content"><a class="image" href="" title="" target="_blank"></a></div>');
        d.append('<div class="close"><a class="terminate" href="#"></a></div>');
        var e = {
            height: jQuery("body").height(),
            width: jQuery("body").width()
        };
        f = {
            href: "#",
            src: "/public/media/electric/" + f
        };
        jQuery('<div id="overlay"></div>').animate({
            opacity: 0
        },
        0).prependTo("body").css(e).animate({
            opacity: 0.6
        },
        180, function() {
            jQuery(d).animate({
                opacity: 0
            },
            0).prependTo("body").animate({
                opacity: 1
            },
            360, function() {
                new Loader(f, "#layer");
                Close();
            }).center();
        });
    },
    animation: function(f) {
        var f_org = f;
        var d = jQuery('<div id="layer" class="flashplayer electric_flash_3"></div>');
		if (f == "7ec846-source.swf") {
            d.addClass('electric_flash_3_wide');
		}
        d.append('<div class="content" id="video_player"></div>');
        var e = {
            height: jQuery("body").height(),
            width: jQuery("body").width()
        };
        f = "/public/media/electric/" + f;
        jQuery('<div id="overlay"></div>').animate({
            opacity: 0
        },
        0).prependTo("body").css(e).animate({
            opacity: 0.6
        },
        180, function() {
            jQuery(d).animate({
                opacity: 0
            },
            0).prependTo("body").animate({
                opacity: 1
            },
            360, function() {
                var c = {};
                var a = {
                    scale: "noscale",
                    allowFullScreen: "true"
                };
                var b = {};
                if (f_org == "7ec846-source.swf") {
                    swfobject.embedSWF(f, "video_player", "980", "580", "9.0.0", "/public/flash/expressinstall.swf", c, a, b);                    
                } else {
                    swfobject.embedSWF(f, "video_player", "800", "600", "9.0.0", "/public/flash/expressinstall.swf", c, a, b);
                }
                
                Close();
            }).center();
        });
    },
    video: function(g, h) {
        var e = jQuery('<div id="layer" class="flashplayer"></div>');
        e.append('<div class="content" id="video_player"></div>');
        var f = {
            height: jQuery("body").height(),
            width: jQuery("body").width()
        };
        jQuery('<div id="overlay"></div>').animate({
            opacity: 0
        },
        0).prependTo("body").css(f).animate({
            opacity: 0.6
        },
        180, function() {
            jQuery(e).animate({
                opacity: 0
            },
            0).prependTo("body").animate({
                opacity: 1
            },
            360, function() {
                var c = {
                    description: h,
                    video_file: g
                };
                var a = {
                    scale: "noscale",
                    allowFullScreen: "true"
                };
                var b = {};
                swfobject.embedSWF("/public/frontend/flash/videoplayer.swf", "video_player", "480", "430", "9.0.0", "/public/flash/expressinstall.swf", c, a, b);
                Close();
            }).center();
        });
    }
};

var electric = {
    image: function(f) {
        var d = $('<div id="layer"></div>');
        d.append('<div class="content"><a class="image" href="" title="" target="_blank"></a></div>');
        d.append('<div class="close"><a class="terminate" href="#"></a></div>');
        var e = {
            height: $(document).height(),
            width: $(document).width()
        };
        source = {
            src: "/public/media/electric/" + f.source
        };
        $('<div id="overlay"></div>').animate({
            opacity: 0
        },
        0).prependTo("body").css(e).animate({
            opacity: 0.6
        },
        180, function() {
            d.animate({
                opacity: 0
            },
            0).prependTo("body").animate({
                opacity: 1
            },
            360, function() {
                new Loader(source, "#layer");
                Close();
            }).center();
        });
        return false;
    },
    animation: function(h) {
        var e = $('<div id="layer" class="flashplayer electric_flash_3"></div>');
        e.append('<div class="content" id="animation"></div>');
        var f = {
            height: $(document).height(),
            width: $(document).width()
        };
        var g = "/public/media/electric/" + h.source;
        $('<div id="overlay"></div>').animate({
            opacity: 0
        },
        0).prependTo("body").css(f).animate({
            opacity: 0.6
        },
        180, function() {
            e.animate({
                opacity: 0
            },
            0).prependTo("body").animate({
                opacity: 1
            },
            360, function() {
                var c = {};
                var a = {
                    scale: "noscale",
                    allowFullScreen: "true",
                    wmode: "opaque"
                };
                var b = {};
                swfobject.embedSWF(g, "animation", "800", "600", "9.0.0", "/public/flash/expressinstall.swf", c, a, b);
                Close();
            }).center();
        });
        return false;
    },
    video: function(l) {
        try {
            var p = {
                description: strip_tags(l.description),
                video_file: l.source
            };
            if (l.category == "article" || l.category == "fictions") {
                var h = l.directory.split("_");
                var k = "/public/frontend/flash/videoplayer.swf";
                p.year = h[0];
                p.issue = h[1];
            } else {
                var k = "/public/frontend/flash/videoplayer.swf";
            }
            var o = {
                height: $(document).height(),
                width: $(document).width()
            };
            var m = $('<div id="layer" class="flashplayer"></div>');
            m.append('<div class="content" id="video_player"></div>');
            $('<div id="overlay"></div>').animate({
                opacity: 0
            },
            0).prependTo("body").css(o).animate({
                opacity: 0.6
            },
            180, function() {
                m.animate({
                    opacity: 0
                },
                0).prependTo("body").animate({
                    opacity: 1
                },
                360, function() {
                    var a = {
                        scale: "noscale",
                        allowFullScreen: "true",
                        wmode: "opaque",
                        bgcolor: "#000000"
                    };
                    var b = {};
                    swfobject.embedSWF(k, "video_player", "480", "430", "9.0.0", "/public/flash/expressinstall.swf", p, a, b);
                    Close();
                }).center();
            });
        } catch(n) {
            alert(n);
        }
        return false;
    },
    audio: function(n, m) {
        var p = $(m).parent().attr("id");
        var h = n.directory.split("_");
        var k = {
            description: jQuery(n.description).html(),
            video_file: n.source,
            year: h[0],
            issue: h[1]
        };
        var l = {
            scale: "noscale",
            allowFullScreen: "true",
            wmode: "transparent"
        };
        var o = {};
        swfobject.embedSWF("/public/frontend/flash/audioplayer-small.swf", p, "220", "120", "9.0.0", "/public/flash/expressinstall.swf", k, l, o);
    }
};

var engine = {
    start: function() {
        this.google();
        this.cufon();
        this.archive();
        this.newsletter();
        if (document.getElementById("list")) {
            this.fixed();
        }
        if (document.getElementById("poem")) {
            this.poems();
        }
        if (document.getElementById("electric")) {
            this.electric();
        }
        this.category();
        if (document.getElementById("felietony")) {
            this.authors();
        }
        if (document.getElementById("homepage")) {
            this.homepage();
        }
        this.images();
        this.tags();
        this.media();
    },
    media: function(source) {
        $(".mediacreator").each(function(i, source) {
            var target = $(this).find("img").attr("alt");
            $(mediacontainer).each(function(i, element) {
                    if (target == element.id) {
                        $(source).empty();
                        $(source).append('<div id="mediacreator-' + element.id + '"></div>');
                        switch (element.type) {
                            case "audio":
                                c(element);
                            break;
                            case "video":
                                d(element);
                            break;
                        }
                    }
                });
            });

            function c(b) {
                var h = {
                    description: b.description,
                    video_file: b.source,
                    year: b.year,
                    issue: b.issue
                };
                var a = {
                    scale: "noscale",
                    allowFullScreen: "true"
                };
                var e = {};
                swfobject.embedSWF("/public/frontend/flash/audioplayer.swf", "mediacreator-" + b.id, "480", "86", "9.0.0", "/public/flash/expressinstall.swf", h, a, e);
            };


            function d(b) {
                var h = {
                    description: b.description,
                    video_file: b.source,
                    year: b.year,
                    issue: b.issue
                };
                var a = {
                    scale: "noscale",
                    allowFullScreen: "true"
                };
                var e = {};
                swfobject.embedSWF("/public/frontend/flash/videoplayer.swf", "mediacreator-" + b.id, "480", "430", "9.0.0", "/public/flash/expressinstall.swf", h, a, e);
            };
    },
    cufon: function() {
        Cufon.replace("#list h4, .articles h4, #shortly .content .title, #fictions dt, #feuilletons .title a", {
            hover: true,
            fontFamily: 'Baskerville Win95BT'
        });
        Cufon.replace(".content h2", {
            fontFamily: 'Baskerville Win95BT'
        });
    },
    homepage: function() {
        Pager("#news");
    },
    authors: function() {
        jQuery(".filter .authors").bind("click", function() {
            jQuery("#authors").toggle(1);
        });
        jQuery("#authors .content a").bind("click", function() {
            jQuery(this).toggleClass("selected");
            return false;
        });
        jQuery("#authors .proced").bind("click", function() {
            var f = new Array();
            jQuery("#authors .content .selected").each(function(b, a) {
                f[b] = jQuery(a).attr("rel");
            });
            var d = "" + jQuery(this).attr("href");
            var e = f.join(",");
            address = "/archiwum/autor-" + e + "/felietony.html";
            if (f.length > 0) {
                jQuery(this).attr("href", address);
            }
        });
    },
    category: function() {
        jQuery(".filter .category").bind("click", function() {
            jQuery("#category").toggle(1);
        });
        jQuery("#category .content a").bind("click", function() {
            jQuery(this).toggleClass("selected");
            return false;
        });
        jQuery("#category .proced").bind("click", function() {
            var f = new Array();
            jQuery("#category .content .selected").each(function(b, a) {
                f[b] = jQuery(a).attr("rel");
            });
            var d = "" + jQuery(this).attr("href");
            var e = f.join("+");
            address = "/kategorie," + e + "/elektryczne.html";
            if (f.length > 0) {
                jQuery(this).attr("href", address);
            }
        });
    },
    tags: function() {
        jQuery(".filter .tags").bind("click", function() {
            jQuery("#tags").toggle(1);
        });
        jQuery("#tags .content a").bind("click", function() {
            jQuery(this).toggleClass("selected");
            return false;
        });
        jQuery("#tags .proced").bind("click", function() {
            var f = document.getElementById("collectioncloud") ? "" : "/archiwum/tagi/";
            var g = new Array();
            jQuery("#tags .content .selected").each(function(b, a) {
                g[b] = jQuery(a).attr("rel");
            });
            if (document.getElementById("collectioncloud")) {
                var h = "" + jQuery(this).attr("href");
                var e = g.join("+");
                f += (e.length == 0) ? "" : h.replace(/archiwum/, "archiwum/" + e);
            } else {
                f += g.join("+") + ".html";
            }
            if (g.length > 0) {
                jQuery(this).attr("href", f);
            }
        });
    },
    google: function() {

    },
    newsletter: function() {
        var b = jQuery("#newsletter");
        jQuery("#navigation .newsletter").click(function() {
            b.toggle(1);
            return false;
        });
        jQuery("#newsletter form").submit(function() {
            var a = jQuery("#newsletter input[name='action']:checked").val();
            jQuery.ajax({
                type: "POST",
                url: "/newsletter/" + a + "/format/json",
                data: "email=" + jQuery("#newsletter .email").val(),
                dataType: "json",
                beforeSend: function() {
                    var message = {
                        pl: "Trwa zapisywanie...",
                        en: "Connecting..."
                    };
                    jQuery("#newsletter .message").html(message[language]);
                },
                success: function(c) {
                    if (typeof c === "object") {
                        jQuery("#newsletter .message").fadeIn(100, function() {
                            jQuery(this).html(c.message);
                        });
                        if (c.status == true) {
                            setTimeout(function() {
                                b.hide(1);
                                jQuery("#newsletter .message").fadeOut(100);
                            },
                            2400);
                        }
                    }
                }
            });
            return false;
        });
    },
    print: function() {
        jQuery("#print a, .print a").click(function() {
            $('<img src="/public/image/logo.png" border="0" class="printme" />').insertBefore("#header h2:first");
            print();
            return false;
        });
    },
    images: function() {
        $(".zoom").click(function() {
            var b = {};
            $anchor = $(this);
            b.src = $anchor.attr("href");
            b.href = $anchor.attr("href");
            b.title = $anchor.find(".legend").html();
            new Layer(b);
            return false;
        });
        jQuery("#materials .media-anchor").bind("click", function() {
            var e = $(this).attr("rel");
            var f = $(this).attr("href");
            var d = $(this).attr("title");
            switch (e) {
            case "mediatype-video":
                mediaplayer.video(f, d);
                break;
            case "mediatype-image":
                mediaplayer.image(f);
                break;
            case "mediatype-animation":
                mediaplayer.animation(f);
                break;
            }
            return false;
        });
    },
    electric: function() {
        $("#electric .mediatype a").each(function() {
            var c = $(this);
            var d = {};
            d.source = c.attr("href");
            d.category = c.attr("title");
            d.type = c.attr("rel");
            d.description = $(this).parent().parent().find(".description").html();
            d.directory = c.find("img").attr("alt");
            switch (d.type) {
            case "video":
                $(this).bind("click", function() {
                    electric.video(d);
                    return false;
                });
                break;
            case "image":
                $(this).bind("click", function() {
                    electric.image(d);
                    return false;
                });
                break;
            case "animation":
                $(this).bind("click", function() {
                    electric.animation(d);
                    return false;
                });
                break;
            case "audio":
                electric.audio(d, c);
                break;
            }
        });
    },
    archive: function() {
        jQuery(".prev-end, .next-end").click(function() {
            return false;
        });
        var d = 0;
        jQuery("#header .archive").bind("click", function() {
            jQuery(this).toggleClass("active");
            jQuery("#archive").slideToggle(600);
            if (d == 0) {
                $("#archive .slide dl").each(function() {
                    d += $(this).outerWidth(true);
                });
                $("#archive .slide").width(d);
            }
            return false;
        });
        
        var shortly = $('#header #archive');
        if (shortly.size() > 0) {
            var size = shortly.find('.content dd').size();
            shortly.find('.content .slide').width(97 * size);
            var list = shortly.find('.content .slide');
            var page = 1;
            var pages = Math.round(size / 9);
            var action = ['prev', 'next'];
            action.next = shortly.find('.next a');
            action.prev = shortly.find('.prev a');
            action.next.addClass('blocked');
            pages = pages == 0 ? 1 : pages;
            function disabledA() {

                if (page == 1) {
                    action.next.addClass('blocked');
                } else {
                    action.next.removeClass('blocked');
                }
                if (page > pages) {
                    action.prev.addClass('blocked');
                } else {
                    action.prev.removeClass('blocked');
                }
            }
            disabledA();
            action.prev.click(function() {
                if ($(this).hasClass('blocked')) {
                    return false;
                } else {
                    page++;
                    disabledA();
                    var item = (page * 9) > size ? ((page * 9) - size) : 9;
                    item = (97 * item) == (97 * 9) ? 0 : (97 * item);
                    item = -(((97 * 9) * (page - 1)) - item);
                    list.stop().animate({'right': item}, 690, 'easeInOutQuad');
                }
                return false;
            });

            action.next.click(function() {
                if ($(this).hasClass('blocked')) {
                    return false;
                } else {
                    page--;
                    disabledA();
                    list.stop().animate({'right': -((97 * 9) * (page - 1))}, 690, 'easeInOutQuad');
                }
                return false;
            });            
        }
    },
    fixed: function() {
        if ($(".article .related li").size() > 4) {
            $(".article .related li:gt(3)").hide();
            $(".article .related ul").after('<a class="more" href="#">pokaż wszystkie</a>');
            var s = 2;
            $(".article .more").click(function() {
                var b = this;
                var a = s++%2 == 0;
                $(".article .related ul li:gt(3)").slideToggle(300, function() {
                    if (a) {
                        $(b).html("schowaj");
                    } else {
                        $(b).html("pokaż wszystkie");
                    }
                });
                return false;
            });
        }
        var r = (document.getElementById("felietony")) ? 3 : 4;
        var p = document.getElementById("list");
        var n = p.getElementsByTagName("li");
        var l = Math.ceil(n.length / r);
        var t, o;
        for (i = 0; i < l; i++) {
            o = 0;
            for (j = 0; j < r; j++) {
                var q = i * r + j;
                var m = jQuery(n[q]).height();
                t = ((q + 1) > n.length) ? false : true;
                if (t) {
                    if (m > o) {
                        o = m;
                    }
                }
            }
            for (j = 0; j < r; j++) {
                var q = i * r + j;
                n[q].style.height = o + "px";
                if ((q + 1) == (n.length)) {
                    return false;
                }
            }
        }
        return false;
    },
    poems: function() {
        switch(window['language']) {
            case 'pl':
                $("#poem .chapter:first").addClass("description").before('<p id="print"><a href="" title="">Wersja do druku</a></p>');
                break;
            case 'en':
                $("#poem .chapter:first").addClass("description").before('<p id="print"><a href="" title="">Print version</a></p>');
                break;
        }
    }
};

var common = {
    start: function() {
        this.cufon();
        this.slide();
        this.comments();
        this.chapters();
        this.shareemail();
        this.pudelit();
        setTimeout(function() {
            common.short();
            common.fixed();
        }, 300);
        if (document.getElementById('redaction-comments')) {
            this.sharecomments();
        }
    },

    fixed: function() {
        if (document.getElementById('search-results')) {
            var r = 4;
            var p = document.getElementById('search-results');
            var n = p.getElementsByTagName("dd");
            var l = Math.ceil(n.length / r);
            var t, o;
            for (i = 0; i < l; i++) {
                o = 0;
                for (j = 0; j < r; j++) {
                    var q = i * r + j;
                    var m = jQuery(n[q]).height();
                    if (j == 0) {
                        jQuery(n[q]).addClass('first');
                    }
                    if (j == 3) {
                        jQuery(n[q]).addClass('last');          
                    }
                    t = ((q + 1) > n.length) ? false : true;
                    if (t) {
                        if (m > o) {
                            o = m;
                        }
                    }
                }
                for (j = 0; j < r; j++) {
                    var q = i * r + j;
                    n[q].style.height = o + "px";
                    if ((q + 1) == (n.length)) {
                        return false;
                    }
                }
            }
            return false;
        }
    },

    cufon: function() {
        Cufon.replace("#navigation a, #short .control dd a, #numbers li, .pager li a",{hover:true,fontFamily:'Depot Bold'});
        Cufon.replace("#footer a, #footer span",{fontFamily:'Depot Bold',hover:true,textShadow:'-1px -1px #2f2f2f'});
        Cufon.replace("#promoted h3 a, #pudelit-list dt,#short .control dt strong, #short .list strong, #sidebar h4 strong, .chapter .border h2 strong, #comments .head h3 strong, #twitter h3, #redaction-news h2 strong, #redaction-news-list dt strong",{hover:true,fontFamily:'Baskerville Win95BT'});
        Cufon.replace(".articles dt, #article-info h3",{fontFamily:'Depot Bold',textShadow:'1px 1px #FFFFFF'});
        Cufon.replace("#messages h2,#redaction-comments #content .source-title h3,#news h3,#sidebar .external a strong, .strop h2",{fontFamily:'Baskerville Win95BT'});
    },

    pudelit: function() {
        var shortly = $('#pudelit-list');
        if (shortly.size() > 0) {
            var size = shortly.find('.body li').size();
            shortly.find('.body ul').width(199 * size);
            var list = shortly.find('.body ul').eq(0);
            list.css({'position': 'absolute'});
            var page = 1;
            var pages = Math.round(size / 4);
            var action = ['prev', 'next'];
            action.prev = shortly.find('.prev');
            action.next = shortly.find('.next');
            action.prev.addClass('blocked');
            shortly.find('.stat .count').html(pages);
            function disabled() {
                if (page == 1) {
                    action.prev.addClass('blocked');
                } else {
                    action.prev.removeClass('blocked');
                }
                if (page == pages) {
                    action.next.addClass('blocked');
                } else {
                    action.next.removeClass('blocked');
                }
            }

            action.prev.click(function() {
                if ($(this).hasClass('blocked')) {
                    return false;
                } else {
                    page--;
                    disabled();
                    list.stop().animate({'left': -((199 * 4) * (page - 1))}, 690, 'easeInOutQuad');
                    shortly.find('.stat .index').html(page);
                }
            });

            action.next.click(function() {
                if ($(this).hasClass('blocked')) {
                    return false;
                } else {
                    page++;
                    disabled();
                    item = (page * 4) > size ? ((page * 4) - size) : 4;
                    item = (199 * item) == (199 * 4) ? 0 : (136 * item);
                    list.stop().animate({'left': -(((199 * 4) * (page - 1)) - item)}, 690, 'easeInOutQuad');
                    shortly.find('.stat .index').html(page);
                }
            });            
        }
    },
    
    short: function() {
        var shortly = $('#shortly');
        if (shortly.size() > 0) {
            size = shortly.find('.content li').size();
            shortly.find('.content ul').width(136 * size);
            list = shortly.find('.content ul').eq(0);
            page = 1;
            pages = Math.round(size / 6);
            pages = pages == 0 ? 1 : pages;
            action = ['prev', 'next'];
            action.prev = shortly.find('.prev');
            action.next = shortly.find('.next');
            action.prev.addClass('blocked');
            shortly.find('.stat .count').html(pages);
            function disabled() {
                if (page == 1) {
                    action.prev.addClass('blocked');
                } else {
                    action.prev.removeClass('blocked');
                }
                if (page == pages) {
                    action.next.addClass('blocked');
                } else {
                    action.next.removeClass('blocked');
                }
            }
            disabled();
            action.prev.click(function() {
                if ($(this).hasClass('blocked')) {
                    return false;
                } else {
                    page--;
                    disabled();
                    list.stop().animate({'left': -((136 * 6) * (page - 1))}, 690, 'easeInOutQuad');
                    shortly.find('.stat .index').html(page);
                }
            });

            action.next.click(function() {
                if ($(this).hasClass('blocked')) {
                    return false;
                } else {
                    page++;
                    disabled();
                    var item = (page * 6) > size ? ((page * 6) - size) : 6;
                    item = (136 * item) == (136 * 6) ? 0 : (136 * item);
                    list.stop().animate({'left': -(((136 * 6) * (page - 1)) - item)}, 690, 'easeInOutQuad');
                    shortly.find('.stat .index').html(page);
                }
            });            
        }

        root = $('#short');
        if (root.size() > 0) {
            var $list = root.find('.content .list li');
            var size = $list.size();
            var l = Math.ceil(size / 5);
            var t, o;
            for (i = 0; i < l; i++) {
                o = 0;
                for (j = 0; j < 5; j++) {
                    var q = i * 5 + j;
                    var m = $list.eq(q).height();
                    t = ((q + 1) > size) ? false : true;
                    if (t) {
                        if (m > o) {
                            o = m;
                        }
                    }
                }
                for (j = 0; j < 5; j++) {
                    var q = i * 5 + j;
                    $list.eq(q).height(o);
                    if ((q + 1) == (size)) {
                        continue;
                    }
                }
            }
        }
    },
    
    slide: function() {
        var elements = $('#materials dt');
        var size = elements.size();
        if (size > 1) {
            var interval = 0;
            elements.each(function(i, e) {
                $(this).addClass('element-' + (i + 1));
            }).click(function(event) {
                if ($(this).hasClass('unactive')) {
                    $(this).siblings('dd').stop().animate({opacity: 0}, 600, function() {
                        $(this).css({'z-index': 1});
                    }).css({'z-index': 9});
                    $(this).next().stop().animate({opacity: 1}, 300).css({'z-index': 8});
                    $(this).siblings('dt').addClass('unactive');
                    $(this).removeClass('unactive');
                }
            }).not(':first').addClass('unactive');

            $('#materials dd').css({position: 'absolute', left: 0, 'top': 55, 'margin': 0, 'opacity': 0, 'z-index': 1}).eq(0).css({'opacity': 1, 'z-index': 9});

            function slide() {
                interval = setInterval(function() {
                    element = elements.not('.unactive').eq(0).attr('-data-element');
                    element = size == element ? 1 : parseInt(element) + 1;
                    element = $("#materials dt[-data-element='"+element+"']");
                    if (element.hasClass('unactive')) {
                        element.siblings('dd').stop().animate({opacity: 0}, 600, function() {
                            $(this).css({'z-index': 1});
                        }).css({'z-index': 9});
                        element.next().stop().animate({opacity: 1}, 300).css({'z-index': 8});
                        element.siblings('dt').addClass('unactive');
                        element.removeClass('unactive');
                    }

                }, 7200);
            }

            $('#materials').hover(function() {
                clearInterval(interval);
            }, function() {
                clearInterval(interval);
                slide();
            });
            slide();
        }        
    },
    
    chapters: function() {
        $('.chapter').each(function() {
            var $list = $(this).find('li');
            var size = $list.size();
            var l = Math.ceil(size / 5);
            var t, o;
            for (i = 0; i < l; i++) {
                o = 0;
                for (j = 0; j < 5; j++) {
                    var q = i * 5 + j;
                    var m = $list.eq(q).height();
                    t = ((q + 1) > size) ? false : true;
                    if (t) {
                        if (m > o) {
                            o = m;
                        }
                    }
                }
                for (j = 0; j < 5; j++) {
                    var q = i * 5 + j;
                    $list.eq(q).height(o);
                    if ((q + 1) == (size)) {
                        continue;
                    }
                }
            }

            if (size > 5) {
                $self = $(this);
                $list = $self.find('li:gt(4)');
                $list.hide();
                var $elem = $('<span class="collapse">pokaż wszystkie</span>').insertAfter($self.find('.border h2'));
                var count = 2;
                $elem.click(function() {
                    var $elem = $(this);
                    var slide = count++%2 == 0;
                    $list.slideToggle(300, function() {
                        if (slide) {
                            $elem.html("schowaj");
                        } else {
                            $elem.html("pokaż wszystkie");
                        }
                    });
                    return false;
                })
            }
        })
        return false;
    },

    sharecomments: function() {
        function clickShareStatus(event) {
            var close = true;
            $(this).parents().map(function () { return this.className; }).each(function(e) {
                if (this == 'share-by') {
                    close = false;
                }
            });
            if (close == true) { closeShare(); }
            return close;
        }

        function closeShare() {
            $("*").unbind('click', clickShareStatus);
            $('.share-by').hide();
        }

        $('#redaction-comments .share-by').hide();
        $('#redaction-comments .share').css({'cursor': 'pointer'}).click(function() {
            var t = $(this).parent().find('.share-by');
            if (t.is(':visible')) {
                closeShare();
            } else {
                t.fadeIn(120, function() {
                    $("*:not(.share-by, .share-by *)").bind('click', clickShareStatus);
                });
            }
        });
    },

    shareemail: function() {
        
        function clickShareStatus(event) {
            var close = true;
            $(this).parents().map(function () { return this.id; }).each(function(e) {
                if (this == 'layer-share-email') {
                    close = false;
                }
            });
            if (close == true) { closeShare(); }
            return close;

        }

        function closeShare() {
            $("*").unbind('click', clickShareStatus);
            $('#layer-share-email').fadeOut(300, function() {
                $(this).remove();
            })
        }
        
        function error(e) {
            for (i in e) {
                if (errors[e[i][0]]) {
                    element = $('form#shareemail').find("*[name='"+i+"']");
                    element.parents('.parent').addClass('error');
                    element.unbind('keypress').bind('keypress', function() {
                        p = $(this).parents('.parent');
                        if (p.hasClass('error')) {
                            p.removeClass('error')
                        } else {
                            element.unbind('keypress');
                        }
                    });
                }
            }
        }
        
        $(".share-by .email a").click(function() {
            p = $(this).parents('.cloud-container');
            $('#redaction-comments .share-by').hide();
            $.get($(this).attr('href'), function(content){
                $(p).append(content);
                
                defaults('#shareemail #sender, #shareemail #message, #shareemail #recipient');

                $("*").bind('click', clickShareStatus);

                var propagate = true;

                $('form#shareemail #submit').click(function(){
                    $('form#shareemail').submit();  
                });

                $('form#shareemail').submit(function() {
                    if (propagate) {
                        $('form#shareemail #submit').addClass('loading');
                        propagate = false;
                        $.post('/share/email/', $(this).serialize(), function(response) {
                            if (response.status == true) {
                                $("form#shareemail")[0].reset();
                                $("#layer-share-email .content").html('<p class="message">Wiadomość została wysłana.</p>');
                                setTimeout(closeShare, 1200);
                            } else {
                                error(response.errors);
                            }
                            $('form#shareemail #submit').removeClass('loading');
                            $('#shareemail #sender, #shareemail #message, #shareemail #recipient').blur();
                            propagate = true;
                        }, 'json');             
                    } else {
                        alert('Trwa przetwarzanie danych...');
                    }
                    return false;
                });
            });
            return false;
        });
    },

    comments: function() {
        form = $('form#comment');
        function error(e) {
            for (i in e) {
                if (e[i][0]) {
                    element = form.find("*[name='"+i+"']");
                    element.parents('.parent').addClass('error');
                    element.unbind('keypress').bind('keypress', function() {
                        p = $(this).parents('.parent');
                        if (p.hasClass('error')) {
                            p.removeClass('error')
                        } else {
                            element.unbind('keypress');
                        }
                    });
                    // wrap.prepend('<span class="error">'+errors[e[i][0]]+'</span>');                
                }
            }
        }
        
        function succes(e) {
            root = $('#comments .body ul');
            $(e).each(function(i, d) {
                text = '';
                text += '<li -data-comment="'+d.id+'">';
                text += '<span class="username">'+stripslashes(d.username)+' <em>'+d.created+'</em></span>';
                text += '<span class="quantity"><em class="lower">-</em> <em class="upper">+</em> <strong>'+d.quantity+'</strong></span>';
                text += '<p>'+stripslashes(d.comment)+'</p>';
                text += '</li>';
                $(text).prependTo(root);
            });
            // document.getElementById('comment').reset();
        }
        
        defaults('#comments #email, #comments #username, #comments #comment');
        
        $('div#comments .head').click(function() {
            p = $(this).parents('div#comments');
            if (p.hasClass('visible')) {
                p.removeClass('visible');
                p.find('.form, .body').slideUp(300);
            } else {
                p.addClass('visible');
                p.find('.form, .body').slideDown(300);
                $.scrollTo('#comments', 320);
            }
        });

        var clicked = cookie.read('comments');
        clicked = clicked ? clicked.split('+') : [];

        for(i in clicked) {
            $("#comments li[-data-comment='"+clicked[i]+"'] .quantity em").remove();
        }

        $('#comments .quantity em').click(function() {          
            self = $(this);
            id = $(this).parents('li').attr('-data-comment');
            method = $(this).attr('class');
            if ($.inArray(id, clicked) == -1) {
                $.get('/comments/quantity/resource/' + id + '/method/' + method + '/', function(response) {
                    if (isNaN(response) == false) {
                        response = response.toString();
                        data = response < 0 ? response : '+' + response;
                        self.siblings('strong').html(data);
                        self.parent().find('em').remove();
                    }
                }, 'json');
                clicked.push(id);
                cookie.write('comments', clicked.join('+'), 7);
            }
            return false;
        });
        
        var propagate = true;
        
        $('form#comment').submit(function() {
            if (propagate) {
                $('form#comment #submit').addClass('loading');
                propagate = false;
                $.post('/comments/', $(this).serialize(), function(response) {
                    if (response.status == true) {
                        $("form#comment")[0].reset();
                        $('#comments #email, #comments #username, #comments #comment');
                        $.scrollTo('#comments .body', 320);
                        succes(response.data);
                    } else {
                        error(response.errors);
                    }
                    $('form#comment #submit').removeClass('loading');
                    $('#comments #email, #comments #username, #comments #comment').blur();
                    propagate = true;
                }, 'json');             
            } else {
                alert('Trwa przetwarzanie danych...');
            }
            return false;
        });
    }
}

var Librarian = {
    multimedia: function(action, label, value) {
        value = isNaN(value) ? 0 : value;
        var tracker = _gat._getTracker(customTracker);
        tracker._initData();
        tracker._trackEvent('Multimedia', action, label, parseInt(value));
    }
}

$().ready(function() {
    window['language'] = $('body').attr('id').split('-')[1];
    window['message'] = window['message'][language];
    engine.start();    
    common.start();
    livesearch.start();
    engine.print();

    $(".share-by a").attr('target', '_blank');

    var track = {
        'share': {
            once: true, category: 'Social Media', action: function(event){ return $(this).attr('-data-action'); }, label: function(){ return $(this).attr('-data-label'); }
        },
        comment: {
            'open': {
                once: true, category: 'Interakcja', action: 'Rozwiń', label: function(event){ return $('title').html().split('|')[0].trim(); }
            },
            'submit': {
                once: true, category: 'Interakcja', action: 'Dodaj', label: function(event){ return $('title').html().split('|')[0].trim(); }
            },
            'vote': {
                once: true, category: 'Interakcja', action: 'Oceń', label: function(event){ return $('title').html().split('|')[0].trim(); }
            }
        }
    }

    $(".share-by a").trackEvent(track.share);
    
    $('#comments .head').trackEvent(track.comment.open);
    $('#comments #submit').trackEvent(track.comment.submit);
    $('#comments .body .quantity em').trackEvent(track.comment.vote);
            
    // $('.article img').hover(function() {
    //  $(document).bind("contextmenu",function(e){return false;});
    // }, function() {
    //  $(document).unbind("contextmenu");
    // });
    // 
    // $('#layer img').live('mouseover', function() {
    //  $(document).bind("contextmenu",function(e){return false;});
    // });
    // 
    // $('#layer img').live('mouseout', function() {
    //  $(document).unbind("contextmenu");
    // });

    $("a[rel='external']").attr('target', '_blank');

    setTimeout(function() {
        $('.vertical-align').each(function(i, e) {
            $(e).parent().css({'position': 'relative'});
            $(e).css({'top': '50%', 'left': '0', 'marginTop': -($(e).height() / 2), 'position': 'absolute'});
        }); 
    }, 600);
});

