var ie = false;
var ie6 = false;
var ie7 = false;

var newheight = 0;
var newwidth = 0;

var homeslider;
var animating = false;
var currentSlide = 1;
var total = 0;

$(document).ready(function(){
    detectIe();
    setContentHeight();
    waitAfterLoadingForImagePositioning();
    setBackgroundImagePositions();
    setContentBg();
    setNavigationHeight();
    setNavigationAnimation();
    setItemBoxSlider();
    setItemListSlider();
    setSplitTitles();
    setHomeSliding();
    setWrapperPosition();
    setPhotoViewer();
    setVideoViewer();
    setAccordions();
    setDatepicker();
    setSubmits();
    setOverlay();
    setDmMap();
    var t = setTimeout(function(){
        $(window).trigger('resize')
    }, 500);
});

$(window).resize(function(){
    setContentHeight();
    setBackgroundImagePositions();
    setContentBg();
    setNavigationHeight();
    setHomeGradientHeights()
    setWrapperPosition();
    setOverlay();
});

function setHomeSliding(){

    setHomeGradientHeights();
    $('.home #content>div:not(:first-child)').css('left', '-9999px');
    $('.home #content>div').each(function(){
        var slide = $(this);
        total++;
        slide.attr('slide', total);
    });
    
    $('.home #content img.next').click(function(){
        if (!animating) {
            animating = true;
            clearInterval(homeslider);
            setHomeSlidingInterval();
            $('.home #content>div[slide="' + currentSlide + '"]').animate({
                left: (0 - newwidth)
            }, 'slow', function(){
                animating = false;
                $(this).css('left', '-9999px');
            });
            currentSlide++;
            if (currentSlide > total) {
                currentSlide = 1;
            }
            var nextDiv = $('.home #content>div[slide="' + currentSlide + '"]');
            setRandomImage(nextDiv);
            nextDiv.css({
                left: newwidth
            }).animate({
                left: 0
            }, 'slow');
            setBackgroundImagePositions();
        }
    });
    
    $('.home #content img.prev').click(function(){
        if (!animating) {
            animating = true;
            clearInterval(homeslider);
            setHomeSlidingInterval();
            $('.home #content>div[slide="' + currentSlide + '"]').animate({
                left: newwidth
            }, 'slow', function(){
                animating = false;
                $(this).css('left', '-9999px');
            });
            currentSlide--;
            if (currentSlide < 1) {
                currentSlide = total;
            }
            var nextDiv = $('.home #content>div[slide="' + currentSlide + '"]');
            setRandomImage(nextDiv);
            nextDiv.css({
                left: (0 - newwidth)
            }).animate({
                left: 0
            }, 'slow');
            setBackgroundImagePositions();
        }
    });
    
    setHomeSlidingInterval();
    
}

function setHomeSlidingInterval(){

    homeslider = setInterval(function(){
        if (!animating) {
            animating = true;
            $('.home #content>div[slide="' + currentSlide + '"]').animate({
                left: (0 - newwidth)
            }, 'slow', function(){
                animating = false;
                $(this).css('left', '-9999px');
            });
            currentSlide++;
            if (currentSlide > total) {
                currentSlide = 1;
            }
            var nextDiv = $('.home #content>div[slide="' + currentSlide + '"]');
            setRandomImage(nextDiv);
            nextDiv.css({
                left: newwidth
            }).animate({
                left: 0
            }, 'slow');
            setBackgroundImagePositions();
        }
    }, 7000);
    
}

function setHomeGradientHeights(){

    $('#content>div div.left.png_bg').height(newheight);
    $('#content>div div.right.png_bg').height(newheight);
    
}

function setSplitTitles(){

    $('.home #content>div h3').each(function(){
        var title = $(this);
        var content = title.html();
        var array = content.split("|");
        var newcontent = "";
        jQuery.each(array, function(indexInArray, valueOfElement){
            var random = $.randomBetween(0, 60);
            random = Math.round(random / 6) * 6;
            newcontent += '<span style="margin-left:' + random + 'px">' + valueOfElement + '</span>';
        });
        title.html(newcontent);
    });
    
    $('#item_list li a, #item_box h4 a, #text_box h3, #video_box h3, #photo_box h3, option').each(function(){
        $(this).html($(this).html().replace('|', ' ').replace('|', ' ').replace('|', ' ').replace('|', ' '));
    });
    
}

