﻿var firstSelect = 1;
function checkIfFirstSelect()
{
	if (firstSelect == 1)
	{
		hideElement("frontImage");
		document.getElementById("topDescription").style.marginTop = "20px";
		document.getElementById("displayScreen").style.display = "block";
		firstSelect  = 0;
		return true;
	}
	return false;
}

var selectedCountryJustChanged = 0;
function listSelectedCountryBrands(elementId)
{
	selectedCountryJustChanged = 1;
	checkIfFirstSelect();

    try
    {
	    switch (currentMode)
	    {
	        case "":
		    case privateConsumerModeText:   setStatesFilterContent(elementId, "stateSelection", " index"); break;		
		    case foodServiceModeText:	   setStatesFilterContent(elementId, "stateSelection-foodServiceMode",' Food-Service index');  break;
		    default: break;
	    }
	}
	catch(ex)
	{
	    pageNotFullyLoaded();
	    return;
	}
	
	
	//var country = document.getElementById(elementId).innerHTML;
	// Replacing "index" with "options" to get the options element's id
	var countryOptionsElementId = elementId.replace(/index/, "options");
	
	var countryBrandsDataElement = document.getElementById(countryOptionsElementId);
	var brandListItems = countryBrandsDataElement.getElementsByTagName ("a");
	
	var htmlBuilderBrandsTextList = ""; // The html for the brands list div
	var htmlBuilderBrandsLogoList = ""; // The html for the main div (the one for the selected brand details)
	
	htmlBuilderBrandsTextList += "<ul class='countryList'>";
	htmlBuilderBrandsLogoList += "<div id='availableBrandsLogos'>" +
								 "<div id='availableBrandsLogosTitle'><span style='padding-right:40px;'>Hover to see product range</span><span>Click to see complete details</span></div>";
	
	for (var i = 0;  i < brandListItems.length;  i++)
	{
		var brandText = brandListItems[i].innerHTML;
		var brandId = brandListItems[i].href.substr(brandListItems[i].href.indexOf('#')+1);
		
		// Setting current brand images
		//setBrandMultimedia (brandId);
		
		// Before converting chars, getting the logo src
		var logoSrc;

		//NEW CODE
		logoSrc = "images/brands/" + getBrandImages(brandId).split(',')[0];

		while (brandId.indexOf("'") != -1)
			brandId = brandId.replace("'", "&#39;");	// simple replace only replace 1st occurance
		while (brandText.indexOf("'") != -1)
			brandText = brandText.replace("'", "&#39;");	// simple replace only replace 1st occurance
		  while (logoSrc.indexOf("'") != -1)
			logoSrc = logoSrc.replace("'", "&#39;");	// simple replace only replace 1st occurance
		
		var eventText = "return displayBrand(\"" + brandId + "\",\"" + brandText + "\");";
		
		// Decorating Non-Brand text (the manufacturer, which is inside brackets).
		var innerHTML = getBrandListItemInnerHTML(brandText);
	  
		//htmlBuilderBrandsTextList += "<li class='sideBarListItem' title='" + brandId + "'" + ( ((i%2) == 0) ? "" : "") + "  onclick='" + eventText + "'><a href='' onclick='" + eventText + "'>" + innerHTML + "</a></li>";
		htmlBuilderBrandsTextList += "<li class='sideBarListItem' id='li_" + brandId + "' onclick='" + eventText + "'>" + innerHTML + "</li>";
  
		var charIndex = brandText.indexOf('(');
		var brandShortText = (charIndex == -1) ? brandText : brandText.substr(0,charIndex-1);
		
		// Special case for Viana by Concious Company
		var charIndex2 = brandText.indexOf(' by ');
		brandShortText = (charIndex2 == -1) ? brandShortText : brandShortText.substr(0,charIndex2);

		var logoHeight = getBrandLogoHeight(brandListItems.length);
		var productRangeToolTipId = "productRangeToolTip";
		var elementId = "listedBrandLogo" + i;
		var logoCode =  "<a id='" + elementId + "' class='listedBrandLogo' href='' onclick='" + eventText + "' " +
						 //" onmouseover='fillProductRange(\"" + brandId + "\", event); showElement(\"" + productRangeToolTipId + "\");' " +
						 //" onmouseout='hideProductRange()' " +   // no title attribute due to floating div
						 " onmouseover='if (triggerElementMouseOver(\"" + productRangeToolTipId + "\", event)) fillProductRange(\"" + brandId + "\", event);' " +
						 " onmouseout='triggerElementMouseOut(this, \"" + productRangeToolTipId + "\", event)' " +   // no title attribute due to floating div
						 //" onmousemove='setMouseXY(\"" + productRangeToolTipId + "\", event)' " +
						">" +
						"<span>" +
						"<img height='" + logoHeight + "px' src='" + logoSrc + "' />" +   // no alt attribute due to floating div in IE
						"<br />" +
						brandShortText +
						"</span></a>";
									   
	   htmlBuilderBrandsLogoList += logoCode;
	}
	
	htmlBuilderBrandsTextList += "</ul>"
	htmlBuilderBrandsLogoList += "</div>";
	   
	// Filling the proper <div> with the brands list
	document.getElementById("displayScreenSideBarContent").innerHTML = htmlBuilderBrandsTextList;
	
	// Reseting filter
	// Filling the proper <div> with the brands logos
	document.getElementById("productsFilterSelectControl").selectedIndex = 0;
	document.getElementById("displayScreenCenter").innerHTML = htmlBuilderBrandsLogoList;
	
	// Reseting filter and brand-details window
	//document.getElementById("productsFilterSelectControl").selectedIndex = 0;
	//document.getElementById("displayScreenCenter").innerHTML = "<div class='startMessage' style='padding-top: 160px;'>Selected Brand Details</div>";
}

