/*********************************
	Commands to run immediately
*********************************/
addEvent(window, 'load', OpenMenus);
addEvent(window, 'load', PreloadMapImages);
addEvent(window, 'load', AddPopupBehaviour);

/*********************************
	Menu show / hide functions
*********************************/

/*
function OpenMenus2() {
	var strQ, strMenu;
	
	strQ = location.search;
	
	var re = /^.*[?&]+open=([0-9]+).*$/gi;
	
	strMenu = strQ.replace(re, '$1');
	
	if (strMenu != '') {
		showhideMenu(strMenu, 0)
	}
}
*/

function OpenMenus() {
	//Open submenus when there is a link to current page
	var objLink;
	
	//Get current page path
	var strPath = location.protocol + '//' + location.host + location.pathname
	
	//Loop through links on page
	for (var i = 0; i < document.links.length; i++) {
		objLink = document.links[i];
		
		//For matching links, check ID of parent node
		if (objLink.href == strPath) {
			var strID = objLink.parentNode.id;
			var re = /^(b_menu_[0-9]+)_[0-9]+$/gi;
			
			//If id is a menu item id then make sure menu is open 
			if (re.test(strID)) {
				//Chop submenu bits off menu item id
				strID = strID.replace(re, '$1');
				
				//Get parent menu item
				var objParent = document.getElementById(strID);
				
				//Set parent menu item to open
				if (objParent) objParent.className = 'firstparent';
			}
		}
	}
}

function showhideMenu(menuid, submenuid) {
	//open the ones passed above
	var objEl;
	
	objEl = document.getElementById('b_menu_' + menuid)
	objEl.className = (objEl.className == 'firstparent') ? '' : 'firstparent';
	
	//No submenus at present
	
	return false;
}


/********************************
	Form submission functions
********************************/
var msg = '', errmsg = '', focuselement = null, aEmailFields = null, aNumericFields = null, aRequireOneFields = null;

function CheckDestination(frm) {
	var msg="";
	selval = frm.productid.selectedIndex;
	if (selval==0)   {
		alert("Please select an itinerary..\n");
		return false;
		}
	else  {
		thevalue = frm.productid.options[selval].value;
		if (isNaN(Number(thevalue))) frm.action = thevalue;
		frm.submit();
		return true;
		}
	return CheckSelection(frm, 'destination');
}
function CheckSubject(frm) {
	return CheckSelection(frm, 'subject');
}
function CheckSelection(frm, strType) {
	var objList = frm.productid;
	
	if (objList) {
		if (objList.value == '') {
			alert('Please select a ' + strType + ' first.')
			objList.focus();
			return false;
		}
		if (objList.value == '0') {
			var strNewAction;
			strNewAction = objList[objList.selectedIndex].label;
			if (strNewAction  != '')
				frm.action = strNewAction;
			else
				return false;
		}
	}
	
	return true;
}

function CheckForm(frm) {
	//Loop through form elements, checking for a non-empty value, a selection, or valid email
	// Use the TITLE attribute of the element as the error message, adding for each error
	// Focus is set to the first offending element
	
	msg = '';
	errmsg = '';
	focuselement = null;

	//Array of email fields
	var objEmailFields = document.getElementById('emailfields')
	if (objEmailFields) aEmailFields = objEmailFields.value.split(',')

	//Array of numeric fields
	var objNumericFields = document.getElementById('numberfields')
	if (objNumericFields) aNumericFields = objNumericFields.value.split(',')

	//Check each form element
	for (var i = 0; i <= frm.elements.length - 1; i++) {
		CheckElement(frm.elements[i])
	}
	
	if (msg == '') {
		frm.submit();
	} else {
		msg = 'You need to complete the form fully before proceeding\n\n' + msg;
		alert(msg);
		if (focuselement && focuselement.focus) focuselement.focus();
	}
	
	return false;	
}

function CheckElement(element) {
	var blnEmailProblem, blnNumericProblem, blnRequireOneProblem;
	errmsg = element.title;

	//If email field then validate
	blnEmailProblem = false;
	if (element.value != '' && IsElementInArray(element, aEmailFields)) {
		blnEmailProblem = !ValidEmail(element);
	}
	//If numeric field then validate
	blnNumericProblem = false;
	if (element.value != '' && IsElementInArray(element, aNumericFields)) {
		blnNumericProblem = !ValidNumeric(element);
	}
	//If require one field
	blnRequireOneProblem = false;
	if (element.value != '' && element.name.indexOf('requireone-') == 0) {
		blnRequireOneProblem = !ValidRequireOne(element);
		if (blnRequireOneProblem) {
			//Change element to first required field
			element = document.getElementById(aRequireOneFields[0]);
		}
	}

	//If there were problems then show message and set focus to first problem
	if ( blnEmailProblem || blnNumericProblem || blnRequireOneProblem || (element.title != '' && element.value == '') ) {
		msg += errmsg + '\n';
		if (!focuselement) focuselement = element;
	}
}

function IsElementInArray(element, aFields) {
	if (aFields) {
		for (var i = 0; i < aFields.length; i++) {
			if (element.name == aFields[i]) {
				return true;
			}
		}
	}

	return false;
}

