
String.prototype.capitalize = function() {
    return this.slice(0,1).toUpperCase() + this.slice(1)
}
String.prototype.format = function() {
    var pattern = /\{\d+\}/g;
    var a = arguments;
    return this.replace(pattern,
    function(capture) {
        return a[capture.match(/\d+/)];
    });
};
Array.prototype.getIndex = function(argument) {
    for (i in this) {
        if (this[i] == argument) {
            return i;
        }
    }
    return false;
}


    var methods = {
        getOptionValue: function(value, elem, event) {
            if ($.isFunction(value)) {
                value = value.call(elem, event);
            }
            return value;
        },
        getCategory: function() {
            return this.nodeName;
        },
        getAction: function(event) {
            return event.type;
        },
        getLabel: function() {
            var self = $(this);
            if (self.is("a")) {
                return self.attr("href");
            }
            else if (self.is("input")) {
                return self.val();
            }
            else if (self.attr("id")) {
                return self.attr("id");
            }
            else {
                return self.text();
            }
        }
    };

    $.expr[':'].external = function(elem) {
        return (elem.host && elem.host !== location.host) === true;
    };

    $.fn.trackEvent = function(options) {
        var settings = {
            eventType : "click",
            once      : true,
            category  : methods.getCategory,
            action    : methods.getAction,
            label     : methods.getLabel,
            value     : 1
        };

        if (options) $.extend(settings, options);

        this.each(function(i) {
            var eventHandler = function(event) {
                var category = methods.getOptionValue(settings.category, this, event);
                var action   = methods.getOptionValue(settings.action  , this, event);
                var label    = methods.getOptionValue(settings.label   , this, event);
                var value    = methods.getOptionValue(settings.value   , this, event);
                // _gaq.push(['_trackEvent', category, action, label]);
                var tracker = _gat._getTracker(customTracker);
                tracker._initData();
                tracker._trackEvent(category, action, label, value);
            };

            if (settings.once) {
                $(this).one(settings.eventType, eventHandler);
            } else {
                $(this).bind(settings.eventType, eventHandler);
            }
        });
        return this;
    };

var translation = {
    pl: {
        lightbox: {
            prev: 'poprzednie', 
            next: 'następne',
            close: 'zamknij'
        },
		subscription: {
			ok: 'zostałeś zapisany!',
			error: 'BŁĄD: spróbuj ponownie'
		}
    },
    en: {
        lightbox: {
            prev: 'previous',
            next: 'next',
            close: 'close'
        },
		subscription: {
			ok: 'subscribed!',
			error: 'ERROR: please try again'
		}
    }
}

var env = {'city': null};

jQuery.fn.defaults = function(b) {
	return this.each(function() {
		if (this.type != "text" && this.type != "password" && this.type != "textarea") {
			return;
		}
		var a = this;
		if (this.value == "") {
			this.value = b;
		} else {
			return;
		}
		$(this).bind("focus", function() {
			if (this.value == b || this.value == "") {
				this.value = "";
			}
		});
		$(this).bind("blur", function() {
			if (this.value == b || this.value == "") {
				this.value = b;
			}
		});
		$(this).parents('form').submit(function() {
			if (a.value == b || a.value == "") {
				a.value = b;
			}
		});
	});
};

jQuery.fn.center = function(params) {
	var options = {
		vertical: true,
		horizontal: true
	}
	op = jQuery.extend(options, params);
	return this.each(function() {
		var $self = jQuery(this);
		var width = $self.width();
		var height = $self.height();
		var paddingTop = parseInt($self.css("padding-top"));
		var paddingBottom = parseInt($self.css("padding-bottom"));
		var padding = parseInt((parseInt($self.css("padding-left")) + parseInt($self.css("padding-right"))) / 2);
		var borderTop = parseInt($self.css("border-top-width"));
		var borderBottom = parseInt($self.css("border-bottom-width"));
		var mediaBorder = parseInt((borderTop + borderBottom) / 2);
		var mediaPadding = parseInt((paddingTop + paddingBottom) / 2);
		var positionType = $self.parent().css("position");
		var halfWidth = parseInt((((width / 2) + padding) * (-1)));
		var halfHeight = parseInt(((height / 2) * (-1)) - (mediaPadding));
		var cssProp = {
			position: 'absolute'
		};
		if (op.vertical) {
			cssProp.height = height;
			cssProp.top = '50%';
			cssProp.marginTop = halfHeight;
		}
		if (op.horizontal) {
			cssProp.width = width;
			cssProp.left = '50%';
			cssProp.marginLeft = halfWidth;
		}
		if (positionType == 'static') {
			$self.parent().css("position", "relative");
		}
		$self.css(cssProp);
	});
};

