﻿function confirmAction(msg)
{
	if (!msg)
		msg = "Are you sure you wish to do this?";
		
	var agree=confirm(msg);
	if (agree)
		return true ;
	else
		return false ;
}
	
function printWindow(){
	browserVersion = parseInt(navigator.appVersion);
	if (browserVersion >= 4) 
	    window.print();
	// only v 4 and up print
}


function getElement(elementID)
{
	if (document.getElementById)
		return document.getElementById(elementID);
	else if (document.all)
		return document.all(elementID);
	else if (document.layers)
	    return document.elementID;
	else
		return null;
}

function toggleMenuVisibility()
{
	var openMenu = getElement('hidMenuOpen');
	if (openMenu)
	{
		if (openMenu.value == 1)
		{
			hideMenu();
		}
		else
			showMenu();
	}
	else
	{
		hideMenu();
	}
}

function tryMenuClose()
{
	var openMenu = getElement('hidMenuOpen');
	if (openMenu)
	{
		if (openMenu.value == 0)
		{
			hideMenu();
		}
		else
		{
			setTimeout("tryMenuClose();", 500);
		}
	}
	else
	{
		hideMenu();
	}
}

function getElementPosition(id) 
{
	var offsetElement = getElement(id);
	var offsetLeft = 0;
	var offsetTop = 0;
	while (offsetElement) 
	{
		offsetLeft += offsetElement.offsetLeft;
		offsetTop += offsetElement.offsetTop;
		offsetElement = offsetElement.offsetParent;
	}
	
	if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined") 
	{
		offsetLeft += document.body.leftMargin;
		offsetTop += document.body.topMargin;
	}
	
	return {left:offsetLeft, top:offsetTop};
}
/*
var	requiredVersion = 8;
var	maxVersion = 8;
var	actualVersion = 0;
var	isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;    // true if we're on ie
var	isWin = (navigator.appVersion.indexOf("Windows") != -1) ? true : false; // true if we're on windows

var vbs = '<SCR' + 'IPT language=vbsc' + 'ript>';
vbs = vbs + 'If isIE And isWin Then\n';
vbs = vbs + 'On Error Resume Next\n';
vbs = vbs + 'For vbi = 2 To maxVersion\n';
vbs = vbs + 'If (IsObject(CreateObject("ShockwaveFlash.ShockwaveFlash." & vbi))) Then\n';
vbs = vbs + 'actualVersion = vbi\n';
vbs = vbs + 'End If\n';
vbs = vbs + 'Next\n';
vbs = vbs + 'End If\n';
vbs = vbs + '</SCR' + 'IPT>'

document.write(vbs);

function hasFlash()
{
	if (navigator.plugins) 
	{
		if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) 
		{
			var isVersion2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
			var flashDescription = navigator.plugins["Shockwave Flash" + isVersion2].description;

			var flashVersion = parseInt(flashDescription.charAt(flashDescription.indexOf(".") - 1));
			for (var index = 2; index <= maxVersion; index++)
			{
				if (flashVersion == index)
					actualVersion = index;
			}
		}
	}

	if(navigator.userAgent.indexOf("WebTV") != -1) 
		actualVersion = 3;

	return (actualVersion >= requiredVersion);
}
*/

var	requiredVersion = 8;
var	maxVersion = 10;
var	actualVersion = 0;

var activeXDetectRules = [
        {
            "name":"ShockwaveFlash.ShockwaveFlash.7",
            "version":function(obj){
                return getActiveXVersion(obj);
            }
        },
        {
            "name":"ShockwaveFlash.ShockwaveFlash.6",
            "version":function(obj){
                var version = "6,0,21";
                try{
                    obj.AllowScriptAccess = "always";
                    version = getActiveXVersion(obj);
                }catch(err){}
                return version;
            }
        },
        {
            "name":"ShockwaveFlash.ShockwaveFlash",
            "version":function(obj){
                return getActiveXVersion(obj);
            }
        }
    ];

function getActiveXVersion(activeXObj){
        var version = -1;
        try{
            version = activeXObj.GetVariable("$version");
        }catch(err){}
        return version;
    };
    
