var asSignApp = {};

asSignApp.api_pkey 		= "qwerty";
asSignApp.api_url 		= RELATIVE_ROOT + 'api/rest-json/'; // RELATIVE_ROOT is a JS variable set in default.html
asSignApp.current_step 	= 1;
asSignApp.container		= false;


$(document).ready(function()
{
	// Override default error message
    // jQuery.validator.messages.required = "";
	
	// Custom validations
	jQuery.validator.addMethod("postcode_validate", function(value, element) {  
    	return this.optional(element) || /([0-9]{4})/i.test(value); }, "Ongeldige postcodecijfers"
	);
	jQuery.validator.addMethod("postcode_suffix_validate", function(value, element) {  
    	return this.optional(element) || /([a-zA-Z]{2})/i.test(value); }, "Ongeldige postcodeletters"
	);	
	jQuery.validator.addMethod("terms_agreed", function(value, element) {  
    	return $('#chk_agreed:checked').size() != 0; }, "U moet akkoord gaan met de algemene voorwaarden."
	);	

	// Initialize asSignApp here...
	asSignApp.init();
});

asSignApp.init = function()
{
	// Only initialize app when step wrapper is found
	if ($('.frmStep').length)
	{
		this.container = $('.frmStep');

		// Set current step
		this.current_step = parseInt(this.container.find('input[name=curr_step]').val());

		// Initialize current step-specific event listeners
		this.InitStep(this.current_step);		

		// Initialize button listeners
		this.container.on('click', '.button.submit',   this.PostStep.bind(this));
		this.container.on('click', '.button.previous', this.PreviousStep.bind(this));
	}
};

/**
 * This method takes us a step back
 */
asSignApp.PreviousStep = function(e)
{
	// Stop SUBMIT event
	e.preventDefault();
	// Only perform when no other action is running
	if (!$('#loader').is(':visible'))
	{
		this.ShowLoader();
		this.current_step = this.current_step - 1;
		if (this.current_step < 1) this.current_step = 1;
		this.data = this.container.serialize();
		$.getJSON(
			this.api_url + 'signup/steprouter/?pkey='+this.api_pkey+'&move=prev',
			this.data,
			asSignApp.LoadStep.bind(this)
		);
	}
	
	return false;
};

/**
 * This method calls the API, passing the serialized form data
 */
asSignApp.PostStep = function(e)
{
	// Stop SUBMIT event
	e.preventDefault();

	// Only perform when no other action is running
	if (!$('#loader').is(':visible'))
	{
		if (this.Validate(this.current_step))
		{
			this.data = this.container.serialize();
			$.getJSON(
				this.api_url + 'signup/steprouter/?pkey='+this.api_pkey+'&move=next',
				this.data,
				asSignApp.LoadStep.bind(this)
			);

		}
	}

	return false;
};

/**
 * This method parses the API return data
 */
asSignApp.LoadStep = function(data)
{

	var valid_HTML = false;
	var step_HTML = "RL API error";
	if (typeof data === 'object' &&	typeof data.status === 'string' && data.status == "success")
	{
		step_HTML = data.response;
		valid_HTML = true;
	}

	$("#section").html(step_HTML);

	if (valid_HTML)
	{
		// Re-Initialize asSignApp here...
		asSignApp.init();	
	}
	
};

/*
 * Check for matching franchisee based on zip
 */ 
asSignApp.CheckFranchisezip = function(z)
{
	var fzip = false;
	this.ShowLoader();
	$.ajax({
		   url: this.api_url + 'franchise/searchfranchise/?pkey='+this.api_pkey+'&zipcode='+z,
		   success: function(data) {
				if (typeof data === 'object' &&	typeof data.status === 'string' && data.status == "success")
				{
					franchisecheck = data.response;
					if(franchisecheck)	fzip = true;
				}
				
		   },
		   dataType: "json",
		   async:   false
	});
	
	if (!fzip)
	{
		if ($('#err-no-email').length == 0 )
		{
			$("#error_list").html('').append("<li id='err-no-service' class='error'><label>Helaas zijn wij in uw regio nog niet actief. Vaak kunnen wij u toch helpen met een afspraak op maat. Neem hiervoor contact op via 0900-221 3333 of via <a href=\"mailto:info@autostomerij.nl\">info@autostomerij.nl</a></label></li>");
		}
		$("#error_list").show();
		this.HideLoader();
	}
	else
	{
		if ($('#err-no-service').length) 	$("#err-no-service").remove();	
		$("#error_list").hide();			
	}
	
	return fzip;
};

