var panel={};
panel.params = [];
panel.slides = [];
panel.status = 'HIDDEN';
panel.language = '';
panel.activeSlide=0;
panel.animationComplete=true;
panel.isOpen=false;
panel.canOpen=false;
var background = {
    animationComplete:true
}

var SLIDE_TPL = $.template('<div id="${id}" class="slide"><div class="slidebox"><div class="slide-content">${content}</div></div><div class="slide-number"><a href="#!${path}/">${number}</a></div></div>');

var AUTO_LINKS = 'a:not([href^=http],[href^=mailto])';
var BG_WIDTH = 1920;
var BG_HEIGHT = 1109;
var BACKGROUND_FADE = 3000;
var HEADLINE_FADE = 1000;
var SLIDER_TIME_BOTTOM = 800;
var SLIDER_TIME_LEFT = 1200;
var MENU_FADE = 'slow';
var SLIDE_FADE = 'slow';
var SCROLLBAR_SETTINGS = {
    showArrows: false,
    scrollbarWidth: 15
};
var WIN_WIDTH_CORR = 0;
var WIN_HEIGHT_CORR = 0;
var FIX_BG_HEIGHT = false;


function loadPage(event) {
    var newParams = event.path.replace(/^\/|\/$/g, "").split('/');
    if(newParams[0]==""){
        panel.slides[0]={};
        panel.nextSlide=0;
        return;
    }
    panel.nextSlide = newParams.length-1;
    if(newParams[0] != panel.params[0]){
        fadeOutSlide();
        panel.callbackFunction = fadeInSlide;
    } else {
        panel.callbackFunction = slideToSlide;
    }
    panel.params=newParams;
    $(panel.params).each(function(index,slug){
        if(typeof(panel.slides[index])== "undefined" || panel.slides[index].slug!=slug || panel.slides[index].isGarbage){
            panel.slides[index] = {};
            panel.slides[index].path = '';
            panel.slides[index].drawed=false;
            for(var i=0;i<=index;i++)
                panel.slides[index].path += '/'+panel.params[i];
            $.getJSON('/api/page' + panel.slides[index].path + '.json', function(data){
                //console.log('loaded page '+slug);
                panel.slides[index].slug = slug;
                panel.slides[index].rendered_content = data.rendered_content;
                panel.slides[index].language = data.language;
                panel.slides[index].languagemenu = data.languagemenu;
                panel.slides[index].loaded=true;
                panel.slides[index].isGarbage=false;
                panel.slides[index].has_children = (data.has_children)?true:false;
                checkLoadingComplete();
            });
        }
    });
    checkLoadingComplete();
}

function checkLoadingComplete() {
    //console.log("checkLoadingComplete");
    var allLoaded=true;
    $(panel.params).each(function(index,element){
        if(typeof(panel.slides[index].loaded)!="boolean" || !panel.slides[index].loaded)
            allLoaded = false;
    });
    if(!allLoaded)
        return false;
    if(typeof(panel.animationComplete)!="boolean" || !panel.animationComplete)
        return false;
    refreshNavigationAndLinks();
    if(panel.canOpen && !panel.isOpen)
        openSliders();
    if(!panel.isOpen)
        return false;
    if(typeof(panel.callbackFunction)=="function"){
        panel.callbackFunction(panel.nextSlide);
        panel.callbackFunction=function(){};
    }
}

function drawSlides() {
    //console.log("drawSlides");
    // remove all garbage slides from dom
    for(var i=0;i<panel.slides.length;i++) {
        if(panel.slides[i].isGarbage) {
            $('#slide'+i).remove();
            panel.slides[i].drawed=false;
        }
    }
    // draw all slides which are not already drawed and mark them as no garbage
    for(var i=0;i<panel.params.length;i++){
        if(!panel.slides[i].drawed) {
            $('#slide'+i).remove();
            drawSlide(i);
            panel.slides[i].isGarbage=false;           
        }
    }
    // mark all slides which are > than current level as garbage
    for(var i=panel.params.length;i<panel.slides.length;i++){
        if(typeof(panel.slides[i])=="object")
            panel.slides[i].isGarbage=true;
    }
    resizeContent();
}

