$(document).ready(function() {
  
  if($('#subnavigation a[title=\'Klachten\']').length > 0){
    $('#subnavigation a[title=\'Klachten\']').addClass('fancybox');
  }
  
  GenerateCaptcha();
  
  $("select, input:radio, input:checkbox").uniform();

  $('#slideshow .right .images').cycle({
    fx                  :  'fade',
    speed                :  'fast',
    timeout              :  6000,
    random                : true
  });
  
  $('#slideshow .right .news .slides').cycle({
    fx                  :  'fade',
    speed                :  'fast',
    timeout              :  7000,
    pager                :  '.nav',
    pagerAnchorBuilder  : function(index) {            
      var LinkTitle = $('#slideshow .right .news .item').eq(index).find('h1:first').text();
      return '<a title="' + LinkTitle + '" class="slide-nav" href="#">&nbsp;</a>';
    }
  });
  
  $(".list-toggle .item").each(function() {
    $(this).find(".category_name").click(function() {      
      // set settings for current item
      $(this).addClass("current");
      
      $(this).next("div:first").stop(true,true).slideToggle(function() {
        if($(this).css("display") == "none") {
          $(this).prev(".category_name").removeClass("current");
        } else {
          $(this).prev(".category_name").addClass("current");  
        }
      });

    });
  });
  
  $('a.house, a.company').mouseenter(function(){
    var _this = $(this);
    
    $('img', $(this)).eq(1).fadeIn('fast', function(){
      _this.stop(true).animate({ bottom : '-10px' });  
    });
    $('img', $(this)).eq(0).fadeOut('fast');
  }); 
  
  $('a.house, a.company').mouseleave(function(){
     var _this = $(this);
    $(this).stop(true).animate({ bottom : '-44px' }, function(){
      $('img', _this).eq(1).fadeOut('fast');
      $('img', _this).eq(0).fadeIn('fast');
    });
  });
  
  $('a[rel=external]').attr('target','_blank');
  
  $(".twitter").tweet({
    join_text: "auto",
    username: ["opsparkstad"], //"oppenpelzersimo"
    avatar_size: 0,
    count: 2,
    auto_join_text_default: "",
    auto_join_text_ed: "",
    auto_join_text_ing: "",
    auto_join_text_reply: "",
    auto_join_text_url: "",
    loading_text: "tweets laden...",
    template: '{text}'
  });
  
  $('.quick-links a[href="#"]').click(function(){
    if($(this).hasClass('link')){
      return true;
    }
    var FoldDiv = $(this).parent().find('.fold-div');
    var NewHeight = FoldDiv[0].scrollHeight;
    if(FoldDiv.height() > 0){
      FoldDiv.animate({
        height : '0px'
      });
    } else {
      FoldDiv.animate({
        height : NewHeight + 'px'
      });
    }
    return false;
  });
  
  $("a.fancybox").fancybox({
    'transitionIn'  :  'elastic',
    'transitionOut'  :  'elastic',
    'speedIn'    :  600, 
    'speedOut'    :  200, 
    'overlayShow'  :  true
  });
  
  CreateTables();  
  
  if($("#newsletter").length > 0){
    $("#newsletter").validateForm(aFormValidationFields, formSettings, debugSettings);
  }
	
	SetSlider();
  SetYoutubeVideos(); 
});

var toolTipCall = "<" + "script" + " type='text/javascript'>" + "setTooltip()" + "<" + "/script" + ">";  

var formSettings = {
  formId                  : "newsletter",
  errorMsgClass           : "errorMsg",
  completeMsgSucces       : "Bedankt voor het inschrijven. U ontvangt binnen enkele minuten een bevestigings e-mail.",
  completeMsgDivId        : "newsletter_container",
  errorMsgCustomHTML      : "<span class='spanTooltip' style='display: none;'>_ERROR_</span><img src='/pics/error.png' alt='' class='tooltip png_fix' />  " + toolTipCall,
  selectboxDefaultValue   : -1,
  postUrl                 : "/IManager/MailingOptIn"      
}

var debugSettings = { }

var aFormValidationFields = new Array(              
  { ElementId   : "__d",     ValidationType : "NotEmpty",         ErrorMsg : "Vul uw voornaam in." }, 
  { ElementId   : "__e",     ValidationType : "NotEmpty",         ErrorMsg : "Vul uw achternaam in." },                                
  { ElementId   : "__g",     ValidationType : "EMailAddress",     ErrorMsg : "Vul een correct e-mailadres in." }                                                                  
);

function DisplaySearchMode(ActiveMode) {
  $(".SearchModeSwitch a").removeClass("active");
  $('.SearchModeSwitch a.' + ActiveMode).addClass("active");
  $('div[id^="search_"]').each(function() {$(this).hide()});
  $('#search_'+ ActiveMode).show();
}

