// error handling for firebug
$(document).ajaxError(function(){
	if (window.console && window.console.error) {
		console.error(arguments);
	}
});

// when ready
$().ready(function(){
	// load the wizard
	$("#wizard").wizard({
		prevnext: false,
        show: function(element) {
        	$('.wizard-nav a').corner();
        	
			$('.errormessage').removeClass('error');
			$('.errormessage').addClass('noerror');
        	
        	if($(element).is("#SecondPage")) {
        		var hasErrors = false;
        		if (($('#package').val() != "" || $('#subscription').val() != "-1")
        			&& $('#newnumber').val() == '0') {
        			$('#newnumber').addClass('error');    
        			hasErrors = true;    		
        		} else {
        			$('#newnumber').removeClass('error');
	        		$('#newnumber').addClass('noerror');
        		}
        		$('#subscription').removeClass('error');
        		if ($('#affiliatecode').val() == "WHT2011") {
        			if ($('#subscription').val() == "-1") {
        				alert("De WHT actie is alleen geldig in combinatie met een abonnement.\nKies een abonnement of pakket.");
        				hasErrors = true;
        			}
        		}
        		
        		if (hasErrors) {
	        		goto('FirstPage');
	        		return this;
	        	}
        	}  
        	if($(element).is("#ThirdPage")) {
        		var hasErrors = false;
        		var nrs = numbrsForCurrentSubscription();
        		if (nrs < parseInt($('#product39').val())) {
        			alert("Met de WHT actie kunt u niet meer toestellen bestellen dan u extenties afneemt.");
        			hasErrors = true;
        		}
        		if (hasErrors) {
	        		goto('SecondPage');
	        		return this;
	        	}        		
        	}  
        
        	if($(element).is("#FourthPage")) {
        		// validate previous page
        		//if ($('input[name=customerexists]:checked').val() == "0") { 
	        		var ids = ['firstname','lastname', 'company', 'email', 'phonenumber', 
	        			'address', 'postcode', 'city', 'kvk', 'vatnumber'];
	        		var hasErrors = false;
	        		for(i=0; i<ids.length; i++) {
	        			var val = $('#' + ids[i]).val();
	        			if (val == "") {
	        				$('#' + ids[i]).addClass('error');
	        				hasErrors = true;
	        			} else {
	        				$('#' + ids[i]).removeClass('error');
	        				$('#' + ids[i]).addClass('noerror');
	        			}
	        		}
	        		if (hasErrors) {
	        			goto('ThirdPage');
	        			return this;
	        		}
	        	//}
	        	
        		$('#productlist-monthly').html('');
        		$('#productlist-once').html("<img src='img/ajax-loader.gif' />&nbsp&nbsp;Bezig met ophalen prijsinformatie.").removeClass("error");
				$.ajax({
					url: 'ajax.php',
					data: 'action=product_list_html' 
						+ '&order=' + JSON.stringify(readOrder()),
					dataType: 'json',
					type: 'post',
					success: function (j) {
						if (j.ok) {
							if (j.oncetotal > 0) {
								$('#productlist-once').html(j.oncetable);
							} else {
								$('#productlist-once').html("");
							}
							$('#priceonce').val(j.oncetotal);
							if (j.monthlytotal > 0) {
								$('#productlist-monthly')
									.html(j.monthlytable)
									.append( 
										'<div id="agreedirectdebit">'				
										+ '  <input name="dd" type="checkbox" class="textfield" id="dd"/>'
										+ '  Ja, ik ga akkoord met de automatische afschrijving van het aangegeven abonnementsbedrag.'
										+ '  <!-- <img src="img/question.png" id="questionDirectDebit" align="bottom"> -->'
										+ '  <br/>'
										+ '  <label for="accountnumber">&nbsp;&nbsp;&nbsp;rekeningnummer</label>'
										+ '  <input name="accountnumber" type="text" class="textfield" id="accountnumber"/>'
										+ '  <br/>'
										+ '  <label for="accountname">&nbsp;&nbsp;&nbsp;rekeninghouder</label>'
										+ '  <input name="accountname" type="text" class="textfield" id="accountname"/>'
										+ '  <br/>'
										+ '</div>'
									 );
									 // createTooltipWithText('Indien u niet akkoord gaat met automatische afschrijving, zijn wij genoodzaakt &euro;2,50 administratieve kosten per factuur in rekening te brengen.', 'questionDirectDebit');
							} else {
								$('#productlist-monthly').html("");
							}
							$('#pricemonthly').val(j.monthlytotal);
							$('.productsummary').corner();							
						}
					},
					error: function (XMLHttpRequest, textStatus, errorThrown) {
						$('#productlist-once').html(XMLHttpRequest.responseText).addClass("error");
					}
				});
        	}
        
        	// handle form submission
            if($(element).is("#LastPage")) {
            	order = readOrder();
            	options = order.options;
            	var agreedOnGeneralTerms = false;
            	var agreedOnDirectDebit = false;
            	for(var i=0; i<options.length; i++) {
            		if (options[i] == 'genterms') agreedOnGeneralTerms = true;
            		if (options[i] == 'dd') agreedOnDirectDebit = true;
            	}
            	var msg = $('#errorMessageFourthPage');
            	msg.html("");
            	
            	// check general terms agree
            	if (!agreedOnGeneralTerms) {
            		msg.hide().fadeIn(1500, function() {
						msg.html("<img src='img/error.png' />&nbsp&nbsp;U dient akkoord te gaan met de algemene voorwaarden.").addClass("error");
					});
					goto('FourthPage');
	        		return this;
            	}            	
            	// check direct debit agree
            	var accountnumber = $('#accountnumber').val();
            	var accountname = $('#accountname').val();
            	if (parseInt($('#pricemonthly').val()) > 0 && (!agreedOnDirectDebit || accountnumber=='' || accountname=='')) {
            		var message = "U heeft geen volledige gegevens ingevuld voor automatische afschrijving.\n" + 
            			"Wilt u deze alsnog invullen?"; 
        			msg.hide().fadeIn(1500, function() {
						msg.html("<img src='img/error.png' />&nbsp&nbsp;" + message).addClass("error");
					});
        			goto('FourthPage');
        			return this;            		
            	}
            	

            	
            
                var msg = $('#errorMessageLastPage');
                msg.html('<img src="img/ajax-loader.gif" height="16" width="16" />&nbsp;&nbsp;Bezig met verwerken...');

				$.ajax({
					url: 'ajax.php',
					data: 'action=submit_order&order=' + JSON.stringify(readOrder()),
					dataType: 'json',
					type: 'post',
					success: function (j) {
						var msg = $('#errorMessageLastPage');
						if (j.ok) {
							msg.hide() 
							.fadeIn(1500, function() {
								msg.html("<img src='img/check.png' />&nbsp&nbsp;" + j.msg).addClass("success");
								$('#paymentOptions').show();
							});
						} else {
							msg.html("<img src='img/error.png' />&nbsp&nbsp;" + j.msg).addClass("error");										
						}
					},
					error: function (XMLHttpRequest, textStatus, errorThrown) {
						msg.html(XMLHttpRequest.responseText).addClass("error");
					}
				});
				
				$('#paywithideal').click(function () {
					$.ajax({
						url: 'ajax.php',
						data: 'action=pay_ideal&amount=' + $('#priceonce').val(),
						dataType: 'json',
						type: 'post',
						success: function (j) {
							$('#LastPage').html('<br/><div style="width:450px">' + $('#productlist-once').html() + "</div><br/>" + j.html);
						},
						error: function (XMLHttpRequest, textStatus, errorThrown) {
							$('#LastPage').html(XMLHttpRequest.responseText).addClass("error");
						}
					});				
				});
				
				
			}
        }
    });
    fillPackageOptions();
    fillSubscriptionOptions();
    $("#numbersdiv").hide();
    $('#newnumber').change(function () {
    	if (parseInt(this.value) == 2) {
    		$('#numbersdiv').show();			    	
    	} else {
    		$('#numbersdiv').hide();
    	}
    });
    $('#gxp2020ext').hide();		// initially hide extension module for the GXP2020
    $('#product41').keyup(function () {
    	// if we ordered at least one GXP2020 
    	if (parseInt(this.value) > 0) {
    		$('#gxp2020ext').show();			    	
    	}
    });
    createTooltipWithProductInformation(42, 'question42');
    createTooltipWithText('Het klantnummer vind u rechtsboven aan uw factuur.', 'questionClientid');
    createTooltipWithText('Dit is het emailadres waarop u normaliter uw facturen ontvangt.', 'questionEmail2');
    createTooltipWithText('Vult u hier de volledige nummers in die u wilt porteren gescheiden door een komma.', 'qnumbers');
    
    // handle existing client block
    $('#mbclientinfo').hide();
    $('#customerexists1').click(function() { 
    	$('#mbclientinfo').show(); 
    	//$('#clientinfo1 .textfield').attr("disabled", true);
    	$('#clientinfo1').hide();
    	$('#clientinfo2').hide();
    	$('#billinginfo1').hide();
    	$('#billinginfo2').hide();
    });
    $('#customerexists0').click(function() { 
    	$('#mbclientinfo').hide();
    	//$('#clientinfo1 .textfield').removeAttr("disabled");
    	$('#clientinfo1').show();
    	$('#clientinfo2').show();
    	$('#billinginfo1').show();
    	$('#billinginfo2').show();
    });
 
    // handle email validation remotely via ajax
	var validateEmail = $('#validate_email');
	$('#email').keyup(function () {
		var t = this;
		if (this.value != this.lastValue) {
			if (this.timer) clearTimeout(this.timer);
			validateEmail.removeClass('error').html('<img src="img/ajax-loader.gif" height="16" width="16" />');
			this.timer = setTimeout(function () {
				$.ajax({
					url: 'ajax.php',
					data: 'action=validate_email&email=' + t.value,
					dataType: 'json',
					type: 'post',
					success: function (j) {
						if (j.ok) {
							validateEmail
							.hide() 
							.fadeIn(1500, function() {
								$('#validate_email').html("<img id='checkmark' src='img/check.png' />");
							});
						} else {
							validateEmail.html(j.msg);
						}
					}
				});
			}, 400);
			this.lastValue = this.value;
		}
	});
	
	// producten
	$("#productcatalog").accordion({header: "h3",  autoHeight: false});
	$("#productcatalog").accordion( 'activate' , 0);
	$("#paymentOptions").hide();
	
	// acties
	if ($.getURLParam("aff") == "WHT2011") {
		$("#packagediv").hide();
		goto('SecondPage');
		$("#product39").val("1");
		goto('FirstPage');
		$('#subscription').val("13");
		fillSubscriptionOptions()
	}
	
	if ($.getURLParam("Grandstream") != null) {
		var phone = $.getURLParam("Grandstream");
		goto('SecondPage');
		$('#' + phone).val("1");
	}
	if ($.getURLParam("package") != null) {
		var package = $.getURLParam("package");
		$('#package').val(package);
		fillPackageOptions();
	}
	if ($.getURLParam("aff") != null) {
		var aff = $.getURLParam("aff");
		$('#affiliatecode').val(aff);	
	}
	
});