function setStatesFilterContent (countryElementId, stateSelectionElementId, countryIdSuffix)
{
	var stateSelectionElement = document.getElementById(stateSelectionElementId);
	
	if (countryElementId == ("USA" + countryIdSuffix))
	{
		stateSelectionElement.innerHTML = getUSStates();
	}
	else if (countryElementId == ("Australia" + countryIdSuffix))
	{
		stateSelectionElement.innerHTML = getAustraliaStates();
	}
	else if (countryElementId == ("Brazil" + countryIdSuffix))
	{
		stateSelectionElement.innerHTML = getBrazilStates();
	}
	else if (countryElementId == ("Canada" + countryIdSuffix))
	{
		stateSelectionElement.innerHTML = getCanadaStates();
	}
	else if ( (countryElementId == ("UK" + countryIdSuffix)) && (currentMode == foodServiceModeText))
	{
		stateSelectionElement.innerHTML = getUKFoodServiceRegions();
	}
	else
	{
		stateSelectionElement.innerHTML = getEmptyStates();
	}
}

function getBrandLogoHeight(itemsCount)
{
	if (itemsCount > 35)   return 22;
	if (itemsCount > 32)   return 24;
	if (itemsCount > 22)   return 32;
	if (itemsCount > 16)   return 36;
	return 40;
}

function displayBrand(brandId, brandText)
{ 
	var brandElement = getBrandElement(brandId);
	
	if(brandElement == null)
	{
		alert("The brand is yet to be loaded. Please try again...");
		return false;
	}
	
	// If first select: changin GUI settings
	checkIfFirstSelect();
	try
	{
		clearInterval(highlightProductInterval);
		//hideElement("productRangeToolTip");
		setElementVisibility("productRangeToolTip", false);
	}
	catch(ex){}
	
	while (brandText.indexOf(" & ") != -1)
		brandText = brandText.replace(" & ", " &amp; ");	// simple replace only replace 1st occurance
	
	// Setting different background to selected brand
	var sideBarContentElement = document.getElementById("displayScreenSideBarContent");
	var listedBrands = sideBarContentElement.getElementsByTagName("li");
	for (var i = 0;  i < listedBrands.length;  i++)
	{
		listedBrands[i].className = "sideBarListItem";

		// Before the comparison, decorating Non-Brand text (the manufacturer, which is inside brackets).
		var clickedBrandText = getBrandListItemInnerHTML(brandText);
		var currentBrandText = listedBrands[i].innerHTML;
		
		// using ToLowerCase() for IE
		if (clickedBrandText.toLowerCase() == currentBrandText.toLowerCase())
		{   
			// Setting different style fo the item
			listedBrands[i].className = "sideBarListItemSelected";
			  
			// In case it is the first select
			if (selectedCountryJustChanged && (i > 9))
			{  
				// Making sure the selected brand's text on the sidebar will be visible
				sideBarContentElement.scrollTop = i * 24;
			}
		}
		//alert ("clicked: " + clickedBrandText + " ;   current: " + currentBrandText);
	}
	
	// FireFox adjustments
	brandId = adjustToFireFox(brandId);
	
	// Setting the brand images and video
	setBrandMultimedia (brandId);
	
	// Filling the display portion with selected brand
	document.getElementById("displayScreenCenter").innerHTML = document.getElementById(brandId).innerHTML;
	
	HighlightProductRange (brandId);
	
	selectedCountryJustChanged = 0;
	return false;
}