function GetLabel(element) {
	var aLabels, objLabel;
	
	aLabels = document.getElementsByTagName('LABEL');
	
	for (var i = 0; i < aLabels.length; i++) {
		objLabel = aLabels[i];
		if (objLabel.htmlFor == element.id) {
			return objLabel;
		}
	}
	
	return null;
}

function ValidEmail(element) {
	var valid, strFor, re = /^[a-z0-9_-]+(\.[a-z0-9_-]+)*@[a-z0-9_-]+(\.[a-z0-9_-]+)+$/ig;
	valid = re.test(element.value);
	if (!valid) {
		objLabel = GetLabel(element);
		if (objLabel) strFor = ' for ' + objLabel.childNodes[0].nodeValue;
		errmsg = 'Please enter a valid value' + strFor;
	}
	return valid;
}

function ValidNumeric(element) {
	var valid, strFor, re = /^[-+]?[0-9]+([.][0-9]*)?$/ig;
	valid = re.test(element.value);
	if (!valid) {
		objLabel = GetLabel(element);
		if (objLabel) strFor = ' for ' + objLabel.innerText;
		errmsg = 'Please enter a numeric value' + strFor;
	}
	return valid;
}

function ValidRequireOne(element) {
	var valid, strFor, objField;
	
	valid = false;
	
	aRequireOneFields = element.value.split(',');
	for (var i = 0; i < aRequireOneFields.length; i++) {
		objField = document.getElementById(aRequireOneFields[i]);
		
		if (objField) {
			switch (objField.type) {
			case 'checkbox':
				valid = objField.checked;
				break;
			default:
				valid = objField.value != '';
				break;
			}
			
		}
		
		//Quit loop early if valid
		if (valid) break;
	}
	
	if (!valid) {
		strFor = element.name.replace('requireone-', '');
		errmsg = 'At least one is required: ' + strFor;
	}
	return valid;
}


/******************************************************
	Support for adding multiple events to an object
******************************************************/
function addEvent(obj, evType, fn) {
	if (obj.addEventListener){
		obj.addEventListener(evType, fn, true);
		return true;
	} else if (obj.attachEvent){
		var r = obj.attachEvent("on" + evType, fn);
		return r;
	} else {
		var r = fallbackAddEventListener(obj, evType, fn);
		return r
	}
	return false;
}

var Listeners;

function fallbackAddEventListener(obj, evType, fn) {
	var l = GetListener(obj, evType);

	if (!l) {
		l = new Listener(obj, evType);
		var intListener = Listeners.length;
		Listeners[intListener] = l;
		obj.listener = l;
		eval('obj.on' + evType + ' = function() {CallListeners(' + intListener + ')}');
	}

	if (l) {
		l.functions[l.functions.length] = fn;
		return true;
	}

	return false;
}

function GetListener(obj, evType) {
	var l, strName;
	
	if (!Listeners) Listeners = new Array();
	
	strName = ListenerName(obj, evType);
	
	for (var i = 0; i < Listeners.length; i++) {
		if (Listeners[i].name == strName) {
			l = Listeners[i];
			break;
		}
	}
	
	return l;
}

function Listener(obj, evType) {
	this.name = ListenerName(obj, evType);
	this.functions = new Array();
}

function ListenerName(obj, evType) {
	return '__' + obj.tagName + '_' + obj.id + '_' + obj.name + '_' + evType;
}

function CallListeners(intListener) {
	var l;
	
	l = Listeners[intListener];
	
	if (l) {
		for (var i = 0; i < l.functions.length; i++) {
			var func = l.functions[i];
			func();
		}
	}
}



/*********************************
	Support functions
*********************************/
function findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function ClearPopupTimer() {
	if (objTimer) {
		clearTimeout(objTimer);
		objTimer = null;
	}
}

function ShowPopupText(strTextID, intX, intY) {
	var el = document.getElementById(strTextID);
	if (el) {
		el.style.display = '';
		
		el.style.top = intY + 'px';
		el.style.left = intX + 'px';
	}
}
function HidePopupText(strTextID) {
	var el = document.getElementById(strTextID);
	if (el) el.style.display = 'none';
}

/*********************************
	Popup DIV functions
*********************************/
var objTimer, objCurrent;

function ShowDestinations(e, obj, intX, intY) {
//alert('ShowDestinations');
	ShowPopupText('destination-' + obj.id, intX, intY);
	ClearPopupTimer();

	if (objCurrent && objCurrent.id != obj.id) HideDestinations(objCurrent);
	objCurrent = obj;
	
	if (obj.blur) obj.blur();
	
	obj.nohide = true;

	SetClosureDelay(obj.id)
}
function SetClosureDelay(strID) {
	strID = strID.replace('destination-', '');
	objTimer = setTimeout('CloseDestinations(\'destination-' + strID + '\')', 10000);
}
function HideDestinations(obj) {
//alert('HideDestinations');
	ClearPopupTimer();
	//objTimer = setTimeout('HidePopupText(\'destination-' + obj.id + '\')', 1000);
	HidePopupText('destination-' + obj.id);
	obj.nohide = false;
	HideMap(obj);
}
function CloseDestinations(strID) {
	strID = strID.replace('destination-', '');
	var obj = document.getElementById(strID);
	if (obj) HideDestinations(obj);
}


