/*******************************************************************************
 * File Name            : JCPModelMenu.js
 * Author               : Keane India Pvt Ltd.,
 * Date of Creation     : 29 September 2008.
 * Description          : Created for ModelMenu Module.
 * Version Number       : 1.0
 * Modification History :
 Date         Version  Who             Description of change
 2008-09-29   1.0      Keane India     Initial - created methods for displaying
 									   Models.
 2009-12-01   1.01     Kevin Compton   K02683 JCP Adhoc Changes - open external 
                                       hotspots in new window
 *******************************************************************************/
var lastModel = 100;
var id = 0;
var languageId = null;
var languageCode = null;
var memberId = null;
var storeId = null;

// The hotspots.
var hotspots = "";

// The current start index of the hotspot to be displayed.
var curStartIndex = 0;

// The total number of hotspots.
var totalHotspots = 0;

// Flag used to check whether the hotspot table is built for the first time.
var flag = 0;

function initialiseModelMenu() {

	var modelXML = top.frames[1].document.getElementById("xmlData");
	
   if ((top.frames[1].document.getElementById("languageId") == null) || (modelXML == null) || (modelXML.value == null) || (modelXML.value.length == 0)) {
      setTimeout(initialiseModelMenu,500);
      return;
   }

   document.getElementById('model_List').style.width = document.body.offsetWidth + "px";
   document.getElementById('model_List').style.height = getInnerFrameHeight()+"px";   

   languageId = top.frames[1].document.getElementById("languageId").value;

   // Get the Language code for given languageId.
   languageCode = getLanguageCode(languageId);
 
   // Member id.
   memberId = top.frames[1].document.getElementById("memberId").value;

   // Store id.
   storeId = top.frames[1].document.getElementById("storeId").value;

   setTitle();
   setModelMenu();   
   setShoppingUrl();
   getHotspots();
   
}

// Function to set the title.
function setTitle() {
	parent.document.title = "Genuine Jaguar Parts and Jaguar Accessories for Classic Jaguars";
}

 /**
 * Function to retrieve the model xml file based on the language selected. 
 */
function setModelMenu() {
	document.getElementById("modelMenulabel_Id").innerHTML = HtmlDecode(eval("MODEL_MENU_LABEL" + languageCode));
	pText = top.frames[1].document.getElementById("xmlData").value;

	if (pText != null || pText != undefined || pText != "") {	
		buildUtility("buildMenu", unescape(pText));
		aModelSlot = document.getElementById('modelSlot');
		tmpRow = aModelSlot.insertRow(aModelSlot.rows.length);
		tmpCell = tmpRow.insertCell(tmpRow.cells.length);
		tmpCell.style.backgroundColor = "white";
		tmpCell.innerHTML = "<a class=\"buttonStyleMenuPage\" id=\"Link" 
				+ "\" href=\"JCPSpecialOffers.html\" onmouseover=\"changeStaticModelImage('clspoff_s','" 
				+ eval("SPECIAL_OFFERS_LABEL" + languageCode) + "')\" target=\"mainFrame\">" 
				+ eval("SPECIAL_OFFERS_LABEL" + languageCode) + "</a>";
		tmpRow = aModelSlot.insertRow(aModelSlot.rows.length);
		tmpCell = tmpRow.insertCell(tmpRow.cells.length);
		tmpCell.style.backgroundColor = "white";
		tmpCell.innerHTML = "<a class=\"buttonStyleMenuPage\" id=\"Link" 
				+ "\" href=\"JCPClassicNews.html\" onmouseover=\"changeStaticModelImage('clsnews_s','" 
				+ eval("CLASSIC_NEWS_LABEL" + languageCode) + "')\" target=\"mainFrame\">" 
				+ eval("CLASSIC_NEWS_LABEL" + languageCode) + "</a>";
		tmpRow = aModelSlot.insertRow(aModelSlot.rows.length);
		tmpCell = tmpRow.insertCell(tmpRow.cells.length);
		tmpCell.style.backgroundColor = "white";
		tmpCell.innerHTML = "<a class=\"buttonStyleMenuPage\" id=\"Link" 
				+ "\" href=\"JCPOlderVehicles.html\" onmouseover=\"changeStaticModelImage('clslist_s','" 
				+ eval("OLDER_VEHICLES_MM" + languageCode) + "')\" target=\"mainFrame\">" 
				+ eval("OLDER_VEHICLES_MM" + languageCode) + "</a>";
	}
	
}

