var addthis_config = {  services_compact: 'print,email,favorites' } // addthis configuratie
var $url = getBaseURL();  // base url

$(function()
{
	// referentie animatie starten
	if($("#referenties").exists()){ referenties(); }
	
	// inlogbalk bovenaan
	$(".btn-slide").inloggen();
	
	// popup vensters
	$('.popup').popup();
	
	// contactformulier
	$('.contact').contact();
	
	// FAQ venster
	$('.faqBtn').FAQ();
	
	// page specific functions
	if( page == "contact" ){  initialize(); } // google maps initiëren
	if( page == "bevestig" ){  levering(); bevestigButton(); } // levering berekenen of bevestiging controle
	
	// buttons
	$('.button').button();
	$(".printBtn").button({ icons: { primary: 'ui-icon-print' }}).click(function(){ window.print(); });
	$("#bestelItems a.orange").button({ icons: {  primary: 'ui-icon-cart' } });
	$("#bestellijst a.orange").button({ icons: {  primary: 'ui-icon-cart' } });
	$("#zoek").button();
	$(".del").button({ icons: {  primary: 'ui-icon-trash' }, text: false }).deleteItem();
	$(".toNxt").minimum();
	$(".toCat, .toNxt").button();
	
	$("#uploadVak").uploadify({
		'uploader'       : '/assets/swf/uploadify.swf',
		'script'         : '/uploads/uploads.php',
		'cancelImg'      : '/assets/img/site/cancel.png',
		'folder'         : '/uploads/files/',
		'queueID'        : 'fileQueue',
		'auto'           : true,
		'multi'          : true,
		'onComplete'	 : function(event, queueID, fileObj, response) 
							{ 
								$("<li/>").html(response).appendTo("#files ul");
								$.post("/upload/add-item/", { fileName: response } ); 
							}
	});
	
	$(".btn").button();
	
	$('#actieForm input[name=fuif]').changeOrganiseerFuif();
	
});


// bepaal leveringskost
function levering(){
	
	var totaal = eval($("#totaal").val());
	
	if(role != 2 && totaal > 100){
		 
		$("input[name='levering']").change(function(){
			
			if ($("input[name='levering']:checked").val() == '1'){
				
				var gewicht = eval($("#gewicht").val());
				
				if(gewicht > 30){
					
					$(".levering").html("&euro; 45,00");
					var btw = (totaal + 45) * 0.21;
					$("#btw").html("&euro; " + (btw.toFixed(2)).replace(".", ","));
					var allTotaal = totaal + btw + 45;
					$("#allTotaal").html("&euro; " + (allTotaal.toFixed(2)).replace(".", ","));
					$("#levKost").val("45");
				}else{
					$(".levering").html("&euro; 15,00");
					var btw = (totaal + 15) * 0.21;
					$("#btw").html("&euro; " + (btw.toFixed(2)).replace(".", ","));
					var allTotaal = totaal + btw + 15;
					$("#allTotaal").html("&euro; " + (allTotaal.toFixed(2)).replace(".", ","));
					$("#levKost").val("15");
				}
			}else{
				$(".levering").html("&euro; 0,00");
				var btw = (totaal) * 0.21;
				$("#btw").html("&euro; " + (btw.toFixed(2)).replace(".", ","));
				var allTotaal = totaal + btw;
				$("#allTotaal").html("&euro; " + (allTotaal.toFixed(2)).replace(".", ","));
				$("#levKost").val("0");
			}
		});
	}
} 


// navigatie
$(function()
{ 
    $("ul.subnav").parent().addClass("sub"); 
 
	$("ul.topnav li.sub").hover(function()
	{
		$(this).find('ul:first').css({visibility: "visible",display: "none"}).show(400);
	},function(){
		$(this).find('ul:first').css({visibility: "hidden"});
	});
});  


