/*function wowInit() {
    var wow = new WOW({
        mobile: false
    });
    wow.init();
}*/

var gasPresent = 0;
var previousCollapsing = null;

$("#navigation-example").on("hide.bs.collapse",function(){
	$('.hamburger').removeClass('is-active');
	$('.logo-img').removeClass('inverted');
	
	var collapsee = $(this);
	collapsee.addClass("collapsed-fix");
	
	if(previousCollapsing != null)
	{
		clearTimeout(previousCollapsing);
	}
	
	previousCollapsing = setTimeout(function(){
		collapsee.removeClass("collapsed-fix");
	}, 500);
});

$("#navigation-example").on("show.bs.collapse",function(){
	$('.hamburger').addClass('is-active');
	$('.logo-img').addClass('inverted');
});

$(document).ready(function(){

  var clicked = false;
  var activeByClicked = false;
  

  var hovers = $('.hover-info');
  if( hovers ) {

    var videos = [
      {
        id:'chatvid',
        src:'https://s3.eu-west-2.amazonaws.com/cleoassets/videos/hero_video.mp4',
        cover:'assets/img/Iphone6Plus.png'
      },
      {
        id:'socialvid',
        src:'https://s3.eu-west-2.amazonaws.com/cleoassets/videos/hero_video.mp4',
        cover:'assets/img/Iphone6Plus.png'
      },
      {
        id:'twittervid',
        src:'https://s3.eu-west-2.amazonaws.com/cleoassets/videos/hero_video.mp4',
        cover:'assets/img/Iphone6Plus.png'
      },
      {
        id:'telegramvid',
        src:'https://s3.eu-west-2.amazonaws.com/cleoassets/videos/hero_video.mp4',
        cover:'assets/img/Iphone6Plus.png'
      }
    ];

    playMyVideo = function(obj) {
      if(!obj) { return false; }
      var videl = $("#swapvid");
      videl.src = obj.src;
      videl.load();
    }

    getVideo = function(id) {

      console.log(id);

      if(!id) { return false; }

      var vids = videos;

      var foo = $.grep(vids, function(e){ return e.id === id})
      return vids.pop(foo);
    }

    hovers.hover(
      function() {
        if(!activeByClicked) {
          $(this).addClass('active');
        }
      },
      function() {
        if(!activeByClicked) {
          clicked = false;
          $( this ).removeClass('active');
         }
      }
    );

    hovers.click(function(){
      if(clicked) {
        if(!$(this).hasClass('active')) {
            hovers.removeClass('active');
            $(this).addClass('active');
            activeByClicked = true;

            var myid = $(this).attr('id');
            var myvid = getVideo(myid);

            console.log(myvid);
            
            playMyVideo(myvid);
            return false;

        } else {
            // clicked = false;
            // activeByClicked = false;
        }
      } else {
        clicked = true;
        activeByClicked = true;
      }
    });

    if(hovers && hovers[0]) {
      hovers[0].click();
    }
  }
});

/*
http://www.formvalidator.net/index.html#configuration
*/

$.formUtils.addValidator({
  name : 'uk_postcode',
  validatorFunction : function(value, $el, config, language, $form) {
    return /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i.test(value);
  },
  errorMessage : 'Valid UK postcode?',
  errorMessageKey: 'bad_uk_postcode'
});

$(document).ready(function(){

  $.validate({
    form : '#form-postcode, #form-postcode-lower',
    modules : 'sanitize, html5',
    scrollToTopOnError: false,
    validateOnBlur : false,
    errorMessagePosition : 'inline',
    onError : function($form) {
      return false;
    },
    onSuccess : function($form) {
      return true; // Will stop the submission of the form
    },
    onValidate : function($form) {
    },
    onElementValidate : function(valid, $el, $form, errorMess) {
    }
  });

});


$("#navigation-example").on("hidden.bs.collapse",function(){
	
	$(this).closest(".navbar").removeClass("solid-fix");
});

$("#navigation-example").on("show.bs.collapse",function(){
	
	$(this).closest(".navbar").addClass("solid-fix");
});


/* Quotation Page */

var page = window.location.pathname.split("/").pop();

