function carouselItemCallBack(carousel, item, index, state) {
  var carouselContainer = $(carousel.container);
/*
  if(index >= 2) {
    $('.eventDate:not(.today, .lastweek, .cancelled)', carouselContainer.parents().eq(2)).fadeOut('fast');
  } else {
    $('.eventDate:not(.today, .lastweek, .cancelled)', carouselContainer.parents().eq(2)).fadeIn('fast');
  }
*/
/*
  var positions = carouselContainer.parents().eq(1).children().eq(0);
  if (positions.attr('class') == 'twitterPosition') {
    var carouselClass = 'twitterCurrentPosition';
  }
*/ /*else {
     var carouselClass = 'eventCurrentPosition';
  }*/
/*
  positions = positions.children();
  $.each(positions, function (i, e) { $(e).attr({'class':''}); });
  positions.eq(index-1).attr({'class':carouselClass});
*/
}

function hoverCallback(carousel) {
  //Make the activated carousel globally accessible
  activeCarousel = carousel;
}

function toggleCarousel() {
  $('.jcarousel-skin-worm').hide();
	$(".jcarousel-skin-tweets").jcarousel({
    auto: 5,
    wrap: 'both',
    scroll: 1,
    buttonNextHTML: '',
    buttonPrevHTML: '',
    itemFirstInCallback: carouselItemCallBack
	});

  $('ul#itemList li:not(.livestream) div.event:not(.long)').live('mouseenter mouseleave', function(event){
    if (event.type == 'mouseover') {
      var carousel = $('.jcarousel-skin-worm', this);
      if (carousel.length != 0) {
        $('.eventImage', this).hide();
        $(carousel).show();
        $('li, li a, li a span', carousel).show();
      	$(carousel).jcarousel({
          auto: 1,
          wrap: 'both',
          scroll: 1,
          animation: 100,
          buttonNextHTML: '',
          buttonPrevHTML: '',
          initCallback: hoverCallback,
          itemFirstInCallback: carouselItemCallBack,
          itemFallbackDimension: 175
      	});
      } else {
        //$('.eventDate:not(.today, .lastweek, .cancelled)', this).fadeIn();
      }
    } else {
      if (typeof activeCarousel != 'undefined') {
        //$('.eventDate:not(.today, .lastweek, .cancelled)', this).hide();
        //Reinsert the list items into the dom
        var carousel = $('.jcarousel-skin-worm', this);
        if (carousel.length != 0) {
          var listItems = activeCarousel.list.children();
          var listItems = $.map(listItems, function(n, i) { return '<li>'+$(n).html()+'</li>'; });
          var tempCarousel = "<ul class=\"jcarousel-skin-worm\" style=\"display: none;\">\n"+listItems.join("\n")+"\n</ul>";
          carousel.remove();
          $('.eventImages', this).append(tempCarousel);
          $('.eventImage', this).show();
          activeCarousel.reset();
        }
      }
    }
  });
}

function bounceItems() {   
  $('.app.special div.event').each(function(i, e) {
    $(e).css({'position':'absolute'}).animate({'margin-top':"-5px"},{duration: 50, queue: "bounceQueue"}).animate({'margin-top':"+5px"},{duration: 50, queue: "bounceQueue"}).animate({'margin-top':"-5px"},{duration: 50, queue: "bounceQueue"}).animate({'margin-top':"+5px"},{duration: 50, queue: "bounceQueue"}).animate({'margin-top':"-5px"},{duration: 50, queue: "bounceQueue"}).animate({'margin-top':"0px"},{duration: 50, queue: "bounceQueue"});
  }); 
}