function getActiveXObject(name){
        var obj = -1;
        try{
            obj = new ActiveXObject(name);
        }catch(err){
            obj = {activeXError:true};
        }
        return obj;
    };

function parseActiveXVersion(str){
        var versionArray = str.split(",");//replace with regex
        return {
            "raw":str,
            "major":parseInt(versionArray[0].split(" ")[1], 10),
            "minor":parseInt(versionArray[1], 10),
            "revision":parseInt(versionArray[2], 10),
            "revisionStr":versionArray[2]
        };
    };


function parseStandardVersion(str){
        var descParts = str.split(/ +/);
        var majorMinor = descParts[2].split(/\./);
        var revisionStr = descParts[3];
        return {
            "raw":str,
            "major":parseInt(majorMinor[0], 10),
            "minor":parseInt(majorMinor[1], 10), 
            "revisionStr":revisionStr,
            "revision":parseRevisionStrToInt(revisionStr)
        };
    };

var parseRevisionStrToInt = function(str){
        return parseInt(str.replace(/[a-zA-Z]/g, ""), 10);
    };

function hasFlash()
{		
	if(navigator.plugins && navigator.plugins.length>0){
            var type = 'application/x-shockwave-flash';
            var mimeTypes = navigator.mimeTypes;
            if(mimeTypes && mimeTypes[type] && mimeTypes[type].enabledPlugin && mimeTypes[type].enabledPlugin.description){
                var version = mimeTypes[type].enabledPlugin.description;
                var versionObj = parseStandardVersion(version);
                
                actualVersion = parseInt(versionObj.major);
            }
        }else if(navigator.appVersion.indexOf("Mac")==-1 && window.execScript){
            var version = -1;
            for(var i=0; i<activeXDetectRules.length && version==-1; i++){
                var obj = getActiveXObject(activeXDetectRules[i].name);
                if(!obj.activeXError){
                
                    version = activeXDetectRules[i].version(obj);
                    if(version!=-1){
                        var versionObj = parseActiveXVersion(version);
                        actualVersion = parseInt(versionObj.major);
                    }
                }
            }
        }

	return (actualVersion >= requiredVersion);
}

function toggleElementVisibility(id)
{
    if (document.getElementById)
	{
	    if (document.getElementById(id).style.display == 'none' || document.getElementById(id).style.visibility == 'hidden')
	    {
	        document.getElementById(id).style.display = '';
		    document.getElementById(id).style.visibility = 'visible';
	    }
	    else
	    {
	        document.getElementById(id).style.display = 'none';
		    document.getElementById(id).style.visibility = 'hidden';
	    }
	}
	else if (document.layers)
	{
	    if (document.layers[id].display == 'none')
		    document.layers[id].display = '';
		else
		    documeny.layers[id].display = 'none';
	}
}

function showElement(id)
{    
	if (document.getElementById)
	{
		if (document.getElementById(id).style.display == 'none')
			document.getElementById(id).style.display = '';
			
		if (document.getElementById(id).style.visibility == 'hidden')
			document.getElementById(id).style.visibility = 'visible';
	}
	else if (document.layers)
	{
		document.layers[id].display = '';
		document.layers[id].visibility = 'show';
	}
	
}

function hideElement(id)
{
	if (document.getElementById)
	{
	    document.getElementById(id).style.display = 'none';
		document.getElementById(id).style.visibility = 'hidden';
	}
	else if (document.layers)
	{
		document.layers[id].display = 'none';
		document.layers[id].visibility = 'hide';
	}
	else if (document.all)
	{
		eval("document.all." + id + ".style.display = 'none'");
	}
	
}

function clearTextBox(textBoxID)
{
    var textElement = getElement(textBoxID);
    textElement.value = "";
}

function toggleSelectAll(superCheckBoxID, checkBoxPrefix)
{
    if (getElement)
    {
        var chkBox = getElement(superCheckBoxID);
        if (chkBox)
        {
            var theForm = chkBox.form;
    
            for(z=0; z<theForm.length;z++)
            {
                if(theForm[z].type == 'checkbox' && theForm[z].name.toLowerCase().indexOf(checkBoxPrefix.toLowerCase()) == 0)
                {
	                theForm[z].checked = chkBox.checked;	  
	            }
	        }
        }
    }
}

