﻿//#REGION Globals
//COMMONLY USED GLOBAL VARIABLES JAVASCRIPT GLOBAL VARIABLES: (JGB)
//if glbIsTesting =true then the activex will keep appending to a detailed log and the user will see error popups if javascript errors occur
var glbIsTesting = false;

//if glbIsLogging=true then the activex will keep appendiMPng to a log any problems or exceptions it has found
var glbIsLogging = false;

//the location of the log
var glbLogPath = "c:\\XPRESSVIP4.TXT";
var glbIsIE = /msie (\d+\.\d+);/.test(navigator.userAgent.toLowerCase());
var glbTotalErrors = 0;
var glbAXVersion = -1;
var glbIsVirginPage = true;
var glbAXObj = null;
var glbAXDetectReturnValue = "";
var glbAXD2DReadReturnValue = "";

//tell if the window has focus to start and stop the activex requests
var glbHasFocus = true;
//tell if the cookies are enabled or not
var glbCookies = false;
//tell if ajax is supported
var glbAJAX = false;
//keep the previously detected platformid to know if it was plugged/unplugged
var glbPreviousPlatformID;
//keep the previously detected firmware to know if it was plugged/unplugged
var glbPreviousFirmware;
//keep track of the last executed line number
var glbLn = 0; //also used in common.js
var glbHasPathAccess = false;
var glbPageLoadedAt = new Date();
//tell if the page is being unloaded, then ignore all errors
var glbIsPageUnloading = false;
window.onbeforeunload = function () {
	glbIsPageUnloading = true;
};
var glbRunSearch = false;

var glbAX1IsFlashing = false;
var glbAX1FlashingIsFinished = false;
var glbAX1URL = "./repository/firmwares/" + getURLParam("filename");
var glbAX1DownloadSec = 60;

var glbAX2TooltipObj;
var glbAX2InitializingDisplay = true;

//states
//reservation states (occurs at the same time as the waiting for results states)
//var glbAX2ReserveStates = { "none": 0, "ForFeatBrand": 1, "ForFeatSysType": 2, "ForFeatFeaturesDelete": 3, "ForFeatFeatures": 4, "ForFeatDataFeatures": 5, "ForFeatFOB": 6, "ForFeatEIPS": 7, "ForXPRESSKITID": 8, "ForFeatFlash": 9, "ForClose": 10 };
//var glbAX2WaitingStates = { "none": 0, "KitResults": 1, "FlashResults": 2, "IDsResults": 3, "ReadD2DResults": 4, "WriteD2DResults": 5, "WriteW2WResults": 6, "WriteEIPSResults": 7, "WriteFeatBrandResults": 8, "WriteFeatSysTypeResults": 9, 
//"WriteFeatFeaturesResults": 10, "WriteFeatDataFeaturesResults": 11, "DeleteFeatFeaturesResults": 12, "WriteFeatFOBResults": 13, "WriteFeatEIPSResults": 14, "WriteXPRESSKITIDResults": 15, "WriteFeatFlashResults": 16 };

//waiting for results states
//sl 167
var glbAX2WaitingStates = { "none": 0, "KitResults": 1, "FlashResults": 2, "IDsResults": 3, "ReadD2DResults": 4, "WriteD2DResults": 5, "WriteW2WResults": 6, "WriteEIPSResults": 7, "WriteKitCodeEntry": 8, "ReadHT2LOG": 9, "WriteFeatures": 10, "DeleteFeatures": 11, "WriteD2DTypeResults": 12, "VIPVersionUpgrade": 13, "W2WResults": 18, "D2DDeleteResults": 19};

//reservation states (occurs at the same time as the waiting for results states)
//sl 167
var glbAX2ReserveStates = { "none": 0, "ForFlashing": 1, "ForVehicle": 2, "ForD2D": 3, "ForEIPS": 4, "ForFeatBrand": 5, "ForFeatSysType": 6, "ForFeatFeatures": 7, "ForFeatEIPS": 8, "ForFeatFlash": 9, "ForFeatures": 10, "ForFeaturesDelete": 11, "ForKitCodeEntry": 12, "ForReadHT2LOG": 13, "ForD2DType": 14, "ForVIPVersionUpgrade": 15, "BusyWait": 16, "ForW2W": 18, "ForD2DDelete": 19};

var glbAX2WaitingState = 0;
var glbAX2ReserveState = 0;

var glbAX2KitVarsENum = { "platform": 0, "port_details": 1, "type_details": 3, "firmware_name": 4, "firmware_version": 6, "bootloader_details": 7, "glbAX2ID": 8, "port_conflict": 9, "error_details": 10, "glbAX2D2D": 11, "nvfs_dump": 12, "NVFSDumpEIPSEnabled": 13, "NVFSDumpEIPSShutdown": 14, "NVFSDumpEIPSAlertMinutes": 15, "NVFSDumpEIPSAlertSeconds": 16, "brand": 17, "hw_id": 18, "nvfs_platform": 19 };

//detected states
var glbKitStates = { "NotFound": 0, "Found": 1, "BrowserIncompatible": 2, "Install": 3, "xkloaderNotFound": 4, "noDriverFound": 5 };

var glbAX2ID = "";
var glbAX2URL = "./repository/firmwares/" + getURLParam("filename");
var glbAX2DownloadSec = 60;
var glbAX2NeedsExtraVariables = false;
var glbAX2W2W = "";
var glbAX2W2WAfterChanges = "";
var glbAX2W2WResults = "";
var glbAX2D2D_TYPE = "";
var glbAX2VehicleWrite = "";
var glbAX2VehicleResults = "";
var glbAX2ForceToDump = false;
var glbAX2Platform;
var glbAX3DriverFound = false;
var glbAX2Dump = "";

//sl 167
var glbD2DFunctionsTransport = { "d2dgroupid": 0, "d2d_id": 1, "d2d_tooltip": 2, "isEnabled": 3, "isAvailable": 4 };
var glbD2DGroupsTransport = { "d2dgroupid": 0, "groupname": 1, "groupdescription": 2, "groupEnabled": 3, "groupAvailable": 4, "checked": 5, "changed": 6 };
var glbKitFirmawreName = "";

//#ENDREGION

//#REGION XpressVIP Controller and functions common to both vip4.0 & vip4.2
//#region initializing
function initAutoRefresh() {
	if (glbIsVirginPage) {
		wsGetTermLocalized();

		//switch to test mode automatically if we detect the url contains LOCALHOST
		if (isInURL("localhost")) {
			glbIsTesting = true;
			glbIsLogging = true;
		}

		if (glbIsIE) {
			glbCookies = cookiesAreEnabled();
			glbAJAX = ajaxIsSupported();

			 if(glbServerDateTime!==null){
				if(glbServerDateTime.length===10){
					var dateArray = glbServerDateTime.split("/"); 
					var serverdate = new Date(parseInt(dateArray[0],10), parseInt(dateArray[1],10)-1, parseInt(dateArray[2],10)); 
					var clientDate = new Date();
					var one_day=1000*60*60*24;

					var daysDiff = Math.ceil((serverdate.getTime()-clientDate.getTime())/(one_day));

					if (daysDiff <= -3 || daysDiff >= 3) {
						eReport("", glbIP.toString() + "Detected client date (" + clientDate.toString() + ") compared to the server date (" + serverdate.toString() + ") is " + daysDiff + " days different. This may cause a problem for cookies");
					}
				}
			}

			initAXVersion(true);
			InitializeEmbedAX();

			if (isInPage("flashing")) {
				if (glbAXVersion === 1) {
					AX1PrepareFlashingInfo();
				}
				else if (glbAXVersion === 2 || glbAXVersion === 3) {
					AX2prepareFlashingInfo();
				}
			}
			//if it is vip4.0 then just find the kit once
			if (glbAXVersion === 1) {
				AX1RefreshKitClicked();
			}

			wsInitializeYear(glbLanguage, "-1", 1, glbCountry);
			glbIsVirginPage = false;
		}
		else {
			InitializeKitView(glbKitStates.BrowserIncompatible);
			wsInitializeYear(glbLanguage, "-1", 1, glbCountry);
		}
		glbCookies = cookiesAreEnabled();
		glbAJAX = ajaxIsSupported();

		//when this returns false usually because security level is set to high so isInPage breaks
		glbHasPathAccess = hasPermissionToPathname();
	}
	//if it is vip4.2,4.3 then autorefresh
	if (glbAXVersion === 2 || glbAXVersion === 3) {
		//D224
		if ((glbHasFocus || glbAX2WaitingState > glbAX2WaitingStates.KitResults || glbAX2ReserveState > glbAX2ReserveStates.none) && (glbAX2ReserveState != glbAX2ReserveStates.BusyWait)) {
			AX2PollKit();
		}
		if (glbAX2WaitingState !== glbAX2WaitingStates.none) setTimeout("initAutoRefresh()", 100); else setTimeout("initAutoRefresh()", 2e3)
	}
}

