//------------------------------------------------------------------------------
//	Program:	scripts/general.js
//	Function:	general javascript functions.
//	Version:	1.0
//
//	Version History
//
//	V#    Date        Author          Reason
//	==    ====        ======          ======
//	1.0   20/08/2001	Bill Hicks	    New Program
//	1.1   05/12/2004	Julian Wilkins	    Added check for Public Sector.
//	1.2   22/02/2005	Julian Wilkins	    Reworded Public Sector msg.
//------------------------------------------------------------------------------
//

// determine browser
var base="";
var br;
// shows the drop down menu
var textColour="333366";
var backgroundColour="e7e7f7";
var highlightBColour="e7e7f7";
var highlightTColour="3366cc";
// change logo counters
var numLogos;
var countLogo;


//==============================================================================
// Function: Centre a window.
//==============================================================================

function centreWindow(pWinObj, pWinWidth, pWinHeight)
{

	var newX;
	var newY;

	newX = Math.round((screen.availWidth - pWinWidth) / 2);
	newY = Math.round((screen.availHeight - pWinHeight) / 2);

	pWinObj.moveTo(newX,newY);
	pWinObj.focus();

} // end of winCentreWindow()

//==============================================================================
// Function: Open a small window centred on the screen
//==============================================================================

function smallWin(sName, sUrl)
{
	var	openedWindow;

	openedWindow = window.open(sUrl, sName,'width=300,height=200,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,copyhistory=0,top=0,left=200');
	//centreWindow(openedWindow, 300, 200);
	//TAMU changed: openedwin.focus in openedwindow.focus
	openedWindow.focus();

	return openedWindow;

} // end of oWin()

function helpWindow(help)
{
	smallWin("Help", "help.htm?id=" + help);
}
function DetermineBrowser()
{
	if(navigator.appName == 'Netscape' && document.layers != null)
	{
		br="N";
//		base="file:///G|/PA Business Systems/prototype/";
		highlightBColour="d0d0e0";
	}
	else if(navigator.appName == 'Microsoft Internet Explorer' && document.all != null)
 	{
		br="IE";
//		base="G:\\PA Business Systems\\prototype\\";
	}
	else
	{
		br=null
	}
}

//
// determine if input string is a positive integer
//	return: true if input is a positive integer
//	        false if it is not
//
function isPosInteger(input)
{
	var inputStr = input.toString();
	if (inputStr.length == 0)
		return false;
	for (var i = 0; i < inputStr.length; i++)
	{
		var ch = inputStr.charAt(i);
		if (ch < "0" || ch > "9")
			return false;
	}
	return true;
}

//
// jump to specified url
//
function gotoUrl(href)
{
	location.href=base + href;
}

// logout of the site

function logout()
{
	gotoUrl("logout.htm");
}

// from the parameters afetr the URL pick out the value for this one

function decodeEntry(entryName)
{
	var passed, vstring, vend;

	passed=window.location.search.substring(1);
	vstart = passed.search("[?&]" + entryName + "=");
	vstring = passed.slice(vstart + entryName.length+2);
	vend = vstring.search("&");
	if (vend != -1)
		vstring = vstring.slice(0, vend).replace(/\+/g, ' ');
	return(vstring);
}


function copyFields()
{
	var n = copyFields.arguments.length;
	if (n >= 4)
	{
		var form, groupFrom, groupTo, i;
		form = copyFields.arguments[0];
		if (document.forms[form] == null)
		{
			alert("'"+form+"' is not a valid form name");
			return(true);
		}
		groupFrom = 'txt' + copyFields.arguments[1];
		groupTo = 'txt' + copyFields.arguments[2];
		for (i = 3; i < n; i++)
		{
			if (document.forms[form][groupTo+copyFields.arguments[i]] == null)
			{
				alert("'"+groupTo+copyFields.arguments[i]+"' is not a valid field name in form '"+form+"'");
				return(true);
			}
			if (groupFrom == "")
				document.forms[form][groupTo+copyFields.arguments[i]].value = "";
			else
			{
				if (document.forms[form][groupFrom+copyFields.arguments[i]] == null)
				{
					alert("'"+groupFrom+copyFields.arguments[i]+"' is not a valid field name in form '"+form+"'");
					return(true);
				}
				document.forms[form][groupTo+copyFields.arguments[i]].value = document.forms[form][groupFrom+copyFields.arguments[i]].value;
			}
		}
	}
	return(true);
}