if(page == "energy-quotation.php")
{
	var steps = [
		'Postcode',
		'FuelRequirements',
		'Address',
		'GasOnly',
		'PaymentMethod',
		'PaperBill',
		'IsCurrentSupplierKnown',
		'CurrentSupplier',
		'HowDidYouHearAboutUs',
		'CurrentEnergyUsage',
		'CurrentEnergyUsageInkWh',
		'CurrentEnergyUsageInPounds',
		'HouseSize',
		'Summary',
	];
	
	var freeze = false;
	var animationDelay = 0.2*1000;

	var quoteParameters = {};

	var currentStep = 'Postcode';
	history.replaceState({step:currentStep}, "page "+currentStep, "energy-quotation.php?step="+currentStep);
	
	$('#step-'+currentStep).removeClass('hidden');
	$('#step-'+currentStep).removeClass('hiding');
	
	/* Step 1 - Postcode */
	
	$('#step-Postcode .continue-button').click(function(){
		var postCodeInput = $("#postcode");
		var postcode = postCodeInput.val().trim();
		
		$('#error-postcode-required').addClass('hidden');
		$('#error-postcode-invalid').addClass('hidden');
		postCodeInput.closest(".form-group").removeClass("has-error");
		
		if(postcode == "")
		{
			$('#error-postcode-required').removeClass('hidden');
			postCodeInput.closest(".form-group").addClass("has-error");
		}
		else
		{
			$.ajax({
				dataType: "json",
				url: "lookup-fuelAddresses.php",
				data: {PostCode: postcode},
				success: function(data, textStatus, jqXHR){
					var selectElectricityAddress = $("#address-elec");
					selectElectricityAddress.empty();
					selectElectricityAddress.append('<option disabled selected value> Select Address </option>');
					
					var selectGasAddress = $("#address-gas");
					selectGasAddress.empty();
					selectGasAddress.append('<option disabled selected value> Select Address </option>');
					
					if(jqXHR.status == 200 && data.Data != null)
					{
						$.each(data.Data.Electricity,function(key, value)
						{
							selectElectricityAddress.append('<option value="' + value.Address + '">' + value.Address + '</option>');
						});
						
						$.each(data.Data.Gas,function(key, value)
						{
							selectGasAddress.append('<option value="' + value.Address + '">' + value.Address + '</option>');
						});
						
						quoteParameters.postcode = postcode;
						
						changeStep('FuelRequirements');
					}
					else if(data.Message == "ERROR: postcode is not valid.")
					{
						$('#error-postcode-invalid').removeClass('hidden');
						postCodeInput.closest(".form-group").addClass("has-error");
					}
					else
					{
						window.location.href = "/issue.php";
					}
				}
			});
		}
	});
	
	/* Step 2 - Fuel requirements */
	
	$('#fuel-requirements-elec').click(function(){
		quoteParameters.fuelRequirements = 'elec';
		$('#elec-details').removeClass('hidden');
		$('#gas-details').addClass('hidden');
		$('#elec-usage').removeClass('hidden');
		$('#gas-usage').addClass('hidden');
		
		$('#address-elec-form-group').removeClass('hidden');
		$('#address-gas-form-group').addClass('hidden');
		
		$('#address-label-elec').removeClass('hidden');
		$('#address-label-gas').removeClass('hidden');
		$('#address-label-elec-confirm').addClass('hidden');
		$('#address-label-gas-confirm').addClass('hidden');
		
		changeStep('Address');
	});
	
	$('#fuel-requirements-gas').click(function(){
		changeStep('GasOnly');
	});
	
	$('#fuel-requirements-both').click(function(){
		quoteParameters.fuelRequirements = 'both';
		$('#elec-details').removeClass('hidden');
		$('#gas-details').removeClass('hidden');
		$('#elec-usage').removeClass('hidden');
		$('#gas-usage').removeClass('hidden');
		
		$('#address-elec-form-group').removeClass('hidden');
		$('#address-gas-form-group').addClass('hidden');
		
		$('#address-label-elec').removeClass('hidden');
		$('#address-label-gas').removeClass('hidden');
		$('#address-label-elec-confirm').addClass('hidden');
		$('#address-label-gas-confirm').addClass('hidden');
		
		changeStep('Address');
	});
	
	/* Step 3 â€“ Address */
	
	$('#step-Address #address-elec').change(function(){
		if(quoteParameters.fuelRequirements == 'both')
		{
			var elecAddress = $(this).val();
			
			var elecAddressParts = elecAddress.split(",");
			
			var matchingGasAddress = null;
			if(elecAddressParts.length > 3)
			{
				$('#step-Address #address-gas option').each(function(){
					
					var valueParts = this.value.split(",");
					
					if (valueParts[0].trim() == elecAddressParts[0].trim()
					 && valueParts[1].trim() == elecAddressParts[1].trim()
					 && valueParts[2].trim() == elecAddressParts[2].trim()) {
						matchingGasAddress = this.value;
						return false;
					}
				});
			}
			
			if(matchingGasAddress != null)
			{
				$('#step-Address #address-gas').val(matchingGasAddress);
				$('#address-gas-form-group').addClass('hidden');
				$('#address-label-elec').removeClass('hidden');
				$('#address-label-gas').removeClass('hidden');
				$('#address-label-elec-confirm').addClass('hidden');
				$('#address-label-gas-confirm').addClass('hidden');
			}
			else
			{
				$("#step-Address #address-gas").val($("#step-Address #address-gas option:first").val());
				$('#address-gas-form-group').removeClass('hidden');
				$('#address-label-elec').addClass('hidden');
				$('#address-label-gas').addClass('hidden');
				$('#address-label-elec-confirm').removeClass('hidden');
				$('#address-label-gas-confirm').removeClass('hidden');
			}
		}
	});
	
	$('#step-Address .continue-button').click(function(){
		$("#error-address-required").addClass("hidden");
			
		var valid = true;
			
		var gasAddress = $("#address-gas").val();
		var elecAddress = $("#address-elec").val();
		
		var needsElec = (quoteParameters.fuelRequirements == 'both' || quoteParameters.fuelRequirements == 'elec');
		var needsGas = (quoteParameters.fuelRequirements == 'both' || quoteParameters.fuelRequirements == 'gas');
		
		if(needsElec && elecAddress == null
		 || needsGas && gasAddress == null)
		{
			$("#error-address-required").removeClass("hidden");
			valid = false;
		}
		else
		{
			quoteParameters.address = {};
			if(needsElec) quoteParameters.address.electricity = elecAddress;
			if(needsGas) quoteParameters.address.gas = gasAddress;
		}
		
		if(valid)
		{
			changeStep('PaymentMethod');
		}
	});
	
	/* Step 4 â€“ Payment Method */
	
	$('#payment-method-prepay').click(function(){
		quoteParameters.paymentMethod = 'prepay';
		changeStep('IsCurrentSupplierKnown');
	});
	
	$('#payment-method-directdebit').click(function(){
		quoteParameters.paymentMethod = 'directdebit';
		changeStep('IsCurrentSupplierKnown');
	});
	
	$('#payment-method-paperbill').click(function(){
		changeStep('PaperBill');
	});
	
	/* Step 5 - Is Supplier Known? */
	
	$('#supplier-known').click(function(){
		changeStep('CurrentSupplier');
	});
	
	$('#supplier-unknown').click(function(){
		quoteParameters.suppliers = null;
		changeStep('HowDidYouHearAboutUs');
	});
	
	/* Step 6 - Supplier */
	
	function initSupplierSelect(details, energyNeeds)
	{
		var supplierSelect = details.find('#supplier');
		var tariffSelect = details.find('#tariff');
		
		supplierSelect.change(function(e){
			e.preventDefault();
			var supplier = supplierSelect.val();
			
			tariffSelect.empty();
			tariffSelect.append('<option selected value> Loading </option>');
			
			$.ajax({
				dataType: "json",
				url: "lookup-tarrifs.php",
				data: {
					SupplierName: supplier,
					FuelType: energyNeeds,
				},
				success: function(data, textStatus, jqXHR){
					tariffSelect[0].selectedIndex = 0;
					tariffSelect.empty();
					tariffSelect.append('<option disabled selected value> Select Tariff </option>');
					if(jqXHR.status == 200 && data != null)
					{
						tariffSelect.prop('disabled', false);
						$.each(data.tariffs,function(key, value) 
						{
							tariffSelect.append('<option value="' + value.TariffName + '">' + value.TariffName + '</option>');
						});
					}
					else
					{
						tariffSelect.prop('disabled', true);
					}
				}
			});
		});
	}

	initSupplierSelect($('#gas-details'), 'gas');
	initSupplierSelect($('#elec-details'), 'elec');
	
	$('#step-CurrentSupplier .continue-button').click(function(){
		var valid = true;
		$("#elec-details #error-supplier").addClass("hidden");
		$("#elec-details #error-tariff").addClass("hidden");
		$("#gas-details #error-supplier").addClass("hidden");
		$("#gas-details #error-tariff").addClass("hidden");
		
		quoteParameters.suppliers = {};
		
		if(quoteParameters.fuelRequirements == 'gas' || quoteParameters.fuelRequirements == 'both'){
			quoteParameters.suppliers.gas = {};
			var gasSupplier = $('#gas-details #supplier').val();
			if(gasSupplier == null)
			{
				$("#gas-details #error-supplier").removeClass("hidden");
				valid = false;
			}
			else
			{
				quoteParameters.suppliers.gas.supplier = gasSupplier;
			}
			var gasTariff = $('#gas-details #tariff').val();
			if(gasTariff == null)
			{
				$("#gas-details #error-tariff").removeClass("hidden");
				valid = false;
			}
			else
			{
				quoteParameters.suppliers.gas.tariff = gasTariff;
			}
		}
		
		if(quoteParameters.fuelRequirements == 'elec' || quoteParameters.fuelRequirements == 'both'){
			quoteParameters.suppliers.elec = {};
			var elecSupplier = $('#elec-details #supplier').val();
			if(elecSupplier == null)
			{
				$("#elec-details #error-supplier").removeClass("hidden");
				valid = false;
			}
			else
			{
				quoteParameters.suppliers.elec.supplier = elecSupplier;
			}
			var elecTariff = $('#elec-details #tariff').val();
			if(elecTariff == null)
			{
				$("#elec-details #error-tariff").removeClass("hidden");
				valid = false;
			}
			else
			{
				quoteParameters.suppliers.elec.tariff = elecTariff;
			}
		}
		
		if(valid)
		{
			changeStep('HowDidYouHearAboutUs');
		}
	});
	
	/* Step 7 â€“ How did you hear about us? */
	
	$('#howDidYouHearAboutUs-google').click(function(){
		quoteParameters.howDidYouHearAboutUs = 'google';
		changeStep('CurrentEnergyUsage');
	});
	
	$('#howDidYouHearAboutUs-tv').click(function(){
		quoteParameters.howDidYouHearAboutUs = 'tv';
		changeStep('CurrentEnergyUsage');
	});
	
	$('#howDidYouHearAboutUs-radio').click(function(){
		quoteParameters.howDidYouHearAboutUs = 'radio';
		changeStep('CurrentEnergyUsage');
	});
	
	$('#howDidYouHearAboutUs-facebook').click(function(){
		quoteParameters.howDidYouHearAboutUs = 'facebook';
		changeStep('CurrentEnergyUsage');
	});
	
	$('#howDidYouHearAboutUs-priceComparisonSite').click(function(){
		quoteParameters.howDidYouHearAboutUs = 'priceComparisonSite';
		changeStep('CurrentEnergyUsage');
	});
	
	$('#howDidYouHearAboutUs-referral').click(function(){
		quoteParameters.howDidYouHearAboutUs = 'referral';
		changeStep('CurrentEnergyUsage');
	});
	
	$('#howDidYouHearAboutUs-other').click(function(){
		quoteParameters.howDidYouHearAboutUs = 'other';
		changeStep('CurrentEnergyUsage');
	});
	
	/* Step 8 â€“ Current Energy Usage */
	
	$('#currentEnergyUsage-IKnowUsage').click(function(){
		quoteParameters.usage = null;
		quoteParameters.cost = null;
		quoteParameters.houseSize = null;
		changeStep('CurrentEnergyUsageInkWh');
	});
	
	$('#currentEnergyUsage-IKnowSpend').click(function(){
		quoteParameters.usage = null;
		quoteParameters.cost = null;
		quoteParameters.houseSize = null;
		changeStep('CurrentEnergyUsageInPounds');
	});
	
	$('#currentEnergyUsage-IDontKnow').click(function(){
		quoteParameters.usage = null;
		quoteParameters.cost = null;
		quoteParameters.houseSize = null;
		changeStep('HouseSize');
	});
	
	/* Step 9 â€“ Current Energy Usage in kWh */
	
	$('#step-CurrentEnergyUsageInkWh .continue-button').click(function(){
		var valid = true;
		
		var usage = {};
		
		$("#error-gas-kWh").addClass("hidden");
		$("#error-elec-kWh").addClass("hidden");
		
		if(quoteParameters.fuelRequirements == 'gas' || quoteParameters.fuelRequirements == 'both')
		{
			var gasUsage = parseFloat($('#kWh-details-gas').val());
			if(isNaN(gasUsage))
			{
				$("#error-gas-kWh").removeClass("hidden");
				valid = false;
			}
			else if($("#kWh-details-gas-per").val() == "month")
			{
				gasUsage*=12;
			}
			usage.gas = gasUsage;
		}
		
		if(quoteParameters.fuelRequirements == 'elec' || quoteParameters.fuelRequirements == 'both')
		{
			var elecUsage = parseFloat($('#kWh-details-elec').val());
			if(isNaN(elecUsage))
			{
				$("#error-elec-kWh").removeClass("hidden");
				valid = false;
			}
			else if($("#kWh-details-elec-per").val() == "month")
			{
				elecUsage*=12;
			}
			usage.elec = elecUsage;
		}
		
		if(valid)
		{
			quoteParameters.usage = usage;
			loadQuote(quoteParameters);
		}
	});
	
	/* Step 10 â€“ Current Energy Usage in Pounds */
	
	$('#step-CurrentEnergyUsageInPounds .continue-button').click(function(){
		var valid = true;
		
		var cost = {};
		
		$("#error-gas-cost").addClass("hidden");
		$("#error-elec-cost").addClass("hidden");
		
		if(quoteParameters.fuelRequirements == 'gas' || quoteParameters.fuelRequirements == 'both')
		{
			var gasCost = parseFloat($('#cost-details-gas').val());
			if(isNaN(gasCost))
			{
				$("#error-gas-kWh").removeClass("hidden");
				valid = false;
			}
			else if($("#cost-details-gas-per").val() == "month")
			{
				gasCost*=12;
			}
			cost.gas = gasCost;
		}
		
		if(quoteParameters.fuelRequirements == 'elec' || quoteParameters.fuelRequirements == 'both')
		{
			var elecCost = parseFloat($('#cost-details-elec').val());
			if(isNaN(elecCost))
			{
				$("#error-elec-cost").removeClass("hidden");
				valid = false;
			}
			else if($("#cost-details-elec-per").val() == "month")
			{
				elecCost*=12;
			}
			cost.elec = elecCost;
		}
		
		if(valid)
		{
			quoteParameters.cost = cost;
			loadQuote(quoteParameters);
		}
	});
	
	/* Step 11 â€“ House size */
	
	$('#houseSize-small').click(function(){
		quoteParameters.houseSize = 'small';
		loadQuote(quoteParameters);
	});
	
	$('#houseSize-medium').click(function(){
		quoteParameters.houseSize = 'medium';
		loadQuote(quoteParameters);
	});
	
	$('#houseSize-large').click(function(){
		quoteParameters.houseSize = 'large';
		loadQuote(quoteParameters);
	});
	
	/* Step 12 â€“ Summary */
	
	function loadQuote(quoteParameters)
	{
		$('#step-Summary #loading').removeClass('hidden');
		$('#step-Summary #tariff-details').addClass('hidden');
		
		changeStep('Summary');
		
		$.ajax({
			url: "compare-prices.php",
			type: 'post',
			data: JSON.stringify(quoteParameters),
			dataType: "json",
			contentType: "application/json; charset=UTF-8",
			success: function(data, textStatus, jqXHR){
				if(jqXHR.status == 200)
				{
					if(data.html != null)
					{
						$("#step-Summary #tariff-details").html(data.html.tariff);
						$("#tariff-info").html(data.html.tariffInfo);
						$('#step-Summary #loading').addClass('hidden');
						$('#step-Summary #tariff-details').removeClass('hidden');
					}
					else
					{
						window.location.href = "issue.php";
					}
				}
				else
				{
					window.location.href = "issue.php";
				}
			}
		});
	}
	
	window.onpopstate = function(event) {
		var oldStep = currentStep;
		var oldIndex = steps.indexOf(oldStep);
		
		var newStep = event.state.step;
		var newIndex = steps.indexOf(newStep);
		
		var diff = newIndex - oldIndex;
		
		if(diff > 0)
		{
			window.history.back();
		}
		else
		{
			currentStep = newStep;
			animateChangeToStep(oldStep, currentStep);
		}
	};
	
	function changeStep(step)
	{
		if(!freeze)
		{
			freeze = true;
			var oldStep = currentStep;
			currentStep = step;
			history.pushState({step:currentStep}, "page "+currentStep, "energy-quotation.php?step="+currentStep);
			
			animateChangeToStep(oldStep, currentStep);
		}
	}
	
	function previousStep()
	{
		if(!freeze)
		{
			window.history.go(-1);
		}
	}
	
	function animateChangeToStep(oldStep, newStep) {
		$('#step-'+oldStep).addClass('hiding');
		
		setTimeout(function(){
			$('#step-'+oldStep).addClass('hidden');
			$('#step-'+newStep).removeClass('hiding');
			$('#step-'+newStep).removeClass('hidden');
			freeze = false;
		}, animationDelay);
	}
}