function initAXVersion(showPopupIfApplicable) {
	var showInstallPopup = false;
	var showUpdatePopup = false;
	var InstallDriver = false;
	//version detector
	try {
		glbAXObj = new ActiveXObject("XpressVIP4.3");		

		if (getURLParam("verbose") !== "") {
			glbIsTesting = true;
			glbIsLogging = true;
		}

		glbAXObj.Initialize(glbIsTesting, 400, 500, 1000);

		var driver = glbAXObj.DriverIsInstalled("silicon laboratories", "");
		//D220
		glbAX3DriverFound = (driver.toLowerCase().indexOf("silicon laboratories")!==-1);
		glbAXVersion = 3;
	}
	catch (ErrorAX) {
		try {
			glbAXObj = new ActiveXObject("XpressVIP4.2");

			if (getURLParam("verbose") !== "") {
				glbIsTesting = true;
				glbIsLogging = true;
			}
			glbAXObj.SUB_INITIALIZE(glbIsLogging, glbIsTesting, glbLogPath);

			glbAXVersion = 2;
		}
		catch (ErrorAX) {
			try {
				glbAXObj = new ActiveXObject("DIRECTED_SEARCH_HELPER_V1");
				showUpdatePopup = true;
				glbAXVersion = 1;

			}
			catch (ErrorAX) {
				showInstallPopup = true;
				InitializeKitView(glbKitStates.Install);

				//it is possible the user did not install the activex
				glbAXVersion = -1;
				InstallDriver = true;
			}
		}
	}
	if (showPopupIfApplicable) {
		if (showUpdatePopup) {
			if (isInPage("default.aspx") || isInPageExact("http://www.xpresskit.com/")) {
				if (getCookie("COOKIE_XPRESSVIP43_INSTALL_CLICKED") !== "1" && getCookie("COOKIE_REMIND_ME_XPRESSVIP43") !== "1") {
					InitializeInstallView43();
				}
			}
		}
		else if (showInstallPopup) {
			if (isInPage("default.aspx") || isInPageExact("http://www.xpresskit.com/")) {
				if (getCookie("COOKIE_XPRESSVIP43_INSTALL_CLICKED") !== "1" && getCookie("COOKIE_REMIND_ME_XPRESSVIP43") !== "1") {
					InitializeInstallView43();
				}
			}
		}
	}
}

function focusin() {
	glbHasFocus = true;
}
function focusout() {
	glbHasFocus = false;
}

if (glbIsIE) {
	if ("onfocusin" in document) {
		document.onfocusin = focusin;
		document.onfocusout = focusout;
	}
	else {
		window.onblur = focousout;
		window.onfocus = focusin;
	}
}

function InitializeInstallView() {
	$(document).ready(function () {
		tb_show("Install XpressVIP4.2", "xpressvip4v2_withdriver.aspx?height=400&width=500", "");
	});
}
function InitializeUpgradeView() {
	$(document).ready(function () {
		tb_show("Install XpressVIP4.2", "xpressvip4v2_nodriver.aspx?height=400&width=500", "");
	});
}
function InitializeInstallView43() {
	$(document).ready(function () {
		tb_show("Install XpressVIP4.3", "xpressvip4v3.aspx?height=400&width=500", "");
	});
}
function InitializeUpgradeView43() {
	$(document).ready(function () {
		tb_show("Install XpressVIP4.3", "xpressvip4v3_required.aspx?height=280&width=500", "");
	});
}

function InitShowOpenDocs() {
	//if there are no docs then just hide the open button
	if (document.getElementById("CHK_DOC1") !== null) {
		display("A_OpenDocs", "");
		document.getElementById("A_OpenDocs").style.visibility = "visible";
	}
}
//#endregion
//#region onresults callbacks

function OnYearResults(result) {
	try {
		clearDropDown("ddYear");
		clearDropDown("ddMake");
		clearDropDown("ddModel");

		if (session_year === "") { colorFade('ddYear', 'background', 'FF0000', 'FFFFFF', 5, 3); }
		document.getElementById("ddYear").disabled = false;
		document.getElementById("ddMake").disabled = true;
		document.getElementById("ddModel").disabled = true;

		if (result !== null) {
			var index = result.length;
			var i = 0;

			document.getElementById("ddYear").options[0] = new Option("Select Year", "Select Year");
			for (i = 0; i < index; i++) {
				document.getElementById("ddYear").options[i + 1] = new Option(result[i], result[i]);
			}

			if (session_year !== "") {
				if (!IsInHomePage()) {
					selectDropDown("ddYear", session_year);
				}
				FillMakeSelected();
			}
		}
	}
	catch (fnError) {
		eReport(fnError, "OnYearResults: error while processing year listing");
	}
}

function OnYearResultsFailed(result) {
	eReport(result, "OnYearResultsFailed: error while getting the year list from the dataservice");
}

function OnMakeResults(result) {
	try {
		clearDropDown("ddMake");
		clearDropDown("ddModel");
		document.getElementById("ddYear").disabled = false;
		document.getElementById("ddMake").disabled = false;
		document.getElementById("ddModel").disabled = true;

		if (session_make === "") { colorFade('ddMake', 'background', 'FF0000', 'FFFFFF', 5, 3); }

		if (result !== null) {
			var index = result.length;
			var i = 0;

			document.getElementById("ddMake").options[0] = new Option("Select Make", "Select Make");
			for (i = 0; i < index; i++) {
				document.getElementById("ddMake").options[i + 1] = new Option(result[i], result[i]);
			}

			if (session_make !== "") {
				selectDropDown("ddMake", session_make);
				fillModels();
			}
		}
	}
	catch (fnError) {
		eReport(fnError, "OnMakeResults: error while processing Makes listing");
	}
}

function OnModelResults(result) {
	try {
		clearDropDown("ddModel");

		document.getElementById("ddYear").disabled = false;
		document.getElementById("ddMake").disabled = false;
		document.getElementById("ddModel").disabled = false;

		if (session_model === "") { colorFade('ddModel', 'background', 'FF0000', 'FFFFFF', 5, 3); }

		if (result !== null) {
			var index = result.length;
			var i = 0;

			document.getElementById("ddModel").options[0] = new Option("Select Model", "Select Model");
			for (i = 0; i < index; i++) {
				document.getElementById("ddModel").options[i + 1] = new Option(result[i], result[i]);
			}

			if (session_model !== "") {
				if (!isInPage("vehiclecompatibility")) {
					selectDropDown("ddModel", session_model);
				}
				if (glbRunSearch) {
					if (isInPage("vehiclecompatibility.aspx")) {
						//force search if we are in vehiclecompatibility page
						//todo if the user had clicked back and is on vehiclecompatibility
						// need a way to relaunch the search
						DoVehicleSearch();
					}
				}
			}
		}
	}
	catch (fnError) {
		eReport(fnError, "OnModelResults: error while processing Models listing or executing search");
	}
}

function openFlashPage(Parameters) {
	if (glbAXVersion === 1) {
		window.location = "flashing.aspx" + Parameters;
	}
	else if (glbAXVersion === 2 || glbAXVersion === 3) {
		//window.location = "flashing2.aspx" + Parameters;
		window.location = "Kitflashing.aspx" + Parameters;
	}
}
//#endregion
//#region webservice calls
function wsInitializeMake(platformID, ddYear, State, Country, Language) {
	try {
		if ((isUInt(platformID) || platformID === "-1") && isUInt(ddYear) && isUInt(State) && isUInt(Country) && isUInt(Language)) {
			if (parseInt(platformID, 10) === 202) {
				platformID = -1;
			}

			DataService.InitializeMake(platformID, ddYear, State, Country, Language, OnMakeResults);
		}
	}
	catch (WSERROR) {
		eReport(WSERROR, "wsInitializeMake: " + platformID.toString());
	}
}