function checkSuperCheckBox(superCheckBoxID, checkBoxPrefix)
{
    if (getElement)
    {
        var chkBox = getElement(superCheckBoxID);
        if (chkBox)
        {
            var theForm = chkBox.form;
            var check = true;
            for(z=0; z<theForm.length;z++)
            {
                if (theForm[z] != chkBox)
                {
                    if(theForm[z].type == 'checkbox' && theForm[z].name.toLowerCase().indexOf(checkBoxPrefix.toLowerCase()) == 0)
                    {
                        if (!theForm[z].checked)
                            check = false;	  
	                }
	            }
	        }
	        
	        chkBox.checked = check;
        }
    }
}

function changeCollapseExpand(id, collapseUrl, expandUrl)
{
    var img = getElement(id);
    if (img)
    {
       if (img.src.toLowerCase().indexOf(collapseUrl.toLowerCase()) >= 0)
            img.src = expandUrl;
        else
            img.src = collapseUrl;
    }
}

function checkSearchLength(id, msg)
{
    var searchBox = getElement(id);
    if (searchBox)
    {
        if (searchBox.value.length < 0)
        {
            alert(msg);
            searchBox.focus();
            return false;
        }
        else
            return true;
    }
    else
        return false;
}

function onChangeText(textBox, counterID, maxLength, lengthMessage)
{
    if (textBox.value.length > maxLength)
    {
        textBox.value = textBox.value.substring(0, maxLength);
        alert(lengthMessage);
    }
    
    var counterBox = document.getElementById(counterID);
    if (counterBox)
    {
        if (counterBox.innerText)
            counterBox.innerText = maxLength - textBox.value.length;
        else
            counterBox.value = maxLength - textBox.value.length;
    }
}

function roundNumber(number, decimalPlaces)
{
    var newnumber = 0;
	if (number > 8191 && number < 10485) // javascript handles these number strangely
	{
		number = number - 5000;
		newnumber = Math.round(number*Math.pow(10,decimalPlaces))/Math.pow(10,decimalPlaces);
		newnumber = newnumber + 5000;
	} 
	else 
	{
		newnumber = Math.round(number * Math.pow(10, decimalPlaces)) / Math.pow(10, decimalPlaces);
	}
	
	return newnumber;
}

function changeElementCssClass(id, className)
{
	var element = getElement(id);
	if (element)
	{
		element.className = className;
	}
}

function changeThumbnailClass(idPrefix, selectedClassName, deselectedClassName, firstImageNumber, lastImageNumber, selectedImageNumber)
{
	for (i = firstImageNumber; i <= lastImageNumber; i++)
	{
		if (i == selectedImageNumber)
			changeElementCssClass(idPrefix + i, selectedClassName);
		else
			changeElementCssClass(idPrefix + i, deselectedClassName);
	}
}

function changeImageSource(id, imageUrl)
{
	var element = getElement(id);
	if (element)
	{
		element.src = imageUrl;
	}
}

function getWindowDimensions() 
{
	var myWidth = 0
	var myHeight = 0;
	
	if(typeof(window.innerWidth) == 'number') 
	{
		//Non-IE
		myWidth = window.innerWidth;
		myHeight = window.innerHeight;
	} 
	else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) 
	{
		//IE 6+ in 'standards compliant mode'
		myWidth = document.documentElement.clientWidth;
		myHeight = document.documentElement.clientHeight;
	} 
	else if (document.body && (document.body.clientWidth || document.body.clientHeight))
	{
		//IE 4 compatible
		myWidth = document.body.clientWidth;
		myHeight = document.body.clientHeight;
	}
  
  return {width:myWidth, height:myHeight};
}

function getElementDimensions(id) 
{
	var element = getElement(id);
	var myWidth = -1;
	var myHeight = -1;
	
	if (element)
	{
		myWidth = element.offsetWidth;
		myHeight = element.offsetHeight;
	}
	
	return {width:myWidth, height:myHeight};
}