/* Switch page */

function isEmail(email) {
  var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return regex.test(email);
}

var switchLock = false;

$('#switch-now').click(function(){
	if(!switchLock)
	{
		switchLock = true;
		$("#error-email-required").addClass("hidden");
		$("#error-email-invalid").addClass("hidden");
		$("#error-email-confirmation").addClass("hidden");
		$("#error-title-required").addClass("hidden");
		$("#error-forename-required").addClass("hidden");
		$("#error-surname-required").addClass("hidden");
		$("#error-dob-required").addClass("hidden");
		$("#error-dob-invalid").addClass("hidden");
		$("#error-phone-required").addClass("hidden");
		$("#error-phone-invalid").addClass("hidden");
		$("#error-card-details-account-number").addClass("hidden");
		$("#error-card-details-sort-code").addClass("hidden");
		$('#error-card-details-invalid').addClass("hidden");
		$("#error-terms-checkbox").addClass("hidden");
		
		var valid = true;
		
		var email = $("#email").val().trim();
		var emailConfirmation = $("#email-confirmation").val().trim();
		if(email == "")
		{
			$("#error-email-required").removeClass("hidden");
			valid = false;
		}
		else if(!isEmail(email))
		{
			$("#error-email-invalid").removeClass("hidden");
			valid = false;
		}
		else if(email != emailConfirmation)
		{
			$("#error-email-confirmation").removeClass("hidden");
			valid = false;
		}
		
		var nameTitle = $("#name-title option:selected").val();
		if(nameTitle == "")
		{
			$("#error-title-required").removeClass("hidden");
			valid = false;
		}
		
		var forename = $("#forename").val().trim();
		if(forename == "")
		{
			$("#error-forename-required").removeClass("hidden");
			valid = false;
		}
		
		var surname = $("#surname").val().trim();
		if(surname == "")
		{
			$("#error-surname-required").removeClass("hidden");
			valid = false;
		}
		
		var dob = $("#dob").val().trim();
		var dobStandard = null;
		if(dob == "")
		{
			$("#error-dob-required").removeClass("hidden");
			valid = false;
		}
		else
		{
			if(!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dob))
			{
				$("#error-dob-invalid").removeClass("hidden");
				valid = false;
			}
			else
			{
				function formatDate(d)
				{
					var dd = d.getDate();
					var mm = d.getMonth()+1; //January is 0!

					var yyyy = d.getFullYear();
					if(dd<10){
						dd='0'+dd;
					} 
					if(mm<10){
						mm='0'+mm;
					} 
					return mm+'/'+dd+'/'+yyyy;
				}
				
				var dobSplit = dob.split('/')
				var dobDate = new Date(dobSplit[2], dobSplit[1] - 1, dobSplit[0]);
				dobStandard = formatDate(dobDate);
			}
		}
		
		var phoneNumber = $("#phone-number").val().replace(" ", "");
		var mobileNumber = $("#mobile-number").val().replace(" ", "");
		if(phoneNumber == "" && mobileNumber=="")
		{
			$("#error-phone-required").removeClass("hidden");
			valid = false;
		}
		
		var cardDetails = null;
			
		if($("#card-details").length > 0)
		{
			cardDetails = {
				accountNumber: $("#account-number").val().trim(),
				sortCode: $("#sort-code").val().trim(),
			};
			$("#error-payment-method").addClass("hidden");
			if(cardDetails.accountNumber == "")
			{
				$("#error-card-details-account-number").removeClass("hidden");
				valid = false;
			}
			if(cardDetails.sortCode == "")
			{
				$("#error-card-details-sort-code").removeClass("hidden");
				valid = false;
			}
		}
		
		if(!$("#terms-checkbox").is(':checked'))
		{
			$("#error-terms-checkbox").removeClass("hidden");
			valid = false;
		}
		
		if(valid)
		{
			var request = {
				email:email,
				name:{
					title:nameTitle,
					forename:forename,
					surname:surname
				},
				dobUK:dob,
				dob:dobStandard,
				phoneNumber:phoneNumber,
				mobileNumber:mobileNumber,
				cardDetails:cardDetails
			};
			
			$.ajax({
				url: "complete-switch.php",
				type: 'post',
				data: JSON.stringify(request),
				dataType: 'json',
				contentType: "application/json; charset=UTF-8",
				success: function(data, textStatus, jqXHR){
					$('#section_packages').removeClass("hidden");
					switchLock = false;
					if(jqXHR.status == 200)
					{
						if(data.response == null)
						{
							window.location.href = "issue.php";
						}
						else if(data.response.Message == 'ERROR: Sorry, invalid bank details.')
						{
							$('#error-card-details-invalid').removeClass("hidden");
						}
						else if(data.response.Message == 'ERROR: Sorry, this landline or mobile number is not valid.')
						{
							$('#error-phone-invalid').removeClass("hidden");
						}
						else if(data.response.Message == 'SUCCESS') 
						{
							window.location.href = "congrats.php";
						}
						else
						{
							window.location.href = "issue.php";
						}
					}
					else
					{
						window.location.href = "issue.php";
					}
				}
			});
		}
		else
		{
			switchLock = false;
		}
	}
});