// animatie cataloog onderaan
$(function()
{ 
	var $overlayHeight = 130,
		$list = $("#cat ul"),
		$activeList = 1, 
		$total = 4, 
		$catHeight = $list.height(),
		$startPos = $catHeight - $overlayHeight,
		$factor = $startPos / $overlayHeight;
		
	$list.css({ 'top' : - $startPos / 2 });
		
	$("#cat").mouseover(function(e)
	{
		var y = e.pageY - 480;
		var newPos = -( y * $factor) + ($startPos / 2);
		
		$list.stop().animate({ 'top' : newPos  }, 100);
	});
	
	$('#catItems div:gt(2)').css({'display':'none' });
	//$('#catItems img, .itemImage').fixBroken();
	
	//var timer = setInterval( showItems, 4000);
	
	/*function showItems()
	{
		
		$total = $total - 1;
		if($total == 0) 
		{
			$activeList++;
			$total = 4;
			
			$.post($url + "/index/get-catlist", 
			{ 
				list: $activeList 
			},function(data){
				
				jQuery.each(data, function(field, value) 
				{
					html = "<a href='/cataloog/items/"+ value.NLkort +"/"+ value.artikel +"'>";
					html+= "<img src='"+$url+"/assets/prod/MOB/img/"+ value.artikel +"_"+ value.kleur + ".jpg' alt=''/>";
					html+= "<h4></h4>";
					html+= "<p></p>";
					html+= "</a>";
					$("<div/>").html(html).appendTo('#catItems');
					$("#cat ul li:eq("+ ($activeList - 2) +")").removeClass('activeItem');
					$("#cat ul li:eq("+ ($activeList - 1) +")").addClass('activeItem');
					
					$('#catItems img').fixBroken();
				});
				
			}, 'json');			
			
		}else{
			$('#catItems div:lt(3)').fadeOut("slow", function(){ $(this).remove(); $('#catItems div:lt(3)').show(); });
		}
	};*/
});


// banner indexpagina
$(function()
{ 
	var $active = 0,
		$width 	= 546,
		$links 	= $('#acties li'),
		$size	= $links.size(),
		$counter = 0;
	
	var $overlayHeight = 185,
		$list = $("#acties ul"),
		$catHeight = $list.height(),
		$startPos = $catHeight - $overlayHeight,
		$factor = $startPos / $overlayHeight;
	
	$("#banners").css({ 'width': $width * $size });
	
	$links//na banner, de andere banners laden
		.each(function(index) {	
		
			if(index != 0){
			
			}
		})
		.click(function()
		{
			$active = $links.index(this);
			$counter = 0;
			$("#banners").animate({ left: -( $active * $width ) });
			changeActief();
			
			return false;
		});	
	
	
	$list.css({ 'top' : - $startPos / 2 });
		
	$("#acties").mouseover(function(e)
	{
		var y = e.pageY - 40;
		var newPos = -( y * $factor) + ($startPos / 2);
		
		$list.stop().animate({ 'top' : newPos  }, 100);
	});
	
	$("#acties ul li").hover(function()
	{
		if(!$(this).hasClass('actieActive'))
		{
			$(this).addClass('Mover');
		}
	},function(){
		$(this).removeClass('Mover');
	});
	
	 var timer = setInterval( showDiv, 100);

	 function showDiv() 
	 {  
	 	$counter+=100;
		
		if($counter >= 4000)
		{
	 		$active = ($active < $size-1) ? $active+1 : 0;
	 		$("#banners").animate({ left: -( $active * $width)});
			
			$counter = 0;
			
			changeActief();
		}
	 }
	 
	 function changeActief()
	 {
		$("#acties ul li").removeClass('actieActive');
		$("#acties ul li:eq("+$active+")").addClass('actieActive');
	 }
});


