


// ***************************** SHOPPINGCART.JSP ***************************** //
	
	function deleteItem(id) {
		if (confirm('Are you sure you want to delete this flight?')) {
			submitAjaxFromQuery("deleteAirItem",deleteReturn,"POST","item_pk="+id,"Deleting flight" );
		}
    }
	
	function deleteReturn(returnJSONTxt) {
		var json = eval("new Object(" + returnJSONTxt + ")");
		if ( json.errors ) {
			alert(json.errors);
		}
		if ( defined(json.returnView) ) {
			goToURL( views[json.returnView] );
		}
		else {
			var id = "cartItem-" + json.returnMsg.replace("Deleted air item: ","");
			hideElement(id);
			window.scrollTo(0,0);
		}
	}
	
	var views = new Object();
	views["homePage"] = "/";
	views["cart"] = "/shoppingcart/";
	views["results"] = "/fly/airsearchResults.jsp";
	views["flyPage"] = "/";  // fly page is the home page since the grid redesign
	views["searchError"] = "/?err=true";
	views["airsearchWait"] = "/includes/airsearchWait.jsp";
	views["myAccount"] = "/register/update";
	
	function focusOnPhone() {
		if ( getJoinForm().passengerPhone.value == '') {
			getJoinForm().passengerPhone.focus();
		}
	}
	
	function setCheckedValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
		else {
			radioObj[i].checked = false;
		}
	}
}

	function matchSelectBoxValue(selObj1,selObj2) {
		var selIndex = selObj1.options[selObj1.selectedIndex].value;
		selObj2.length=0;
		for ( var i=0 ; i < selObj1.options.length ; i++ ) {
			selObj2.length++;
			newOption=new Option( selObj1.options[i].text );
			newOption.value= selObj1.options[i].value;
			if ( selIndex == newOption.value ) newOption.selected=true;
			selObj2.options[i]=newOption;
		}
		
	}

    
    function check_onClick(checkbox) {
		thisForm=checkbox.form;
		var countryName = thisForm.billcountry.options[thisForm.billcountry.selectedIndex].value;
		
		if ( checkbox.checked && ( countryName == "United States" || countryName == "Canada")  ) {
			thisForm.shipname.value=thisForm.nameoncard.value;
			thisForm.shipaddress1.value=thisForm.billaddress1.value;
        	thisForm.shipaddress2.value=thisForm.billaddress2.value;
        	thisForm.shipcity.value=thisForm.billcity.value;
			matchSelectBoxValue(thisForm.billstate,thisForm.shipstate);
			setCheckedValue(thisForm.shipcountry,countryName);
        	thisForm.shippostalcode.value=thisForm.billpostalcode.value;
			if ( thisForm.name == "requestToPayForm" ) {
				thisForm.shipphone.value=thisForm.billphone.value;
			}
			else {
				thisForm.shipphone.value=thisForm.billingPhone.value;
			}
		}
		
		else { //not checked - clear shipping info
			if ( checkbox.checked ) {
				alert("Shipping address must be in the United States or Canada");
				checkbox.checked = false;
			}	
			else {
				setCheckedValue(thisForm.shipcountry,"United States");
			}
			
			
			thisForm.shipname.value='';
			thisForm.shipaddress1.value='';
        	thisForm.shipaddress2.value='';
        	thisForm.shipcity.value='';
        	thisForm.shipstate.value='';
        	thisForm.shippostalcode.value='';
			thisForm.shipphone.value='';
		}
		
	}
	

	function group_check_same_as_billing(checkbox) {
		thisForm = checkbox.form;
		 		
		if ( checkbox.checked ) {
			thisForm.shipname.value = thisForm.nameoncard.value;
			thisForm.shipaddress1.value = thisForm.billaddress1.value;
        		thisForm.shipaddress2.value = thisForm.billaddress2.value;
        		thisForm.shipcity.value = thisForm.billcity.value;
        		thisForm.shipstate.value = thisForm.billstate.value;
        		thisForm.shipcountry.value = thisForm.billcountry.value;
        		thisForm.shippostalcode.value = thisForm.billpostalcode.value;
        		thisForm.shipphone.value = thisForm.billphone.value;
		}
		
		else { //not checked - clear shipping info
			thisForm.shipname.value = '';
			thisForm.shipaddress1.value = '';
        		thisForm.shipaddress2.value = '';
        		thisForm.shipcity.value = '';
        		thisForm.shipstate.value = '';
        		thisForm.shipcountry.value = '';
        		thisForm.shippostalcode.value = '';
			thisForm.shipphone.value = '';
		}
		
	}
	
    
	function finalizeOrder() {
		if ( get("agreeToTerms").checked ) {
			goToURL("/shoppingcart/finalizeWait");
		}
		else {
			alert('You must check the box above the Finalize Order button, agreeing to the Fare Rules & Terms of Use');
		}
	}
	
	function showFinalizeTimeoutWarning() {
	    alert('We\'re sorry, we could not get confirmation for your flight from the airline, so you have not yet purchased a ticket for this flight.  Please contact us at 800-272-9676 (outside the U.S. 617-321-3100) to book this flight.  Our agents are available 9AM-9PM Monday-Friday, 11AM-6PM Saturday-Sunday, ET.');
	}
	
	function showOptions(query){
    document.airOptionsForm.deal.value=query;
    document.airOptionsForm.submit();
}
	
	function selectOption(query, outindex, inindex){
    document.airOptionsForm.deal.value=query;
    document.airOptionsForm.inboundOption.value=inindex;
    document.airOptionsForm.outboundOption.value=outindex;
    document.airOptionsForm.submit();
}