function detectIe(){

    if ($.browser.msie) {
        ie = true;
        $('html').addClass('ie');
        if ($.browser.version.substr(0, 1) == "6") {
            ie6 = true;
            $('html').addClass('ie6');
        }
        if ($.browser.version.substr(0, 1) == "7") {
            ie7 = true;
            $('html').addClass('ie7');
        }
    }
    else {
        $('html').addClass('no-ie');
    }
    
}

function setContentHeight(){

    newheight = $(window).height() - 185;
    var origheight = 415;
    var wrapheight = $('#wrapper').height() + 100;
    
    if (wrapheight > origheight) {
        origheight = wrapheight;
    }
    
    if (newheight < origheight) {
        newheight = origheight;
    }
    $('#content').height(newheight);
    $('#content>div').height(newheight);
    
    newwidth = $(window).width();
    if (newwidth < 960) {
        newwidth = 960;
    }
    $('#content').width(newwidth);
    $('#content>div').width(newwidth);
    
}

function setNavigationHeight(){

    var nav = $('body>header>nav');
    var bh = $('body').height();
    
    if (bh > $(window).height()) {
        nav.height(bh);
    }
    else {
        nav.height($(window).height());
    }
    
    if ($('html').hasClass('home') && !$.cookie('thasbeenhome')) {
        $.cookie('thasbeenhome', true);
        nav.css({
            left: 10
        });
        setTimeout(function(){
            hideNavigation(nav);
        }, 2000);
    }
    else {
        nav.css({
            left: (10 - nav.width())
        });
    }
    
}

function setNavigationAnimation(){

    var nav = $('body>header>nav');
    var navbtn = $('body>header>nav>img');
    navbtn.toggle(function(){
        showNavigation(nav);
    }, function(){
        hideNavigation();
    });
    nav.click(function(){
        hideNavigation();
    });
    $('#content').click(function(){
        hideNavigation();
    });
}

function hideNavigation(){

    var nav = $('body>header>nav');
    nav.animate({
        left: (10 - nav.width())
    });
    
}

function showNavigation(nav){

    nav.animate({
        left: 0
    });
    
}

function waitAfterLoadingForImagePositioning(){

    $('img.background').each(function(){
        $(this).load(function(){
            setBackgroundImagePosition($(this));
            
            if ($(this).parents('html').hasClass('home')) {
                $(this).siblings('img.background').remove();
                $(this).show();
            }
        });
    });
    
}

function setBackgroundImagePositions(){

    $('img.background').each(function(){
        setBackgroundImagePosition($(this));
    });
    
}

function setRandomImage(div){

    var imgs = div.find('img.background');
    var count = imgs.length;
    if (count > 1) {
        var random = $.randomBetween(1, count) - 1;
        jQuery.each(imgs, function(indexInArray, valueOfElement){
            if (indexInArray == random) {
                $(valueOfElement).show();
                setBackgroundImagePosition($(valueOfElement));
            }
            else {
                $(valueOfElement).hide();
            }
        });
    }
    else 
        if (count == 1) {
            setBackgroundImagePosition(imgs);
        }
    
}

function setBackgroundImagePosition(img){

    var imgheight = img.height();
    var offset = (newheight - imgheight) / 2;
    img.css({
        top: offset,
        left: 0,
        height: 'auto',
        width: newwidth
    });
    
    var imgheight = img.height();
    var imgwidth = img.width();
    
    if (imgheight < newheight) {
        img.css({
            top: 0,
            height: newheight,
            width: 'auto'
        });
        var offset = (newwidth - imgwidth) / 2;
        img.css({
            left: offset
        });
    }
    
}

function setContentBg(){
    var img = $('html:not(.home) body #content div img.background');
	setBackgroundImagePosition(img);
}