function drawSlide(slideID) {
    //console.log('draw slide '+slideID);
    $('#sliders').prepend(SLIDE_TPL, {
       id: 'slide'+slideID,
       path: panel.slides[slideID].path,
       number: (panel.slides[slideID].has_children || slideID>0)?slideID+1:'',
       content: panel.slides[slideID].rendered_content
    });
    createEventHovers(slideID);
    createEventSubmitListener(slideID);
    panel.slides[slideID].drawed = true;
    //console.log(slideID+'drawed='+panel.slides[slideID].drawed);
    
}

function fadeOutSlide(){
    //console.log('fadeOutSlide');
    slides=$('.slide');
    if(slides.length > 0) {
        panel.animationComplete = false;
        slides.customFadeOut(SLIDE_FADE, function(){
            if(!panel.animationComplete) {
                // only run once if multiple slides got hidden
                panel.animationComplete=true;
                $(panel.slides).each(function(index, entry){
                    panel.slides[index].drawed = false;
                });
                checkLoadingComplete();            
            }
        });
    } else {
        checkLoadingComplete();
    }
}

function nextSlideIsActive() {
    // console.log('nextSlideIsActive');
    panel.activeSlide = panel.nextSlide;
}

function fadeInSlide(slideID){
    //console.log('fadeInSlide'+slideID);
    drawSlides();
    var slide0 = $('#slide0');
    if(!panel.isOpen) {
        slide0.show();
        slide0.find('.slidebox').jScrollPane(SCROLLBAR_SETTINGS);
        openSliders(function(){
            for(var i=1;i<panel.params.length;i++) {
                var slideN = $('#slide'+i);
                slideN.show();
                slideN.find('.slidebox').jScrollPane(SCROLLBAR_SETTINGS);
            }
            slideToSlide(slideID);
        });
    } else {
        slide0.customFadeIn(SLIDE_FADE,function(){
            slide0.find('.slidebox').jScrollPane(SCROLLBAR_SETTINGS);
            for(var i=1;i<panel.params.length;i++) {
                var slideN = $('#slide'+i);
                slideN.show(0,function(){
                    slideN.find('.slidebox').jScrollPane(SCROLLBAR_SETTINGS);
                    resizeContent();
                    //console.log(slideN.height);
                });
            }
            slideToSlide(slideID);
        });
    }
}

function slideToSlide(slideID) {
    //console.log('slideToSlide'+slideID);
    drawSlides();
    for(var i=0;i<panel.slides.length;i++){
        var slideN = $('#slide'+i);
        if(!slideN.is(':visible'))
            slideN.show(0);
        if(i<panel.nextSlide && isSlideOpen(i))
            closeSlide(i);
        if(i>=panel.nextSlide && !isSlideOpen(i))
            openSlide(i);
        if(i>=panel.nextSlide && isSlideOpen(i))
            slideN.find('.slidebox').jScrollPane(SCROLLBAR_SETTINGS);
        if(i>panel.nextSlide)
            slideN.find('.jScrollPaneTrack').customFadeOut(SLIDER_TIME_LEFT);
        resizeContent();
        nextSlideIsActive();
    }    
}

function refreshNavigationAndLinks() {
    //console.log("refreshNavigationAndLinks "+panel.slides[panel.activeSlide].language);
    if(typeof(panel.slides[panel.nextSlide])=="undefined" || typeof(panel.slides[panel.nextSlide].language) =="undefined")
        return;
    // refresh menu, if language has changed
    if (panel.language != panel.slides[panel.nextSlide].language) {
        $.getJSON('/api/navigation/' + panel.slides[panel.nextSlide].language + '.json', function(data){
            // refresh menu bar
            var menu = $('#menu');
            menu.customFadeOut(MENU_FADE, function(){
                $('#menu').empty();
                var menuhtml='';
                $.each(data.navigation, function(index, value){
                    menuhtml+='<li><a slug="'+value.slug+'" href="#!'+value.url+'" title="'+value.title+'">'+value.title+'</a></li>';
                });
                menu.append('<ul>'+menuhtml+'</ul>');
                menu.customFadeIn(MENU_FADE);
                refreshLinks();
            });
            // refresh footer_navigation
            var impressum = $('#impressum');
            var menuhtml='';
            $.each(data.footer_navigation, function(index, value){
                menuhtml+='<a href="#!'+value.url+'" title="'+value.title+'">'+value.title+'</a> | ';
            });
            impressum.empty();
            impressum.append(menuhtml.substr(0,menuhtml.length-2))
        });
        panel.language=panel.slides[panel.nextSlide].language;
    }
    
    // refresh lang mneu
    var right=$('#right');
    right.empty();
    langmenuhtml='';
    $.each(panel.slides[panel.nextSlide].languagemenu, function(index, p){        
        langmenuhtml+='<li><a href="#!'+p.link+'"';
        if(p.key==panel.language){
            langmenuhtml+=' class="active"';            
        }
        langmenuhtml+='>'+p.key+'</a></li>';
    });
    right.append('<ul>'+langmenuhtml+'</ul>');
    
    refreshLinks();
}