jQuery.fn.layer = function(options) {
	this.load;
	var defaults = {
		type: 'get',
		handler: 'href',
		overlay: 0.8,
		animation: 0,
		center: true,
		callbackOpen: false,
		callbackLoad: false,
		callbackClose: false,
		callbackError: false,
		customClass: '',
		alternativeResponse: false
	};
	var settings = $.extend({},
	defaults, options);
	var local = this.selector;
	var callback = function(name) {
		functionName = settings[name];
		if (typeof functionName === 'function') {
			functionName(local);
			return true;
		}
		return false;
	};
	var closeWindow = function() {
		$('#layer-overlay').animate({
			opacity: 0
		}, 1, function() {
			$(this).remove();
		});
		$('#layer-window').animate({
			opacity: 0
		},
		1, function() {
			callback('callbackClose');
			$(this).remove();
		});
		return false;
	};
	var bindClose = function(event) {
		if (event.keyCode == 27) {
			closeWindow();
			return false;
		}
	}
	var response = function(response) {
		var overlay = jQuery('<div id="layer-overlay"></div>');
		overlay.appendTo('body').addClass(settings.custom).css({
			width: $(document).width(),
			height: $(document).height(),
			opacity: 0
		}).animate({
			opacity: settings.overlay
		}, 1);
		var content = $('<div id="layer-window"></div>');
		content.appendTo('body').addClass(settings.customClass).css({
			opacity: 0
		}).html(response).animate({
			opacity: 1
		},
		settings.animation).center();
		$('#layer-overlay, #layer-window .terminate').live('click', closeWindow);
		return {
			content: content,
			overlay: overlay
		};
	};
	var request = function(address) {
		$.ajax({
			url: address,
			type: settings.type,
			data: (settings.data),
			global: false,
			dataType: "html",
			success: function(data) {
				response(data);
				callback('callbackLoad');
			},
			error: function(data) {
				callback('callbackError');
			}
		});
	};
	$(local).live('click', function() {
		callback('callbackOpen');
		fn = settings['alternativeResponse'];
		if (typeof fn === 'function') {
			response('<div class="image"></div>');
			fn($(this));
		} else {
			request($(this).attr(settings.handler));
		}
		return false;
	});
	return this;
};