/**
 * Function to build the menu.
 *
 * @param pChildren		String[] - the array of sub-models.
 * @param pParent 		String - the model.
 * @param pFlag			int - used to differentiate between building the menu
 *						where the model name is same as the sub-model name
 *						(pFlag=1) and building the menu where model contains
 *						dissimilar sub-models(pFlag=0).
 */
function buildMenu(pChildren, pParent, pFlag) {
	var tmpRow = null;
	var div = null;
	var modelId = null;
	var table = null;
	var tmpCell = null;
	var tmpCell1 = null;
	var tmpCell2 = null;
	var splitTextParams = null;
	var	formattedChildren = null;
	var splitChildren = null;
	var identifiers = new Array();
	var childrenCount = null;
	childrenCount = pChildren.length;
	modelId = pParent[0];

	if (pFlag == 1) {
		splitTextParams = pChildren[0].split("\'");
		splitTextIdentifiers = splitTextParams[0].split(",");
		aModelSlot = document.getElementById('modelSlot');		
		tmpRow = aModelSlot.insertRow(aModelSlot.rows.length);
		tmpCell = tmpRow.insertCell(tmpRow.cells.length);
		tmpCell.name = "Parent" + id;
		tmpCell.id = "Parent" + id;
		//tmpCell.style.backgroundColor = "white";
		tmpCell.innerHTML = "<a class=\"buttonStyleMenuPage\" id=\"Link" + id
				+ "\" href=\"JCPCategoryMenu.html?modelId="
				+ splitTextIdentifiers[0] + "&modelName=" + escape(pParent[2])
				+ "&waterMarkModelId=" + modelId
				+ "\" onmouseover=\"changeModelImage('" + escape(modelId)
				+ "','" + escape(pParent[2]) + "','" + tmpCell.id + "','"
				+ "Link" + id + "')\">" + pParent[2] + "</a>";
	} else {
  		aModelSlot = document.getElementById('modelSlot');
		tmpRow = aModelSlot.insertRow(aModelSlot.rows.length);
		tmpCell = tmpRow.insertCell(tmpRow.cells.length);
		tmpCell.name = "Parent" + id;
		tmpCell.id = "Parent" + id;
		tmpCell.style.backgroundColor = "white";
		tmpCell.innerHTML = "<a class=\"buttonStyleMenuPage\" id=\"Link" + id
				+ "\" href=\"javascript:showModelMenu(" + id + ")\""
				+ "onmouseover=\"changeModelImage('"
				+ escape(modelId) + "', '" + escape(pParent[2]) + "', '"
				+ tmpCell.id + "', '" + "Link" + id + "')\">" + pParent[2]
				+ "</a>";
		div = document.createElement("div");
		div.id = "DIV" + id;
		div.style.visibility = "hidden";
		div.style.display = "none";
		table = document.createElement("table");
		table.width = "100%";
		table.cellPadding = "3";
		table.cellSpacing = "3";
		table.summary = "Contains the sub models of the model";
		document.getElementById("Parent" + id).appendChild(div);
		div.appendChild(table);

		for (var i = 0; i < childrenCount; i++) {
			lastIndexOfModelId = pChildren[i].indexOf(",");
			lastIndexOfParentId = pChildren[i].indexOf(",", lastIndexOfModelId + 1);
			firstIndexOfModelName = pChildren[i].indexOf("'");
			
			identifiers[0] = pChildren[i].substring(0, lastIndexOfModelId);
			identifiers[1] = pChildren[i].substring(lastIndexOfModelId + 1,
					lastIndexOfParentId);
			modelName = pChildren[i].substring(firstIndexOfModelName + 1,
					pChildren[i].length - 1);
			
			tmpRow = table.insertRow(table.rows.length);
			tmpCell1 = "tmpCell1" + i;
			tmpCell2 = "tmpCell2" + i;
			tmpCell1 = tmpRow.insertCell(tmpRow.cells.length);
			tmpCell1.width = "7%";
			tmpCell2 = tmpRow.insertCell(tmpRow.cells.length);
			tmpCell2.width = "93%";
			tmpCell2.id = "tmpCell2" + id + i;
			tmpCell2.style.backgroundColor = "white";
			tmpCell2.innerHTML = "<a class=\"buttonStyleMenuPage\" id=\"childLink"
					+ id + i  + "\" href=\"JCPCategoryMenu.html?modelId="
					+ identifiers[0] + "&modelName=" + escape(modelName)
					+ "&waterMarkModelId=" + modelId
					+ "\" onmouseover=\"changeModelImage('" + identifiers[0] + "', '"
					+ escape(modelName) + "', '" + tmpCell2.id + "', '"
					+ "childLink" + id + i + "')\">" + modelName + "</a>";
		}
	}
	id++;
}
function changeLength() {

/*
	var tableHolder = document.getElementById("model_List");
		offsetHeight = document.getElementById("model_details_Id")
							.offsetHeight;
							
		if (offsetHeight > 400) {
			tableHolder.style.height = 400;
			tableHolder.style.overflow = "auto";
		} else {
			tableHolder.style.height = offsetHeight;
		}
*/

}
/**
 * Function to change the model image.
 *
 * @param pImageName 	String - the name of the image to be displayed.
 * @param pModelName 	String - the alt text for the image is the name.
 */
 var lastHoveredModel = null;
 var lastHoveredLink = null;
