var video_players = [];
var nav_label_timer = null;
var _navid;

var Global = {
    linkvoorwaardenURL: "wat-biedt-haga-nog-meer.aspx",
    currentBranch: '',
    currentTarget: '',
    currentScrollTarget: '',
    currentVacancy: '',
    _isIE7: false,
    _isIE8: false,

  init: function(){
        var _isIE = ($.browser.msie);
        Global._isIE7 = ($.browser.msie && parseFloat($.browser.version) <= 7.0);
        Global._isIE8 = ($.browser.msie && parseFloat($.browser.version) <= 8.0);
        Global._isIE9 = ($.browser.msie && parseFloat($.browser.version) <= 9.0);

        if(_isIE) {
            $('body').addClass('msie');
        }
        if(Global._isIE7) {
            $('body').addClass('msie7');
        }
        if(Global._isIE8) {
            $('body').addClass('msie8');
        }
        if(Global._isIE9) {
            $('body').addClass('msie9');
        }

    if($('#splash-scroll').length > 0) {
      $('#splash-scroll').SplashScroll();
        }

  },

    // init functionality after ajax content load
    afterAjaxInit: function() {
        if($('#nav').length > 0) {
            Global.positionNav($('#nav'));
            Global.initScrollto($('#nav li a'));
        }
        if($('.vacancies').length > 0) {
            Global.showVacancy();
        }


        if($(YoutubeVideo.videoWrap).length > 0) {
            YoutubeVideo.init();
        }

        if($('.navigate-to').length > 0) {
            Global.initScrollto($('.navigate-to'));

            $('#nav li:first').addClass('active');
            nav_label_timer = setTimeout(function(){
                $('#nav li:first').removeClass('active');
                $('#nav li:first').removeClass('active-balls');
                $('#nav li:first').addClass('active-balls');
                nav_label_timer = null;
            }, 4000);

            Global.activeNav();
            $(document).scroll(function (e) {
                Global.activeNav();
            });
        }

        if($('.video-carousel').length > 0) {
            carousel.init();
        }



    },

    showVacancy: function() {
        $('.vacancies a').bind('click', function(e){
            e.preventDefault();

            var _link = $(this).attr('href');
            var _url = Global.currentBranch + '/' + Global.currentTarget+ '/' + _link;
            Global.currentVacancy = _link;
            _gaq.push(['_trackPageview', _url]);

            $.ajax({
                url: _link,
                success: function(data){
                    $('#vacature-detail').html(data);
                    $('#vacature-detail').css('visibility', 'visible');

                    $(document).scrollTo('#vacature-detail', 500);

                    $('#nav').hide();

                    $('#vacature-detail').css({marginLeft:1000}).animate({
                        marginLeft: 0
                    }, 500, function() {
                        if(Global._isIE7 || Global._isIE8 || Global._isIE9) {
                            Global.fixPlaceholder();
                        }
                        $('#vacancies').css('visibility', 'hidden');
                        $('.close-button').unbind('click');
                        $('.close-button').bind('click', function(){

                            _gaq.push(['_trackEvent', 'Sluit-knop', 'sluit-vacature']);
                            var _urlVacatures = Global.currentBranch + '/' + Global.currentTarget;
                            _gaq.push(['_trackPageview', _urlVacatures]);

                            $('#vacancies').css('visibility', 'visible');
                            $('#vacature-detail').animate({
                                marginLeft: 1000
                            }, 500, function() {
                                $('#nav').show();
                                $('#vacature-detail').css('visibility', 'hidden');
                            });
                        });


                        $('.next-vacature').bind('click', function(e){
                            e.preventDefault();

                            var _urlVacatureDetail = Global.currentBranch + '/' + Global.currentTarget + '/' + Global.currentVacancy + '/' + Global.linkvoorwaardenURL ;
                            _gaq.push(['_trackPageview', _urlVacatureDetail]);

                            $.ajax({
                                url: Global.linkvoorwaardenURL,
                                success: function(data){

                                    $('#vacature-voorwaarden').html(data);

                                    $('#vacature-voorwaarden').css('visibility', 'visible');
                                    $('.next-vacature').hide();

                                    $('#vacature-voorwaarden').css({marginLeft:1000}).animate({
                                        marginLeft: 0
                                    }, 500, function() {
                                        $('#vacature-detail').css('visibility', 'hidden');
                                        $('.close-button').bind('click', function(){
                                            _gaq.push(['_trackEvent', 'Sluit-knop', 'sluit-vacature-voorwaarden']);
                                            var _urlVacatures = Global.currentBranch + '/' + Global.currentTarget;
                                            _gaq.push(['_trackPageview', _urlVacatures]);

                                            $('#vacancies').css('visibility', 'visible');
                                            $('#vacature-voorwaarden').animate({
                                                marginLeft: 1000
                                            }, 500, function() {
                                                $('#vacature-voorwaarden').css('visibility', 'hidden');
                                            });
                                            $('#vacature-detail').animate({
                                                marginLeft: 1000
                                            }, 500, function() {
                                                $('#vacature-detail').css('visibility', 'hidden');
                                            });
                                        });

                                        $('.prev-vacature').bind('click', function(){
                                            _gaq.push(['_trackEvent', 'Terug-naar-vacature-knop', 'sluit-voorwaarden']);
                                            var _urlVacatures = Global.currentBranch + '/' + Global.currentTarget + '/' + Global.currentVacancy;
                                            _gaq.push(['_trackPageview', _urlVacatures]);

                                            $('#vacature-detail').css('visibility', 'visible');
                                            $('#vacature-voorwaarden').animate({
                                                marginLeft: 1000
                                            }, 500, function() {
                                                $('#vacature-voorwaarden').css('visibility', 'hidden');
                                                $('.next-vacature').show();
                                            });
                                        });
                                    });
                                }
                            });
                        });


                    });
                }
            });
        });

    },

    fixPlaceholder: function() {

        $('input[type="text"]').each(function(){
            var placeholderTxt = $(this).attr('placeholder');
            $(this).attr('data-placeholder', placeholderTxt);
        });

        Global.inputPlaceholder();

    },



  initScrollto: function($el) {
    $el.each(function() {
      $(this).click(function(e){
        e.preventDefault();
        var target = $(this).attr('href');

                // some browsers (IE7) put the full url in front of a # in a link. Our scrollto does not like that as input so we'll rip it off
                indexofhash = target.indexOf("#");
                target = target.substring(indexofhash);

                var _link = target.substring(1);
                Global.currentTarget = _link;
                var _url = Global.currentBranch + '/' + _link;
                _gaq.push(['_trackPageview', _url]);


        var scrollelm = $(window)._scrollable();
        $(scrollelm).scrollTo(target, 1000, { easing:'easeInOutQuart' });
      });
    });
  }, 
  
  positionNav: function($el) {
    var $win = $(window);
    var winW = $win.width();
    var contentW = $('#content-wrap .inner-wrap').outerWidth();
    var spaceAround = (winW - contentW);
    
    // only reposition if we have spacing around...
    if (spaceAround > 0) {
      var spaceRight = spaceAround / 2 + 20;
      $el.css({right: spaceRight});
    }
    $el.hide();
    
  },
  
  activeNav: function($el) { 
    var $win = $(window);
    var winH = $win.height();
    
    var $scroll = ($.browser.mozilla || $.browser.msie) ? $('html') : $('body');
    var scrollTop = $scroll.get(0).scrollTop;
    
    var partsPercentages = [];
    var percentages = [];

    $('.page-part').each(function(i, pagePart){
      var $p = $(pagePart)
      ,  offsetTop = $p.offset().top
      ,  height = $p.outerHeight()
      ,  posTop = offsetTop - scrollTop
      ,  posBottom = posTop + height
      ,  visiblePixels = height
      ;
      
      if (posTop < 0) {
        visiblePixels -= -posTop;
      }
      
      if (posBottom > winH) {
        visiblePixels -= (posBottom - winH);
      }

      if (visiblePixels < 0) visiblePixels = 0;
      var perc = Math.round(visiblePixels / (winH/100));

            percentages.push(perc);
            partsPercentages.push({'id': $p.attr('id'), 'percentage': perc, 'object': $p});

    });

        var iMax = 0;
        for(var i=0; i<percentages.length; i++){
            if(iMax < percentages[i] ){
                iMax = percentages[i];
            }
        }

        var activeElmChosen = false;
        for(var i=0; i<partsPercentages.length; i++){
            if(partsPercentages[i].percentage == iMax && !activeElmChosen) {
                // let the script choose only one active item (on start are 3 items 0 and on scroll the percentage could be 50 50. Choose the first item in these cases)
                activeElmChosen = true;

                var $activePart = partsPercentages[i].object;
                var activeId = partsPercentages[i].id;

                $('#nav li').removeClass('active');
                $('#nav li').removeClass('active-balls');
                $('#nav li a[href="#'+activeId+'"]').parent('li').addClass('active');
                _navid = activeId;


                var beleefVideoId = $('#beleef-het-werk .video-placeholder').attr('id');

                if(activeId != 'beleef-het-werk' && video_players.length > 0){
                    for(var i=0; i<video_players.length; i++) {
                        if(video_players[i].id == beleefVideoId) {
                            var player = video_players[i].player;
                            if(player.getPlayerState() == 1){
                                player.pauseVideo();
                            }
                        }

                    }

                }
                if(activeId != 'werken-bij' && video_players.length > 0){
                    for(var i=0; i<video_players.length; i++) {
                        if(video_players[i].id != beleefVideoId) {
                            var player = video_players[i].player;
                            if(player.getPlayerState() == 1){
                                player.pauseVideo();
                            }
                        }

                    }

                }

                if(nav_label_timer == null){
                    var el = $('#nav li a[href="#'+activeId+'"]').parent('li');
                    nav_label_timer = setTimeout(function(){
                        $('#nav li a').parent('li').removeClass('active');
                        $('#nav li a').parent('li').removeClass('active-balls');
                        $('#nav li a[href="#'+activeId+'"]').parent('li').addClass('active-balls');
                        nav_label_timer = null;
                    }, 4000);
                }
            }
        }


    
  },
  inputPlaceholder: function() {
    $('input[data-placeholder]').each(function() {
      if($(this).val() == '') {
        var value = $(this).attr('data-placeholder');
        $(this).val(value);
        $(this).addClass('iPlaceholder');
      }

      $(this).focus(function(){
        var value = $(this).attr('data-placeholder');
        if($(this).val() == '' || $(this).val() == value) {
          $(this).val('');
          $(this).removeClass('iPlaceholder');
        }

      }).blur(function() {
        if($(this).val() == '') {
          var value = $(this).attr('data-placeholder');
          $(this).val(value);
          $(this).addClass('iPlaceholder');
        }
      });
    });
  }
  
}