function setItemListSlider(){

    var n = 4;
    var nItems = $('ul#item_list li').size();
    var sHeight = $('ul#item_list li').height() + 2;
    var tHeight = sHeight * nItems;
    var mT = 0;
    var rest = nItems % n;
    
    
    
    $('#content div #wrapper ul#item_list li.active').each(function(){
    
        var t = $(this).position().top;
        var v = $('ul#item_list').height() - t;
        
        if (v <= 0) {
            mT = v - sHeight;
            $('ul#item_list li').animate({
                'top': mT + 'px'
            });
        }
    });
    
    $('#content div #wrapper ul#item_list li p a').each(function(){
        var l = $(this).attr('href');
        $(this).parent('p').parent('li').click(function(){
            location.href = l;
        });
        
        if ($(this).html().length > 40) {
            $(this).css('font-size', '11px');
        }
        
    });
    
    $('a#item_list_down').removeAttr('href').css('cursor', 'pointer').click(function(){
        mT -= (sHeight * n);
        if (mT <= ((tHeight * -1) + (sHeight * rest) + ((n - rest) * sHeight))) {
        
            mT = ((tHeight * -1) + (sHeight * rest) + ((n - rest) * sHeight));
        }
        $('ul#item_list li').animate({
            'top': mT + 'px'
        });
    });
    $('a#item_list_up').removeAttr('href').css('cursor', 'pointer').click(function(){
        mT += (sHeight * n);
        if (mT >= 0) {
            mT = 0;
        }
        $('ul#item_list li').animate({
            'top': mT + 'px'
        });
    });
}

function setItemBoxSlider(){

    var nItems = $('ul#item_box li').size();
    var sWidth = $('ul#item_box li').width();
    var tWidth = sWidth * nItems;
    var mL = 0;
    
    $('a#item_box_right').removeAttr('href').css('cursor', 'pointer').click(function(){
        mL -= sWidth;
        if (mL <= (tWidth * -1)) {
            mL = 0;
        }
        $('ul#item_box li').animate({
            'left': mL + 'px'
        });
    });
    $('a#item_box_left').removeAttr('href').css('cursor', 'pointer').click(function(){
        mL += sWidth;
        if (mL > 0) {
            mL = ((tWidth * -1) + sWidth);
        }
        $('ul#item_box li').animate({
            'left': mL + 'px'
        });
    });
    
}

function setWrapperPosition(){

    if ($(window).width() < 1080) {
        $('#wrapper').css('margin-left', '60px');
    }
    else {
        $('#wrapper').css('margin-left', '120px');
    }
}

function setPhotoViewer(){

    var iWidth = 579;
    var tWidth = 74;
    var nThumbs = 8;
    var nImages = $('#photo_viewer_main ul li').size();
    var tML = 0;
    var iML = 0;
    var iTotalWidth = iWidth * nImages;
    var tTotalWidth = tWidth * nImages;
    var rest = nImages % nThumbs;
    var index = 0;
    
    $('#photo_viewer_thumbs ul li:eq(' + index + ')').addClass('active');
    
    $('a#photo_viewer_right').removeAttr('href').css('cursor', 'pointer').click(function(){
        iML -= iWidth;
        if (iML <= ((iTotalWidth - 1) * -1)) {
            iML = 0;
        }
        $('#photo_viewer_main ul li').animate({
            'left': iML + 'px'
        });
        
        index++;
        if (index >= nImages) {
            index = 0;
        }
        
        console.log(index);
        
        if (index % nThumbs == 0) {
            tML = (index / nThumbs) * (tWidth * nThumbs) * -1;
            $('#photo_viewer_thumbs ul li').animate({
                'left': tML + 'px'
            });
        }
        
        $('#photo_viewer_thumbs ul li').removeClass('active');
        $('#photo_viewer_thumbs ul li:eq(' + index + ')').addClass('active');
        
    });
    $('a#photo_viewer_left').removeAttr('href').css('cursor', 'pointer').click(function(){
        iML += iWidth;
        if (iML > 0) {
            iML = ((iTotalWidth * -1) + iWidth);
        }
        $('#photo_viewer_main ul li').animate({
            'left': iML + 'px'
        });
        
        index--;
        if (index < 0) {
            index = nImages - 1;
            
            tML = ((tTotalWidth) * -1) + (tWidth * nThumbs);
            $('#photo_viewer_thumbs ul li').animate({
                'left': tML + 'px'
            });
        }
        else {
            if (index % nThumbs == 7) {
                tML = (Math.ceil((index / nThumbs)) - 1) * (tWidth * nThumbs) * -1;
                $('#photo_viewer_thumbs ul li').animate({
                    'left': tML + 'px'
                });
            }
        }
        
        $('#photo_viewer_thumbs ul li').removeClass('active');
        $('#photo_viewer_thumbs ul li:eq(' + index + ')').addClass('active');
        
    });
    
    $('#photo_viewer_thumbs ul li').each(function(){
        $(this).click(function(){
        
            $('#photo_viewer_thumbs ul li').removeClass('active');
            $(this).addClass('active');
            
            iML = iWidth * $(this).index() * -1;
            index = $(this).index();
            
            $('#photo_viewer_main ul li').animate({
                'left': iML + 'px'
            });
            
        });
    });
    
    $('a#photo_viewer_thumbs_right').removeAttr('href').css('cursor', 'pointer').click(function(){
    
        tML -= (tWidth * nThumbs);
        
        if (tML <= ((tTotalWidth * -1) + (tWidth * rest) + ((nThumbs - rest) * tWidth))) {
        
            tML = ((tTotalWidth * -1) + (tWidth * rest) + ((nThumbs - rest) * tWidth));
        }
        
        $('#photo_viewer_thumbs ul li').animate({
            'left': tML + 'px'
        });
    });
    $('a#photo_viewer_thumbs_left').removeAttr('href').css('cursor', 'pointer').click(function(){
        tML += (tWidth * nThumbs);
        if (tML >= 0) {
            tML = 0;
        }
        
        $('#photo_viewer_thumbs ul li').animate({
            'left': tML + 'px'
        });
    });
}