function changeModelImage(pImageName, pModelName, pCell, pId) {
	var obj = document.getElementById(pCell);
	var link = document.getElementById(pId);
	var lastObj = null;
	var modelImage = document.getElementById("modelImg");
	
	//obj.className = "modelHoverStyle";
	//link.className = "buttonStyleMenuPage1";
	
	modelImage.alt = HtmlDecode(unescape(pModelName)) + "_Image"
	modelImage.src = "../images/" + unescape(pImageName) + ".jpg";
	
	if (lastHoveredModel != null && lastHoveredLink != null) {
		lastObj = document.getElementById(lastHoveredModel);
		//lastObj.className = "modelNonHoverStyle";
		lastLink = document.getElementById(lastHoveredLink);
		//lastLink.className = "buttonStyleMenuPage1";
	}
	lastHoveredModel = pCell;
	lastHoveredLink = pId;
}

function changeStaticModelImage(pImageName, pModelName) {
	var modelImage = document.getElementById("modelImg");
	
	//obj.className = "modelHoverStyle";
	//link.className = "buttonStyleMenuPage1";
	
	modelImage.alt = HtmlDecode(unescape(pModelName)) + "_Image"
	modelImage.src = "../images/" + unescape(pImageName) + ".jpg";
}

/**
 * Function to toggle the visibility of the sub-models of a given model.
 *
 * @param pMenuId 	String - the id of the model whose sub-models' visibility
 * 							 needs to be toggled.
 */
function showModelMenu(pMenuId) {
	var menuId = pMenuId;
	var modelMenu = document.getElementById("DIV" + menuId);
	var lastModelToggle = null;

	if (modelMenu.style.visibility == "visible") {
		modelMenu.style.visibility = "hidden";
		modelMenu.style.display = "none";
	} else {
		modelMenu.style.visibility = "visible";
		modelMenu.style.display = "block";
	}

	if ((lastModel != null && lastModel != undefined && lastModel != 100)
		&& (lastModel != menuId)) {
		lastModelToggle = document.getElementById("DIV" + lastModel);

		if (lastModelToggle.style.visibility == "visible") {
			lastModelToggle.style.visibility = "hidden";
			lastModelToggle.style.display = "none";
		} 
	}
	lastModel = menuId;
	
}

// Function to retrieve the list of marketing hotspots by making an AJAX call to
// the server.
function getHotspots() {
	var url = "";
	var errorMsg = "";
	var noHotspotsMsg = "";

	try {
		url = onlineURL + "getHotspots.jcp";

		initRequest();
		req.onreadystatechange = function() {
			if (req.readyState == 4) {
				try {
					if (req.status == 200) {				
						hotspots = eval("(" + req.responseText + ")");					
						errorMsg = eval('hotspots.errorMessage');
						noHotspotsMsg = eval('hotspots.noHotspots');

						if (!(errorMsg != null && errorMsg != undefined
								&& errorMsg != "") && (!(noHotspotsMsg != null
								&& noHotspotsMsg != undefined && noHotspotsMsg != ""))) {
								buildHotspotsTable();
						}
					} else {
						alert(HtmlDecode(eval("APPLICATION_ERROR" + languageCode)));
					}
				} catch (exception) {
					alert(HtmlDecode(eval("APPLICATION_ERROR" + languageCode)));
				}
			}
		}

		req.open("POST", url, true);
		req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
		req.send("&memberId=" + escape(memberId) + "&languageId=" + languageId
				+ "&storeId=" + storeId + "&uid=" + generateUID());
	} catch(exception) {
		alert(HtmlDecode(eval("APPLICATION_ERROR" + languageCode)));
	}

}

