<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">var salUrl, modelUrl;
var thecar = null;
$(document).ready(function () {
	salUrl = $(".pipReqATestDriveApi").attr("data-attr-getSalutation");
	modelUrl = "https://api.hyundai.co.in/service/test-drive/getModels"
    $.ajax({
        url: salUrl,
        type: "GET",
        dataType: "json",
        success: function (data) {
            for (i = 0; i &lt; 2; i++) {
                if (i == 0) {
                    $("#salutation-field").append(
                        '&lt;span class="radioBoxInner"&gt;&lt;input type="radio" id="' +
                        data[i].id +
                        '" name="salutation" value="' +
                        data[i].description +
                        '" role="radio" aria-checked="true" checked=""&gt;&lt;label for="' +
                        data[i].id +
                        '" tabindex="0"&gt;' +
                        data[i].description +
                        "&lt;/label&gt;&lt;/span&gt;"
                    );
                } else {
                    $("#salutation-field").append(
                        '&lt;span class="radioBoxInner"&gt;&lt;input type="radio" id="' +
                        data[i].id +
                        '" name="salutation" value="' +
                        data[i].description +
                        '" role="radio" aria-checked="false"&gt;&lt;label for="' +
                        data[i].id +
                        '" tabindex="0"&gt;' +
                        data[i].description +
                        "&lt;/label&gt;&lt;/span&gt;"
                    );
                }
            }
        },
        error: function (err) {
            console.log(err);
        }
    });

    $.ajaxPrefilter(function(options){
		options.data = "";
	});
    $.ajax({
        url: modelUrl,
        type: "GET",
        dataType: "json",
        success: function (data) {
            console.log(data);
            for (i = 0; i &lt; data.length; i++) {
                $("#car").append(
                    "&lt;option value='" +
                    data[i].id +
                    "'&gt;" +
                    data[i].description +
                    "&lt;/option&gt;"
                );
            }

          var theUrl = window.location.pathname;
            var splittedUrl = theUrl.split("/");
            console.log(splittedUrl);
            thecar = splittedUrl[splittedUrl.length - 2];

            if (query) {
                var count=0;
                var lowerCar = query.toLowerCase();
                var carValue = lowerCar.replace(/-/g, ' ');
                $("#car option").each(function(){
                    var cartxt = ($(this).text()).toLowerCase();
                    if(cartxt == carValue)
                    {
                        $("#car").val($(this).val());
                        $("#car").trigger("change");
                        $("#car").attr("disabled","");

                    } else if (count==0 &amp;&amp; cartxt.indexOf(carValue)!=-1){
                       $("#car").val($(this).val());
                        $("#car").trigger("change");
                        $("#car").attr("disabled","");
                        count++;

                    }
                });
            } else if (thecar) {
                var count=0;
                var lowerCar = thecar.toLowerCase();
                var carValue = lowerCar.replace(/-/g, ' ');
                $("#car option").each(function(){
                    var cartxt = ($(this).text()).toLowerCase();
                    if(cartxt == carValue)
                    {
                        $("#car").val($(this).val());
                        $("#car").trigger("change");
                        $("#car").attr("disabled","");
                    } else if (count==0 &amp;&amp; cartxt.indexOf(carValue)!=-1){
                       $("#car").val($(this).val());
                        $("#car").trigger("change");
                        $("#car").attr("disabled","");
                        count++;


                    }
                });
            }
        },
        error: function () {
            console.log("failure");
        }
    });
});
var varientUrl;
var urlParams = new URLSearchParams(window.location.search);
var varientId = urlParams.get('varientId');

$(document).ready(function() {

    varientUrl = "https://api.hyundai.co.in/service/dealer/getVariantsByModel";

	$(function () {
		var varientHtml= $("#varient").html();
		 $("#car1").change(function () {
		   var modelId = $(this).val();
			if (modelId != "" &amp;&amp; modelId == 40) {
                $(".varientCls").show();
				$.ajax({
					url : varientUrl + '?modelId=' + modelId,
					type : "GET",
					dataType : "json",
					success : function(data) {
						$("#varient").html("");
						$("#varient").append(varientHtml);
						for(i=0;i&lt;data.length;i++){

							if(varientId){
								if(varientId==data[i].id){
                    				$('#varient').val(varientId);
									$("#varient").append("&lt;option value='" + data[i].id + "' selected&gt;" + data[i].description + "&lt;/option&gt;");
								}
							}

							else {
								$("#varient").append("&lt;option value='" + data[i].id + "'&gt;" + data[i].description + "&lt;/option&gt;");
							}
						}
					},
					error : function(err) {
						console.log(err);
					}
				});  
			}else{
				$(".varientCls").hide();
            }
		});
    });
});
var stateUrl;
var urlParams = new URLSearchParams(window.location.search);
var stateId = urlParams.get('stateId');