function validatePollForm(ContentIndex) {        
    if($("input[name=pt_88570]:checked").val() == null) {
        alert("Kies een optie!");
        return false;
    }
    
    setCookie('poll_' + ContentIndex,1,'365'); 
    
    $.ajax({
      url : '/IManager/Post/26403/kMR9/msc8yVL6TZCXnrUzBNGSxOK4XZhYC1hC0j/mxNL',
      data: $('#poll-form').serialize(),
      type: 'POST',
      success: function(response){
        var Obj = $("<div>" + response + "</div>");
        var Html = Obj.find('#poll-result');
        
        $('#result').html(Html);
        $('#result').closest('.fold-div').css('height','auto');
      }
    });
     
    return false;    
}

function setTooltip() 
{
  $('.errorMsg img').tooltip({
    track: true,
    delay: 0,
    showURL: false,
    bodyHandler: function() { 
      return $($(this).prev(".spanTooltip")).html(); 
    }
  });
}

function ValidateNewsletterForm () {
  if($('#_firstname').val().length <= 0){
    alert('Vul uw voornaam in.');
    $('#_firstname').focus();
    return false;
  }
  if($('#_lastname').val().length <= 0){
    alert('Vul uw achternaam in.');
    $('#_lastname').focus();
    return false;
  }
  if($('#_email').val().length <= 0){
    alert('Vul een correct e-mailadres in.');
    $('#_email').focus();
    return false;
  }
  
  $('#newsletter-top').attr('action','/newsletter/postform.php');
  return true;  
}

function ValidateReactionForm () {
  if($('#reaction_captcha').val() != $('.captcha').text()){
    alert('U heeft de antispam vraag niet correct over genomen.');
    return false;
  }
  
  if($('#reaction_name').val().length <= 0){
    alert('Vul uw naam in.');
    $('#reaction_name').focus();
    return false;
  }
  if($('#reaction_email').val().length <= 0){
    alert('Vul een correct e-mailadres in.');
    $('#reaction_email').focus();
    return false;
  }
  if($('#reaction_reaction').val().length <= 0){
    alert('Vul een reactie in.');
    $('#reaction_reaction').focus();
    return false;
  }
  
  $('#reaction-form').attr('action','/IManager/Post/26802/KV6j/msG8teKEvfcDngYLYGRW4ivPCF5iLYcHRq/mxNL');
  return true;  
}

function GenerateCaptcha(){
  var randomnumber=Math.floor(Math.random()*10001);
  $('.captcha').html(randomnumber);
}

$(window).load(function(){
  $('.partners img').each(function(){
    imgObj = document.getElementById($(this).attr('id'));
    var Img         = $(this);
    var top = ( Img.parent().height() - Img.height() ) / 2; 
    Img.css('margin-top', top); 
      
    if($.browser.msie){
      
      grayscaleImageIE(imgObj);
      Img.mouseenter(function(){
        imgObj = document.getElementById($(this).attr('id'));
        imgObj.style.filter = '';
        $(this).css({ opacity : 1 });
      });
      Img.mouseleave(function(){
        imgObj = document.getElementById($(this).attr('id'));
        imgObj.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayScale=1)';
        $(this).css({ opacity : 0.4 });
      });
      
    } else {
      var GrayScale   =  grayscaleImage(imgObj);
      var Original    = $(this).attr('src');      
      Img.attr('src', GrayScale);

      Img.parent().mouseenter(function(){
        $(this).find('img').attr('src', Original);
        $(this).find('img').css({ opacity : 1 });
      });
      Img.parent().mouseleave(function(){
        $(this).find('img').attr('src', GrayScale);
        $(this).find('img').css({ opacity : 0.4 });
      });
    }
    Img.css({ opacity : 0.4 });
    Img.css('visibility', 'visible'); 
  });
});

function CreateTables (){
  var Counter = 0;
  $('.column-right table').attr('cellspacing','0');
  $('.column-right table tr').each(function(){
    if(Counter != 0){
      if(Counter%2 == 0){
        $(this).addClass('even');
      } else {
        $(this).addClass('uneven');
      }
      if($(this).html() == ''){
        $(this).html('&nbsp;');
      }
    } else {
      $(this).addClass('heading');
    }
    Counter++;
  });
  $('.column-right table td').each(function(){
    if($(this).text() == ''){
      $(this).html('&nbsp');
    }  
  });
}
function grayscaleImageIE(imgObj) {
  imgObj.style.filter = 'progid:DXImageTransform.Microsoft.BasicImage(grayScale=1)';
}

