function myToggleClass(fieldId, fieldClass) {
	document.getElementById(fieldId).className = fieldClass;
}

function submitForm(id) {
	if (id == 'searchForm') {
		if (document.getElementById('query').value == 'Uw zoekopdracht') {
			document.getElementById('query').value = '';
		}
	}
	document.forms[id].submit();
}

function printwindow(mypage, myname, w, h) {
	LeftPosition = (screen.width) ? (screen.width - w) / 2 : 100;
	TopPosition = (screen.height) ? (screen.height - h) / 2 : 100;
	settings = 'width=' + w + ',height=' + h + ',top=' + TopPosition + ',left=' + LeftPosition + ',scrollbars=yes,location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=yes';
	win = window.open(mypage, myname, settings);
}

function updateDatePullDownMenu(objForm, fieldName) {
	var pdmDays = fieldName + "_days";
	var pdmMonths = fieldName + "_months";
	var pdmYears = fieldName + "_years";

	time = new Date(objForm[pdmYears].options[objForm[pdmYears].selectedIndex].text, objForm[pdmMonths].options[objForm[pdmMonths].selectedIndex].value, 1);

	time = new Date(time - 86400000);

	var selectedDay = objForm[pdmDays].options[objForm[pdmDays].selectedIndex].text;
	var daysInMonth = time.getDate();

	for ( var i = 0; i < objForm[pdmDays].length; i++) {
		objForm[pdmDays].options[0] = null;
	}

	for ( var i = 0; i < daysInMonth; i++) {
		objForm[pdmDays].options[i] = new Option(i + 1);
	}

	if (selectedDay <= daysInMonth) {
		objForm[pdmDays].options[selectedDay - 1].selected = true;
	} else {
		objForm[pdmDays].options[daysInMonth - 1].selected = true;
	}
}

// BOOKMARK FUNCTION
function addToFavorites(obj, url, title) {
	if (window.sidebar) { // Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url, "");
	} else if (window.external) { // IE Favorite
		window.external.AddFavorite(url, title);
	} else if (window.opera && window.print) {
		// Opera Hotlist
		obj.setAttribute('href', url);
		obj.setAttribute('title', title);
		obj.setAttribute('rel', 'sidebar');
		obj.click();
	}
	return false;
}

function showDialog(p_sTitle, p_sHtml, p_iW, p_iH) {
	if (empty(p_sTitle)) {
		p_sTitle = '';
	}
	if (empty(p_sHtml)) {
		p_sHtml = '';
	}
	if (empty(p_iW)) {
		p_iW = 400;
	}
	if (empty(p_iH)) {
		p_iH = 240;
	}

	$("#dialog").attr('title', p_sTitle).html(p_sHtml).dialog({
		height: p_iH,
		width: p_iW,
		modal: true
	});
}

function initFormFancybox(id, w, h, m){ 			
	$('#'+id).fancybox({
   		changeFade: 'fast',
   		overlayColor: '#000',
   		overlayOpacity: 0.65,		
		type: 'iframe',
		width: w,
		height: h,
		transitionIn: 'elastic', 
		transitionOut: 'fade',
		speedIn: 600, 
		speedOut: 600,
		autoScale: false,
		centerOnScroll: true,
		onClosed: m
	});
}

function setRandomIndent() {
	iCurrentIndent = Math.round(3*(Math.random() % 1)) * 40;
	$('.img').each(function() {
		$(this).css('margin-left', '0px');
		if(this.offsetLeft == 20) {
			$(this).css('margin-left', iCurrentIndent+'px');
			while(iCurrentIndent == (iCurrentIndent = Math.round(3*(Math.random() % 1)) * 40)) { }			
		}
	});	
}

function setHovers() {
	$('.img').hover(
		// hover on
		function() {
			$(this).css({ 'z-index' : '10' });
			$(this).find('img').stop().animate({
				width: Math.round(this.clientWidth+(this.clientWidth/this.clientHeight*30)) + 'px',
				height: (this.clientHeight+30) + 'px'				
			},100);			
			var oCss = {
				marginTop: (this.clientHeight+50)/-2 + 'px',
				marginLeft: ((this.clientWidth*1.3)+20)/-2 + 'px',
				top: '50%',
				left: '50%',
				paddingLeft: '10px', 
				paddingRight: '10px',
				paddingTop: '10px',
				paddingBottom: '10px'
			};
			if ( $.browser.msie != true || parseInt( $.browser.version.slice(0,1) ) >= 9 ) {
				oCss.boxShadow = '0px 0px 8px #333';
			}
			$(this).find('div.wrapper').stop().css({'height': 'auto'}).animate(oCss, {
				complete: function(){
					$(this).find('div.details').show('fast');
				},
				duration: 100
			});
		},
		// hover off
		function() {
			$(this).css({ 'z-index' : '9'});
			$(this).find('div.details').hide('fast', function(){
				var oHolder = $(this).closest('div.img');
				oHolder.find('img').stop().css({'width' : 'auto'}).animate({
					height: '100px'
				},100);					
				var oCss = {
					marginTop: '0px',
					marginLeft: '0px',
					top: '0%',
					left: '0%',
					height: '100px',
					paddingLeft: '0px', 
					paddingRight: '0px',
					paddingTop: '0px',
					paddingBottom: '0px'
				};
				if ( $.browser.msie != true || parseInt( $.browser.version.slice(0,1) ) >= 9 ) {
					oCss.boxShadow = '0px 0px 0px 0px #FFF';
				}
				oHolder.find('div.wrapper').stop().css({'height': 'auto'}).animate(oCss,{
					complete: function(){
						oHolder.css({ 'z-index' : '0'});
					},
					duration: 100
				});
			
			});
		}
	);
}