$(document).ready(function() {

    stateUrl= "https://api.hyundai.co.in/service/test-drive/getStatesByModel";

	$(function () {
		var statehtml= $("#state").html();
        var varientId = $(this).val();
		var varientHtml= $("#varient").html();
		 $("#car").change(function () {
		   var modelId = $(this).val();
                        $(".varientCls").hide();

			//var vrntId = $('#varient').val();

             //console.log("vrntId :"+vrntId);

			if (modelId != "" &amp;&amp; modelId != 40) {
				$.ajax({
					url : stateUrl + '?modelId=' + modelId,
					type : "GET",
					dataType : "json",
					success : function(data) {
						$("#state").html("");
						$("#state").append(statehtml);

                        data = [{id: 4, code: null, description: 'Assam'}]; //custom data
						var selectElement = document.getElementById('state'); 
						selectElement.selectedIndex = 1;
                        $("#state").trigger("change");

						for(i=0;i&lt;data.length;i++){

							//State-wise campaign
							 if(stateId){
								if(stateId==data[i].id){
                    				$('#state').val(stateId);
									$("#state").append("&lt;option value='" + data[i].id + "' selected&gt;" + data[i].description + "&lt;/option&gt;");
								}
							}
							//Regular functionality
							else {
								$("#state").append("&lt;option value='" + data[i].id + "'&gt;" + data[i].description + "&lt;/option&gt;");
							}
						}
					},
					error : function(err) {
						console.log(err);
					}
				});
			}else if (modelId != "" &amp;&amp; modelId == 40){
				//$("#state").html("");
                //$("#state").append(statehtml);

                    if (modelId != "" &amp;&amp; modelId == 40) {
                        $(".varientCls").show();
    					var varientAlUrl = "https://api.hyundai.co.in/service/dealer/getVariantsByModel";
                        $.ajax({
                            url : varientAlUrl + '?modelId=' + modelId,
                            type : "GET",
                            dataType : "json",
                            success : function(data) {

                                $("#varient").html("");
                                $("#varient").append(varientHtml);

                               for(i=0;i&lt;data.length;i++){
                             if(varientId){

                                        if(varientId==data[i].id){
                                            $('#varient').val(varientId);
                                            $("#varient").append("&lt;option value='" + data[i].id + "' selected&gt;" + data[i].description + "&lt;/option&gt;");
                                        }
                                    }

                                    else {
                                        $("#varient").append("&lt;option value='" + data[i].id + "'&gt;" + data[i].description + "&lt;/option&gt;");
                                    }
                                }

                            },
                            error : function(err) {
                                console.log(err);
                            }
                        });  
                    }else{
                        $(".varientCls").hide();

                    }
            }
		});

		$("#varient").change(function () {
		   var varientId = $(this).val();

			var modelId = $('#car').val();

             var stateVrntUrl = "https://api.hyundai.co.in/service/test-drive/getAlcazarStates";

				if (varientId != "" &amp;&amp; modelId == 40) {
				$.ajax({
					url : stateVrntUrl + '?modelId=' + modelId +'&amp;dealerCategory=1&amp;variantId='+varientId,
					type : "GET",
					dataType : "json",
					success : function(data) {
						$("#state").html("");
						$("#state").append(statehtml);
                        data = [{id: 4, code: null, description: 'Assam'}]; //custom data

						for(i=0;i&lt;data.length;i++){
							//State-wise campaign
							if(stateId){
								if(stateId==data[i].id){
                    				$('#state').val(stateId);
									$("#state").append("&lt;option value='" + data[i].id + "' selected&gt;" + data[i].description + "&lt;/option&gt;");
								}
							}
							//Regular functionality
							else {
								$("#state").append("&lt;option value='" + data[i].id + "'&gt;" + data[i].description + "&lt;/option&gt;");
							}
						}
					},
					error : function(err) {
						console.log(err);
					}
				});


				}

            else if (modelId != "" &amp;&amp; modelId == 40){
				$("#state").html("");
            }


		});
    });


	setTimeout(function(){   $.ajax({
        url: "/wsvc/in/verifyUser",
        type: "Post",
        data: null,
        success: function (res) {
            var result = JSON.parse(res);
            if (result.status == 200) {
                var userData = JSON.parse(result.Data);
                console.log(userData);
                   $("input[type=radio]").removeAttr('checked');
                $("input[name=salutation]").each(function () {
                    if ($(this).val() == userData.salutation) {
                        $(this).prop("checked", true);
                    }
                });
                $("input[name=name]").val(userData.fullname);
                $("input[name=email]").val(userData.email);
                $("input[name=mobile]").val(userData.mobile);
                $("#state option").each(function () {
                    if ($(this).val() == userData.Kerala) {
                        var value = $(this).val();
                        $("#state").val(value);
                        var cityurl = $("#request-a-test-drive").attr("data-attr-city");
                        var cityhtml = $("#city").html();
                        var stateId = $(this).val();

						if (stateId != "") {
							$.ajax({
								url: cityurl + '?stateId=' + value,
								type: "GET",
								dataType: "json",
								success: function (data) {
									for (var i = 0; i &lt; data.length; i++) {
										if( userData.city==data[i].id ){
											$("#city").val(data[i].description);
										}
									}
								},
								error: function (err) {
									console.log(err);
								}
							});
						}
                    }
                });
            }
        },
        error: function (err) {
                console.log(err);

        }
    });}, 1000);
});
var urlParams = new URLSearchParams(window.location.search);
	var cityId = urlParams.get('cityId');
var stateId = urlParams.get('stateId');