function emailStatus(orderNumber)
{
	gotoUrl("email_order_status.htm?order=" + orderNumber);
}

function disableUsers()
{
	gotoUrl("manage_users.htm");
}

function deleteUsers()
{
	gotoUrl("manage_users.htm");
}

function deleteMessages()
{
	gotoUrl("home.htm");
}

//
//	startNum
//		determine whether a string starts with a number
//
function startNum(num)
{
	return isPosInteger(num.substring(0,1));
}
//
//	given a javascript date object, return a string represenation of the date and time
//
var INCLUDE_TIME = 1;
var EXCLUDE_TIME = 2;
function dateToString(jsDate, inex_time)
{
	var yr = jsDate.getYear();
	if (yr < 1000)
		yr += 1900;
	var strDate = to2(jsDate.getDate()) + "/" + to2(jsDate.getMonth() + 1) + "/" + yr;
	if (inex_time == INCLUDE_TIME)
		strDate = strDate + " " + to2(jsDate.getHours()) + ":" + to2(jsDate.getMinutes());
	return strDate;
}


function dateToParts(dateString)
{
	var parts, datePart, timePart;
	var allParts = new Array();

	allParts[0] = "is empty";

	if (dateString == "")
	{
		allParts[0] = "is empty";
		return allParts;
	}

	parts = dateString.split(" ")
	if (parts.length == 0 || parts.length > 2)
	{
		allParts[0] = "has a bad format";
		return allParts;
	}

	datePart = parts[0].split("/");
	if (datePart.length != 3)
	{
		allParts[0] = "has a bad date part";
		return allParts;
	}

	if (numberRange(datePart[2], 0, 49))
	{
		datePart[2] = 2000 + parseInt(datePart[2], 10);
	}
	else if (numberRange(datePart[2], 50, 99))
	{
		datePart[2] = 1900 + parseInt(datePart[2], 10);
	}
	else if (numberRange(datePart[2], 1000, 9999))
	{
		datePart[2] = parseInt(datePart[2], 10);
	}
	else
	{
		allParts[0] = "has a bad year";
		return allParts;
	}

	if (parts.length == 2)
	{
		timePart = parts[1].split(":");
		if (timePart.length != 2)
		{
			allParts[0] = "has a bad time part";
			return allParts;
		}
	}
	else
	{
		timePart = new Array(2);
		timePart[0] = 0;
		timePart[1] = 0;
	}

	allParts[0] = datePart[0];
	allParts[1] = datePart[1];
	allParts[2] = datePart[2];
	allParts[3] = timePart[0];
	allParts[4] = timePart[1];
	return(allParts);
}

var ALLOW_EMPTY_DATE = 1
var DISALLOW_EMPTY_DATE = 2

function validateDate(str, emptyAction)
{
	var dateParts = new Array();
	dateParts = dateToParts(str);
	if (dateParts.length == 1)
	{
		if (dateParts[0] != "is empty" || emptyAction != ALLOW_EMPTY_DATE)
		{
			return dateParts[0];
		}
		return "";
	}
	var jsDate = new Date(dateParts[2], dateParts[1] - 1, dateParts[0], dateParts[3], dateParts[4], 0);
	if (jsDate == "Invalid Date")
	{
		return "has bad date or time values";
	}
	if (jsDate.getDate() != parseInt(dateParts[0],10) || jsDate.getMonth() + 1 != parseInt(dateParts[1],10))
	{
		return "has a bad day or month";
	}
	return(dateToString(jsDate, INCLUDE_TIME));
}