// Function to build the hotspots table.
function buildHotspotsTable() {
	var tmpRow = null;
	var tmpCell = null;
	var url = "";
	var target = "";
	var imageName = "";
	var imagePath = "";
	var hotspotsCount = hotspots.length;
	var hotspotTable = document.getElementById("hotspotTable");
	var hotspotHolder = document.getElementById("hotspotHolder");

	if (hotspotsCount > 4) {
		totalHotspots = hotspotsCount;
		flag = 1;
		buildScrollableTable();
		return;
	}

	tmpRow = hotspotTable.insertRow(-1);

	for (var i = 0; i < hotspotsCount; i++) {
		tmpCell = tmpRow.insertCell(-1);
		tmpCell.align = "center";

		if (1 == hotspotsCount) {
			hotspotHolder.align = "left";
			hotspotTable.removeAttribute("width");
		} else if (2 == hotspotsCount) {
			tmpCell.width = "50%";
		} else if (3 == hotspotsCount) {
			tmpCell.width = "33%";
		} else if (4 == hotspotsCount) {
			tmpCell.width = "25%";
		}

		url = eval('hotspots[' + i + '].urlPath');

		if (url.toUpperCase().indexOf(hostName.toUpperCase()) > -1) {
			target = "_self"
		} else {
			target = "_new"
		}
		
		imageName = eval('hotspots[' + i + '].imageName');

		if (imageName == null) {
			imageName = "";
		}

		imagePath = "../images/marketing_hotspot/" + imageName;

		tmpCell.innerHTML = "<a href='" + url + "' target='" + target + "'><img src='"
				+ imagePath + "'" + "border='0' width='100px' height='80px' alt='"
				+ imageName + "' /></a><br />" + "<a href='" + url
				+ "' target='" + target + "' class='text12greyBold'>"
				+ eval('hotspots[' + i + '].description') + "</a>";
	}
}

// Function to build the scrollable hotspots table if the number of hotspots is
// more than 4.
function buildScrollableTable() {
	var tmpRow = null;
	var tmpCell = null;
	var url = "";
	var target = "";
	var imageName = "";
	var imagePath = "";
	var curEndIndex = curStartIndex + 4;
	var hotspotTable = document.getElementById("hotspotTable");
	var hotspotHolder = document.getElementById("hotspotHolder");

	if (flag == 1) {
		flag = 0; 
	} else {
		hotspotTable.deleteRow(0);
	}

	tmpRow = hotspotTable.insertRow(-1);
	left_id = tmpCell = tmpRow.insertCell(-1);
	tmpCell.id = "left_id";
	tmpCell.paddingTop = "20px";
	tmpCell.innerHTML = "<a href='javascript:scrollBack();'>"
			+ "<img src='../images/leftArrow.gif' border='0' /></a>";

	if (curStartIndex == 0) {
		left_id.style.visibility = "hidden";
	}

	for (var i = curStartIndex; i < curEndIndex; i++) {
		tmpCell = tmpRow.insertCell(-1);
		tmpCell.align = "center";
		tmpCell.width = "23%";
		url = eval('hotspots[' + i + '].urlPath');
		
		if (url.toUpperCase().indexOf(hostName.toUpperCase()) > -1) {
			target = "_self"
		} else {
			target = "_new"
		}
		
		imageName = eval('hotspots[' + i + '].imageName');

		if (imageName == null) {
			imageName = "";
		}
		imagePath = "../images/marketing_hotspot/" + imageName;

		tmpCell.innerHTML = "<a href='" + url + "' target='" + target + "'><img src='"
				+ imagePath + "'" + "border='0' width='100px' height='80px' alt='"
				+ imageName + "' /></a><br />" + "<a href='" + url
				+ "' target='" + target + "' class='text12greyBold'>"
				+ eval('hotspots[' + i + '].description') + "</a>";
	}

	right_id = tmpCell = tmpRow.insertCell(-1);
	tmpCell.id = "right_id";
	tmpCell.paddingTop = "20px";
	tmpCell.innerHTML = "<a href='javascript:scrollForward();'>"
			+ "<img src='../images/rightArrow.gif' border='0' /></a>";

	if (curEndIndex >= totalHotspots) {
		right_id.style.visibility = "hidden";
	}
}

// Function to scroll back on click of left arrow icon.
function scrollBack() {
	curStartIndex -= 1;
	buildScrollableTable();
}

// Function to scroll forward on click of right arrow icon.
function scrollForward() {
	curStartIndex += 1;
	buildScrollableTable();
}