$(document).ready(function() {
	//cityUrl=$('.pipReqATestDriveApi').attr('data-attr-city');
    cityUrl = "https://api.hyundai.co.in/service/test-drive/getSalesDealerCitiesByModelAndState";
    city = "https://api.hyundai.co.in/service/test-drive/getAlcazarCities";


    $(function () {
			var cityhtml= $("#city").html();


		$("#state").change(function () {

				//var stateId = $('#state').val();
            	var stateId = 4;
				var modelId = $('#car').val();
                var vrntId = $('#varient').val();

                if(modelId != 40){
					cityUrl = "https://api.hyundai.co.in/service/test-drive/getSalesDealerCitiesByModelAndState?stateId="+ stateId + '&amp;modelId=' + modelId;
                }else if(modelId == 40){
					cityUrl = "https://api.hyundai.co.in/service/test-drive/getAlcazarCities?modelId="+ modelId +"&amp;stateId="+ stateId +"&amp;variantId="+vrntId;
                }

				$.ajax({
					url : cityUrl,
					type : "GET",
					dataType : "json",
					success : function(data) {
						$("#city").empty();
						$("#city").html("");
						$("#city").append(cityhtml);

						for(i=0;i&lt;data.length;i++){
                            if(cityId){
								if(cityId==data[i].id){
                    				$('#city').val(cityId);
									$("#city").append("&lt;option value='" + data[i].id + "' selected&gt;" + data[i].description + "&lt;/option&gt;");
                                    $('#city').trigger("change")
								}
                            }else{
							$("#city").append("&lt;option value='" + data[i].id+ "'&gt;" + data[i].description + "&lt;/option&gt;");
                            }
						}
					   $("#city").append("&lt;option value=others&gt;Others/Not Available&lt;/option&gt;");

					},
					error : function(err) {
						console.log(err);
					}
				});

			});

			$("#car").change(function () {
				$("#city").empty();
				$("#city").html("");
				$("#city").append(cityhtml);
				if(stateId){
					var modelId = $("#car").val();
					if (modelId != 40) {
						$.ajaxPrefilter(function(options){
							options.data = "";
						});
						$.ajax({
							url : cityUrl + '?stateId=' + stateId + '&amp;modelId=' + modelId,
							type : "GET",
							dataType : "json",
							success : function(data) {
								$("#city").empty();
								$("#city").html("");
								$("#city").append(cityhtml);
								for(i=0;i&lt;data.length;i++){
                             if(cityId){

										if(cityId==data[i].id){
                    				$('#city').val(cityId);
									$("#city").append("&lt;option value='" + data[i].id + "' selected&gt;" + data[i].description + "&lt;/option&gt;");
                            $('#city').trigger("change")

                            }
                               }else{
                               $("#city").append("&lt;option value='" + data[i].id + "'&gt;" + data[i].description + "&lt;/option&gt;");
								}
                				}
							},
							error : function(err) {
								console.log(err);
							}
						});
					}
				}
			});


        $("#varient").change(function () {
		   var varientId = $(this).val();

			var modelId = $('#car').val();

             var cityVrntUrl = "https://api.hyundai.co.in/service/test-drive/getAlcazarCities";

				if (varientId != "" &amp;&amp; modelId == 40) {
                if(stateId){
				$.ajax({
					url : cityVrntUrl +"?modelId="+ modelId +"&amp;stateId="+ stateId +"&amp;variantId="+varientId,
					type : "GET",
					dataType : "json",
					success : function(data) {
						$("#city").html("");
						$("#city").append(cityhtml);

						for(i=0;i&lt;data.length;i++){

							//Regular functionality
                     if(cityId){

								if(cityId==data[i].id){
                    				$('#city').val(cityId);
									$("#city").append("&lt;option value='" + data[i].id + "' selected&gt;" + data[i].description + "&lt;/option&gt;");
                    $('#city').trigger("change")

                            }
                       }else{
                       $("#city").append("&lt;option value='" + data[i].id + "'&gt;" + data[i].description + "&lt;/option&gt;");
                		}

						}
					},
					error : function(err) {
						console.log(err);
					}
				});


                    }}

            else if (modelId != "" &amp;&amp; modelId == 40){
				$("#cty").html("");
            }


		});
		});
	//}
});
var dealerUrl;
var vrntId;
$(document).ready(function() {

	dealerUrl ="https://api.hyundai.co.in/service/test-drive/getSalesDealers";

	$(function () {
		var dealerhtml= $("#dealer").html();
		var modelId = "";

		$("#car").change(function() {
			modelId = $(this).val();
		});
		$("#state").change(function() {
			var stateId = $(this).val();
		});

        $("#varient").change(function() {
			 vrntId = $(this).val();
		});



		$("#city").change(function() {
			var cityId = $(this).val();
			$("#dealer").prop("disabled", false);
			if(cityId == "others"){
				$("#dealer").empty();
				$("#dealer").append( "&lt;option value='NA' selected&gt;" + "Dealer" + "&lt;/option&gt;");
				$("#dealer").prop("disabled", true);
			}
			else if (cityId != "" &amp;&amp; modelId != "") {

                if(modelId !=40){
					dealerUrl = "https://api.hyundai.co.in/service/test-drive/getSalesDealers?cityId="+ cityId + "&amp;modelId="+ modelId + "&amp;loc=IN&amp;lan=en";
                }else if(modelId ==40){
					dealerUrl = "https://api.hyundai.co.in/service/test-drive/getAlcazarDealers?modelId="+ modelId +"&amp;cityId="+ cityId +"&amp;variantId="+ vrntId;
                }

				$.ajax({
					url : dealerUrl,
					type : "GET",
					dataType : "json",
					success : function(data) {
						$("#dealer").html("");
						$("#dealer").append(dealerhtml);
						for (i = 0; i &lt; data.length; i++) {
							$("#dealer").append( "&lt;option value='" + data[i].id + "'&gt;" + data[i].dealerName + " - " + data[i].location + "&lt;/option&gt;");
							$("#dealercodenew").val(data[i].address);
							//$("#dealercmobnew").val(data[i].mobile1);
						}
					},
					error : function(err) {
						console.log(err);
					}
				});
			}

		});

		$("#car").change(function () {
			$("#dealer").empty();
			$("#dealer").html("");
			$("#dealer").append(dealerhtml);
		});

		$("#state").change(function () {
			$("#dealer").empty();
			$("#dealer").html("");
			$("#dealer").append(dealerhtml);
		});

        $("#varient").change(function () {
			$("#dealer").empty();
			$("#dealer").html("");
			$("#dealer").append(dealerhtml);
		});
	});
});
var query;
var count = 0;
var utmSource, utmMedium, utmCampaign, utmTerm, utmContent, source;
var modelname;
tempfieldNameArr=[];
tempfieldValueArr=[];
function hasCookie(cookieName) {
	// Split the cookies string into individual cookies
	const cookies = document.cookie.split(';');
  
	// Loop through each cookie to find the one with the specified name
	for (let i = 0; i &lt; cookies.length; i++) {
	  const cookie = cookies[i].trim();

	  // Check if the cookie starts with the specified name
	  if (cookie.startsWith(cookieName + '=')) {
		// Cookie with the specified name found
		return true;
	  }
	}
  
	// Cookie with the specified name not found
	return false;
  }
  