function setVideoViewer(){

    var vWidth = 575;
    var tWidth = 118;
    var nThumbs = 5;
    var nVideos = $('#video_viewer_main ul li').size();
    var tML = 0;
    var vML = 0;
    var vTotalWidth = vWidth * nVideos;
    var tTotalWidth = tWidth * nVideos;
    var rest = nVideos % nThumbs;
    var index = 0;
    
    $('#video_viewer_thumbs ul li:eq(' + index + ')').addClass('active');
    
    $('a#video_viewer_right').removeAttr('href').css('cursor', 'pointer').click(function(){
        vML -= vWidth;
        if (vML <= ((vTotalWidth - 1) * -1)) {
            vML = 0;
        }
        $('#video_viewer_main ul li').animate({
            'left': vML + 'px'
        });
        
        index++;
        if (index >= nVideos) {
            index = 0;
        }
        
        $('#video_viewer_thumbs ul li').removeClass('active');
        $('#video_viewer_thumbs ul li:eq(' + index + ')').addClass('active');
        
        
    });
    
    $('a#video_viewer_left').removeAttr('href').css('cursor', 'pointer').click(function(){
        vML += vWidth;
        if (vML > 0) {
            vML = ((vTotalWidth * -1) + vWidth);
        }
        $('#video_viewer_main ul li').animate({
            'left': vML + 'px'
        });
        
        index--;
        if (index < 0) {
            index = nVideos - 1;
        }
        
        $('#video_viewer_thumbs ul li').removeClass('active');
        $('#video_viewer_thumbs ul li:eq(' + index + ')').addClass('active');
        
    });
    
    $('#video_viewer_thumbs ul li').each(function(){
        $(this).click(function(){
        
            $('#video_viewer_thumbs ul li').removeClass('active');
            $(this).addClass('active');
            
            vML = vWidth * $(this).index() * -1;
            index = $(this).index();
            
            $('#video_viewer_main ul li').animate({
                'left': vML + 'px'
            });
            
        });
    });
    
    $('a#video_viewer_thumbs_right').removeAttr('href').css('cursor', 'pointer').click(function(){
    
        tML -= (tWidth * nThumbs);
        
        if (tML <= ((tTotalWidth * -1) + (tWidth * rest) + ((nThumbs - rest) * tWidth))) {
        
            tML = ((tTotalWidth * -1) + (tWidth * rest) + ((nThumbs - rest) * tWidth));
        }
        
        $('#video_viewer_thumbs ul li').animate({
            'left': tML + 'px'
        });
    });
    $('a#video_viewer_thumbs_left').removeAttr('href').css('cursor', 'pointer').click(function(){
        tML += (tWidth * nThumbs);
        if (tML >= 0) {
            tML = 0;
        }
        
        $('#video_viewer_thumbs ul li').animate({
            'left': tML + 'px'
        });
    });
}