function refreshLinks() {
    $('#menu a').removeClass('active');
    $('a[slug=' + panel.slides[0].slug + ']').addClass('active');
}

/*
   createEventHovers.
*/
function createEventHovers(slideID) {
   // standard
   $('#slide'+slideID+' ul.events li').hover(function() {
       $(this).addClass('hover');
   }, function() {
    $(this).removeClass('hover');
   });
}

/*
    resizeContent()
    recalculates and sets the size of the slider and jscrollpane container
    and reinstantiate the jscrollpane on the scollpane div.
    this function should be called on resizing, scrolling, changing slide
    content and once at start.
*/
function resizeContent() {
    //console.log('resizeContent');
    var winheight = $(window).height();
    var bottombarheight = $('#bottombar').height();
    var newheight = winheight - bottombarheight;
    $('#sliders').css({
        height: newheight + 'px'
    });
    $('.slide').css({
        height: newheight + 'px'
    });
    $('.slidebox').css({
        height: newheight-80 + 'px'
    });
    $('.jScrollPaneContainer').css({
        height: newheight + 'px'
    });
    if(background.animationComplete)
        $('#background').fullBg(BG_WIDTH, BG_HEIGHT);
    if(panel.nextSlide==panel.activeSlide)
        $('#slide'+panel.activeSlide+':visible').find('.slidebox').jScrollPane(SCROLLBAR_SETTINGS);
}



/*
    toggleLeft(f)
    shows and hides the given object with a sliding effect from left into
    the content and sets position to fixed for scrolling issues. it's also
    possible to give a callback function, which will be called after the
    slide is done.
*/
$.fn.toggleLeft = function(f){
    var position = parseInt($(this).css('left')) == 0 ? '-' + $(this).css('width') : 0;
    $(this).animate({
        left: position
    }, SLIDER_TIME_LEFT, f);
    $(this).css({
        position: 'fixed'
    });
}

/*
    toggleBottom(f)
    shows and hides the given object with a sliding effect from bottom into
    the content and sets position to fixed for scrolling issues. it's also
    possible to give a callback function, which will be called after the
    slide is done.
*/
$.fn.toggleBottom = function(f){
    var position = parseInt($(this).css('bottom')) == 0 ? '-' + $(this).css('height') : 0;
    $(this).animate({
        bottom: position
    }, SLIDER_TIME_BOTTOM, f);
    $(this).css({
        position: 'fixed'
    });
}

function openSlide(slideID, f) {
    //console.log('openSlide'+slideID);
    var slide = $('#slide'+slideID);
    var slideNumber = slide.find('.slide-number');

    var position = 0;
    var opacity = 1;
    
    slide.css('width', '461px');
    slide.find('.jScrollPaneTrack').customFadeIn(SLIDER_TIME_LEFT);
    slide.animate({
        left: position+'px'
    }, SLIDER_TIME_LEFT, f);
    slideNumber.fadeTo(SLIDER_TIME_LEFT, opacity);
}

