$(function() {
	//ALGEMEEN
	jQuery.httpbase = function( ){
		return $('base')[0].href;
	}
	
	$("#showNB").click(function(e) {
		$.ajax({
			url: $.httpbase()+'nieuws/nieuwsbriefinschrijven/',
			dataType: 'html',
			success: function(r) {
				$.popup.show('',r);
			}
		});
		return false;
	});	
	
	$(".clickable").click( function() {
		if($('a:eq(0)',this).attr('target') == "_blank"){
			window.open($('a:eq(0)',this).attr('href'));
		}else{			
			top.window.location.href=$('a:eq(0)',this).attr('href');
		}
		return false;
	});
	
	$('.searchfield label').each(function(i,e){
		if($('input',e).is(":checked")) {
			$(e).addClass('active');
			$(e).parents('form').attr('action',$('input:cheched',e).val());
		}
		$(e).click(function(){
			$('.searchfield label').removeClass('active');
			$('.searchfield label input').removeAttr('checked');
			$(e).addClass('active');
			$('input',e).attr('checked','checked');
			$(e).parents('form').attr('action',$('input:cheched',e).val());
		});
	});
	
	$('.sortable').sortable({helper:'clone',containment:'document'});
	$(".sortable").disableSelection();
	
	$("input#sms_label").change(function() {
		jQuery.smsMobielRequired(this);
	});
	
	$('input:button,button:button').keypress(function (e) {
		if(e.which == 13) {			
			$(e).trigger('click');
		}
	});
	
	$('#klantgegevensForm input').click(function() {
		$.copyAfleveradres( this.form );
	});
	$('#klantgegevensForm input').keyup(function() {
		$.copyAfleveradres( this.form );
	}); 
	$('#klantgegevensForm select').change(function() {
		$.copyAfleveradres( this.form );
	});
	$('#klantgegevensForm').each(function(){
		$.copyAfleveradres( this );
	});
	
	$('.getadres').each( function() {
		$(this).blur(function() {							
			if($(this).attr("name") == 'factuuradres_postcode' || $(this).attr("name") == 'factuuradres_huisnummer') {
				formulier = this.form;
				
				$.ajax({
					url: $.httpbase()+'ajaxgetadres/',
					data: 'land=' + formulier['factuuradres_land'].value + '&postcode=' + formulier['factuuradres_postcode'].value + '&huisnummer=' + formulier['factuuradres_huisnummer'].value,
					dataType: 'json',
					success: function(r) {	
						formulier['factuuradres_straat'].value = r['straat'];
						formulier['factuuradres_plaats'].value = r['plaats'];
						$.copyAfleveradres(formulier);
					}
				});
			} else if($(this).attr("name") == 'afleveradres_postcode' || $(this).attr("name") == 'afleveradres_huisnummer') {
				formulier = this.form;
				$.ajax({
					url: $.httpbase()+'ajaxgetadres/',
					data: 'land=' + formulier['afleveradres_land'].value + '&postcode=' + formulier['afleveradres_postcode'].value + '&huisnummer=' + formulier['afleveradres_huisnummer'].value,
					dataType: 'json',
					success: function(r) {			
						formulier['afleveradres_straat'].value = r['straat'];
						formulier['afleveradres_plaats'].value = r['plaats'];
						$.copyAfleveradres(formulier);
					}
				});
			}
			
		});
	}); 


	$("#bestel .betaalmethode").each( function() {
    	$(this).mouseover( function() {
    		$(this).addClass("hover");
    	});
    	
    	$(this).mouseout( function() {
    		$(this).removeClass("hover");
    	});
    	
    	
    	$(this).click( function() {    		
			$("#bestel .betaalmethode").each( function() {
				$(this).removeClass("active");
			});
			
			$(this).addClass("active");
			
			$.ajax({
				url: $.httpbase()+'bestel/ajaxsetbetaalmethode/',
				data: 'betaalmethode=' + $("input[type=hidden]",this).val(),
				dataType: 'html',
				success: function(r) {					
					$('#betaalmethode').html(r);
				}
			});
    	});
    	
    	if( $(this).hasClass("active")){
    		$.ajax({
				url: $.httpbase()+'bestel/ajaxsetbetaalmethode/',
				data: 'betaalmethode=' + $("input[type=hidden]",this).val(),
				dataType: 'html',
				success: function(r) {					
					$('#betaalmethode').html(r);
				}
			});
    	}
    	
    });
	
	$.showErrors = function() {
		$.ajax({
			url: $.httpbase()+'bestel/ajaxshowerrors/',
			dataType: 'html',
			success: function(r) {			
			$.popup.show('Melding(en)',r); 			
			}
		});
	}
	
	/* Set top border to first row items */
	$('#shop .items .row:first').find('.item').css('border-top', '1px solid #E6E6E6');
	
	$('#shop .items .item').mousemove(function(e) {
		var x = ((e.pageX - $(this).offset().left) + 10);
		var y = ((e.pageY - $(this).offset().top) + 10);
		
		$('.sizes',this).css('left', x + 'px').css('top', y + 'px');		
	}).mouseover(function() {
		$('.sizes',this).show();
	}).mouseout(function(){
		$('.sizes',this).hide();
	});
		
	$('#shop select.refer').change(function() {		
		return document.location.href = $(this).val();
	});
	
	$('#shop .popular').hover(
		function() {
			$('#shop .popular.title').addClass('active');
			$('#shop .popular.item').addClass('active');
		},
		function() {
			$('#shop .popular.title').removeClass('active');
			$('#shop .popular.item').removeClass('active');
		}
	);

	/* prijs ophalen bij geselecteerde maat */	
	$('#detail .maten .maat').click(function() {	
		$("#detail .maten .maat input").removeAttr("checked");
		$('#detail .maten .maat').removeClass("is_active");

		$("input",this).attr('checked','checked');
		$(this).addClass("is_active");
		
		$.doPrijsRequest( $("input[name='artikel_id']").val() , $("input[name='maat']",this).val());
		return false;
	});	
	
	$pirobox = $().piroBox({
	      my_speed: 300, //animation speed
	      bg_alpha: 0.5, //background opacity
	      radius: 4, //caption rounded corner
	      scrollImage : false, // true == image follows the page _|_ false == image remains in the same open position
	                           // in some cases of very large images or long description could be useful.
	      slideShow : 'false', // true == slideshow on, false == slideshow off
	      slideSpeed : 3, //slideshow duration in seconds(3 to 6 Recommended)
	      pirobox_next : 'piro_next', // Nav buttons -> piro_next == inside piroBox , piro_next_out == outside piroBox
	      pirobox_prev : 'piro_prev', // Nav buttons -> piro_prev == inside piroBox , piro_prev_out == outside piroBox
	      close_all : '.piro_close,.piro_overlay' // add class .piro_overlay(with comma)if you want overlay click close piroBox
	});		
	
	/* kleine afbeeldingen vergroten naar large	*/
	$("#thumbs .thumb").each( function(i,thumb) {
		if(i==0) {
			$(thumb).addClass('active');
		}
		$(thumb).mouseover( function() {
			if(!$(thumb).hasClass("active")) {
				$("#thumbs .thumb").removeClass('active');
				$(thumb).addClass('active');										
			}
		});
	});
	
	$("#image").click( function() {				
		$("#detail .gallery a").eq($("#thumbs .thumb").index($("#thumbs .thumb.active"))).trigger('click');	
	});
		
	//SUPPORT
	var values = new Array();
	var inputs = $(":input");
	
	inputs.each(function(i,e) {
		values[i] = e.value;
		if($(e).hasClass("clear")) {
			$(e).focus(function() {			
				if(e.value == values[i]) {				
					e.value = '';
				}
			});
			$(e).blur(function() {
				if(e.value == '') {
					e.value = values[i];
				}
			});
		} else if($(e).hasClass("password")) {
			$(e).focus(function() {			
				if(e.value == values[i]) {				
					e.value = '';
					e.type = 'password';
				}		
			});
			$(e).blur(function() {
				if(e.value == '') {
					e.value = values[i];
					e.type = 'text';
				}				
			});
		}
	});
	
	//SELECTIE RECHTERMENU
	
	$(".selectbox .select").each(function() { 
		$(this).hide();
		$(this).css('background-color', '#ffffff');
		if ($(this).height() > 200) {
			$(".items.scrollable", this).css("height", 200);
		} else {
			$(".items.scrollable", this).css("height", $(this).height());
		}
		
	});
	
	
	$(".selectbox").click( function() {
			var selectbox = $(this);
			$('#wrapper').css("z-index","15");
			selectbox.find(".select").first().slideDown("normal");
			selectbox.addClass("active");
			
			elmTitel = selectbox.find(".titel").first();
			sTitel = elmTitel.html();
			elmTitel.html('');

			
			$('<input type="text" name="'+sTitel+'" value="'+sTitel+'"/>').appendTo(elmTitel);
			$('input', elmTitel).focus().select().keyup( {obj : selectbox}, 
				function(e){
					if (e.keyCode == 13) {
						document.location.href= e.data.obj.find(".items a:visible").eq(0).attr('href');
					} else {
						input = this;
							e.data.obj.find(".items a").each( function() {
							if ($(this).html().substr(0,input.value.length).toLowerCase() == input.value.toLowerCase() ) {
								$(this).show();
							} else {
								$(this).hide();
							}
						});
					}
				}
			);
						
			
			$(this).find(".items a").each( function() {
				$(this).click( {obj : selectbox}, function(e) {				
					e.data.obj.find(".titel").html($(this).html());	
					if ($(this).hasClass("no_click")) {
						$('#search_menu form').attr('action', $(this).attr("href"));							
						e.preventDefault();
					}				
									
				});
			});
			
										
			setTimeout(function() {$.hideSelectbox(selectbox); selectbox = null}, 50);			
	});
		
	$.hideSelectbox = function(obj) {		
		$("body").bind("click", function() {						
			obj.find(".select").slideUp("fast", function() {
				inputs = $('.titel input', obj);
				
				if(inputs.length > 0) {
					$('.titel', obj).html(inputs[0].name);
				}
				
				obj.removeClass("active");
				$("body").unbind("click");
				$('#wrapper').css("z-index","1");
				obj = null;
			});				
		});
	}
	
	$('input[name="q"]').focus(function() {
		if ($(this).val() == "ZOEK IN DE CATEGORIE") {
			$(this).val('');
		}
	});
	
	$('input[name="q"]').blur(function() {
		if ($(this).val() == "") {
			$(this).val('ZOEK IN DE CATEGORIE');
		}
	});
	

	jQuery.expr[':'].Contains = function(a,i,m){
	    return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;
	};

	$('#merken .titel input').change( function () {
		var filter = $(this).val();
		if (filter) {
			$('#merken .items ul').find(".checkbox").each( function() {
				input = $('#merken .titel input').val().toLowerCase();
				item_value = $(this).html().toLowerCase().replace(/^\s*/, "").replace(/\s*$/, "").substr(0, input.length);
	
				if ( item_value == input && !$(this).hasClass('.disabled')) {
					$(this).parent().show();
				}else{
					$(this).parent().hide();
				}
			});
		} else {
			$('#merken .items ul').find("li").show();
		}
		
	}).keyup(function() {
		$(this).change();
	});

	if ($.browser.msie && $.browser.version.substr(0,1) < 7) {
		// jScrollPane plugin doesn't work completely in IE6 (autoReinitialise:true => keeps expanding)
	} else {
		$('#wrapper').ready(function(){
			$('#wrapper').pngFix();
			$('.scrollPane').jScrollPane();
			$('.scrollable').jScrollPane(
				{
					autoReinitialise: true,
					horizontalGutter: 10,
					verticalGutter: 10
				}
			);
		});
	}

	$('#login_wachtwoord').hide();
	
	$('.clear').each( function() {
		value = $(this).val();		
		$(this).focus( function() {
			if($(this).val() == value) {
				$(this).attr("value","");
			}
		});
		$(this).blur( function() {
			if($(this).val() == "") {
				$(this).attr("value",value);
			}
		});
	});
	
	$('.tooltip').each(function(i,tt) {
		$('.tt',tt).css('left',12 + 20);
		$('.tt_img',tt).hover(
			function(){				
				$('.tt',tt).show();
				$(tt).css("z-index",1000);
			},
			function(){
				$('.tt',tt).hide();
				$(tt).css("z-index",1);
			}
		);
	});
	
	$('#login_tekst').focus( function(){
		if (this.value.toLowerCase() == 'wachtwoord' || this.value.toLowerCase() == 'passwort'){
			$('#login_wachtwoord').show();
			$('#login_wachtwoord').focus();
			$('#login_tekst').hide();
		}
	});
	
	$('#login_wachtwoord').blur( function(){
		if ((this).value == ''){
			$('#login_tekst').show();
			$('#login_wachtwoord').hide();
		}
	});	
		
	$('#detail .vorige_volgende .vorige').each( function(i, vorige) {
		$(document).keydown(function (e) {		
			if(e.keyCode == 37) {			
				$(location).attr('href',$('a',vorige).attr('href'));
			}
		});
	});
	
	$('#detail .vorige_volgende .volgende').each( function(i, volgende) {
		$(document).keydown(function (e) {					
			if(e.keyCode == 39) {			
				$(location).attr('href',$('a',volgende).attr('href'));
			}
		});
	});
	
	$('#shops .vacatures li a').hover(
		function() {
			$(this).find('img').attr('src', staticbase + "img/icons/arrow_hover_bg.png");			
		},
		function() {
			$(this).find('img').attr('src', staticbase + "img/icons/arrow_bg.png");
		});
	
	$.omodaChat = function() {
		window.open("http://app.helponclick.com/help?lang=en&a=4ddf93769fdc417080dc2acfb86aab83","hoc_chat_login","width=720,height=550,scrollbars=no,status=0,toolbar=no,location=no,resizable=no");
	}
	
	$('#nieuwsbrief button').click( function(){		
		$.ajax({
			url: $.httpbase()+'home/ajaxaddnieuwsbrief/',
			data: 'nb_email=' + $('#nieuwsbrief input[name="nb_email"]').val(),
			dataType: 'html',
			success: function(r) {							
				$('#nieuwsbrief').html(r);
			}
		});
	});
	
	$.Switch = function() {		
		$(".switch").each( function(i, e) {			    
		    
		    var $active = $(e).find('TABLE.active');
			
		    if ( $active.length == 0 ) $active = $(e).find('TABLE:last');
		
		    var $next =  $active.next().length ? $active.next() : $(e).find('TABLE:first');
				
		    $active.addClass('last-active');
		
		    $next.css({opacity: 0.0})
		        .addClass('active')
		        .animate({opacity: 1.0}, 1000, function() {
		            $active.removeClass('active last-active');
		    });	   		    
		});
	}
    setInterval( "$.Switch()", 5000 );

    $(".faq").each( function(i, e) {
    	$(e).find(".antwoord").hide();
    	$(e).find(".vraag").click( function() {
    		$(".faq").each( function() {
    			$(this).find(".antwoord").hide();
    		});    		
    		$(e).find(".antwoord").show();
    	});
    });
    
	$.loadFaq = function(faq) {
		$.ajax({
			url: $.httpbase()+'contact/ajaxfaq/',	
			data: 'faq=' + faq,
			dataType: 'json',
			success: function(r) {			
				$.popup.show(r["vraag"], "<div style='width: 600px'>"+r["antwoord"]+"</div>");				
			}
		});		
		
	}
	
	$.loadPopup = function(code) {
		$.ajax({
			url: $.httpbase()+'cm/ajaxpopup/',	
			data: 'code=' + code,
			dataType: 'json',
			success: function(r) {					
				$.popup.show(r["titel"], r["content"]);					

				$("#popup a").each(function() {
					$(this).attr("href",$.httpbase().replace("https","http")+$(this).attr("href").replace($.httpbase(),""));
				});
				if($("#popup").height() > $(window).height()) {
					$("#popup_message").height((($("#popup").height()-($("#popup").height()-$(window).height()))-100)+'px');
					$("#popup_message").addClass('scroll');					
					$("#popup").css('top',(($(window).height()-$("#popup").height()) / 2)+'px');
				}							
			}
		});	
	}		
	
	var curdate = new Date();
	
	$.datepicker.setDefaults({
		   showOn: 'both',
		   buttonImageOnly: true,
		   buttonImage: staticbase + 'img/icons/kalender.gif',
		   buttonText: 'Calendar',
		   dayNames : ['zondag','maandag','dinsdag','woensdag','donderdag','vrijdag','zaterdag'],
		   dayNamesMin : ['zo','ma','di','wo','do','vr','za'],
		   dayNamesShort : ['zon','maa','din','woe','don','vri','zat'],
		   monthNames : ['januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'],		   
		   monthNamesShort : ['jan','feb','mrt','apr','mei','jun','jul','aug','sept','okt','nov','dec'],
		   nextText : 'volgende',
		   numberOfMonths: 1,
		   prevText : 'vorige',
		   changeMonth: true,
		   changeYear: true,
		   yearRange: curdate.getFullYear()-100 + ':' + curdate.getFullYear(),		   
		   dateFormat: 'dd-mm-yy'
	});
	
	$(document).ready(function(){
		$("input.date").each( function() {
			if($(this).val()) {
				$("input.date").datepicker({ defaultDate: $(this).val() });
			} else {
				$("input.date").datepicker({ defaultDate: '-20y' });
			}
		});	
		if($('#criteria').find('a').length == 0) {
			$('#criteria').hide();
		}
		$('#thumbs .gallery a:first').addClass("active");
	});		
	
	$.SwitchItem = function(e) {						    		 
	    var $active = $(e).find('.item.active');
		
	    if ( $active.length == 0 ) $active = $(e).find('.item:last');
	    	
	    var $next =  $active.next('.item').length ? $active.next('.item') : $(e).find('.item:first');
			
	    $active.addClass('last-active');
	
	    $next.css({opacity: 0.0})
	        .addClass('active')
	        .animate({opacity: 1.0}, 1000, function() {
	            $active.removeClass('active last-active');
	    });	   		    	
	}
    setInterval( "$.SwitchItem('.switchitem')", 3500 );

    if($('.collectie_nieuw .menu li').length > 1) {
    	$('.collectie_nieuw .menu li').eq(0).addClass('active');
    	setInterval('$.switchTrend()', 5000 );
    };
    
    $.switchTrend = function() {

    	$('.collectie_nieuw .menu li').each(function(i,e) {
    		
    		if ($(e).hasClass('active')) {
    			active = i;
    			next = $('.collectie_nieuw .menu li').eq(active).next('li').attr('id');
    		}
    		$(e).removeClass('active');
    	});
    	
    	if (active == ($('.collectie_nieuw .menu li').length - 1)) {
			active = 0;
			next = $('.collectie_nieuw .menu li').eq(active).attr('id');
		}
    	
    	$('#' +next).addClass('active');
    	    	
    	$('.collectie_nieuw .trend_items').each(function(i,e) {
    		$(this).addClass('hidden');
    	});
    	$('.collectie_nieuw .' +next).css({opacity: 0.0}).removeClass('hidden').animate({opacity: 1.0}, 1250);

    }
	$('.fade').cycle({fx: 'fade', speed: 1250});
	
	/*******************************************
	 * Blog functions.
	 ******************************************/
	
	// Load the blog comments.
	$('.blog-blok .blog-comments-outer').hide();
	$('.blog-comments-inner').each(function() {
		var blog_id = $(this).attr('id');
		id = blog_id.replace('blog-', '');
		$.ajax({
			'url': 'blog/ajax-comments',
			'data': {'blog_id': id},
			'success': function(data) {
				$('#'+blog_id).html(data);
			}
		});
		
	});
	
	// Bind pager clicks.
	$('.blog-comments-inner').on('click', '.blog-comments-content .paginator a', function(e) {
		// Stop default event. 
		e.preventDefault();
		
		// Retrieve the blog id and page number
		var blog_id = $(this).parents('.blog-comments-inner').attr('id');
		id = blog_id.replace('blog-', '');
		var page_id = $(this).text();
		
		
		if (page_id == '') {
			page_id = $(this).siblings('span').text()*1;

			if ($(this).hasClass('next') ) {
				page_id++;
			} else {
				page_id--;
			}
		}
		page_id =  (page_id > 0) ? page_id : 1 ;
	

		// Retrieve the comments
		$.ajax({
			'url': 'blog/ajax-comments',
			'data': {'blog_id': id, 'page': page_id},
			'beforeSend': function () {
				$('#'+blog_id + ' .blog-comments-content').empty().append('<div class="spinner"></div>');
			},
			'success': function(data) {
				$('#'+blog_id).html(data);
			}
		});
		return false;
	});	
});