function getElementPosition(id) 
{
	var offsetElement = getElement(id);
	var offsetLeft = 0;
	var offsetTop = 0;
	while (offsetElement) 
	{
		offsetLeft += offsetElement.offsetLeft;
		offsetTop += offsetElement.offsetTop;
		offsetElement = offsetElement.offsetParent;
	}
	
	if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined") 
	{
		offsetLeft += document.body.leftMargin;
		offsetTop += document.body.topMargin;
	}
	
	return {left:offsetLeft, top:offsetTop};
}

function horizontalAlignElement(id, alignment)
{
	var elementToAlign = getElement(id);

	var elementWidth = elementToAlign.offsetWidth;
	var screenWidth = getWindowDimensions().width;
	if (elementToAlign)
	{
		switch (alignment)
		{
			case 'center':
				var left = 0.5 * (screenWidth - elementWidth);
				elementToAlign.style.left = left + 'px';
				break;
			case 'right':
				var left = screenWidth - elementWidth - 2;
				elementToAlign.style.left = left + 'px';
				break;
			default:
				elementToAlign.style.left = '0px';
				break;
		}
	}
}

/****** Trader Notes in Basket ************/

function showTraderNotes(id)
{
    showElement(id);
}

function hideTraderNotes(id)
{   
    hideElement(id);    
}

function isElementVisible(id)
{
    var element = getElement(id);
    
    if (element)
    {
        if (element.style.display == 'none')
            return false;
        else if (element.style.visibility == 'hidden')
            return false;
        else
            return true;
    }
    else
        return false;
}

function toggleTraderNotes(id)
{ 

    if(isElementVisible(id))
    {
        hideTraderNotes(id);
    }
    else
    {        
        showTraderNotes(id);
    }
}

function setIncVATValue(incVatID, exVatID, vatRate)
{     
    var exVatPrice = Number(getElement(exVatID).value);
    var incVatTextBox = getElement(incVatID);
    
    if (!isNaN(exVatPrice))
    {
        var tax = bankersRound(exVatPrice * vatRate / 100);    
        var price = exVatPrice + tax;  
        
        if (exVatPrice == 0)
        {
            incVatTextBox.value = "";
        }
        else
        {
            incVatTextBox.value = bankersRound(price).toFixed(2);    
        }
    }
    else
    {
        incVatTextBox.value = "";    
    }        
}

function setExVATValue(exVatID, incVatID, vatRate)
{
    var incVatPrice = Number(getElement(incVatID).value);
    var exVatTextBox = getElement(exVatID);
    
    if (!isNaN(incVatPrice))
    {
        var exVatPrice = incVatPrice / ((100 + vatRate) / 100);  
        
        if (incVatPrice == 0)
        {
            exVatTextBox.value = "";
        }
        else
        {   
            exVatTextBox.value = bankersRound(exVatPrice).toFixed(2);  
        }
    }
    else
    {  
        exVatTextBox.value = "";    
    } 
}   

function bankersRound(input)
{
      if (!isNaN(input))
      {
            var multiple = 1;
            if (input < 0)
                  multiple = -1;
                  
            var abs = Math.abs(input);
            var fullFigure = abs * 100;
            var floor = Math.floor(fullFigure);
            
            if (fullFigure - floor != 0.5)
                  return Math.round(input * 100) / 100;
            else
            {
                  if (Math.round(fullFigure) % 2 == 1) // 0.5, 2.5, 4.5, 6.5, 8.5 should round down
                        return Math.floor(fullFigure) / 100 * multiple;
                  else
                        return Math.round(fullFigure) / 100 * multiple;
            }
            
      }
      else
            throw "bankersRound(" + input + "): input is not a number";
}

// Brand Hover Functions

function openBrandHoverMenu(id)
{
    var spanMenu = getBrandHoverElement(id);        
    var menuState = getBrandHoverElement("hid" + id);        
    
    // alignHoverMenu(id);
    
    if (menuState.value != 1)
    {
        spanMenu.style.visibility = "visible";
        menuState.value = 1
    }
}

