// get the base url
var baseUrl = $('base').attr('href');

function addressArray(data) {
    this.id = parseInt(data.id);
    this.address = data.address[0];
}

var addressFinder = {
    addresses: [],
    api: new Jamiedia.RPC({url: baseUrl + 'api/FindAddress'}),
    lookupPostcode: function() {
    
    var formPostcode = $('#postcode').attr('value');
    addressFinder.api.invoke('getAddresses', {postcode : formPostcode}, function(data) {
		if (data=="[]"){
			alert("Please enter a valid postcode");
			Loader.hide();
		}else{
			array = eval(data);
			
			for (var i = 0, l = array.length; i < l; i++) {
			addressFinder.addresses[i] = new addressArray(array[i]);
			}
			
			$('#addressList option').remove();
			
			if(addressFinder.addresses.length > 0) {
			$('#addressList').append('<option value="Please Choose">Please Choose</option>');
			for (var i = 0, l = addressFinder.addresses.length; i < l; i++) {
				
				$('#addressList').append('<option value="' + addressFinder.addresses[i].address + '">' + addressFinder.addresses[i].address + '</option>');
			}
			
			$('#addressList').fadeIn('slow');
			Loader.hide();
			} 
		}
    });
    }
}

$(document).ready(function() {
    if(jQuery.browser.msie && parseInt(jQuery.browser.version, 10) == 6) {
    $('#wrap').each( function() {
        $(this).attr('writing-mode', 'tb-rl');
        $(this).css('background-image', 'none');
        $(this).css( 'filter', 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="http://dev.jamiedia.co.uk/redlime/application/resources/styles/wrap-bg.png",sizingMethod="scale")');
    });
    try {
      document.execCommand("BackgroundImageCache", false, true);
    } catch(err) {}
    }    
    
     //Boolean for the status of the login box
    var loginToggleStatus = false;
    //Amount of time for text to fade in and out
    var textFadeDelay = 500;
    //For required fields with errors
    var formErrors = 0;
    //Boolean for the email error message
    var emailError = true;
    var emailValError = true;
    //Booleans for showing and hiding the loan calculator/application form
    var calcToggleStatus = false;
    var appToggleStatus = false;
 
 
    $('.against-image h3').hide();
    $('#applicationFormErrors').hide();
    $('#submit-application').hide();
    if (location.href.match(/how-does-it-work/) != null) {
        $('#loan-application-form').show();
    } 
    
    $('#what-we-loan-against DIV').mouseenter(function() {
        var hoveredItem = ($(this).attr('id'));
        $('#' + hoveredItem + ' h3').fadeIn(textFadeDelay), { queue:false, duration:1000 };
    })
    
    $('#what-we-loan-against DIV').mouseleave(function() {
        var hoveredItem = ($(this).attr('id'));
        $('#' + hoveredItem + ' h3').fadeOut(textFadeDelay), { queue:false, duration:1000 };
    })
    
    $('#addressList').change(function () {
        var address = '';
        $("#addressList option:selected").each(function () {
        address += $(this).text() + '';
        });
    
        $('#address').attr('value', address);
        
        $(this).fadeOut('slow');
        
        if($('#address').attr('value') != '') {
        Loader.hide();
        }
    })  
    
    //Create an array of all required inputs
    var inputs = $('.required');	    
    $('#confirmEmailMessage').hide();
    $('#emailMessage').hide();
    
    function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
    }    
    
 
   
    $('.app-email').blur(function () {
		if(isValidEmailAddress($('.app-email').attr('value'))) {
			$('#emailMessage').customFadeOut('slow');
			emailValError = false;
		}
    });
    
    $('.required').keyup(function () {
	for(var i = 0; i < inputs.length; i++) {
	    if(inputs[i].value == '') {
		formErrors++;
	    }
	}
		if(formErrors == 0 && emailValError == true) {
		$('#applicationFormErrors').html('Please correct any errors');	} else {		$('#applicationFormErrors').html(formErrors + ' required fields need completing.');	}
	
	if(formErrors != 0 || emailValError == true) {
	    $('#applicationFormErrors').customFadeIn('slow');
	    $('#submit-application').slideUp('slow');
	} else if(formErrors == 0 && emailValError == false) {
	    $('#applicationFormErrors').slideUp('slow');
	    $('#submit-application').slideDown('slow');
	}
	
	formErrors = 0;
    });
    $('.required').click(function () {
	for(var i = 0; i < inputs.length; i++) {
	    if(inputs[i].value == '') {
		formErrors++;
	    }
	}
		if(formErrors == 0 && emailValError == true) {
		$('#applicationFormErrors').html('Please correct any errors');	} else {		$('#applicationFormErrors').html(formErrors + ' required fields need completing.');	}
	
	if(formErrors != 0 || emailValError == true) {
	    $('#applicationFormErrors').customFadeIn('slow');
	    $('#submit-application').slideUp('slow');
	} else if(formErrors == 0 && emailValError == false) {
	    $('#applicationFormErrors').slideUp('slow');
	    $('#submit-application').slideDown('slow');
	}
	
	formErrors = 0;
    });	
	
    
    $('.login-toggle').click(function() {
	if (loginToggleStatus == false) {
	    $('#login').customFadeIn(400);
	    loginToggleStatus = true;
	} else {
	    $('#login').customFadeOut(700);
	    loginToggleStatus = false;
	}
    });
	
	$('.app-toggle').click(function() {
	if(appToggleStatus == false) {
	    appToggleStatus = true;
	    $('#loan-application-form').slideToggle(700);
	    $('#loan-calc-form').slideToggle(700);
        $('#li-link').html('Please fill out the form on the right');
	} else {
	    appToggleStatus = false;
	    $('#loan-application-form').slideToggle(700);
	    $('#loan-calc-form').slideToggle(700);
        $('#li-link').html('Click to apply in under one minute');
	}
    });
    

    $('#addressList').hide();
    
    $('.find-postcode').click(function() {
    addressFinder.lookupPostcode();
    Loader.show();
    })
    
    $('#addressList option').click(function () {
    var address = '';
    $("#addressList option:selected").each(function () {
        address += $(this).text() + '';
    });

    $('#address').attr('value', address);
    $('#address').fadeIn('slow');
    
    $(this).fadeOut('slow');
    })
  
    
    
    
    $('.calc-toggle').click(function() {
	if(calcToggleStatus == false) {
	    calcToggleStatus = true;
	    $('#loan-calc-form').slideToggle(700);
	    $('#loan-application-form').slideToggle(700);
	} else {
	    calcToggleStatus = false;
	    $('#loan-calc-form').slideToggle(700);
	    $('#loan-application-form').slideToggle(700);
	}
    }); 

	$('#submit-application').bind('click', function() {
		Loader.show();
	});		(function($) {		$.fn.customFadeIn = function(speed, callback) {			$(this).fadeIn(speed, function() {				if(jQuery.browser.msie)					$(this).get(0).style.removeAttribute('filter');				if(callback != undefined)					callback();			});		};		$.fn.customFadeOut = function(speed, callback) {			$(this).fadeOut(speed, function() {				if(jQuery.browser.msie)					$(this).get(0).style.removeAttribute('filter');				if(callback != undefined)					callback();			});		};})(jQuery);		
});