var YoutubeVideo = {
  dataEmbedCode: 'videoembed',
  videoWrap: '.video-wrap',
  startBtn: '.video-start',
  videoPlaceholder: '.video-placeholder',
  videoLoader: '.loader',
  
  init: function() {
    $(YoutubeVideo.videoWrap).each(function() {
      $(YoutubeVideo.startBtn, this).click(function(e){
        e.preventDefault();
        YoutubeVideo.placeVideo($(this));
        
      });
    });
  
  },
  
  placeVideo: function(elm) {
    var parent = $(elm).parents(YoutubeVideo.videoWrap);
    var video_id = $(parent).data(YoutubeVideo.dataEmbedCode);
    
    var videoW = $(parent).outerWidth();
    var videoH = $(parent).outerHeight();

    var player = new YT.Player($(YoutubeVideo.videoPlaceholder, parent).attr('id'), {
      height: videoH,
      width: videoW,
      videoId: video_id,
      playerVars: {
        controls: 1,
          showinfo: 1 ,
          modestbranding: 1,
          wmode: "opaque"
      },  
      events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
      }
    });
    
    
    var _ph = $(YoutubeVideo.videoPlaceholder, parent);
      $(_ph).children('div').hide();


    var temp = {
            id: $(YoutubeVideo.videoPlaceholder, parent).attr('id'),
            player:player
        };
    video_players.push(temp);
    $(elm).fadeOut('fast');
    }

}