function closeBrandHoverMenu(id)
{    
    var menuState = getBrandHoverElement("hid" + id);
    var spanMenu = getBrandHoverElement(id);
    
    menuState.value = 0;
    
    setTimeout("scheduleBrandHoverClose('" + id + "');", 500);
}

function scheduleBrandHoverClose(id) 
{
    
    var spanMenu = getBrandHoverElement(id);
    var menuState = getBrandHoverElement("hid" + id);
    
    if (menuState.value == 0)
    {
	    spanMenu.style.visibility = "hidden";	
    }
    else
        setTimeout("scheduleBrandHoverClose('" + id + "');", 1000);
}

function getBrandHoverElement(elementID)
{
	if (document.getElementById)
		return document.getElementById(elementID);
	else if (document.all)
		return document.all(elementID);
	else
		return null;
}

function addHandlerToElement(element, evt, handler)
{
	if (element.addEventListener)
	{
		element.addEventListener(evt, handler, false);
	}	
	else if (element.attachEvent)
	{
		element.attachEvent('on' + evt, handler);
	}
}

/* Expanding Top Nav Sub Menu */


		
		var ExpandingMenuOptions = function() {
			return {
				menuID : '',
				firstCellID: '',
				otherCellPrefix: '',
				separatorCellPrefix: '',
				linkPrefix: '',
				separatorTextPrefix: '',
				permanentItems: 3,
				extraPadding: 20				
			};
		}
		
		ExpandingMenu = function(options) {
		
			ExpandingMenu.prototype.getMenuElement = function() { return document.getElementById(options.menuID); };
			
			ExpandingMenu.prototype.getFirstCell = function() { return document.getElementById(options.firstCellID); };
			
			ExpandingMenu.prototype.getOtherCellPrefix = function() { return options.otherCellPrefix; };
			
			ExpandingMenu.prototype.getSeparatorCellPrefix = function() { return options.separatorCellPrefix; };
			
			ExpandingMenu.prototype.getLinkPrefix = function() { return options.linkPrefix; };
			
			ExpandingMenu.prototype.getSeparatorTextPrefix = function() { return options.separatorTextPrefix; };
			
			ExpandingMenu.prototype.getNumberOfPermanentItems = function() { return options.permanentItems; };
			
			ExpandingMenu.prototype.getExtraPadding = function() { return options.extraPadding; };
		};
		
		var showAlerts = false;
		
		ExpandingMenu.prototype.resize = function() {
				var i = 1;
				
				var viewportWidth = document.documentElement.clientWidth; // available width in browser window
				var leftOfMenu = getElementPosition(this.getMenuElement().id).left; // how far in from the left is the menu element
				//alert(leftOfMenu);
				var availableWidth = viewportWidth - leftOfMenu - this.getExtraPadding(); // determine available width
				
				var totalWidth = this.getFirstCell().offsetWidth; // make sure the first cell is already taken account of
				var hideRemainingCells = false;
				
				// foreach cell, we check to see if showing it will push the width of the menu past the available space.
				// if it does, we hide it again, and all remaining cells
				while (true)
				{
					var otherCellID = this.getOtherCellPrefix() + i; // id of cell containing link
					var separatorID = this.getSeparatorCellPrefix() + i; // id of cell containing separator
					var spanID = this.getLinkPrefix() + i; // id of link
					var separatorTextID = this.getSeparatorTextPrefix() + i; // id of separator span
				
					
					var otherCell = document.getElementById(otherCellID); // table cell containing link
					var separatorCell = document.getElementById(separatorID); // table cell containing separator
					
					var otherCellText = document.getElementById(spanID); // link element
					var separatorText = document.getElementById(separatorTextID); // separator element
					
					if (!otherCell) // if we have not found the cell, we have accounted for all cells, so we are done
						break;
						
					if (hideRemainingCells) // if we are hiding all remaining cells, we hide this one and continue our loop
					{
						otherCell.style.visibility = 'hidden';
						otherCell.style.display = 'none';	
						
						if (separatorCell)
						{
							separatorCell.style.visibility = 'hidden';
							separatorCell.style.display = 'none';	
						}
						
						i++;
						continue;
					}	
					
					/* Make this cell visible, so we can determine its width */
					
					otherCell.style.visibility = 'visible';
					otherCell.style.display = '';	
					
					if (separatorCell)
					{
						if (showAlerts)
						{
							alert('Made visible');
							alert(separatorCell.innerHTML);
						}
							
						separatorCell.style.visibility = 'visible';
						separatorCell.style.display = '';	
					}		
					
					/* Determine width of the cell */
					
					var cellWidth = otherCellText.offsetWidth + this.getExtraPadding();
					if (separatorText)
						cellWidth += separatorText.offsetWidth;						
												
					// if we are past the width available to show items, and we have already shown more than is mandatory
					// we hide the cell again, and the previous separator, and signal the loop to hide all remaining cells
					if (totalWidth + cellWidth > availableWidth && i > this.getNumberOfPermanentItems())
					{
						// hide the cell and separator again
						
						otherCell.style.visibility = 'hidden';
						otherCell.style.display = 'none';	
						
						if (separatorCell)
						{
							separatorCell.style.visibility = 'hidden';
							separatorCell.style.display = 'none';	
						}
						
						// hide previous separator cell						
				
						var lastSeparatorID = this.getSeparatorCellPrefix() + (i - 1);
						var lastCell = document.getElementById(lastSeparatorID);
						
						if (lastCell)
						{
							lastCell.style.visibility = 'hidden';
							lastCell.style.display = 'none';	
						}
						
						hideRemainingCells = true;
					}
					
					// accumulate the total width of visible cells and advance the loop
					totalWidth = totalWidth + cellWidth;
					i++;
				}
};
/*************** Recently Viewed Hover *****************************/

