
$(document).ready(function() {

    // Fixes Chrome issues with date validator validator method
    jQuery.extend(jQuery.validator.methods, {
        date: function(value, element) {
            //return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
            var d = new Date();
            return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
        }
    });

    // Add a postcode validator method
    jQuery.validator.addMethod("postcode", function(value, element) {
            return this.optional(element) || /^(GIR 0AA)|(((A[BL]|B[ABDHLNRSTX]?|C[ABFHMORTVW]|D[ADEGHLNTY]|E[HNX]?|F[KY]|G[LUY]?|H[ADGPRSUX]|I[GMPV]|JE|K[ATWY]|L[ADELNSU]?|M[EKL]?|N[EGNPRW]?|O[LX]|P[AEHLOR]|R[GHM]|S[AEGKLMNOPRSTY]?|T[ADFNQRSW]|UB|W[ADFNRSV]|YO|ZE)[1-9]?[0-9]|((E|N|NW|SE|SW|W)1|EC[1-4]|WC[12])[A-HJKMNPR-Y]|(SW|W)([2-9]|[1-9][0-9])|EC[1-9][0-9]) [0-9][ABD-HJLNP-UW-Z]{2})$/.test(value);
        }, "Enter a valid UK postcode with a space."
    );

	$("input.postcode[type=text]").live("keyup", function(){
		$(this).val( this.value.toUpperCase());
	})

	// Create tabs and start them working
    $("#tabVehicleSearch").tabs();
	$("#tabNewVehicleSpec").tabs();
	$("#tabNewVehicleInfo").tabs();
	$("#tabUsedVehicleDetails").tabs();
	$("#tabLeasingVehicleDetails").tabs();

	// Generate GUID for intellitracker.
	if( typeof itGuid === 'undefined' ){
		itGenerateGuid();
	}

	$('#layout_stockUpdates_email').click(
		function(event) {
			if ($('#layout_stockUpdates_email').val() == '- Enter Email Here -') {
				$('#layout_stockUpdates_email').val('');
			}
		}
	);

	$("body").prepopulateLists();

	$(".init-validator").validate();

	// Work around for webkit scrollbar problem when using jquery ui dialog :|
	if ($.browser.webkit) {
		$('div[id*=dialog]').bind('dialogopen', function(){
			setTimeout(function(){
				$(document).unbind('mousedown.dialog-overlay').unbind('mouseup.dialog-overlay');
			}, 1);
		});
	}

	/**
	 * Files added in the CMS should open in a new window
	 */
	$( "a.new-window,.cmsDownloads a, .mce-container-file a" ).click( function(){
		window.open( this.href );
		return false;
	});

	$('.ui-dialog-buttonpane button').each( function () {
		var html = $(this).text();
		$(this).addClass('btn' + html);
		$(this).html('<span class="ui-button-text">' + html + '</span');
	});

	var buttons = $('.ui-dialog-buttonpane').children('button');
	buttons.removeClass('ui-button-text-only').addClass('ui-button-text-icon').addClass('ui-button');

	$("input.postcode[type=text]").live("paste change keyup", function(){
		this.value = this.value.toUpperCase()
	})

	$("tr.trOut").live("mouseover", function(){
		$(this).addClass("trOver").removeClass("trOut");
	});

	$("tr.trOver").live("mouseout", function(){
		$(this).removeClass("trOver").addClass("trOut");
	});
	updateRecentlyViewedItems();


    $('.ui-dialog-buttonpane button').each( function () {
		var html = $(this).text();
		$(this).attr('title', html);
	});
});