function shakeItems() {
  $('.app.wormschoice div.event').each(function(i, e) {
    $(e).css({'position':'absolute'}).animate({'margin-left':"-5px"},{duration: 50, queue: "shakeQueue"}).animate({'margin-left':"+5px"},{duration: 50, queue: "shakeQueue"}).animate({'margin-left':"-5px"},{duration: 50, queue: "shakeQueue"}).animate({'margin-left':"+5px"},{duration: 50, queue: "shakeQueue"}).animate({'margin-left':"-5px"},{duration: 50, queue: "shakeQueue"}).animate({'margin-left':"0px"},{duration: 50, queue: "shakeQueue"});
  });
}

function pulsateItems() {
/*
  $('.wormschoice img').each(function(i, e) {
    $(e).css({'position':'absolute'}).animate({'margin-left':"-5px"},{duration: 50, queue: "shakeQueue"}).animate({'margin-left':"+5px"},{duration: 50, queue: "shakeQueue"}).animate({'margin-left':"-5px"},{duration: 50, queue: "shakeQueue"}).animate({'margin-left':"+5px"},{duration: 50, queue: "shakeQueue"}).animate({'margin-left':"-5px"},{duration: 50, queue: "shakeQueue"}).animate({'margin-left':"0px"},{duration: 50, queue: "shakeQueue"});
  });
*/
  $('.app.livestream div.event').effect('pulsate', 'fast');
}

function loadEffects() {
  setInterval ( "bounceItems()", 3000);
  setInterval ( "shakeItems()", 5000);
  setInterval ( "pulsateItems()", 5000);
}

function loadApplications() {
  if ($('body').attr('id') === 'home') {
    var i=0;
    var worm = new Array('W', 'O', 'R', 'M', '');
    $('ul#menu li.app').each(function() {
      $(this).prepend('<div class="globalOverlay" style="background: #FF44A5;"><div class="globalOverlayContainer"><span class="overlayLetter">'+worm[i]+'</span></div></div>');
      i++;
      $(this).children().eq(0).delay(1000).animate({opacity: 0}, {easing: 'linear', duration: 1000, complete: function() {
        $(this).remove();
      }});
  
    }); 
    var quote = 'Welkom bij WORM';
    if (typeof CURRENT_QUOTE != 'undefined') {
      var quote = CURRENT_QUOTE;
    }
    var i=0;
    $('ul#itemList li.app').each(function() {
      if (quote[i]) {
        quoteCharacter = quote[i];
      } else {
        quoteCharacter = '';
      }
      $(this).prepend('<div class="globalOverlay"><div class="globalOverlayContainer"><span class="overlayLetter">'+quoteCharacter+'</span></div></div>');
      i++;
      $(this).children().eq(0).animate({opacity: 0}, {queue: "fadeQueue", easing: 'linear', duration: 80, complete: function() {
        $(this).remove();
      }});
    });
  }
}

function infiniteScroll() {
  var itemList = $('ul#itemList.search');
  var navigation = $("ul#menuBottom");
  if (!itemList.hasClass('sidebar') && navigation.length != 0) {
    itemList.infinitescroll({
      navSelector  : "ul#menuBottom",
      nextSelector : "a#nextList:last",
      itemSelector : "ul#itemList li.app",
      loadingImg : SITE_URL+'/images/spacer.gif',
      loadingText: '<li class="app loading"></li> <li class="app loading"></li> <li class="app loading"></li> <li class="app loading"></li> <li class="app loading"></li>',
      donetext: ''
    }, function() {
      retriggerAppEffects();
    });
    navigation.remove();
  }
}