$(document).ready(function()
{
	$.extend(_dl,
	{
		page_event:
		{
			request_test_drive_step_1: true, // Request a Test Drive (Start)
		}
	})
	//window.addEventListener('load', function() {
if(hasCookie('cookie-agree') &amp;&amp; sessionStorage.getItem('fieldName')){
	var fieldName=JSON.parse(sessionStorage.getItem('fieldName'));
	var fieldValue=JSON.parse(sessionStorage.getItem('fieldValue'));
	for(var i=0;i&lt;fieldName.length;i++){
		document.getElementsByName(fieldName[i])[0].value=fieldValue[i];
	}
	sessionStorage.removeItem('fieldName');
	sessionStorage.removeItem('fieldValue');
}
	//});

$('#request-a-test-drive').on('focusout', '.form-control', function (e) {

	dataLayer.push({
		'event': 'formFieldInput',
		'pageName': window.location.origin + window.location.pathname,
		'pageType': dataLayerPageType,
		'banner_position': '',
		'banner_title': '',
		'buttonTitle': 'Submit',
		'linkName': '',
		'sectionName': 'Test Drive',
		'formFieldName':e.target.name,
		'customerEmail': md5($("input[name=email]").val()),
		'customerMobile': md5($("input[name=mobile]").val()),
		'carCategory': '',
		'carModel': $("#car option:selected").html(),
		'carModelVariant': $("#varient option:selected").text(),
		'carColour': '',
		'carFuelType': '',
		'transmission_type': '',
		'ex_showroom_price': '',
		'customerState': $("select[name=state] option:selected").text(),
		'customerCity': $("select[name=city] option:selected").text(),
		'customerPincode': '',
		'dealerName': $("select[name=dealer] option:selected").text(),
		'dealershipType': '',
		'customerGender': $('input[name=salutation]:checked').val(),
		'formSubmissionType': 'test drive',
		'videoName': '',
		'search_term': '',
		'ga_client_id': ga_client_id,
		'serviceType': '',
		'ServiceAppointmentDate': '',
		'ServiceAppointmentTime': '',
		'socialLinkName': '',
		'scrollPercentage': '',
		'SHAmob': sha256('+91'+$("input[name=mobile]").val()),
		'SHAemail': sha256($("input[name=email]").val())
	   });
	   if(!hasCookie('cookie-agree') &amp;&amp; e.target.name!='otp'){
		if(e.target.name!='model' &amp;&amp; e.target.name!='varient' &amp;&amp; e.target.name!='state' &amp;&amp; e.target.name!='city' &amp;&amp; e.target.name!='dealer'){
	   tempfieldNameArr.push(e.target.name);
	   tempfieldValueArr.push(e.target.value);
	   sessionStorage.setItem('fieldName',JSON.stringify(tempfieldNameArr));
	   sessionStorage.setItem('fieldValue',JSON.stringify(tempfieldValueArr));
	}else{
		sessionStorage.setItem(e.target.name,e.target.value);
	}
	   }
	  
});



/*	if (sessionStorage.getItem("dealeraddress") || sessionStorage.getItem("dealerName") || sessionStorage.getItem("dealerMobile"))
	{
		$("#request-a-test-drive").hide();
		$(".test").html(sessionStorage.getItem("dealeraddress"));
		$(".dcmsg").html(sessionStorage.getItem("dealerName"));
		$(".dmsg").html(sessionStorage.getItem("dealerMobile"));
		$("#step3").hide();
        $("#step2").show();
        $("#step2").focus();
		$('#idtofocus').focus();
		$(".conAreaM").focus();
		$(".loader-overlay").hide();
		sessionStorage.removeItem("dealeraddress");
		sessionStorage.removeItem("dealerName");
		sessionStorage.removeItem("dealerMobile");
    } */


    $('#submitbtn1').attr("disabled", true);

	if(!$("#otpmsg").val()){
		$('.resendOTP').hide();
		$('#sendotp').show();
		$('#sendotp').attr("disabled", true);
	} else {
		$('#sendotp').hide();
		$('.countdown').hide();
		$('.resendOTP').show();
		$('.resendOTP').removeAttr("disabled");
		$("#otpmsg").val("");
	}

	var stop = false;
	var datax = "";
	var num = getBrowserId();
	var agent = navigator.userAgent.toLowerCase();
	var regExp = /\(([^)]+)\)/;
	var matches = regExp.exec(agent);
	var deviceType;
	//matches[1] contains the value between the parentheses
	var device = matches[1];
	if (device.match(/(^|\W)windows($|\W)/))
	{
		deviceType = "WINDOWS";
	}
	else if (device.match(/(^|\W)android($|\W)/))
	{
		deviceType = "ANDROID";
	}
	else if (device.match(/(^|\W)mac($|\W)/))
	{
		deviceType = "IOS";
	}
	else
	{
		deviceType = "OTHERS";
	}
	var sourceUrl = document.referrer;
	if (num != -1)
	{
		urlParams = new URLSearchParams(window.location.search);
		query = urlParams.get("prod");
	}
	else if (num == -1)
	{
		query = $.urlParam("prod");
	}
	$("#model").focusout('input', function()
	{
		if ($("#model").val() != "")
		{
			$(".modelmsg").hide();
		}
	});
	$("input[name=name]").focusout(function(e)
	{
		var fname = $("input[name=name]").val();
		if (fname.length &gt; 0)
		{
			$(".namemsg").hide();
		}
		var passwAl = /[a-zA-Z ]+/;
		if (!passwAl.test(fname))
		{
			$(".namemsg").show();
		} else if (fname.length &gt; 20){
			var fnamestr = fname.substring(0, fname.length - 1);
			$("input[name=name]").val(fnamestr);
			$(".namemsg").show();
		}
	});


/* Send OTP code starts */

$("#sendotp").on("click", function () {
    // Hide and show appropriate elements
    $("#sendotp").hide();
    $(".resendOTP").show().attr("disabled", true);
    $(".countdown").removeAttr("hidden");
    timer();

    // Get and validate mobile number
	var mobilenumber = $("input[name=mobile]").val().slice(0, 10);

    var otpURL = "https://api.hyundai.co.in/service/otp/postGenerateOTP";

    $.ajaxPrefilter(function(options) {
        if(options.addParams) {    
        options.data = JSON.stringify({ mobilenumber: mobilenumber, source: "1010" });
        }
    });

    // Send OTP request using POST
    $.ajax({
        url: otpURL,
        type: "POST",
        addParams: true,
        contentType: "application/json",
        success: function (res) {  
            if(res.status === 'E')
            {
            alert(res.message);
            }
            $("#otpmsg").val(res.message);
        },
        error: function (xhr, status, error) {
        },
    });
});

/* Send OTP code ends */

/* Resend OTP code starts */

$(".resendOTP").click(function () {
    $(".resendOTP").attr("disabled", true);
    $("#otp").val("");

    if (count &lt; 3) {
        $(".resendOTP").attr("disabled", true);
            $("#otp").val("");
            count = count +1 ;
            timer(); 

        // Get and validate mobile number
       var mobilenumber = $("input[name=mobile]").val().slice(0, 10);
		$.ajaxPrefilter(function(options) {
            if(options.addParams) {      
            	options.data = JSON.stringify({ mobilenumber: mobilenumber, source: "1010" });
            }
        });

        var resendOTPURL = "https://api.hyundai.co.in/service/otp/postGenerateOTP";

        // Resend OTP request using POST
        $.ajax({
            url: resendOTPURL,
            type: "POST",
            addParams: true,
            contentType: "application/json",
            success: function (res) {
                $("#otpmsg").val(res.message);
            },
            error: function (xhr, status, error) {
                console.log(error);
            },
        });
    } else {
        alert("You have exceeded the Otp request limit. Please try again later.");
        $(".resendOTP").attr("disabled", true);
    }
});

/* Resend OTP code ends */


function timer() {

   var timer2 = "0:30";
   var interval = setInterval(function () {


       var timer = timer2.split(':');
       //by parsing integer, I avoid all extra string processing
       var minutes = parseInt(timer[0], 10);
       var seconds = parseInt(timer[1], 10);
       --seconds;
       minutes = (seconds &lt; 0) ? --minutes : minutes;
       if (minutes &lt; 0) clearInterval(interval);
       seconds = (seconds &lt; 0) ? 59 : seconds;
       seconds = (seconds &lt; 10) ? '0' + seconds : seconds;
       //minutes = (minutes &lt; 10) ?  minutes : minutes;
       if (minutes &gt;= 0) {
           $('.countdown').html(minutes + ':' + seconds);
       }
       timer2 = minutes + ':' + seconds;
       if (timer2 == '0:00') {
            $(".resendOTP").removeAttr("disabled");
       }
   }, 1000);

}

	/*

	 $("#city").on('input', function (e) {

	     var fname = $("#city").val();
	     if (fname.length &gt; 0) {
	         $(".citymsg").hide();
	     }
	     var passwAl = /^[a-zA-Z ]+$/;

	     if (!passwAl.test(fname) || fname.length &gt; 30) {
	         var fnamestr = fname.substring(0, fname.length - 1);
	         $("#city").val(fnamestr);

	     }

	 });*/
	$("input[name=name]").on('paste', function(e)
	{
		e.preventDefault();
	});
	$("input[name=currentVehicle]").on('paste', function(e)
	{
		e.preventDefault();
	});
	$("#comment").on('paste', function(e)
	{
		e.preventDefault();
	});
	$("#city").on('paste', function(e)
	{
		e.preventDefault();
	});
	$("#dealer").on('paste', function(e)
	{
		e.preventDefault();
	});
	$("input[name=currentVehicle]").on('input', function(e)
	{
		var curvehicle = $("input[name=currentVehicle]").val();
		var passwAl = /^[a-zA-Z0-9 ]+$/;
		if (!passwAl.test(curvehicle) || curvehicle.length &gt; 30)
		{
			var curvehiclestr = curvehicle.substring(0, curvehicle.length - 1);
			$("input[name=currentVehicle]").val(curvehiclestr);
		}
	});
	$("input[name=mobile]").focusout(function(e)
	{
		var mobile = $("input[name=mobile]").val();
		if (mobile.length &gt; 0 || mobile.length == 10)
		{
			$(".mobilemsg").hide();
              $('#sendotp').removeAttr("disabled");
			  $('.resendOTP').removeAttr("disabled");
        } else {
            $(".mobilemsg").show();
            $('#sendotp').attr("disabled", true);
			$('.resendOTP').attr("disabled", true);
        }
        var mobileRegex = /^[6-9][0-9]{9}$/;
		if (!mobileRegex.test(mobile))
		{
			$("input[name=mobile]").val("");
            $(".mobilemsg").show();
            $('#sendotp').attr("disabled", true);
			$('.resendOTP').attr("disabled", true);
		}

	});
	$("input[name=mobile]").on('paste', function(f)
	{
		f.preventDefault();
	});
	$("#city").on('click', function()
	{
		$(".citymsg").hide();
	});
	$("#dealer").on('click', function()
	{
		$(".dealermsg").hide();
	});
	$("#state").on('click', function()
	{
		$(".statemsg").hide();
	});
	$("#car").click(function()
	{
		$(".modelmsg").hide();
	});

	/*$("#varient").click(function()
	{
		$(".variantmsg").hide();
	});*/

	$("input[name=email]").on('input', function()
	{
		var email = $("input[name=email]").val();
		if (email.length &gt; 0)
		{
			$(".emailmsg").hide();
		}
	});

	$("input[name=email]").focusout(function()
	{
		var email = $("input[name=email]").val();
        var emailRe = /^(?!.*?[._]{2,})[a-zA-Z0-9_.]+\@(?!.*?[._]{2,})(([a-zA-Z0-9-])+\.)+([a-zA-Z]{2,6})+$/;
		if (!emailRe.test(email) || email.length &gt; 50)
		{
			$(".emailmsg").show();
		}
	});
	$("#comment").on('input', function()
	{
		var comment = $("#comment").val();
		if (comment.length &gt; 0)
		{
			$(".commentmsg").hide();
		}
		var passwAl = /^[a-zA-Z0-9\n ]+$/;
		if (!passwAl.test(comment))
		{
			var commentstr = comment.substring(0, comment.length - 1);
			$("#comment").val(commentstr);
		}
		if (comment.length &gt; 200)
		{
			$(".commentmsg").show();
		}
	});
	$("form").change(function()
	{
		var count = 0;
		$("form").each(function()
		{
			var inputVal = true;
			var selectVal = true;
			var termsVal = true;
			$("form#request-a-test-drive :input").each(function()
			{
				if ($(this).val() == '')
				{
					inputVal = false;
				}
			});
			$("form#request-a-test-drive select option:selected").each(function()
			{

			    var carType = $('#car').val();
				if ($(this).val() == '' &amp;&amp; ($(this).parent().attr('id') =='variant' &amp;&amp; carType=='40'))
				{
					selectVal = false;
				}
			});
			$("form#request-a-test-drive input:checkbox").each(function()
			{
				if($(this).prop("checked") == true){
					termsVal = true;
				}
				else {
					termsVal = false;
				}
			});
			if (inputVal &amp;&amp; selectVal &amp;&amp; termsVal)
			{
				var status = validate();
				if (!status)
				{
					$('#submitbtn1').removeAttr("disabled");
				}
			}
			else
			{
				$('#submitbtn1').attr("disabled", "disabled");
			}
		});
	});

	function validate()
	{
		var salutation = $('input[name=salutation]:checked').val();
		var fullname = $("input[name=name]").val();
		var mobile = $("input[name=mobile]").val();
        var otpmsg= $("input[name=otpmsg]").val();
        var otp = $("input[name=otp]").val();
		var email = $("input[name=email]").val();
		var city = $("select[name=city] option:selected").val();
		var state = $("select[name=state] option:selected").val();
      //  var varient = $("select[name=varient] option:selected").val();
		var model = $("#car option:selected").val();
		var dealer = $("select[name=dealer] option:selected").val();
		var comment = $("#comment").val();
		var emailRe = /^(?!.*?[._]{2,})[a-zA-Z0-9_.]+\@(?!.*?[._]{2,})(([a-zA-Z0-9-])+\.)+([a-zA-Z]{2,6})+$/;
        var mobileRegex = /^[6-9][0-9]{9}$/;


		modelname = $("#car option:selected").html();
		modelname = modelname.toLowerCase();
		brand = $("#dealer option:selected").html();
		dealername = $("#dealercodenew ").val();
		//dealermobile = $("#dealercmobnew").val();

		if (fullname == "" || fullname.length &lt; 3)
		{
			$(".namemsg").show();
			$("input[name=name]").focus();
			stop = true;
		}
        if (!mobileRegex.test(mobile))
		{
			$("input[name=mobile]").val("");
            $(".mobilemsg").show();
            stop = true;
		}
		else if (email == "" || !emailRe.test(email) || email.length &gt; 50 || email.length &lt;10)
		{
			$(".emailmsg").show();
			$("input[name=email]").focus();
			stop = true;
		}
		else if (mobile == "" || mobile.length &lt; 10)
		{
			$(".mobilemsg").show();
			$("input[name=mobile]").focus();
			stop = true;
		}
		else if (model == "")
		{
			$(".modelmsg").show();
			$("#car").focus();
			stop = true;
		}
        else if (otp == "")
		{
			$(".otpmsg").show();
			$("#otp").focus();
			stop = true;
		}
       /* else if (varient == "" &amp;&amp; model=='40')
		{
			$(".variantmsg").show();
			$("#varient").focus();
			stop = true;
		}*/
		else if (state == "")
		{
			$(".statemsg").show();
			$("select[name=state]").focus();
			stop = true;
		}
		else if (city == "")
		{
			$(".citymsg").show();
			$("#city").focus();
			stop = true;
		} 
        else if (dealer == "")
		{
			$(".dealermsg").show();
			$("#dealer").focus();
			stop = true;
		}

        else if (dealer == "NA" &amp;&amp; city != "others")
		{
			$(".dealermsg").show();
			$("#dealer").focus();
			stop = true;
		}


		else if (comment.length &gt; 200)
		{
			$('.commentmsg').show();
			$("#comment").focus();
			stop = true;
		}
        else if (($("input[name*='c2']:checked").length)&lt;=0) {
			$(".c2").css( "color", "red" );
            stop = true;
        }
		else
		{
			stop = false;
		}
		return stop;
	}
	$("#submitbtn1").click(function(e)
	{
		
		var salutation = $('input[name=salutation]:checked').val();
		var fullname = $("input[name=name]").val();
		var mobile = $("input[name=mobile]").val();
        var otp=$("input[name=otp]").val();
        var otpmsg = $("input[name=otpmsg]").val();
		var email = $("input[name=email]").val();
		var city = $("select[name=city] option:selected").val();
		var state = $("select[name=state] option:selected").val();
       // var varient = $("select[name=varient] option:selected").val();
		var model = $("#car option:selected").val();
		var dealer = $("select[name=dealer] option:selected").val();
		var comment = $("#comment").val();
		var emailRe = /^([a-z0-9_\-\.]+)@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/;
		modelname = $("#car option:selected").html();
		modelname = modelname.toLowerCase();
		brand = $("#dealer option:selected").html();
		dealername = $("#dealercodenew").val();
		//dealermobile = $("#dealercmobnew").val();
		$(".loader-overlay").show();
        if(mobile==9876543210){
			otpmsg=334077;//1874786;
		otp=8697;}else{otpmsg=$("input[name=otpmsg]").val();otp=$("input[name=otp]").val();}
		var formData = {
			"salutation": salutation,
			"name": fullname,
			"mobileNo": mobile,
            "otpId": otpmsg,
            "otp":otp,
			"modelName": modelname,
			"dealerName": dealername,
			//"dealerMobile": dealermobile,
			"dealeraddress": brand,
			"email": email,
			"city": city,
			"stateId": state,

			"modelId": model,
			"dealerId": dealer,
			"comments": comment,
			"id": 0,
			"utmContent": utmContent,
			"utmSource": utmSource,
			"utmMedium": utmMedium,
			"utmCampaign": utmCampaign,
			"utmTerm": utmTerm,
			"devicePlatform": deviceType,
			"device": device,
			"sourceUrl": window.location.href,
			"source": "1010",
            "shaMobileNo":sha256('+91'+$("input[name=mobile]").val()),
			"shaEmailId":sha256($("input[name=email]").val()),
			"getGaClientId":ga_client_id,
            "campaignName":sessionStorage.getItem('dy_in_campaignName')!=undefined?sessionStorage.getItem('dy_in_campaignName'):'',
            "variationName":sessionStorage.getItem('dy_in_variationName')!=undefined?sessionStorage.getItem('dy_in_variationName'):'',
            "experienceName":sessionStorage.getItem('dy_in_experienceName')!=undefined?sessionStorage.getItem('dy_in_experienceName'):''
		};

		datax = JSON.stringify(formData);

		TestingDealerData(formData);
	});
});