/*
 * Verify existing customer by email, tel
 */ 
asSignApp.CheckCustomeremail = function(email, tel)
{
	var exists = false;
	$.ajax({
		   url: this.api_url + 'customer/emailexists/?pkey='+this.api_pkey+'&email='+email+'&phonenumber='+tel,
		   success: function(data) {
				if (typeof data === 'object' &&	typeof data.status === 'string' && data.status == "success")
				{
					emailcheck = data.response;
					if(emailcheck)	exists = true;
				}
				
		   },
		   dataType: "json",
		   async:   false
	});
	
	if (!exists)
	{
		if ($('#err-no-email').length == 0 )
		{
			$("#error_list").append("<li id='err-no-email' class='error'><label>Helaas, u bent niet bekend binnen ons systeem. Controleer uw invoer en probeer het nogmaals.</label></li>");
		}
		$("#error_list").show();			
	}
	else
	{
		if ($('#err-no-email').length) 	$("#err-no-email").remove();	
		$("#error_list").hide();			
	}
	
	return exists;
};

/*
 * Get existing customer by email
 */ 
asSignApp.GetExistingCustomerByEmail = function(email)
{
	var customer_data = false;
	$.ajax({
		   url: this.api_url + 'customer/getinfo/?pkey='+this.api_pkey+'&email='+email+'&phonenumber='+tel,
		   success: function(data) {
				if (typeof data === 'object' &&	typeof data.status === 'string' && data.status == "success")
				{
					customer_data = data.response;
				}
		   },
		   dataType: "json",
		   async:   false
	});

	return customer_data;
};

/*
 * Verify existing company by code
 */ 
asSignApp.CheckCompany = function(code, zipcode)
{
	var exists = false;
	$.ajax({
		   url: this.api_url + 'company/companyexists/?pkey='+this.api_pkey+'&code='+code+'&zipcode='+zipcode,
		   success: function(data) {
				if (typeof data === 'object' &&	typeof data.status === 'string' && data.status == "success")
				{
					companycheck = data.response;
					if(companycheck)	exists = true;
				}
				
		   },
		   dataType: "json",
		   async:   false
	});
	
	if (!exists)
	{
		if ($('#err-no-email').length == 0 )
		{
			$("#error_list").append("<li id='err-no-email' class='error'><label>Deze code wordt niet herkend.</label></li>");
		}
		$("#error_list").show();			
	}
	else
	{
		if ($('#err-no-email').length) 	$("#err-no-email").remove();	
		$("#error_list").hide();			
	}
	
	return exists;
};


/**
 * This method performs the basic form validation
 * plugin source: jquery.validate.js
 */