function buyNow(uuid) {
	showWaitMsg("Adding flight to cart");
    url="/nospring/ajax/addToCart?outboundIndex=0&inboundIndex=0&itinUUID="+uuid;
	xmlBasicRequest(url,addedToCart);
}

function replaceItinerary(itinUUID) {
	updatedItinID="itinerary-"+itinUUID;
	if ( get("thisItineraryHTML") ) {
		get(updatedItinID).innerHTML=get("thisItineraryHTML").innerHTML;
		layoutPage();
	}
}

function join(signUpStartForm) {
	userType=getCheckedValue(signUpStartForm.userType);
	if(userType=="" && get("userTypeId").value != null){
		userType=get("userTypeId").value;
	}
	url="/register/new?userType="+userType;
	goToURL(url);
}

function addedToCart(returnMsg) {
	if ( returnMsg.indexOf("error") >= 0 ) {
		goToURL("/airItemCartError.html");
	}
	else if ( returnMsg == "login" ) goToURL("/register");
	else goToURL("/shoppingcart");
	//else hideWaitMsg();
}

function submitAjaxForm(formObj) {
	params=getParams(formObj);
	url=formObj.action+params;
	returnFunction=eval(formObj.target);
	xmlBasicRequest(url,returnFunction,formObj.method,false);
}

function updateProfileReturn(returnMsg) {
	if ( returnMsg.indexOf("success") >= 0 ) replaceURL("/");
	else showErrors("errorTop",returnMsg,true);
}

function showErrors(errorClass,errorReturnMsg,showPrompt) {
	currentErrors=getElementsByClassName(document,'*',errorClass);
	for ( var i=0 ; i < currentErrors.length ; i++ ) {
		currentErrors[i].style.display="none";
	}
	errors=errorReturnMsg.split("\n");
	for ( var i=0 ; i < errors.length ; i++ ) {
		thisError=errors[i];
		if ( thisError.indexOf(":") >= 0 ) {
			firstColon=thisError.indexOf(":");
			errorField=thisError.substring(0,firstColon);
			errorMsg=thisError.substring(firstColon+1);
			//errorMsg=thisError.split(":")[1];
			errorDiv="errorField-"+errorField;
			if ( get(errorDiv) ) {
				get(errorDiv).innerHTML=errorMsg;
				get(errorDiv).style.display='block';
			}
		}
	}
	layoutPage();
	scroll(0,0);
	if ( showPrompt ) {
		showElement("error-message");
	}
}

function hideErrors(errorClass) {
	currentErrors=getElementsByClassName(document,'*',errorClass);
	for ( var i=0 ; i < currentErrors.length ; i++ ) {
		currentErrors[i].style.display="none";
	}
}