function wsInitializeModel(platformID, ddYear, ddMake, State, Country, Language) {	
	try {
		if ((isUInt(platformID) || platformID === "-1") && isUInt(ddYear) && isNonEmptyString(ddMake) && isUInt(State) && isUInt(Country) && isUInt(Language)) {

			if (parseInt(platformID, 10) === 202) {
				platformID = -1;
			}			
			DataService.InitializeModel(platformID, ddYear, ddMake, State, Country, Language, OnModelResults);
		}
	}
	catch (WSERROR) {
		eReport(WSERROR, "wsInitializeModel: error ;" + platformID.toString() + ", year" + ddYear.toString() + ", make" + ddMake.toString());
	}
}
//#endregion
//#region External calls
function FillMakeSelected() {

	//generic function for all ax versions
	try {

		var ddYearIndex = document.getElementById('ddYear').selectedIndex;
		var ddYear = document.getElementById('ddYear')[ddYearIndex].value;

		var platformID = getCookie("previous_platform");
		//if (platformID === "" || platformID === "NA" || platformID === null) { platformID = "-1"; }
		if (isUInt(platformID) === false) { platformID = "-1"; }
		if (ddYear != "Select Year") {
			document.getElementById("ddMake").disabled = true;
			document.getElementById("ddModel").disabled = true;
			wsInitializeMake(platformID, ddYear, 1, glbCountry, glbLanguage);
		}
		else {
			document.getElementById("ddYear").disabled = false;
			document.getElementById("ddMake").disabled = true;
			document.getElementById("ddModel").disabled = true;
		}
	}
	catch (fnError) {
		eReport(fnError, "FillMakeSelected: error while getting Makes listing");
	}
}
function fillModels() {
	try {

		var platformID = getCookie("previous_platform");

		if (isUInt(platformID) === false) { platformID = "-1"; }

		var ddYearIndex = document.getElementById('ddYear').selectedIndex;
		var ddYear = document.getElementById('ddYear')[ddYearIndex].value;

		var ddMakeIndex = document.getElementById('ddMake').selectedIndex;
		var ddMake = document.getElementById('ddMake')[ddMakeIndex].value;

		if (ddMake != "Select Make") {
			document.getElementById("ddModel").disabled = true;
			wsInitializeModel(platformID, ddYear, ddMake, 1, glbCountry, glbLanguage);
		}
		else {
			document.getElementById("ddYear").disabled = false;
			document.getElementById("ddMake").disabled = true;
			document.getElementById("ddModel").disabled = true;
		}
	}
	catch (fnError) {
		eReport(fnError, "fillModels: error while getting Models listing");
	}
}
function DoFlashingClicked() {
	if (glbAXVersion === 1) {
		AX1DoFlashing();
	}
	else if (glbAXVersion === 2 || glbAXVersion === 3) {
		AX2DoFlash();
	}
}
function OpenDocsClicked() {
	var docnum;

	docnum = 1;
	while (docnum < 30) {
		if (document.getElementById("CHK_DOC" + docnum) !== null) {
			var Checkbox = document.getElementById("CHK_DOC" + docnum);
			if (Checkbox.checked) { window.open(Checkbox.title); }
		}
		docnum++;
	}
}
function RunOptflashClicked() {
	try {
		RunOptFlash();
	}
	catch (fnError) {
		eReport(fnError, "RunOptflashClicked: error while trying to run optflash software");
	}
}
function RefreshKitClicked() {
	if (glbAXVersion === 1) {
		AX1RefreshKitClicked();
	}
	else if (glbAXVersion === 2 || glbAXVersion === 3) {
		AX2PollKit();
	}
}
function InitializeEmbedAX() {
	if (isInPage("flashing")) {
		var dvAXContainer = document.getElementById("dvAXContainer");

		//ADD THE APPROPRIATE OBJECT REFERENCE DEPENDING ON VERSION TO THE FLASHING PAGE
		if (glbAXVersion == 2) {
			setInnerHTML("dvAXContainer", "<object name='CABActivex'  id='CABActivex' classid='CLSID:A5843692-004F-4c37-BC07-624BBA56F810' codebase='/repository/downloads/xpressvip4_activex2.cab#version=1,0,0,0' border='2px' style=' border-color:#eeeeee'  width='0px' height='0px'></object>", false);
		}
	}
}
//#endregion
//#region Utility functions
function CategoryChanged() {
	try {
		var selectedYearIndex = document.getElementById('ddYear').selectedIndex;
		var selectedModelIndex = document.getElementById('ddModel').selectedIndex;
		var selectedMakeIndex = document.getElementById('ddMake').selectedIndex;
		var selectedCategoryIndex = document.getElementById('ddlCategory').selectedIndex;

		var currentPlatform = getCookie("previous_platform");
		if (currentPlatform == "NA") { currentPlatform = "-1"; }

		if (currentPlatform === "202") {
			//ignore xl202
			currentPlatform = -1;
		}

		var selectedState = 1;

		if (document.getElementsByName('rbState')[1].checked) {
			selectedState = 2;
		}
		else if (document.getElementsByName('rbState')[2].checked) {
			selectedState = 3;
		}

		var selectedCategory = document.getElementById('ddlCategory')[selectedCategoryIndex].value;
		if (selectedYearIndex > 0 && selectedMakeIndex > 0 && selectedModelIndex > 0) {
			var selectedYear = document.getElementById('ddYear')[selectedYearIndex].value;
			var selectedMake = document.getElementById('ddMake')[selectedMakeIndex].value;
			var selectedModel = document.getElementById('ddModel')[selectedModelIndex].value;

			window.location = "VehicleCompatibility.aspx?p=" + escape(currentPlatform) + "&year=" + escape(selectedYear) + "&make=" + escape(selectedMake) + "&model=" + escape(selectedModel) + "&ps=" + escape(selectedState) + "&s=0&c=" + escape(selectedCategory);
		}
		else if (isInPage("vehiclecompatibility") && getURLParam("year") !== "" && getURLParam("make") !== "" && getURLParam("model") !== "") {
			if (selectedCategory === getURLParam(escape("c"))) {
				window.location = "VehicleCompatibility.aspx?p=" + escape(currentPlatform) + "&year=" + getURLParam(escape("year")) + "&make=" + escape(getURLParam("make")) + "&model=" + escape(getURLParam("model")) + "&ps=" + escape(selectedState) + "&s=0&c=" + getURLParam(escape("c"));
			}
			else {
				window.location = "VehicleCompatibility.aspx?p=" + escape(currentPlatform) + "&year=" + getURLParam(escape("year")) + "&make=" + escape(getURLParam("make")) + "&model=" + escape(getURLParam("model")) + "&ps=" + escape(selectedState) + "&s=0&c=" + selectedCategory;
			}
		}
	}
	catch (fnError) {
		eReport(fnError, "DoVehicleSearch: error while redirecting to search results page");
	}
}
//sl 186 once deploy category with masterpage need to switch to this function
function DoVehicleSearch() {
	try {
		var selectedYearIndex = document.getElementById('ddYear').selectedIndex;
		var selectedModelIndex = document.getElementById('ddModel').selectedIndex;
		var selectedMakeIndex = document.getElementById('ddMake').selectedIndex;
		var selectedCategoryIndex = document.getElementById('ddlCategory').selectedIndex;

		var currentPlatform = getCookie("previous_platform");
		if (currentPlatform == "NA") { currentPlatform = "-1"; }

		if (currentPlatform === "202") { //ignore xl202
			currentPlatform = -1;
		}

		var selectedState = 1;

		if (document.getElementsByName('rbState')[1].checked) {
			selectedState = 2;
		}
		else if (document.getElementsByName('rbState')[2].checked) {
			selectedState = 3;
		}

		var selectedCategory = document.getElementById('ddlCategory')[selectedCategoryIndex].value;
		if (selectedYearIndex > 0 && selectedMakeIndex > 0 && selectedModelIndex > 0) {
			var selectedYear = document.getElementById('ddYear')[selectedYearIndex].value;
			var selectedMake = document.getElementById('ddMake')[selectedMakeIndex].value;
			var selectedModel = document.getElementById('ddModel')[selectedModelIndex].value;

			window.location = "VehicleCompatibility.aspx?p=" + escape(currentPlatform) + "&year=" + escape(selectedYear) + "&make=" + escape(selectedMake) + "&model=" + escape(selectedModel) + "&ps=" + escape(selectedState) + "&s=0&c=" + escape(selectedCategory);
		}
		else if (isInPage("vehiclecompatibility") && getURLParam("year") !== "" && getURLParam("make") !== "" && getURLParam("model") !== "") {
			window.location = "VehicleCompatibility.aspx?p=" + escape(currentPlatform) + "&year=" + getURLParam(escape("year")) + "&make=" + escape(getURLParam("make")) + "&model=" + escape(getURLParam("model")) + "&ps=" + escape(selectedState) + "&s=0&c=" + getURLParam(escape("c"));
		}
	}
	catch (fnError) {
		eReport(fnError, "DoVehicleSearch: error while redirecting to search results page");
	}
}

function SaveFlashingStats(KitID, VehicleID, PlatformID, FirmwareID, Flashed, VIP) {
	try {
		var browser_major = parseInt(navigator.appVersion, 10);
		var browser_minor = 0;

		//navigator.appMinorVersion doesnt exist for ie6
		if (typeof (navigator.appMinorVersion) !== 'undefined') {
			browser_minor = parseFloat(navigator.appMinorVersion, 10);
			if (isNaN(browser_minor)) {
				browser_minor = 0;
			}
		}

		if (!isUInt(KitID)) { KitID = "0"; }
		if (!isUInt(VehicleID)) { VehicleID = "0"; }
		if (isUInt(VehicleID) && isUInt(PlatformID) && isUInt(FirmwareID) && isUInt(Flashed)) {
			try {
				DataService.InsertStatisticsUserKitFlashing(removeLeftPadding(KitID, "0"), VehicleID, PlatformID, FirmwareID, os_code, browser_major, browser_minor, Flashed, VIP, glbCountry);
			}
			catch (error) { }
		}
		else {
			eReport("", "SaveFlashingStats: invalid parameter; " + KitID.toString() + "," + VehicleID.toString() + "," + PlatformID.toString() + "," + FirmwareID.toString() + "," + os_code.toString() + "," + browser_major.toString() + "," + browser_minor.toString() + "," + Flashed.toString() + "," + VIP.toString());
		}
	}
	catch (WSERROR) {
		eReport(WSERROR, "SaveFlashingStats: " + KitID.toString() + "," + VehicleID.toString() + "," + PlatformID.toString() + "," + FirmwareID.toString() + "," + os_code.toString() + "," + browser_major.toString() + "," + browser_minor.toString() + "," + Flashed.toString() + "," + VIP.toString());
	}
}
function IsEquivalent(v1, v2) {
	var v1_is_same_as_blank = false;
	var v2_is_same_as_blank = false;

	if (v1 === null) { v1_is_same_as_blank = true; }
	if (v2 === null) { v2_is_same_as_blank = true; }

	if (v1 == "") { v1_is_same_as_blank = true; }
	if (v2 == "") { v2_is_same_as_blank = true; }

	if (v1 == "NA") { v1_is_same_as_blank = true; }
	if (v2 == "NA") { v2_is_same_as_blank = true; }

	if (v1 == "-1") { v1_is_same_as_blank = true; }
	if (v2 == "-1") { v2_is_same_as_blank = true; }

	if (v1_is_same_as_blank && v2_is_same_as_blank) { return true; }
	else { return (v1 == v2); }
}
//#endregion
//#region version switch functions

function StartCommand(commandType, NVFSName, Value) {
	if (glbAXVersion === 2) {
		glbAXObj.SUB_START_RUN_NVFS_COMMAND_REQUEST(NVFSName, Value);
	}
	else if (glbAXVersion === 3) {
		glbAXObj.StartCommand(commandType, NVFSName, Value);
	}
}

function PopCommandResults() {
	if (glbAXVersion === 2) {
		return glbAXObj.FNC_POP_THREAD_NVFS_RESULTS();
	}
	else if (glbAXVersion === 3) {
		return glbAXObj.PopCommandResults();
	}
}

function StartKitInfo(GetDump) {
	if (glbAXVersion === 2) {
		glbAXObj.SUB_START_KIT_INFO_REQUEST(glbAX2InitializingDisplay || glbAX2ForceToDump);
	}
	else if (glbAXVersion === 3) {
		glbAXObj.StartKitInfo(glbAX2InitializingDisplay || glbAX2ForceToDump);
	}
}

function GetKitInfoResults() {
	if (glbAXVersion === 2) {
		return glbAXObj.FNC_GET_THREAD_KIT_INFO_RESULTS();
	}
	else if (glbAXVersion === 3) {
		return glbAXObj.GetKitInfoResults();
	}
}

function StartFlash(enc) {
	if (glbAXVersion === 2) {
		glbAXObj.SUB_START_FLASH_REQUEST(enc);
	}
	else if (glbAXVersion === 3) {
		glbAXObj.StartFlash(enc);
	}
}

function PopFlashResults() {
	if (glbAXVersion === 2) {
		return glbAXObj.FNC_POP_THREAD_FLASHING_RESULTS();
	}
	else if (glbAXVersion === 3) {
		return glbAXObj.PopFlashResults();
	}
}

