// JavaScript Document
var $url = getBaseURL();

$(function()
{
	
	$(".button").button();	
	
	$(".print").print();	
	
	$('.contact').contact();
	
	$(".bereken").berekenPrijs();
	
	$("input[name=levering]").levering();
	
	$("input[name=leverdatum]").datepicker({
		minDate: $("input[name=leverdatum]").attr('alt'),
		dateFormat: 'dd/mm/yy',
		beforeShowDay: $.datepicker.noWeekends
	});
	
	// levering overzicht
	$('select[name=leveringOverzicht]').change(function(e) {
	
		var prijs = $(this).val();
		
		$.post($url + '/bevestig/change-verzending', { verzending : prijs, totPrijs : $('.subtotaalPrijs').html().replace(',','.').replace(' ', '') }, function(data) {
			
			$('.levering').html('&euro; ' + data.leveringPrijs);
			$('.totaalPrijs').html(data.totaalPrijs);
			$('.btw').html('&euro; ' + data.btw);
			
		}, 'json')
			
		
	});
	
	$('.tabs').tabs();
	
	// bij overzicht bestelling 
	$(".bekijk").button({ icons: { primary: "ui-icon-zoomin" }, text: false }).bekijk();
	$(".delete").button({ icons: { primary: "ui-icon-trash" }, text: false }).deleteBandje();
	
	if(action == 'contact'){ initialize() }
	
	$('.faqBtn').click(function(){ $("#dialog-faq").dialog('open'); return false; });
	
	$("#bevestig").button({ icons: { primary: 'ui-icon-check' } }).checkBevestig();
	
	$("#dialog-faq a, .faqvraag").faqAntwoord();
	
	$(".opmerking").button({ icons: { primary: "ui-icon-help" }, text: false }).opmerking();
	
	$("#overschrijving").overschrijving();
	
	$('#mogelijkheden').getFaqVraag();

	$("#dialog-opmerking").dialog(
	{
		bgiframe: true,
		autoOpen: false,
		height: 200,
		width: 250,
		position: [650, 150],
		modal: true,
		buttons: {
			'Sluit': function() 
			{
				$(this).dialog('close');
			}
		}
	});
	
	$("#dialog-faq").dialog(
	{
		bgiframe: true,
		autoOpen: false,
		height: 400,
		width: 500,
		modal: true,
		buttons: {
			'Sluit': function() 
			{
				$(this).dialog('close');
			}
		}
	});
	
	$("#dialog-contact").dialog(
	{
		bgiframe: true,
		autoOpen: false,
		height: 450,
		width: 310,
		modal: true,
		buttons: {
			'Zend': function() 
			{
				var naam = $("#naam"),
					bedrijf = $("#bedrijf"),
					straat = $("#straat"),
					postcode = $("#postcode"),
					gemeente = $("#gemeente"),
					email = $("#email"),
					onderwerp = $("#onderwerp"),
					telefoon = $("#telefoon"),
					bericht = $("#bericht"),
					
					allFields = $([]).add(naam).add(email).add(telefoon),
					tipsObject = new Object(), 
					tips = $("#dialog-contact #validateTips"),
					
					valid = true;
					
				function updateTips(t)//opmerking geven  
				{
					tips.children('li').remove();
					$("<li>").html(t).appendTo(tips);
				}		
					
				$('#dialog-contact input, #dialog-contact textarea').removeClass('ui-state-error').click(function()//indien er op een veld geklikt wordt, toon de opmerking als er 1 is
				{
					var f = $(this).attr('id');
					
					jQuery.each(tipsObject[f], function(tip) 
					{
						updateTips(tipsObject[f][tip]);
					});
				});
				
				allFields.each(function()
				{ 
					if($(this).val() == "")
					{
						$(this).addClass('ui-state-error');
						valid = false; 
						updateTips('Gelieve de aangeduidde velden in te vullen:');
					}
				}); 
				
				if(valid)
				{
					$.post($url+"/contact/info-zend", 
					{ 
						naam: naam.val(), bedrijf: bedrijf.val(), straat: straat.val(), postcode: postcode.val(), gemeente: gemeente.val(), email: email.val(), 
						onderwerp: onderwerp.val(), telefoon: telefoon.val(), bericht: bericht.val()
					},
					function(data)
					{
						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);
						}
					});
				}
			},
				
			'Annuleer': function() 
			{
				$(this).dialog('close');
			}
		}
	});
});