function showRegionalFilterToolTip(e)
{
	setMouseXY ("regionalFilterToolTip", e);
	showElement("regionalFilterToolTip");
}

//function hideProductRange() { hideElement("productRangeToolTip"); }
function fillProductRange(brandId, e)
{
	setMouseXYbyOffset ("productRangeToolTip", e, 1);
	
	var productRangeToolTipContentElement = document.getElementById("productRangeToolTipContent");
	productRangeToolTipContentElement.innerHTML = getProductRange(brandId, true);

	var length = productRangeToolTipContentElement.innerHTML.length;
	var footerIndex = productRangeToolTipContentElement.innerHTML.indexOf("productRangeToolTipFooter");
	
	if (footerIndex != - 1)
	{
		length = (footerIndex - 8);
	}
		
	var productRangeToolTipElement = document.getElementById("productRangeToolTip");
			if (length > 300) productRangeToolTipElement.style.width = "320px";
	else	if (length > 200) productRangeToolTipElement.style.width = "280px";
	else	if (length > 16)  productRangeToolTipElement.style.width = "240px";
	else					  productRangeToolTipElement.style.width = "180px";
}

function getProductRange(brandId, includeFooterLinks)
{
	var brandElement = getBrandElement(brandId);
	
	if(brandElement == null)
		return "Loading...";
	
	// ----------------------
	
	var rangeText = "";
	var brandListItems = brandElement.getElementsByTagName("li");
	
	for (var i = 0;  i < brandListItems.length;  i++)
	{
		if (brandListItems[i].innerHTML.indexOf("Product range") != -1)
		{
			var labelElements = brandListItems[i].getElementsByTagName("label");
			rangeText += labelElements[1].innerHTML;
			break;
		}
	}
	
	// ----------------------
	
	var links = "";
	
	if (includeFooterLinks)
	{
		var aElements = brandElement.getElementsByTagName("a");
		
		for (var i = 0;  i < aElements.length;  i++)
		{
			var a = aElements[i];
	  
			if ((a.title.toUpperCase() == "FIND A STORE")  ||  (a.title.toUpperCase() == "ORDER ONLINE"))
			{
				
				var link = "<a href=\"" + a.href + "\" title=\"" + a.title + "\" target=\"_blank\">" + a.title + "</a>";
				links += link;
			}
		}
	}
	// -----------------------
	
	if ( (rangeText != "")  ||  (links != "") )
		return rangeText + (includeFooterLinks ? ("<div id='productRangeToolTipFooter'>" + links + "</div>") : "");
	
	// If there is no range and there is no footer links	
	return "Feature is not applicable for this brand.";
}
function setProductRange(productRangeText)
{
	var brandListItems = document.getElementById("displayScreenCenter").getElementsByTagName("li");

	for (var i = 0;  i < brandListItems.length;  i++)
	{
		if (brandListItems[i].innerHTML.indexOf("Product range") != -1)
		{
			var labelElements = brandListItems[i].getElementsByTagName("label");
			labelElements[1].innerHTML = productRangeText;
			return;
		}
	}
}