$.fn.prepopulateLists = function(){

	/**
	 * Looks for any form title fields and populates the title select box
	 */
	$( 'select.prePopulateTitleList', this ).each(function(){

		var $this = $(this);

		var defaultVal = $this.val();

		// Remove all options
		$("option", $this).remove();

		$this.append( $("<option value=''>- Select Title -</option>") );

		// Add Options
		$.each(selectTitleList, function(i,item){

			var option = $("<option>").text(item.title)

			if( item.title == defaultVal ){
				option.attr("selected", true);
			}

			$this.append( option );
		});

		if( !defaultVal ){
			$this.attr( "selectedIndex", 0);
		}

	});


	/**
	* Looks for any form country fields and populates the country select box
	*/
	$( '.prePopulateCountryList', this ).each(function(){

		var thisSelection = '#' + this.id;
		// Remove all options
		$( thisSelection ).removeOption(/./).addOption('', '- Select Country -').addOption('United Kingdom', 'United Kingdom');

		// Add Options
		$.each(selectCountryList, function(i,item){
			$( thisSelection ).addOption(item.country, item.country);
		});
		$( thisSelection ).attr( "selectedIndex", 0);
	});


	/**
	* Looks for any form county fields and populates the county select box
	*/
	$( '.prePopulateCountyList', this ).each(function(){

		var thisSelection = '#' + this.id;
		// Remove all options
		$( thisSelection ).removeOption(/./).addOption('', '- Select County -');

		var currentCountry = '';
		var text = '';

		// Add Options
		$.each(selectCountyList, function(i,item){

			if( currentCountry != item.country ){
				if( i > 0 ){
					text += '</optgroup>';
				}
				text += '<optgroup label="' + item.country + '">';
				currentCountry = item.country;
			}
			text += '<option value="' + item.county + '">' + item.county + '</option>';
		});
		text += '</optgroup>';
		$( thisSelection ).html(text);
		$( thisSelection ).attr( "selectedIndex", 0);
	});


	/**
	* Looks for any form country field and adjusts the county fields accordingly
	*/
	$( '.prePopulateCountryList', this ).change(function(){

		// Find the formId of the form this element sits in
		var thisFormId = '#' + $( this ).get( 0 ).form.id;

		// Then adjust the county field where necessary
		if( this.options[ this.selectedIndex].value == 'United Kingdom' ){
			$( thisFormId + ' .countySelectboxField').show();
            $( thisFormId + ' .countySelectboxField select').attr('name', 'county');
            $( thisFormId + ' .countyInputField input').addClass('required');
			$( thisFormId + ' .countyInputField').hide();
            $( thisFormId + ' .countyInputField input').attr('name', '');
            $( thisFormId + ' .countyInputField input').removeClass('required');

		}else{

			$( thisFormId + ' .countySelectboxField').hide();
            $( thisFormId + ' .countySelectboxField select').attr('name', '');
            $( thisFormId + ' .countyInputField input').removeClass('required');
			$( thisFormId + ' .countyInputField').show();
            $( thisFormId + ' .countyInputField input').attr('name', 'county');
            $( thisFormId + ' .countyInputField input').addClass('required');
		}
	});

	return this;
}


/**
 * @todo: modify most of the code below into a more jquery-esque way of thinking.
 */

/**
* @ desc This will attempt to open a dialog form via passed in ids
*/
function openDialogForm( dialogName, formName, alertBoxName ){

	if( dialogName != '' && formName != '' ){

		// Clear the form values
		clearFormElements('#' + formName);

		// Removes validation messages
		var validator = $('#' + formName).validate();
		if(validator){
			validator.resetForm();
		}

		if( alertBoxName != '' ){

			// Clear Alert Box Text
			resetTips( alertBoxName, true );
		}

		// Open the dialog box
		$('#' + dialogName ).dialog('open');

		// highlight first input
		$('#' + dialogName + ' :input:text:first').focus();
	}
}


function displayFormCaptchaImage( formElementId ){

	var form = $(formElementId)

	if( form.length && $('div.captcha', form).length ){

		var target = '/' + netdirector.franchiseUrl + 'frontend-operations/get-form-captcha-image/';

		$.getJSON(target,
		function(data){
			//If data is null, then captcha is turned off.
			if(data){
				if( data.id && $( 'input[name=sc[id]]', form ).length  ){

					$('input[name=sc[id]]', form ).val( data.id );

				}

				if( data.image && $('div.captcha div.captchaImage', form).length ){

					$('div.captcha div.captchaImage', form).html( data.image );

					if( $('div.captcha:hidden', form).length ){

						$('div.captcha', form).animate({
							opacity: 'toggle',
							height: 'toggle'
						},500);
					}
				}
			}

		});

	}
}


