/*
    ymme.js
    Copyright 2010 AutoZone, Inc.
    Content is confidential to and proprietary information of
    AutoZone, Inc., its subsidiaries and affiliates.
*/

/*
  Stubbed js object for YMME selection.

  EX: 4T1BE32K54U888829  1FMRU15W84LB50789  1N4BL11D35C232904  WDBJF70J41X055644  3VWED21C61M478028

  author slee
  version %PCMS_HEADER_SUBSTITUTION_START%$Id: %PM% %PR% %PRT% %PO% %PS% $%PCMS_HEADER_SUBSTITUTION_END%
*/

// Check and return params
function checkURIParams(param) {
	var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
	for(var i = 0; i < hashes.length; i++) {
		var hash = hashes[i].split('=');
		if(hash[0] == param) {
			return hash[1];
		}
	}
	return null;
}

function getVinValidation(vin) {
	//var minVinLength = 17; // This is the standard length for all VIN's
	var minVinLength = 10; // This is the length needed for the AZ service to find a match
	return (vin != null && vin != "" && vin.length >= minVinLength);
}


$(window).load(function(){
    $('input.alphanumeric').alphanumeric();

    var decoderArea = $('#vin-decoder-area'),
        decoder = $('#decoder'),
        link = $('#vin-decoder-link'),
        button = $('#btn-vin-disabled'),
        vin = decoder.val();

    decoder.focus(function() {
        decoder.val('');
        link.hide();
        button.show();
	});

    $(decoder).bind('paste', function(e) {
		setTimeout(function() {
			$(e.target).trigger('keyup');
		}, 200);
    })


	decoder.keyup(function() {
		var valid = getVinValidation(decoder.val());
		if (valid) {
			link.show().addClass("btn");
			button.hide();
		} else {
			link.hide();
			button.show();
		}
	});

	// This is for the VIN input that appears on the overlay
	$('input#decoder-input').live('keyup', function() {
		var valid = getVinValidation($('input#decoder-input').val());
		if (valid) {
			$('div.vin-decoder #vin-decoder-overlay-link').show();
			$('div.vin-decoder #vin-decoder-overlay-link').addClass("btn");
			$('div.vin-decoder #overlay-btn-go-disabled').hide();
		} else {
			$('div.vin-decoder #vin-decoder-overlay-link').hide();
			$('div.vin-decoder #overlay-btn-go-disabled').show();
		}

	});

	// Check URL for forceYMME param and display YMME popup if it occurs
	if (checkURIParams('forceYMME') != null && checkURIParams('forceYMME') == "true") {
		ymme.start();
	}

    link.click(function() {
        ymme.lookupVIN();
        return false;
    });

});

//This function will store the previous page's URL upon loading another page
//This was included due to AZPRO-867
window.onbeforeunload = function () {
	var previousURL =  window.location.href;
	$.cookies.set("previousURL", previousURL);
};

$(function() {
	$(".ymme-start-link").click(function() {
		var targetURL = $(this).attr('href');
		$.cookies.set("successURL", targetURL);
		ymme.start();
		return false;
	});

	$(".ymme-start-brand").click(function() {
  		if ($('input.part-checkbox').is(':checked'))
  		{
			var triggerSubmit = 'true';
			$.cookies.set("triggerSubmit", triggerSubmit);
			ymme.start();
			return false;
  		}
	});
});