//
//	firstDate
//
//	determine which of two dates and times comes first
//
var EARLY_EMPTY = 1
var LATE_EMPTY = 2
var EARLY_AND_LATE_EMPTY = 3
var EARLY_FIRST = 4
var LATE_FIRST = 5
var EARLY_ERROR = 6
var LATE_ERROR = 7
var EARLY_LATE_SAME = 8
function firstDate(earlyDate, lateDate)
{
	var earlyParts = new Array(), lateParts = new Array();
	earlyParts = dateToParts(earlyDate);
	lateParts = dateToParts(lateDate);
	if (earlyParts[0] == "is empty" && lateParts[0] == "is empty")
		return(EARLY_AND_LATE_EMPTY);
	if (earlyParts[0] == "is empty")
		return(EARLY_EMPTY);
	if (lateParts[0] == "is empty")
		return(LATE_EMPTY);
	if (earlyParts.length == 1)
		return(EARLY_ERROR);
	if (lateParts.length == 1)
		return(LATE_ERROR);
	if (earlyParts[2] < lateParts[2])
		return(EARLY_FIRST);
	if (earlyParts[2] > lateParts[2])
		return(LATE_FIRST);
	if (earlyParts[1] < lateParts[1])
		return(EARLY_FIRST);
	if (earlyParts[1] > lateParts[1])
		return(LATE_FIRST);
	if (earlyParts[0] < lateParts[0])
		return(EARLY_FIRST);
	if (earlyParts[0] > lateParts[0])
		return(LATE_FIRST);
	if (earlyParts[3] < lateParts[3])
		return(EARLY_FIRST);
	if (earlyParts[3] > lateParts[3])
		return(LATE_FIRST);
	if (earlyParts[4] < lateParts[4])
		return(EARLY_FIRST);
	if (earlyParts[4] > lateParts[4])
		return(LATE_FIRST);
	return(EARLY_LATE_SAME);
}

//
// validateCurrency
//
//	check whether the string can be interpreted as an amount of money
//
var ALLOW_EMPTY_PRICE = 1
var DISALLOW_EMPTY_PRICE = 2

function validateCurrency(amount, allowEmpty)
{
	var strAmount = amount.toString();
	if (strAmount.length == 0 && allowEmpty == DISALLOW_EMPTY_PRICE)
		return "is empty";
	var parts = amount.split(".");
	if (parts.length == 0 || parts.length > 2)
		return "is an invalid price";
	if (parts[0].length == 0)
		parts[0] = "0";
	var cparts = parts[0].split(",");
	if (cparts.length > 1 && cparts[0].length > 3)
		return "has an invalid format";
	parts[0] = cparts[0];
	for (var i = 1; i < cparts.length; i++)
	{
		if (cparts[i].length != 3)
			return "has an invalid format";
		parts[0] += cparts[i];
	}
	if (!isPosInteger(parts[0]))
		return "is an invalid price";
	if (parts.length == 2)
	{
		if (parts[1].length > 2)
			return "is an invalid price";
		if (parts[1].length == 0)
			parts[1] = "00";
		if (parts[1].length == 1)
			parts[1] = parts[1] + "0";
		if (!isPosInteger(parts[1]))
			return "is an invalid price";
	}
	else
		parts[1] = "00";
	parts[0] = cparts[0];
	for (var i = 1; i < cparts.length; i++)
	{
		parts[0] += "," + cparts[i];
	}
	return parts[0] + "." + parts[1];
}

//
//	validateQty
//
//	check whether the string can be interpreted as a quantity
//
var ALLOW_ZERO_QUANTITY = 1;
var DISALLOW_ZERO_QUANTITY = 2;