/**
* @ desc This updates the dialog alert box, passes in a header, text, type of msg, and optional input to highlight
*/
function updateTips(header,text,msgType,highlightInput,alertBoxId) {

	// Clear Alert Box Text
	resetTips(alertBoxId);

	var alertBox = ( alertBoxId != null && alertBoxId != '' ) ? $('#'+alertBoxId) : $('#dialogAlertBox');

	txt = '<strong>'+header+':</strong> '+ text;
	switch( msgType ){
		case 'error':
			msg = "<p>" + txt + "</p>";
			alertBox.addClass('ui-state-error').html(msg);
		break;

		case 'highlight':
			msg = "<p>" + txt + "</p>";
			alertBox.addClass('ui-state-highlight').html(msg);
		break;

		default:
			console.log('Error: No valid message type set');
		break;
	}

	if( highlightInput != '' ){
		$('#' + highlightInput).addClass('ui-state-error');
	}

	alertBox.slideDown(200);
}


/**
* @ desc This Resets the dialog alert box
*/
function resetTips(alertBoxId, close) {

	alertBox = ( alertBoxId != null && alertBoxId != '' ) ? $('#'+alertBoxId) : $('#dialogAlertBox');
	alertBox.removeClass('ui-state-error ui-state-highlight').html('');

	if (typeof close !== 'undefined' && !close) {
		alertBox.css('display', 'none');
	}
}


/**
* @ desc This will close the dialog box
*/
function autoCloseDialog(dialogFormType){

	$( "#" + dialogFormType ).dialog('close');
}


/**
* @ desc This will empty all form elements
*/
function clearFormElements(el) {

	$(el).find(':input').each(function() {
		switch(this.type) {
			case 'password':
			case 'select-multiple':
			case 'select-one':
			case 'text':
			case 'textarea':
				$(this).val('');
				break;
			case 'checkbox':
			case 'radio':
				this.checked = false;
		}
		$(this).removeClass('ui-state-error');
	});
}


/**
* @ desc This is a generic ajax request function
*/
function ndCollector( target, params, successFunction, errorFunction ){

	$.ajax({
		url: target,
		dataType: 'json',
		data: params,
		success: successFunction,
		error: errorFunction
	});
}




/**
* @ desc This will collect All Models under a particular Make
*/
function collectAllModels(elementId, marqueId, isVan, selectedId){

	var modelId = $( elementId );
	modelId.attr('disabled', 'disabled');

	$.ajax({
		url: '/' + netdirector.franchiseUrl + 'frontend-operations/all-model-list/',
		dataType: 'json',
		data: 'marque_id=' + marqueId + '&is_van=' + isVan,
		success: function(data){

				// Remove all options
				modelId.removeOption(/./).addOption('', '- Select Model -');

				// Add Options
				$.each(data, function(i,item){

					modelId.addOption(item.id, item.modelName);
				});

				// If previously selected..
				if( selectedId != null && selectedId > 0){
					modelId.selectOptions(selectedId);
				}else{
					// select 1st one if only one available
					var preSelect = ( data.length == 1 ) ? 1: 0;
					modelId.attr( "selectedIndex", preSelect);
				}
				modelId.removeAttr('disabled');
			},
		error: function(objRequest){

			modelId.removeAttr('disabled').removeOption(/./).addOption('', '- Select Model -');
		}
	});
}