new function() {
    $.fn.validate = {
        init: function(element) {
            if ($(element).is("[type='text']") || $(element).is("[type='password']") || $(element).is("textarea")) {
                // element.focus();
                if ($(element).data('required') == true) {
                    this.proced(element);
                } else if ($(element).data('required') == false && element.value.length == 0) {

                } else {
                    if (element.value.length == 0) {
                        this.success(element);
                    } else {
                        this.proced(element);
                    }
                }
            }
            if ($(element).is("[type='checkbox']")) {
                if ($(element).data('required') == true) {
                    if ($(element).is(':checked')) {
                        this.success(element);
                    } else {
                        this.error(element, 'notGreaterThan');
                    }
                }
            }
        },
        proced: function(element) {
            if ($(element).is("[type='text'], textarea")) {

    			if (element.value == $(element).data('default')) {
    			    
    				element.value = "";
    			}
            }; 
            switch ($(element).data('validate')) {
                case 'email':
                    this.email(element);
                    break;
                case 'phone':
                    this.phone(element);
                    break;
                case 'string':
                    this.string(element);
                    break;
                case 'postcode':
                    this.postcode(element);
                    break;
                case 'nip':
                    this.nip(element);
                    break;
                default:
                    this.string(element);
                    break;
            }
        },
        string: function(e) {
			if (e.value.length == 0) {
				$.fn.validate.error(e, 'isEmpty');
			} else if (e.value.length < 1 && e.value.length > 0) {
				$.fn.validate.error(e, 'stringLengthTooShort');
			} else {
				$.fn.validate.success(e);
			}
        },
        phone: function(e) {
            var rule = /^[0-9 ]{9,12}$/;
            if (e.value.match(rule)) {
                $.fn.validate.success(e);
            } else {
                $.fn.validate.error(e, 'invalidPhone');
            };
        },
        postcode: function(e) {
            var rule = /^[0-9]{2}\-[0-9]{3}$/;
            if (e.value.match(rule)) {
                $.fn.validate.success(e);
            } else {
                $.fn.validate.error(e, 'invalidPostcode');
            };
        },
        email: function(e) {
            var rule = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
            if (e.value.match(rule)) {
                $.fn.validate.success(e);
            } else {
                $.fn.validate.error(e, 'emailAddressInvalidFormat');
            };
        },
        nip: function(e) {
            if(!e.value.match( /^[0-9]{3}-[0-9]{2}-[0-9]{2}-[0-9]{3}$/ ) && !e.value.match( /^[0-9]{3}-[0-9]{3}-[0-9]{2}-[0-9]{2}$/ ) && !e.value.match( /^[0-9]{10}$/ )) {
                $.fn.validate.error(e, 'invalidNip');
            }
            var my_nums=e.value.replace(/-/g,'');
            var valid_nums="657234567";
            var sum=0;
            for (var temp=8;temp>=0;temp--) {
                sum += (parseInt(valid_nums.charAt(temp)) * parseInt(my_nums.charAt(temp)));
            }
            if ((sum % 11) == 10 ? false : ((sum % 11) == parseInt(my_nums.charAt(9)))) {
                $.fn.validate.success(e);
                return false;
            }
            $.fn.validate.error(e, 'invalidNip');
        },
        success: function(e) {
            $(e).removeClass('error').siblings('label, .label').removeClass('error');
            return true;
        },
        error: function(e, message) {
            $(e).addClass('error').siblings('label, .label').addClass('error');
            return false;
        },
        validate: function(e) {
        }
    };
};


var photos = [];
var photosIndex = 0;

Propagate = function() {
    this.status = true,

    this.start = function() {
        this.status = false;
    }

    this.stop = function() {
        this.status = true;
    }

    this.state = function() {
        return this.status;
    }
};