function validateQty(num, allow_zero)
{
	if (!isPosInteger(num))
		return false;
	if (allow_zero == ALLOW_ZERO_QUANTITY)
		return true;
	if (parseInt(num, 10) == 0)
		return false;
	return true;
}

//
//	quantityChange
//
//	validate a change in quantity and mark the row as changed
//
function quantityChange(formName, column, row, allow_zero)
{
	var elementName;
	if (row == "")
		elementName = column;
	else
		elementName = column + " " + row;
	var inputField = "document.forms[\""+formName+"\"].elements[\""+elementName+"\"]";
	var quantity = eval(inputField + ".value")
	var valid = validateQty(quantity, allow_zero);
	if (!valid)
	{
		if (allow_zero == ALLOW_ZERO_QUANTITY)
			alert("You have entered an invalid quantity.\nPlease enter a new quantity (zero or more).");
		else
			alert("You have entered an invalid quantity.\nPlease enter a new quantity (greater than zero).");
		document.forms[formName].elements[elementName].focus();
		document.forms[formName].elements[elementName].select();
//		eval(inputField).select();
	}
	else
		maintChange(formName, row);
}

var INCLUDE_TIME = 1;
var EXCLUDE_TIME = 2;
//
//	validate a user entered date change
//
function dateChangeProcess(formName, column, row, inex_time)
{
	var elementName;
	if (row == "")
		elementName = column;
	else
		elementName = column + " " + row;
	var inputField = "document.forms[\""+formName+"\"].elements[\""+elementName+"\"]";
	var parsedDate = validateDate(eval(inputField + ".value"), ALLOW_EMPTY_DATE);
	if (parsedDate != "" && !isPosInteger(parsedDate.substring(0,1)))
	{
		alert("You have entered an invalid date and/or time.\nIt " + parsedDate + ".\nPlease enter a date in dd/mm/yy format\nor a date and time in dd/mm/yy hh:mm format.");
		document.forms[formName].elements[elementName].focus();
		document.forms[formName].elements[elementName].select();
//		eval(inputField).select();
	}
	else
	{
		if (row != "")
			maintChange(formName, row);
		if (inex_time == EXCLUDE_TIME)
			parsedDate = parsedDate.substring(0, 10);
		eval(inputField).value = parsedDate;
	}
}
function dateChange(formName, column, row)
{
	dateChangeProcess(formName, column, row, INCLUDE_TIME);
}

function dateOnlyChange(formName, column, row)
{
	dateChangeProcess(formName, column, row, EXCLUDE_TIME);
}

//
//	validate a user entered price change
//
function priceChange(formName, column, row)
{
	var elementName;
	if (row == "")
		elementName = column;
	else
		elementName = column + " " + row;
	var inputField = "document.forms[\""+formName+"\"].elements[\""+elementName+"\"]";
	var parsedPrice = validateCurrency(eval(inputField + ".value"), DISALLOW_EMPTY_PRICE);
	if (parsedPrice != "" && !isPosInteger(parsedPrice.substring(0,1)))
	{
		alert("You have entered an invalid price.\nIt " + parsedPrice + ".\nPlease enter the correct price.");
		document.forms[formName].elements[elementName].focus();
		document.forms[formName].elements[elementName].select();
//		eval(inputField).select();
	}
	else
	{
		if (row != "")
			maintChange(formName, row);
		eval(inputField).value = parsedPrice;
	}
}

//
//	imageDir
//
//	return the relative directory of the image directory
//
function imageDir(isMaint)
{
	//	if (isMaint)
	//		return "../images";
	return "../images";
}

//
//	validateAddress
//
//	return an empty string if the address looks OK
//	return a string containing a description of the
//		problem if the address does not look OK
//
function validateAddress(formName, postFix)
{
	if (document.forms[formName].elements["address_l1" + postFix].value == "" &&
	    document.forms[formName].elements["address_l2" + postFix].value == "" &&
	    document.forms[formName].elements["street" + postFix].value == "")
		return "must have address1, address2 or street";
	if (document.forms[formName].elements["city" + postFix].value == "" &&
	    document.forms[formName].elements["county" + postFix].value == "")
		return "must have city and/or county";
	return "";
}

