$(document).ready(function(){
    $(window)._scrollable();
    var reise_fe={
        pix:new Array(),
        cpic:0,
        timer:0,
        timerObj:null,
        
        init:function(){
            $('#select_menu ul li a').click(function(e){
                e.preventDefault();
                reise_fe.loadPic($(this));
                //window.location=$(this).attr('title');
            })
            var h=$('#select_menu ul li a:first').attr('href');
            var t=$('#select_menu ul li a:first').attr('title');
            $('#header_pic').css({backgroundImage:'url('+h+')'});
            $('#linkToOffer').attr('href',t);
            $('#select_menu li a').each(function(i,e){
                reise_fe.pix[i]=$(this);
            })
            if(reise_fe.pix.length){
               reise_fe.setStartVars();
               reise_fe.timerOn();
            }
        },

        loadPic:function(e){
            $('#header_pic_change').css('backgroundImage','none');
            $('#header_pic_change').show();
            var h=e.attr('href');
            var t=e.attr('title');
            $('#preloader').fadeIn();
            h.toString();
            var img=new Image();
            $(img).load(function(){
              $('#header_pic_change').css({backgroundImage:$('#header_pic').css('backgroundImage')})
              $('#header_pic').css({backgroundImage:'url('+h+')'});
              $('#header_pic_change').fadeOut('slow');
              $('#linkToOffer').attr('href',t);
              $('#preloader').hide();
            }).attr('src',h);
        },

        switchPic:function(){
            reise_fe.loadPic(reise_fe.pix[reise_fe.cpic]);
            reise_fe.cpic=reise_fe.cpic+1;
            if(reise_fe.pix.length<=reise_fe.cpic){
                reise_fe.cpic=0;
            }
            _self=this;
            //reise_fe.switchPicRand();
            reise_fe.timerObj=setTimeout("_self.switchPic()",8000);
        },

        switchPicRand:function(){
            reise_fe.loadPic(reise_fe.pix[Math.floor(Math.random()*(reise_fe.pix.length))]);
            _self=this;
            reise_fe.timerObj=setTimeout("_self.switchPicRand()",8000);
        },

        timerOn:function(){
            if(!reise_fe.timer){
                reise_fe.timer=1;
                //random; um die bilder nacheinander anzuzeigen dann reise_fe.switchPic() aufrufen
                reise_fe.switchPicRand();
            }
        },

        timerOff:function(){
            clearTimeout(reise_fe.timerObj);
            reise_fe.timer=0;
        },

        getLocation:function(){
            var gv=reise_fe.getUrlVars();
            //alert(gv['article_id']);
        },

        setStartVars:function(){
            //var gv=reise_fe.getUrlVars();
            var gv=reise_fe.getJourneyId();
            
            if(gv){
                var rp=/[0-9]{1,3}-/;
                var re=new RegExp(rp);
                $('#select_menu ul li a').each(function(i){
                    var id=re.exec($(this).attr('title')).toString().slice(0,-1);
                    if(id==gv){
                        var h=$(this).attr('href');
                        var t=$(this).attr('title');
                        
                        for(var i=0;i<reise_fe.pix.length;i++){
                            //alert(reise_fe.pix[i]);
                            if(re.exec(reise_fe.pix[i].attr('title')).toString().slice(0,-1)==gv){
                                reise_fe.cpic=i;
                            }
                        }
                        //$('#header_pic').css({backgroundImage:'url('+h+')'});
                        //$('#linkToOffer').attr('href',t);
                    }
                })
            }
        },

        getJourneyId:function(){
            var url=window.location.href;
            var rp=/\/[0-9]{1,3}-/;
            var re=new RegExp(rp);
            var r=re.exec(url)
            if(r){
                return r.toString().slice(1).slice(0,-1);
            }
            
        },

        getUrlVars:function(){
            var vars = [], hash;
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');

            for(var i = 0; i < hashes.length; i++){
                hash = hashes[i].split('=');
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
            return vars;
        }

    }

    reise_fe.init();

    var journey_end={
        srv:'',
        txt:['St&auml;dteinformationen werden gesammelt','Daten werden &uuml;bermittelt','Traumurlaub wird angefragt'],
        init:function(){
            $('#pers_data input[type=text],#pers_data input[type=checkbox],#pers_data input[type=radio]').focusin(function(){
                if($(this).parent().get(0).tagName=='DIV'){
                    $(this).parent().css('color','#535355');
                }else{
                    $(this).parent().prevUntil('.labdiv').css('color','#535355');
                }
            })
            var now=new Date();
            var range=now.getFullYear()+':'+(now.getFullYear()+10)
            var juiopt={
                dateFormat:'dd.mm.yy',
                dayNames:['Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Fritag','Samstag'],
                dayNamesMin:['So','Mo','Di','Mi','Do','Fr','Sa'],
                monthNames:['Januar','Februar','M&auml;rz','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'],
                monthNamesShort:['Jan','Feb','M&auml;r','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'],
                nextText:'N&auml;chster Monat',
                prevText:'Vorheriger Monat',
                yearRange:range.toString(),
                minDate:+7
                }
            var juiopt_out=juiopt;
            juiopt_out=$.extend({onClose:function(dateText,inst){
                    var d=dateText.split('.');
                    d[0]=new Number(d[0]);
                    $('#j_in').datepicker('option','minDate',new Date(d[2],d[1]-1,d[0]+7));
            }},juiopt_out)
            
            $('#j_out').datepicker(juiopt_out);
            $('#j_in').datepicker(juiopt);

            $('#selected_journeys a').click(function(e){
                e.preventDefault();
                var did=new Number($(this).attr('href').slice(1));
                if(isNaN(did)){
                    did=2;
                }
                if($('#journeys ul li').length){
                    $('#selected_journeys > div').each(function(i){
                        $(this).slideUp();
                        if((i+1)==did){
                            $(this).slideDown();
                        }
                    })
                }
                
            })
            $('#notavail').click(function(e){
                e.preventDefault();
                $('input[name=j_avail]').val('0');
                $('#pers_data').slideDown();
                $('#journeys').slideUp();
                $('#notavail_1,#notavail_2').show();
                $('#journeys ul').empty();
            })
            $('#pers_data').hide();
            $('#journey_preloader').hide();
            $('#journey_finish').hide();
            $('#pers_data form').submit(function(){
                journey_end.prepareData($(this).serialize());
                return false;
            })
            if(typeof($.fn.reise1001.globme)=='object'){
                journey_end.srv=$.fn.reise1001.globme.srv;
            }
        },

        prepareData:function(d){
            var fdata=$('#pers_data form').serialize();
            var pid=journey_end.getPlacesId();
            journey_end.ajx(fdata+'&action=validate'+'&pid='+pid,'validate');
            
            //journey_end.showText(0);
            
            //journey_end.ajx();
            return false;
        },

        showText:function(i){
            if(i<journey_end.txt.length){
                $('#journey_preloader p').html(journey_end.txt[i]);
                journey_end.ajx('action=sleepabit&c='+i,'sleepabit');
            }else{
                $('#journey_preloader').slideUp();
                $('#journey_finish').slideDown();
            }
        },

        getPlacesId:function(){
            var pid='';
            $('#journeys ul li .journey input[name=mid]').each(function(i){
                pid+=$(this).val()+',';
            })
            pid=pid.slice(0,-1);
            return pid;
        },

        ajx:function(d,a){
            $.ajax({
                url:this.srv+'index.php',
                type: 'GET',
                dataType: 'json',
                data: d,
                success:function(data){
                    journey_end.afterAjx(data,a);
                }
            })
        },

        afterAjx:function(d,a){
            switch(a){
                case 'sleepabit':
                    if(d.result=='success'){
                        journey_end.showText(d.c);
                    }
                break;
                case 'validate':
                    if(d.result=='success'){
                        journey_end.showText(0);
                        $('#pers_data,.journey_step').slideUp();
                        $('#journey_preloader').slideDown();
                    }else{
                        journey_end.handleError(d);
                    }
                break;
            }
        },

        handleError:function(d){
            $.each(d.error,function(i,k){
                if($('#'+i).parent().get(0).tagName=='DIV'){
                    $('#'+i).parent().css('color','red');
                }else{
                    $('#'+i).parent().prev().css('color','red');
                }
            })
        },

        sleep:function(ms){
            var start = new Date().getTime();
            while (new Date().getTime() < start + ms);
            return true;
        }
    }
    

    journey_end.init();
    $('#select_menu ul').jcarousel({
        visible: 5,
        buttonPrevHTML:     '<div id="select_left"><a href="#">Zurueck</a></div>',
        buttonNextHTML:     '<div id="select_right"><a href="#">Vor</a></div>',
        itemFallbackDimension: 760

    });
    $('#newsletter_abmelden').hide();
    $('#newsletter_radio input').change(function(){
        switch($(this).val()){
            case '0':
                $('#newsletter_abmelden').slideDown();
                $('#newsletter_anmelden').slideUp();
            break;
            case '1':
                $('#newsletter_abmelden').slideUp();
                $('#newsletter_anmelden').slideDown();
            break;
        }
    })

    $('#select_left a,#select_right a').live('click',function(e){
        e.preventDefault();
    })

    $('#add_journey_to,.add_journey_to').click(function(e){
        if(!$('#selected_journeys ul li').length){
            var tmp='<div class="journey"><input type="hidden" name="mid" value="_mid_" /><h4>_title_</h4><button id="remove_journey"><span>Reise Entfernen</span></button></div>';
            var str=tmp.replace(/_title_/g,$('h1:first').text()).replace(/_mid_/g,window.location.href);
            $('#selected_journeys ul').append('<li>'+str+'</li>');
            $(window).scrollTo(200,{duration:1000,axis:'y'});
        }
    })
    $('#remove_journey').live('click',function(e){
        $(this).parent().parent().remove();
    })
    
    $('.galerie a').lightBox();
})