function billShipReturn(returnMsg) {
	if ( returnMsg.indexOf("success") >= 0 ) goToURL("/shoppingcart/reviewOrder");
	else if ( returnMsg.indexOf("error:null invoice id") == 0 ) {
		goToURL("/cart/expired.jsp");
	}
	else {
		if (returnMsg.indexOf("cardnumber:") < 0 && get("cardnumber").value.length == 0 ) 
			returnMsg += "cardnumber:Please re-enter your credit card number.\n";
		showErrors("errorTop",returnMsg,true);
		get("error-message").innerHTML="Please correct the errors found below";
		get("error-message").style.margin="0 0 0 200px";
		get("error-message").style.display="block";
	}
}

function chooseProgram(destContentName,programIndex) {
	document.requestToPayChooser.destContentName.value=destContentName;
	document.requestToPayChooser.programIndex.value=programIndex;
	document.requestToPayChooser.submit();
}

function buyAirItem(airItemID){
    var returnFunction=function(returnMsg) {
		if ( returnMsg.indexOf("redirect") == 0 ) {
			var bookingURL = returnMsg.substring(9);
			get("orbitzURL").value = bookingURL;
			get("redirectToOrbitzForm").submit();
		}
		else if ( returnMsg == "eticket" || returnMsg == "billship" ) goToURL("/shoppingcart/billShip");
		else if ( returnMsg == "error" ) goToURL("/shoppingcart/AirItemCartError.jsp");
	}
	var query="airItemID="+airItemID;
	submitAjaxFromQuery("buyAirItem",returnFunction,"POST",query,"Proceeding to checkout");
}

function setSessionData(name,value) {
	url="/nospring/ajax/setSessionData?name="+name+"&value="+value;
	xmlBasicRequest(url,nullFunction);
}

function nullFunction(returnMsg) {}

function getParams(obj) {
      //var getstr="?";
      var getstr="";
      
	  for (var i=0; i < obj.getElementsByTagName("input").length ; i++) {
			inputObj=obj.getElementsByTagName("input")[i];
			if (inputObj.type == "text" || inputObj.type == "hidden" || inputObj.type == "password" ) {
               getstr += inputObj.name+"="+inputObj.value+"&";
            }
            if (inputObj.type == "checkbox") {
               if (inputObj.checked) {
                  getstr += inputObj.name+"="+inputObj.value+"&";
               }
            }
            if (inputObj.type == "radio") {
               if (inputObj.checked) {
                  getstr += inputObj.name+"="+inputObj.value+"&";
               }
            }
	  }
	  for (var i=0; i < obj.getElementsByTagName("select").length ; i++) {
			var sel=obj.getElementsByTagName("select")[i];
			if ( sel.options.length > 0 ) {
				getstr += sel.name+"="+sel.options[sel.selectedIndex].value+"&";
			}  
	  }
      return getstr;
   }

function focusOnField() {
	if (document.form1.email.value == '') 
		document.form1.email.focus();
	else if (document.form1.firstname.value == '') 
		document.form1.firstname.focus();
	else if (document.form1.lastname.value == '') 
		document.form1.lastname.focus();
	else if (document.form1.universityLocationID.value == '') 				
		document.form1.universityLocationID.focus();
	else if (document.form1.universityCountryID.value == '') 			
		document.form1.universityCountryID.focus();		
	else if (document.form1.universityID.value == '') 				
		document.form1.universityID.focus();
}

function monitorFields() {
	if (document.form1 != null && document.form1.universityLocationID != null && document.form1.universityLocationID.options != null && document.form1.universityLocationID.options.length > 1 
	 && document.form1.universityLocationID.selectedIndex == 0
	 && document.form1.universityID.options[document.form1.universityID.options.selectedIndex].value == '-1') {
    	resetUniv();
	}
}

// ***************************** GENERAL UTILITIES ***************************** //

// this defines which url patterns should be sent to a secure page - all others, forced to insecure
var securePages=new Array("/shoppingcart/","/register","/study/requestToPay","confirmJoin.html","/membership/updatePassword");