jQuery.smsMobielRequired = function(cb) {
	if($(cb).length > 0 && $(cb).get(0).checked) {
		$('td#td_fld_mobiel').addClass('verplicht');
	} else {
		$('td#td_fld_mobiel').removeClass('verplicht');
	}
}

jQuery.copyAfleveradres = function( form ){
	if( form["afleveradres"][0].checked ){
		$('#afleveradres').hide();
		form["afleveradres_straat"].value  = form["factuuradres_straat"].value;
		form["afleveradres_huisnummer"].value  = form["factuuradres_huisnummer"].value;
		form["afleveradres_huisnummer_tv"].value  = form["factuuradres_huisnummer_tv"].value;
		form["afleveradres_postcode"].value  = form["factuuradres_postcode"].value;
		form["afleveradres_plaats"].value  = form["factuuradres_plaats"].value;
		form["afleveradres_land"].value  = form["factuuradres_land"].value;
	} else {
		$('#afleveradres').show();
	}
}

jQuery.doPrijsRequest = function( artikel_id, maat ) {
	$.ajax({
		url: $.httpbase()+'shop/ajaxgetprice/',
		data: 'artikel_id=' + artikel_id + '&maat=' + maat,
		dataType: 'html',
		success: function(r) {
			$('#detail .prijs').html(r);
		}
	});	
};