function numbrsForCurrentSubscription() {
	if ($('#subscription').val() == "13")
		return 1;
	if ($('#subscription').val() == "14")
		return 2;
	if ($('#subscription').val() == "16")
		return 10;
	if ($('#subscription').val() == "17")
		return 30;
	if ($('#subscription').val() == "18")
		return 100;
	return 0;
}

/**
 * readContactDetails(prefix)
 *
 * Helper function to read contact details
 */
function readContactDetails(prefix) {
	contact = new Object;
	contact.firstname = $('#' + prefix + 'firstname').val();
	contact.lastname = $('#' + prefix + 'lastname').val();
	contact.company = $('#' + prefix + 'company').val();
	contact.kvk = $('#' + prefix + 'kvk').val();
	contact.vatnumber = $('#' + prefix + 'vatnumber').val();
	contact.email = $('#' + prefix + 'email').val();
	contact.phonenumber = $('#' + prefix + 'phonenumber').val();
	contact.faxnumber = $('#' + prefix + 'faxnumber').val();
	contact.address = $('#' + prefix + 'address').val();
	contact.postcode = $('#' + prefix + 'postcode').val();
	contact.city = $('#' + prefix + 'city').val();
	return contact;
}

/**
 * readOrder()
  *
 * Read the order from the form and construct order object which can
 * be sent in json format to the server
 */
