$(function() {
	//ALGEMEEN
	jQuery.httpbase = function( ){
		return $('base')[0].href;
	}
	
	
	$(".clickable").click( function() {		
		document.location.href=$('a:eq(0)',this).attr('href');
		return false;
	});
	
	// Beoordelingen
	$('div.sterren.selectable img').mouseover(function() {
		for (i=1; i<=parseInt(this.id.substring(5,6)); i++) {
			$('img#'+this.id.replace(this.id.substring(4,7),'_'+i+'_')).each(function() {
				this.src = this.src.replace('_inactive','_active');
			});
		}
		while (i<=5) {
			$('img#'+this.id.replace(this.id.substring(4,7),'_'+i+'_')).each(function() {
				this.src = this.src.replace('_active','_inactive');
			});
			i++;
		}
	});

	$('div.sterren.selectable img').mouseout(function() {
		$(this.parentNode).find('img').each(function() {
			if (parseInt(this.id.substring(5,6))<=parseInt($('input#score'+this.id.substring(6)).attr('value'))) {
				this.src = this.src.replace('_inactive','_active');
			} else {				
				this.src = this.src.replace('_active','_inactive');
			}
		});
	});
	
	$('div.sterren.selectable img').click(function() {
		$('input#score'+this.id.substring(6)).attr('value',this.id.substring(5,6));
	});
	
	$('.sortable').sortable({helper:'clone',containment:'document'});
	$(".sortable").disableSelection();
	
	$("input#sms_label").change(function() {
		jQuery.smsMobielRequired(this);
	});
	
	$('input: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);
					}
				});
			}
			
		});
	}); 

	$('#creditcardForm :button').click(function(){				
		$.getJSON($.httpbase()+"betaal/creditcardvalidate",$('#creditcardForm').serialize(),function( data ){
    		if (data['succes']){
    			$('#creditcardForm').submit();
    		}else{
    			$('#creditcardMeldingen').html(data['html']);
    		}
    	});		
	});
	
	$('#creditcardremindForm :button').click(function(){				
		$.getJSON($.httpbase()+"betaalreminder/creditcardvalidate",$('#creditcardremindForm').serialize(),function( data ){
    		if (data['succes']){
    			$('#creditcardremindForm').submit();
    		}else{
    			$('#creditcardMeldingen').html(data['html']);
    		}
    	});		
	});
	
	$("#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); 			
			}
		});
	}
	
	/* 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;
	});	
	
	$('#zoom').click(function() {
		$('#detail .merk').hide();
	});
	
	/* transparancy kleine afbeeldingen regelen */	
	$.setImagesTransparancy = function() {		
		$("#thumbs .thumb").each( function() {
			src1 = $(this).find('img')[0].src.replace('/75/','/270/').replace('/75/','/270/');
			src2 = $("#image img")[0].src;
			if (src1 != src2){
				$(this).animate({ 
	        	opacity: 0.4}, 200
	        	);
			}else{
				$(this).animate(
					{opacity: 1.0}, 
					200
	        	);
			}							
		});
	}
	$.setImagesTransparancy();	
	
	$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_out', // Nav buttons -> piro_next == inside piroBox , piro_next_out == outside piroBox
	      pirobox_prev : 'piro_prev_out', // 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) {
		$(this).click( function() {
			$(".gallery a").removeClass("active");				
			$(".gallery a").each(function(j) {
				if(i==j) {					
					$(this).addClass("active");
				}
			});		
			$("#image img")[0].src = $(this).find('img')[0].src.replace('/75/','/270/').replace('/75/','/270/');
			$.setImagesTransparancy();
		});
	});
	
	$(".imagepopup").click( function() {
		$(".gallery .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
	var $selectbox;
			
	$(".selectbox").each( function() {
		$(this).find(".select").hide();
		
		if($(this).find(".select").height() > 160) {
			$(this).find(".select .items").addClass("scroll");
		}
		
		$(this).click( function() {
			if(!$selectbox) {
				$selectbox = this;
				$('#wrapper').css("z-index","15");
				$(this).addClass("active");
				$(this).find(".select").slideDown("normal");
				
				$(this).find(".items a").each( function() {
					$(this).click( function() {
						$($selectbox).find(".titel").html($(this).html());					
					});
				});
											
				setTimeout("$.hideSelectbox()",50);
			}
		});
	});
	
	$.hideSelectbox = function(selectbox) {		
		$("body").bind("click", function() {						
			$($selectbox).find(".select").slideUp("fast", function() {				
				$($selectbox).removeClass("active");
				$("body").unbind("click");
				$('#wrapper').css("z-index","1");
				$selectbox = '';
			});				
		});
	}

	$('#wrapper').ready(function(){
		$('#wrapper').pngFix();
	});
	
	$('#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);
			}
		});
	});
	
	$('#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'));
			}
		});
	});
	
	$.omodaChat = function() {
		window.open("http://www.helponclick.com/livechat.php?usrname=omoda&usr_id=6050&dp_id=0&op_id=0&nickname=&s_url="+escape(top.window.document.URL),"chat_login","top="+((screen.height/2)-200)+",left="+((screen.width/2)-225)+",width=450,height=400,scrollbars=no,status=0,toolbar=no,location=no,resizable=no");
	}
	
	$.addNieuwsbrief =  function(form){		
		$.ajax({
			url: $.httpbase()+'nieuwsbrief/',
			data: 'nb_email=' + form["nb_email"].value,
			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");
	});		
	
	$.SwitchAanbieding = function(e) {						    		 
	    var $active = $(e).find('.item.active');
		
	    if ( $active.length == 0 ) $active = $(e).find('.item:last');
	    	
	    var $next =  $active.next().length ? $active.next() : $(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( "$.SwitchAanbieding('#aanbieding')", 3500 );

});

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) {
			$('#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;
			
		}
	});	
}

jQuery.fade = function(e) {
	
}