// product images navigation
var aImg = [];
var iCurrentImg = 1;
var iMaxImg = 0;


$(document).ready(function() {

	if($('#grid').length){
		setRandomIndent();
		setHovers();
		$(window).resize(setRandomIndent);
	}
	
	
	
	if($("#dyslectisch").length){		
		$("#dyslectisch").hover(
		  function () {
			  $('#fontdyslectisch').show();
		  },
		  function () {
			  $('#fontdyslectisch').hide();
		  }
		);
		$("#dyslectisch").click(function(){
			if ($.cookie('dyslexie') == 1) {
				$.cookie('dyslexie', '0');
				document.location.reload();
			} else {
				Cufon.replace('#contentwrap *');
				Cufon.replace('.blogMessage *');
				Cufon.replace('#indexfooter *');
				$.cookie('dyslexie', '1');
			}
		});
		jQuery(document).ready(function(){
			if ($.cookie('dyslexie') == 1) {
				Cufon.replace('#contentwrap *');
				Cufon.replace('.blogMessage *');
				Cufon.replace('#indexfooter *');
			}
		});
	}
	
	/**
	 * @todo
	 */
	if($("#advancedSearch").length){
		var oSearchFormTimer = null;
		$("#advancedSearch").hover(
			function () {
				$('#uitgebreidzoeken').show();
			},
			function () {
				oSearchFormTimer = setTimeout(function(){
					$('#uitgebreidzoeken').hide();	
				}, 1000);
			}
		);
		$('#uitgebreidzoeken').hover(
			function(){ clearTimeout(oSearchFormTimer); }, 
			function(){ $(this).hide(); }
		);
	}
	
	
	// tonen/verbergen reserveren eten formulier
	if($('#closeReserverenForm').length){		
		$('#closeReserverenForm').click(function(){
			var opacityState = $('#formReserveren').css("opacity");
			$(this).html(((opacityState == 1) ? '<img width="14" height="45" border="0" src="template/images/klapuit.png">' : '<img width="14" height="39" border="0" src="template/images/klapin.png">')); 
			
			$('#formReserveren').animate({
			    opacity: ((opacityState == 1) ? 0 : 1)
			}, 1000);
			
			$('#commentReserveren table').animate({
				opacity: ((opacityState == 1) ? 0 : 1)
			}, 300, function(){
				$(this).slideToggle('slow');
			});			
		});
	}
	
	// tonen/verbergen reserveren eten formulier
	if($('#closeAgenda').length){
		
		$('#closeAgenda').click(function(){
			var opacityState = $('#agendaBoxes').css("opacity");
			$(this).html(((opacityState == 1) ? '<img width="14" height="45" border="0" src="template/images/klapuit.png">' : '<img width="14" height="39" border="0" src="template/images/klapin.png">')); 
			
			$('#agendaBoxes').animate({
				opacity: ((opacityState == 1) ? 0 : 1)
			}, 1000);
			
			$('#agendaItem').animate({
				opacity: ((opacityState == 1) ? 0 : 1)
			}, 300, function(){
				$(this).slideToggle('slow');
			});			
		});
	}
	
	// Search by hover effect (just above right menu)
	if($("#showItemGroups").length){		
		$("#showItemGroups").mouseover(
		function () {
			$('#itemGroups').show();
		});
		
		$("#itemGroups").mouseleave(
		function () {
			$('#itemGroups').hide();
		});
	}
	
	// Input text field toggle
	// Set default text in attr value and add class to input
	// field with
	// classname: toggle
	$('input:text.toggle').each(function(idx, elem) {
		var oInput = $('#' + elem.id);
		oInput.click(function() {
			if (empty(oInput.attr('rel')) || oInput.attr('rel') == oInput.val()) {
				oInput.attr('rel', oInput.val());
				oInput.val('');
			}
		});
		oInput.blur(function() {
			if (oInput.val() == '') {
				oInput.val(oInput.attr('rel'));
			}
		});
	});

	if($("#date").length){
		var oDate = new Date();
	    var month = oDate.getMonth();
	    var day = oDate.getDate();
	    console.log(day);
	    console.log(day);
	    console.log(day);
		$("#date").datepicker({ 
			dateFormat: 'dd-mm-yy', 
			minDate: new Date(oDate.getFullYear(), oDate.getMonth(), (oDate.getDate()+1))
		});
	}
	
	// Fancybox
	if ($("table.gallerytable").length) {
		$("table.gallerytable a").attr('rel', 'fancybox').fancybox({
	   		changeFade: 'fast',
	   		overlayColor: '#000',
	   		overlayOpacity: 0.65,		
			transitionIn: 'fade', 
			transitionOut: 'fade',
			speedIn: 600, 
			speedOut: 600				
		});
	}
	
	// lightbox for product images and image navigation
	if ($("#icLightBox").length) {
		
		$("#icLightBox").click(function(){
			$(".lightBox:nth-child("+iCurrentImg+")").triggerHandler('click'); 
		});
	                
		$(".lightBox").fancybox({
	   		changeFade: 'fast',
	   		overlayColor: '#000',
	   		overlayOpacity: 0.65,
			transitionIn: 'fade', 
			transitionOut: 'fade',
			centerOnScroll: true,
			speedIn: 600, 
			speedOut: 600
		    			
	   	});
								
		$('#icLightBox a.lightBox img').each(function(i){
			aImg[i] = $(this).attr('src');
			iMaxImg = (i+1);
			if(iMaxImg > 1){
				$('#pagingimages .next').css('visibility','visible');
			}		
		});
		
		function setImgNavigation(){			
			if(iCurrentImg > 1){
				$('#pagingimages .previous').css('visibility','visible');
			} 
			if(iCurrentImg < iMaxImg){				
				$('#pagingimages .next').css('visibility','visible');
			}
			$('#imageNo').text(iCurrentImg);
		}
		
		$('#pagingimages .previous').click(function(){			
			iCurrentImg = (iCurrentImg-1);
			if(iCurrentImg <= 1){
				$(this).css('visibility','hidden');
				iCurrentImg = 1;
			}
			setImgNavigation();
			$('#productImage').attr('src',aImg[(iCurrentImg-1)]);			
		});
		
		$('#pagingimages .next').click(function(){
			iCurrentImg = (iCurrentImg+1);
			if(iCurrentImg >= iMaxImg){
				$(this).css('visibility','hidden');				
				iCurrentImg = iMaxImg;
			}			
			setImgNavigation();
			$('#productImage').attr('src',aImg[(iCurrentImg-1)]);			
		});
	}
			
	// must be this frame size because after login the page will 
	// redirect to the above mentioned form inside the same frame
	if ($("#login").length) {	
		initFormFancybox('login', 850, 600, function(){
			document.location.href =  window.location.pathname;
		});
	}
	
	if ($("#gids").length) {
		initFormFancybox('gids', 800, 650);
	}
	
	if ($("#gids_info").length) {	
		initFormFancybox('gids_info', 610, 420);
	}
	
	if ($("#home_info").length) {	
		initFormFancybox('home_info', 610, 420);
	}
	
	if ($("#atelier_huren").length) {
		initFormFancybox('atelier_huren', 810, 340);
	}
	
	if ($("#atelier_vermelding").length) {
		initFormFancybox('atelier_vermelding', 610, 460);
	}
	
	if ($("#atelier_info").length) {	
		initFormFancybox('atelier_info', 610, 420);
	}
		
	if ($("#sectiec_info").length) {	
		initFormFancybox('sectiec_info', 610, 420);
	}
		
	if ($("#product_bestel").length) {	
		initFormFancybox('product_bestel', 650, 650);
	}
	
	if ($("#product_contact").length) {	
		initFormFancybox('product_contact', 572, 420);
	}
	
	if ($("#product_verkoop").length) {	
		initFormFancybox('product_verkoop', 592, 420);
	}
	
	if ($("#agenda_suggesties").length) {	
		initFormFancybox('agenda_suggesties', 610, 380);
	}
			
	if ($("#blog_info").length) {	
		initFormFancybox('blog_info', 610, 420);
	}
		
	if ($("#blog_reageer").length) {	
		initFormFancybox('blog_reageer', 610, 420);
	}
	
	if ($("#blog_suggesties").length) {	
		initFormFancybox('blog_suggesties', 610, 420);
	}	
		
	if($('#cycleBg').length){
		
		$('marquee').marquee().mouseover(function () {
			$(this).trigger('stop');
		}).mouseout(function () {
			$(this).trigger('start');
		}).mousemove(function (event) {
			if ($(this).data('drag') == true) {
				this.scrollLeft = $(this).data('scrollX') + ($(this).data('x') - event.clientX);
			}
		}).mousedown(function (event) {
			$(this).data('drag', true).data('x', event.clientX).data('scrollX', this.scrollLeft);
		}).mouseup(function () {
			$(this).data('drag', false);
		});;
		
		$('<div class="darkenBackground"></div>').insertBefore('#cycleBg img');
		$('.darkenBackground').css({
			backgroundColor: 'black',
			opacity: 0.4,
			position: 'absolute',
			width: '100%',
			height: '100%',
			zIndex: '2',
			left: 0,
			top: 0
		});
		
		// Background fading for serveral modules
		$(window).resize(function() {
			$('#cycleBg').css({
				height: $('body').height(),
				width: $('body').width()		    	
			});
			$('#cycleBg').find('div.bgImage').css({
				height: $('body').height(),
				width: $('body').width()
			});
			bodyAspect = $('body').width()/$('body').height();
			$('#cycleBg div.bgImage').find('img').each(function() {
				imgAspect = $(this).width() / $(this).height();
				if(bodyAspect>imgAspect) {
					$(this).width( $('body').width() );
					$(this).height( $('body').width()/imgAspect );
				} else {
					$(this).width( $('body').height()*imgAspect );	
					$(this).height( $('body').height() );				
				}
				$(this).css({
					marginLeft: $(this).width()/-2,
					marginTop: $(this).height()/-2
				});
			});
		});
		$(window).resize();
		
		
		$('#cycleBg').cycle({
			before: function() { $(window).resize(); }, 
			fx: 'fade',
			containerResize: false,
			slideResize: false,
			fit: true,
			speed:    1, 
			timeout:  7000,
			next:   '.nextBg', 
			prev:   '.prevBg',
			pause: 0
		});
	}

	// Uploadify for gids form		
	if($('#member_image').length){	
		var oImg = $('#member_image');
		var sSID = $('#SID').val();
		
		oImg.uploadify({
		    'uploader': '/template/swf/uploadify.swf',
		    'script': '/template/front_form.php',
		    'cancelImg': '/template/images/cancel.png',
		    'buttonImg': '/template/images/browsefile.png',
		    'scriptData': {},
		    'folder': '/upload/Image',
		    'sizeLimit': (2 * (1024 * 1024)),
		    'wmode': 'transparent',
		    'auto': false,
		    'width': 170,
		    'height': 20,
		    'multi': true,
		    'queueSizeLimit': 5,
		    'buttonText': (!empty($('#currentImages').html()) ? 'Afbeeldingen vervangen' : 'Afbeeldingen kiezen'),
		    'fileDataName' : 'member_image',
		    'fileExt': '*.jpg;*.jpeg;*.png',
		    'fileDesc': 'Website afbeeldingen (.jpg, .jpeg, .png)',
		    'onComplete': function(event, ID, fileObj, response, data) {
		    	$('#myImages').append('<input type="hidden" name="images[]" value="'+response+'" />');
		    	$('#currentImages').append('<img src="'+response+'" alt="" title="" style="margin: 3px; margin-left: 0px;" align="left" width="33" height="" />');
		    },
		    'onAllComplete': function() {
		    	document.getElementById('smallehavenForm').submit();						   
		    },
		    'onSelectOnce': function(){	    	
		    	if(empty($('#email').val())){
		    		$('#member_image').uploadifyClearQueue();
		    		showDialog('Er trad een probleem op!', 'Vul eerst al uw gegevens in alvorens u afbeeldingen probeert te uploaden.', 300, 120);
		    		return false;
		    	}
		    	return true;
		    }
		});
		
		$('#smallehavenForm').submit(function(){
			if(!empty($('#member_imageQueue').html())){
				$.ajax({ 
					// first remove complete dir with images before upload new one (only when user has logged on dir will be removed)
					url: '/template/front_form.php',
					data: "action=clear&SID="+sSID,
					cache: false,
					async: false,
					type: "POST",
					success: function(data) {						
						$('#myImages').html(''); // clear old images data
						$('#currentImages').html(''); // clear old images data
						//upload new images
						oImg.uploadifySettings('scriptData',{'SID': sSID, 'email': $('#email').val()},true);
						oImg.uploadifyUpload();
					}
				});				
			} else {
				// no images selected so submit directly (only possible when user has logged on and has already images uploaded 
				// images is required so... 
				document.getElementById('smallehavenForm').submit();
			}
			return false;
		});
		
	}	
});