//
//	validateTelFax
//
//	return true if OK as a telephone number
//
function validateTelFax(number, allow_empty)
{
	if (!allow_empty && number == "")
		return false;
	return true;
}

//
//	chooseSelect
//
//	choose a particular option in a dropdown select
//
function chooseSelect(formSelect, value)
{
	var i;
	for (i = 0; i < formSelect.length; i++)
	{
		if (formSelect.options[i].value == value)
		{
			formSelect.selectedIndex = i;
			return true;
		}
	}
	return false;
}

function ClientSideError(type,no,message)
{
	document.all.hidErrorType.value   = type;
	document.all.hidErrorNumber.value = no;
	document.all.hidErrorMsg.value    = message;
	document.frmError.submit();
	return true;
}

function WM_preloadImages() {
/*
WM_preloadImages()
Loads images into the browser's cache for later use.
Usage: WM_preloadImages('image 1 URL', 'image 2 URL', 'image 3 URL', ...);
*/

  // Don't bother if there's no document.images
  if (document.images) {
    if (typeof(document.WM) == 'undefined'){
      document.WM = new Object();
    }
    document.WM.loadedImages = new Array();
		document.WM.manufacturerID = new Array(); //take this line out once asp written to define Manufacturer ID
    // Loop through all the arguments.
    var argLength = WM_preloadImages.arguments.length;
    for(arg=0; arg < argLength; arg++) {
      // For each arg, create a new image.
      document.WM.loadedImages[arg] = new Image();
      // Then set the source of that image to the current argument.
      document.WM.loadedImages[arg].src = WM_preloadImages.arguments[arg];
			document.WM.manufacturerID[arg] = arg; //take this line out once asp written to define Manufacturer ID
    }
		//set logo counters
    numLogos = argLength;
    countLogo = 0;
  }
}

function logoSwap() {
	if(numLogos==0)
		return;

	window.setTimeout('logoSwap()',3000);
	countLogo = countLogo + 1;
	if (countLogo >= numLogos) {
		countLogo = 0;
	}
	var fileName = document.WM.loadedImages[countLogo].src;
	if (document.images.middleImage)
	{
		document.images.middleImage.src = unescape(fileName);
	}
}

//function callSearch() {
//	document.location.href = "search_products.asp?" + document.WM.manufacturerID[countLogo];
//}

//==============================================================================
// Function: Open a big window.
//==============================================================================

function openWindow(pName, pUrl)
{
	var	featureString = 'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,copyhistory=0,top=0';
	var	openedWindow = openWindowFeatures(pName, pUrl, featureString);
	return openedWindow;
}


function openWindowWithToolBar(pName, pUrl)
{
	var	featureString = 'toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes,copyhistory=0,top=0';
	var	openedWindow = openWindowFeatures(pName, pUrl, featureString);
	return openedWindow;
}


function openWindowFeatures(pName, pUrl, featureString)
{
	var	winX = 790;
	var	winY = 350;
	var	openedWindow;

	featureString = 'width=' + winX + ',height=' + winY + ',' + featureString;

	// OCS Open window of set dimensions and centre it.
	if (br=="N")
	{
		openedWindow = window.open(pUrl, pName, featureString);
		centreWindow(openedWindow, winX, winY);
	}
	else
	{
		openedWindow = window.open(pUrl, pName, featureString);
		centreWindow(openedWindow, winX, winY);
		openedWindow.location.href = pUrl;
	}

	openedWindow.focus();

		// Return the window object.



	return openedWindow;

} // end of openWindow()

//==============================================================================
// Function: Open a smaller window.
//==============================================================================