function getLogoSrc(brandId)
{
	var brandElement = getBrandElement(brandId);
	
	if (brandElement == null)
	{
		return null;
	}
	
	//alert(brandId);
	var imageElements = brandElement.getElementsByTagName('img');
	
	for (var i = 0;  i < imageElements.length;  i++)
	{
		if (imageElements[i].alt == "Brand Logo")
			return imageElements[i].src;
	}
	return "";
}

function getBrandElement(brandId)
{
	// FireFox adjustments
	brandId = adjustToFireFox(brandId);
	 
	//alert(brandId);
	return document.getElementById(brandId);
}
function adjustToFireFox(string)
{
	while (string.indexOf("%20") != -1)
		string = string.replace ("%20", " ");
	while (string.indexOf("%27") != -1)
		string = string.replace ("%27", "'");
	
	return string;
}

function getBrandListItemInnerHTML(brandText)
{
	var innerHTML = brandText;
	var charIndex = innerHTML.indexOf('(');
	if (charIndex != -1)
	{
		// Setting different color to the manufacturer
		innerHTML = innerHTML.substr(0, charIndex) + "<label>" + innerHTML.substr(charIndex) + "</label>"; 
	}
	return innerHTML;
}


function clearDisplayScreen()
{
	document.getElementById("displayScreenCenter").innerHTML = "";
	document.getElementById("displayScreenSideBarContent").innerHTML = "";
}


///////////////////////////////////
//// Highlight Product Range //////
///////////////////////////////////
var highlightProductInterval = -1;
function HighlightProductRange(brandId)
{
	try
	{
		var productRangeText = getProductRange(brandId, false);
		
		while (productRangeText.indexOf("\n") != -1)
			productRangeText = productRangeText.replace("\n", " ");
		while (productRangeText.indexOf("\"") != -1)
			productRangeText = productRangeText.replace("\"", "'");
		
		while (productRangeText.indexOf("&amp;") != -1)
		    productRangeText = productRangeText.replace("&amp;", "&");


		// Running on all products
		highlightProductIndex = 0;
		var code = "highlightProduct (\"" + productRangeText + "\")";
		
		highlightProductInterval = setInterval (code, 1400);
	}
	catch(ex)
	{
		clearInterval(highlightProductInterval);
	}
}

var highlightProductIndex = 0;
function highlightProduct (productRangeText)
{
    
	// Splitting the product range
	//var productItems = productRangeText.split(", ");
	var productItems = productRangeText.split(/[,]|[;]/);
	
	// If current product's index within the range's count
	if (highlightProductIndex >= productItems.length)
	{
		clearInterval(highlightProductInterval);	// Canceling the thread
		setProductRange (productRangeText);		 // Setting original text
		return;
	}
	
	var rebuiltProductRange = "";
	var highlightedItemText = "";
	
	//Redesigning the item
	var productText = productItems[highlightProductIndex];
	var spanEndIndex = productText.toUpperCase().indexOf("</SPAN>");
	
	// If sub range exists
	if (spanEndIndex != -1)
	{
		spanEndIndex += ("</SPAN>".length);
		// not putting in design the sub range' related part
		highlightedItemText = productText.substr(0, spanEndIndex) + "<span class='highlightedProduct'>" + productText.substr(spanEndIndex) + "</span>";
	}
	else
	{
		highlightedItemText = "<span class='highlightedProduct'>" + productText + "</span>";
	}
	
	
	// Running on all items to build new product range HTML
	for (var j = 0;  j < productItems.length;  j++)
	{
		var productItemText = productItems[j];
		
		// If the current item is the highlightedItem
		if (j == highlightProductIndex)
		{
			// Replacing it with the designed text
			productItemText = highlightedItemText;
		}
		
		// If last item
		if (j == productItems.length-1)
		{
			// Adding item without the seperator (space char) after
			rebuiltProductRange += productItemText;
		}
		else
		{
			// If last item of sub range and this item is not "more..."
			if ((productItems[j+1].indexOf("subRange") != -1)  && (productItems[j+1].indexOf("...") == -1))
			{
				rebuiltProductRange += (productItemText + ";");
			}
			else
			{
				rebuiltProductRange += (productItemText + ",");
			}
		}
	}
	
	// Setting the new HTML
	setProductRange (rebuiltProductRange);
	highlightProductIndex++;
}