asSignApp.Validate = function(step)
{
	console.log('validate step: ' + step);
	valid = false;
	switch(step)
	{
		case 1:
			mode = $("input[name$='customer_mode']:checked").val();			
			this.container.validate({
				errorClass: "error",
				errorLabelContainer: "#error_list",
				wrapper: "li",
				rules: {
					"customer[zipcode]": "postcode_validate",
					"customer[zipcode_suffix]": "postcode_suffix_validate",
					"customer[housenumber]": "required",
					"customer[email]": {
							required: true,
      						email: true
						},
					"customer[phonenumber]": {
							required: true
						}					
				},
				messages: {
					"customer[zipcode]": "Ongeldige postcodecijfers",
					"customer[zipcode_suffix]": "Ongeldige postcodeletters",
					"customer[housenumber]": "Huisnummer is verplicht",
					"customer[email]": "Een geldig e-mailadres is noodzakelijk",
					"customer[phonenumber]": "Telefoonnummer is verplicht"
				}
			});
			console.log('Customer mode: ' + mode);
			
			
			// Use validate.valid method check
			if (this.container.valid())			
			{
				if ("new" == mode)
				{
					// Validate returned true, proceed RL API franchise zipcode lookup					
					zipcode = $("input[name='customer[zipcode]']").val();					
					console.log('CheckFranchisezip: ' + zipcode);
					valid = this.CheckFranchisezip(zipcode);
				}
				if ("existing" == mode)
				{
					// Validate returned true, proceed RL API customer lookup			
					email = $("input[name='customer[email]']").val();
					tel = $("input[name='customer[phonenumber]']").val();
					console.log('CheckCustomeremail: ' + email + ' - ' + tel);
					valid = this.CheckCustomeremail(email, tel);
					if (valid)
					{
						// Retrieve zipcode from matched customer
						console.log('GetExistingCustomerByEmail: ' + email);
						customer = this.GetExistingCustomerByEmail(email);
						zipcode = customer.zipcode;
						console.log('Retrieved zipcode: ' + zipcode);
					}
				}
				
				// Check if company code is supplied
				if (valid && $("input[name='company[code]']").val() != "" && zipcode)
				{
					companycode = $("input[name='company[code]']").val();
					console.log('CheckCompany: ' + companycode);
					valid = this.CheckCompany(companycode, zipcode);																	  
				}				
			}
			else
			{
				valid = false;			
			}
		break;
		case 2:
			this.container.validate({
				errorClass: "error",
				errorLabelContainer: "#error_list",
				wrapper: "li",			
				rules: {
					"customer[firstname]": "required",
					"customer[lastname]": "required",
					"customer[street]": "required",
					"customer[city]": "required",
					"customer[housenumber]": "required",
					"customer[phonenumber]": "required",
					"customer[email]": {
							required: true,
      						email: true
					},
					"car[brand]": "required",
					"car[type]": "required",
					"customer[invoice_firstname]": "required",
					"customer[invoice_lastname]": "required",
					"customer[invoice_street]": "required",
					"customer[invoice_city]": "required",
					"customer[invoice_housenumber]": "required",
					"company[name]": "required",
					"company[address]": "required",
					"company[phonenumber]": "required",
					"company[zipcode]": "postcode_validate",
					"company[email]": {
							required: true,
      						email: true
					},
					"company[invoice_name]": "required",
					"company[invoice_address]": "required",
				},				
				messages: {
					"customer[firstname]": "Voornaam is verplicht",
					"customer[lastname]": "Achternaam is verplicht",
					"customer[street]": "Straat is verplicht",
					"customer[city]": "Stad is verplicht",
					"customer[housenumber]": "Huisnummer is verplicht",
					"customer[phonenumber]": "Telefoonnummer is verplicht",
					"customer[email]": "Een geldig e-mailadres is verplicht",
					"car[brand]": "Automerk is verplicht",
					"car[type]": "Autotype is verplicht",
					"customer[invoice_firstname]": "Voornaam is verplicht",
					"customer[invoice_lastname]": "Achternaam is verplicht",
					"customer[invoice_street]": "Straat is verplicht",
					"customer[invoice_city]": "Stad is verplicht",
					"customer[invoice_housenumber]": "Huisnummer is verplicht",
					"company[name]": "Bedrijfsnaam is verplicht",
					"company[address]": "Bedrijfsadres is verplicht",
					"company[phonenumber]": "Bedrijfstelefoonnummer is verplicht",
					"company[email]": "Bedrijfse-mail is verplicht",
					"company[invoice_name]": "Bedrijfsnaam is verplicht",
					"company[invoice_address]": "Bedrijfsadres is verplicht",
					"company[zipcode]": "Ongeldige postcodecijfers"
				}
			});	
			
			valid = this.container.valid(); // returns true/false valid from .validate()			
		break;
		case 3:
			if($('#frmStep3 input[type="checkbox"]').is(':checked'))
			{
				$("#err-no-product").remove();	
				$("#error_list").hide();					
				valid = true;
			}
			else
			{
				if ($('#err-no-product').length == 0 )
				{
					$("#error_list").append("<li id='err-no-product' class='error'><label>Selecteer a.u.b. minimaal 1 product.</label></li>");
				}
				$("#error_list").show();
				valid = false;
			}
		break;
		case 4:
			if ($("#dateFlag").is(':checked')) 
				valid = true;
			else
				valid = false;
		break;
		case 5:				
			this.container.validate({
				errorClass: "error",
				errorLabelContainer: "#error_list",
				wrapper: "li",					
				rules: {
					"chk_agreed": "required"
				},
				messages: {
					"chk_agreed": "U moet akkoord gaan met de algemene voorwaarden.",
				}
			});								
			valid = this.container.valid(); // returns true/false valid from .validate()	
		break;		
		default:
			valid = true;
		break;
	}
	
	console.log('Valid: ' + valid);
	
	if (valid)
	{
		this.ShowLoader();		
	}
	else
	{
		this.HideLoader();				
	}
	
	return valid;
};	