function DriverIsInstalled(ContainedInDisplayName, ContainedInVersion) {
	if (glbAXVersion === 2) {
	}
	else if (glbAXVersion === 3) {
	}
}

function RunOptFlash() {
	if (glbAXVersion === 2) {
		glbAXObj.RUN_OPTFLASH();
	}
	else if (glbAXVersion === 3) {
		glbAXObj.RunOptFlash();
	}
}
//#endregion
//#ENDREGION

//#REGION XpressVIP4.0
//#region onresults callbacks
function onPlatformResults(platformName) {
	try {
		if (platformName !== null) {
			var index = platformName.length;
			if (index === 2) {
				var platformNameValue = platformName[0];
				var HasVehicleSpecificFirmwareValue = platformName[1];

				var platformName = document.getElementById("dPlatformName");
				setInnerText("dPlatformName", platformNameValue);

				var platformName2 = document.getElementById("dvPlatformInfo");
				if (platformName2 !== null) { setInnerText("dvPlatformInfo", platformNameValue); }
			}
		}
	}
	catch (fnError) {
		eReport(fnError, "");
	}
}

function onPlatformError(result) {
	eReport(result, "");
}

function onYearResults(result) {
	clearDropDown("ddYear");
	clearDropDown("ddMake");
	clearDropDown("ddModel");

	if (session_year == "") { colorFade('ddYear', 'background', 'FF0000', 'FFFFFF', 5, 3); }
	document.getElementById("ddYear").disabled = false;
	document.getElementById("ddMake").disabled = true;
	document.getElementById("ddModel").disabled = true;

	if (result !== null) {
		var index = result.length;
		var i = 0;

		document.getElementById("ddYear").options[0] = new Option("Select Year", "Select Year");
		for (i = 0; i < index; i++) {
			document.getElementById("ddYear").options[i + 1] = new Option(result[i], result[i]);
		}

		if (session_year != "") {
			selectDropDown("ddYear", session_year);
			FillMakeSelected();
		}
	}
}

function onYearResultsFailed(result) {
	eReport(result, "error while getting the year list from the dataservice");
}

function onMakeResults(result) {
	clearDropDown("ddMake");
	clearDropDown("ddModel");
	document.getElementById("ddYear").disabled = false;
	document.getElementById("ddMake").disabled = false;
	document.getElementById("ddModel").disabled = true;

	if (session_make == "") { colorFade('ddMake', 'background', 'FF0000', 'FFFFFF', 5, 3); }

	if (result !== null) {
		var index = result.length;
		var i = 0;

		document.getElementById("ddMake").options[0] = new Option("Select Make", "Select Make");
		for (i = 0; i < index; i++) {
			document.getElementById("ddMake").options[i + 1] = new Option(result[i], result[i]);
		}

		if (session_make != "") {
			if (!isInPage("vehiclecompatibility")) {
				selectDropDown("ddMake", session_make);
			}
			fillModels();
		}
	}
}

function onModelResults(result) {
	clearDropDown("ddModel");

	document.getElementById("ddYear").disabled = false;
	document.getElementById("ddMake").disabled = false;
	document.getElementById("ddModel").disabled = false;

	if (session_model == "") { colorFade('ddModel', 'background', 'FF0000', 'FFFFFF', 5, 3); }

	if (result !== null) {
		var index = result.length;
		var i = 0;

		document.getElementById("ddModel").options[0] = new Option("Select Model", "Select Model");
		for (i = 0; i < index; i++) {
			document.getElementById("ddModel").options[i + 1] = new Option(result[i], result[i]);
		}

		if (session_model != "") {
			if (!isInPage("vehiclecompatibility")) {
				selectDropDown("ddModel", session_model);
			}
			if (glbRunSearch) {
				if (isInPage("vehiclecompatibility.aspx")) {
					//force search if we are in vehiclecompatibility page
					//todo if the user had clicked back and is on vehiclecompatibility
					// need a way to relaunch the search
					DoVehicleSearch();
				}
			}
		}
	}
}
//#endregion

//#region External Calls
function AX1RefreshKitClicked() {
	if (!glbAX1IsFlashing) {
		var kitinfo = document.getElementById("kitinfo");
		var errorinfo = document.getElementById("errorinfo");
		var kitLED = document.getElementById("kitLED");
		var btn_refresh = document.getElementById("btn_refresh");

		if (glbCookies) {
			glbPreviousPlatformID = getCookie("previous_platform");
			glbPreviousFirmware = getCookie("previous_firmware");
		}

		var firmware = document.getElementById("dFirmware");

		var platform = "-1";
		var platform_details = "";
		var port_details = "";
		var type_details = "";
		var firmware_details = "";
		var bootloader_details = "";

		var dvkitDetect = document.getElementById("dvkitDetect");
		var dvkitInstall = document.getElementById("dvkitInstall");

		var tbKit = document.getElementById("tbKit");

		var platformname;

		if (glbIsIE) {
			try {
				var glbAXObj = new ActiveXObject("DIRECTED_SEARCH_HELPER_V1");

				try {
					if (isInPage("flashing.aspx") && !glbAX1FlashingIsFinished) {
						dvkitDetect.style.visibility = "hidden";
						dvkitInstall.style.visibility = "hidden";
						tbKit.style.visibility = "hidden";

						display("dvkitDetect", "none");
						display("dvkitInstall", "none");
						display("tbKit", "none");

						platform = getURLParam("p");
						firmware_details = getURLParam("filename");

						if (platform != "-1" && platform != "NA") {

							setInnerText("dFirmware", firmware_details);

							platformname = document.getElementById("dPlatformName");
							setInnerText("dPlatformName", platform);

							DataService.GetPlatformName(platform, onPlatformResults, onPlatformError);
						}
					}
					else if (!isInPage("flashing.aspx") || glbAX1FlashingIsFinished) {
						dvkitDetect.style.visibility = "visible";
						dvkitInstall.style.visibility = "hidden";
						tbKit.style.visibility = "visible";

						display("dvkitDetect", "");
						display("dvkitInstall", "none");
						display("tbKit", "");

						glbAXDetectReturnValue = "";

						try {
							glbAXDetectReturnValue = glbAXObj.Get_Kit_Info();
						}
						catch (ErrorAX) {
							//unknown error occured while getting info from kit
							eReport(ErrorAX, "unexpected error while trying to get kit information");
						}

						platform = glbAXDetectReturnValue.slice(0, 49).replace(/\s*$/, "");
						platform_details = glbAXDetectReturnValue.slice(50, 99).trimall();
						port_details = glbAXDetectReturnValue.slice(100, 149).trimall();
						type_details = glbAXDetectReturnValue.slice(150, 199).trimall();
						firmware_details = glbAXDetectReturnValue.slice(200, 249).trimall();
						bootloader_details = glbAXDetectReturnValue.slice(250, 299).trimall();

						if (glbPreviousPlatformID != platform || glbPreviousFirmware != firmware_details || glbIsVirginPage) {

							if (isUInt(platform) === true) {

								setInnerText("dFirmware", firmware_details);

								platformname = document.getElementById("dPlatformName");
								setInnerText("dPlatformName", platform);

								DataService.GetPlatformName(platform, onPlatformResults, onPlatformError);

								if (isInPage("flashing.aspx") && !glbAX1FlashingIsFinished) {
									btn_refresh.style.visibility = 'hidden';
									kitinfo.style.visibility = 'hidden';
									errorinfo.style.visibility = 'hidden';
								}
								else {
									btn_refresh.style.visibility = 'visible';
									kitinfo.style.visibility = 'visible';
									errorinfo.style.visibility = 'hidden';
								}

								kitLED.src = 'images/kit_on.gif';
								kitLED.title = 'Device Connected.';
								kitinfo.style.height = 35;
								errorinfo.style.height = 0;

								btn_refresh.width = 38;
								btn_refresh.height = 35;

								tbKit.style.visibility = "visible";
								display("tbKit", "");

							}
							else {

								setInnerHTML("errorinfo", "<span style='font-size:10px' >Plug in device and click " + "<a id='a_refresh' title='Refresh' href='#' onclick='AX1RefreshKitClicked();return false;'>REFRESH</a></span><br /><span style='font-size:11px'>To flash <span style='color:Red;'>OPTIMAX</span> products click <a id='a_fortin'  title='To flash OPTIMAX products such as PKALL, DLPKGM' href='#' onclick='RunOptflashClicked();return false;'>HERE</a></span>", false);

								btn_refresh.style.visibility = 'hidden';
								kitinfo.style.visibility = 'hidden';
								errorinfo.style.visibility = 'visible';

								kitinfo.style.height = 0;
								errorinfo.style.height = 35;

								btn_refresh.width = 0;
								btn_refresh.height = 0;

								kitLED.src = 'images/kit_off.gif';
								kitLED.title = 'Device Not Connected.';

								tbKit.style.visibility = "visible";
								display("tbKit", "");

								setInnerText("dFirmware", "");
							}
						}
					}
				}
				catch (ErrorObj) {
					//unknown error occured while getting info from kit
					eReport(ErrorObj, "unexpected error");
				}
			}
			catch (ErrorObj2) {
				InitializeKitView(glbKitStates.Install);
			}
		}

		//refresh year drop down when the state if the platform detection changed
		if (!IsEquivalent(glbPreviousPlatformID, platform) || !IsEquivalent(glbPreviousFirmware, firmware_details) || glbIsVirginPage) {

			clearDropDown("ddYear");

			if (isInPage("vehiclecompatibility") && !glbIsVirginPage && (glbPreviousPlatformID != platform || glbPreviousFirmware != firmware_details)) {
				glbRunSearch = true;
			}

			if (glbCookies) {
				//if cookies are enabled then the plaform and firmware info can survive postbacks and page changes
				setCookie("previous_platform", platform);
				setCookie("previous_firmware", firmware_details);
			}
			else {
				//if cookies are disabled then the plaform and firmware info cannot survive postbacks
				// so store it locally in the global variables
				glbPreviousPlatformID = platform;
				glbPreviousFirmware = firmware_details;
			}

			if (isUInt(platform) === true) {
				wsInitializeYear(glbLanguage, platform, 1, glbCountry);
			}
			else {
				//if (platform === "NA" || platform === "") { }
				wsInitializeYear(glbLanguage, "-1", 1, glbCountry);
			}
		}

		glbIsVirginPage = false;
	}
}