function alignRecentlyViewedHoverMenu(id) {
    var linkCell = getRecentlyViewedHoverElement('RecentlyViewedLink');
    var spanMenu = getRecentlyViewedHoverElement(id);

    var cellY = getRecentlyViewedHoverElementOffsetTop('RecentlyViewedLink');
    var cellX = getRecentlyViewedHoverElementOffsetLeft('RecentlyViewedLink');
    var adjustedY = cellY + linkCell.offsetHeight;
    var adjustedX = cellX + linkCell.offsetWidth - spanMenu.offsetWidth;

    if (adjustedX < 0)
        adjustedX = 0;

    if (adjustedY < 0)
        adjustedY = 0;

    if (spanMenu.style) {
        spanMenu.style.left = adjustedX + "px";
        spanMenu.style.top = adjustedY + "px";
    }
}

function getRecentlyViewedHoverElementOffsetLeft(id) {
    var offsetElement = getRecentlyViewedHoverElement(id);
    var offsetLeft = 0;
    while (offsetElement) {
        offsetLeft += offsetElement.offsetLeft;
        offsetElement = offsetElement.offsetParent;
    }

    if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined") {
        offsetLeft += document.body.leftMargin;
    }

    return offsetLeft;
}

function getRecentlyViewedHoverElementOffsetTop(id) {
    var offsetElement = getRecentlyViewedHoverElement(id);
    var offsetTop = 0;
    while (offsetElement) {
        offsetTop += offsetElement.offsetTop;
        offsetElement = offsetElement.offsetParent;
    }

    if (navigator.userAgent.indexOf("Mac") != -1 && typeof document.body.leftMargin != "undefined") {
        offsetTop += document.body.topMargin;
    }

    return offsetTop;
}

function openRecentlyViewedHover(id) {
    var spanMenu = getRecentlyViewedHoverElement(id);

    spanMenu.style.visibility = "visible";
    spanMenu.style.display = "block";

    alignRecentlyViewedHoverMenu(id);
}

function closeRecentlyViewedHover(id) {
    var spanMenu = getHoverElement(id);
    spanMenu.style.visibility = "hidden";
    spanMenu.style.display = "none";
}

function getRecentlyViewedHoverElement(elementID) {
    if (document.getElementById)
        return document.getElementById(elementID);
    else if (document.all)
        return document.all(elementID);
    else
        return null;
}

function getHoverElement(elementID) {
    if (document.getElementById)
        return document.getElementById(elementID);
    else if (document.all)
        return document.all(elementID);
    else
        return null;
}