function grayscaleImage(imgObj) {
  var canvas = document.createElement('canvas');
  var canvasContext = canvas.getContext('2d');
  
  var imgW = imgObj.width;
  var imgH = imgObj.height;
  canvas.width = imgW;
  canvas.height = imgH;
  
  canvasContext.drawImage(imgObj, 0, 0);
  var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);
  
  for(var y = 0; y < imgPixels.height; y++){
    for(var x = 0; x < imgPixels.width; x++){
      var i = (y * 4) * imgPixels.width + x * 4;
      var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
      imgPixels.data[i] = avg; 
      imgPixels.data[i + 1] = avg; 
      imgPixels.data[i + 2] = avg;
    }
  }
  
  canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
  return canvas.toDataURL();
}

function SetSlider() {    
	var ProductContainerWidth = parseInt($(".slider-container").width()) + 10;
	var SlideBlock            = $(".slider-container .slider");

	var SlideWidth = $(".slider-container #prod_container").width();

	CheckArrows();
	
	$(".slider-container .sliderimg a").click( function() {
    $(".slider-container .sliderimg a").removeClass('active');
    $(this).addClass('active');
		$(".imageslider .mainimg img").attr("src", $(this).attr("href"));
		return false;
	});

	$("#slider .arrowleft .active").unbind('click');
	$("#slider .arrowleft .active").click( function() {
		$(".slider-container .slider").stop(true,true);
		
		SlideBlockLeft     = parseInt(SlideBlock.css("left"));
		SlideBlockLeftPos = SlideBlockLeft * -1;

		if(SlideBlockLeftPos >= ProductContainerWidth) {
			NewLeft = -1 * (SlideBlockLeftPos - ProductContainerWidth); 
			DoAnimateSlider(NewLeft);
		}
	});

	$("#slider .arrowright .active").unbind('click');  
	$("#slider .arrowright .active").click( function() {
		$(".slider-container .slider").stop(true,true);
		
		SlideBlockLeft = parseInt(SlideBlock.css("left"));
		SlideBlockLeft -= ProductContainerWidth;
		if(SlideBlockLeft < $(".slider-container #prod_container").width()) {
			DoAnimateSlider(SlideBlockLeft);
		}
	});
}

function CheckArrows() {
	var SlideBlock 						= $(".slider-container .slider");
	var ProductContainerWidth = parseInt($(".slider-container").width()) + 10;  
	var SlideWidth 						= $(".slider-container #prod_container").width();

	SlideBlockLeft     	= parseInt(SlideBlock.css("left"));
	SlideBlockLeftPos 	= SlideBlockLeft * -1;
	SlideDiff          	= SlideWidth - SlideBlockLeftPos;

	if(SlideBlockLeft >= 0) {
		$("#slider .arrowleft .active").css("display","none");
	} else { 
		$("#slider .arrowleft .active").css("display","block");
	}

	if(SlideDiff <= ProductContainerWidth) {
		$("#slider .arrowright .active").css("display","none");
	} else {
		$("#slider .arrowright .active").css("display","block");
	}
}
	
function DoAnimateSlider(Left)
{
	var SlideBlock = $(".slider-container .slider");
	SlideBlock.stop(true,true);
	
	var CurrentLeft = SlideBlock.css("left");
	SlideBlock.css("left", Left + "px");
	
	CheckArrows();
	SlideBlock.css("left", CurrentLeft);
	SlideBlock.animate({
		left: SlideBlockLeft
	}, 500, function () { CheckArrows(); });
}

function SetYoutubeVideos() {
  
  $(".youtube").each( function() {
    var VideoId   = GetYoutubeVideoId($(this).attr("href"));
    $(this).html("<img style=\"width: 222px;\" src=\"http://img.youtube.com/vi/"+ VideoId +"/0.jpg\" alt=\"youtube\" />")
    $(this).wrap('<div class="youtube-block">');
    $(this).before('<div class="overlay"></div>');
    
    $(this).prev().click(function() {
      $(this).next().trigger('click');
    });
    
    $(this).click(function() {
      var VideoId   = GetYoutubeVideoId($(this).attr("href"));
        $.fancybox({
          'padding'        : 0,
          'autoScale'      : false,
          'transitionIn'  : 'none',
          'transitionOut'  : 'none',
          'title'          : this.title,
          'titleShow'      : false,
          'width'          : 854,
          'height'        : 480,
          'href'          : "http://www.youtube.com/v/" + VideoId + "&autoplay=1",
          'type'          : 'swf',
          'swf'            : {
            'wmode'            : 'transparent',
            'allowfullscreen'  : 'true'
          }
      });
      
      return false;
    });
  });
}

function GetYoutubeVideoId (URL) {
  if(URL === null){ 
    return ""; 
  }
  
  var VideoId;
  var Results;
  Results = URL.match("[\\?&]v=([^&#]*)");
  
  if(Results == null){
    Results = URL.split("/")  
    VideoId = ( Results === null ) ? URL : Results[3];  
  } else {
    VideoId = Results[1]
  }

  return VideoId;
}