function oWin(sName, sUrl)
{
	var	openedWindow;

	openedWindow = window.open(sUrl, sName,'width=300,height=200,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=0,copyhistory=0,top=0,left=200');
	openedWindow.focus();

	return openedWindow;

} // end of oWin()

//==============================================================================
// Function: Open a big window.
//==============================================================================

function openURL(sUrl)
{
	var	openedWindow;

	openedWindow = window.open(sUrl, 'remotelink','copyhistory=0,top=0,left=0,copyhistory=0,top=0,left=0,toolbar=1,location=1,directories=1,status=1,menubar=1,scrollbars=1,resizable=1,copyhistory=0');
	openedWindow.focus();

} // end of openURL()

//==============================================================================
// Function: Open a restricted window.
//==============================================================================

function openRestrictedURL(sUrl)
{
	var	openedWindow;

	openedWindow = window.open(sUrl, 'restrictlink','copyhistory=0,top=0,left=0,copyhistory=0,top=0,left=0,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,copyhistory=0');
	openedWindow.focus();

} // end of openURL()

//==============================================================================
// Function: Return a boolean to indicate if this is a valid email address.
//==============================================================================

function IsValidEmailAddress(sMailAddress)
{
	var	result;
	var	emailAddress;
	var	supported;
	var	tempStr;
	var	tempReg;
	var r1;
	var r2;

	result = false;

	if (sMailAddress.length > 0)
	{
			// Check if the format of the email address is correct.

		supported = 0;
		if (window.RegExp)
		{
			tempStr = "a";
			tempReg = new RegExp(tempStr);
			if (tempReg.test(tempStr))
			{
				supported = 1;
			}
		}
		if (!supported)
		{
			result = (sMailAddress.indexOf(".") > 2) && (sMailAddress.indexOf("@") > 0);
		}
		else
		{
			r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)");
			r2 = new RegExp("^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
			result = (!r1.test(sMailAddress) && r2.test(sMailAddress));
		}
	}

	return (result);
}

//==============================================================================
// Function: Open a help info window
//==============================================================================

function OpenHelpWin(sHelpID)
{
	var url = "popup_help.asp?helpid=" + sHelpID;
	var newWin = openWindow("HelpInfo", url);
} // end of openHelpWin()


//==============================================================================
// Function: Open a product information window
//==============================================================================

function OpenProductWin(iProdID, sessionID)
{
	var newWin = openWindow("ProductInfo", 'popup_product_info.asp?prodID=' + iProdID + '&sessionID=' + sessionID);
}

//==============================================================================
// Function: Open a Customer Register Conditions window
//==============================================================================


function OpenConditionsRegWin()
{
	var newWin = openWindow("TermsInfo", '../order/conditions_register.asp');
}

//==============================================================================
// Function: Open a Competition Register Conditions window
//==============================================================================

function OpenConditionsCompetitionWin()
{
	var newWin = openWindow("TermsInfo", 'conditions_competition.asp');
}
//==============================================================================
// Function: Open a CUG Conditions window
//==============================================================================

function OpenConditionsCugWin()
{
	var newWin = openWindow("TermsInfo", 'conditions_cugo.asp');
}

//==============================================================================
// Function: Open a Re-marketed window
//==============================================================================

function OpenRemarketedWin()
{
	var newWin = openWindow("Remarketed", 'aboutRemarketed.asp');
}

//==============================================================================
// Function: Open a Re-marketed window
//==============================================================================

function updatePublicSectorCookie(pCookieValue)
{
	SaveCookie('PAisHPPublicSector', pCookieValue, 30);
}

//==============================================================================
// Function: Open a Re-marketed window
//==============================================================================

function chkIfPublicSector(pObject)
{
	if (pObject.checked == true)
	{
		updatePublicSectorCookie("1");
	}
	else
	{
		alert("Please tick the box to confirm you qualify for the Public Sector Programme");
		updatePublicSectorCookie("0");
		pObject.focus();
		return(false);
	}
	return(true);
}