$.fn.maakDatePicker = function() {
	
	$(this).datepicker();

	return this.click(function(e) {
	
		$.get($url + '/bevestig/get-levertermijn', { type : 'stof' }, function(data) {
		
			$( this ).datepicker( "option", "minDate", data.termijn );
		
		}, 'json')
	
	
	});
	
}


$.fn.opmerking = function()
{
	return this.click(function()
	{
		var opmerking = $(this).attr('title');
		
		alert(opmerking);
	});
}


$.fn.checkBevestig = function()
{
	this.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;
		}*/
		
	})
}


$.fn.overschrijving = function() {

	return this.click(function() {
		
		$("#betalingDiv").slideDown();
	})
	
}


$.fn.bekijk = function()
{
	return this.click(function()
	{
		var id = $(this).attr('rel');
			
		$("#dialog-opmerking").dialog( "option", "height", 280 );
		$("#dialog-opmerking").dialog( "option", "width", 630 );
		$("#dialog-opmerking").dialog( "option", "position", 'center' );
		
		$.getJSON($url + "/bevestig/get-bandje", 
		   { id: id },
		function(data)
		{
			switch(data.type)
			{
				case "tyvek":
					var html = "<div id='tyvek' class='rounded'>";
						html+= "<div id='kleurvlak'>";
						
						if(data.opdrukImage == "geen"){ 
						html+= "<div id='pict1' class='pict' ";
						if(data.pict1 != "geen"){ html+= "style='background-image: url("+$url+"/pict/"+ data.pict1 +".png);'"; }else
						if(data.opdrukLogo != "geen"){ html+= "style='background-image: url("+$url+"/uploads/logo/preview/"+ data.opdrukLogo +");'"; }
						html+= "></div>";
						}
						html+= "<div id='tekst' ";
						if(data.opdrukImage != "geen"){ 
							html+= "style='background-image: url("+$url+"/uploads/ontwerp/preview/"+ data.opdrukImage +");width: 400px;border: none;margin-left:15px;'"; 
						}
						html+= ">";
						if(data.opdrukImage == "geen"){ 
						html+= "<div id='lijn1'>"+ data.tekst1 +"</div>";
						html+= "<div id='lijn2'>"+ data.tekst2 +"</div>";
						}
						html+= "</div>";
						
						html+= "<div id='pict2' class='pict' ";
						if(data.sponsoring == "1"){ 
							if(data.opdrukImage != "geen"){ 
								html+= "style='background: url("+$url+"/img/sponsor.png) no-repeat left center; width: 50px;float:right;'"; 
							} else {
								html+= "style='background-image: url("+$url+"/img/sponsor.png); width: 137px;'"; 
							}
						} else if(data.pict2 != "geen"){ 
							html+= "style='background-image: url("+$url+"/pict/"+ data.pict2 +".png);'"; 
						}
						html+= "></div>";
						html+= "</div>";
						html+= "<div id='previewKleuren'><span class='titelPR'>Preview:</span> </div></div>";
					break;
				
				case "vinyl":
					var html = "<div id='vinyl' class='rounded' >";
						html+= "<div id='kleurvlak'>";
						if(data.sponsoring == "1"){ 
							html+= "<div id='tekst' style='background: url("+$url+"/img/sponsor_vinyl.png) no-repeat center right'>";
						} else {
							html+= "<div id='tekst'>";
						}
						if(data.opdrukLogo != "geen") { 
							html+= "<div id='lijn1' style='background-image: url("+$url+"/uploads/logo/preview/"+ data.opdrukLogo +"); width: 147px; height: 62px;'></div>";
						}else{  
							html+= "<div id='lijn1'>"+ data.tekst1 +"</div>";
							html+= "<div id='lijn2'>"+ data.tekst2 +"</div>";
						}
						html+= "</div>";
						html+= "<img src='"+$url+"/img/vinyl.png'>";
						html+= "</div>";
						html+= "<div id='previewKleuren'><span class='titelPR'>Preview:</span> </div></div>";
					break;
					
				case "stof":
					var html = "<div id='stof' class='rounded'>";
						if (data.opdrukLogo != 'geen') {
							html+= "<div id='kleurvlak' style='background:"+ data.opdrukLogo+"'>";
						} else {
							html+= "<div id='kleurvlak' style='background:"+ data.kleurBandje+"'>";
						}
						
						if(data.sponsoring == "1"){ 
							html+= "<div id='tekst' style='background: url("+$url+"/img/sponsor_stof.png) no-repeat center right'>";
						} else {
							html+= "<div id='tekst'>";
						}
						
						html+= "<div id='lijn1' style='color:"+ data.kleurOpdruk+"'>"+ data.tekst1 +"</div></div></div></div>";
					break;
					
				case "silicone":
					var html = "<div id='silicone' class='rounded'>";
						html+= "<div id='kleurvlak' style='background:"+ data.kleurBandje+"'>";
						if(data.sponsoring == "1"){ 
							html+= "<div id='tekst' style='background: url("+$url+"/img/sponsor_stof.png) no-repeat center right'>";
						} else {
							html+= "<div id='tekst'>";
						}
						html+= "<div id='lijn1' style='color:"+ data.kleurOpdruk+"'>"+ data.tekst1 +"</div></div></div></div>";
					break;	
					
				case "munten":
					var pict1 = (data.bedrukt == "b" || data.bedrukt == "c") ? 'eigen.png' : data.opdrukLogo;
					if(data.bedrukt != "d"){
						
						var pict2 = (data.bedrukt == "a" || data.bedrukt == "c" || data.bedrukt == "e") ? 'eigen.png' : data.opdrukLogo;
					}else{
						var pict2 = 'geen.png';
					}
					var html = "<div id='center'>";
						html+= "<div id='munten' class='rounded'>";
						html+= "<div id='kleurvlak'>";
						html+= "<div id='pictMunt1'><img src='"+ $url +"/munt/"+ pict1 +"'/></div>";
						html+= "<div id='pictMunt2'><img src='"+ $url +"/munt/"+ pict2 +"'/></div>";		
						html+= "<img src='"+ $url +"/img/munt_"+ data.grootte +".png' class='muntImg'/>";
						html+= "<img src='"+ $url +"/img/munt_"+ data.grootte +".png' class='muntImg'/>";
						html+= "</div>";
						html+= "</div>";
						html+= "</div>";
						break;	
			}
			
			$("#dialog-opmerking").attr({ 'title': data.type }).html(html).dialog('open');
			
			$.each(data.opmaak1, function(index, value) { opmaak("#lijn1", index, value); });
			
			if(data.type != "stof" && data.type != "silicone")
			{
				$.each(data.opmaak2, function(index, value) { opmaak("#lijn2", index, value); });
			
				$.each(data.kleuren, function(index, value) 
				{
					$("<span/>").html(value.aantal).css({'background': '#'+value.code, 'width' : 'auto', 'padding':'1px 3px'}).appendTo("#previewKleuren").changeColor();
					
				});
			}
			
			$("#previewKleuren span:eq(1)").click();
		})
	})
}