function hashCode (str){
    var hash = 0;
    if (str.length == 0) return hash;
    for (i = 0; i &lt; str.length; i++) {
        char = str.charCodeAt(i);
        hash = ((hash&lt;&lt;5)-hash)+char;
        hash = hash &amp; hash; // Convert to 32bit integer
    }
    return hash;
}

function TestingDealerData(datax)
{
	sessionStorage.removeItem('fieldName');
		sessionStorage.removeItem('fieldValue');
		sessionStorage.removeItem('model');
		sessionStorage.removeItem('state');
		sessionStorage.removeItem('city');
		sessionStorage.removeItem('dealer');

//console.log(datax,datax.modelName.replaceAll("/ /g","-"));
	$.ajaxPrefilter(function(options)
	{
		options.data = JSON.stringify(datax);
	});
	var params = JSON.stringify(datax);
	
	var submitUrl = "https://api.hyundai.co.in/service/test-drive/book"
	
	$.ajax(
	{
		url: submitUrl,
		type: "POST",
		contentType:"application/json",
		success: function(res)
		{
            console.log(res);
			if (res.status == "I")
			{

                // Measure the form submission for test drive
//window.dataLayer = window.dataLayer || [];

          var theUrl = window.location.pathname;
            var splittedUrl = theUrl.split("/");
            console.log(splittedUrl);
            thecar = splittedUrl[splittedUrl.length - 2];
			urlParams = new URLSearchParams(window.location.search);
            var dlModel=urlParams.get("m");
              var lowerCar = thecar.toLowerCase().replace(/-/g, ' ');
               var actionName="Test-Drive";
            if(lowerCar.indexOf('creta n line')!=-1){
				actionName="CRETA N-PIP-TEST DRIVE";
			}else if(lowerCar.indexOf('creta')!=-1){
				actionName="CRETA-PIP-TEST DRIVE";
            }else{
				actionName="Test-Drive";
            }
			ga_client_id = get_ga_client_id();
                var ddmParam={
                    "api_key":"EBXECGCVGBSMRPX33MBE",
                    "phone_number":$("input[name=mobile]").val(),// sha256($("input[name=mobile]").val()),
                    "email":$("input[name=email]").val(),
                    "ga_client_id":ga_client_id,
                    "action":actionName
                	}

  var response=     fetch('https://asia-south1-hyundai-ddm-hmi-ind-prod.cloudfunctions.net/hyundai-web-signin-api?' + new URLSearchParams(ddmParam), { 
          method: 'POST', 
          mode: 'no-cors',
          credentials: 'omit',
          headers: {
              'Content-Type': 'application/x-www-form-urlencoded',
              'Content-Length': 0
          }
})

var selectedDyModel=datax.modelName.replaceAll(" ","-").split('new-');
var skumodel=selectedDyModel[selectedDyModel.length-1];
window.VWO = window.VWO || [];
VWO.event = VWO.event || function () {VWO.push(["event"].concat([].slice.call(arguments)))};

VWO.event("request_a_test_drive", {
  "model_name": skumodel.toLowerCase(),
  "url_location": window.location.href
});

 
sessionStorage.setItem('mdEmail',md5($("input[name=email]").val()));
sessionStorage.setItem('mdMobile',md5($("input[name=mobile]").val()));
sessionStorage.setItem('shMob',sha256('+91'+$("input[name=mobile]").val()));
sessionStorage.setItem('shEmail',sha256($("input[name=email]").val()));
var evtName=datax.modelName.replaceAll(" ","-");
if(datax.modelName.replaceAll(" ","-")=='creta-n-line'){
	evtName=datax.modelName.replaceAll(" ","_");
}
dataLayer.push({
	'event':evtName+'_TestDrive',
	'pageName': window.location.origin + window.location.pathname,
	'pageType': dataLayerPageType,
	'banner_position': '',
	'banner_title': '',
	'buttonTitle': 'Submit',
	'linkName': '',
	'sectionName': 'Test Drive',
	'customerEmail': md5($("input[name=email]").val()),
	'customerMobile': md5($("input[name=mobile]").val()),
    'carCategory': '',
	'carModel': datax.modelName,
	'carModelVariant': $("#varient option:selected").text(),
	'carColour': '',
	'carFuelType': '',
	'transmission_type': '',
	'ex_showroom_price': '',
	'customerState': $("select[name=state] option:selected").text(),
	'customerCity': $("select[name=city] option:selected").text(),
	'customerPincode': '',
	'dealerName': $("select[name=dealer] option:selected").text(),
	'dealershipType': '',
	'customerGender': $('input[name=salutation]:checked').val(),
	'formSubmissionType': 'test drive',
	'videoName': '',
	'search_term': '',
	'ga_client_id': ga_client_id,
	'serviceType': '',
	'ServiceAppointmentDate': '',
	'ServiceAppointmentTime': '',
	'socialLinkName': '',
	'scrollPercentage': '',
	'SHAmob': sha256('+91'+$("input[name=mobile]").val()),
	'SHAemail': sha256($("input[name=email]").val())
  });

                dataLayer.push({
					'event':'Test-Drive_successfully_done',
					'vehicleName':datax.modelName,


				})

                
     var selectedDyModel=datax.modelName.replaceAll("/ /g","-").split('new-');
var skumodel=selectedDyModel[selectedDyModel.length-1];
/*window.VWO = window.VWO || [];
VWO.event = VWO.event || function () {VWO.push(["event"].concat([].slice.call(arguments)))};

VWO.event("request_a_test_drive", {
  "model_name": skumodel.toLowerCase(),
  "url_location": window.location.href
});*/



				_trackEvent(
					$.extend(_dl,
					{
						vehicle_name: datax.modelName, // Vehicle Name
						vehicle_model_code: datax.modelName, // Model Code
						page_event:
						{
							request_test_drive_complete: true, // test drive request (complete)
						}
					})
				);
               // floodlightTag(datax.modelName);
               // floodLightThankYou(datax.modelName);
				//submitTag();
                $("#request-a-test-drive").hide();
				$(".test").html(datax.dealeraddress);
				$(".dcmsg").html(datax.dealerName);
				$(".dmsg").html(datax.dealerMobile);
                $(".loader-overlay").hide();
				$("#step3").hide();
				$("#step2").show();
				$("#step2").focus();
				$("#idtofocus").focus();
				$(".conAreaM").focus();
				console.log("datax.dealeraddress"+datax.dealeraddress);
				sessionStorage.setItem("dealeraddress", datax.dealeraddress);
				sessionStorage.setItem("dealerName", datax.dealerName);
				//sessionStorage.setItem("dealerMobile", datax.dealerMobile);
			}
		},
		error: function(xhr, status, error)
		{
            $.ajaxPrefilter(function(options)
            {
                options.data = "";
            });
			var err = eval("(" + xhr.responseText + ")");
sessionStorage.setItem('mdEmail',md5($("input[name=email]").val()));
sessionStorage.setItem('mdMobile',md5($("input[name=mobile]").val()));
sessionStorage.setItem('shMob',sha256('+91'+$("input[name=mobile]").val()));
sessionStorage.setItem('shEmail',sha256($("input[name=email]").val()));
 dataLayer.push({
	'event':'FormSubmitFailure',
	'pageName': window.location.origin + window.location.pathname,
	'pageType': dataLayerPageType,
	'banner_position': '',
	'banner_title': '',
	'buttonTitle': 'Submit',
	'linkName': '',
	'sectionName': 'Test Drive',
     "errorMessage":err.message,
	'customerEmail': md5($("input[name=email]").val()),
	'customerMobile': md5($("input[name=mobile]").val()),
    'carCategory': '',
	'carModel': datax.modelName,
	'carModelVariant': $("#varient option:selected").text(),
	'carColour': '',
	'carFuelType': '',
	'transmission_type': '',
	'ex_showroom_price': '',
	'customerState': $("select[name=state] option:selected").text(),
	'customerCity': $("select[name=city] option:selected").text(),
	'customerPincode': '',
	'dealerName': $("select[name=dealer] option:selected").text(),
	'dealershipType': '',
	'customerGender': $('input[name=salutation]:checked').val(),
	'formSubmissionType': 'test drive',
	'videoName': '',
	'search_term': '',
	'ga_client_id': ga_client_id,
	'serviceType': '',
	'ServiceAppointmentDate': '',
	'ServiceAppointmentTime': '',
	'socialLinkName': '',
	'scrollPercentage': '',
	'SHAmob': sha256('+91'+$("input[name=mobile]").val()),
	'SHAemail': sha256($("input[name=email]").val())
  });
			//submitTag();
			$("#step2").hide();
			$("#step3").show();
			$("#step3").focus();
			window.location.href = "#step3";
			$(".loader-overlay").hide();
			$(".errmsg1").html(err.message);
            if(null != err.messageList){	
				$(".errmsg2").html(err.messageList[0]);
            }
			$(".errmsg1").focus();
		}
	}).done(function() {
		 floodLightThankYou(datax.modelName);

	});
}
$.urlParam = function(name)
{
	var results = new RegExp("[?&amp;]" + name + "=([^&amp;#]*)").exec(
		window.location.href
	);
	if (results == null)
	{
		return null;
	}
	else
	{
		return decodeURI(results[1]) || 0;
	}
};