/***************************************************
	Map higlighting functions
***************************************************/
var strPath = '';

function PreloadMapImages() {
	var objPath = document.getElementById('mappath');
	
	if (objPath && document.getElementsByTagName) {
		strPath = objPath.value;
		
		var objAreas = document.getElementsByTagName('area');
		
		if (objAreas) {
			var strID, objIMG;
			for (var i = 0; i < objAreas.length; i++) {
				strID = objAreas[i].id;
				
				if (strID != '') {
					objIMG = new Image();
					objIMG.src = strPath + strID + '.gif';
				}
			}
		}
	}
}

function ShowMap(e, objLink, intX, intY) {
	var strImage, strID = objLink.id;
	
	if (strPath == '') {
		var objPath = document.getElementById('mappath');
		if (objPath)
			strPath = objPath.value;
		else
			strPath = '/images/maps/';
	}
	
	strImage = strPath + strID + '.gif';

	if (strID == '')
		//blank image	
		SetMapImage('/images/trans-spacer.gif');
	else
		SetMapImage(strImage);

//	ShowDestinations(e, objLink, intX, intY);
}

function HideMap(objLink) {
	var strImage, strID = objLink.id;

	//blank image	
	if (!objLink.nohide)
		SetMapImage('/images/trans-spacer.gif');

	if (objCurrent && objCurrent.nohide)
		ShowMap(null, objCurrent, null, null);
//	HideDestinations(objLink);
}


function SetMapImage(strImage) {
	var objMapIMG = document.getElementById('map');
	
	if (objMapIMG) objMapIMG.src = strImage;
}

var intMapCurrentX, intMapCurrentY;

function CurrentPosition(e) {
	intMapCurrentX = e.clientX;
	intMapCurrentY = e.clientY;

	var objMap = document.getElementById('map');
	intMapCurrentX -= findPosX(objMap);
	intMapCurrentY -= findPosY(objMap);

	window.status = 'X: ' + intMapCurrentX + ', Y: ' + intMapCurrentY;
}

/***************************************************
	Add popup functionality to A tags with class starting 'popup'
***************************************************/
function AddPopupBehaviour() {
	var aLinks = document.links;
	var objLink, re = /^.*(popup[^ ]+).*$/i;

	for (var i = 0; i < aLinks.length; i++) {
		objLink = aLinks[i];
		if (objLink.className != '' && re.test(objLink.className)) {
			objLink.target = objLink.className.replace(re, '$1');
			objLink.onclick = PopupClick;
		}
	}
}


/***************************************************
	Popup support functions
***************************************************/
function PopupClick() {
	var aClasses;
	aClasses = this.className.toString().split(' ');
	
	for (var i = 0; i < aClasses.length; i++) {
		switch(aClasses[i]) {
		case 'popupLogo':
			popupLogoInfo(aClasses[i]); break;
		default:
			return false;
		}
	}
}

function popup(url, title, width, height, scroll) {
	var s = 'menubar=no,toolbar=no,location=yes,resizable=yes,status=yes,dependent=yes'
	s += ',scrollbars=' + scroll
	s += ',width=' + width + ',height=' + height;
	s += ',top=' + (screen.availHeight - height) / 2 + ',left=' + (screen.availWidth - width) / 2;

	//close existing window
	try {
		if (navigator.newwindow && navigator.newwindow.close) navigator.newwindow.close();
	}
	catch(e) {}
	
	//save new window object in navigator object and activate
	navigator.newwindow = self.open(url, title, s);
	navigator.newwindow.focus();
	
	return false;
}

function popupLogoInfo(strTarget) {
	return popup('', strTarget, 600, 400, 'yes')
}

function CloseWindow() {
	window.close();
	navigator.newwindow = null;
	if (window.opener)
		if (!window.opener.closed)
			window.opener.focus();
}

function addPopupEvents() {
	document.onkeydown = KeyDown;
	
	if (window.self.location != window.top.location) {
		addEvent(window, 'load', HideCloseLinks);
	}
}

function HideCloseLinks() {
	var objCloseLink;
	objCloseLink = document.getElementById('close-top');
	if (objCloseLink) objCloseLink.style.display = 'none';
	objCloseLink = document.getElementById('close-bottom');
	if (objCloseLink) objCloseLink.style.display = 'none';
}

function KeyDown(e) {
	if (e && e.which == 27) CloseWindow(); //Netscape
	else if (event && event.keyCode == 27) CloseWindow(); //IE
}

function popupSTD(URL,winwidth,winheight)  {
	day = new Date();
	id = day.getTime();
	pleft=(screen.width-winwidth)/2;
	ptop=(screen.height-winheight)/2;
	eval("page" + id + " = window.open('"+URL+"', '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=1,width="+winwidth+",height="+winheight+",left="+pleft+",top="+ptop+"');");
	}