// stel $url op: global parameter om de url te bepalen: localhost of op het web
function getBaseURL() {
    var url = location.href;
    var baseURL = url.substring(0, url.indexOf('/', 14));

    if (baseURL.indexOf('http://webserver') != -1) {
        
        var url = location.href;
        var pathname = location.pathname;
        var index1 = url.indexOf(pathname);
        var index2 = url.indexOf("/", index1 + 1);
        var baseLocalUrl = url.substr(0, index2);

        return baseLocalUrl + "/html";
    }
    else {
        return "";
    }
}


// bij contact: initialize google maps
function initialize() 
{
	  if (GBrowserIsCompatible()) 
	  {
		var map = new GMap2(document.getElementById("map_canvas"));
		map.setCenter(new GLatLng(51.016596266861065, 3.5816287994384766), 13);
		map.setUIToDefault();
		
		var point = new GLatLng(51.01625710526187, 3.5818031430244446);
		map.addOverlay(new GMarker(point));
	  }
}


// referenties: stel lijst op en start animatie
function referenties()
{
	var $list 		= $("#referenties ul li"),
		$total		= $list.size(),
		$active 	= 0,
		$refImage	= $('#refImage'),
		$start = true;
	
	$refImage.load(function()
	{
		if($start){ startRefAnimation($list, $active, $refImage, $total); $start = false; }
	});
}


// loop om de 3 sec een nieuwe animatie
function startRefAnimation($list, $active, $refImage, $total)
{
	$refImage.delay(3000).fadeOut('slow', function() 
	{  
		$active = ($active < $total) ? $active + 1 : 0;
		img = $list.eq($active).attr('title');
		$refImage.attr({'src': $url + '/assets/ref/'+img }).load(function()
		{
			$refImage.css({'margin-left': - $refImage.width() / 2 +'px','margin-top': - $refImage.height() / 2 +'px' });
		});
		$refImage.fadeIn('slow', function() 
		{  
			startRefAnimation($list, $active, $refImage, $total)
		});
	});
}

// knop bevestigen controleren of men aangeduid heeft van te leveren en betaalwijze
function bevestigButton()
{
	$("#bevestig")	.button({ icons: {  primary: 'ui-icon-check' } })
					.click(function(){ 
						if(!$("input[name='levering']:checked").val()){
							alert("Gelieve aan te duiden of de goederen moeten geleverd worden of u ze komt afhalen.");
							return false;
						}
						
						if(!$("input[name='betaling']:checked").val()){
							alert("Gelieve aan te duiden of u de goederen cash betaald bij levering of vooraf via overschrijving.");
							return false;
						}
						
			});
	$(".aanpassen").button({ icons: {  primary: 'ui-icon-pencil' } });
}