function AX1PrepareFlashingInfo() {
	setInnerText("dvFirmwareInfo", "Flashing Firmware: " + getURLParam("filename"));
	setInnerText("dvVehicleInfo", "For Vehicle: " + getURLParam("year") + " " + getURLParam("make") + " " + getURLParam("model"));
	document.getElementById("A_BACK").href = "VehicleCompatibility.aspx?p=" + escape(getURLParam("p")) + "&year=" + escape(getURLParam("year")) + "&make=" + escape(getURLParam("make")) + "&model=" + escape(getURLParam("model")) + "&ps=1&s=0";

	var URLForPreDownloadTest;
	URLForPreDownloadTest = "./repository/firmwares/performance_packet_test_file.txt";

	var before = new Date();

	$.ajax({
		url: URLForPreDownloadTest,
		type: 'GET',
		//async: false,
		cache: false,
		timeout: 7000,
		error: function (data) {
			//document.getElementById("CABActivex").Show_Message_In_Label("The download test failed.",true);
			var error_msg = "connecting to firmware repository failed when trying to access the download-speed file (performance_packet_test_file.txt). Please contact a support representative.";

			eReport(data, error_msg);

			glbAX1FlashingIsFinished = true;

			return true;
		},
		success: function (data) {
			//estimate the time it will take to download the file with a small test file
			var after = new Date();
			var elapsed = after.getTime() - before.getTime();
			var size_in_bytes = data.length;

			var request;
			request = $.ajax({
				type: "HEAD",
				url: glbAX1URL,
				timeout: 7000,
				success: function () {

					var EncFileSizeBytes;
					EncFileSizeBytes = request.getResponseHeader("Content-Length");

					glbAX1DownloadSec = parseInt(elapsed / size_in_bytes * EncFileSizeBytes / 1000, 0);

					setInnerText("dvEstimatedTimeToDownload", "Download taking: " + glbAX1DownloadSec + " seconds ");

					if (EncFileSizeBytes / 1000 > 0) { setInnerText("dvFirmwareSize", "Firmware Size: " + parseInt(EncFileSizeBytes / 1000, 0) + "kb "); }
					else if (EncFileSizeBytes / 1000 > 0) { setInnerText("dvFirmwareSize", "Firmware Size: " + EncFileSizeBytes + "bytes "); }
					document.getElementById("dvFlashNow").style.visibility = "visible";

				},
				error: function (data) {

					var error_msg = "Retrieving the firmware file information failed. Please contact a support representative for assistance.";

					eReport(data, error_msg);
					document.getElementById("CABActivex").Show_Message_In_Label(error_msg, true);

					glbAX1FlashingIsFinished = true;

					return true;
				}
			});
		}
	});
}

function AX1DoFlashing() {
	glbAX1IsFlashing = true;

	document.getElementById("dvFlashNow").style.visibility = "hidden";
	document.getElementById("imFlashNow").width = 0;
	document.getElementById("imFlashNow").height = 0;
	document.getElementById("dvFlashAgain").style.visibility = "hidden";
	document.getElementById("imFlashAgain").width = 0;
	document.getElementById("imFlashAgain").height = 0;
	document.getElementById("CABActivex").width = 325;
	document.getElementById("CABActivex").height = 223;

	if (glbAX1FlashingIsFinished) {
		document.getElementById("CABActivex").Show_Message_In_Label("Preparing communication with kit, this will take 5 seconds.", true);

		//wait a few seconds to allow any previous refreshes to finish
		setTimeout("AX1DoFlashingWhenReady();", 5000);
	}
	else {
		AX1DoFlashingWhenReady();
	}
}
//#endregion

//internal function
function AX1DoFlashingWhenReady() {

	$.ajax({
		url: glbAX1URL,
		type: 'GET',
		async: false,
		cache: false,
		timeout: glbAX1DownloadSec * 10,
		error: function (msg, text) {
			var error_msg = "The firmware file failed to download. It was estimating a download taking " + glbAX1DownloadSec + " seconds. Please contact a support representative for assistance. ";
			if (text !== null) { error_msg += " Technical Details: " + text; }

			eReport(null, error_msg);

			document.getElementById("CABActivex").Show_Message_In_Label(error_msg, true);

			glbAX1FlashingIsFinished = true;

			initAutoRefresh();

			return true;
		},
		success: function (data) {

			var glbAX2ID = ""; //vip4.0 we cannot read the id of the kit
			var VehicleID = getURLParam("vehicleid");
			var PlatformID = getURLParam("p");
			var FirmwareID = getURLParam("firmwareid");

			glbFlashingStartedAt = new Date();

			var Result = document.getElementById("CABActivex").flash_file(data);
			if (Result == 1) {
				document.getElementById("CABActivex").width = 1;
				document.getElementById("CABActivex").height = 1;

				document.getElementById("dvFlashAgain").style.visibility = "visible";

				document.getElementById("imFlashAgain").width = 225;
				document.getElementById("imFlashAgain").height = 223;

				document.getElementById("imFlashNow").width = 0;
				document.getElementById("imFlashNow").height = 0;

				try {
					SaveFlashingStats(glbAX2ID, VehicleID, PlatformID, FirmwareID, "1", "41");
				} catch (exceptionerr) {
					eReport(exceptionerr, "AX1doFlashingWhenReadyer:error while trying to record flash stats");
				}
			}
			else {
				var error_msg = "A problem occured while trying to flash the kit. This may have happened if the kit was unplugged or the website was interrupted. Try to flash the kit again or click the link below for assistance.";

				eReport(null, error_msg);
				document.getElementById("CABActivex").Show_Message_In_Label(error_msg, true);

				try {
					SaveFlashingStats(glbAX2ID, VehicleID, PlatformID, FirmwareID, "2", "41");
				} catch (exceptionerr) {
					eReport(exceptionerr, "AX1doFlashingWhenReadyer:error while trying to record flash stats");
				}
			}

			glbAX1FlashingIsFinished = true;
			initAutoRefresh();
		}
	});

	glbAX1IsFlashing = false;
}

function wsInitializeYear(languageID, platformID, status, country) {
	try {
		if (isUInt(status) && isUInt(country) && isUInt(languageID) && (isUInt(platformID) || platformID === "-1")) {
			if (parseInt(platformID, 10) === 202)
				platformID = -1;

			DataService.InitializeYear(parseInt(languageID, 10), parseInt(platformID, 10), parseInt(country, 10), parseInt(status, 10), OnYearResults, OnYearResultsFailed);
		}
	}
	catch (WSERROR) {
		eReport(WSERROR, "wsInitializeYear: " + platformID.toString());
	}
}
//#ENDREGION