// THIS TAKES A RELATIVE URI and determines its correct scheme, returning the correct full url with updated scheme, host, and uri
function fullPathToMe(uri) {
	var correctHost=insecureHost;
	var securePage=false;
	for ( var i=0 ; i < securePages.length; i++ ) {
		if ( uri.indexOf(securePages[i]) >= 0 ) {
			correctHost=secureHost;
			securePage=true;
			break;
		}
	}
	fullPath=correctHost+uri;
	if ( securePage && secureHost.indexOf("https") != 0 && fullPath.indexOf("#secure") < 0 ) {
		fullPath += "#secure";
	}
	return fullPath;
}

function getFullPathCurrentScheme(url) {
	if ( window.location.href.indexOf(secureHost) == 0 ) hostToUse=secureHost;
	else hostToUse=insecureHost;
	var uri=getURI(url);
	return hostToUse+uri;
}

function getURI(url) {
	if ( url.indexOf("http") == 0 ) return url.substring(url.indexOf("/",8));
	else return url;
}

// THIS TAKES A FULLY QUALIFIED URL (from link href) and determines its correct scheme, returning the correct full url with updated scheme
function resolveScheme(url) {
	// abort if this isn't a regular url ("javascript:" or something)
	if ( url.indexOf("http") != 0 ) return url; 
	// abort if this url isn't on the current domain (external link)
	else if ( url.indexOf(insecureHost) != 0 && url.indexOf(secureHost) != 0 ) return url;
	var uri=getURI(url);
	return fullPathToMe(uri);
}

function goToURL(uri) {
	window.location.href=fullPathToMe(uri);
}

function replaceURL(uri) {
	window.location.replace( fullPathToMe(uri) );
}

function getElementsByTagName(tagName) {
	elementList=document.getElementsByTagName(tagName);
	elementArray=new Array();
	for ( var i=0 ; i < elementList.length ; i++ ) {
		elementArray.push(elementList[i]);
	}
	return elementArray;
}

function switchStyles(selector) {
	url=window.location.href;
	if ( url.indexOf('?stylesheet=') > 0 ) {
		url=url.substring(0,url.indexOf('?stylesheet='));
		url += '?stylesheet='+ selector.options[selector.selectedIndex].value;
	}
	else if ( url.indexOf('?') > 0 ) {
		url += '&stylesheet='+ selector.options[selector.selectedIndex].value;
	}
	else {
		url += '?stylesheet='+ selector.options[selector.selectedIndex].value;
	}
	window.location=url;
}

function classMatches(element,classToMatch) {
	if ( element.className && 
		 element.className == classToMatch ||
		 element.className.indexOf(" "+classToMatch) >= 0 ||
		 element.className.indexOf(classToMatch+" ") >= 0 ) {
		return true 
	}
	else return false;
}

function prepopGatewayPageSearch(inboundAPCode) {
	switchToRoundTrip();
	SearchForm.setInboundAirport(inboundAPCode);
	get("inboundAirport").value = inboundAPCode;
}

function lookupCodes(anchorTag) {
	now=new Date();
	dataURL=anchorTag.href+"&time="+now.getTime();
	xmlBasicRequest(dataURL,showCodes);
}

function showCodes(htmlResponse) {
	get("codesArea").innerHTML=htmlResponse;
}

var debugTimerStartTime;

function timerStart() {
	debugTimerStartTime=new Date();
}

function timerEnd() {
	endTime=new Date();
	totalTime=endTime.getTime() - debugTimerStartTime.getTime();
	window.status=totalTime;
}

function removeElement(element) {
	element.parentNode.removeChild(element);
}

function cleanUpForIE() {
	if ( isIE() ) {
		var sliders=getElementsByClassName(document,'IMG',"slider");
		for ( var i = 0 ; i < sliders.length ; i++ ) {
			sliders[i].sliderObj = null;
		}
	}
}

function trackEchoTarget(inboundAirport) {
	var echoIframe = get("echoTargetIframe");
	if ( echoIframe ) {
		var echoURL = "http://pbid.pro-market.net/engine?site=sud" + inboundAirport + "+size=1x1";
		echoIframe.src = echoURL;
	}
}

function convertToInteger(string) {
	return parseInt(string,10);
}