// popup contactformulier
$.fn.contact = function()
{ 
	this.click(function()
	{
		var onderwerp = $(this).attr('title'),
			dialog 	  = $("<div/>").attr({ 'id': 'dialog-contact', 'title': onderwerp })
								   .html('<ul id="validateTips"></ul>')
								   .appendTo('body')
								   .dialog({ bgiframe: true, height: 450, width: 310, modal: true }),
			tips 	  = $("#dialog-contact #validateTips");
		
			
		// opmerking geven indien velden niet of niet juist zijn ingevuld				   
		function updateTips(t) {
			
			tips.children('li').remove();
			$("<li>").html(t).appendTo(tips);
		}
		
		
		// contactformulier ophalen 
		$.get($url+'/contact/get-form', function(data) {
			
		  	$(dialog).append(data)

					 .dialog( "option", "buttons", { 
					 
					 	'Annuleer': function() {
							
								$(this).dialog('close');
						},
							
					 	'Zend': function() {
									
								var allReqField = $(this).find('label').not('.optional').parent().next().find('input'),
									tipsObject 	= new Object(), 
									valid 		= true;
									
									// indien er op een veld geklikt wordt, toon de opmerking als er 1 is
									$('#dialog-contact input, #dialog-contact textarea').removeClass('ui-state-error').click(function() {
										
										var f = $(this).attr('id');
										
										jQuery.each(tipsObject, function(tip) {
											
											updateTips(tipsObject[f][tip]);
											
										});
										
									});
									
									// controleren of verplichte velden zijn ingevuld
									allReqField.each(function()	{ 
									
										if($(this).val() == "") {
											
											$(this).addClass('ui-state-error');
											valid = false; 
											updateTips('Gelieve de aangeduidde velden in te vullen:');
										}
									}); 
									
									// als alle verplichte velden zijn ingevuld, controleren op server 
									if(valid)
									{
										$.post($url + "/contact/info-zend", $('#contactInfo').serialize(),
										
										function(data){
											//door fouten loopen en velden aanduiden
											if(data != true){
												tipsObject = data;
							
												jQuery.each(tipsObject, function(field) {
													$('#'+ field).addClass('ui-state-error');
												});
											}else{
												$("#dialog-contact").html('<p><b>Wij hebben uw vraag goed ontvangen.</b></p><p>Wij zullen u zo spoedig mogelijk contacteren.</p>');
												var options = { buttons: {'Sluit': function() {  $("#dialog-contact").dialog('close');  } } };
												$("#dialog-contact").dialog('option', options);
											}
										});
									}
							},
							
					 })
					 //bericht textarea leeg maken
					.find('textarea').emptyField();
					
					// onderwerp auto. invullen
					$('#onderwerp').val(onderwerp);
		});
		
		
		return false; 
	})
}





// functie: veld leegmaken
$.fn.emptyField = function()
{
	return this.focus(function()
	{
		if($(this).val() == 'Indien u wenst kan u hier extra informatie vermelden.'){
		
			$(this).val("");
		}
	});
}
		

// functie: open schuiven van bovenste balk om in te loggen
$.fn.inloggen = function()
{
	return this.click(function()
	{
		$("#panel").slideToggle("slow");
		$(this).toggleClass("active"); 
		return false;
	}); 
}


// functie: alle elementen met popup class openen popup met waarden in rel.
$.fn.popup = function()
{
	this.click(function()
	{
		var dim 	= ($(this).attr('rel')).split("-"),
			width 	= dim[0],
			height	= dim[1],
			url 	= $(this).attr('href');

			window.open(url,'popup', 'width=' + width + ', height=' + height + ',scrollbars=no,toolbar=no,location=no'); 
			
		return false;
	});
}


//functie: maak faq-dialog en append to body, daarna haal vragen op
$.fn.FAQ = function()
{
	this.click(function()
	{
		$("<div/>").attr({ 'id': 'dialog-faq', 'title': 'F.A.Q.' })
				   .html('<p>Hieronder vindt u een lijst van frequente gestelde vragen. Misschien biedt 1 er van al een antwoord op uw vraag.</p><p>U mag ons ook altijd contacteren via mail of telefonisch op 09 282 84 38.</p>')
				   .appendTo('body')
				   .dialog({ bgiframe: true, height: 500, width: 350, modal: true, buttons: { Sluit: function() { $( this ).remove(); } } });
				   
		getVragen();
		
		return false;
	});
}
	
	
//functie: haal vragen op van server
function getVragen()	
{
	$.getJSON($url + "/faq/get-vragen", { },
	function(data)
	{
		$("#dialog-faq h3, #dialog-faq #antwoord, #dialog-faq #nuttigP").remove();
		
		var ul =  $("<ul/>").attr({"id" : "faqVragen" });
		$.each(data, function(key, value) 
		{
			li = $("<li/>");
			$("<a/>").attr({ 'title': key, 'href': '#' }).html(value).appendTo(li).getAntwoord();
			li.appendTo(ul);
		});
		ul.appendTo("#dialog-faq");
	});
}