/**
* @ desc This will collect All Makes under a particular Vehicle Type
*/
function collectAllMakes(elementId, isVan, selectedId){

	var marqueId = $( elementId );
	marqueId.attr('disabled', 'disabled');

	$.ajax({
		url: '/' + netdirector.franchiseUrl + 'frontend-operations/all-marque-list/',
		dataType: 'json',
		data: 'is_van=' + isVan,
		success: function(data){

				// Remove all options
				marqueId.removeOption(/./).addOption('', '- Select Marque -');

				// Add Options
				$.each(data, function(i,item){

					marqueId.addOption(item.id, item.marqueName);
				});

				// If previously selected..
				if( selectedId != null && selectedId > 0){
					marqueId.selectOptions(selectedId);
				}else{
					// select 1st one if only one available
					var preSelect = ( data.length == 1 ) ? 1: 0;
					marqueId.attr( "selectedIndex", preSelect);
				}
				marqueId.removeAttr('disabled');
			},
		error: function(objRequest){

			marqueId.removeAttr('disabled').removeOption(/./).addOption('', '- Select Marque -');
		}
	});
}

/**
* @ desc Adds commas in the right places to make long prices presentable
*/
function addCommas(nStr){

	nStr += '';
	var x = nStr.split('.');
	var x1 = x[0];
	var x2 = ( x.length > 1 ) ? '.' + ( ( x[1].length == 1 )? x[1] + '0' : x[1] ) : '';
	var rgx = /(\d+)(\d{3})/;

	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}


/**
* @ desc Searches for passed in "word" within passed in "array" (used for intellisearch)
*/
function wordExists(arr, obj) {
	for(var i=0; i<arr.length; i++) {
		if( arr[i] != '' ){
			if (obj.search(arr[i]) >= 0) return true;
		}
	}
}


/**
* @ desc This will post the (custom cms) form via Ajax
*/
function submitCustomForm( formType ){

	if( formType == '' ){
		return;
	}

	// Check if form is valid before proceeding
	if( $( "#form" + formType ).valid() ){

		$('body').css('cursor', 'progress');

		$.ajax({
		  url: '/' + netdirector.franchiseUrl + 'frontend-operations/submit-form/',
		  dataType: 'json',
		  data: $( '#form' + formType ).serialize(),
		  success: function(data){

				if( data != 0 ){

					// Submitted ok.
					setupCustomForm( formType );
					updateTips('Thank You','Your details have been submitted successfully','highlight','','alertBox' + formType);

					if ( typeof itForm == 'function' ) {
						itForm(data.intellitracker);
					}

					//Google analytics tracking
					window._gaq = window._gaq || [];
					window._gaq.push(['_trackPageview',  netdirector.baseUrl + "/" + netdirector.franchiseUrl + 'submit-form/' + encodeURIComponent( formType ) ]);
				}else{

					// Show generic message
					updateTips('Request Failed','The request to submit failed, please try again.','error','','alertBox' + formType);
				}
				$('body').css('cursor', 'default');
			},
		error: function( objRequest ){
				updateTips('Request Failed','The request failed to submit, please try again.','error','','alertBox' + formType);
				$('body').css('cursor', 'default');
			}
		});
	}
}

/**
* @ desc This will setup form
*/
function setupCustomForm(formType){

	// Clear the form values
	clearFormElements('#form' + formType);

	// Removes validation messages
	var validator = $('#form' + formType).validate();
	validator.resetForm();

	// Clear Alert Box Text
	$('#alertBox' + formType).html('');

	// highlight first input
    //removed as causing page to jump down
	//$('#form' + formType + ' :input:text:first').focus();
}