var ymme = {
		start: function() {
			$('#dialog-ymme-vin').dialog('close');
			var frag = $("#dialog-ymme-year");
			$.get("/vehicle/ymme/overlay_year.jsp", function(data) {
				frag.html(data)
				$('input.alphanumeric').alphanumeric();
				$("#enter-vin").bind("focus", function(e) {
					$("#enter-vin").hide();
					$("#decoder-input").show();
					$("#decoder-input").focus();
				});
				$("#decoder-input").focus();
				$("#decoder-input").bind("keydown", function(e) {
					if (e.keyCode == 13 && getVinValidation($('input#decoder-input').val()))
						return ymme.lookupVINOverlay();
				});

				$('.ui-dialog-titlebar-close').click(function() {
					$.cookies.set("successURL", null);
					var currentVehicle = $("#current-vehicle-select").val();
					if (checkURIParams('forceYMME') != null && checkURIParams('forceYMME') == "true") {
						var redirect = $.cookies.get("previousURL");
						$.cookies.set("previousURL", null);
						location.replace(redirect);
					}
				});
			});
			ymme.emptyAll();
			$('#dialog-ymme-year').dialog('open');
			omniture.st({pageName: 'azpro:ymme:year'});

			return false; // stop link href
		},

		startError: function(vinError, redirectURL) {
			$('#dialog-ymme-vin').dialog('close');
			omniture.st({pageName: 'azpro:ymme:vin error', events: 'event13'});
			//Need to find the YMME step the user was on before the VIN step was chosen
			//Force the type to be a string -- wlll be something like _year.jsp or _make.jsp
			var temp = "" + redirectURL.match(/_.*jsp/i);
			var ymmeStep = temp.slice(1,temp.length-4);//Get rid or the '_' & '.jsp'

			//In case you are coming from somewhere other than the YMME overlay (i.e. myZone or VIN overlay)
			if (redirectURL == null || redirectURL == "" || ymmeStep == "vinDecoder") {
				redirectURL = "/vehicle/ymme/overlay_year.jsp";
				ymmeStep = "year";
			}

			var frag = $("#dialog-ymme-"+ymmeStep);//Dynamically create the proper selector
			$.get(redirectURL, {vinError: true}, function(data) {
				frag.html(data);
				$('input.alphanumeric').alphanumeric();
				$("#enter-vin").bind("focus", function(e) {
					$("#enter-vin").hide();
					$("#decoder-input").show();
					$("#decoder-input").focus();
				});
				$("#decoder-input").focus();
				$("#decoder-input").bind("keydown", function(e) {
					if (e.keyCode == 13 && getVinValidation($('input#decoder-input').val()))
						return ymme.lookupVINOverlay();
				});

				$('.ui-dialog-titlebar-close').click(function() {
					$.cookies.set("successURL", null);
					var currentVehicle = $("#current-vehicle-select").val();
					if (checkURIParams('forceYMME') != null && checkURIParams('forceYMME') == "true") {
						var redirect = $.cookies.get("previousURL");
						$.cookies.set("previousURL", null);
						location.replace(redirect);
					}
				});
			});
			ymme.emptyAll();
			$('#dialog-ymme-' + ymmeStep).dialog('open');//Dynamically open the proper dialog
			omniture.st({pageName: 'azpro:ymme:' + ymmeStep});
			return false; // stop link href
		},

		submitYear: function(ymmeYearId, ymmeYearName) {
			var frag = $("#dialog-ymme-make");
			$.get("/vehicle/ymme/overlay_make.jsp", {yearNodeId: ymmeYearId, yearName:ymmeYearName, forceYMME: "inprogress"}, function(data) {
				frag.html(data);
				$('input.alphanumeric').alphanumeric();
				$("#enter-vin").bind("focus", function(e) {
					$("#enter-vin").hide();
					$("#decoder-input").show();
					$("#decoder-input").focus();
				});
				$("#decoder-input").focus();
				$("#decoder-input").bind("keydown", function(e) {
					if (e.keyCode == 13 && getVinValidation($('input#decoder-input').val()))
						return ymme.lookupVINOverlay();
				});

				$('.ui-dialog-titlebar-close').click(function() {
					$.cookies.set("successURL", null);
					var currentVehicle = $("#current-vehicle-select").val();
					if (checkURIParams('forceYMME') != null && checkURIParams('forceYMME') == "true") {
						var redirect = $.cookies.get("previousURL");
						$.cookies.set("previousURL", null);
						location.replace(redirect);
					}
				});
			});
			ymme.emptyAll();
			$('#dialog-ymme-make').dialog('open');
			omniture.st({pageName: 'azpro:ymme:make'});
			$('#dialog-ymme-year').dialog('close');
			return false; // stop link href
		},

		submitMake: function(ymmeMakeId, ymmeMakeName) {

			//Get these values from hidden inputs -- Needed for the Breadcrumbs
			var yearId = $("input#ymmeYearId").val();
			var yearName = $("input#ymmeYearName").val();
			var frag = $("#dialog-ymme-model");
			$.get("/vehicle/ymme/overlay_model.jsp", {yearNodeId: yearId, yearName:yearName, makeNodeId: ymmeMakeId, makeName:ymmeMakeName, forceYMME: "inprogress"}, function(data) {
				frag.html(data);
				$('input.alphanumeric').alphanumeric();
				$("#enter-vin").bind("focus", function(e) {
					$("#enter-vin").hide();
					$("#decoder-input").show();
					$("#decoder-input").focus();
				});
				$("#decoder-input").focus();
				$("#decoder-input").bind("keydown", function(e) {
					if (e.keyCode == 13 && getVinValidation($('input#decoder-input').val()))
						return ymme.lookupVINOverlay();
				});

				$('.ui-dialog-titlebar-close').click(function() {
					$.cookies.set("successURL", null);
					var currentVehicle = $("#current-vehicle-select").val();
					if (checkURIParams('forceYMME') != null && checkURIParams('forceYMME') == "true") {
						var redirect = $.cookies.get("previousURL");
						$.cookies.set("previousURL", null);
						location.replace(redirect);
					}
				});
			});
			ymme.emptyAll();
			$('#dialog-ymme-model').dialog('open');
			omniture.st({pageName: 'azpro:ymme:model'});
			$('#dialog-ymme-make').dialog('close');
			return false; // stop link href
		},

		submitModel: function(ymmeModelId, ymmeModelName) {

			//Get these values from hidden inputs -- Needed for the Breadcrumbs
			var yearId = $("input#ymmeYearId").val();
			var yearName = $("input#ymmeYearName").val();
			var makeId = $("input#ymmeMakeId").val();
			var makeName = $("input#ymmeMakeName").val();

			var frag = $("#dialog-ymme-engine");
			$.get("/vehicle/ymme/overlay_engine.jsp", {yearNodeId: yearId, yearName:yearName, makeNodeId: makeId, makeName:makeName, modelNodeId: ymmeModelId, modelName:ymmeModelName, forceYMME: "inprogress"}, function(data) {
				frag.html(data);
				$('input.alphanumeric').alphanumeric();
				$("#enter-vin").bind("focus", function(e) {
					$("#enter-vin").hide();
					$("#decoder-input").show();
					$("#decoder-input").focus();
				});
				$("#decoder-input").focus();
				$("form#ymme-vehicle-form .hidden").hide();//Hide the form and button from the user
				$("#enter-name").bind("focus", function(e) {
					$("#enter-name").hide();
					$("#unique-name").show();
					$("#unique-name").focus();
				});
				$("#unique-name").bind("keydown", function(e) {
					if (e.keyCode == 13) return false;
				});
				$("#decoder-input").bind("keydown", function(e) {
					if (e.keyCode == 13 && getVinValidation($('input#decoder-input').val()))
						return ymme.lookupVINOverlay();
				});

				$('.ui-dialog-titlebar-close').click(function() {
					$.cookies.set("successURL", null);
					var currentVehicle = $("#current-vehicle-select").val();
					if (checkURIParams('forceYMME') != null && checkURIParams('forceYMME') == "true") {
						var redirect = $.cookies.get("previousURL");
						$.cookies.set("previousURL", null);
						location.replace(redirect);
					}
				});
			});
			ymme.emptyAll();
			$('#dialog-ymme-engine').dialog('open');
			omniture.st({pageName: 'azpro:ymme:engine'});
			$('#dialog-ymme-model').dialog('close');

			return false; // stop link href
		},

		submitEngine: function(ymmeEngineId) {
			//Remove the "forceYMME" from the url
			var url = window.location.href.replace(/forceYMME=.*&/i, "");
			//Remove the "_DARGS" from the url (just in case)
			url = url.replace(/_DARGS=.*&?/i, "");

			if(url.indexOf("#") != -1) {
				url = [url.split('#')[0], '&forceRefreshAt=', new Date().getTime(),'#',url.split('#')[1]].join('');
			}

			//Set the hidden input field to the engine id
			$("input#ymme-engine-selection").val(ymmeEngineId);

			//This code is needed to modify the serializedArray that represents
			//the form so that it will work correctly with ATG's REST
			var array = $('#ymme-vehicle-form').serializeArray();
			var restArray = [];
			//Iterate through the array
			for (var x in array) {
				var name = array[x].name
				//If the name does NOT start with '_D:' then it needs to go in the new array for REST
				if(name.indexOf("_D:") == -1) {
					array[x].name = name.substr(name.indexOf(".")+1,name.length);//Get rid of the unnecessary info
					restArray.push(array[x]);//Add to the new Array
				}
			}

			//The code below is needed for REST
			$.ajax({
		        url: '/rest/bean/autozone/pro/formhandler/YmmeFormHandler/create',
		        type: 'POST',
		        data: restArray,
		        success: function(data, textStatus, xhr) {
					$("div#ymme-error").html("");//Clear out the errors
					var cache = $.cookies.get("successURL");
					var triggerSubmit = $.cookies.get("triggerSubmit");
					if (cache != null) {
						window.location = cache;
						$.cookies.set("successURL", null);
					} else if (triggerSubmit != null) {
						$.cookies.set("triggerSubmit", null);
						window.location = url;
					} else {
						window.location.href = url;
					}
					return false;
		        },
		        error:function (xhr, textStatus, errorThrown){
		        	var errorText = xhr.statusText
		        	errorText = errorText.substr(errorText.indexOf(":")+1,errorText.length);//Get rid of the class name
		        	errorText = errorText.substr(0,errorText.length / 2);//Get rid of the repeat message
		        	$("div#ymme-error").html(errorText);//display error
		        }
			});

			return false; // stop link href
		},

		submitVehicleVIN: function(ymmeVehicleId) {
			//Remove the "forceYMME" from the url
			var url = window.location.href.replace(/forceYMME=.*&/i, "");
			//Remove the "_DARGS" from the url (just in case)
			url = url.replace(/_DARGS=.*&?/i, "");

			//Set the hidden input field to the engine id
			$("input#vin-vehicle-selection").val(ymmeVehicleId);

			//This code is needed to modify the serializedArray that represents
			//the form so that it will work correctly with ATG's REST
			var array = $('#vin-vehicle-form').serializeArray();
			var restArray = [];
			//Iterate through the array
			for (var x in array) {
				var name = array[x].name
				//If the name does NOT start with '_D:' then it needs to go in the new array for REST
				if(name.indexOf("_D:") == -1) {
					array[x].name = name.substr(name.indexOf(".")+1,name.length);//Get rid of the unnecessary info
					restArray.push(array[x]);//Add to the new Array
				}
			}

			//The code below is needed for REST


			$.ajax({
		        url: '/rest/bean/autozone/pro/formhandler/YmmeFormHandler/create',
		        type: 'POST',
		        data: restArray,
		        success: function(data, textStatus, xhr) {
					$("div#ymme-error").html("");//Clear out the errors

					var cookieURL = $.cookies.get("successURL");
					if(cookieURL != null) {
						window.location = cookieURL;
						$.cookies.set("successURL", null);
					} else
						window.location = url;

					return false;
		        },
		        error:function (xhr, textStatus, errorThrown){
		        	var errorText = xhr.statusText
		        	errorText = errorText.substr(errorText.indexOf(":")+1,errorText.length);//Get rid of the class name
		        	errorText = errorText.substr(0,errorText.length / 2);//Get rid of the repeat message
		        	$("div#ymme-error").html(errorText);//display error
		        }
			});

			return false; // stop link href
		},

		lookupVIN: function() {
			var frag = $("#dialog-ymme-vin");
			var vinDecoderValue = $('input#decoder').val();
			 // Omniture
            omniture.st({eVar14: vinDecoderValue});
		   	// end Omniture
			if (vinDecoderValue != null && vinDecoderValue != "") {
				$.get("/vehicle/ymme/overlay_vinDecoder.jsp", {vinDecoder: vinDecoderValue }, function(data) {
					frag.html(data);
					$('input.alphanumeric').alphanumeric();
					$("#enter-vin").bind("focus", function(e) {
						$("#enter-vin").hide();
						$("#decoder-input").show();
						$("#decoder-input").focus();
					});
					$("#decoder-input").focus();
					$("form#vin-vehicle-form .hidden").hide();//Hide the form and button from the user
					$("#enter-name").bind("focus", function(e) {
						$("#enter-name").hide();
						$("#unique-name").show();
						$("#unique-name").focus();
					});
					$("#unique-name").bind("keydown", function(e) {
						if (e.keyCode == 13) return false;
					});

					$("#decoder-input").bind("keydown", function(e) {
						if (e.keyCode == 13 && getVinValidation($('input#decoder-input').val())) {
							return ymme.lookupVINOverlay();
						}
					});

					$('.ui-dialog-titlebar-close').click(function() {
						$.cookies.set("successURL", null);
						var currentVehicle = $("#current-vehicle-select").val();
						if (checkURIParams('forceYMME') != null && checkURIParams('forceYMME') == "true") {
							var redirect = $.cookies.get("previousURL");
							$.cookies.set("previousURL", null);
							location.replace(redirect);
						}
					});
				});
				ymme.emptyAll();
				$('#dialog-ymme-vin').dialog('open');
				omniture.st({pageName: 'azpro:ymme:vin'});
			}

			return false; // stop link href
		},

		lookupVINOverlay: function() {
			var currentURL = $("input#vin-current-url").val();
			var frag = $("#dialog-ymme-vin");
			var vinDecoderValue = $('input#decoder-input').val();
			$.get("/vehicle/ymme/overlay_vinDecoder.jsp", {vinDecoder: vinDecoderValue, redirectURL: currentURL }, function(data) {
				frag.html(data);
				$('input.alphanumeric').alphanumeric();
				$("#enter-vin").bind("focus", function(e) {
					$("#enter-vin").hide();
					$("#decoder-input").show();
					$("#decoder-input").focus();
				});
				$("#decoder-input").focus();
				$("form#vin-vehicle-form .hidden").hide(); //Hide the form and button from the user
				$("#enter-name").bind("focus", function(e) {
					$("#enter-name").hide();
					$("#unique-name").show();
					$("#unique-name").focus();
				});
				$("#unique-name").bind("focus", function(e) {
					$("#unique-name").val('');
				});
				$("#unique-name").click(function() {
					if (e.keyCode == 13) return false;
				});
				$("#decoder-input").bind("keydown", function(e) {
					if (e.keyCode == 13 && getVinValidation($('input#decoder-input').val())) {
						return ymme.lookupVINOverlay();
					}
				});

				$('.ui-dialog-titlebar-close').click(function() {
					$.cookies.set("successURL", null);
					var currentVehicle = $("#current-vehicle-select").val();
					if (checkURIParams('forceYMME') != null && checkURIParams('forceYMME') == "true") {
						var redirect = $.cookies.get("previousURL");
						$.cookies.set("previousURL", null);
						location.replace(redirect);
					}
				});
			});
			ymme.emptyAll();
			$('#dialog-ymme-vin').dialog('open');
			omniture.st({pageName: 'azpro:ymme:vin'});
			return false; // stop link href
		},

		emptyAll: function() {
			$("#dialog-ymme-year").empty();
			$("#dialog-ymme-make").empty();
			$("#dialog-ymme-model").empty();
			$("#dialog-ymme-engine").empty();
			$("#dialog-ymme-vin").empty();
			$('#dialog-ymme-year').dialog('close');
			$('#dialog-ymme-make').dialog('close');
			$('#dialog-ymme-model').dialog('close');
			$('#dialog-ymme-engine').dialog('close');
			return false;
		}
};