function compareToSite(website,index,method) {
	var compareURL = "/fly/compareSearch.jsp?website=" + website +"&method=" + method;
	var windowLabel = "Search_" + website;
	
	if ( index != -1 ) {
		windowLabel = "Search" + index;
	}
	else {
		index = 0;
	}
	var width = Math.floor(screen.width * 0.5 );
	var height = Math.floor(screen.height * 0.5 );
	var left = (screen.width - width - 180 ) + ( index * 50);
	var top = index * 50;
	var options = "width="+width+",height="+height+",left="+left+",top="+top+",screenX="+left+",screenY="+top+",resizable,scrollbars,location,directories,status,titlebars,menubar";
	var thisPopup = window.open(compareURL,windowLabel,options);
}

function compareTo(website) {
	if ( website != "null" ) {
		compareToSite(website, -1, 'link');
		return;
	}
	var num_checked = 0; // number of checked
	if ( get("compareToOrbitz").checked){
		num_checked ++;
	}
	if ( get("compareToCheaptickets").checked){
		num_checked ++;
	}
	if ( get("compareToKayak").checked){
		num_checked ++;
	}
	if ( get("compareToMobissimo").checked){
		num_checked ++;
	}
	//creat the array
	var random_num = new Array(num_checked+1);
	var compare_arr = new Array(num_checked);
	num_checked = 0;
	if ( get("compareToOrbitz").checked){
		compare_arr[num_checked] = 'ORBITZ';
		num_checked ++;
	}
	if ( get("compareToCheaptickets").checked){
		compare_arr[num_checked] = 'CHEAPTIX';
		num_checked ++;
	}
	if ( get("compareToKayak").checked){
		compare_arr[num_checked] = 'KAYAK';
		num_checked ++;
	}
	if ( get("compareToMobissimo").checked){
		compare_arr[num_checked] = 'MOBISSIMO';
		num_checked ++;
	}
	for (i = 1; i < num_checked+1; i++) {
		random_num[i] = i;
	}
	//Shuffling the numbers in the array
	for (i = 1; i < num_checked+1; i++) {
		newnumber = (Math.random() * num_checked) + 1;
		newnumber = parseInt(newnumber, 10);
		temp = random_num[i];
		random_num[i] = random_num[newnumber];
		random_num[newnumber] = temp;
	}
	
	if(num_checked == 0){
		alert("You must select at least one site to compare results with.");
	}else{
		for (i = 1; i < num_checked+1; i++) {
			setTimeout("compareToSite('"+compare_arr[random_num[i]-1]+"',"+(i-1)+",'button')",0);
		}
	}

}
			
function upd_shortcn_img(img_src){
	if(img_src == 1){
	
		get("shortChinesePopupImg").src ="http://images.studentuniverse.com/zh_CN/images/buttons/shortchinese_blue.jpg";
	}else{
	
		get("shortChinesePopupImg").src ="http://images.studentuniverse.com/zh_CN/images/buttons/shortchinese_black.jpg";	
	}


}			



// ***************************** init functions ***************************** //

onLoad = function() { this.funcStack = new Array(); this.tasksRan = false; }

onLoad.prototype = {
    funcStack: null,
	tasksRan: null,
	
	add: function(funcObj) {
        this.funcStack.push(funcObj);
    },
	
	unshift: function(funcObj) {
        this.funcStack.unshift(funcObj);
    },
	
	run: function() {
		if ( !this.tasksRan ) {
			for ( var i = 0 ; i < this.funcStack.length ; i++ ) {
				thisFunc = this.funcStack[i];
				if (undefined != thisFunc) thisFunc();
			}
			this.tasksRan = true;
		}
	}
	
}

windowLoadTasks = new onLoad();
windowLoadTasks.add(layoutPage);
windowLoadTasks.add(initTextPrompts);
windowLoadTasks.add(sessionTimer);


var aryClassElements = new Array();
function getLoopElementsByClassName( strClassName, objBody ) {
    if ( objBody.className == strClassName ) {
        aryClassElements[aryClassElements.length] = objBody;
    }
    for ( var i = 0; i < objBody.childNodes.length; i++ )
        getLoopElementsByClassName( strClassName, objBody.childNodes[i] );
}