function onPlayerReady(evt) {
    evt.target.playVideo();
}

function onPlayerStateChange(evt) {
  //if (evt.data == YT.PlayerState.PLAYING && !done) {
  //}
}

/**
 * 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);

/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
 *
 * TERMS OF USE - jQuery Easing
 * 
 * Open source under the BSD License. 
 * 
 * Copyright © 2008 George McGinley Smith
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 * 
 * Redistributions of source code must retain the above copyright notice, this list of 
 * conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright notice, this list 
 * of conditions and the following disclaimer in the documentation and/or other materials 
 * provided with the distribution.
 * 
 * Neither the name of the author nor the names of contributors may be used to endorse 
 * or promote products derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY 
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 *  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 *  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 *  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
 * OF THE POSSIBILITY OF SUCH DAMAGE. 
 *
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
  def: 'easeOutQuad',
  swing: function (x, t, b, c, d) {
    return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
  },

  easeInQuad: function (x, t, b, c, d) {
    return c*(t/=d)*t + b;
  },
  easeOutQuad: function (x, t, b, c, d) {
    return -c *(t/=d)*(t-2) + b;
  },
  easeInOutQuad: function (x, t, b, c, d) {
    if ((t/=d/2) < 1) return c/2*t*t + b;
    return -c/2 * ((--t)*(t-2) - 1) + b;
  },
  easeInCubic: function (x, t, b, c, d) {
    return c*(t/=d)*t*t + b;
  },
  easeOutCubic: function (x, t, b, c, d) {
    return c*((t=t/d-1)*t*t + 1) + b;
  },
  easeInOutCubic: function (x, t, b, c, d) {
    if ((t/=d/2) < 1) return c/2*t*t*t + b;
    return c/2*((t-=2)*t*t + 2) + b;
  },
  easeInQuart: function (x, t, b, c, d) {
    return c*(t/=d)*t*t*t + b;
  },
  easeOutQuart: function (x, t, b, c, d) {
    return -c * ((t=t/d-1)*t*t*t - 1) + b;
  },
  easeInOutQuart: function (x, t, b, c, d) {
    if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
    return -c/2 * ((t-=2)*t*t*t - 2) + b;
  },
  easeInQuint: function (x, t, b, c, d) {
    return c*(t/=d)*t*t*t*t + b;
  },
  easeOutQuint: function (x, t, b, c, d) {
    return c*((t=t/d-1)*t*t*t*t + 1) + b;
  },
  easeInOutQuint: function (x, t, b, c, d) {
    if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
    return c/2*((t-=2)*t*t*t*t + 2) + b;
  },
  easeInSine: function (x, t, b, c, d) {
    return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
  },
  easeOutSine: function (x, t, b, c, d) {
    return c * Math.sin(t/d * (Math.PI/2)) + b;
  },
  easeInOutSine: function (x, t, b, c, d) {
    return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
  },
  easeInExpo: function (x, t, b, c, d) {
    return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
  },
  easeOutExpo: function (x, t, b, c, d) {
    return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
  },
  easeInOutExpo: function (x, t, b, c, d) {
    if (t==0) return b;
    if (t==d) return b+c;
    if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
    return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
  },
  easeInCirc: function (x, t, b, c, d) {
    return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
  },
  easeOutCirc: function (x, t, b, c, d) {
    return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
  },
  easeInOutCirc: function (x, t, b, c, d) {
    if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
    return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
  },
  easeInElastic: function (x, t, b, c, d) {
    var s=1.70158;var p=0;var a=c;
    if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
    if (a < Math.abs(c)) { a=c; var s=p/4; }
    else var s = p/(2*Math.PI) * Math.asin (c/a);
    return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
  },
  easeOutElastic: function (x, t, b, c, d) {
    var s=1.70158;var p=0;var a=c;
    if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
    if (a < Math.abs(c)) { a=c; var s=p/4; }
    else var s = p/(2*Math.PI) * Math.asin (c/a);
    return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
  },
  easeInOutElastic: function (x, t, b, c, d) {
    var s=1.70158;var p=0;var a=c;
    if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
    if (a < Math.abs(c)) { a=c; var s=p/4; }
    else var s = p/(2*Math.PI) * Math.asin (c/a);
    if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
    return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
  },
  easeInBack: function (x, t, b, c, d, s) {
    if (s == undefined) s = 1.70158;
    return c*(t/=d)*t*((s+1)*t - s) + b;
  },
  easeOutBack: function (x, t, b, c, d, s) {
    if (s == undefined) s = 1.70158;
    return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
  },
  easeInOutBack: function (x, t, b, c, d, s) {
    if (s == undefined) s = 1.70158; 
    if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
    return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
  },
  easeInBounce: function (x, t, b, c, d) {
    return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
  },
  easeOutBounce: function (x, t, b, c, d) {
    if ((t/=d) < (1/2.75)) {
      return c*(7.5625*t*t) + b;
    } else if (t < (2/2.75)) {
      return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
    } else if (t < (2.5/2.75)) {
      return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
    } else {
      return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
    }
  },
  easeInOutBounce: function (x, t, b, c, d) {
    if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
    return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
  }
});



$('#header-visual ul').cycle({
    fx:      'scrollHorz',
    speed:    700,
    timeout:  8000,
    pause:   0
});



$(Global.init);
