/* part of fxisCMS framework */

$(document).ready(function(){

  //new slider
	var theInt = null;
	var $crosslink, $navthumb;
	var curclicked = 0;
	
	function checkThumbs(){
	 var thumbCount = 1;
	 $('#slider-arrow').remove();
	 $('.cross-link').each(function(){
	   if($(this).hasClass('active-thumb')){
	     $('img',this).attr('src','/gfx/slides/thumbs/'+thumbCount+'active.png');
	     $('body').prepend('<div id="slider-arrow"></div>');
	     var posTopImg = $('img',this).offset().top;
	     var posLeftImg = $('img',this).offset().left;
	     $('#slider-arrow').css('top',posTopImg-9);
	     $('#slider-arrow').css('left',posLeftImg+18);
	   } else {
	     $('img',this).attr('src','/gfx/slides/thumbs/'+thumbCount+'.png');
	   }
	   thumbCount = thumbCount+1;
	 });
	}
	
	theInterval = function(cur){
		clearInterval(theInt);
		
		if( typeof cur != 'undefined' )
			curclicked = cur;
		
		$crosslink.removeClass("active-thumb");
		$navthumb.eq(curclicked).parent().addClass("active-thumb");
			$(".stripNav ul li a").eq(curclicked).trigger('click');
		
		theInt = setInterval(function(){
			$crosslink.removeClass("active-thumb");
			$navthumb.eq(curclicked).parent().addClass("active-thumb");
			$(".stripNav ul li a").eq(curclicked).trigger('click');
			curclicked++;
			checkThumbs();
			if( 6 == curclicked )
				curclicked = 0;
			
		}, 6000);
	};
	
	$(function(){
		
		$("#main-photo-slider").codaSlider();
		
		$navthumb = $(".nav-thumb");
		$crosslink = $(".cross-link");
		
		$navthumb
		.click(function() {
			var $this = $(this);
			theInterval($this.parent().attr('href').slice(1) - 1);
			checkThumbs();
			return false;
		});
		theInterval();
		$('.slide-wrap img').each(function(){
		  $(this).css('visibility','visible');
		});
	});  

  //function extension
  $.fn.repairWidth = function() {
      var width = 0;
      $('li',this).each(function(){  
        width = width+$('div',this).outerWidth();
      });
      $(this).width(width+20);
  }

  //error box overlay
  function adjustOverlay(){
    $('#overlay').height($(document).height());
    $('#overlay').width($(document).width());
    $('#overlay').click(function(){
      closeOverlay();
    });
    
    $('#messagebox #close').click(function(e){
      e.preventDefault();
      closeOverlay();
    });        
  }
  function closeOverlay(){
    $('#overlay').fadeOut('fast',function(){
      $('#overlay').remove();
    });
    $('#messagebox').fadeOut('fast',function(){
      $('#messagebox').remove();
    });  
  }
  function adjustMessagebox(){
    var width = $('#messagebox').outerWidth();
    var height = $('#messagebox').outerHeight();
    $('#messagebox').css("top", ( $(window).height() - height ) / 2+$(window).scrollTop() + "px");
    $('#messagebox').css("left", ( $(window).width() - width ) / 2+$(window).scrollLeft() + "px");    
  }
  $(window).bind("resize", adjustOverlay);
  $(window).bind("resize", adjustMessagebox);
  $(window).bind("scroll", adjustMessagebox);
  
  //kopen
  
  //set page url
  var pageURL = document.location.href;
  myregexp = new RegExp("/Kopen2?");
  kopenUrlAr = myregexp.exec(pageURL);
  if(kopenUrlAr){
    var kopenUrl = kopenUrlAr[0];
  } else {
    var kopenUrl = "/Kopen"
  }
  
  //see if we have errors to show
  $.ajax({
    type: "POST",
    url: kopenUrl+'?ajaxErrors',
    data: '',
    success: function(returnData){
      var result = jQuery.parseJSON(returnData);
      if(result.errors){
        $('body').prepend('<div id="overlay"></div><div id="messagebox"><a href="#" id="close">Sluiten</a><h3>Er zijn fouten opgetreden</h3><ul>'+result.errors+'</ul></div>');
        adjustOverlay();
        adjustMessagebox();
      }      
    }
  });
   
  $('.page-kopen .form .right').bind('click', function(e){
    //this is a checkbox click
    if(!$(e.target).is('input:checkbox')){
      if($('input:checkbox',this).length > 0){
        if(!$('input:checkbox',this).attr('disabled')){
          if($('input:checkbox',this).attr('checked')){
            $('input:checkbox',this).attr('checked',false);
          } else {
            $('input:checkbox',this).attr('checked',true);
          }
        } 
      }
      if($('input:radio',this).length > 0 && !$('input:radio',this).attr('disabled')){
        var name = $('input:radio',this).attr('name');
        $('input:radio[name='+name+']').attr('checked',false);
        $('input:radio',this).attr('checked',true);      
      }
    }
    highlightDivRight(); 
    submitKoopForm();   
  }); 
  function submitKoopForm(){
    var formData = $('.page-kopen .form form#koopform').serialize();
    $.ajax({
      type: "POST",
      url: kopenUrl+'?ajax',
      data: formData,
      success: function(returnData){
        $('.form div.summary div.contents').html(returnData);
      }
    });
  }
  submitKoopForm(); 
  $('.page-kopen .form a.prev').html("Vorige Stap");
  $('.page-kopen .form a.next').html("Volgende Stap");
  $('.page-kopen .form a#submit_step3').click(function(e){
    //disable link
    e.preventDefault();
    
    //remove errors
    $('.page-kopen .form .formError').each(function(){
      $(this).remove();
    });    
    
    var formData = $('.page-kopen .form form#koopform').serialize();
    $.ajax({
      type: "POST",
      url: kopenUrl+'?ajax2',
      data: formData,
      success: function(returnData){
        var result = jQuery.parseJSON(returnData);
        var hold = false;
        var errors = '';
        $.each(result,function(id, error){
          if(error.length  > 0){
            hold = true;
            $('.page-kopen .form input#'+id).parent().append($('<div class="formError">*</div>').hide().fadeIn('fast'));
            errors = errors+'<li>'+error+'</li>';
          }
        });
        if(hold == true){
          $('body').prepend('<div id="overlay"></div><div id="messagebox"><a href="#" id="close">Sluiten</a><h3>Er zijn fouten opgetreden</h3><ul>'+errors+'</ul></div>');
          adjustOverlay();
          adjustMessagebox();
        } else {
          //submit form
          $('form#koopform').submit();
        }         
      }
    });                                    
  });
  
  $('.page-kopen .form a#submit_step4').click(function(e){
    //disable link
    e.preventDefault();
    if($('.page-kopen .form .idealBank:checked').val()){
      $('form#koopform').submit();  
    } else {
      $('body').prepend('<div id="overlay"></div><div id="messagebox"><a href="#" id="close">Sluiten</a><h3>Er zijn fouten opgetreden</h3><ul>Selecteer een bank voor uw iDeal overboeking</ul></div>');
      adjustOverlay();
      adjustMessagebox();
    }
  });
  
  //get session variables
  if($('.page-kopen .form input#mpossible_step').val() == 3){
    $.ajax({
      type: "POST",
      url: kopenUrl+'?ajax3',
      data: '',
      success: function(returnData){
        var result = jQuery.parseJSON(returnData);
        $.each(result,function(id, value){
          var elem = $('.page-kopen .form #'+id);
          var type = elem.get(0).tagName;
          if(elem.length > 0){
            if(type == 'INPUT' && id !== 'mpossible_captcha'){
              if(elem.attr('type') == 'text'){
                elem.val(value);
              } else if (elem.attr('type') == 'checkbox'){
                elem.attr('checked',true);
              }
            }
            if(type == 'SELECT'){
              $('option',elem).each(function(){
                if($(this).val() == value){
                  $(this).attr('selected',true);
                } else {
                  $(this).attr('selected',false);
                }
              });
            }        
          }
        });        
      }
    });
  }
  
  //buy
  $('.page-kopen .form a#buy').click(function(e){
    e.preventDefault();
    $.ajax({
      type: "POST",
      url: kopenUrl+'?ajax4',
      data: '',
      success: function(returnData){
        var result = jQuery.parseJSON(returnData);
        if(result.status == 'error'){
          var title = 'Er is een fout opgetreden';
        } else {
          var title = 'Uw bestelling is geplaatst';
        }
        var text = result.text;
        var location = result.location;
        $('body').prepend('<div id="overlay"></div><div id="messagebox"><h3>'+title+'</h3>'+text+'<p><a href="'+location+'">Klik hier om verder te gaan!</a></p></div>');
        adjustOverlay();
        adjustMessagebox();        
      }
    });    
    
  });   
    
  
  function highlightDivRight(){
    $('.page-kopen .form .right').each(function(){
      if($('input:checkbox',this).attr('checked') || $('input:radio',this).attr('checked')){
        $(this).addClass('extra');
      } else {
        $(this).removeClass('extra');
      }
    });
  }
  
  highlightDivRight();
  
  //item hover kopen
  $('.page-kopen .form div.right').hover(function(){
    var itemimgbox = $('div.itemimg',this);
    var arrow = $('div.arrow',this);
    var itemimgboxHeight = itemimgbox.outerHeight();
    var rightBoxHeight = $(this).outerHeight();
    arrow.css('top',rightBoxHeight/2-6);    
    itemimgbox.css('top',(itemimgboxHeight/-2+rightBoxHeight/2));
    itemimgbox.show();
    arrow.show();
  },function(){
    $('div.itemimg',this).hide();
    $('div.arrow',this).hide();
  });

  //menu
  $('ul.menu-level-2').each(function(){
    $(this).repairWidth();
  });
  function rePosMenu(){
    var width = $('.menu li.menu-level-1').offset().left;
    $('.menu ul.menu-level-2').each(function(){
      parentDiv = $('div',$(this).parent());
      posLeftParent = parentDiv.offset().left;
      posLeft = posLeftParent - parseInt($(this).outerWidth()/2) + parseInt(parentDiv.outerWidth()/2);
      posLeft = posLeft < 0 ? 0 : posLeft;
      var top = $(this).parent().parent().offset().top;
      $(this).css('top',top+28);
      $(this).css('left',posLeft);
    });
  }
  function closeAll(){
    $('.menu ul.menu-level-2').each(function(){
      $(this).hide();
      $(this).css('visibility','hidden');
      $(this).css('display','block');
    });
  }
  rePosMenu();
  //hover submenu
  $('.menu li.menu-level-1').each(function(){
    $(this).hover(function(){
      clearTimeout($(this).data('timeout'));
      var object = $(this); 
      if($('ul',object).css('visibility') == 'hidden'){
        closeAll();
        rePosMenu();       
        var t2 = setTimeout(function() {
            $('ul',object).css('display','none');
            $('ul',object).css('visibility','visible');
            $('ul',object).fadeIn('fast');  
        }, 100);  
        $(this).data('timeout2', t2);
       }        
    },function(){ 
      var object = $(this); 
      var t = setTimeout(function() {
        $('ul',object).fadeOut('fast', function(){
          $('ul',object).css('visibility','hidden');
          $('ul',object).css('display','block');
        });
      }, 1000);
      $(this).data('timeout', t);          
    });
  });

  //fix png
  $('body').supersleight({shim: '/gfx/x.gif'});

  //slider (oud)
  $("#slider").css('display','block');
  $("#slider img").css('display','block');
	$("#slider").easySlider({
		auto: true, 
		continuous: true,
		prevId: 'sliderPrev',
		nextId: 'sliderNext',
		controlsShow: false,
		pause: 6000,
		speed: 200
	});

  //guestbook
  if($('#guestbook').length > 0){
    //if there is an error
    if($('#guestbookForm .error').length > 0){
      createGuestbookForm();    
    }
    $('#guestbookSubmitMessage').click(function(){
      createGuestbookForm();
    });
    
    //get the submitbutton click
    $('#guestbookForm form').submit(function(e){
      var name = $('#fxiscmsName').val();
      var email = $('#fxiscmsEmail').val();
      var subject = $('#fxiscmsSubject').val();
      var captcha = $('#fxiscmsCaptcha').val();
      var emailCheck = /^(?:$)|(?:[a-zA-Z0-9\-_.]+@[a-zA-Z0-9\-_.]+\.[a-zA-Z]{1,5}$)/.exec(email);
      var nameCheck = /^[0-9a-zA-Z.,-_&@ ]{3,255}$/.exec(name);
      var subjectCheck = /^(?:$)|(?:(?:.+){3,255}$)/.exec(subject);
      var captchaCheck = /^[A-Z1-9]{6}$/.exec(captcha);
      
      //remove errors
      $('#guestbookForm .errorSmall').each(function(){
        $(this).remove();
      });
      var returnCheck = true;
      if(!emailCheck){
        $('<div class="errorSmall">**Geen geldig emailadres opgegeven</div>').hide().appendTo('#guestbookForm .row-fxiscmsemail .right').fadeIn('fast');
        returnCheck = false;
      }
      if(!nameCheck){
        $('<div class="errorSmall">**Geen geldige naam opgegeven</div>').hide().appendTo('#guestbookForm .row-fxiscmsname .right').fadeIn('fast');
        returnCheck = false;
      }
      if(!subjectCheck){
        $('<div class="errorSmall">**Geen geldig onderwerp opgegeven</div>').hide().appendTo('#guestbookForm .row-fxiscmssubject .right').fadeIn('fast');
        returnCheck = false;
      }
      if(!captchaCheck){
        $('<div class="errorSmall">**Geen geldige Captcha code opgegeven</div>').hide().appendTo('#guestbookForm .row-fxiscmscaptcha .right').fadeIn('fast');
        returnCheck = false;
      }             
      
      //return
      if(returnCheck){
        return true;
      } else {
        return false;
      }
    });    
  }
  
  //pagination
  if($('#pagination').length > 0){
    $('#pagination span').each(function(){
      $(this).click(function(){
        var id = $(this).attr('id');
        var idReg = /^pagination-([0-9]+)$/.exec(id);
        if(id[0]){
          //construct url
          var params = $.url.attr('query');
          var path = $.url.attr('path');
          if(!/\/$/.exec(path)) path = path+'/';
          if(params){
            params = params.replace(/page[0-9]+/i,'page'+idReg[1]);
          } else {
            params = 'page'+idReg[1];
          }
          if(!/page/.exec(params)){
            params = params+'&page'+idReg[1];
          }        
          $(location).attr('href',path+'?'+params);
        }
      });
    });
  }  
  
  //contact form
  if($('#contactForm').length > 0){
    //get the submitbutton click
    $('#contactForm form').submit(function(e){
      var name = $('#fxiscmsName  ').val();
      var email = $('#fxiscmsEmail').val();
      var emailCheck = /^[a-zA-Z0-9\-_.]+@[a-zA-Z0-9\-_.]+\.[a-zA-Z]{1,5}$/.exec(email);
      var nameCheck = /^[0-9a-zA-Z.,-_&@ ]{3,255}$/.exec(name);
      
      //remove errors
      $('#contactForm .errorSmall').each(function(){
        $(this).remove();
      });

      var returnCheck = true;
      if(!emailCheck){
        $('<div class="errorSmall">**Geen geldig emailadres opgegeven</div>').hide().appendTo('#contactForm .row-fxiscmsemail .right').fadeIn('fast');
        returnCheck = false;
      }
      if(!nameCheck){
        $('<div class="errorSmall">**Geen geldige naam opgegeven</div>').hide().appendTo('#contactForm .row-fxiscmsname .right').fadeIn('fast');
        returnCheck = false;
      }      
      
      //return
      if(returnCheck){
        return true;
      } else {
        return false;
      }
    });
  }
  
  //captcha Refresh
  if($('#captchaRefresh').length > 0 && $('#captchaImg').length > 0){
    $('#captchaRefresh').click(function(){
      var timestamp = new Date().getTime();
      $('#captchaImg').attr('src','/captcha.php?'+timestamp);
    });
  }
  
  //lightbox
  if ($('.attachments').length > 0){
    $('.attachments .lightbox').attr('rel','bijlage');
    $('.attachments .lightbox').colorbox({speed:500, maxWidth:'80%', maxHeight:'90%'});
  }
  
  //contact form
  if ($('#contactForm #berichtFieldFull').length > 0){
    //wysiwyg   
  };         
});

function createGuestbookForm(){
  if($('#guestbookFormOverlay').length > 0) $('#guestbookFormOverlay').remove();
  $('#guestbookForm').hide().prependTo('body').fadeIn('slow');
  $('<div class="guestbookFormOverlay" id="guestbookFormOverlay"></div>').hide().prependTo('body').fadeTo('slow',0.6);
  //fadeout
  $('#guestbookFormOverlay').click(function(){
    $('#guestbookForm').fadeOut('slow');
    $('#guestbookFormOverlay').fadeOut('slow');
  });       
}