/**
 * This method initializes step specific event behavior/listener
 */
asSignApp.InitStep = function(step)
{
	switch(step)
	{
		case 1:
			$("input[name$='customer_mode']").click(function() {			
				 mode = $(this).val();
				 $('.frmStep').find('#error_list li').remove();
				 if ("new" == mode)
				 {
					$('#postcodeNew').show();
					$('#postcodeExist').hide(); 
				 }
				 else
				{
					$('#postcodeExist').show();
					$('#postcodeNew').hide(); 			
				}
			}); 			
		break;
		case 2:
			$("#toggle_alternative").click(function() {			
				$('#altAddress').toggle(); 			
				$('.frmStep').find('#error_list li').remove();
			});
			// Chain car-brand and car-type dropdowns
			$("select[name='car[brand]']").change(function(){ 	
				var brand 		= $("select[name='car[brand]'] option:selected").attr('value');		
				var auto_type 	= $("select[name='car[type]']");
				auto_type.attr('disabled', 1);
				if (brand.length) {					
					$.getJSON(
						asSignApp.api_url + 'autolookup/typeforbrand/?pkey='+asSignApp.api_pkey+"&brand="+brand,
						false,
						function(data)
								{
									if (typeof data === 'object' &&	typeof data.status === 'string' && data.status == "success")
									{
										type_list = data.response;
										auto_type.removeAttr('disabled'); 
										auto_type.empty().append("<option></option>");
										$.each(type_list, function(i, d) { auto_type.append("<option value=\""+d.ID+"\">"+d.serie+"</option>"); });
									}
								}
					);				
				}		
				
			});			
		break;
		case 3:
			// Toggle product list
			$("#specific-products").click(function(){
				$(".product_wrap").toggle();										
			});
			
			// Pre-select products based from product groups	
			$(".product_group_item").click(function(){ 	
				var raw_id	= $(this).attr("id");	
				var group 	= raw_id.replace('pg_', '');
				if (group.length) {	
					$('input:checkbox').removeAttr('checked');
					$("input:radio[name=productgroup][value="+group+"]").attr('checked', true); 		

					asSignApp.ShowLoader();

					$.getJSON(
						asSignApp.api_url + 'productgroupproduct/productpergroup/?pkey='+asSignApp.api_pkey+"&groupid="+group,
						false,
						function(data)
								{
									if (typeof data === 'object' &&	typeof data.status === 'string' && data.status == "success")
									{
										product_list = data.response;									
										$.each(product_list, function(i, d) { 
											$("input[name$='product[" + d.productID + "]']").attr("checked", true);
										});
										$('.product_wrap').show();
									}

									asSignApp.HideLoader();
								}	
					);						
					
				}		
				
			});			
		break;
		default:
		break
	}
	return false;
};	


asSignApp.ShowLoader = function()
{
	$('#loader').show();	
};

asSignApp.HideLoader = function()
{
	if ($('#loader').length) $('#loader').fadeOut();
};