function initTextPrompts() {
	setTextPrompt("outboundAirport",""," City name or code");
	setTextPrompt("inboundAirport",""," City name or code");
	setTextPrompt("outboundJawAirport",""," City name or code");
	setTextPrompt("inboundJawAirport",""," City name or code");
	setTextPrompt("email",""," Enter your email");
	
	setTextPrompt("groupEmail",""," For Confirmation");
	getLoopElementsByClassName( 'groupFirstName', document.body );
	promptVal = " First";
    for ( var i = 0; i < aryClassElements.length; i++ ) {
        if ( aryClassElements[i].value == "" )  aryClassElements[i].value = promptVal;
    }
    getLoopElementsByClassName( 'groupMiddleName', document.body );
    promptVal = " Middle (optional)";
    for ( var i = 0; i < aryClassElements.length; i++ ) {
        if ( aryClassElements[i].value == "" )  aryClassElements[i].value = promptVal;
    }
    getLoopElementsByClassName( 'groupLastName', document.body );
    promptVal = " Last";
    for ( var i = 0; i < aryClassElements.length; i++ ) {
        if ( aryClassElements[i].value == "" )  aryClassElements[i].value = promptVal;
    }
    
}

function needTimeout() {
	var uri = getURI(window.location.href);
	if ( (loggedIn || hasResults) && (uri.indexOf("/shoppingcart/printitinerary") != 0) && (uri.indexOf("/shoppingcart/final") != 0) ) {
		return true;
	}
	else return false;
}

var checkSessionTimer;
var warningShown = false;

function sessionTimer() {
	if ( needTimeout() ) checkSessionTimer = setTimeout("checkSession()",sessionWarningPeriod);
}

function checkSession() {
	submitAjax("sessionTimer",reactToSessionTimeLeft,null,null,null);
}

function reactToSessionTimeLeft(thisData) {
	if ( thisData == "expired" ) goToURL("/sessionExpired.html");
	else sessionTimer();
}

function getNowDate() {
	return new Date();
}

function unitSpec(number,singularTxt,pluralTxt) {
	if ( number == 1 ) return singularTxt;
	else return pluralTxt;
}

function keepAlive() {
	if ( needTimeout() ) {
		submitAjax("keepAlive",reactToSessionTimeLeft,null,null,null);
	}
}

function setTextPrompt(inputObjID,emptyVal,promptVal) {
	inputObj = get(inputObjID);
	
	// this semi-hack prevents setting prompt for non-newsletter fields labeled "email"
	if ( inputObjID == "email" && inputObj && inputObj.form.id != "newsletter" ) return;
	
	if ( inputObj && inputObj.type == "text" ) {
		if ( inputObj.value == emptyVal ) inputObj.value = promptVal;
		else if ( inputObj.id.indexOf("Airport") >= 0 &&  inputObj.value.length == 3 ) {
			//var varID = inputObj.id + "";
			//get(varID).value = inputObj.value;
		}
	}
}

function initUniversityDropdowns() {
	var selectTags = getElementsByTagName("select");
	if ( selectTags && selectTags.length > 0 ) {
		for ( i = 0 ; i < selectTags.length ; i++ ) {
			thisSelectTag = selectTags[i];
			if ( thisSelectTag.id == "universityCountryID" ) {
				thisSelectTag.onchange = function() { loadStates(this) };
			}
			else if ( thisSelectTag.id == "universityLocationID" ) {
				thisSelectTag.onchange = function() { loadUnivs(this) };
			}
			else if ( thisSelectTag.id == "dobMonth" ) {
				thisSelectTag.onchange = function() { loadDays(this) };
			}
		}
	}
}


/* Script by GalaSoft Laurent Bugnion */
/* 27.01.2001                         */
/* www.galasoft-LB.ch                 */

var cookiePath = '/';

// Cookie functions ---------------------------------------------------------
// Thanx a lot to Jerry Aman, Optima System
// and Bill Dortch, hIdaho Design for the free use of their code.
// Found on http://www.cookiecentral.com/js_cookie8.htm

//---------------------------------------------------------------------------
// Utility function to get the cookie's value