//#REGION XpressVIP4.2
//#region Polling functions
//important high-level procedure timed to automatically fire every 2 seconds to prevent kit communication collisions
function AX2PollKit() {
	try {
		//do not show the kit info box when browser is not IE
		if (!glbIsIE) {
			InitializeKitView(glbKitStates.BrowserIncompatible);
		}
		else {
			glbLn = 399;

			//if the next operation is not reserved
			//and not waiting for any results then just try to detect the kit by default
			if (glbAX2WaitingState === glbAX2WaitingStates.none && glbAX2ReserveState === glbAX2ReserveStates.none) {
				StartKitInfo(glbAX2InitializingDisplay || glbAX2ForceToDump);
				glbAX2WaitingState = glbAX2WaitingStates.KitResults;
			}
			else if (glbAX2WaitingState === glbAX2WaitingStates.ReadD2DResults) {
				AX2PollAndDisplayNVFSReadD2DResults();
			}
			else if (glbAX2WaitingState === glbAX2WaitingStates.WriteFeatEIPSResults) {
				AX2PollAndDisplayNVFSWriteFeatureEIPSResults();
			}
			else if (glbAX2WaitingState === glbAX2WaitingStates.WriteFeatSysTypeResults) {
				AX2PollAndDisplayNVFSWriteFeatureSysTypeResults();
			}
			else if (glbAX2WaitingState === glbAX2WaitingStates.WriteFeatBrandResults) {
				AX2PollAndDisplayNVFSWriteFeatureBrandsResults();
			}
			else if (glbAX2WaitingState === glbAX2WaitingStates.WriteFeatFeaturesResults) {
				AX2PollAndDisplayNVFSWriteFeatureResults();
			}
			else if (glbAX2WaitingState === glbAX2WaitingStates.WriteFeatFlashResults) {
				AX2PollAndDisplayNVFSWriteFeatureFlashResults();
			}
			else if (glbAX2WaitingState === glbAX2WaitingStates.WriteW2WResults) {
				AX2PollAndDisplayNVFSWriteW2WResults();
			}
			else if (glbAX2WaitingState === glbAX2WaitingStates.KitResults) {
				AX2PollAndDisplayKitInfo();
			}
			else if (glbAX2WaitingState === glbAX2WaitingStates.FlashResults) {
				AX2PollAndDisplayFlashInfo();
			}
			else if (glbAX2WaitingState === glbAX2WaitingStates.IDsResults) {
				AX2PollAndDisplayFlashIDsInfo();
			}
			else if (glbAX2WaitingState === glbAX2WaitingStates.WriteEIPSResults) {
				AX2PollAndDisplayEIPSResults();
			}
			else if (glbAX2WaitingState === glbAX2WaitingStates.DeleteFeatures) {
				AX2PollAndDisplayDeleteFeaturesResults();
			}
			else if (glbAX2WaitingState === glbAX2WaitingStates.WriteFeatures) {
				AX2PollAndDisplayFeaturesResults();
			}
			else if (glbAX2WaitingState === glbAX2WaitingStates.WriteD2DTypeResults) {
				AX2PollAndDisplayD2DTypeResults();
			}
			else if (glbAX2WaitingState === glbAX2WaitingStates.D2DDeleteResults) {
				//sl 167
				AX2PollAndDisplayNVFSDeleteD2DResults();
			}
			else if (glbAX2WaitingState === glbAX2WaitingStates.WriteD2DResults) {
				AX2PollAndDisplayNVFSWriteD2DResults();
			}
			else if (glbAX2WaitingState === glbAX2WaitingStates.WriteKitCodeEntry) {
				AX2PollAndDisplayCodeEntryResults();
			}
			else if (glbAX2WaitingState === glbAX2WaitingStates.VIPVersionUpgrade) {
				AX2PollAndDisplayAXVersionDetection();
			}
			else if (glbAX2WaitingState === glbAX2WaitingStates.ReadHT2LOG) {
				AX2PollAndDisplayReadHT2LOGResults();				
			}
			else if (glbAX2ReserveState === glbAX2ReserveStates.ForKitCodeEntry) {
				ResetReserve();
				glbAX2WaitingState = glbAX2WaitingStates.WriteKitCodeEntry;

				AX2DoWriteCodeEntryWhenReady();
			}
			else if (glbAX2ReserveState === glbAX2ReserveStates.ForReadHT2LOG) {
				ResetReserve();
				glbAX2WaitingState = glbAX2WaitingStates.ReadHT2LOG;
				
				AX2DoReadHT2LOGWhenReady();
			}
			else if (glbAX2ReserveState === glbAX2ReserveStates.ForFlashing) {
				ResetReserve();
				glbAX2WaitingState = glbAX2WaitingStates.FlashResults;

				AX2InitializeFlashingView(glbAX2FlashStates.Flashing, 0);

				AX2DoFlashingWhenReady();

			}
			else if (glbAX2ReserveState === glbAX2ReserveStates.ForVehicle) {
				ResetReserve();
				glbAX2WaitingState = glbAX2WaitingStates.IDsResults;
				//sl 167
				AX2ResetCompletedFlags();
				AX2DoFlashingIDsWhenReady();
			}
			else if (glbAX2ReserveState === glbAX2ReserveStates.ForEIPS) {
				ResetReserve();
				glbAX2WaitingState = glbAX2WaitingStates.WriteEIPSResults;

				AX2DoFlashingEIPSFeatureWhenReady();
				AX2InitializeFlashingView(glbAX2FlashStates.WaitEIPS, 99);

			}
			else if (glbAX2ReserveState === glbAX2ReserveStates.ForFeaturesDelete) {
				ResetReserve();
				glbAX2WaitingState = glbAX2WaitingStates.DeleteFeatures;

				StartCommand(3, "FEAT_FW_" + glbFirmwarePrefix, "");
				AX2InitializeFlashingView(glbAX2FlashStates.WaitFeatures, 99);
			}
			else if (glbAX2ReserveState === glbAX2ReserveStates.ForFeatures) {
				ResetReserve();
				glbAX2WaitingState = glbAX2WaitingStates.WriteFeatures;

				StartCommand(1, "FEAT_FW_" + glbFirmwarePrefix, glbAX2DataFeaturesWrite);

				AX2InitializeFlashingView(glbAX2FlashStates.WaitFeatures, 99);
			}
			else if (glbAX2ReserveState === glbAX2ReserveStates.ForD2DType) {
				ResetReserve();
				glbAX2WaitingState = glbAX2WaitingStates.WriteD2DTypeResults;

				StartCommand(1, "D2D_TYPE", glbAX2D2DTypeWrite);
				AX2InitializeFlashingView(glbAX2FlashStates.WaitD2DType, 99);
			}
			else if (glbAX2ReserveState === glbAX2ReserveStates.ForD2DDelete) {
				//sl 167
				AX2ExecuteDeleteD2D();
			}
			else if (glbAX2ReserveState === glbAX2ReserveStates.ForD2D) {
				AX2ExecuteSaveD2D();
			}
			else if (glbAX2ReserveState === glbAX2ReserveStates.ForVIPVersionUpgrade) {
				ResetReserve();
				glbAX2WaitingState = glbAX2WaitingStates.VIPVersionUpgrade;
			}			
		}
	}
	catch (fnError) {
		eReport(fnError, "AX2PollKit: error while refreshing kit status");
	}
}

//sl 180 move ResetReserveWait,ResetReserve,ResetWait to common.js

function AX2PollAndDisplayKitInfo() {
	try {
		var kitinfo = document.getElementById("kitinfo");
		var errorinfo = document.getElementById("errorinfo");
		var btn_refresh = document.getElementById("btn_refresh");
		var firmware = document.getElementById("dFirmware");
		var platformname = document.getElementById("dPlatformName");

		//get the platform and firmware info from the cookies
		glbPreviousPlatformID = getCookie("previous_platform");
		glbPreviousFirmware = getCookie("previous_firmware");

		glbAXDetectReturnValue = GetKitInfoResults();

		if (isNonEmptyString(glbAXDetectReturnValue)) {

			if (glbAXVersion === 3 && !glbAX3DriverFound) {
				InitializeKitView(glbKitStates.noDriverFound);
			}
			else {
				var kcReq = false;
				//-2 means no xkloader found
				if (glbAXDetectReturnValue === "-2") {
					InitializeKitView(glbKitStates.xkloaderNotFound);
					ResetWait();
					glbPreviousPlatformID = "";
					glbPreviousFirmware = "";
				}
				else {
					//if the results are ready, return value and change the state to not waiting
					ResetWait();

					var Vars = AX2GetKitVarsFromKitDetails(glbAXDetectReturnValue);

					glbAX2ID = Vars[glbAX2KitVarsENum.glbAX2ID];
					glbAX2D2D = Vars[glbAX2KitVarsENum.glbAX2D2D];

					var firmware_details = (Vars[glbAX2KitVarsENum.firmware_name] + " " + Vars[glbAX2KitVarsENum.firmware_version]).trimall();

					var KitDetailsChanged = (glbAX2InitializingDisplay || !IsEquivalent(glbPreviousPlatformID, Vars[glbAX2KitVarsENum.platform]) || !IsEquivalent(glbPreviousFirmware, firmware_details));

					if (glbAX2InitializingDisplay || glbAX2ForceToDump) {
						//sometimes a dball may have a dump but no id if it is a prototype
						if (typeof (Vars[glbAX2KitVarsENum.nvfs_dump]) != "undefined" && typeof (Vars[glbAX2KitVarsENum.glbAX2ID]) != "undefined") {
							if (Vars[glbAX2KitVarsENum.nvfs_dump] !== null && Vars[glbAX2KitVarsENum.nvfs_dump] !== "" && Vars[glbAX2KitVarsENum.glbAX2ID] !== null && Vars[glbAX2KitVarsENum.glbAX2ID] !== "") {
								glbLn = 989;

								//since firmware is not in the dump then just add it manually since we need it in the reports
								Vars[glbAX2KitVarsENum.nvfs_dump] += "++++firmware_details====" + firmware_details;
								//output the dump to the database
								wsKitDump(Vars[glbAX2KitVarsENum.glbAX2ID], Vars[glbAX2KitVarsENum.nvfs_dump], firmware_details);
								glbAX2ForceToDump = false;
								
								if (AX2GetVariableValuesFromDump('HT2_LOG').length > 0) {
									//kcReq = true;
								}
							}
						}

						if (isInPage("flashing2")) {
							InitShowOpenDocs();
						}
					}
					glbLn = 1007;

					var KitIsConnected = isUInt(Vars[glbAX2KitVarsENum.platform]);
					if(!KitIsConnected)
					{
						glbAX2ForceToDump = true;
					}
					//things to do when we detect a change in kit (plugged/unplugged)
					if (KitDetailsChanged) {
						var KitSearchID = getURLParam("KitSearchID");
						var KitConnectedID = getURLParam("KitConnectedID");
						
						//get the firmwares if the vehicle does not apply
						if (Vars[glbAX2KitVarsENum.platform] !== "") {
							wsGetFirmwares(Vars[glbAX2KitVarsENum.platform]);
						}

						//things to do in specific pages
						if (isInPage("flashing")) {
							var VehicleID = getURLParam("vehicleid");
							var PlatformID = getURLParam("p");
							var FirmwareID = getURLParam("firmwareid");

							glbLn = 409;
							var EIPSExists = (Vars[glbAX2KitVarsENum.NVFSDumpEIPSEnabled] !== null);

							InitializeEIPS(Vars);

							wsGetIsPlatformCompatFW(Vars[glbAX2KitVarsENum.platform], FirmwareID, glbAX2InitializingDisplay, EIPSExists);
						}
						else if (isInPage("kit.aspx")) {
							AX2PollAndDisplayKitPage(KitSearchID, KitConnectedID, Vars);
							//AX2InitializeKitFeaturesIframe(Vars);

						}
						else if (IsInHomePage()) {
							AX2InitializeFeaturesPopup(Vars);
						}

						//things to do for the header
						setInnerText("dFirmware", firmware_details);
						setInnerText("dPlatformName", Vars[glbAX2KitVarsENum.platform]);

						if (isUInt(Vars[glbAX2KitVarsENum.platform]) === true) {
							glbLn = 1014;

							//request the platform name
							wsGetPlatformName(Vars[glbAX2KitVarsENum.platform], (isUInt(KitConnectedID) || isInPage("flashing")));
							InitializeKitView(glbKitStates.Found);
						}
						else {
							glbLn = 1041;
							InitializeKitView(glbKitStates.NotFound);
						}

						//update the cookies if possible
						if (glbCookies) {
							glbLn = 1060;
							//if cookies are enabled then the plaform and firmware info can survive postbacks and page changes
							setCookie("previous_platform", Vars[glbAX2KitVarsENum.platform]);
							setCookie("previous_firmware", firmware_details);
						}
						else {
							//if cookies are disabled then the plaform and firmware info cannot survive postbacks
							// so store it locally in the global variables
							glbPreviousPlatformID = Vars[glbAX2KitVarsENum.platform];
							glbPreviousFirmware = firmware_details;
						}

						if (!glbAX2InitializingDisplay && isInPage("vehiclecompatibility.aspx")) {
							glbRunSearch = true;
							DoVehicleSearch();
						}
						else if (getURLParam("p") === "-1" && isUInt(Vars[glbAX2KitVarsENum.platform]) && isInPage("vehiclecompatibility.aspx")) {
							//patch; when following link from directechs the plaform parameter will not be known 
							//so need to relaunch search
							//glbRunSearch = true;
							DoVehicleSearch();
						}

						//put the platfrom and firmware info in a cookie so that if go to another page
						// it will not have refresh the drop downs
						glbLn = 1057;

						//reinitialize the year dropdowns when a change in module is detected
						if (isUInt(Vars[glbAX2KitVarsENum.platform]) === true) {
							glbLn = 1073;
							wsInitializeYear(glbLanguage, Vars[glbAX2KitVarsENum.platform], 1, glbCountry);
						}
						else {
							glbLn = 1078;
							wsInitializeYear(glbLanguage, "-1", 1, glbCountry);
						}
					}
					TODOInitTooltip();

					glbAX2InitializingDisplay = false;
					ResetWait();

					//sl 204
					if (Vars[glbAX2KitVarsENum.platform] === "401" && kcReq && glbIsIE) {

						ExternShowKCPopup(true);
					}
				}
				// END KitDetailsChanged
			}
		}
	}
	catch (fnError) {
		eReport(fnError, "AX2PollAndDisplayKitInfo: error while polling and displaying kit info");
	}
}