function setAccordions(){

    setContentHeight();
    setBackgroundImagePositions();
    setNavigationHeight();
    setWrapperPosition();
    
    $('#routebeschrijving div, #nieuws div').each(function(){
        $(this).hide();
    });
    
    $('#routebeschrijving h4, #nieuws h4').each(function(){
    
        var o = false;
        
        $(this).click(function(){
        
            if (o == false) {
                o = true;
                $('a.closeacc').html('');
                $(this).children('a.closeacc').html('X');
            }
            else 
                if (o == true) {
                    o = false;
                    $(this).children('a.closeacc').html('');
                }
            
            $(this).next('div').slideToggle(function(){
                $(window).trigger('resize');
            });
            $(this).siblings('#routebeschrijving h4, #nieuws h4').next('div').slideUp(function(){
                $(window).trigger('resize');
            });
        })
    });
}

//var daysToEnable = ['5-21-2011'];

function setDatepicker(){

    $('select[name="program"]').change(function(){
        var value = $(this).val();
        var option = $(this).find('option[value="' + value + '"]');
        var url = option.attr('class');
        if (url != "") {
            window.location = url;
        }
    });
    
    var selectedDates = [];
    
    $('input#datum').datepicker({
        dateFormat: 'dd-mm-yy',
        onSelect: function(dateText, inst){
            selectedDates.push(dateText);
        },
        onClose: function(dateText, inst){
            $('input#datum').attr('value', selectedDates.toString());
        },
        beforeShowDay: enableSpecificDates,
        minDate: new Date(daysToEnable[0])
    });
    
    $('a#popDate').removeAttr('href').css('cursor', 'pointer').click(function(){
        selectedDates.pop();
        $('input#datum').attr('value', selectedDates.toString());
    });
    
}

function enableSpecificDates(date){
    var month = date.getMonth();
    var day = date.getDate();
    var year = date.getFullYear();
    for (i = 0; i < daysToEnable.length; i++) {
        if ($.inArray((month + 1) + '-' + day + '-' + year, daysToEnable) != -1) {
            return [true];
        }
    }
    return [false];
}


function setSubmits(){
    $('a.button').removeAttr('href').css('cursor', 'pointer').click(function(){
    
        var id = $(this).parent('form').attr('id');
        
        if (checkForm(id) == true) {
            $(this).parent('form').submit();
            
        }
    });
}

function checkForm(id){

    var v = true;

	var busInputType;
	
    $('#' + id + ' p label input.obl, #' + id + ' p label select').each(function(){
	// remove the condition for input type="bus"
	
		if ( $(this).attr("name") == "bus")  
		{
			busInputType = $(this);
			busInputType.css("border","#444 1px inset !important");
		}	
	
        if ( ($(this).val() == "") && ($(this).attr("name") != "bus") ) {
            $(this).addClass('emptyfield');
            v = false;
        }
        else {
            $(this).removeClass('emptyfield');
			$(this).css("border","#444 1px inset !important");
        }
    });
    
    if (v == false) {
        return false;
    }
    else {
        return true;
    }
}

function setOverlay(){
    $('div#overlay').width($(window).width()).height($(window).height());
    $('body').css('overflow', 'hidden');
    
    $('div#overlay a').click(function(){
        $('div#overlay').fadeOut('fast');
    });
}

function setDmMap(){

    if ($('#dmmap').length) {
        var demensen = new google.maps.LatLng(50.869285, 4.463539);
        
        var mapOptions = {
            zoom: 15,
            center: demensen,
            disableDefaultUI: true,
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            navigationControl: true
        };
        map = new google.maps.Map(document.getElementById("dmmap"), mapOptions);
        
        var image = '../../images/template/marker.png';
        var marker = new google.maps.Marker({
            position: demensen,
            map: map,
            title: "deMensen",
            icon: image
        });
    }
}

/* extensions */
jQuery.extend({
    random: function(X){
        return Math.floor(X * (Math.random() % 1));
    },
    randomBetween: function(MinV, MaxV){
        return MinV + jQuery.random(MaxV - MinV + 1);
    }
});