//functie: haal antwoord op van server en voeg antwoord toe
$.fn.getAntwoord = function()
{
	return this.click(function()
	{
		$("#faqVragen").remove();
		
		var id 		= $(this).attr('title');
		var vraag 	= $(this).html();
		
		$.post( $url+ "/faq/get-antwoord", { id: id },
		function(data)
		{
			$("#dialog-faq").append( "<div id='antwoord'><h3>"+ vraag + "</h3><p>"+ data +"</p></div>");
						
			var nuttig = $("<p id='nuttigP'/>").html("<span class='ui-widget-header'>Was dit antwoord nuttig?</span>&nbsp;&nbsp;<input type='radio' name='nuttig' value='ja' checked='checked'/>ja&nbsp;&nbsp;<input type='radio' name='nuttig' value='nee'/>nee<br/><textarea id='faqOpmerking' style='width:100%;height:50px'>Voeg hier extra opmerking toe.</textarea><br/>");
			
			$("<input/>").attr({'type': 'submit', 'value': 'zend' })
						 .css({'float':'right'})
						 .click(function()
						 { 
						 	var opmerking = $('#faqOpmerking').html(),
								nuttig = $("input[name='nuttig']:checked").val(); 
								
						 	$.post($url + "/faq/send-opmerking", 
							{ 
								vraag: vraag, nuttig: nuttig, opmerking:opmerking, res: false 
							},
							function(data)
							{
								$("#nuttigP").html("Bedankt voor uw opmerking!");
							});	   
						 })
						 .appendTo(nuttig);
						 
			nuttig.appendTo("#dialog-faq");
			
			$("<span/>").html("Terug naar de vragen")
						.css({ 'cursor':'pointer', 'font-weight':'bold'})
						.addClass('blue')
						.click(function()
						{ 
							$(this).remove();
							getVragen();
						})
						.appendTo("#dialog-faq");
		});
		
		return false; 	
	})
}
		

//functie: kijkt of element bestaat
$.fn.exists = function(){return $(this).length>0;}


//vervang niet gevonden images door witte jpg
$.fn.fixBroken = function(){
	
	return this.each(function()
	{
		var tag = $(this),
		 	alt_img = '/assets/prod/off.jpg';
		
		tag.error(function() { 
			tag.attr("src", alt_img).addClass('off'); 
			return true;
		});
	});
};


// bij bestellijst, item verwijderen
$.fn.deleteItem = function(){

	return this.click(function(){
	
		var id 	= $(this).parent().parent().attr('id'),
			div	= $('<div/>').attr({ id: "dialog-delete", title: "Artikel verwijderen" })
						   	 .html('Bent u zeker dat u dit artikel uit de lijst wilt verwijderen?')
						   	 .appendTo('body')
						   	 .dialog({
								bgiframe: true,
								height: 150,
								width: 220,
								modal: true,
								buttons: {
									'verwijderen': function() 
									{
										window.location = $url+'/bestellijst/delete/id/' + id;
									},
									Cancel: function() 
									{
										$(this).dialog('close');
									}
								}
						   });
		return false; 
	});
}	


// bij bestellijst controle minimum 100
$.fn.minimum = function(){
	
	return this.click(function(){
		
		if(eval($("#totaal").val()) < 100 && role != 2){
			
			var div = $('<div/>').attr({ id: "dialog-minimum", title: "Opmerking" })
								 .html('<p>Het minimum aankoop bedrag moet &euro; 100 excl. bedragen.</p><a href="'+$url+'/cataloog">Naar de cataloog</a>')	
								 .appendTo('body')
								 .dialog({
									bgiframe: true,
									height: 150,
									width: 350,
									modal: true,
									buttons: {
										Sluit: function() {
											$(this).dialog('close');
										}
									}
								})
			return false;
		}
	});
}

$.fn.changeOrganiseerFuif = function() {
	
	return this.click(function() {
		
		var val = parseInt($(this).val());
		
			if (val) {
				$('#actieForm .polsbandshop').show();
			} else {
				$('#actieForm .polsbandshop').hide();
			}
		
	});
	
}