function getCookieVal( offset )
{
  var endstr = document.cookie.indexOf ( ";", offset );

  if ( endstr == -1 )
  {
    endstr = document.cookie.length;
  }
  return unescape( document.cookie.substring( offset, endstr ) );
}

//---------------------------------------------------------------------------
// Returns the value of a cookie corresponding to the name
// Returns null if the cookie can't be found

function getCookie( name )
{
  var arg = name + "=";
  var alen = arg.length;
  var clen = document.cookie.length;
  var i = 0;

  while ( i < clen )
  {
    var j = i + alen;

    if ( document.cookie.substring( i, j ) == arg )
    {
      return getCookieVal ( j );
    }

    i = document.cookie.indexOf( " ", i ) + 1;

    if ( i == 0 )
    {
      break;
    }
  }
  return null;
}

//---------------------------------------------------------------------------
// Sets a cookie according to the name and value.
// Optional parameters:
// - expires (Date object)
// - path (use cookiePath for the whole domain)
// - domain
// - secure
// For more information about those parameter, check www.cookiecentral.com

function setCookie( name, value )
{
  var argv = setCookie.arguments;
  var argc = setCookie.arguments.length;
  var expires = (argc > 2) ? argv[2] : null;
  var path = (argc > 3) ? argv[3] : null;
  var domain = (argc > 4) ? argv[4] : null;
  var secure = (argc > 5) ? argv[5] : false;

  document.cookie = name + "=" + escape (value) +
    ( ( expires == null ) ? "" : ( "; expires=" + expires.toGMTString() ) ) +
    ( ( path == null ) ? "" : ( "; path=" + path ) ) +
    ( ( domain == null ) ? "" : ( "; domain=" + domain ) ) +
    ( ( secure == true ) ? "; secure" : "" );
}

function deleteCookie ( name ) {
  var exp = new Date();
  exp.setTime ( exp.getTime() - 1 );  // This cookie is history
  setCookie( name,"",exp,cookiePath);
}


//---------------------------------------------------------------------------
// Tests if cookies are enabled.

function testCookie() {
  var expDate = new Date();
  expDate.setTime( expDate.getTime() + ( 60000 ) ); //valid one minute
  setCookie("testCookie","OK",expDate);
  testing = getCookie( "testCookie" );
  if ( testing == "OK" ) return true;
  else return false;
}

if ( !testCookie() ) {
	replaceURL("/cookiesRequired.html");
}

Event = function() {

}

Event = function(description,targetFunction,preventDefault) {
	this.targetFunction = targetFunction;
	this.description = description;
	this.preventDefault = preventDefault;
}

Event.prototype = {
	eventType: null,
	target:null,
	targetFunction: null,
	description: null,
	keypress:null,
	xMousePos:null,
	yMousePos:null,
	preventDefault:null,
	
	// this executes the function stored in the targetFunction field, passing the event object, and this Event object
	execute: function() {
		if ( this.targetFunction != null ) this.targetFunction.call(this,this);
		else alert("Target Function is null: " + this.targetFunction);
	},
	
	clone: function() {
		var newEvent = new Event();
		newEvent.eventType = this.eventType;
		newEvent.target = this.target;
		newEvent.targetFunction = this.targetFunction;
		newEvent.description = this.description;
		newEvent.keypress = this.keypress;
		newEvent.xMousePos = this.xMousePos;
		newEvent.yMousePos = this.yMousePos;
		newEvent.preventDefault = this.preventDefault;
		return newEvent;
	},
	
	toString: function() {
		return "<b>" + this.target.id + "</b>: " + this.description;
	}
}

EventTrigger = function(tagName,id,className,eventType,keypress) {
	this.tagName = tagName; // the tag type ( i.e. "A","INPUT","DIV","BODY","SELECT" )
	this.id = id; // the id of the element ( <div id="myDiv"> )
	this.className = className; // the class name given to the element ( <a class="popupLink"> )
	this.eventType = eventType; // the type of event ( i.e. "mouseover","click","focus","keypress" )
	this.keypress = keypress; // the key code that has to be pressed
}

EventTrigger.prototype = {
    tagName: null,
	id: null,
	className: null,
	eventType: null,
	keypress:null,
	
	matches: function(event) {
		
	}
}