/**
* @ desc This should start to be used for all form submits
*/
function globalSubmitForm( formType, successMsg ){

	if( !formType || !$( "#form" + formType ).length ){
		throw new Error("Invalid form(#form" + formType + "), cant submit data");
	}

	// Check if form is valid before proceeding
	if( $( "#form" + formType ).valid() && !$( "#form" + formType ).data('disable') ){

		var params = $( '#form' + formType ).serialize();

		globalFormStatus(formType, true);
		updateTips('<img src="/local/images/loading.gif" width="15" style="position:relative; display:inline; top:4px; margin:0 5px" />Submitting Form', '', 'highlight', '', 'alertBox' + formType);

		var formData = '';

		if( formType == 'ValueMyVehicle' ){

			var formData = 'my_make=' + $('#valuemyvehicle_my_make_id > option:selected').text() + '&my_model=' + $('#valuemyvehicle_my_model_id > option:selected').text() + '&';
		}

		$.ajax({
			url: '/' + netdirector.franchiseUrl + 'frontend-operations/submit-form/?ajax_submit=true',
			dataType: 'json',
			data: formData + params,
			type: "post",
			success: function(data){

				if( data.status == true ){

					if ( typeof itForm == 'function' ) {
						itForm(data.intellitracker);
					}
					// Submitted ok.
					successMsg = ( successMsg != null && successMsg != '' ) ? successMsg : 'Thank you for your enquiry. We will respond as soon as possible';
					updateTips('Successful', successMsg,'highlight','','alertBox' + formType);

					clearFormElements("#form" + formType);

					//Google analytics tracking
					window._gaq = window._gaq || [];
					window._gaq.push(['_trackPageview',  netdirector.baseUrl + "/" + netdirector.franchiseUrl + 'submit-form/' + encodeURIComponent( formType ) ]);

					setTimeout(function () {
						globalFormStatus(formType, false);
						autoCloseDialog('dialog' + formType);
					}, 4000);

				}else{

					displayFormCaptchaImage( '#form' + formType );

					if( data.error != null ){
						updateTips('Request Failed',data.error,'error','','alertBox' + formType);
					}else{
						updateTips('Request Failed','The request to submit failed, please try again.','error','','alertBox' + formType);
					}
					globalFormStatus(formType, false);
				}
			},
			error: function( objRequest ){
				updateTips('Request Failed','The submission request failed, please try again.','error','','alertBox' + formType);
				globalFormStatus(formType, false);
			}
		});
	}

}


/**
* @ desc Controls disabling of forms during submission process
*/
function globalFormStatus(formType, disable) {

	var id = '#form' + formType, height = 400;

	if (typeof formType === 'undefined') {
		return false;
	}
	var form = $(id);

	$(":input", form).attr("disabled", disable );

	if( disable ){
		form.add( form.closest(".ui-dialog").find(".ui-dialog-buttonpane") ).slideUp();
	}else{
		form.add( form.closest(".ui-dialog").find(".ui-dialog-buttonpane") ).show();
	}
}


/**
 *
 * Monthly repayment calculator, everything else int
 *
 * loanAmmount - the total ammount to be financed
 *
 * apr - the APR rate ( As a decimal e.g. 0.1 == 10% )
 *
 * term - number of months that the loan will last.
 */
function monthlyRepayments( principle, apr, term ){

	netdirector.monthlyRepayments = { principle : principle };

	//No principle will throw an error
	if( !( principle > 0 ) ){
		throw new Error("You must provide a principle greater than 0");
	}

	//No term means that there is no monthly repayment to make
	if( !term ){
		return 0;
	}

	//No APR means that you pay only the principle back each month.
	if( !( apr > 0 ) ){
		return principle / term;
	}

	var monthlyRate = apr/12;

	return Math.floor( ( principle * monthlyRate ) / ( 1 - Math.pow( ( 1 + monthlyRate ),( -1 * term ) ) ) * 100 ) / 100;
}





/**
 * Collect Recently viewed vehicles by Ajax
 */