/* Free boiler page */

$('.benefits-option').change(benfitOptionsUpdated);

function benfitOptionsUpdated() {
	if($('#benefits-tax-credit').is(':checked')) {
		$('.tax-credits').show();
	}
	else
	{
		$('.tax-credits').hide();
	}
	if($('#benefits-universal-credit').is(':checked')) {
		$('.universal-credit').show();
	}
	else
	{
		$('.universal-credit').hide();
	}
	if($('#benefits-pension').is(':checked')
	|| $('#benefits-job-seekers').is(':checked')
	|| $('#benefits-income-support').is(':checked')
	|| $('#benefits-esa').is(':checked')
	|| $('#benefits-tax-credit').is(':checked')
	|| $('#benefits-universal-credit').is(':checked')) {
		$('.benefits-property-type').show();
	}
	else
	{
		$('.benefits-property-type').hide();
	}
}

benfitOptionsUpdated();

var tcIncomeThresholds = {
	'single':{
		'0':13200,
		'1':17400,
		'2':21600,
		'3':25800,
		'4 or more':30000,
	},
	'joint':{
		'0':19800,
		'1':24000,
		'2':28200,
		'3':32400,
		'4 or more':36000,
	}
}

$('#tc-children, input[name=tc-single-joint]:radio').click(function(){
	var numberOfChildren = $('#tc-children').val();
	var singleJoint = $('input[name=tc-single-joint]:checked').val();
	var tcIncomeThreshold = tcIncomeThresholds[singleJoint][numberOfChildren];
	var tcIncomeThresholdFormatted = tcIncomeThreshold.toLocaleString('en-UK', {minimumFractionDigits: 0});
	$('.tc-income-threshold').text(tcIncomeThresholdFormatted);
	$('input[name=tc-below-threshhold]:checked').attr('checked', false);
});