function closeSlide(slideID, f) {
    //console.log('closeSlide'+slideID);
    var slide = $('#slide'+slideID);
    var slideNumber = slide.find('.slide-number');
    var level = slideID + 1;

    var position = -506 + (27 * level);
    var opacity = 0.5;

    slide.find('.jScrollPaneTrack').customFadeOut(SLIDER_TIME_LEFT);
    slide.animate({
        left: position+'px'
    }, SLIDER_TIME_LEFT, function(){
        slide.css('width', '447px');
        if(typeof(f)=="function")
            f();
    });
    slideNumber.fadeTo(SLIDER_TIME_LEFT, opacity);
}

function isSlideOpen(slideID) {
   var slide = $('#slide'+slideID);
   var position = parseInt(slide.css('left'));
   return position < 0 ? false : true;
}

/*
    background resizing
*/
$.fn.fullBg = function(width, height) {
    var imgwidth = width;
    var imgheight = height;

    var winwidth = $(window).width() + WIN_WIDTH_CORR;
    var winheight = $(window).height() + WIN_HEIGHT_CORR;

    var widthratio = winwidth / imgwidth;
    var heightratio = winheight / imgheight;

    var widthdiff = heightratio * imgwidth;
    var heightdiff = widthratio * imgheight;

    if(heightdiff>winheight && FIX_BG_HEIGHT==false) {
        $(this).css({
            width: winwidth+'px',
            height: heightdiff+'px'
        });
    } else {
        var imgContentWidth = winwidth - 510;
        var imgContentHeight = winheight - 115;
        if (widthdiff < imgContentWidth) {
            var heightAntiOverflow = (imgContentWidth / imgwidth * imgheight);
            $(this).css({
                //opacity: 0.5,
                width: imgContentWidth+'px',
                height: heightAntiOverflow+'px',
                bottom: '-'+(Math.floor(imgContentHeight-heightAntiOverflow) / 2)+'px'
            });
        } else {
            $(this).css({
                //opacity: 1.0,
                width: widthdiff+'px',
                height: winheight+'px'
            });
        }
    }
}

function bgImageReposition() {
    var bottombar_height = $('#bottombar').height();
    
    FIX_BG_HEIGHT = true;
    WIN_HEIGHT_CORR = -1 * bottombar_height;
    
    var imgwidth = BG_WIDTH;
    var imgheight = BG_HEIGHT;

    var winwidth = $(window).width() + WIN_WIDTH_CORR;
    var winheight = $(window).height() + WIN_HEIGHT_CORR;

    var widthratio = winwidth / imgwidth;
    var heightratio = winheight / imgheight;

    var widthdiff = heightratio * imgwidth;
    var heightdiff = widthratio * imgheight;
    background.animationComplete=false;
    $('#background').animate({
        bottom: bottombar_height+'px',
        width: widthdiff+'px',
        height: winheight+'px'
    }, 2500, function(){
        background.animationComplete=true;
    });   
}

$.fn.customFadeIn = function(speed, callback) {
    $(this).fadeIn(speed, function() {
        if(jQuery.browser.msie) {
            $(this).get(0).style.removeAttribute('filter');
        }
        if(callback != undefined) {
            callback();
        }
    });
};

$.fn.customFadeOut = function(speed, callback) {
    $(this).fadeOut(speed, function() {
        if(jQuery.browser.msie) {
            $(this).get(0).style.removeAttribute('filter');
        }
        if(callback != undefined) {
            callback();
        }
    });
};