function updateRecentlyViewedItems(){

	if( !$('.recentlyViewed .thumbs').length ){
		return;
	}
	var recentlyViewedVehicles = getCookie('recentlyViewedVehicles');
	var vehicleId = 0;

	if( netdirector.stockDetail  != null && netdirector.stockDetail.id ){

		vehicleId = netdirector.stockDetail.id;
	}

	if(!recentlyViewedVehicles){

		if( vehicleId == 0 ){
			return;
		}
		recentlyViewedVehicles = '{}';
	}
	
	$.ajax({
		url: '/' + netdirector.franchiseUrl + 'component-operations/get-recently-viewed-vehicles/',
		dataType: 'json',
		data: 'vehicleId=' + vehicleId + '&recentlyViewedVehicleIds=' + recentlyViewedVehicles,
		type: "post",
		success: function(data){

			var html = '';
			var endofRow = '';
			var vehicleUrl = '';

			if( data ){
				$.each(data, function(i,item){
					endofRow = ( (i+1) % parseInt(recentlyViewed.itemsPerRow) == 0 )? ' class="endItem"' : '';
					html += '<a ' + endofRow + ' title="' + item.marqueModelVariant + '" href="' + netdirector.baseUrl + '/' + recentlyViewed.area + '/' + item.id + '/' + item.marqueModelSafeUrl + '/">';

					if( item.imageSrc != null && item.imageSrc != '' ){
						html += '<img width="' + recentlyViewed.imageWidth + '" src="' + netdirector.baseUrl + '/upload/images/stock/small/' + item.imageSrc + '" alt="' + item.marqueModelVariant + '">';
					}else if( item.capDetails != null && parseInt( item.capId ) > 0 ){
						html += '<img src="http://images.capnetwork.co.uk/VehicleImage.aspx?SUBID=' + item.capDetails.username + '&amp;HASHCODE=' + item.capDetails.hash + '&amp;DB=' + item.capDetails.db + '&amp;CAPID=' + item.capId + '&amp;DATE=' + item.capDetails.date + '&amp;WIDTH=' + recentlyViewed.imageWidth + '&amp;HEIGHT=' + recentlyViewed.imageHeight + '&amp;IMAGETEXT=&amp;VIEWPOINT=" alt="' + item.marqueModelVariant + '" style="width: ' + recentlyViewed.imageWidth + 'px; height: ' + recentlyViewed.imageHeight + 'px;" />';
					}else{
						html += '<img src="' + netdirector.baseUrl + '/local/images/filler' + recentlyViewed.imageWidth + 'x' + recentlyViewed.imageHeight + '.jpg" alt="' + item.marqueModelVariant + '" />';
					}
					html += '<span class="frame"></span>';
					html += '</a>';
				});
			}

			html += '<div class="clear"></div>';
			$('.recentlyViewed .thumbs').html(html);
		},
		error: function( objRequest ){

		}
	});
}


/**
* Collect Cookie by Name
*/
function getCookie(name){
	var results = document.cookie.match ( '(^|;) ?' + name + '=([^;]*)(;|$)' );
	return results ? decodeURIComponent(results[2].replace(/\+/g, ' ')) : null;
}


//@hack Fix for not being able to scroll when a dialog is open in Chrome.
(function(){
	if( $.browser.webkit ){
		var oldCreate = $.ui.dialog.overlay.create;
		$.ui.dialog.overlay.create = function(){
			var r = oldCreate.apply(this, arguments);

			//Needs to happen after the bit below, which also runs a setTimeout
			setTimeout(function(){
				$([document, window]).unbind('.dialog-overlay');
			}, 1)

			return r;
		}
	}
})();



/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
(function(){
	jQuery.cookie=function(e,b,a){if(1<arguments.length&&"[object Object]"!==""+b){a=jQuery.extend({},a);if(null===b||void 0===b)a.expires=-1;if("number"===typeof a.expires){var d=a.expires,c=a.expires=new Date;c.setDate(c.getDate()+d)}b=""+b;return document.cookie=[encodeURIComponent(e),"=",a.raw?b:encodeURIComponent(b),a.expires?"; expires="+a.expires.toUTCString():"",a.path?"; path="+a.path:"",a.domain?"; domain="+a.domain:"",a.secure?"; secure":""].join("")}a=b||{};c=a.raw?function(a){return a}:decodeURIComponent; return(d=RegExp("(?:^|; )"+encodeURIComponent(e)+"=([^;]*)").exec(document.cookie))?c(d[1]):null};
})();