$.fn.deleteBandje = function() {

	return this.click( function() {
		
		var id = $(this).attr('rel');
		
		$('<div/>').appendTo('body')
				   .html('Bent u zeker dat u dit item wilt verwijderen?')
				   .attr({ 'title': 'Item verwijderen'})
				   .dialog({ buttons: {
								'Annuleer': function() {
										$(this).dialog('close');
								},
								'Verwijder': function() {
									
									$.post($url+"/bevestig/delete-bandje", { id: id }, function(data) { location.reload(true ) });
								
									$(this).dialog('close');
								},
									
				   			}
					   
					   });
	});
}

$.fn.changeColor = function()
{
	return this.click(function()
	{
		var kleur = $(this).css('background');
		$("#kleurvlak").css({ 'background': kleur });
	
	});
};

function opmaak(field, index, value)
{
	switch(index)
	{
		case "font":
			$(field).css({ 'font-family': value });
			break;
				
		case "align":
			$(field).css({ 'text-align': value });
			break;	
		
		case "fontsize":
			$(field).css({ 'font-size': value+'px' });
			break;	
			
		case "hoogte":
			$(field).css({ 'margin-top': value-16+'px' });
			break;	
		
		case "bold":
			$(field).css({ 'font-weight': (value == '1') ? 'bold' : 'normal' });
			break;	
		
		case "italic":
			$(field).css({ 'font-style': (value == '1') ? 'italic' : 'normal' });
			break;	
		
		case "underline":
			$(field).css({ 'text-decoration': (value == '1') ? 'underline' : 'none' });
			break;	
	}	
}