function readOrder() {
	var products = [];
	if ($('#subscription').val() != "-1") {
		products.push({"id":$('#subscription').val(), "count":1});
	}
	if ($('#package').val() != "") {
    	products.push({"id":$('#package').val(), "count":1});
	}
	$('input:text', document.forms[0]).each(function() {
		// 'this' is a DOM element, wrap 'this' in a jQuery object
		var $this = $(this); // now we have the full jQuery API at our disposal
		var name = $this.attr("id");
       	if (name.substring(0, 7) == 'product') {
       		var value = $this.attr("value");
       		if (parseInt(value) > 0) {
       			var productid = name.substring(7, 10);
       			if (parseInt(productid) > 0) {
   					products.push( {"id":productid, "count":value} );
   				}
       		}
       	}
	});
	var cbs = $('#fullpage').find('input:checkbox:checked');
	var options = [];
	for(var i=0; i<cbs.length; i++) {
		options.push(cbs[i].name);
	}
	
	var order = new Object;
	order.products = products;
	order.newnumber = $("#newnumber").val();
	order.numbers = $("#numbers").val();
	order.contactDetails = readContactDetails("");
	order.billingDetails = readContactDetails("billing_");
	order.newnumber = $("#newnumber").val();
	order.options = options;
	order.accountnumber = $("#accountnumber").val();
	order.accountname = $("#accountname").val();
	order.affiliatecode = $("#affiliatecode").val(); 
	return order;
}

