(function(window, undefined)
{
    var Curtain = function(conf)
    {
        this._init_(conf);
    }
    Curtain.prototype =
    {
        _init_:function(conf)
        {
            this.curtain = conf.curtain;
            this.closedWidth = conf.closedWidth;
            this.openWidth = conf.openWidth;

            this.rope = conf.rope;
        },
        doSth : function()
        {
            this.isOpen();
        },
        isOpen : function()
        {
            if( this.openWidth === this.curtain.width() )
            {
                return true;
            }
            if( this.closedWidth === this.curtain.width() )
            {
                return false;
            }
            return null;
        },
        isClosed : function()
        {
            var val = this.isOpen();
            if(null === val){return null;}
            return (!val);
        },
        isOpening : function()
        {
        },
        isCloseing : function()
        {
        },
        open : function()
        {
            //return if it is open or opening
            if(
                (true === this.isOpen())
              || this.isOpening()
            )
            { return; }
            //var self = this;
            this.pullRope();
            this.curtain.animate(
                {
                    width: [this.openWidth, 'swing']
                },
                300,
                function()
                {
                    // Animation complete.
                    console.log('opened');
                }
            );
        },
        close : function(callback)
        {
            if( (true === this.isClosed())
              || this.isCloseing())
            {
                //don't forget the callback!
                //if isCloseing there should be another thing to do
                callback();
                return;
            }
            //var self = this;
            this.pullRope();
            this.curtain.animate(
                {
                    width: [this.closedWidth, 'swing']
                },
                300,
                function()
                {
                    // Animation complete.
                    callback();
                    console.log('closed');
                }
            );
        },
        pullRope: function()
        {
            var self = this;
            this.rope.animate(
            {
                top: [ 26, 'swing']
            },
            150,
            function()
            {
            // Animation complete.
                self.rope.animate(
                {
                    top: [ 19, 'swing']
                },
                75
                )
            });
        }
    };
    window.Curtain = Curtain;
})(window);

(function(window, undefined)
{
    var Cache = function(conf)
    {
        this._cache = {};
    };
    Cache.prototype =
    {
        set : function(key, data)
        {
            this._cache[escape(key)] = data;
            return true;
        },
        get : function(key)
        {
            return this._cache[escape(key)] || null;
        },
        has : function(key)
        {
            if(undefined !== this._cache[escape(key)])
            {
                return true;
            }
            return false;
        }
    };
    window.Cache = Cache;
})(window);