$.fn.levering = function()
{
	return this.change(function()
	{
		var levering = ($('input[name=levering]:checked').val() == "0") ? false : true;
		var land = $('#land').html();
		var totaal = parseFloat($('#totaal').val());
								   
		if(levering)
		{
			if(land == "BE")
			{
				$(".levering").html("&euro; 10,00");
				var leveringskost = 10;
			}else{
				
				
				$(".levering").html("&euro; 18,00");
				var leveringskost = 18;
				
				
			}
		}else{
			$(".levering").html("&euro; 0,00");
			var leveringskost = 0;
		}
		
		$("#btw").html("&euro;" + ((totaal + leveringskost) * 0.21).toFixed(2)); 
		$("#allTotaal").html("&euro;" + ((totaal + leveringskost) * 1.21).toFixed(2)); 
		
		$("#levKost").val(leveringskost);
	});
}


$.fn.faqAntwoord = function()
{
	this.click(function()
	{
		if(!$("#dialog-faq").dialog("isOpen")) { $("#dialog-faq").dialog('open'); }
		
		var id = $(this).attr('rel'),
			vraag = $(this).html();
		
		$.post($url+"/faqantwoord", 
		   { id: id },
		function(data)
		{
			$("#faqContent").html("<h3>" + vraag + "</h3>" + data);
			var faqVragen = $("<a></a>").attr({ 'href': '#' }).html('Terug naar de vragen').appendTo('#faqContent');
			faqVragen.faqVragen();
		});
		
		return false; 
	})
}


$.fn.faqVragen = function()
{
	this.click(function()
	{
		$.getJSON($url+"/faqvragen", 
		   { },
		function(data)
		{
			var ul =  $("<ul/>");
			
			$("#faqContent").html("");
			
			$.each(data, function(key, value) 
			{
				li = $("<li/>");
				$("<a/>").attr({'rel' : key, 'href': '/faq/'+ key }).html(value).appendTo(li).faqAntwoord();
				li.appendTo(ul);
			});
			ul.appendTo('#faqContent');
		})
		
		return false; 
	})
}

$.fn.contact = function()
{
	this.click(function()
	{ 
		var onderwerp = $(this).attr('title');
		$("#dialog-contact #onderwerp").val(onderwerp);
		$("#dialog-contact").dialog('open');
		return false; 
	});
}

$.fn.print = function()
{
	this.click(function()
	{ 
		window.print();
		return false; 
	});
}