function clearProducts() {
	$('input:text', document.forms[0]).each(function() {
		var $this = $(this);
		var name = $this.attr("id");
     	if (name.substring(0, 7) == 'product') {
       		$this.attr("value", "");
       	}
	});
}

function fillSubscriptionOptions() {
   	// schedule next
   	$('#subscription').change(fillSubscriptionOptions);
   	// show/hide extra extension
   	if ($('#package').val() == "" && parseInt($("#subscription").val()) < 0) {
   		$("#pbxext").hide();
   	} else {
   		$("#pbxext").show();
   	}
   	$("#product21").val(numbrsForCurrentSubscription());
}

function fillPackageOptions() {
	$('#package').change(fillPackageOptions);
	// reset all
	//clearProducts();
	// disable/enable all products
	$('input:text', document.forms[0]).each(function() {
		var $this = $(this); // now we have the full jQuery API at our disposal
		var name = $this.attr("id");
		if (name.substring(0, 7) == 'product') {
			if ($('#package').val() == "") {
				$this.removeAttr("disabled");
			} else {
				$this.attr("disabled", true);
			}
		}
	});	
	// disable/enable subscription	
   	if ($('#package').val() == "") {
		$("#subscription").removeAttr("disabled"); 
   	} else {
   		$("#subscription").attr("disabled", true);
   	}
   	// fill products
   	if ($('#package').val() == "2002") {
   		$("#subscription").val("14");
   		$("#product21").val("2");    	
   		$("#product39").val("2");
   	} else if ($('#package').val() == "2005") {
   		$("#subscription").val("49");
   		$("#product21").val("5");
   		$("#product39").val("5");
   	} else if ($('#package').val() == "2010") {
   		$("#subscription").val("16");
   		$("#product21").val("10");
   		$("#product39").val("10");
   	} else if ($('#package').val() == "3010") {
   		$("#subscription").val("16");
   		$("#product21").val("10");
   		$("#product39").val("10");
   	} else if ($('#package').val() == "3015") {
   		$("#subscription").val("17");
   		$("#product21").val("15");    	
   		$("#product39").val("15"); 		   	   		   	
   	} else if ($('#package').val() == "3025") {
   		$("#subscription").val("17");
   		$("#product21").val("25");
   		$("#product39").val("25");
   	} else {
   		$("#subscription").val("-1");
   	}
 	// show package image
	$('#mainProductImg').fadeOut(200, function() {
		var val = $('#package').val();
		if (val == "") val = "none";
		$(this).attr({'src' : 'img/products/' + val + '.jpg'});
		if (this.complete) $(this).fadeIn(500);
	});	
}

function createTooltipWithProductInformation(productID, tooltipID) {
	$.ajax({
		url: 'ajax.php',
		data: 'action=product_tooltip&productid=' + productID,
		dataType: 'json',
		type: 'post',
		success: function (j) {
			var message = "Sorry, no product information could be found.";
			if (j.ok) {
				message = j.description;
			} 
			createTooltipWithText(message, tooltipID);
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			alert("error:" + XMLHttpRequest.responseText);
		}
	});
}
function createTooltipWithText(text, tooltipID) {
   	$('#' + tooltipID).qtip({
   		content: text,
   		show: 'mouseover',
   		hide: 'mouseout',
   		style: { name: 'dark' }
   	});
}
function goto(page) {
	$('.wizard-nav').children('a').removeClass('active', 'slow');

//	$('a[href="#FirstPage"]').removeClass('active');
//	$('a[href="#SecondPage"]').removeClass('active');
//	$('a[href="#ThirdPage"]').removeClass('active');
//	$('a[href="#FourthPage"]').removeClass('active');
//	$('a[href="#LastPage"]').removeClass('active');
		
//	$('.wizard-nav').children('input[type="button"].wizardprev').trigger('click');
	$('a[href="#' + page + '"]').trigger('click').addClass('active', 'slow');
}

function fillDemoData() {
	$('#firstname').val("Thiadmer");
	$('#lastname').val("Sikkema");
	$('#company').val("BLUEPalm B.V.");
	$('#email').val("t.sikkema@bluepalm.nl");
	$('#phonenumber').val("0157112727");
	$('#faxnumber').val("0157112728");
	$('#address').val("Marshalllaan 2");
	$('#postcode').val("2625 GZ");
	$('#city').val("Delft");
	$('#kvk').val("Haaglanden 27183560");
	$('#vatnumber').val("NL815990388B01");
}

function floatval(mixed_var) {
    return (parseFloat(mixed_var) || 0);
}