function socialButtons() {
  $('#socialButtonShop, #socialButtonShare').click(function(event) {
    var requestType = $(this).attr('id');
    $('#socialList').animate({'left':'-175px'}, 'fast', function() {
      switch(requestType) {
        case 'socialButtonShop':
          var id = $("a#socialButtonShop").parent().attr('id');
          var id = id.substr(7);
          var requestUrl = '/social/shop/'+id;
        break;
        case 'socialButtonShare':
          var requestUrl = '/social/share';
        break;
      }
      var url = window.location.pathname;
      var url = SITE_URL+url.substr(url.indexOf('/')+1);
      var socialList = $(this);
      $.ajax({
        url : SITE_URL+requestUrl,
        type : "POST",
        data : {url:url},
        beforeSend : function() {
          $("#socialContainer").addClass('loading');
        },
        success : function(response) {
          $("#socialContainer").removeClass('loading');
          socialList.hide();
          $(response).insertAfter(socialList);
          $('#socialSharing').jScrollPane({showArrows: true, animateScroll: true});
        }      
      });        
    });
    event.preventDefault();
  });
  
  $('span.socialClose').live('click', function() {
    $('#socialList').show();
    $('#socialSharing').hide();
    $('#socialList').animate({'left':'0px'}, 'fast', function() {
      $('#socialSharing').remove();
    });    
  });
}

function filterApps() {
  $('ul#pictograms li a').click(function(event) {
    $(this).parent().toggleClass('selected');
    var pictograms = new Array();
    $('ul#pictograms li').each(function(index) {
      if ($(this).hasClass('selected')) {
        var pictogram = $(this).attr('id').substr(10);
        pictograms.push(pictogram);
      }    
    });
    if (pictograms == '') {
      var queryString = SITE_URL+'/home/filter';
    } else {
      var queryString = SITE_URL+'/home/filter/'+pictograms.join(',');
    }
    $("#apps").load(
      queryString,
      function () {
        /* infiniteScroll(); */
        retriggerAppEffects();
      }
    );
    event.preventDefault();
  });
}

function retriggerAppEffects() {
  $('.jcarousel-skin-worm').css({'display':'none'});
  $('.event.long.scroll-pane').jScrollPane({showArrows: true, animateScroll: true});
}

function agendaList() {
  $('li#agendaPrevious a, li#agendaNext a').live('click', function(event) {
    var pageId = $(this).attr("id").substr(5);
    $.ajax({
      url : SITE_URL+'/home/agenda',
      type : "GET",
      data : {page:pageId},
      success : function(response) {
        $('ul#agendaList li').remove();
        $('ul#agendaList').html(response);
      }
    });
    event.preventDefault();
  });
}

function newsletter() {
  $('form#NewsletterForm').submit(function(event) {
    $(this).ajaxSubmit({
      'beforeSend' : function() {
        $("li#newsletter span.pageAppBody").hide();
        $("li#newsletter span.pageAppNewsletterContainer").append('<span class="loading"></span>');
      },
      'success' : function(result) {
        $("li#newsletter span.pageAppNewsletterContainer .loading").remove();
        $("li#newsletter span.pageAppNewsletterContainer").append(result);
      }
    });
    event.preventDefault();
  });
  
/*
  $('span.pageAppCapsules span.pageAppCapsule').click(function(event) {
    $("li#newsletter span.pageAppBody").show();
    $("li#newsletter span.pageAppMessage").remove();
    if (!$(this).hasClass('selected')) {
      $('span.pageAppCapsules span').toggleClass('selected');
      if ($(this).text() === 'Uitschrijven') {
        $('li#newsletter span.pageAppNewsletterContainer').animate({'left' : '-165px'});
      } else {
        $('li#newsletter span.pageAppNewsletterContainer').animate({'left' : '0px'});
      }
    }
    event.preventDefault();
  });
*/
}

/*Cookies*/
function createCookie(name,value,days) {
  if (days) {
  	var date = new Date();
  	date.setTime(date.getTime()+(days*24*60*60*1000));
  	var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function removeCookie(name) {
  createCookie(name,"",-1);
}

function externalLinks() {
  $("a[href^=http]").each(function(){
    if(this.href.indexOf(location.hostname) == -1) {
       $(this).attr({
          target: "_blank",
          title: "Opens in a new window"
       });
    }
  });
}

$(document).ready(function() {
	toggleCarousel();
	loadApplications();
/* 	infiniteScroll(); */
	socialButtons();
	loadEffects();
	filterApps();
	agendaList();
	newsletter();
	externalLinks();
});