function lightbox() {

    var s = this;

    this.index = 0;
    this.photos = [];
    
    this.next = function() {
        $('#lightbox .description').fadeOut(0);
        $('#lightbox .image img').fadeOut('normal', 0, function() { $(this).remove(); });
        s.index++;
        s.index = s.index == s.photos.length ? 0 : s.index;
        s.load(s.photos[s.index]);
        return false;
    };

    this.prev = function() {
        $('#lightbox .description').fadeOut(0);
        $('#lightbox .image img').fadeOut('normal', 0, function() { $(this).remove(); });
        s.index--;
        s.index = s.index < 0 ? (s.photos.length - 1) : s.index;
        s.load(s.photos[s.index]);
        return false;
    };

    this.start = function(target) {
        var b = $('<div id="lightbox"></div>');
        $(".lightbox[data-lightbox='"+$(target).data('lightbox')+"']").each(function(i, e) {
            s.photos.push($(this).attr('href'));
        });
        s.index = s.photos.getIndex($(target).attr('href'));
        b.append('<div class="content"><span class="image"></span> <a class="prev" title="'+i18n.lightbox.prev.capitalize()+'"></a> <a class="next" title="'+i18n.lightbox.next.capitalize()+'"></a></div>');
        b.append('<div class="description"><span class="index">1</span>/<span class="count">'+s.photos.length+'</span></div>')
        b.append('<div class="close"><a class="prev">< '+i18n.lightbox.prev+'</a> <a class="next">'+i18n.lightbox.next+' ></a><a class="terminate" title="" href="#">'+i18n.lightbox.close+'</a></div>');
        var a = {height: $(document).height(), width: $(document).width()};
        $('<div id="overlay"></div>').animate({opacity: 0},0).prependTo("body").css(a).animate({opacity: 0.9},0, function() {
            $(b).animate({opacity: 0},0).prependTo("body").animate({opacity: 1},1, function() {
                if (s.photos.length == 0) {
                    $('#lightbox .next, #lightbox .prev, #lightbox .description').remove();
                };
                $('#lightbox .image').click(function() {
                    $("#lightbox").fadeOut("90", function() {
                        $("#overlay").fadeOut(1, function() {
                            $("#lightbox, #overlay").remove();
                        });
                    });
                }).css({'cursor': 'pointer'});
                s.load(target, "#lightbox");
                s.hide();
                $('#lightbox .next').click(function() {
                    s.next();
                });
                $('#lightbox .prev').click(function() {
                    s.prev();
                });
            }).center();
        });
        return false;
    };

    this.hide = function() {
        $("#overlay, #lightbox .terminate").click(function() {
            $("#lightbox").fadeOut("90", function() {
                $("#overlay").fadeOut(5, function() {
                    $("#lightbox, #overlay").remove();
                });
            });
            return false;
        });
    };

    this.load = function(target, c) {
        var e = new Image();
        var a;
        e.onload = function() {
            var h = e.width;
            var f = e.height;
            var g = $('#lightbox').attr('index', target).find(".image");
            var i = $('<img src="' + target + '" />');
            i.attr("width", h).attr("height", f).appendTo(g).hide(0);
            e.width = h;
            e.height = f;
            b(h, f);
            e.onload = function() {};
        };
        e.src = target;
        function b(i, f, d) {
            var h = i / 2;
            var g = f / 2;
            $('#lightbox').animate({width: i, height: f + 22, marginLeft: -h, marginTop: -g, left: "50%", opacity: 1}, 1, function() {
                $('#lightbox .content .prev').css({'width': (i/2), 'height' : f});
                $('#lightbox .content .next').css({'width': (i/2), 'height' : f, 'left': (i/2)});
                $(this).find('.image img, .close, .description').fadeIn();
                $(this).find('.index').html((parseInt(s.index) + 1));
            }).append;
        }
    };
}

var librarian = {
	
    track: function(action, label) {
        var city = env.city.capitalize();
        var category = 'MulWykl' + city;
        var action   = action + city;
        var label    = label + ' ' + city;
        var tracker  = _gat._getTracker(customTracker);
        tracker._initData();
        tracker._trackEvent(category, action, label);
    },
	
	trackGalleryVideo: function(action, label) {
        var city = env.city.capitalize();
        var category = 'MulGaleria';
        var tracker  = _gat._getTracker(customTracker);
        tracker._initData();
        tracker._trackEvent(category, action, label);
    },

    click: function(target, action, label) {
        var city = env.city.capitalize();
        var category = 'MenuKursu';
        var tracker  = _gat._getTracker(customTracker);
        tracker._initData();
        tracker._trackEvent(category, action, label);
        document.location.href = '#anchor-' + target;
    },
	
	videoplayer: function(action, label, value) {
        value = isNaN(value) ? 0 : value;
        var tracker = _gat._getTracker(customTracker);
        tracker._initData();
        tracker._trackEvent('VideoPlayer', action, label, parseInt(value));
    }

}