$('.vid-video').on('loadstart',function(){
	$(this).get(0).play();
});

/* Quotation page updates */

// LOGIN
jQuery(document).ready(function(){
        jQuery('#proceedWithLogin').on('click', function(event) {    			
			var email = $("#username").val().trim();
			if (email = "") {
				$("#error-username").removeClass("hidden");
			} else {
				$("#error-username").addClass("hidden");
			}

			var password = $("#password").val().replace(" ", "");
			if (password = "") {
				$("#error-password").removeClass("hidden");
				return;
			} else {
				$("#error-password").addClass("hidden");
			}

			proceedWithLogin();	
			

			//WHEN SUCCESSFUL LOGIN
	// 		//hide the current fieldset with style
	// jQuery(activeSectionClassId).animate({opacity: 0}, {
	// 	step: function(now, mx) {
	// 		//as the opacity of current_fs reduces to 0 - stored in "now"
	// 		//1. scale current_fs down to 80%
	// 		scale = 1 - (1 - now) * 0.2;
	// 		//2. bring next_fs from the right(50%)
	// 		left = (now * 50)+"%";
	// 		//3. increase opacity of next_fs to 1 as it moves in
	// 		opacity = 1 - now;
	// 		jQuery(activeSectionClassId).css({'transform': 'scale('+scale+')'});
	// 		jQuery(nextSectionClassId).css({'left': left, 'opacity': opacity});
	// 	}, 
	// 	duration: 800, 
	// 	complete: function(){
	// 		jQuery(activeSectionClassId).addClass("hidden");
	// 		jQuery(activeSectionClassId).css('opacity', '1.0');
	// 		jQuery(nextSectionClassId).removeClass("hidden");
	// 		animating = false;
	// 	}, 
	// 	//this comes from the custom easing plugin
	// 	easing: 'easeInOutBack'
	// });

        });

jQuery('#changepasswordform').submit(function(event)
{
	event.preventDefault();
	jQuery('.ajax_loader').show();
	$.ajax({
		url: 'changepassword.php',
		type: 'post',
		data: jQuery('#changepasswordform').serialize(),
		success: function(result)
		{
			console.log(result);
			if( result == 'User, '+$('#email').val()+', created.' )
			{
				jQuery('#login_div').hide();
				jQuery('.ajax_loader').hide();
				jQuery('#div_text').css('display', 'block');
			}
			else
			{
				jQuery('.ajax_loader').hide();
				$('#error_msg').html(result);	
			}
		}
	});
});



jQuery('#switch_text').click(function(){
	jQuery('#div_text').hide();
	jQuery('.ajax_loader').show();
	setTimeout(function(){  
			jQuery('.ajax_loader').hide();
			jQuery('#change_password_div').css('display', 'block');
	 }, 2000);
});



        
    });