jQuery(function($)
{
    try
    {
        console;
    }
    catch(err)
    {
        console =
        {
            log: function(){},
            dir: function(){}
        }
    }
});
jQuery(function($)
{
    var $header = $('.header').eq(0);

    var getRand = function(mini, maxi)
    {
        return (mini + parseInt( Math.random() * ( maxi - mini + 1 ) ) );
    }

    var animateCloud = function(key)
    {
        var v = clouds[key];
        x = getRand(v.x[0], v.x[1]);
        y = getRand(v.y[0], v.y[1]);
        $(v.selector, $header).animate(
            {
                left: [x, 'linear'],// 'swing'
                top: [y, 'linear']// 'swing'
            },
            getRand(2500, 3000),
            function()
            {
                // Animation complete.
                setTimeout ( function(){animateCloud(key)}, 50);
            }
        );
    }
    var clouds = [
        {
            selector : '.cloud1',
            x : [142,152],//left:147px
            y : [52,62]//top: 57px
        },
        {
            selector : '.cloud2',
            x : [225,235],//left:230px;
            y : [60,70]//top:65px;
        },
        {
            selector : '.cloud3',
            x : [564,574],//left:569px;
            y : [30,40]//top:35px;
        },
    ];

    setTimeout ( function()
    {
        for(var cloud in clouds)
        {
            animateCloud(cloud);
        }
    }, 500 );

    var twinkerData =
    {
        'duration' : 400,
        'minBreak' : 3000,
        'maxBreak' : 7000
    };
    var $girl = $('.girl .closedEyes');

    var twinker = function()
    {
        //open eyes
            $girl.removeClass('active');
        var close = function()
        {
            //close eyes
            $girl.addClass('active');
            //open in twinkerData.duration
            setTimeout(twinker,twinkerData.duration);
        }
        //close in some secconds
        setTimeout(
            close,
            getRand(twinkerData.minBreak, twinkerData.maxBreak)
        )
    }
    twinker();

    //left and right curtain
    var CurtainClosedWidth = 161;

    var cur = new Curtain({
        curtain: $('.curtain-left').eq(0),
        closedWidth: CurtainClosedWidth,
        openWidth: 80,
        rope: $('.rope').eq(0)
    });
    cur.doSth();


    //used with each
    //to make the spammers live a bit harder
    //$('span.no-spam').each(makeMail);
    //from:
    //  <span class="no-spam">name [a   t }dom<code>ian{d oT]c</code>om</span>
    //to:
    //  <a href="mailto:name@domain.org">mailto:name@domain.org</a>
    var makeMail = function()
    {
        var $element = $(this);
        // replace spaces with nothing
        var email = $element.text()
            .toLowerCase()
            .replace(/\s+/g, '')
            .replace(/[\[{]at[}\]]/, '@')
            .replace(/[\[{]dot[}\]]/,'.');
        $element.replaceWith
        (
            $(document.createElement('a'))
            .attr('href','mailto:'+ escape(email))
            .text(email)
        );
    }
    var pwxSettings =
    {
        //the most of these settings do no longer have any effect
        maxResults: 5,
        showAlbumDescription: true,
        showPhotoCaption: true,
        photoCaptionLength: 500,
        showPhotoDate: true,
        showSlideshowLink: true,
        maxResults: 2,
        mode: 'album',
        thumbSize: 512,
        //thumbSize: 320,
        thumbCrop: true
    }
    //all links where href is starting width /
    //not of .language-switch, these have to reload/change/translate the whole interface

    var setActive = function(href)
    {
        var $mainMenu = $('.header .menu li');
        //    if href is in the main menu
        //    else we presst a link not in the mainmenu, but in a submenu or in the text
        //    there will be no active link in the mainmenu if we unset it here
        var links = $('a[href="' + href + '"]',$mainMenu);

        //thats not really right, but diary for example would stay active if we load a filter
        if(links.length === 0)
        {
            return;
        }
        $mainMenu.removeClass('active');
        links.parent().addClass('active');
    }


    var ajaxSelector = 'a[href^="/"], .tourmap area[href^="/"]';
    var ajaxSelectorNot = [
        '.language-switch a',
        'a[href*=download]',
        '.tourmap area[href*=download]'
    ];

    var makeHoverMap = function($map, $context)
    {
        /*
         * the html map element is great, it lets us define free forms as clickable areas on a link
         * but there seems to be no way to style the area elements
         * */

        // $map is a div containing a map element
        //that class adds a background image to the class with the map image
        $map.addClass('hovering');
        //change the filename of the real image to blank.gif a fully transparent gif
        //will show the div with the map image, it showed rh map before
        var mapImg = $('img', $map);
        var src = mapImg.attr('src').split('/');
        delete  src[src.length - 1];
        src.push( 'blank.gif');
        //finally make the new src attribute
        mapImg.attr('src', src.join('/'));


        //add hovering states to the $map div
        //for each element we specify here
        //the hovering states have a display:none rule
        //having a class "active" they become display:block
        var countries = ['peru', 'bolivia', 'ecuador'];
        var selector;
        for(var key in countries)
        {
            $map.prepend
            (
                $(document.createElement('div')).addClass('mapImage ' + countries[key])
            );

            selector = 'div.mapImage.'+countries[key];

            var over = (function($country){return function (evt)
            {
                $('div.mapImage', $map).removeClass('active');
                //$($(this).data('mapImage'), $map).addClass('active');

                $($('area.' + $country, $map).eq(0).data('mapImage'), $map).addClass('active');

            }})(countries[key])
            var out = function (evt)
            {
                $('div.mapImage', $map).removeClass('active');
            }
            //areas
            $('area.' + countries[key] ,$map).hover(over, out).data('mapImage', selector);;

            $('.submenu .'+countries[key]+' a', $context).hover(over, out);

            $('.screenings.'+countries[key]+' a', $context).hover(over, out);//.css({border: '2px solid lime'});

        }
    }
    var activatePinheads = function($context)
    {
        var effect = 'fade';

        if( $.browser.msie && $.browser.version < 9)
        {
            effect = 'toggle';
        }
        $('.pin', $context).each(function(i, elem)
        {
            var ph = $('.pinhead', elem)
            var $elem = $(elem);

            var texts = $elem.attr('title').split(' ')
            var tip = $(document.createElement('div')).addClass('tooltip');
            if($elem.hasClass('screening'))
            {
                tip.addClass('screening');
            }

            $elem.removeAttr('title');
            for(var i in texts)
            {
                if(i == 0)
                {
                   tip.append($(document.createElement('strong')).text(texts[i]))
                   continue;
                }
                tip.append(document.createElement('br'))
                tip.append(texts[i])
            }
            $('body').append(tip);
            ph.tooltip({
                events: {
                    def:     "mouseover,mouseout mousedown",
                    input:   "focus,blur",
                    widget:  "focus mouseover,blur mouseout",
                    tooltip: "mouseover,mouseout"
                },
                tip: tip,
                effect : effect,
                offset: [-2, 44]
                //delay: 20
            })

            if($elem.hasClass('screening')){return}

            $elem.mouseover(function(e){$('.pinhead',this).tooltip().show()});
            var out = function(e){$('.pinhead',this).tooltip().hide()}
            $elem.mouseout(out);
            $elem.mousedown(out);
        });
    }


    //the ajax requests will be cached here as a first instance cache
    //if the user want's to play with the curtain
    //this will safe resources on the server an speed up execution
    var ajaxCache = new Cache();
    ajaxCache.set('hallo', 'welt');
    var ajaxRequesting = new Cache();
    var clickAjax = function(evt)
    {
        var url = href = $(this).attr('href');
        if( $.browser.msie)
        {
            //to overcome the cache of the intert Explorers
            //which will likeley return html content and make the ajax call fail
            //of course the response of url with ?ajax=true will be cached
            if(url.match(/\?/))
            {
                url += '&ajax=true';
            }
            else
            {
                url += '?ajax=true';
            }

        }

        if(ajaxRequesting.get(url))
        {
            console.log('Requesting url already: ' + url);
            return false;
        }
        ajaxRequesting.set(url, true);
        var success = function (data)
        {
            ajaxRequesting.set(url, false);
            //if it comes not from cache
            if(! ajaxCache.has(url) || (ajaxCache.get(url) !== data) )
            {
                //chache it
                ajaxCache.set(url, data);
            }

            document.title = data['title'];

            var $intropage = $('.intropage');
            if($intropage.length)
            {
                $('.intro', $intropage).remove();
                $('.curtain-right, .curtain-left', $intropage)
                .animate(
                    {
                        width: [CurtainClosedWidth, 'swing']
                    },
                    1500
                    ,function()
                    {
                        $intropage.removeClass('intropage');
                    }
                );

            }

            if(data['languageSwitch'])
            {
                var $content = $(document.createElement('div')).html(data['languageSwitch']);
                $('.page ul.language-switch').eq(0).empty()
                .append(
                    $('ul.language-switch', $content).get(0).childNodes
                );
            }

            if(data['mainMenu'])
            {
                var $content = $(document.createElement('div')).html(data['mainMenu']);
                $('.page .header ul.menu').eq(0).empty()
                .append(
                    $('ul.menu', $content).get(0).childNodes
                );
                var $header = $('.page .header');
                $('.homelink', $header).eq(0).attr('href', $('ul.menu .home a', $header).eq(0).attr('href'));
                $('ul.menu a, .homelink',$header).click(clickAjax);
                if(data['headerSign'])
                {
                    $('.sign img', $header).eq(0).attr('src', data['headerSign']);
                }
            }

            var $content = $(document.createElement('div')).html(data['content']);
            $('span.no-spam', $content).each(makeMail);
            $('.picasa-container', $content).each(function(i, elem)
            {
                $(elem).pwx($.extend({albumUrl: $('a.id', elem).eq(0).attr('href')}, pwxSettings));
            });
            //remove all leftover tooltips
            $('.tooltip').remove();
            //if theres a map in content ... make hovers
            var map = $('.tourmap', $content);
            if( map.length > 0)
            {
                makeHoverMap(map.eq(0),  $content);
                activatePinheads($content);
            }
            //add this function to the new loacal links in the content
            var $ajaxize = $(ajaxSelector, $content);
            for(var notSelector in ajaxSelectorNot)
            {
               $ajaxize =  $ajaxize.not(ajaxSelectorNot[notSelector]);
            }

            //self copy?! this?
            $ajaxize.click(clickAjax);
            //if theres a sub menu in content ... open the curtain
            if( $('.submenu', $content).length > 0)
            {
                $('.stage').eq(0).empty().append($content.get(0).childNodes);
                cur.open();
                setActive( href );
            }
            else
            {
                cur.close(function()
                {
                    $('.stage').eq(0).empty().append($content.get(0).childNodes);
                    setActive( href );
                });
            }
        }
        if(ajaxCache.has(url))
        {
            success( ajaxCache.get(url) );
        }
        else
        {
            $.ajax({
                'async': true,
                'global': false,
                'dataType': 'json',
                //here
                'url':  url,
                'success': success,
                'error': function(request, textStatus, errorThrown)
                {
                    ajaxRequesting.set(url, false);
                    var say = 'ajax error ' + request.status + ' ' + request.statusText;

                    if(request.status == 200)
                    {
                        //alert('error on ' + href + ' : ' + say + request.responseText);
                    }
                    //alert(say);
                    console.log(say + "\n" + request.responseText);
                }
            });
        }
        //stop propagation of this event, don't leave the page
        return false;
    };

    var map = $('.stage .tourmap');
    if( map.length > 0)
    {
        makeHoverMap(map.eq(0));
        activatePinheads();
    }
    var $ajaxize = $(ajaxSelector);
    for(var notSelector in ajaxSelectorNot)
    {
        $ajaxize = $ajaxize.not(ajaxSelectorNot[notSelector]);
    }

    $ajaxize.click(clickAjax)
    //um zu sehen ob und wo was passiert
    //.attr('style', 'text-transform:uppercase;');
    //var map = $('.stage .tourmap');
    //if( map.length > 0)
    //{
        //makeHoverMap(map.eq(0));
    //}

    $('.page.intropage .language-switch a').each(function(index)
    {
        var url = $(this).attr('href');
        if(url.match(/\?/))
        {
            url += '&mainmenu=true';
        }
        else
        {
            url += '?mainmenu=true';
        }
        $(this).attr('href', url).click(clickAjax);
    });



    // E-Mail Adresse anzeigen
    $('span.no-spam').each(makeMail);
    $('.picasa-container').each(function(i, elem)
    {
        $(elem).pwx($.extend({albumUrl: $('a.id', elem).eq(0).attr('href')}, pwxSettings));
    });

});