var engine = {
    start: function() {

		this.validate();
        this.fixes();
        this.navigation();
		
        this.select('#search-events select', function(element) {
            var rules = {};
            $('#search-events select').each(function(i, e) {
                var key = $(this).attr('name');
                key = /\[(.*)\]/.exec(key)[1];
                var val = $(e).find('option:selected').val();
                if (val) {
                    rules[key] = val;
                } else {
                    rules[key] = false;
                }
            });

            var target = $('#search-events-results li');
            target.hide().filter(function(index) {
                for (rule in rules) {
                    data = $(this).data(rule);
					data = typeof data === 'string'
                        ? data.split(',')
                        : data;
                    temp = typeof data === 'object' 
                        ? !(data.getIndex(rules[rule])) 
                        : data != rules[rule];
                    if (rules[rule] && temp) {
                        return false;
                    }
                }
                return true;
            }).show();
        });
    },
    
    fixes: function() {
        $('#main table tr:odd td').addClass('colored');
        $('.inline-image').each(function() {
            $container = $(this);
            $info = $(this).find('.info');
            if ($container.find('img').size() > 0) {
                var image = new Image();
                image.onload = function() {
                    $info.width(($container.width()));                    
                    image.onload = function() {};
                };
                image.src = $container.find('img').first().attr('src');
            } else {
                $info.width(($container.width()));    
            }
			
			 $(this).find('.zoom, .rotate').click(function() {
                $(this).parents('.inline-image').find('a').first().trigger('click');
            }).css({cursor: 'pointer'});
        });
    },
    
    hover: function(target) {
        $(target).hover(function() {
            $(this).animate({'opacity': 0.65}, 180);
        }, function() {
            $(this).animate({'opacity': 1}, 180);
        });
    },
    
    select: function(target, callback) {
        zindex = 999;
        $(target).each(function(i, target) {
            $(target).wrap('<div class="wrap-select" name="'+$(target).attr('name')+'"></div>');
            container = $(target).parent('.wrap-select');
            selected = container.find('option:selected');
            container.append('<span class="selected"><span class="text">'+selected.html()+'</span> <span class="icon"></span></span>');
            selection = $('<ul class="selection"></ul>').appendTo(container);
            container.find('option').each(function(i, e) {
                selection.append('<li><a data-value='+$(e).val()+'>'+$(e).html()+'</a></li>');
            });
            container.find("a[data-value='"+selected.val()+"']").parent().hide();
            container.find('li a').click(function(element) {
                var self = $(this);
                var v = $(this).data('value');
                var text = $(this).html();
                var core = $(this).parents('.wrap-select');
                core.find('.selected .text').html(text);
                core.find("option[value='"+v+"']").attr('selected', true);
                core.find('ul').slideUp(300, function() {
                    if (typeof callback == 'function' ) {
                        callback(self);
                    };
                });
                $(this).parent().hide().siblings().show();
                return false;
            });
            container.find('.selected').click(function() {
                core = $(this).parents('.wrap-select');
                if (core.find('ul').is(':visible')) {
                    core.find('ul').slideUp(300);
                } else {
                    core.find('ul').css({'z-index': zindex++}).slideDown(300);
                }
            });
        });
    },
    
    navigation: function() {
        $('#subnav li a').each(function(i, e) {
            if ($(this).siblings().size() > 0) {
                $(this).parent().addClass('toggle');
            };
        });
        $('#subnav>ul>.toggle>a').click(function() {
            $(this).parents('ul').find('ul:visible').slideUp(300);
            $(this).siblings('ul').slideDown(300);
            return false;
        });
        $('#subnav>ul>li>ul>li>a').click(function() {
            if ($(this).siblings().size() > 0) {
                $(this).siblings('ul').toggle(300);
                return false;
            }
        });
        $('#subnav a.active').parents('ul').show();  
    },
    
    fonts: function() {

        sIFR.forceTextTransform = true;
        var gotham = {
            'ultra': {
                src: '/script/sifr_gotham_ultra.swf'    
            },
            'light': {
                src: '/script/sifr_gotham_light.swf'
            },
            'book': {
                src: '/script/sifr_gotham_book.swf'
            },
            'extra': {
                src: '/script/sifr_gotham_extralight.swf'
            }
        };

        sIFR.replace(gotham.extra, {
            selector: '.errorpage h2, .errorpage h3, .errorpage h4',
            css: '.sIFR-root { color: #FFFFFF; }',
            wmode: 'transparent'
        });

        sIFR.activate(gotham.ultra, gotham.light);
        sIFR.replace(gotham.ultra, {
            selector: 'h2, #side .section .title',
            css: '.sIFR-root { text-transform: uppercase; }',
            wmode: 'transparent'
        });
        sIFR.replace(gotham.ultra, {
            selector: 'h5',
            wmode: 'transparent'
        });
        sIFR.replace(gotham.light, {
            selector: 'h3, h4',
            css: '.sIFR-root { color: #626262;}, a {color: #626262; text-decoration: none}, a:hover {text-decoration: underline;color: #626262;}',
            wmode: 'transparent'
        });
        sIFR.replace(gotham.light, {
            selector: '#homepage p',
            css: '.sIFR-root { text-transform: uppercase; color: #626262; }',
            wmode: 'transparent'
        }); 
        
        sIFR.replace(gotham.light, {
            selector: '#anchors',
            css: '.sIFR-root { color: #626262;}, a {color: #626262; text-decoration: none}, a:hover {text-decoration: underline;color: #626262;}',
            wmode: 'transparent'
        });
        
    },

    formValidator: function(form) {
        $(form).each(function(i, form) {
            $(form).find('input, textarea').not("[data-validate='false']").blur(function() {
                $(this).validate.init(this);
            });
        });

        $(form).submit(function() {
            $(this).find('input, textarea').not("[data-validate='false']").each(function() {
                $(this).trigger('blur');
            });
            var status = $(this).find('.error').size() == 0 ? true : false;
			
			if(status && $(this).attr('id') == 'questionForm') {
				// send question form
				var name = $('#questionForm #question-name').val();
				var surname = $('#questionForm #question-secondname').val();
				var email = $('#questionForm #question-email').val();
				var message = $('#questionForm #question-message').val();
				var lang = $('#questionForm #lang').val();
				var branch = $('#questionForm #branch').val();
				var url = $('#questionForm #url').val();
				var d = { 'name': name, 'surname': surname, 'email': email, 'message': message, 'lang': lang, 'branch': branch, 'url': url};
				$('#question-form').remove();
				$('#confirmation').show();
				$.post('/helper/ajaxsendcontactform', d, function(response){
					_gaq.push(['_setCustomVar', 1, 'User Type', 'Pytanie', 1]);
					setTimeout(function() {
						$('#fancybox-overlay').trigger('click');
					}, 2000);
					if (response.status == true) {
						//
					} else {
						//
					}
				}, 'json');
				return false;
			}
			
			if(status && $(this).attr('id') == 'courseUpdatesForm') {
				// subscribe user to course updates
				var email = $('#courseUpdatesForm #entry-email').val();
				var courseId = $('#courseUpdatesForm #courseId').val();
				var d = { 'email': email, 'courseId': courseId};
				$('#courseUpdatesForm #entry-email').val('...');
				$.post('/helper/ajaxsubscribetocourseupdates', d, function(response){
					if (response.status == true) {
						
						var GAlabel = $("h2").text() + ' ' + env.city.capitalize() + ' Add';
						_gaq.push(['_trackEvent', 'Newsletter', 'Dodaj', GAlabel]);
						
						$('#courseUpdatesForm #entry-email').val(i18n.subscription.ok);
					} else {
						
						$('#courseUpdatesForm #entry-email').val(i18n.subscription.error);
					}
				}, 'json');
				return false;
			}
			
			if(status && $(this).attr('id') == 'remindersForm') {
				// subscribe user to course updates
				var email = $('#remindersForm #entry-email').val();
				var branchId = $('#remindersForm #branchId').val();
				var d = { 'email': email, 'branchId': branchId};
				$('#remindersForm #entry-email').val('...');
				$.post('/helper/ajaxsubscribetoreminders', d, function(response){
					if (response.status == true) {
						$('#remindersForm #entry-email').val(i18n.subscription.ok);
					} else {
						
						$('#remindersForm #entry-email').val(i18n.subscription.error);
					}
				}, 'json');
				return false;
			}
			
            return status;
        });
    },

    validate: function() {

        $('body').delegate('.submit', 'click', function() {
            $(this).parents('form').submit();
            return false;
        });

        this.formValidator('form');

        // $('#search-query').attr('data-required', true);
        // $('#newsletter-email').attr('data-required', true).attr('data-validate', 'email');
        
        function validateNewsletter(button, callback) {
            $(button).parents('form').find('input').each(function(i, element) {
                $(element).validate.init(element);
                $(element).blur();
            });
            if ($(button).parents('form').find('.error').size() == 0) {
                if (typeof callback == 'function') {
                    callback();
                }
            }
            return false;
        }
        
        $('#newsletter .subscribe').click(function() {
            return validateNewsletter(this, function() {
				_gaq.push(['_trackEvent', 'Newsletter', 'Dodaj', 'Freshmail Add']);
                $('#newsletter').submit();
            });
        });
    }
};