jQuery.showFlipBook = function() {
	$.popup.show('OMODA Style Guide #2','<div id="flipbook"></div>');
	$('#flipbook').media({
		width:1000,
		height:646,
		src:'flippingBook.swf',
		autoplay:true,
		flashvars:{
			xmlConfig: $.httpbase()+'home/flipbook/'			
		}
	});
	
	$.ajax({
		url: $.httpbase()+'home/flipbook/',
		dataType: 'html',
		success: function(r) {			
			xmlData = r;
			
		}
	});	
}

$.initReview = function(e,controller) {
	
	$('.sterren.selectable img',e).each(function(i,ster) {
		if ( i+1 <= $('input[name="beoordeling"]').val()) {
			$(ster).attr('src',$(ster).attr('src').replace('_inactive','_active'));
		} else {				
			$(ster).attr('src',$(ster).attr('src').replace('_active','_inactive'));
		}
		
		$(ster).mouseover(function() {
			$(this).attr('src',$(this).attr('src').replace('_inactive','_active'));
			$(this).prevAll('img').attr('src',$(this).attr('src').replace('_inactive','_active'));
			$(this).nextAll('img').attr('src',$(this).attr('src').replace('_active','_inactive'));
		});
		$(ster).mouseout(function() {
			if($("input[name='beoordeling']",e).val()>1) {				
				$('.sterren.selectable img',e).each(function(j) {
					if(j+1<=$("input[name='beoordeling']",e).val()) {
						$(this).attr('src',$(this).attr('src').replace('_inactive','_active'));
					} else {
						$(this).attr('src',$(this).attr('src').replace('_active','_inactive'));
					}
				});
			} else {
				$('.sterren.selectable img',e).attr('src',$(this).attr('src').replace('_active','_inactive'));
			}			
		});
		$(ster).click(function() {			
			$("input[name='beoordeling']",e).val(i+1);
		});
		
	});

	$('form[name="review"]',e).submit(function() {	
		$.ajax({
			url: $.httpbase()+controller+'/ajaxaddreview',	
			type: 'POST',
			data: $(this).serialize(),
			dataType: 'html',
			success: function(r) {			
				$(e).html(r);
				$.initReview(e,controller);
			}
		});
		return false;
	});
	
}


function saveEmail() {
	$.ajax({
		url: $.httpbase()+'nieuws/nieuwsbriefinschrijven/',
		data: 'nb_email=' + $('#nb_email').val(),
		dataType: 'html',
		success: function(r) {
			$.popup.show('',r);
		}
	});
	return false;
}