if((sessionStorage.hasOwnProperty("utmSource") || sessionStorage.hasOwnProperty("utmMedium") || sessionStorage.hasOwnProperty("utmCampaign") || sessionStorage.hasOwnProperty("utmTerm") || sessionStorage.hasOwnProperty("utmContent") || sessionStorage.hasOwnProperty("source"))){
	utmSource = sessionStorage.getItem('utmSource');
	utmMedium = sessionStorage.getItem('utmMedium');
	utmCampaign = sessionStorage.getItem('utmCampaign');
	utmTerm = sessionStorage.getItem('utmTerm');
	utmContent = sessionStorage.getItem('utmContent');
	source = sessionStorage.getItem('source');
} else {
	utmSource = $.urlParam('utm_source');
	utmMedium = $.urlParam('utm_medium');
	utmCampaign = $.urlParam('utm_campaign');
	utmTerm = $.urlParam('utm_term');
	utmContent = $.urlParam('utm_content');
	source = $.urlParam('source');
}

function getBrowserId()
{
	var aKeys = ["MSIE", "Firefox", "Safari", "Chrome", "Opera"],
		sUsrAg = navigator.userAgent,
		nIdx = aKeys.length - 1;
	for (nIdx; nIdx &gt; -1 &amp;&amp; sUsrAg.indexOf(aKeys[nIdx]) === -1; nIdx--);
	return nIdx;
}