function createEventSubmitListener(slideID) {
    //console.log('EVENT submit listener added');
    var form = $('#signup_form');
    form.submit(function(){
        //$('#activity').customFadeIn(ACTIVITY_FADE);
        //console.log('EVENT id is ' + $(this).attr('eventID'));
        $.ajax({
            type: 'POST',
            url: '/api/event/' + form.attr('eventID') + '/participant.json',
            //contentType: 'application/json',
            //dataType: 'json',
            data:{
                'salutation': $('[name=salutation]:checked').val(),
                'firstname': $('#id_firstname').val(),
                'surname': $('#id_surname').val(),
                'location': $('#id_location').val(),
                'email': $('#id_email').val(),
                'company': $('#id_company').val()
            },
            complete: function(request, status) {
                //$('#activity').customFadeOut(ACTIVITY_FADE);
                if(parseInt(request.status) == 202){
                    // show success msg
                    $('#signup_form').customFadeOut(MENU_FADE,function(){
                        $('#fully_booked_msg').customFadeIn(MENU_FADE);
                    });
                }
                else if (parseInt(request.status) != 201) {
                    // show error msg
                    var data = $.parseJSON(request.responseText)
                    $.each(data,function(key,value){
                        field = $('[name='+key+']');
                        field.addClass('error');
                        field.val(value);
                        if(field.attr('type')=='radio') {
                            $('li.error').remove();
                            $('[name='+key+']').last().parent().parent().after('<li class="error">'+value[0]+'</li>');
                        }
                    });
                    //$('#error_msg').customFadeIn().delay(2000).customFadeOut('slow');
                } else {
                    // show success msg
                    $('#signup_form').customFadeOut(MENU_FADE,function(){
                        $('#success_msg').customFadeIn(MENU_FADE);
                    });
                }
            }
        });
        // don't really send the form
        return false;
    });

    var feedbackform = $('#feedback_form');
    feedbackform.submit(function(){
        //$('#activity').customFadeIn(ACTIVITY_FADE);
        //console.log('EVENT id is ' + $(this).attr('eventID'));
        $.ajax({
            type: 'POST',
            url: '/api/event/' + feedbackform.attr('eventID') + '/feedback.json',
            //contentType: 'application/json',
            //dataType: 'json',
            data:{
                'question_recommend': $('[name=question_recommend]:checked').val(),
                'question_detail': $('[name=question_detail]:checked').val(),
                'question_hear': $('[name=question_hear]:checked').val(),
                'question_useful': $('[name=question_useful]:checked').val(),
                'question_publication': $('[name=question_publication]:checked').val(),
                'question_remarks': $('[name=question_remarks]').val()
            },
            complete: function(request, status) {
                //$('#activity').customFadeOut(ACTIVITY_FADE);
                if(parseInt(request.status) == 202){
                    // show success msg
                    $('#feedback_form').customFadeOut(MENU_FADE,function(){
                        $('#fully_booked_msg').customFadeIn(MENU_FADE);
                    });
                }
                else if (parseInt(request.status) != 201) {
                    // show error msg
                    var data = $.parseJSON(request.responseText);
                    $('li.error').remove();
                    $.each(data,function(key,value){
                        field = $('[name='+key+']');
                        field.addClass('error');
                        field.val(value);
                        if(field.attr('type')=='radio') {
                            $('[name='+key+']').last().parent().after('<li class="error">'+value[0]+'</li>');
                        }
                    });
                    resizeContent();
                    //$('#error_msg').customFadeIn().delay(2000).customFadeOut('slow');
                } else {
                    // show success msg
                    window.location.href='#/'+panel.params[0]+'_success/';
                }
            }
        });
        // don't really send the form
        return false;
    });
    
    // remove error class on click
    $('#signup_form').find('input').not('[type=submit]').focus(function(){
        $(this).removeClass('error');
        if($(this).attr('type')=='radio') {
            $('li.error').remove();
        } else {
            $(this).val('');
        }
    });
}

function openSliders(f) {
    $('#headline').customFadeOut(500);
    $('#sliders').toggleLeft(function(){
        bgImageReposition();
        if(typeof(f)=="function")
            f();
    });
    panel.isOpen=true;
}

$(document).ready(function(){
    // initialise address plugin
    $.address.init(function(event) {
    
        $(AUTO_LINKS).address();
    
    }).change(function(event) {
    
        loadPage(event);

    }).history(true).crawlable(true);

    /*
        add resizeContent function to resize and scroll listener. and call
        resizeContent once.
    */
    $(window).resize(function() {
        resizeContent();
    });
    $(window).scroll(function(){ 
        resizeContent();
    });
    resizeContent();
    
    // start the animation
    $('img#background').fullBg(BG_WIDTH, BG_HEIGHT);
    $('#background').customFadeIn(BACKGROUND_FADE, function(){
        $('#headline').customFadeIn(HEADLINE_FADE, function(){
            $('#bottombar').toggleBottom(function(){
                panel.canOpen=true;
                if(typeof(panel.slides[0].loaded)=="boolean" && panel.slides[0].loaded)
                    checkLoadingComplete();
            });
        });
    });
    
});