$.fn.berekenPrijs = function()
{
	this.click(function()
	{
		var aantal = parseInt($("input[name=aantal]").val()),
			type = $("input[name=type]").val(),
			druk = (type != "munten") ? $('input[name=druk]:checked').val() : $('select[name=druk]').val(),
			grootte = "",
			minTotaal = parseInt($("#minTotaal").html());
		
		if(aantal<minTotaal)
		{
		   	$("#dialog-opmerking").html("<p>Het minimum aantal per bestelling is " + minTotaal +" stuks.</p>");
			$("#dialog-opmerking").dialog('open');
		}else if(aantal%10 != 0)
		{
		   	$("#dialog-opmerking").html("<p>Het aantal moet een veelvoud zijn van 10.</p>");
			$("#dialog-opmerking").dialog('open');
		}else{
			switch(type)
			{
				case "tyvek":
					bedrukt = (druk == "1") ? "bedrukt" : "onbedrukt";
					break;
					
				case "vinyl":
					bedrukt = (druk == "1") ? "bedrukt" : "onbedrukt";
					break;
				
				case "stof":
					bedrukt = "bedrukt";
					druk = '1';
					break;
				
				case "silicone":
					bedrukt = (druk == "1") ? "relief" : "bedrukt";
					//druk = '1';
					break;
					
				case "munten":
					grootte = $('input[name=grootte]:checked').val() +"mm";
					bedrukt = grootte;
					break;
			}
			
			$.post($url+"/bestellen/get-prijs", 
			   { type: type, aantal: aantal, bedrukt: druk, grootte: grootte },
			function(data)
			{
				prijs = parseFloat(data);
				
				$('.omschrijving').html(aantal+" "+type+" "+bedrukt);
				$('.prijs').html("&euro; "+ prijs.toFixed(2));
				$('.btw').html("&euro; "+ (prijs * 0.21).toFixed(2));
				$('.totaal').html("&euro; "+ (prijs * 1.21).toFixed(2));
				
				var sponsoring = ($('input[name=sponsoring]:checked').val() == "1") ? true : false,
					korting = $("#sponsorbedrag").attr('title'),
					korting_type = $("#sponsorbedrag").attr('rel');
				
				if(druk == "1" || (type == 'silicone' && korting != 0)) {
					
					$('input[name=sponsoring]').removeAttr('disabled');
					
					if (korting_type == 'percent') {	
						$("#sponsorbedrag").html("<span class='belangrijk'>- &euro; "+ (prijs * korting * 1.21).toFixed(2) + "</span>");
						$(".totaalSponsoring").html("&euro; "+ (prijs * (1-korting) * 1.21).toFixed(2));
					} else if (korting_type == 'vast') {
						$("#sponsorbedrag").html("<span class='belangrijk'>- &euro; "+ (korting * 1.21).toFixed(2) + "</span>");
						$(".totaalSponsoring").html("&euro; "+ ((prijs - korting) * 1.21).toFixed(2));
					}
				
				
				} else {
					$("#sponsorbedrag").html("Enkel bij bedrukte bandjes");	
					$('input[name=sponsoring]').removeAttr('checked').attr({'disabled': 'disabled' });
				}
				
			});	   	
		}
	});
};

$.fn.getFaqVraag = function() {

	return this.click(function(e) {
	
		$.get($url + '/bestellen/get-faqvraag', { vraagID : '1' }, function(data) {
		
			var html = "<h2>" + data.vraag + "</h2>" + data.antwoord;
		
			$('<div />').attr({ title : 'Leveringstijden' })
						.appendTo('body')
						.html(html)
						.dialog({
						
							modal: false,
							width: 400,
							height: 300,
							buttons: {
							
								'Sluit' : function() {
								
									$(this).dialog('destroy');
									
								}
							
							}
						
						})
		
		}, 'json')
	
	})
	
}


function initialize() 
{
    var latlng = new google.maps.LatLng(51.01622504508186, 3.5817334055900574);
    var myOptions = { zoom: 12, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	
	var marker = new google.maps.Marker({ position: new google.maps.LatLng(51.01622504508186, 3.5817334055900574), map: map });   
}


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 "";
    }
}