function proceedWithLogin() {
	var email = $("#username").val().trim();
	var password = $("#password").val().replace(" ", "");

	$('#input-fields').addClass("hidden");
	$('#ajax_loader').removeClass("hidden");
	$('#error-auth').addClass("hidden");
	$('#proceedWithLogin').addClass("hidden");
	

	$.ajax({
							
							url: "login.php",
							type: 'post',
							data: JSON.stringify({
								username: email,
								password: password
							}),
							contentType: "application/json; charset=UTF-8",
							success: function(data, textStatus, jqXHR) {
								$('#error-auth').addClass("hidden");
								$('#account-login').addClass("hidden");
								$('#account-section').removeClass("hidden");
								if(jqXHR.status == 200 && data != null) {
									$("#account-info").html(data);	
								}
						},
						error: function(XMLHttpRequest, textStatus, errorThrown) { 
							$('#error-auth').removeClass("hidden");
							$('#input-fields').removeClass("hidden");
							$('#ajax_loader').addClass("hidden");
							$('#proceedWithLogin').removeClass("hidden");
						}
						});
						
}

function checkIfValidLogin() {

}





//LOGIN END


/***********************************************
	Additional Stuff I found in random files.
************************************************/

$(document).ready(function(){


	$('.btnClickNew').click( function() {
		$(".main.main-raised").addClass("mainToggle");
	} );
	$('.close').click( function() {
		$(".main.main-raised").removeClass("mainToggle");
	});

	//resetting the form values on close click
	$('.close').click(function(){
		$('#frm_callback')[0].reset();
	});

	$('#frm_callback').submit(function(e){
		e.preventDefault();
		$.ajax({
			url: 'ajax/mail.php',
			type: 'post',
			data: $('#frm_callback').serialize(),
			success: function(res)
			{
				if(res=='done')
				{
					$('#sucessMsg').html('<p style="color:green; font-weight:bold; text-align: center;">Email Sent </p>');
					setTimeout(function(){ $('#sucessMsg').html(' ') }, 3000);
				}
				if( res=='fail' )
				{
					$('#sucessMsg').html('<p style="color:red; font-weight:bold; text-align: center;">Email Send Fail </p>');
					setTimeout(function(){ $('#sucessMsg').html(' ') }, 3000);
				}
			}
		});
	});


	$('#Form_PostCode').submit(function(e){
		e.preventDefault();
		$('#proceedToQuotation').trigger('click');
	});

	$('#account-number').keypress(function()
	{
		$('.error_1').text(' NOTE: Your first direct debit payment will be taken on the day your switch goes live.');
	});

	$('#sort-code-number').keypress(function()
	{
		$('.error_2').text(' NOTE: Your first direct debit payment will be taken on the day your switch goes live.');
	});

	
jQuery('#query_form').submit(function(e){
	e.preventDefault();
	jQuery.ajax({
		url: '/queryForm.php',
		type: 'post',
		data: jQuery('#query_form').serialize(),
		success: function(response)
		{
			//alert(response);
			if(response == 1)
			{
				jQuery('#query_form')[0].reset();
				alert( 'Thanks, We will get back to you soon.' );
			}
			else
			{
				alert( 'Email sending fail, Contact Us at sales@eversmartenergy.co.uk' );
			}
		}
	});
});
	
});