var gallery = {

    homepage: function() {
        var root = $('#homepage .gallery');
        if (root) {
            var wrap = $(root).find('ul');
            list = wrap.find('li');
            wrap.width(list.length * 564)
            var index = 0;
            count = (list.length);

            list.click(function() {
                document.location.href = $(this).data('link');
            }).css({cursor: 'pointer'});		

            function show(element) {
                if (element.children().size() == 0) {
                    element.html('<img src="'+element.data('image')+'" />');        
                }
            }

            function info(element) {
                $('.section.gallery .author strong').html($(element).data('author'));
                $('.section.gallery .button.photo').attr('href', $(element).data('link'));
            }

            show(list.eq(0));
            info(list.eq(0));

			root.find('.preview.prevs, .preview.nexts').hide();
			
            root.find('.prev').click(function() {
                index--;
                if (index < 0) {
                    index = (count - 1);
                }
                wrap.stop().animate({'left': -(index * 564)}, 300, function() {
                });
                root.find('.preview').stop().animate({opacity: 0}, 120, function() {
                    $(this).empty().css({opacity: 1});
                });
                show(list.eq(index));
                info(list.eq(index));
                return false;
            }).hover(function() {
                var tmp = (index - 1);
                if (tmp < 0) {
                    tpm = index;
                }
                e = list.eq(tmp).data('image').split('.');
                root.find('.preview.nexts').empty().hide();
                root.find('.preview.prevs').empty().fadeOut(0).html('<img src="'+e[0]+'-preview.'+e[1]+'" />').fadeIn(300);
            }, function() {
                root.find('.preview.prevs').empty().hide();
            });

            root.find('.next').click(function() {
                index++;
                if (index >= count) {
                    index = 0;
                }
                wrap.stop().animate({'left': -(index * 564)}, 300, function() {
                });
                root.find('.preview').stop().animate({opacity: 0}, 120, function() {
                    $(this).empty().css({opacity: 1});
                });
                show(list.eq(index));
                info(list.eq(index));
                return false;
            }).hover(function() {
                var tmp = (index + 1);
                if (tmp >= count) {
                    tmp = 0;
                }
                e = list.eq(tmp).data('image').split('.');
                root.find('.preview.prevs').empty().hide();
                root.find('.preview.nexts').empty().fadeOut(0).html('<img src="'+e[0]+'-preview.'+e[1]+'" />').fadeIn(300);
            }, function() {
                root.find('.preview.nexts').empty().hide();
            }); 
        }
    },
    
    article: function() {
        $('.article-page .gallery').each(function(i, gallery) {
            var root = $(gallery);
            var next = root.find('.next');
            var prev = root.find('.prev');
            var wrap = root.find('.wrap ul');
            var list = wrap.find('li');
            var length = list.length;
            var size = (length % 2) > 0 ? length + 1 : length;
            wrap.width((size / 2) * 129).height(86 * 2);
            var page = Math.ceil(length / 8);
            var index = 0;
            function controls() {
                if (index == 0) {
                    prev.hide();
                } else {
                    prev.show();
                }
                if (index >= (page - 1)) {
                    next.hide();
                } else {
                    next.show();
                }
                wrap.animate({'left': -(index * (129 * 4))}, 300);
            }
            if (page > 1) {
                prev.hide();
                prev.click(function() {
                    index--;
                    if (index < 0) {
                        index = 0;
                    } else {
                        controls();
                    }
                    return false;
                });
                next.click(function() {
                    index++;
                    if (index > (page - 1)) {
                        index = page;
                    } else {
                        controls();
                    }
                    return false;
                });
            } else {
                prev.hide();
                next.hide();
            }
        });
    }
};

