/*
 * jQuery hashchange event - v1.3 - 7/21/2010
 * http://benalman.com/projects/jquery-hashchange-plugin/
 *
 * Copyright (c) 2010 "Cowboy" Ben Alman
 * Dual licensed under the MIT and GPL licenses.
 * http://benalman.com/about/license/
 */
(function($,e,b){var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);function a(j){j=j||location.href;return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")}$.fn[c]=function(j){return j?this.bind(c,j):this.trigger(c)};$.fn[c].delay=50;g[c]=$.extend(g[c],{setup:function(){if(d){return false}$(f.start)},teardown:function(){if(d){return false}$(f.stop)}});f=(function(){var j={},p,m=a(),k=function(q){return q},l=k,o=k;j.start=function(){p||n()};j.stop=function(){p&&clearTimeout(p);p=b};function n(){var r=a(),q=o(m);if(r!==m){l(m=r,q);$(e).trigger(c)}else{if(q!==m){location.href=location.href.replace(/#.*/,"")+q}}p=setTimeout(n,$.fn[c].delay)}$.browser.msie&&!d&&(function(){var q,r;j.start=function(){if(!q){r=$.fn[c].src;r=r&&r+a();q=$('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){r||l(a());n()}).attr("src",r||"javascript:0").insertAfter("body")[0].contentWindow;h.onpropertychange=function(){try{if(event.propertyName==="title"){q.document.title=h.title}}catch(s){}}}};j.stop=k;o=function(){return a(q.location.href)};l=function(v,s){var u=q.document,t=$.fn[c].domain;if(v!==s){u.title=h.title;u.open();t&&u.write('<script>document.domain="'+t+'"<\/script>');u.close();q.location.hash=v}}})();return j})()})(jQuery,this);

/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(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() {

    var BrowserDetect = {
        init: function () {
            this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
            this.version = this.searchVersion(navigator.userAgent)
                || this.searchVersion(navigator.appVersion)
                || "an unknown version";
            this.OS = this.searchString(this.dataOS) || "an unknown OS";
        },
        searchString: function (data) {
            for (var i=0;i<data.length;i++) {
                var dataString = data[i].string;
                var dataProp = data[i].prop;
                this.versionSearchString = data[i].versionSearch || data[i].identity;
                if (dataString) {
                    if (dataString.indexOf(data[i].subString) != -1)
                        return data[i].identity;
                }
                else if (dataProp)
                    return data[i].identity;
            }
        },
        searchVersion: function (dataString) {
            var index = dataString.indexOf(this.versionSearchString);
            if (index == -1) return;
            return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
        },
        dataBrowser: [
            {
                string: navigator.userAgent,
                subString: "Chrome",
                identity: "Chrome"
            },
            {   string: navigator.userAgent,
                subString: "OmniWeb",
                versionSearch: "OmniWeb/",
                identity: "OmniWeb"
            },
            {
                string: navigator.vendor,
                subString: "Apple",
                identity: "Safari",
                versionSearch: "Version"
            },
            {
                prop: window.opera,
                identity: "Opera"
            },
            {
                string: navigator.vendor,
                subString: "iCab",
                identity: "iCab"
            },
            {
                string: navigator.vendor,
                subString: "KDE",
                identity: "Konqueror"
            },
            {
                string: navigator.userAgent,
                subString: "Firefox",
                identity: "Firefox"
            },
            {
                string: navigator.vendor,
                subString: "Camino",
                identity: "Camino"
            },
            {       // for newer Netscapes (6+)
                string: navigator.userAgent,
                subString: "Netscape",
                identity: "Netscape"
            },
            {
                string: navigator.userAgent,
                subString: "MSIE",
                identity: "Explorer",
                versionSearch: "MSIE"
            },
            {
                string: navigator.userAgent,
                subString: "Gecko",
                identity: "Mozilla",
                versionSearch: "rv"
            },
            {       // for older Netscapes (4-)
                string: navigator.userAgent,
                subString: "Mozilla",
                identity: "Netscape",
                versionSearch: "Mozilla"
            }
        ],
        dataOS : [
            {
                string: navigator.platform,
                subString: "Win",
                identity: "Windows"
            },
            {
                string: navigator.platform,
                subString: "Mac",
                identity: "Mac"
            },
            {
                string: navigator.userAgent,
                subString: "iPhone",
                identity: "iPhone/iPod"
            },
            {
                string: navigator.platform,
                subString: "Linux",
                identity: "Linux"
            }
        ]

    };

    BrowserDetect.init();

    window.$.client = { os : BrowserDetect.OS, browser : BrowserDetect.browser };

})();

/**
 * jQuery custom checkboxes
 *
 * Copyright (c) 2008 Khavilo Dmitry (http://widowmaker.kiev.ua/checkbox/)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * @version 1.3.0 Beta 1
 * @author Khavilo Dmitry
 * @mailto wm.morgun@gmail.com
**/

(function($){
    /* Little trick to remove event bubbling that causes events recursion */
    var CB = function(e)
    {
        if (!e) var e = window.event;
        e.cancelBubble = true;
        if (e.stopPropagation) e.stopPropagation();
    };

    $.fn.checkbox = function(options) {
        /* IE6 background flicker fix */
        try { document.execCommand('BackgroundImageCache', false, true);    } catch (e) {}

        /* Default settings */
        var settings = {
            cls: 'jquery-checkbox',  /* checkbox  */
            empty: 'empty.png'  /* checkbox  */
        };

        /* Processing settings */
        settings = $.extend(settings, options || {});

        /* Adds check/uncheck & disable/enable events */
        var addEvents = function(object)
        {
            var checked = object.checked;
            var disabled = object.disabled;
            var $object = $(object);

            if ( object.stateInterval )
                clearInterval(object.stateInterval);

            object.stateInterval = setInterval(
                function()
                {
                    if ( object.disabled != disabled )
                        $object.trigger( (disabled = !!object.disabled) ? 'disable' : 'enable');
                    if ( object.checked != checked )
                        $object.trigger( (checked = !!object.checked) ? 'check' : 'uncheck');
                },
                10 /* in miliseconds. Low numbers this can decrease performance on slow computers, high will increase responce time */
            );
            return $object;
        };
        //try { console.log(this); } catch(e) {}

        /* Wrapping all passed elements */
        return this.each(function()
        {
            var ch = this; /* Reference to DOM Element*/
            var $ch = addEvents(ch); /* Adds custom events and returns, jQuery enclosed object */

            /* Removing wrapper if already applied  */
            if (ch.wrapper) ch.wrapper.remove();

            /* Creating wrapper for checkbox and assigning "hover" event */
            ch.wrapper = $('<span class="' + settings.cls + '"><span class="mark"><img src="' + settings.empty + '" /></span></span>');
            ch.wrapperInner = ch.wrapper.children('span:eq(0)');
            ch.wrapper.hover(
                function(e) { ch.wrapperInner.addClass(settings.cls + '-hover');CB(e); },
                function(e) { ch.wrapperInner.removeClass(settings.cls + '-hover');CB(e); }
            );

            /* Wrapping checkbox */
            $ch.css({position: 'absolute', zIndex: -1, visibility: 'hidden'}).after(ch.wrapper);

            /* Ttying to find "our" label */
            var label = false;
            if ($ch.attr('id'))
            {
                label = $('label[for='+$ch.attr('id')+']');
                if (!label.length) label = false;
            }
            if (!label)
            {
                /* Trying to utilize "closest()" from jQuery 1.3+ */
                label = $ch.closest ? $ch.closest('label') : $ch.parents('label:eq(0)');
                if (!label.length) label = false;
            }
            /* Labe found, applying event hanlers */
            if (label)
            {
                label.hover(
                    function(e) { ch.wrapper.trigger('mouseover', [e]); },
                    function(e) { ch.wrapper.trigger('mouseout', [e]); }
                );
                label.click(function(e) { $ch.trigger('click',[e]); CB(e); return false;});
            }
            ch.wrapper.click(function(e) { $ch.trigger('click',[e]); CB(e); return false;});
            $ch.click(function(e) { CB(e); });
            $ch.bind('disable', function() {
                label.removeClass('error');
                ch.wrapperInner.addClass(settings.cls+'-disabled').removeClass('error');
            }).bind('enable', function() { ch.wrapperInner.removeClass(settings.cls+'-disabled');});
            $ch.bind('check', function() {
                label.removeClass('error');
                ch.wrapper.addClass(settings.cls+'-checked' ).removeClass('error');
            }).bind('uncheck', function() { ch.wrapper.removeClass(settings.cls+'-checked' );});

            /* Disable image drag-n-drop for IE */
            $('img', ch.wrapper).bind('dragstart', function () {return false;}).bind('mousedown', function () {return false;});

            /* Firefox antiselection hack */
            if ( window.getSelection )
                ch.wrapper.css('MozUserSelect', 'none');

            /* Applying checkbox state */
            if ( ch.checked )
                ch.wrapper.addClass(settings.cls + '-checked');
            if ( ch.disabled )
                ch.wrapperInner.addClass(settings.cls + '-disabled');
        });
    }
})(jQuery);

$.browser.safari = ( $.browser.safari && /chrome/.test(navigator.userAgent.toLowerCase()) ) ? false : true;


/**
 * jQuery custom selectboxes
 *
 * Copyright (c) 2008 Krzysztof Suszyński (suszynski.org)
 * Licensed under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * @version 0.6.1
 * @category visual
 * @package jquery
 * @subpakage ui.selectbox
 * @author Krzysztof Suszyński <k.suszynski@wit.edu.pl>
**/
jQuery.fn.selectbox = function(options){
    /* Default settings */
    var settings = {
        className: 'jquery-selectbox',
        animationSpeed: "normal",
        listboxMaxSize: 10,
        replaceInvisible: false
    };
    var commonClass = 'jquery-custom-selectboxes-replaced';
    var listOpen = false;
    var showList = function(listObj) {
        var selectbox = listObj.parents('.' + settings.className + '');
        listObj.slideDown(settings.animationSpeed, function(){
            listOpen = true;
        });
        selectbox.addClass('selecthover');
        jQuery(document).bind('click', onBlurList);

        return listObj;
    }
    var hideList = function(listObj) {
        var selectbox = listObj.parents('.' + settings.className + '');
        listObj.slideUp(settings.animationSpeed, function(){
            listOpen = false;
            jQuery(this).parents('.' + settings.className + '').removeClass('selecthover');
        });
        jQuery(document).unbind('click', onBlurList);
        return listObj;
    }
    var onBlurList = function(e) {
        var trgt = e.target;
        var currentListElements = jQuery('.' + settings.className + '-list:visible').parent().find('*').andSelf();
        if(jQuery.inArray(trgt, currentListElements)<0 && listOpen) {
            hideList( jQuery('.' + commonClass + '-list') );
        }
        return false;
    }

    /* Processing settings */
    settings = jQuery.extend(settings, options || {});
    /* Wrapping all passed elements */
    return this.each(function() {
        var _this = jQuery(this);
        if(_this.filter(':visible').length == 0 && !settings.replaceInvisible)
            return;
        var replacement = jQuery(
            '<div class="' + settings.className + ' ' + commonClass + '">' +
                '<div class="' + settings.className + '-moreButton" />' +
                '<div class="' + settings.className + '-list ' + commonClass + '-list" />' +
                '<span class="' + settings.className + '-currentItem" />' +
            '</div>'
        );
        jQuery('option', _this).each(function(k,v){
            var v = jQuery(v);
            var listElement =  jQuery('<span class="' + settings.className + '-item value-'+v.val()+' item-'+k+'">' + v.text() + '</span>');
            listElement.click(function(){
                var thisListElement = jQuery(this);
                var thisReplacment = thisListElement.parents('.'+settings.className);
                var thisIndex = thisListElement[0].className.split(' ');
                for( k1 in thisIndex ) {
                    if(/^item-[0-9]+$/.test(thisIndex[k1])) {
                        thisIndex = parseInt(thisIndex[k1].replace('item-',''), 10);
                        break;
                    }
                };
                var thisValue = thisListElement[0].className.split(' ');
                for( k1 in thisValue ) {
                    if(/^value-.+$/.test(thisValue[k1])) {
                        thisValue = thisValue[k1].replace('value-','');
                        break;
                    }
                };
                thisReplacment
                    .find('.' + settings.className + '-currentItem')
                    .text(thisListElement.text());
                thisReplacment
                    .find('select')
                    .val(thisValue)
                    .triggerHandler('change');
                var thisSublist = thisReplacment.find('.' + settings.className + '-list');
                if(thisSublist.filter(":visible").length > 0) {
                    hideList( thisSublist );
                }else{
                    showList( thisSublist );
                }
            }).bind('mouseenter',function(){
                jQuery(this).addClass('listelementhover');
            }).bind('mouseleave',function(){
                jQuery(this).removeClass('listelementhover');
            });
            jQuery('.' + settings.className + '-list', replacement).append(listElement);
            if(v.filter(':selected').length > 0) {
                jQuery('.'+settings.className + '-currentItem', replacement).text(v.text());
            }
        });
        replacement.find('.' + settings.className + '-moreButton').click(function(){
            var thisMoreButton = jQuery(this);
            var otherLists = jQuery('.' + settings.className + '-list')
                .not(thisMoreButton.siblings('.' + settings.className + '-list'));
            hideList( otherLists );
            var thisList = thisMoreButton.siblings('.' + settings.className + '-list');
            if(thisList.filter(":visible").length > 0) {
                hideList( thisList );
            }else{
                showList( thisList );
            }
        }).bind('mouseenter',function(){
            jQuery(this).addClass('morebuttonhover');
        }).bind('mouseleave',function(){
            jQuery(this).removeClass('morebuttonhover');
        });
        replacement.find('.' + settings.className + '-currentItem').click(function () {
            replacement.find('.' + settings.className + '-moreButton').click();
        });
        _this.hide().replaceWith(replacement).appendTo(replacement);
        var thisListBox = replacement.find('.' + settings.className + '-list');
        var thisListBoxSize = thisListBox.find('.' + settings.className + '-item').length;
        if(thisListBoxSize > settings.listboxMaxSize)
            thisListBoxSize = settings.listboxMaxSize;
        if(thisListBoxSize == 0)
            thisListBoxSize = 1;
        var thisListBoxWidth = Math.round(_this.width() + 5);
        if(jQuery.browser.safari)
            thisListBoxWidth = jQuery.client.os != 'Mac' ? thisListBoxWidth + 23 : thisListBoxWidth - 2;
        if(jQuery.browser.msie && jQuery.browser.version == '8.0')
            thisListBoxWidth -= 21;
        if(jQuery.browser.mozilla && jQuery.client.os == 'Mac')
            thisListBoxWidth += 27;
        if(jQuery.browser.mozilla && jQuery.client.os != 'Mac')
            thisListBoxWidth -= 23;
        if(jQuery.browser.opera)
            thisListBoxWidth -= 19;
        replacement.css('width', thisListBoxWidth + 'px');
        thisListBox.css({
            width: Math.round(thisListBoxWidth) + 'px'/*,
            height: thisListBoxSize + 'em'*/
        });
    });
}
jQuery.fn.unselectbox = function(){
    var commonClass = 'jquery-custom-selectboxes-replaced';
    return this.each(function() {
        var selectToRemove = jQuery(this).filter('.' + commonClass);
        selectToRemove.replaceWith(selectToRemove.find('select').show());
    });
}
/**
 * jQuery.fn.sortElements
 * --------------
 * @param Function comparator:
 *   Exactly the same behaviour as [1,2,3].sort(comparator)
 *
 * @param Function getSortable
 *   A function that should return the element that is
 *   to be sorted. The comparator will run on the
 *   current collection, but you may want the actual
 *   resulting sort to occur on a parent or another
 *   associated element.
 *
 *   E.g. $('td').sortElements(comparator, function(){
 *      return this.parentNode;
 *   })
 *
 *   The <td>'s parent (<tr>) will be sorted instead
 *   of the <td> itself.
 */
jQuery.fn.sortElements = (function(){

    var sort = [].sort;

    return function(comparator, getSortable) {

        getSortable = getSortable || function(){return this;};

        var placements = this.map(function(){

            var sortElement = getSortable.call(this),
                parentNode = sortElement.parentNode,

                // Since the element itself will change position, we have
                // to have some way of storing its original position in
                // the DOM. The easiest way is to have a 'flag' node:
                nextSibling = parentNode.insertBefore(
                    document.createTextNode(''),
                    sortElement.nextSibling
                );

            return function() {

                if (parentNode === this) {
                    throw new Error(
                        "You can't sort elements if any one is a descendant of another."
                    );
                }

                // Insert before flag:
                parentNode.insertBefore(this, nextSibling);
                // Remove flag:
                parentNode.removeChild(nextSibling);

            };

        });

        return sort.call(this, comparator).each(function(i){
            placements[i].call(getSortable.call(this));
        });

    };

})();

/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function (key, value, options) {

    // key and at least value given, set cookie...
    if (arguments.length > 1 && String(value) !== "[object Object]") {
        options = jQuery.extend({}, options);

        if (value === null || value === undefined) {
            options.expires = -1;
        }

        if (typeof options.expires === 'number') {
            var days = options.expires, t = options.expires = new Date();
            t.setDate(t.getDate() + days);
        }

        value = String(value);

        return (document.cookie = [
            encodeURIComponent(key), '=',
            options.raw ? value : encodeURIComponent(value),
            options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
            options.path ? '; path=' + options.path : '',
            options.domain ? '; domain=' + options.domain : '',
            options.secure ? '; secure' : ''
        ].join(''));
    }

    // key and possibly options given, get cookie...
    options = value || {};
    var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
    return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};


function array_rand (input, num_req) {
    // http://kevin.vanzonneveld.net
    // +   original by: Waldo Malqui Silva
    // *     example 1: array_rand( ['Kevin'], 1 );
    // *     returns 1: 0
    var indexes = [];
    var ticks = num_req || 1;
    var checkDuplicate = function (input, value) {
        var exist = false,
            index = 0,
            il = input.length;
        while (index < il) {
            if (input[index] === value) {
                exist = true;
                break;
            }
            index++;
        }
        return exist;
    };

    if (Object.prototype.toString.call(input) === '[object Array]' && ticks <= input.length) {
        while (true) {
            var rand = Math.floor((Math.random() * input.length));
            if (indexes.length === ticks) {
                break;
            }
            if (!checkDuplicate(indexes, rand)) {
                indexes.push(rand);
            }
        }
    } else {
        indexes = null;
    }

    return ((ticks == 1) ? indexes.join() : indexes);
}

function in_array (needle, haystack, argStrict) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: vlado houba
    // +   input by: Billy
    // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
    // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
    // *     returns 2: false
    // *     example 3: in_array(1, ['1', '2', '3']);
    // *     returns 3: true
    // *     example 3: in_array(1, ['1', '2', '3'], false);
    // *     returns 3: true
    // *     example 4: in_array(1, ['1', '2', '3'], true);
    // *     returns 4: false
    var key = '',
        strict = !! argStrict;

    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}

function hasDoubleByteChars (str) {
    return /[\u0100-\uffff]/.test(str);
}

function removeDoubleByteChars (str) {
    return str.replace(/[\u0100-\uffff]/g, '');
}


var Leica = function () {
    this.root = '';
    this.cmsRoot = '/cms';

    this.minSideWidth = 799;
    this.maxSideWidth = 1599;

    this.lbCloseOnClick = true;
    this.lbCloseOnEsc = true;

    this.fadeSpeed = 120;
    this.slideSpeed = 300;
    this.fadeTimeout = 100;
    this.columnThumbWidth = 199;
    this.galleryMargin = 40;
    this.pictures = [];
    this.columns = 0;
    this.transid = null;
    this.uploadInProgress = false;
    this.wettbewerbID = 0;
    this.siteLanguage = 'de';
    this.prevNewWidth = 0;

    this.countries = {
        de: {
            'AD': 'Andorra',
            'AE': 'Vereinigte Arabische Emirate',
            'AF': 'Afghanistan',
            'AG': 'Antigua und Barbuda',
            'AI': 'Anguilla',
            'AL': 'Albanien',
            'AM': 'Armenien',
            'AN': 'Niederländische Antillen',
            'AO': 'Angola',
            'AQ': 'Antarktis',
            'AR': 'Argentinien',
            'AS': 'Samoa',
            'AT': 'Österreich',
            'AU': 'Australien',
            'AW': 'Aruba',
            'AZ': 'Aserbaidschan',
            'BA': 'Bosnien-Herzegowina',
            'BB': 'Barbados',
            'BD': 'Bangladesh',
            'BE': 'Belgien',
            'BF': 'Burkina Faso',
            'BG': 'Bulgarien',
            'BH': 'Bahrain',
            'BI': 'Burundi',
            'BJ': 'Benin',
            'BM': 'Bermudas',
            'BN': 'Brunei',
            'BO': 'Bolivien',
            'BR': 'Brasilien',
            'BS': 'Bahamas',
            'BT': 'Bhutan',
            'BV': 'Bouvet-Inseln',
            'BW': 'Botswana',
            'BY': 'Weissrussland',
            'BZ': 'Belize',
            'CA': 'Canada',
            'CC': 'Kokosinseln',
            'CD': 'Demokratische Republik Kongo',
            'CF': 'Zentralafrikanische Republik',
            'CG': 'Kongo',
            'CH': 'Schweiz',
            'CI': 'Elfenbeinküste',
            'CK': 'Cook-Inseln',
            'CL': 'Chile',
            'CM': 'Kamerun',
            'CN': 'China',
            'CO': 'Kolumbien',
            'CR': 'Costa Rica',
            'CS': 'Serbien und Montenegro',
            'CU': 'Kuba',
            'CV': 'Kap Verde',
            'CX': 'Christmas Island',
            'CY': 'Zypern',
            'CZ': 'Tschechien',
            'DE': 'Deutschland',
            'DJ': 'Djibuti',
            'DK': 'Dänemark',
            'DM': 'Dominika',
            'DO': 'Dominikanische Republik',
            'DZ': 'Algerien',
            'EC': 'Equador',
            'EE': 'Estland',
            'EG': 'Ägypten',
            'EH': 'Westsahara',
            'ER': 'Eritrea',
            'ES': 'Spanien',
            'ET': 'Äthiopien',
            'FI': 'Finnland',
            'FJ': 'Fidschi-Inseln',
            'FK': 'Falkland-Inseln',
            'FM': 'Mikronesien',
            'FO': 'Färöer Inseln',
            'FR': 'Frankreich',
            'GA': 'Gabun',
            'GD': 'Grenada',
            'GE': 'Georgien',
            'GF': 'Französisch Guyana',
            'GH': 'Ghana',
            'GI': 'Gibraltar',
            'GL': 'Grönland',
            'GM': 'Gambia',
            'GN': 'Guinea',
            'GP': 'Guadeloupe',
            'GQ': 'Äquatorial Guinea',
            'GR': 'Griechenland',
            'GS': 'South Georgia und South Sandwich Islands',
            'GT': 'Guatemala',
            'GU': 'Guam',
            'GW': 'Guinea Bissau',
            'GY': 'Guyana',
            'HK': 'Hongkong',
            'HM': 'Heard und McDonald Islands',
            'HN': 'Honduras',
            'HR': 'Kroatien',
            'HT': 'Haiti',
            'HU': 'Ungarn',
            'ID': 'Indonesien',
            'IE': 'Irland',
            'IL': 'Israel',
            'IN': 'Indien',
            'IO': 'Britisch-Indischer Ozean',
            'IQ': 'Irak',
            'IR': 'Iran',
            'IS': 'Island',
            'IT': 'Italien',
            'JM': 'Jamaika',
            'JO': 'Jordanien',
            'JP': 'Japan',
            'KE': 'Kenia',
            'KG': 'Kirgisistan',
            'KH': 'Kambodscha',
            'KI': 'Kiribati',
            'KM': 'Komoren',
            'KN': 'St. Kitts Nevis Anguilla',
            'KP': 'Nordkorea',
            'KR': 'Korea (Republik)',
            'KW': 'Kuwait',
            'KY': 'Kaiman-Inseln',
            'KZ': 'Kasachstan',
            'LA': 'Laos',
            'LB': 'Libanon',
            'LC': 'Saint Lucia',
            'LI': 'Liechtenstein',
            'LK': 'Sri Lanka',
            'LR': 'Liberia',
            'LS': 'Lesotho',
            'LT': 'Litauen',
            'LU': 'Luxemburg',
            'LV': 'Lettland',
            'LY': 'Libyen',
            'MA': 'Marokko',
            'MC': 'Monaco',
            'MD': 'Moldavien',
            'MG': 'Madagaskar',
            'MH': 'Marshall-Inseln',
            'MK': 'Mazedonien',
            'ML': 'Mali',
            'MM': 'Myanmar',
            'MN': 'Mongolei',
            'MO': 'Macão',
            'MP': 'Marianen',
            'MQ': 'Martinique',
            'MR': 'Mauretanien',
            'MS': 'Montserrat',
            'MT': 'Malta',
            'MU': 'Mauritius',
            'MV': 'Malediven',
            'MW': 'Malawi',
            'MX': 'Mexiko',
            'MY': 'Malaysia',
            'MZ': 'Mocambique',
            'NA': 'Namibia',
            'NC': 'Neukaledonien',
            'NE': 'Niger',
            'NF': 'Norfolk-Inseln',
            'NG': 'Nigeria',
            'NI': 'Nicaragua',
            'NL': 'Niederlande',
            'NO': 'Norwegen',
            'NP': 'Nepal',
            'NR': 'Nauru',
            'NU': 'Niue',
            'NZ': 'Neuseeland',
            'OM': 'Oman',
            'PA': 'Panama',
            'PE': 'Peru',
            'PF': 'Französisch-Polynesien',
            'PG': 'Papua Neuguinea',
            'PH': 'Philippinen',
            'PK': 'Pakistan',
            'PL': 'Polen',
            'PM': 'St. Pierre und Miquelon',
            'PN': 'Pitcairn',
            'PR': 'Puerto Rico',
            'PS': 'Palästinensische Selbstverwaltungsgebiete',
            'PT': 'Portugal',
            'PW': 'Palau',
            'PY': 'Paraguay',
            'QA': 'Katar',
            'RE': 'Reunion',
            'RO': 'Rumänien',
            'RU': 'Russland',
            'RW': 'Ruanda',
            'SA': 'Saudi-Arabien',
            'SB': 'Solomon-Inseln',
            'SC': 'Seychellen',
            'SD': 'Sudan',
            'SE': 'Schweden',
            'SG': 'Singapur',
            'SH': 'St. Helena',
            'SI': 'Slowenien',
            'SJ': 'Svalbard und Jan Mayen Islands',
            'SK': 'Slowakei (Slowakische Republik)',
            'SL': 'Sierra Leone',
            'SM': 'San Marino',
            'SN': 'Senegal',
            'SO': 'Somalia',
            'SR': 'Surinam',
            'ST': 'Sao Tome',
            'SV': 'El Salvador',
            'SY': 'Syrien',
            'SZ': 'Swasiland',
            'TC': 'Turks- und Kaikos-Inseln',
            'TD': 'Tschad',
            'TF': 'Französisches Süd-Territorium',
            'TG': 'Togo',
            'TH': 'Thailand',
            'TJ': 'Tadschikistan',
            'TK': 'Tokelau',
            'TL': 'Ost-Timor',
            'TM': 'Turkmenistan',
            'TN': 'Tunesien',
            'TO': 'Tonga',
            'TR': 'Türkei',
            'TT': 'Trinidad Tobago',
            'TV': 'Tuvalu',
            'TW': 'Taiwan',
            'TZ': 'Tansania',
            'UA': 'Ukraine',
            'UG': 'Uganda',
            'UK': 'Grossbritannien (UK)',
            'US': 'USA',
            'UY': 'Uruguay',
            'UZ': 'Usbekistan',
            'VA': 'Vatikan',
            'VC': 'St. Vincent',
            'VE': 'Venezuela',
            'VG': 'Virgin Island (Brit.)',
            'VI': 'Virgin Island (USA)',
            'VN': 'Vietnam',
            'VU': 'Vanuatu',
            'WF': 'Wallis et Futuna',
            'WS': 'Samoa',
            'YE': 'Jemen',
            'YT': 'Mayotte',
            'ZA': 'Südafrika',
            'ZM': 'Sambia',
            'ZW': 'Simbabwe'
        },
        en: {
            'AD': 'Andorra',
            'AE': 'United Arab Emirates',
            'AF': 'Afghanistan',
            'AG': 'Antigua and Barbuda',
            'AI': 'Anguilla',
            'AL': 'Albania',
            'AM': 'Armenia',
            'AN': 'Netherlands Antilles',
            'AO': 'Angola',
            'AQ': 'Antarctica',
            'AR': 'Argentina',
            'AS': 'American Samoa',
            'AT': 'Austria',
            'AU': 'Australia',
            'AW': 'Aruba',
            'AZ': 'Azerbaijan',
            'BA': 'Bosnia and Herzegovina',
            'BB': 'Barbados',
            'BD': 'Bangladesh',
            'BE': 'Belgium',
            'BF': 'Burkina Faso',
            'BG': 'Bulgaria',
            'BH': 'Bahrain',
            'BI': 'Burundi',
            'BJ': 'Benin',
            'BM': 'Bermuda',
            'BN': 'Brunei Darussalam',
            'BO': 'Bolivia',
            'BR': 'Brazil',
            'BS': 'Bahamas',
            'BT': 'Bhutan',
            'BV': 'Bouvet Island',
            'BW': 'Botswana',
            'BY': 'Belarus',
            'BZ': 'Belize',
            'CA': 'Canada',
            'CC': 'Cocos (Keeling) Islands',
            'CD': 'Congo (Democratic Republic)',
            'CF': 'Central African Republic',
            'CG': 'Congo',
            'CH': 'Switzerland',
            'CI': 'Ivory Coast',
            'CK': 'Cook Islands',
            'CL': 'Chile',
            'CM': 'Cameroon',
            'CN': 'China',
            'CO': 'Colombia',
            'CR': 'Costa Rica',
            'CS': 'Serbia and Montenegro',
            'CU': 'Cuba',
            'CV': 'Cape Verde',
            'CX': 'Christmas Island',
            'CY': 'Cyprus',
            'CZ': 'Czech Republic',
            'DE': 'Germany',
            'DJ': 'Djibouti',
            'DK': 'Denmark',
            'DM': 'Dominica',
            'DO': 'Dominican Republic',
            'DZ': 'Algeria',
            'EC': 'Ecuador',
            'EE': 'Estonia',
            'EG': 'Egypt',
            'EH': 'Western Sahara',
            'ER': 'Eritrea',
            'ES': 'Spain',
            'ET': 'Ethopia',
            'FI': 'Finland',
            'FJ': 'Fiji',
            'FK': 'Falkland Islands',
            'FM': 'Micronesia',
            'FO': 'Faroe Islands',
            'FR': 'France',
            'GA': 'Gabon',
            'GD': 'Grenada',
            'GE': 'Georgia',
            'GF': 'French Guiana',
            'GH': 'Ghana',
            'GI': 'Gibraltar',
            'GL': 'Greenland',
            'GM': 'Gambia',
            'GN': 'Guinea',
            'GP': 'Guadeloupe',
            'GQ': 'Eqautorial Guinea',
            'GR': 'Greece',
            'GS': 'South Georgia und South Sandwich Islands',
            'GT': 'Guatemala',
            'GU': 'Guam',
            'GW': 'Guinea Bissau',
            'GY': 'Guyana',
            'HK': 'Hong Kong',
            'HM': 'Heard and McDonald Islands',
            'HN': 'Honduras',
            'HR': 'Croatia',
            'HT': 'Haiti',
            'HU': 'Hungary',
            'ID': 'Indonesia',
            'IE': 'Ireland',
            'IL': 'Israel',
            'IN': 'India',
            'IO': 'British indian ocean terretory',
            'IQ': 'Iraq',
            'IR': 'Islamic Republic of Iran',
            'IS': 'Iceland',
            'IT': 'Italy',
            'JM': 'Jamaica',
            'JO': 'Jordan',
            'JP': 'Japan',
            'KE': 'Kenya',
            'KG': 'Kyrgyzstan',
            'KH': 'Cambidoa',
            'KI': 'Kiribati',
            'KM': 'Comoros',
            'KN': 'Saint Kitts and Nevis',
            'KP': 'Korea, Democratic Peoples Republic Of',
            'KR': 'Korea, Republic of',
            'KW': 'Kuwait',
            'KY': 'Cayman Islands',
            'KZ': 'Kazakhstan',
            'LA': 'Lao, Peoples Democratic Republic',
            'LB': 'Lebanon',
            'LC': 'Saint Lucia',
            'LI': 'Liechtenstein',
            'LK': 'Sri Lanka',
            'LR': 'Liberia',
            'LS': 'Lesotho',
            'LT': 'Lithuania',
            'LU': 'Luxembourg',
            'LV': 'Latvia',
            'LY': 'Libyan Arab Jamahiriya',
            'MA': 'Morocco',
            'MC': 'Monaco',
            'MD': 'Moldova, Republic Of',
            'MG': 'Madagascar',
            'MH': 'Marshall Islands',
            'MK': 'Macedonia',
            'ML': 'Mali',
            'MM': 'Myanmar',
            'MN': 'Mongolia',
            'MO': 'Macau',
            'MP': 'Nothern Mariana Islands',
            'MQ': 'Martinique',
            'MR': 'Mauritania',
            'MS': 'Montserrat',
            'MT': 'Malta',
            'MU': 'Mauritius',
            'MV': 'Malidives',
            'MW': 'Malawi',
            'MX': 'Mexico',
            'MY': 'Malaysia',
            'MZ': 'Mozambique',
            'NA': 'Namibia',
            'NC': 'New Caledonia',
            'NE': 'Niger',
            'NF': 'Norfolk Islands',
            'NG': 'Nigeria',
            'NI': 'Nicaragua',
            'NL': 'Netherlands',
            'NO': 'Norway',
            'NP': 'Nepal',
            'NR': 'Nauru',
            'NU': 'Niue',
            'NZ': 'New Zealand',
            'OM': 'Oman',
            'PA': 'Panama',
            'PE': 'Peru',
            'PF': 'French Polynesia',
            'PG': 'Papua New Guinea',
            'PH': 'Philippines',
            'PK': 'Pakistan',
            'PL': 'Poland',
            'PM': 'Saint Pierre and Miquelon',
            'PN': 'Pitcairn',
            'PR': 'Puerto Rico',
            'PS': 'Palestinian Territory',
            'PT': 'Portugal',
            'PW': 'Palau',
            'PY': 'Paraguay',
            'QA': 'Qatar',
            'RE': 'Reunion',
            'RO': 'Romania',
            'RU': 'Russian Federation',
            'RW': 'Rwande',
            'SA': 'Saudi Arabia',
            'SB': 'Solomon Islands',
            'SC': 'Seychelles',
            'SD': 'Sudan',
            'SE': 'Sweden',
            'SG': 'Singapore',
            'SH': 'Saint Helena',
            'SI': 'Slovenia',
            'SJ': 'Svalbard and Jan Mayen',
            'SK': 'Slovakia',
            'SL': 'Sierra Leone',
            'SM': 'San Marino',
            'SN': 'Senegal',
            'SO': 'Somalia',
            'SR': 'Suriname',
            'ST': 'Sao Tome and Principe',
            'SV': 'El Salvador',
            'SY': 'Syrian Arab Republic',
            'SZ': 'Swaziland',
            'TC': 'Turks and Caicos Islands',
            'TD': 'Chad',
            'TF': 'French Southern Territories',
            'TG': 'Togo',
            'TH': 'Thailand',
            'TJ': 'Tajikistan',
            'TK': 'Tokelau',
            'TL': 'Timor-Leste',
            'TM': 'Turkmenistan',
            'TN': 'Tunisia',
            'TO': 'Tonga',
            'TR': 'Turkey',
            'TT': 'Trinidad and Tobago',
            'TV': 'Tuvalu',
            'TW': 'Taiwan',
            'TZ': 'Tanzania',
            'UA': 'Ukraine',
            'UG': 'Ugande',
            'UK': 'United Kingdom (Great Britain)',
            'US': 'United States of America',
            'UY': 'Uruguay',
            'UZ': 'Uzbekistan',
            'VA': 'Holy See (Vatican City State)',
            'VC': 'Saint Vincent and the Grenadines',
            'VE': 'Venezuela',
            'VG': 'Virgin Islands, BRITISH',
            'VI': 'Virgin Islands, U.S.',
            'VN': 'Viet Nam',
            'VU': 'Vanatu',
            'WF': 'Wallus and Futuna',
            'WS': 'Samoa',
            'YE': 'Yemen',
            'YT': 'Mayotte',
            'ZA': 'South Africa',
            'ZM': 'Zambia',
            'ZW': 'Zimbabwe'
        }
    };

    this.filesList = {};

    this.uploadOptions = {
        dataType: 'json',
        dropZone: null,
        replaceFileInput: false,
        
        add: function (e, data) {
            var $input = $(':input[name=' + data.fileInput.attr('name') + ']'),
                file = data.files[0]
                error = false;

            if ( typeof file.type !== 'undefined' && typeof file.size !== 'undefined' ) {
                if ( file.type != 'image/jpeg' && file.type != 'image/jpg' ) {
                    msg = app.lng('Bitte wählen Sie für den Upload ausschließlich JPG-Dateien.');
                    error = true;
                } else if ( file.size > (3 * 1024 * 1024) ) {
                    msg = app.lng('Die Bildgröße entspricht nicht den Vorgaben (maximal 3 MB).');
                    error = true;
                }
            }

            if ( error ) {
                alert(msg);
            } else {
                app.filesList[$input.attr('name')] = data.files[0];

                $input.parent().find('.filename').text(file.name);
                $input.parent().find('.choose-file').removeClass('hover');

                $input.parents('.upload-item').addClass('file').removeClass('error');
            }
        },

        send: function (e, data) {
            var result = data.result,
                $input = $(':input[name=' + app.currUploadFile + ']'),
                $uplItem = $input.parents('.upload-item');

            $('#upload-progress ul').append('<li>' + data.files[0].name + ' <span class="percent"><\/span><\/li>');
            $('#upload-progress').css('marginTop', -( $('#upload-progress').outerHeight() / 2 ));
        },

        progress: function (e, data) {
            var progress = parseInt(data.loaded / data.total * 100, 10),
                $li = $('#upload-progress li:last');

            $li.find('.percent').text(' - ' + progress + '%');
        },

        done: function (e, data) {
            var result = data.result,
                $input = $(':input[name=' + app.currUploadFile + ']'),
                $uplItem = $input.parents('.upload-item'),
                $li = $('#upload-progress li:last');

                $li.find('.percent').text(' - 100%');

            if ( typeof result['json.error'] !== 'undefined' ) {
                $uplItem.find('.disabled').andSelf().removeClass('disabled');
                $uplItem.addClass('error').removeClass('file');
                
                $('.filename', $uplItem).text(app.lng('keine Datei ausgewählt'));
                $('.choose-file', $uplItem).html(app.lng('&raquo; Datei wählen'));

                $('<input type="file" name="' + app.currUploadFile + '" class="file-upload-input">')
                    .css('opacity', 0)
                    .appendTo($('.upload', $uplItem))
                    .fileupload(app.uploadOptions);

                $(':input', $uplItem).prop('readonly', false);

                switch (result['json.error']) {
                    case 'Dateityp nicht erlaubt, nur: JPG , jpg':
                        var errorMsg = app.lng('Bitte wählen Sie für den Upload ausschließlich JPG-Dateien.');
                        break;
                    case 'Bild Dimensionen inkorrekt':
                        var errorMsg = app.lng('Bildmaße entsprechen nicht den Vorgaben. Das Bild muss genau 1200 Pixel hoch sein.');
                        break;
                    case 'Upload nicht erfolgreich >  File size >3M':
                        var errorMsg = app.lng('Dateigröße entspricht nicht den Vorgaben (maximal 3 MB).');
                        break;
                    default:
                        var errorMsg = result['json.error'];
                        break;
                }

                $li.addClass('error').append(' <span class="progress-error">' + app.lng('Fehler') + ': ' + errorMsg + '<\/span>');
            } else {
                $input.css('display', 'none');
            }

            app.startNextInQueue();
        }
    };

    this.currUploadFile = null;
    this.uploadCount = 0;
};

(function ($) {
    $.fn.disable = function () {
        return $(this).each(function () {
            if ( ! $(this).is(':hidden')) {
                $(this).prop('readonly', true).addClass('disabled');
                $('label[for=' + this.id + ']').addClass('disabled');
            }

            if ( $(this).is('select') ) {
                $('.jquery-selectbox-moreButton, .jquery-selectbox-currentItem', $(this).parent()).unbind('click');
                $(this).parent().addClass('disabled');
                $('label[for=' + this.id + ']').addClass('disabled');
                if ( $(this).parents('.birthday-form').length ) {
                    $(this).parents('.birthday-form').find('label').addClass('disabled');
                }
            }

            if ( $(this).is('.file-upload-input') ) {
                $(this).parents('.upload-item').addClass('disabled');
            }

            if ( $(this).is(':checkbox') || $(this).is(':radio') ) {
                var $chWrapper = $(this).next();
                $chWrapper.unbind('click').unbind('hover').addClass('disabled');
                $('label[for=' + this.id + ']').addClass('disabled').unbind('click').unbind('hover').attr('for', '');
                $(this).unbind('click');
            }
        });
    };
    $.fn.disableTextSelect = function() {
        return this.each(function(){
            if($.browser.mozilla){//Firefox
                $(this).css('MozUserSelect','none');
            }else if($.browser.msie){//IE
                $(this).bind('selectstart',function(){return false;});
            }else{//Opera, etc.
                $(this).mousedown(function(){return false;});
            }
        });
    };
})(jQuery);

Leica.prototype = {

    is: function (id) {
        return $('#' + id).length > 0;
    },

    debug: function (msg) {
        if ( typeof console !== 'undefined' ) {
            console.log(msg);
        } else {
            alert(msg);
        }
    },

    initShareButtons: function () {
        var self = this,
            $buttons = $('#share-buttons'),
            timeout,
            buttonsFadeOut = function () {
                $buttons.fadeOut(self.fadeSpeed);
                $('#sub .share').removeClass('open');
            },
            buttonsFadeIn = function () {
                $('#sub .share').addClass('open');
                clearTimeout(timeout);
                $buttons.stop(true, true).fadeIn(self.fadeSpeed);
            };
        $('#sub .share, #share-buttons').hover(buttonsFadeIn, function () {
            timeout = setTimeout(buttonsFadeOut, self.fadeTimeout);
        });
    },

    initSubMenus: function () {
        var self = this;
        $('#main ul ul').each(function () {
            var $submenu = $(this);
            $(this).parent().hover(function () {
                $submenu.stop(true, true).fadeIn(self.fadeSpeed);
            }, function () {
                $submenu.stop(true, true).fadeOut(self.fadeSpeed);
            });
        });
    },

    startNextInQueue: function () {
        var self = this;

        for (var i in self.filesList) break;
        
        if ( typeof i === 'undefined' ) {
            app.currUploadFile = null;
            app.uploadInProgress = false;

            if ( $('.upload-item.error').length ) {
                $('<p><b>' + app.lng('Bitte bearbeiten Sie die rot markierten Felder im Formular.') + '</b></p>').appendTo($('#upload-progress'));
                self.appendCloseButtonToUploadNotice();
            } else {
                $('#upload-progress, #progress-overlay').fadeOut(self.fadeSpeed, function () {
                    $(this).remove();
                });
                $('#overlay').scrollTop(0);

                var finishUrl = self.root + '/en/applying/finish';
                if ( self.siteLanguage == 'de' ) {
                    finishUrl = self.root + '/de/anmeldung/finish';
                }
                $('.signup-form').load(finishUrl, { m: $.trim($('#email').val()) });
            }
        } else {
            var file = self.filesList[i];
            app.currUploadFile = i;

            var jqXHR = $('#register-form')
                .fileupload('option', 'paramName', i)
                .fileupload('send', { files: file, fileInput: $(':input[name=' + i + ']') });
            
            delete self.filesList[i];
        }
    },

    sortUploadFilesList: function () {
        var sortable = [],
            ret = {},
            self = this;

        for (var uplName in self.filesList) {
            sortable.push([uplName, self.filesList[uplName]])
        }

        sortable.sort(function (a, b) {
            var nameA = a[0].split('_').pop(),
                nameB = b[0].split('_').pop(),
                a = nameA.length == 1 ? '0' + nameA : nameA,
                b = nameB.length == 1 ? '0' + nameB : nameB;
            return a > b ? 1 : -1;
        });
        
        var ret = {};
        for ( var i in sortable ) {
            ret[sortable[i][0]] = sortable[i][1];
        }

        self.filesList = ret;
    },

    initUploadForm: function () {
        var self = this,
            $countries = $('#country'),
            lastNameInterval;

        if ( $countries.length ) {
            $countries.parent().find('.jquery-selectbox-list span').click(function () {
                var name = this.className,
                    match = /value[-]([A-Z]{2})/.exec(name)[1].toLowerCase(),
                    formType = $('#address-fields-' + match).length ? match : 'normal';

                if ( ! $('#address-fields-' + formType, $('#address')).length ) {
                    $('#address-fields-' + formType).clone(true, true).removeClass('hidden-address').appendTo($('#address').html(''));
                    if ( $('#address-us-state', $('#address')).length ) {
                        $('#address-us-state').selectbox({
                            animationSpeed: 0
                        }).bind('change', function () {
                            $(this).parent().removeClass('error').prev().removeClass('error');
                        });
                    }
                }
            });
        }

        $(':input[type=text]').change(function () {
            var id = $(this).removeClass('error').attr('id');
            $('label[for=' + id + ']').removeClass('error');
        }).each(function () {
            $(this).bind('click change keyup', function () {
                if ( hasDoubleByteChars(this.value) ) {
                    this.value = removeDoubleByteChars(this.value);
                }
            });
        });

        $(':input[name=upload_person_salutation]').parent().find('.jquery-selectbox-list').css('height', 72);

        // kill previous session
        $.post(app.cmsRoot + '/?exit=true', { upload_TRANSID: $.cookie('TRANSID') }, function () {
            // get new upload session id
            $.getJSON(app.cmsRoot + '/?do=fileupload_data', function (response) {
                // save upload session id
                self.transid = response['session.id'];
                $(':input[name=upload_TRANSID]').val(self.transid);
            });
        });

        // hide file inputs
        $('.file-upload-input').css('opacity', 0);

        $('.file').hover(function () {
            $(this).find('.choose-file:not(.disabled)').addClass('hover');
            $(this).bind('mousemove', function (e) {
                var yminus = 10,
                    xminus = 85;
                if ( $.browser.msie ) {
                    xminus = 290;
                }
                else if ( $.browser.mozilla ) {
                    xminus = 220;
                }
                else if ( $.browser.opera ) {
                    xminus = 320;
                }

                var pagex = e.pageX - $('#lightbox').offset().left,
                    pagey = e.pageY - $('.upload', $(this)).offset().top;

                $('.file-upload-input', $(this)).css({
                    top: pagey - yminus,
                    left: pagex - xminus
                });
            });
        }, function () {
            $(this).find('.choose-file').removeClass('hover');
            $(this).unbind('mousemove');
        });

        function setWettbewerbId () {
            self.wettbewerbID = $(':input[name=upload_wettbewerb_id]:checked').val();
            $('#register-form').prepend('<input type="hidden" name="upload_wettbewerb_id" value="' + self.wettbewerbID + '">');
            $('#wettbewerb-selection').html('<p>' +
                $('label[for=' + $(':input[name=upload_wettbewerb_id]:checked').attr('id') + ']').html()
            + '</p>');
        }

        $(':input[name=upload_wettbewerb_id]').next().click(setWettbewerbId);
        $(':input[name=upload_wettbewerb_id]').next().next().click(setWettbewerbId);

        $('#register-form').find(':input').andSelf().attr('autocomplete', 'off');

        // init fileupload
        $('#register-form')
            .fileupload(self.uploadOptions)
            // validate post data before sending
            .submit(function (e) {
                e.preventDefault();
                var send = self.validateRegisterForm();
                //var send = true;

                if ( send && ! app.uploadInProgress ) {
                    self.uploadInProgress = true;
                    self.sortUploadFilesList();

                    $('#add-more-pics').parent().remove();

                    $(':input', $(this)).disable();

                    self.showUploadNotice(
                        "<h3>" + app.lng('Upload') + "</h3>" + 
                        "<p><b>" + app.lng('Daten werden übertragen') + "</b></p>" +
                        "<p>" + app.lng('Bitte verlassen Sie diese Seite nicht und schließen Sie Ihren Browser nicht bis die Übertragung beendet ist.') + "</p>" +
                        "<ul></ul>"
                    );

                    self.startNextInQueue();
                }
                
            });
    },

    showUploadNotice: function (html, topPosition) {
        var self = this;

        $('<div id="progress-overlay">')
            .css('height', $('#lightbox').outerHeight())
            .appendTo($('#lightbox'))
            .fadeIn(self.fadeSpeed);

        $('#lightbox').append('<div id="upload-progress"><\/div>');
        $('#upload-progress').html(html);

        if ( typeof topPosition !== 'undefined' ) {
            $('#upload-progress').css('top', topPosition);
        }

        var offset = $('#upload-progress')[0];
        $('#overlay').scrollTop(offset.offsetTop + 150);
    },

    appendCloseButtonToUploadNotice: function (special) {
        var self = this,
            special = special || false,
            buttonText = app.lng('&raquo; OK');
        if ( special ) {
            buttonText = app.lng('&raquo; Formular bearbeiten');
        }
        $('<p><button class="close-button' + ( special ? ' bday' : '' ) + '">' + buttonText + '</button></p>')
            .appendTo($('#upload-progress'))
            .find('.close-button').one('click', function () {
                $('#upload-progress, #progress-overlay').fadeOut(self.fadeSpeed, function () {
                    $(this).remove();
                });
            });
        if ( special ) {
            $('<button class="close-button bday">' + app.lng('&raquo; Formular neuladen') + '</button>')
                .insertBefore($('#upload-progress .close-button'))
                .one('click', function () {
                    location.reload();
                });
        }
    },

    // dateString = Ymd
    getAge: function (y, m, d) {
        var today = new Date();
        var birthDate = new Date(y, m, d);
        var age = today.getFullYear() - birthDate.getFullYear();
        var m = today.getMonth() - birthDate.getMonth();
        if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
            age--;
        }
        return age;
    },

    validateRegisterForm: function () {
        var self = this;

        $('#signup-errors').remove();
        $('.error').removeClass('error');

        var $form = $('#register-form'),
            data = {
                wettbewerb: $(':input[name=upload_wettbewerb_id]:checked').val(),
                salutation: $(':input[name=upload_person_salutation]').val(),
                title: $(':input[name=upload_person_title]').val(),
                firstname: $.trim($(':input[name=upload_firstname]').val()),
                surname: $.trim($(':input[name=upload_surname]').val()),
                nation: $.trim($(':input[name=upload_person_nation]').val()),
                email: $.trim($(':input[name=upload_email]').val()),
                country: $.trim($(':input[name=upload_country]').val()),
                countrycode: $.trim($('#countrycode').val()),
                telephone: $.trim($('#telephone').val()),
                camera: $.trim($('#camera').val()),
                uploadtitle: $.trim($('#uploadtitle').val()),
                terms_accepted: $('#terms').is(':checked'),
                datastorage_accepted: $(':input[name=upload_datastorage]:checked').val(),
                bday: $(':input[name=upload_person_birthday]').val(),
                bmonth: $(':input[name=upload_person_birthmonth]').val(),
                byear: $(':input[name=upload_person_birthyear]').val()
            },
            errors = [];

        if ( data.salutation != 'ms' && data.salutation != 'mr' ) {
            errors.push({
                message: app.lng('Anrede fehlt'),
                reds: [$(':input[name=upload_person_salutation]').parent()]
            });
        }

        if ( data.firstname == '' ) {
            errors.push({
                message: app.lng('Vorname fehlt'),
                reds: [$('#first'), $('label[for=first]')]
            });
        }

        if ( data.surname == '' ) {
            errors.push({
                message: app.lng('Nachname fehlt'),
                reds: [$('#last'), $('label[for=last]')]
            });
        }

        if ( data.bday == 0 || data.bmonth == 0 || data.byear == 0 ) {
            errors.push({
                message: app.lng('Geburtsdatum falsch'),
                reds: [$(':input[name=upload_person_birthday]').parent(), $(':input[name=upload_person_birthmonth]').parent(), $(':input[name=upload_person_birthyear]').parent(), $('.birthday-form label')]
            });
        } else if ( this.wettbewerbID == 3 && this.getAge(data.byear, data.bmonth - 1, data.bday) > 25 ) {
            errors.push({
                message: app.lng('Nachwuchsalter größer als 25'),
                reds: [$(':input[name=upload_person_birthday]').parent(), $(':input[name=upload_person_birthmonth]').parent(), $(':input[name=upload_person_birthyear]').parent(), $('.birthday-form label')]
            });

            var topPosition = $('#register-form')[0];
            topPosition = topPosition.offsetTop + 80;

            this.showUploadNotice(
                "<h3>" + app.lng('Fehler') + "</h3>" + 
                "<p class=\"error\">" + app.lng('Sie überschreiten leider die Altersgrenze des Nachwuchswettbewerbs von 25 Jahren. Sofern Sie professioneller Fotograf sind, nehmen Sie bitte am regulären Wettbewerb Teil.') + "</p>", topPosition
            );
            this.appendCloseButtonToUploadNotice(true);
        }

        if ( data.email == '' ) {
            errors.push({
                message: app.lng('E-Mail-Adresse fehlt'),
                reds: [$('#email'), $('label[for=email]')]
            });
        }

        if ( data.nation == '' ) {
            errors.push({
                message: app.lng('Nationalität fehlt'),
                reds: [$('#nation').parent(), $('label[for=nation]')]
            });
        }

        if ( data.countrycode == '' ) {
            errors.push({
                message: app.lng('Ländervorwahl fehlt'),
                reds: [$('#countrycode'), $('label[for=countrycode]')]
            });
        }

        if ( data.telephone == '' ) {
            errors.push({
                message: app.lng('Telefonnummer fehlt'),
                reds: [$('#telephone'), $('label[for=telephone]')]
            });
        }

        if ( data.country == '' ) {
            errors.push({
                message: app.lng('Land fehlt'),
                reds: [$('#country').parent(), $('label[for=country]')]
            });
        } else {
            var country = data.country.toLowerCase();
            switch ( country ) {
                case 'de':
                    if ( $(':input[name=upload_zipcode]', $form).val() == '' ) {
                        errors.push({
                            message: app.lng('Postleitzahl fehlt'),
                            reds: [$(':input[name=upload_zipcode]', $form), $('label[for=address-de-zipcode]', $form)]
                        });
                    }
                    if ( $(':input[name=upload_city]', $form).val() == '' ) {
                        errors.push({
                            message: app.lng('Ort fehlt'),
                            reds: [$(':input[name=upload_city]', $form), $('label[for=address-de-city]', $form)]
                        });
                    }
                    if ( $(':input[name=upload_address_street]', $form).val() == '' ) {
                        errors.push({
                            message: app.lng('Straße fehlt'),
                            reds: [$(':input[name=upload_address_street]', $form), $('label[for=address-de-street]', $form)]
                        });
                    }
                    if ( $(':input[name=upload_address_number]', $form).val() == '' ) {
                        errors.push({
                            message: app.lng('Hausnummer fehlt'),
                            reds: [$(':input[name=upload_address_number]', $form), $('label[for=address-de-number]', $form)]
                        });
                    }
                    break;
                case 'jp':
                    if ( $(':input[name=upload_zipcode]', $form).val() == '' ) {
                        errors.push({
                            message: app.lng('Postleitzahl fehlt'),
                            reds: [$(':input[name=upload_zipcode]', $form), $('label[for=address-jp-zipcode]', $form)]
                        });
                    }
                    if ( $(':input[name=upload_address_prefecture]', $form).val() == '' ) {
                        errors.push({
                            message: app.lng('Präfektur fehlt'),
                            reds: [$(':input[name=upload_address_prefecture]', $form), $('label[for=address-jp-prefecture]', $form)]
                        });
                    }
                    break;
                case 'us':
                    if ( $(':input[name=upload_zipcode]', $form).val() == '' ) {
                        errors.push({
                            message: app.lng('Postleitzahl fehlt'),
                            reds: [$(':input[name=upload_zipcode]', $form), $('label[for=address-us-zipcode]', $form)]
                        });
                    }
                    if ( $(':input[name=upload_city]', $form).val() == '' ) {
                        errors.push({
                            message: app.lng('Ort fehlt'),
                            reds: [$(':input[name=upload_city]', $form), $('label[for=address-us-city]', $form)]
                        });
                    }
                    if ( $(':input[name=upload_address_street]', $form).val() == '' ) {
                        errors.push({
                            message: app.lng('Straße fehlt'),
                            reds: [$(':input[name=upload_address_street]', $form), $('label[for=address-us-street]', $form)]
                        });
                    }
                    if ( $(':input[name=upload_address_number]', $form).val() == '' ) {
                        errors.push({
                            message: app.lng('Hausnummer fehlt'),
                            reds: [$(':input[name=upload_address_number]', $form), $('label[for=address-us-number]', $form)]
                        });
                    }
                    if ( $(':input[name=upload_state]', $form).val() == '' ) {
                        errors.push({
                            message: app.lng('Bundesstaat fehlt'),
                            reds: [$(':input[name=upload_state]', $form).parent(), $('label[for=address-us-state]', $form)]
                        });
                    }
                    break;
                default:
                    if ( $(':input[name=upload_zipcode]', $form).val() == '' ) {
                        errors.push({
                            message: app.lng('Postleitzahl fehlt'),
                            reds: [$(':input[name=upload_zipcode]', $form), $('label[for=address-normal-zipcode]', $form)]
                        });
                    }
                    if ( $(':input[name=upload_city]', $form).val() == '' ) {
                        errors.push({
                            message: app.lng('Ort fehlt'),
                            reds: [$(':input[name=upload_city]', $form), $('label[for=address-normal-city]', $form)]
                        });
                    }
                break;
            }
        }

        if ( data.uploadtitle == '' ) {
            errors.push({
                message: app.lng('Titel der Serie fehlt'),
                reds: [$('#uploadtitle'), $('label[for=uploadtitle]')]
            });
        }

        if ( ! data.terms_accepted ) {
            errors.push({
                message: app.lng('Teilnahmebedingungen nicht akzeptiert'),
                reds: [$('#terms').next(), $('label[for=terms]')]
            });
        }

        if ( data.datastorage_accepted != 'yes' && data.datastorage_accepted != 'no' ) {
            errors.push({
                message: app.lng('Datennutzung fehlt'),
                reds: [$('.radio-privacy .leica-radiobutton, .radio-privacy label')]
            });
        }

        if ( this.wettbewerbID != 3 && this.wettbewerbID != 4 ) {
            errors.push({
                message: app.lng('Wettbewerbauswahl fehlt'),
                reds: [$('#wettbewerb-selection .leica-radiobutton, #wettbewerb-selection label')]
            });
        }

        if ( $('.upload-item.file').length < 10 ) {
            errors.push({
                message: app.lng('Es müssen mindestens 10 Bilder hochgeladen worden sein'),
                reds: (function () {
                    var ret = [$('.upload-text')];
                    if ( $('.upload-item').length < 10 ) {
                        ret.push($('#add-more-pics'));
                    }
                    $('.upload-item:not(.file)').each(function () {
                        ret.push($(this))
                    });
                    return ret;
                })()
            });
        }

        if ( errors.length ) {
            for ( var e in errors ) {
                $.each(errors[e].reds, function () {
                    this.addClass('error');
                });
            }

            $('<p id="signup-errors">').text(app.lng('Bitte füllen Sie die rot markierten Felder des Formulars aus.')).insertBefore($('.signup-form'));
            $('#overlay').scrollTo($('#signup-errors'));

            return false;
        }
        return true;
    },

    restyleInputs: function () {
        var self = this,
            cloudRoot = 'http://media.leica-oskar-barnack-preis.de';

        $('select').selectbox({
            animationSpeed: 0
        }).bind('change', function () {
            $(this).parent().removeClass('error');
            if ( $(this).parent().prev().is('label') ) {
                $(this).parent().prev().removeClass('error');
            }
        });
        $('input:radio').checkbox({
            cls: 'leica-radiobutton',
            empty: cloudRoot + '/images/empty.png'
        });
        $('input:checkbox').checkbox({
            cls: 'leica-checkbox',
            empty: cloudRoot + '/images/empty.png'
        });
    },

    addCounterToLabel: function ($elem) {
        var $element = ($elem || $(':input[data-maxlength]'));
        $element.each(function () {
            var max = $(this).data('maxlength'),
                $cnt = $('<span class="counter">').text(max).appendTo($('label[for="' + this.id + '"]'));
            $(this).bind('keyup.counter', function () {
                var val = $(this).val(),
                    cnt = val.length;
                if ( $(this).val().length > max ) {
                    $(this).val(val.substr(0, max));
                }
                $cnt.text(max - $(this).val().length);
            });
        });
    },

    addMorePics: function () {
        var self = this;

        $('#add-more-pics').click(function () {
            var $item = $('.upload-item:last').clone(true, true),
                num = $('.upload-item').length + 1,
                numText = (num < 10 ? '0' + num : num),
                index = num - 1;

            if ( num > 12 ) {
                return false;
            }

            $('.counter', $item).remove();
            $('.number', $item).text(numText + '.');
            $('label', $item).attr('for', 'upload-' + num).find('span:first').text(numText);
            $('input[type=text]', $item).attr({
                name: 'upload_Filetitle_' + num,
                id: 'upload-' + num
            }).val('').unbind('keyup.counter');
            $('.filename', $item).text(app.lng('keine Datei ausgewählt'));

            $('.file-upload-input', $item).attr({
                name: 'upload_Filedata_' + num
            });
            $('.choose-file', $item).html(app.lng('&raquo; Datei wählen'));

            $item.removeClass('file').appendTo($('#upload-fields')).fileupload(self.uploadOptions);

            self.addCounterToLabel($('input[type=text]', $item));

            if ( num == 12 ) {
                $(this).fadeOut(self.fadeSpeed);
            }
        });
    },

    manipulateDropdowns: function () {
        var self = this,
            $nation = $(':input[name=upload_person_nation]'),
            $bday = $(':input[name=upload_person_birthyear]'),
            $privacy = $('.radio-privacy');

        if ( $nation.length ) {
            var c = this.countries[this.siteLanguage];
            for ( var i in c ) {
                $('<option value="' + i + '">' + c[i] + '<\/option>').data('nouml', c[i].replace('Ä', 'A').replace('Ö', 'O')).appendTo($nation);
            }
            $nation.find('option:not(:first)').sortElements(function(a, b) {
                return $(a).data('nouml') > $(b).data('nouml') ? 1 : -1;
            }).clone().appendTo($('#country'));
        }

        if ( $bday.length ) {
            for ( var i = 1908; i < 2005; i++ ) {
                $('<option value="' + i + '">' + i + '<\/option>').appendTo($bday);
            }
        }

        if ( $privacy.length ) {
            $('#sendinfo-checkboxes').show();
            /*
            setInterval(function () {
                if ( $('#privacy-yes', $privacy).is(':checked') ) {
                    $('#sendinfo-checkboxes').show();
                } else {
                    $('#sendinfo-checkboxes').hide();
                }
            }, 50);
            */
        }
    },

    lightbox: function (url) {
        location.hash = url;
    },

    initLightbox: function () {
        var self = this,
            $overlay = $('<div id="overlay"><\/div>').appendTo($('body')),
            $lightbox = $('<div id="lightbox"><\/div>').appendTo($overlay),

            loadLightbox = function (href) {
                $lightbox.addClass('loading');

                $overlay.unbind('click', closeLightbox);
                $(document).unbind('keyup', bindKeyPress);

                $.cookie('lbref', href, { path: '/' });

                var applying = href.split('/').pop();
                
                if ( applying != 'anmeldungsformular' && applying != 'application-form' ) {
                    if ( self.lbCloseOnClick ) {
                        $overlay.click(closeLightbox);
                    }
                    if ( self.lbCloseOnEsc ) {
                        $(document).bind('keyup', bindKeyPress);
                    }
                }

                $lightbox.load(href, function () {
                    if ( $('.lb-gallery', $lightbox).length ) {
                        self.initLightboxGallery();
                    }

                    self.manipulateDropdowns();

                    self.restyleInputs();
                    self.addCounterToLabel();
                    self.addMorePics();

                    if ( $('#register-form', $lightbox).length) {
                        self.initUploadForm();
                    }

                    $('<span class="close">close<\/span>').prependTo($lightbox).one('click', closeLightbox);

                    $('a.lb', $lightbox).click(function (e) {
                        e.preventDefault();
                        location.hash = $(this).attr('href');
                    });

                    $(this).removeClass('loading');
                });
                openLightbox();
            },

            openLightbox = function () {
                $overlay.css('top', $(window).scrollTop());
                $('body').addClass('lightboxMode')/*.bind('touchmove', function (e) {
                    e.preventDefault();
                    var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
                    console.log(e);
                })*/;
                resizeLightbox();
                $overlay.fadeIn(self.fadeSpeed);

                $('.teaser iframe').each(function () {
                    var $img = $(this).parent().find('img');
                    $(this).remove();
                    $img.show();
                });
            },

            closeLightbox = function (e) {
                if ( e === null || ! $(e.target).parents('#lightbox').andSelf().is('#lightbox') || $(e.target).is('.close') ) {
                    $overlay.fadeOut(self.fadeSpeed, function () {
                        $lightbox.html('');
                    });
                    $('body').removeClass('lightboxMode');
                    location.hash = '';
                    $.cookie('lbref', null, { path: '/' });
                }
            },

            resizeLightbox = function () {
                var wW = $(window).width(),
                    wH = $(window).height();
                $overlay.css({
                    width: wW,
                    height: wH
                });
            },

            bindKeyPress = function (e) {
                if ( e.which == 27 ) {
                    closeLightbox(null);
                }
            };

        $(window).bind('scroll', function () {
            $overlay.css('top', $(window).scrollTop());
        });

        $('#main a:not("#language"), a.lb').click(function (e) {
            if ( ! $(this).parents('#submissions').length ) {
                e.preventDefault();
                location.hash = $(this).attr('href');
            }
        });

        $(window).resize(resizeLightbox).hashchange(function () {
            var hash = location.hash.replace('#', '');
            if ( hash !== '' ) {
                loadLightbox(hash);
            } else if ( $('body').hasClass('lightboxMode') ) {
                closeLightbox(null);
            }
        });

    },

    initLightboxGallery: function () {
        var self = this,
            $lightbox = $('#lightbox');
        $('.lb-gallery', $lightbox).each(function () {
            var $gallerySection = $(this),
                $gallery = $('ul', $gallerySection).wrap('<div><\/div>'),
                galleryWidth = 0,
                galleryUrl = $('img:first', $gallery).attr('src'),

                setImageTitle = function () {
                    var title = $('li:first img', $gallery).attr('alt');
                    if ( ! $('.lb-sub', $gallerySection).length ) {
                        $('<span class="lb-sub"><\/span>').insertAfter($('div', $gallerySection));
                    }
                    $('.lb-sub', $gallerySection).html(title == '' ? '&nbsp;' : title);
                },

                nextPicture = function () {
                    if ( $gallery.is(':animated') ) {
                        return false;
                    }
                    var $first = $('li:first', $gallery),
                        width = $first.outerWidth(true);
                    $gallery.animate({
                        marginLeft: -width
                    }, self.slideSpeed, function () {
                        $first.appendTo($gallery);
                        $gallery.css('marginLeft', 0);
                        setImageTitle();
                    });
                },

                prevPicture = function () {
                    if ( $gallery.is(':animated') ) {
                        return false;
                    }
                    var $last = $('li:last', $gallery),
                        width = $last.outerWidth(true);

                    $last.prependTo($gallery.css('marginLeft', -width));
                    $gallery.animate({
                        marginLeft: 0
                    }, self.slideSpeed, setImageTitle);
                };

            var cnt = $('li', $gallery).length,
                galleryI18n = self.siteLanguage == 'de' ? 'galerie' : 'gallery';

            galleryUrl = /static\/galleries\/([^\/]+)\//.exec(galleryUrl);
            if ( galleryUrl ) {
                galleryUrl = galleryUrl.pop();
            }

            $('li', $gallery).each(function (i) {
                galleryWidth += $(this).outerWidth(true);
                if ( cnt > 1 ) {
                    $('img', $(this)).wrap('<a href="' + self.root + '/' + self.siteLanguage + '/' + galleryI18n + '/' + galleryUrl + '/' + (i + 1) + '?lb"><\/a>');
                }
            });
            $gallery.width(galleryWidth);

            if ( cnt > 1 ) {
                $('<span class="lb-prev"><\/span>').click(prevPicture).disableTextSelect().appendTo($gallerySection);
                $('<span class="lb-next"><\/span>').click(nextPicture).disableTextSelect().appendTo($gallerySection);
            }

            setImageTitle();
        });
    },

    setPictures: function (pictures) {
        var pics = [];
        for ( var i in pictures ) {
            pics.push(pictures[i]);
        }
        this.pictures = pics;
        //this.preloadPictures();
    },

    preloadPictures: function () {
        for ( var i in this.pictures ) {
            var img = new Image();
                img.src = this.root + '/static/galleries/' + this.pictures[i].name;
        }
    },

    buildGallery: function () {
        var self = this;

        if ( this.pictures.length ) {
            if ( $('#gallery-index li').length ) {
                $('#gallery-index li').remove();
            }

            var contentWidth = $('#content-main').width(),
                rowId = 0,
                calcWidth = 0,
                galleryRows = [],
                cloudRoot = 'http://media.leica-oskar-barnack-preis.de';

            for ( var i = 0; i < this.pictures.length; i++ ) {
                var pWidth = this.pictures[i].width,
                    pHeight = this.pictures[i].height,
                    factor = this.pictures[i].width / this.pictures[i].height;

                if ( factor > 1 ) {
                    pHeight = 150;
                }
                if ( factor >= 2 ) {
                    pHeight = 120;
                }

                pWidth = pHeight * (factor);

                calcWidth += (pWidth + 30);
                if ( calcWidth > contentWidth ) {
                    rowId++;
                    calcWidth = pWidth;
                }
                if ( typeof galleryRows[rowId] === 'undefined' ) {
                    galleryRows[rowId] = { height: 0, pics: [] };
                }

                var file = cloudRoot + '/static/galleries/' + this.pictures[i].name;
                if ( $('#content-body').hasClass('entries') ) {
                    file = this.pictures[i].file;
                    self.pictureAppendix = '';
                }

                galleryRows[rowId].pics.push('<img src="' + file + '" width="' + pWidth + '" height="' + pHeight + '">');
                if ( pHeight > galleryRows[rowId].height ) {
                    galleryRows[rowId].height = pHeight;
                }
            }

            var number = 0;
            $.each(galleryRows, function () {
                var $galleryRow = $('<li class="row"><\/li>').height(this.height + 15), // 15 = height of 'number'
                    images = this.pics;
                for ( var j in images ) {
                    number++;
                    $('<p><span class="number">' + ( number < 10 ? '0' : '' ) + number + '</span><a href="' + self.root + '/' + self.galleryRoot + '/' + number + self.pictureAppendix + '">' + images[j] + '</a></p>').appendTo($galleryRow);
                }
                $galleryRow.appendTo($('#gallery-index'));
            });
        }
    },

    setGalleryRoot: function (val) {
        this.galleryRoot = val;
    },

    setPictureAppendix: function (val) {
        this.pictureAppendix = val;
    },

    flagElements: function ($elements) {
        $elements.each(function (i) {
            if ( ! $(this).data('flag') ) {
                $(this).data('flag', i);
            }
        });
    },

    setStartThumbs: function (json) {
        this.startThumbs = json;
    },

    setHomeColumns: function (isThumbHome) {
        // flag elements for sorting
        this.flagElements($('.teaser'));

        var newWidth = $(window).width() - 50,
            columnWidth = (isThumbHome ? 199 : 399),
            columnCount = Math.floor(newWidth / columnWidth),
            minColumnCount = (isThumbHome ? 4 : 2),
            maxColumnCount = (isThumbHome ? 8 : 4),
            teaserClassName = (isThumbHome ? 'thumb-column' : 'teaser-column');

        // min and max of columns
        if ( columnCount < minColumnCount ) {
            columnCount = minColumnCount;
        } else if ( columnCount > maxColumnCount ) {
            columnCount = maxColumnCount;
        }

        // new column count
        if ( this.columns != columnCount ) {
            this.columns = columnCount;
            // adjust site width
            newWidth = (columnCount * columnWidth) + (columnCount - 1);
            $('#site').css('width', newWidth);

            $('.teaser iframe').each(function () {
                var $img = $(this).parent().find('img');
                $(this).remove();
                $img.show();
            });

            // reset all teasers and sort them
            $('.teaser').each(function () {
                $(this).removeClass('set').appendTo($('#content'));
            }).sortElements(function(a, b) {
                return $(a).data('flag') > $(b).data('flag') ? 1 : -1;
            });
            // remove teaser columns
            $('.' + teaserClassName).remove();

            // add new number of teaser columns
            for ( var i = 0; i < this.columns; i++ ) {
                var $col = $('<div class="' + teaserClassName + '">').prependTo($('#content'));
                if ( i < columnCount - 1 ) {
                    $col.css('marginLeft', 1);
                }
            }

            if ( isThumbHome ) {
                var teaserLeftPosition = 400,
                    teaserWidth = 799,
                    teaserColumnIndexes = [1, 2],
                    thumbArray = [],
                    entriesI18n = app.lng('einsendungen');

                for ( var i in this.startThumbs ) {
                    var contest = i.split('_').shift(),
                        awardI18n = ( contest == 'obp' ? app.lng('leica-oskar-barnack-preis') : app.lng('leica-oskar-barnack-nachwuchspreis') ),
                        entry = this.startThumbs[i],
                        $thumb = $('<div class="thumb loading"><\/div>').css({
                            height: entry.thumb.height
                        }),
                        $link = $('<a class="gal" href="' + this.root + '/' + this.siteLanguage + '/' + entriesI18n + '/' + awardI18n + '/' + entry.url + '"><\/a>'),
                        $img = $('<img src="' + entry.thumb.file + '"\/>'),
                        country = (entry.country != '' ? ',</b><br>' + this.countries[this.siteLanguage][entry.country] : '</b>');


                    $img.data('name', entry.name + country).load(function () {

                        $(this).data('size', {
                                    width: this.width,
                                    height: this.height
                                })
                                .fadeIn(app.fadeSpeed)
                                .parents('.thumb')
                                .removeClass('loading')

                        $('<span><b>' + $(this).data('name') + '<\/span>').css('backgroundPosition', '10px ' + ($(this)[0].height - 35) + 'px').appendTo($(this).parent());
                        
                    }).appendTo($link);
                    

                    $link.appendTo($thumb);
                    thumbArray.push($thumb);
                }

                switch ( columnCount ) {
                    case 4:
                        teaserLeftPosition = 200;
                        teaserWidth = 399;
                        break;
                    case 5:
                        teaserLeftPosition = 200;
                        teaserColumnIndexes = [1, 2, 3, 4];
                        break;
                    case 6:
                        teaserLeftPosition = 200;
                        teaserColumnIndexes = [1, 2, 3, 4];
                        break;
                    case 7:
                        teaserLeftPosition = 200;
                        teaserColumnIndexes = [1, 2, 3, 4];
                        break;
                    case 8:
                        teaserColumnIndexes = [2, 3, 4, 5];
                        break;
                }
                
                if ( ! $('#teaser-content').length ) {
                    $('<div id="teaser-content"><\/div>').appendTo($('#content'));
                }

                $('#teaser-content').css({
                    left: teaserLeftPosition,
                    width: teaserWidth
                }).html('');

                var teaserColumns = ( teaserWidth == 799 ? 2 : 1 ),
                    teaserPerColumn = Math.ceil($('.teaser').length / teaserColumns),
                    $teaser = $('.teaser'),
                    teaserIn;

                for ( var i = 0; i < teaserColumns; i++ ) {
                    $('<div class="teaser-column"><\/div>').appendTo($('#teaser-content'));
                }

                $('.teaser-column').each(function (teaserColIndex) {
                    var $col = $(this).css({ marginLeft: teaserColIndex });
                    $teaser.not('.set').each(function (i) {
                        if ( i >= teaserPerColumn ) {
                            return false;
                        }
                        $(this).addClass('set').appendTo($col);
                    });
                });

                if ( teaserWidth == 799 ) {
                    var heightOdd = heightEven = 0;
                    $('.teaser-column').each(function (teaserIndex) {
                        var height = $(this).outerHeight(true);
                        if ( teaserIndex % 2 == 0 ) {
                            heightEven += height;
                        } else {
                            heightOdd += height;
                        }
                    });
                    var teaserHeight = Math.max(heightEven, heightOdd);
                } else {
                    var teaserHeight = $('.teaser-column').outerHeight(true);
                }

                var marginTop = $('#teaser-content').outerHeight(true);
                $.each(teaserColumnIndexes, function (i, v) {
                    if ( teaserColumnIndexes.length == 4 ) {
                        marginTop = ( i < 2 ? heightEven : heightOdd );
                    }
                    
                    $('.thumb-column').eq(v).css({
                        marginTop: marginTop
                    });
                });

                $('#teaser-content').height(teaserHeight);

                var $currCol = $('.thumb-column:first'),
                    columnIndex = 0,

                    appendWhatsLeft = function () {
                        var height = 0;
                        $.each(thumbArray, function () {
                            height += this.outerHeight(true);
                        });
                        var maxColumnHeight = Math.ceil(height / columnCount),
                            $columns = $('.' + teaserClassName);

                        $columns.each(function (colIndex) {
                            var $column = $(this),
                                thisColHeight = 0;
                            $.each(thumbArray, function (i, v) {
                                // remove thumb from array
                                if ( ( thisColHeight + thumbArray[0].outerHeight(true) ) >= maxColumnHeight ) {
                                    return false;
                                }
                                var $thumb = thumbArray.shift();
                                $thumb.appendTo($column);
                                thisColHeight += $thumb.outerHeight(true);
                            });
                        });
                    };

                $.each(thumbArray, function (i, e) {
                    // remove thumb from array
                    var $thumb = thumbArray.shift();
                    // append thumb to curretn column
                    $thumb.appendTo($currCol);
                    if ( $currCol.height() >= teaserHeight ) {
                        columnIndex++;
                        while ( in_array(columnIndex, teaserColumnIndexes) ) {
                            columnIndex++;
                        }
                        $currCol = $('.thumb-column').eq(columnIndex);
                        // first run finished
                        if ( $currCol.length == 0 ) {
                            appendWhatsLeft();
                            return false;
                        }
                    }
                });

            } else {
                // fill the columns with the teasers
                var height = $('#content').height(),
                    maxColumnHeight = Math.ceil(height / columnCount),
                    $columns = $('.' + teaserClassName);

                $columns.each(function (colIndex) {
                    var $column = $(this);
                    $('.teaser:not(.set)').each(function () {
                        var columnHeight = $column.height(),
                            teaserHeight = $(this).height();
                        
                        if ( maxColumnHeight < teaserHeight ) {
                            maxColumnHeight = teaserHeight;
                        }

                        var availHeight = maxColumnHeight - columnHeight;

                        // if the teaser fits in the column
                        if ( teaserHeight <= availHeight ) {
                            $(this).appendTo($column).addClass('set');
                        } else {
                            // if not switch to the next column
                            return false;
                        }
                    });
                });

                // if there are teasers left assign one at a time
                $('.teaser:not(.set)').each(function () {
                    var minHeight = 0,
                        colIndex = 0;
                    // get the smallest column
                    $columns.each(function (i) {
                        if ( minHeight == 0 || $(this).height() < minHeight ) {
                            minHeight = $(this).height();
                            colIndex = i;
                        }
                    });
                    // and add current teaser to it
                    $(this).appendTo($columns.eq(colIndex));
                });
            }

        }

    },

    setSiteWidth: function () {
        if ( $('.teaser').length ) {
            var thumbs = false;
            if ( $('#content-thumbs').length ) {
                thumbs = true;
            }
            this.setHomeColumns(thumbs);
            this.adjustFooterWidth();
            return;
        }

        var newWidth = $(window).width() - 50; // 80 = site margin left + right
        if ( newWidth < this.maxSideWidth ) {
            if ( newWidth < this.minSideWidth ) {
                newWidth = this.minSideWidth;
            }
        } else {
            newWidth = this.maxSideWidth;
        }

        newWidth -= ((newWidth % 20) + 1);
        
        //if ( newWidth != this.prevNewWidth ) {
            this.buildGallery();
        //}

        this.prevNewWidth = newWidth;

        $('#site').css('width', newWidth);

        if ( this.is('gallery-single') ) {
            this.resizeBigPicture();
        }

        this.adjustFooterWidth();
    },

    adjustContentHeight: function () {
        $('#content-main').height('auto');

        var minHeight = $('#content-sidebar').outerHeight();
        if ( $('#content-main').height() < minHeight ) {
            $('#content-main').height(minHeight);
        }

        var minSiteHeight = $(window).height() - ($('header').outerHeight(true) + $('#content-top').outerHeight(true) + $('footer').outerHeight(true) + 73);
        if ( $('#content-main').height() < minSiteHeight ) {
            $('#content-main').height(minSiteHeight);
        }

    },

    adjustFooterWidth: function () {
        var maxColWidth = 419,
            footerWidth = $('footer').width() - 200,
            colWidth = Math.floor(footerWidth / 2);
        if ( (maxColWidth * 2) > footerWidth ) {
            $('.column').width(colWidth - 21);
        } else {
            $('.column').width(maxColWidth - 20);
        }
    },

    setFooterPosition: function () {
        $('#content').css('height', 'auto');

        var winH = $(window).height(),
            contentH = $('header').height() + $('#content').height(),
            footerH = $('footer').outerHeight(true) + 2;

        if ( contentH + footerH < winH ) {
            contentH = winH - (footerH + $('header').height());
            $('#content').height(contentH);
        }
    },

    resizeBigPicture: function () {
        var $pic = $('#gallery-single img'),
            contentWidth = $('#content-main').width() - 26,
            maxHeight = $(window).height() - 230;

        if ( ! $pic.data('size') ) {
            if ( $('#content-body').hasClass('entry') ) {
                $('#gallery-single').css('height', 40);
                $pic.hide().load(function () {
                    $pic.data('size', [ $pic[0].width, $pic[0].height ]);
                    $('#gallery-single').css('height', 'auto');
                    $(window).trigger('resize');
                });
                return false;
            }
            $pic.data('size', [ $pic.width(), $pic.height() ]);
        }
        var picSize = $pic.data('size'),
            newWidth = contentWidth;
        if ( contentWidth > picSize[0] ) {
            newWidth = picSize[0];
        }
        var newHeight = newWidth * (picSize[1] / picSize[0]);

        if ( newHeight > maxHeight ) {
            newHeight = maxHeight;
            newWidth = newHeight * (picSize[0] / picSize[1]);
        }

        $pic.attr({
            width: newWidth,
            height: newHeight
        });

        if ( $pic.is(':hidden') ) {
            $pic.fadeIn();
        }
    },

    initVideoLinks: function () {
        $('img[data-videourl]').each(function () {
            var $figure = $(this).parent(),
                vid = $(this).data('videourl').split('/').pop();
            $(this).click(function () {
                var $iframe = $('<iframe src="http://player.vimeo.com/video/' + vid + '?title=0&amp;byline=0&amp;portrait=0&amp;autoplay=1" width="399" height="226" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>');
                $(this).hide();
                $iframe.prependTo($figure);
            });
        });
    },

    setSitePosition: function () {
        var winWidth = $(window).width();
        winWidth -= winWidth % 20;
        var siteWidth = $('#site').width();

        var left = Math.floor((winWidth - siteWidth) / 2);

        if ( left >= 20 ) {
            $('#site').css('left', left - (left % 20));
        }

        this.setFooterPosition();

    },

    setSiteLanguage: function () {
        var path = location.pathname.split('/'),
            first = ( path.length > 1 && path[0] == '' ? path[1] : path[0] );
        if ( first == 'de' || first == 'en' ) {
            this.siteLanguage = first;
        }
    },

    preloadI18n: function (lang) {
        this.i18n = lang;
    },

    lng: function (msgId) {
        var siteLanguage = this.siteLanguage;
        if ( typeof this.i18n[siteLanguage][msgId] === 'undefined' ) {
            return msgId;
        } else {
            return this.i18n[siteLanguage][msgId];
        }
    }

};

var app = new Leica();
app.setSiteLanguage();

$(function () {
    app.initShareButtons();
    app.initSubMenus();
    app.initLightbox();
    app.initVideoLinks();

    app.setSiteWidth();
    $(window).resize(function () {
        app.setSiteWidth();
    });

    if ( app.is('gallery-index') ) {
        app.buildGallery();
    }

    if ( app.is('content-sidebar') ) {
        app.adjustContentHeight();
        $(window).resize(function () {
            app.adjustContentHeight();
        });
    }

    app.setSitePosition();
    $(window).resize(function () {
        app.setSitePosition();
    });

    $(window).trigger('hashchange');

    $('.top').click(function () {
        $(window).scrollTop(0);
    });

    if ( $('a.nextpic').length ) {
        $('#gallery-single img').wrap('<a href="' + $('a.nextpic').attr('href') + '"><\/a>');
    }
});