//sl 167 moved AX2PollAndDisplayKitPage to activexkitpage.js

//#endregion
//#region Initializing
function InitializeKitView(KitState) {
	try {

		//contains all dvs
		var tbKit = document.getElementById("tbKit");
		var dvkitDetect = document.getElementById("dvkitDetect");
		var btn_refresh = document.getElementById("btn_refresh");
		var dvkitInstall = document.getElementById("dvkitInstall");
		var dvErrorInfoContainer = document.getElementById("dvErrorInfoContainer");
		var kitLED = document.getElementById("kitLED");
		var kitinfo = document.getElementById("kitinfo");

		var isError = (KitState === glbKitStates.noDriverFound || KitState === glbKitStates.xkloaderNotFound || KitState === glbKitStates.NotFound);
		var isKitFound = (KitState === glbKitStates.Found);
		var isKitNotFound = (KitState === glbKitStates.NotFound);
		var isBrowserIncompatible = (KitState === glbKitStates.BrowserIncompatible);
		var isInstall = (KitState === glbKitStates.Install);
		var LedOn = (isKitFound);
		var LedOff = (isKitNotFound);

		tbKit.style.visibility = (isBrowserIncompatible) ? "hidden" : "visible";
		display("tbKit", (isBrowserIncompatible) ? "none" : "");

		dvkitDetect.style.visibility = (isKitFound) ? "visible" : "hidden";
		display("dvkitDetect", (isKitFound) ? "" : "none");

		dvkitDetect.width = (isKitFound) ? 208 : 0;
		dvkitDetect.height = (isKitFound) ? 42 : 0;

		btn_refresh.width = (isKitFound) ? 38 : 0;
		btn_refresh.height = (isKitFound) ? 35 : 0;

		kitinfo.width = (isKitFound) ? 150 : 0;
		kitinfo.height = (isKitFound) ? 35 : 0;

		btn_refresh.style.visibility = (isKitFound) ? "visible" : "hidden";
		display("btn_refresh", (isKitFound) ? "" : "none");

		dvkitInstall.style.visibility = (isInstall) ? "visible" : "hidden";
		display("dvkitInstall", (isInstall) ? "" : "none");

		dvErrorInfoContainer.style.visibility = (isError) ? "visible" : "hidden";
		display("dvErrorInfoContainer", (isError) ? "" : "none");

		if (LedOn) {
			kitLED.src = 'images/kit_on.gif';
			kitLED.title = 'Device Connected.';
		}
		else if (LedOff) {
			kitLED.src = 'images/kit_off.gif';
			kitLED.title = 'Device Not Connected.';
		}
		else {
			kitLED.src = 'images/kit_na.gif';
			kitLED.title = 'Device Problem.';
		}

		if (glbAXVersion === 3) {
		}
		else if (glbAXVersion === 2) {
		}

		setInnerHTML("errorinfo", "");

		switch (KitState) {
			case glbKitStates.noDriverFound:

				setInnerHTML("errorinfo", "<span style='font-size:11px' >Driver not found <a href='http://www.silabs.com/Support%20Documents/Software/CP210x_VCP_Win_XP_S2K3_Vista_7.exe'>Install</a></span>", false);
				
				break;
			case glbKitStates.xkloaderNotFound:

				setInnerHTML("errorinfo", "<span style='font-size:11px' >Plug in XKLOADER and click " + "<a id='a_refresh' title='Refresh' href='#' onclick='AX2PollKit();return false;'>REFRESH</a></span>", false);

				break;
			case glbKitStates.NotFound:

				setInnerHTML("errorinfo", "<span style='font-size:10px' >Plug in device and click " + "<a id='a_refresh' title='Refresh' href='#' onclick='AX2PollKit();return false;'>REFRESH</a></span><br /><span style='font-size:11px'>To flash <span style='color:Red;'>OPTIMAX</span> products click <a id='a_fortin'  title='To flash OPTIMAX products such as PKALL, DLPKGM' href='#' onclick='RunOptflashClicked();return false;'>HERE</a></span>", false);

				break;
			case glbKitStates.Found:

				setInnerHTML("kitmore", "&nbsp;<a href=\"#\" onclick=\"AX2OpenMoreClicked('" + glbAX2ID + "');return false;\">More</a>", false);

				break;
		}
	}
	catch (fnError) {
		eReport(fnError, "");
	}
}

function AX2InitializeFeaturesPopup(Vars) {
	if (isUInt(glbAX2Platform)) {
		if (parseInt(glbAX2Platform, 10) === 800) {
			ExternShowFeaturesPopup(true);
		}
		else {
			ExternShowFeaturesPopup(false);
		}
	}
}

function AX2InitializeKitFeaturesIframe(Vars) {
	if (isUInt(glbAX2Platform)) {
		if (parseInt(glbAX2Platform, 10) === 800) {

			document.getElementById("ifKitFeatures").src = "KitFeatures.aspx";
			document.getElementById("ifKitFeatures").contentWindow.focus();
		}
		else {
			document.getElementById("ifFeatures").src = "";
		}
	}
}
//#endregion

//#region Events attached to controls
function AX2FirmwareClicked(firmwareID) {
	var platform = getCookie("previous_platform");
	var firmwareIDvalue = firmwareID.substring(1, 10).trim();
	var firmwareFile = firmwareID.substring(10, firmwareID.length);
	openFlashPage("?p=" + platform + "&firmwareid=" + firmwareIDvalue + "&filename=" + firmwareFile);
}

function AX2OpenMoreClicked(kitid) {
	try {
		window.location = "kit.aspx?KitConnectedID=" + kitid;
	}
	catch (fnError) {
		eReport(fnError, "AX2OpenMoreClicked: error while trying to redirect to kit page");
	}
}

function installVIP(version) {
	var driver = (glbAXVersion === -1);

	$.cookie("COOKIE_XPRESSVIP42_INSTALL_CLICKED", 1, { expires: 1 });

	if (version === 42) {
		if (driver === true) {
			window.location = 'repository/downloads/xpressvip4_activex2_withdriver.EXE';
		}
		else {
			window.location = 'repository/downloads/xpressvip4_activex2_nodriver.EXE';
		}
	}
	else if (version === 43) {
		if (driver === true) {
			window.location = 'repository/downloads/xpressvip4_activex3_with_driver.EXE';
		}
		else {
			window.location = 'repository/downloads/xpressvip4_activex3_no_driver.EXE';
		}
	}
	wsInsertStatsVIPInstalls(version, glbCustomerID, ua, glbIP);
}
//#endregion

//#region webservice calls (ws)
function wsSendExceptionErrorEmail(Message) {
	try {
		if (isNonEmptyString(Message)) {
			DataService.SendErrorEmail(Message);
		}
		else {
			eReport("", "wsSendExceptionErrorEmail: invalid parameter; " + Message.toString());
		}
	}
	catch (WSERROR) {
		eReport(WSERROR, "wsSendExceptionErrorEmail: " + Message.toString());
	}
}

function wsGetPlatformName(platform, updateKitPage) {
	try {
		if (isUInt(platform)) {
			DataService.GetPlatformName(platform, AX2OnPlatformResults, AX2OnPlatformError, updateKitPage);
		}
		else {
			eReport("", "wsGetPlatformName: invalid parameter; " + platform.toString());
		}
	}
	catch (WSERROR) {
		eReport(WSERROR, "wsGetPlatformName: " + platform.toString());
	}
}
function AX2OnPlatformResults(result, updateKitPage) {
	try {
		if (result !== null) {
			var index = result.length;
			if (index === 2) {
				var platformName = result[0];
				var hasVehicleSpecificFirmwareValue = result[1];
				
				setInnerText("dPlatformName", platformName);
				setInnerHTML('dvFeaturesPlatform', '&nbsp;' + platformName + ' Option Wizard');
				
				var sku = replace(platformName, "-", "");
				if (sku.toLowerCase() == 'dball') {
					//tb_show("Install XpressVIP4.2", "xpressvip4v2_withdriver.aspx?height=400&width=500", "");
				}

				if (updateKitPage) {
					var platformName2 = document.getElementById("dvPlatformInfo");
					if (platformName2 !== null) { setInnerText("dvPlatformInfo", platformName); }
				}
			}
		}
	}
	catch (fnError) {
		eReport(fnError, "AX2OnPlatformResults: error while processing platform listing");
	}
}
function AX2OnPlatformError(result, updateKitPage) {
	eReport(result, "AX2OnPlatformError: error in getting the platform name from the data service");
}