//function floodlightTag(carname)
//{
	//gtag('event', 'conversion',
	//{
	//	'allow_custom_scripts': true,
	//	'u1': carname,
	//	'send_to': 'DC-9077750/invmedia/userc0+standard'
	//});
//}

function floodLightThankYou(carname)
{
	gtag('event', 'form_submission',
	{
		'allow_custom_scripts': true,
		'u1': carname,
		'send_to': 'DC-9077750/invmedia/submi0+standard',
        'pageType': 'Test Drive',
		'buttonTitle': 'Submit',
		'formSubmissionType': 'Request Test Drive',
		'customerEmail':   sha256($("input[name=email]").val()),
		'customerMobile': sha256( $("input[name=mobile]").val()),
		'carModel': $("#car option:selected").text (),
		'customerState':  $("select[name=state] option:selected").text (),
		'customerCity':  $("select[name=city] option:selected").text (),
		'dealerName': $("select[name=dealer] option:selected").text (),
		'customerGender': $('input[name=salutation]:checked').val(),

	});
}

/*function submitTag()
{
	var page = window.location.pathname;
	page = page.replace('\/content\/hyundai', '');
	var ul = "https://" + window.location.hostname + page;
	return gtag_report_conversion(ul);
}*/

var sha256 = function sha256(ascii) {
	function rightRotate(value, amount) {
		return (value&gt;&gt;&gt;amount) | (value&lt;&lt;(32 - amount));
	};
	
	var mathPow = Math.pow;
	var maxWord = mathPow(2, 32);
	var lengthProperty = 'length'
	var i, j; // Used as a counter across the whole file
	var result = ''

	var words = [];
	var asciiBitLength = ascii[lengthProperty]*8;
	
	//* caching results is optional - remove/add slash from front of this line to toggle
	// Initial hash value: first 32 bits of the fractional parts of the square roots of the first 8 primes
	// (we actually calculate the first 64, but extra values are just ignored)
	var hash = sha256.h = sha256.h || [];
	// Round constants: first 32 bits of the fractional parts of the cube roots of the first 64 primes
	var k = sha256.k = sha256.k || [];
	var primeCounter = k[lengthProperty];
	/*/
	var hash = [], k = [];
	var primeCounter = 0;
	//*/

	var isComposite = {};
	for (var candidate = 2; primeCounter &lt; 64; candidate++) {
		if (!isComposite[candidate]) {
			for (i = 0; i &lt; 313; i += candidate) {
				isComposite[i] = candidate;
			}
			hash[primeCounter] = (mathPow(candidate, .5)*maxWord)|0;
			k[primeCounter++] = (mathPow(candidate, 1/3)*maxWord)|0;
		}
	}
	
	ascii += '\x80' // Append Æ‡' bit (plus zero padding)
	while (ascii[lengthProperty]%64 - 56) ascii += '\x00' // More zero padding
	for (i = 0; i &lt; ascii[lengthProperty]; i++) {
		j = ascii.charCodeAt(i);
		if (j&gt;&gt;8) return; // ASCII check: only accept characters in range 0-255
		words[i&gt;&gt;2] |= j &lt;&lt; ((3 - i)%4)*8;
	}
	words[words[lengthProperty]] = ((asciiBitLength/maxWord)|0);
	words[words[lengthProperty]] = (asciiBitLength)
	
	// process each chunk
	for (j = 0; j &lt; words[lengthProperty];) {
		var w = words.slice(j, j += 16); // The message is expanded into 64 words as part of the iteration
		var oldHash = hash;
		// This is now the undefinedworking hash", often labelled as variables a...g
		// (we have to truncate as well, otherwise extra entries at the end accumulate
		hash = hash.slice(0, 8);
		
		for (i = 0; i &lt; 64; i++) {
			var i2 = i + j;
			// Expand the message into 64 words
			// Used below if 
			var w15 = w[i - 15], w2 = w[i - 2];

			// Iterate
			var a = hash[0], e = hash[4];
			var temp1 = hash[7]
				+ (rightRotate(e, 6) ^ rightRotate(e, 11) ^ rightRotate(e, 25)) // S1
				+ ((e&amp;hash[5])^((~e)&amp;hash[6])) // ch
				+ k[i]
				// Expand the message schedule if needed
				+ (w[i] = (i &lt; 16) ? w[i] : (
						w[i - 16]
						+ (rightRotate(w15, 7) ^ rightRotate(w15, 18) ^ (w15&gt;&gt;&gt;3)) // s0
						+ w[i - 7]
						+ (rightRotate(w2, 17) ^ rightRotate(w2, 19) ^ (w2&gt;&gt;&gt;10)) // s1
					)|0
				);
			// This is only used once, so *could* be moved below, but it only saves 4 bytes and makes things unreadble
			var temp2 = (rightRotate(a, 2) ^ rightRotate(a, 13) ^ rightRotate(a, 22)) // S0
				+ ((a&amp;hash[1])^(a&amp;hash[2])^(hash[1]&amp;hash[2])); // maj
			
			hash = [(temp1 + temp2)|0].concat(hash); // We don't bother trimming off the extra ones, they're harmless as long as we're truncating when we do the slice()
			hash[4] = (hash[4] + temp1)|0;
		}
		
		for (i = 0; i &lt; 8; i++) {
			hash[i] = (hash[i] + oldHash[i])|0;
		}
	}
	
	for (i = 0; i &lt; 8; i++) {
		for (j = 3; j + 1; j--) {
			var b = (hash[i]&gt;&gt;(j*8))&amp;255;
			result += ((b &lt; 16) ? 0 : '') + b.toString(16);
		}
	}
	return result;
};
</pre></body></html>