$(document).ready(function() {
	var propagate = new Propagate();
    var lang = (lang = $('body').attr('id')) ? lang.split('-')[1] : 'pl';
    env.city = $('body').data('city');
    i18n = eval('translation.' + lang);
    engine.start();

    $('#search-events .selection a').trackEvent({
        category: 'WyszKurs' + env.city.capitalize(),
        action: function() {
            return $(this).parents('.wrap-select').siblings('label').data('title') + 'Klik' + env.city.capitalize();
        }, 
        label: function() {
            return $(this).text() + ' ' + env.city.capitalize();
        }
    });


    var eventTrackingOptions = {
        once : false,
        category : "WyszKurs" + env.city.capitalize(),
        label : function(event){ return $(this).text(); }
    };

    // $('ul.selection a').trackEvent(eventTrackingOptions)

    $("input[data-default]").each(function(i, e) {
        $(e).defaults($(e).data('default'));
    });
	
    if (document.getElementById('homepage')) {
        gallery.homepage();    
    };
    if ($('.article-page').size() > 0) {
        gallery.article();    
    };
    $('#have-a-question').fancybox({
        onComplete: function() {
            engine.formValidator('#have-a-question-layer form');
            $("#have-a-question-layer *[data-default]").each(function(i, e) {
                $(e).defaults($(e).data('default'));
            });
        }
    });
	
	$("a.lecturer-layer").fancybox({
		ajax : {type: "GET"},
		onComplete: function() {
			$('.videolightbox').each(function(i, e) {
				$(e).fancybox({
					'overlayColor'		: '#000',
					'overlayOpacity'	: 0.9,
					'autoScale'			: false,
					'changeSpeed'		: 1,
					'changeFade'		: 1,
					'transitionIn'		: 'none',
					'transitionOut'		: 'none',
					'speedOut'			: 1,
					'type'				: 'swf',
					'href'				: '/flash/videoplayer.swf',
					'width'				: 954,
					'height'			: 650,
					'bgcolor'			: '#000',
					'padding'			: 0,
					'swf' : {
						'allowfullscreen' : 'true',
						'flashvars': 'video_file='+$(e).attr("lightbox-videofile")
					}
				});
			});
		}
	});
    
    $('.action-reset-form').click(function() {
        $('#search-events a[data-value=""]').each(function() {
            $(this).trigger('click');
        });
    });
    
    $('.lightbox').each(function(i, e) {
       if ($(e).data('lightbox')) {
           $(e).attr('rel', $(e).data('lightbox'));
       } 
    });
    
    $('.lightbox').fancybox({
        'overlayColor'		: '#000',
		'overlayOpacity'	: 0.9,
		'autoScale'			: false,
		'changeSpeed'		: 1,
		'changeFade'		: 1,
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'speedOut'			: 1
    });

	$('.videolightbox').each(function(i, e) {
		$(e).fancybox({
			'overlayColor'		: '#000',
			'overlayOpacity'	: 0.9,
			'autoScale'			: false,
			'changeSpeed'		: 1,
			'changeFade'		: 1,
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'speedOut'			: 1,
			'type'				: 'swf',
			'href'				: '/flash/videoplayer.swf',
			'width'				: 954,
			'height'			: 650,
			'bgcolor'			: '#000',
			'padding'			: 0,
			'swf' : {
				'allowfullscreen' : 'true',
				'flashvars': 'video_file='+$(e).attr("lightbox-videofile")
			}
		});
	});
	
	$('.panolightbox').each(function(i, e) {
		$(e).fancybox({
			'overlayColor'		: '#000',
			'overlayOpacity'	: 0.9,
			'autoScale'			: false,
			'changeSpeed'		: 1,
			'changeFade'		: 1,
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'speedOut'			: 1,
			'width'				: 900,
			'height'			: 600,
			'bgcolor'			: '#000',
			'padding'			: 40,
			'swf' : {
				'allowfullscreen' : 'true'
			}
		});
	});
	
	$("#bannerlightbox").fancybox({'overlayOpacity'	: 0.3}).trigger('click');

	
    engine.hover('#foot a, #partners a, #newsletter a, #search a');
    var zindex = 1609;
    $('form .row').each(function(i, e) {
        $(this).css({'z-index': zindex--});
    })
	$("body").delegate('.button.terminate', 'click', function() {
	    $('#fancybox-overlay').trigger('click');
	    return false;
	});

	$('.image-switch').each(function() {
		var image = $(this).find('img');
		if (image.filter(':gt(0)').size() > 0) {
			image.filter(':gt(0)').hide();
			$(this).hover(function() {
				image.eq(0).hide();
				image.eq(1).show();
			}, function() {
				image.eq(0).show();
				image.eq(1).hide();
			})
		};

	})
});

engine.fonts();