function wsGetVehicleByVehicleID(VehicleID, Firmware, Language) {
	try {
		if (isUInt(VehicleID)) {
			DataService.GetVehicleByVehicleID(VehicleID, Language, AX2OnGetVehicleByVehicleIDResults, AX2OnGetVehicleByVehicleIDError, Firmware);
		}
	}
	catch (WSERROR) {
		eReport(WSERROR, "wsGetVehicleByVehicleID: unexpected error");
	}
}
function AX2OnGetVehicleByVehicleIDResults(Vehicle, Firmware) {
	try {
		var FlashSummary = "Not Found";
		if (Vehicle !== "") {
			FlashSummary = "Successfully flashed " + Firmware;
			if (Vehicle !== "") {
				FlashSummary += " for a " + Vehicle;
			}
			else {
				FlashSummary += " (Unknown vehicle)";
			}
		}
		else {
			FlashSummary = "(Unknown firmware";
			if (Vehicle !== "") {
				FlashSummary += ") for a " + Vehicle;
			}
			else {
				FlashSummary += " & unknown vehicle)";
			}
		}
		InitializeRecentFlashIfBlank(FlashSummary);
	}
	catch (fnError) {
		eReport(fnError, "error while getting vehicle by vehicle id");
	}
}
function AX2OnGetVehicleByVehicleIDError(result, Firmware) {
	eReport(result, "AX2OnGetVehicleByVehicleIDError: error while getting vehicle results");
}

function wsGetFirmwares(platform) {
	try {
		if (isUInt(platform)) {
			DataService.GetFirmwaresByPlatform(platform, AX2OnFirmwaresResults, AX2OnFirmwaresError);
		}
		else {
			display("ddFirmware","none");
		}
	}
	catch (WSERROR) {
		eReport(WSERROR, "wsGetFirmwares: " + platform.toString());
	}
}
function AX2OnFirmwaresResults(result) {
	try {
		clearDropDown("ddFirmware");

		var ddFirmware = document.getElementById("ddFirmware");
		if (result !== null) {
			if (result.length > 0) {
				var index = result.length;
				var i = 0;

				ddFirmware.options[0] = new Option("Flash Firmware", "");
				for (i = 0; i < index; i++) {
					ddFirmware.options[i + 1] = new Option(result[i][1], result[i][0]);
				}
				//todo: set previously selected firmware
				//if (session_firmware !== "") {
				//  selectDropDown("ddFirmware", session_firmware);
				//}
				display("ddFirmware", "");
			}
			else {
				display("ddFirmware", "none");
			}
		}
		else {
			display("ddFirmware", "none");
		}
	}
	catch (fnError) {
		eReport(fnError, "AX2OnFirmwaresResults: error while processing Firmwares listing");
	}
}
function AX2OnFirmwaresError(result) {
	document.getElementById("ddFirmware").style.display = "none";
	eReport(fnError, "AX2OnFirmwaresError: error while processing Firmwares listing");
}

function wsInsertStatsVIPInstalls(VIPID, CustomerID, UserAgent, IP) {
	try {
		if (isUInt(VIPID)) {
			if (!isUInt(CustomerID)) { CustomerID = -1; } else { CustomerID = parseInt(CustomerID, 10); }
			if (!isUInt(IP)) { IP = -1; } else { IP = parseInt(IP, 10); }

			DataService.InsertStatsVIPInstalls(parseInt(VIPID, 10), parseInt(CustomerID, 10), UserAgent, parseInt(IP, 10), onInsertStatsVIPInstallsResults, onInsertStatsVIPInstallsResultsERROR);
		}
		else {
			eReport(WSERROR, "VIPID is not a number " + VIPID);
		}
	}
	catch (WSERROR) {
		eReport(WSERROR, "");
	}
}
function onInsertStatsVIPInstallsResults(Result) {
	try {
		if (Result.toString().search("Fail") !== -1) {
			eReport("", Result);
		}
	}
	catch (fnError) {
		eReport(fnError, "");
	}
}
function onInsertStatsVIPInstallsResultsERROR(LoggingResult) {
	eReport(LoggingResult, "");
}
//#endregion

//#region utility functions
function TODOInitTooltip() {
	//      TODO: SEE WHY TOOLTIP DOES NOT WORK
	//      var KIT_TOOLTIP = "";

	//      if (platform !== null) {
	//        if (platform !== "" && platform !== "NA") {
	//          KIT_TOOLTIP = "Platform: " + platform;

	//          if (firmware_details !== "") {
	//            if (KIT_TOOLTIP !== "") {
	//              KIT_TOOLTIP += "<br>";
	//            }
	//            KIT_TOOLTIP += "Firmware: " + firmware_details;
	//          }
	//          if (bootloader_details !== "") {
	//            if (KIT_TOOLTIP !== "") {
	//              KIT_TOOLTIP += "<br>";
	//            }
	//            KIT_TOOLTIP += "Bootloader: " + bootloader_details;
	//          }
	//          if (glbAX2ID !== "") {
	//            if (KIT_TOOLTIP !== "") {
	//              KIT_TOOLTIP += "<br>";
	//            }
	//            KIT_TOOLTIP += "Kit ID: " + glbAX2ID;
	//          }
	//        }
	//      }

	//      if (KIT_TOOLTIP === "") {
	//        KIT_TOOLTIP = "No kit detected. Please connect your kit and click refresh.";
	//      }
	//KIT_TOOLTIP = "Platform " + platform;
	//KIT_TOOLTIP = KIT_TOOLTIP + "<br>Firmware " + firmware_details;
	//KIT_TOOLTIP = KIT_TOOLTIP + "<br>Bootloader " + bootloader_details;
	//KIT_TOOLTIP = KIT_TOOLTIP + "<br>Kit ID " + glbAX2ID;

	//      if ($(glbAX2TooltipObj) != undefined) {
	//        if ($(glbAX2TooltipObj) !== null) {
	//          if ($(glbAX2TooltipObj).qtip("api") != undefined) {
	//            if ($(glbAX2TooltipObj).qtip("api") !== null) {
	//              if (KIT_TOOLTIP != undefined) {
	//                if (KIT_TOOLTIP !== null) {
	//                  $(glbAX2TooltipObj).qtip("api").updateContent(KIT_TOOLTIP, true);
	//                  $(glbAX2TooltipObj).qtip("api").options.content.text = KIT_TOOLTIP;

	//                }             
	//              }
	//            }
	//          }
	//        }
	//      }
}

function GetVariableFromDump(variable, dump) {
	if (dump.toString() !== "") {
		if (dump.toString().match(/HT2_LOG====((?: \d*)*)/) !== null) {
			return dump.toString().match(/HT2_LOG====((?: \d*)*)/)[1].trimall();
		}		
	}
	return '';
}
//sl 180 removed obsolete functions AX2GetW2WFromDump and AX2GetD2D_TYPEFromDump


function AX2GetVehicleID(Dump) {
	if (Dump.toString() !== "") {
		if (Dump.toString().match(/XPRESSKIT_ID==== \d+ \d+ \d+ \d+/) !== null) {
			var VehicleIDByte1 = parseInt(Dump.toString().match(/XPRESSKIT_ID==== \d+ \d+ ((?:\d+)) \d+/)[1].toString(), 10);
			var VehicleIDByte2 = parseInt(Dump.toString().match(/XPRESSKIT_ID==== \d+ \d+ \d+ ((?:\d+))/)[1].toString(), 10);
			return (VehicleIDByte1 * 256 + VehicleIDByte2);
		}
	}
	return -1;
}

function AX2GetBrandFromDump(Dump) {
	if (Dump.toString() !== "") {
		if (Dump.toString().match(/BRAND==== \d+/) != null) {
			var Byte1 = parseInt(Dump.toString().match(/BRAND==== ((?:\d+))/)[1].toString(), 10);
			return (Byte1);
		}
	}
	return -1;
}

function AX2GetSysTypeFromDump(Dump) {
	if (Dump.toString() !== "") {
		if (Dump.toString().match(/SYS_TYPE==== \d+/) != null) {
			var Byte1 = parseInt(Dump.toString().match(/SYS_TYPE==== ((?:\d+))/)[1].toString(), 10);
			return (Byte1);
		}
	}
	return -1;
}
//#endregion

//#region language
var glbGetTermLocalizedArr;
var glbGetTermLocalizedArrTransport = { 'LanguageID': 0, 'PageName': 1, 'RefName': 2, 'Term': 3 };
function wsGetTermLocalized() {
	try {
		var path = window.location.pathname;
		var pageName = path.substring(path.lastIndexOf('/') + 1).replace(/.aspx/, "") + "js";

		if (isUInt(glbLanguage) && isNonEmptyString(pageName)) {
			DataService.GetTermLocalized(parseInt(glbLanguage, 10), pageName, OnGetTermLocalizedResults, OnGetTermLocalizedError);
		}
	}
	catch (WSERROR) {
		eReport(WSERROR, "");
	}

}
function OnGetTermLocalizedResults(Result) {
	try {
		glbGetTermLocalizedArr = Result;

	}
	catch (fnError) {
		eReport(fnError, "");
	}
}
function OnGetTermLocalizedError(result) {
	try {
		eReport(result, "error while getting the RFs");
	}
	catch (fnError) {
		eReport(fnError, "");
	}
}

function getl(RefName) {
	for (var i = 0; i < glbGetTermLocalizedArr.length; i++) {
		if (glbGetTermLocalizedArr[i][glbGetTermLocalizedArrTransport.RefName] === RefName) {
			return glbGetTermLocalizedArr[i][glbGetTermLocalizedArrTransport.Term];
		}
	}
	return "";
}
//#endregion

function AX2ShowWaitingForVIPUpgrade() {
	if(isInPage("flashing")){
		display("dvAX2Status", "");
		setInnerText("dvAX2Status", "Please wait detecting XpressVIP4.3 upgrade..");
		display("tbFlash", "none");
		glbAX2ReserveState = glbAX2ReserveStates.ForVIPVersionUpgrade;
	}
}
function AX2ShowIgnoreVIPUpgrade() {
	if(isInPage("flashing")){
		AX2InitializeFlashView();
		AX2InitializeVisibleDivs();
	}
}
//#ENDREGION
