var timeoutStartTime;
var browserSpeed;

function browserSpeedTest(){
	var i = 0;
	timeoutStartTime = new Date().getTime();
	for(i; i < 100; i++){
		setTimeout("timeoutTestFunc(" + i + ")",1);
	}
}

function timeoutTestFunc(index){
	if(index == 99){
		browserSpeed = new Date().getTime() - timeoutStartTime;
	}
}

setTimeout("browserSpeedTest()", 2000);

function Trail(trail, name, shortname){
	this.trail = trail;
	this.name = name;
	this.shortname = shortname
}

function gotoUrl(url){
	document.location=url;
}

function replace(value, text, newValue){
	var pos = text.indexOf(value); 
	while(pos > -1){
		text = text.substring(0, pos) + newValue + text.substring(pos + value.length);
		pos = text.indexOf(value); 
	}
	return text;
}

// Deprecated
function getY(id){
	return getElementCoordinates(document.getElementById(id))["Y"];
}

function getElementY(elem){
	return getElementCoordinates(elem)["Y"];
}


// Deprecated
function isIE(){
	return navigator.appName.toLowerCase().indexOf("explorer") > -1;
}

function isIE8(){
	return navigator.appVersion.toLowerCase().indexOf("msie 8") > -1;
}

function getX(id){
	return getElementCoordinates(document.getElementById(id))["X"];
}

function addtofav(){
    if (navigator.appName.toLowerCase().indexOf("explorer")){
        window.external.AddFavorite(document.location, document.title);
    }else{
        alert("Sorry. This function only works with IE4 or higher. Netscape/Firefox users can bookmark this page manually by hitting <Ctrl-D>, Opera users please use <CTRL-ALT-B>.");
    }
}

function stripPX(value, defaultValue){
	if(value == "" || value == null){
		return defaultValue||0;
	}else{
		value = parseInt(value.substring(0, value.length-2));
	}
	return value;
}


function prepareLayerForm(width, height){
	//alert(document.body.clientHeight + " " + document.documentElement.clientHeight + " " + window.innerHeight + " " + document.body.scrollHeight);
	var transparentLayer = document.getElementById("transparentLayer");
	if(transparentLayer.style.display != ""){
		var documentHeight = getDocumentHeight();
		transparentLayer.innerHTML = "<table id=transparentTable width=\"100%\" bgcolor=\"#000000\" style=\"filter:alpha(opacity='75');-moz-opacity:0.75;opacity:0.75;height:" + documentHeight + "px\"><tr><td></td></tr></table>";
		transparentLayer.style.display="";
	}
	var formLayer = document.getElementById("formLayer");
	formLayer.style.width=width + "px";
	formLayer.style.height= height + "px";
	formLayer.style.top = (getWindowHeight()/2 - height/2) + "px";
	formLayer.style.left = (getWindowWidth()/2 - width/2) + "px";
	formLayer.style.display = "";
	return formLayer;
}

function hideLayers(){
	document.getElementById("transparentLayer").style.display = "none";
	document.getElementById("formLayer").style.display = "none";
	document.getElementById("formLayer").innerHTML = "&nbsp;"
}

function loadHtmlDoc(url, async, func, request){
	if(async){
		request.onreadystatechange = func;
		request.open('POST', url, true);
		request.send("");
		return;
	}
	var syncRequest = GXmlHttp.create();
	syncRequest.open('POST', url, false);
	syncRequest.send("");
	//request.send(null);
	return syncRequest.responseText;
}

function encodeURL(sStr) {
    return escape(sStr).
             replace(/\+/g, '%2B').
             replace(/\"/g,'%22').
             replace(/\'/g, '%27').
             replace(/\//g,'%2F');
}

function httpRequest(url, async, func, request){
	if(async){
		request.onreadystatechange = func;
		request.open('POST', url, true);
		request.send("");
		return;
	}
	var syncRequest = createXmlHttpRequest();
	syncRequest.open('POST', url, false);
	syncRequest.send("");
	return syncRequest.responseText;
}

function createXmlHttpRequest(){
	req = false;
    // branch for native XMLHttpRequest object
    if(window.XMLHttpRequest) {
    	try {
			req = new XMLHttpRequest();
        } catch(e) {
			req = false;
        }
    // branch for IE/Windows ActiveX version
    } else if(window.ActiveXObject) {
       	try {
        	req = new ActiveXObject("Msxml2.XMLHTTP");
      	} catch(e) {
        	try {
          		req = new ActiveXObject("Microsoft.XMLHTTP");
        	} catch(e) {
          		req = false;
        	}
		}
    }
	return req;
}

function trim(str){
   return str.replace(/^\s*|\s*$/g,"");
}

function arrayContains(list, value){
	var i = 0;
	for(i = 0; i < list.length; i++){
		if(list[i] == value){
			return true;
		}
	}
	return false;
}


function getPageHeight(){
	var yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		yScroll = document.body.scrollHeight;
	} else if (document.documentElement && document.documentElement.scrollHeight > document.documentElement.offsetHeight){ // Explorer 6 strict mode
		yScroll = document.documentElement.scrollHeight;
	} else { // Explorer Mac...would also work in Mozilla and Safari
		yScroll = document.body.offsetHeight;
	}

	var windowHeight;
	if (self.innerHeight) { // all except Explorer
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	var pageHeight = 0;
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}
	return pageHeight;
}

function getDocumentHeight(){
	if(navigator.appName.toLowerCase().indexOf("explorer") > -1){
		return document.body.scrollHeight;
	}else{
		//return document.body.clientHeight;
		return document.body.scrollHeight;
	}
}

function getDocumentWidth(){
	if(navigator.appName.toLowerCase().indexOf("explorer") > -1){
		return document.body.scrollWidth;
	}else{
		//return document.body.clientHeight;
		return document.body.scrollWidth;
	}
}

function getWindowHeight() {
	if(navigator.appName.toLowerCase().indexOf("explorer") > -1){
		return document.body.clientHeight;
	}
	if (window.self && self.innerHeight) {
		return self.innerHeight;
	}
	if (document.documentElement && document.documentElement.clientHeight) {
		return document.documentElement.clientHeight;
	}
	return 0;
}

function getWindowWidth() {
	if(navigator.appName.toLowerCase().indexOf("explorer") > -1){
		return document.body.clientWidth;
	}
	if (window.self && self.innerWidth) {
		return self.innerWidth;
	}
	if (document.documentElement && document.documentElement.clientWidth) {
		return document.documentElement.clientWidth;
	}
	return 0;
}


// --------------------------------------------------------------------------------
// returns height of inner window

function getViewportHeight() {
	// standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
	if (window.innerHeight!=window.undefined) return window.innerHeight;
	// IE6 in standards compliant mode
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientHeight;
	// IE older versions
	if (document.body) return document.body.clientHeight;

	return window.undefined;
}

// ---------------------------------------------------------------------------------

// returns width of inner window

function getViewportWidth() {
	// standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
	if (window.innerWidth!=window.undefined) return window.innerWidth;
	// IE6 in standards compliant mode
	if (document.compatMode=='CSS1Compat') return document.documentElement.clientWidth;
	// older versions of IE
	if (document.body) return document.body.clientWidth;

	return window.undefined;
}


//-------------------------------------------------------------------------------------------------------
// MODAL DIALOG

var stMask = null;
var stContainer = null;
var stIsShown = false;
var stHideSelects = false;

function getScrollTop() {
	if (self.pageYOffset) {return self.pageYOffset} // non IE browsers
	else if (document.documentElement && document.documentElement.scrollTop) {return document.documentElement.scrollTop} // IE 6 Strict
	else if (document.body) {return document.body.scrollTop} // all other IEs
}

function getScrollLeft() {
	if (self.pageXOffset) {return self.pageXOffset} // non IE browsers
	else if (document.documentElement && document.documentElement.scrollLeft) {return document.documentElement.scrollLeft} // IE 6 Strict
	else if (document.body) {return document.body.scrollLeft} // all other IEs
}

function addEvent(obj,evType,fn){
	if (obj.addEventListener){obj.addEventListener(evType, fn, false); return true}
	else if (obj.attachEvent){var r = obj.attachEvent('on'+evType, fn); return r}
	else {return false}
}


function alertDialog(width, height, txt, title){
	createModalDialog();
	var html = "<div style=width:" + width + "px;height:" + height + "px;position:relative;background-color:#ffffff>"+ 
		"<div style='position:absolute;bottom:0px;left:0px;'><img src=images/modalDiagbottomleftcorner.png></div>" + 
		"<div style='position:absolute;bottom:0px;right:0px;'><img src=images/modalDiagbottomrightcorner.png></div>" +
		"<div style='position:absolute;top:0px;left:0px;'><img src=images/modalDiagtopleftcorner.png></div>" +
		"<div style='position:absolute;top:0px;right:0px;'><img src=images/modalDiagtoprightcorner.png></div>" +
		"<div style='position:absolute;top:0px;left:9px;width:" + (width-18) + "px;height:" + height + "px;background-color:#000000; filter:alpha(opacity=50);-moz-opacity:0.50;opacity:0.50;'></div>" + 
		"<div style='position:absolute;top:9px;left:0px;width:9px;height:" + (height-18) + "px;background-color:#000000; filter:alpha(opacity=50);-moz-opacity:0.50;opacity:0.50;'></div>" +
		"<div style='position:absolute;top:9px;right:0px;width:9px;height:" + (height-18) + "px;background-color:#000000; filter:alpha(opacity=50);-moz-opacity:0.50;opacity:0.50;'></div>" +
		"<div style='position:absolute;top:12px;left:12px;width:" + (width-24) + "px;height:" + (height-24) + "px;'>hello</div>" + 
		"</div>";
	displayModalDialog(width, height, html);
}

function createModalDialog(styleName, keepOpenWithOutsideClick) {
	hideModalDialog();
	if(stMask == null){
		theBody = document.getElementsByTagName('BODY')[0];
		theMask = document.createElement('div');
		var maskId = 'modalMask';
		if(styleName){
			maskId = styleName + '_' + maskId;
		}
		theMask.id = maskId;
		theContent = document.createElement('div');
		theContent.id = "modalContainer";
		theContent.innerHTML = '<div id="modalDialogBody"></div>';
		theBody.appendChild(theMask);
		theBody.appendChild(theContent);
	
		stMask = document.getElementById(maskId);
		stContainer = document.getElementById("modalContainer");
		stContainer.fixedYCoordinate = "";
		
		if(!keepOpenWithOutsideClick){
			stMask.onclick = hideModalDialog;
		}
	
		// check to see if this is IE version 6 or lower. hide select boxes if so
		//var brsVersion = parseInt(window.navigator.appVersion.charAt(0), 10);
		//if (brsVersion <= 6 && window.navigator.userAgent.indexOf('MSIE') > -1) {
		//	stHideSelects = true;
		//}
	}
}

function displayModalDialog(width,height,dialogMessage, fixedYCoordinate) {
	stIsShown = true;

	var modalDialogBody = document.getElementById('modalDialogBody');
	modalDialogBody.innerHTML = dialogMessage;

	stMask.style.display = 'block';
	stContainer.style.display = 'block';
	if(fixedYCoordinate){
		stContainer.fixedYCoordinate = fixedYCoordinate;
	}
	correctPNG("hoverbackground");

	// place window on screen : coordinates
	centerModalDialog(width,height);
	stContainer.style.width = width + 'px';
	stContainer.style.height = height + 'px';
	setMaskSize();

	// hide all SELECT boxes : IE 6 z-index bug
	hideAllSelects();
}

function centerModalDialog(width,height) {
	if (stIsShown == true) {
		if (width == null || isNaN(width)) {
			width = stContainer.offsetWidth;
		}
		if (height == null) {
			height = stContainer.offsetHeight;
		}

		var theBody = document.getElementsByTagName('BODY')[0];
		var scTop = parseInt(getScrollTop(),10);
		var scLeft = parseInt(theBody.scrollLeft,10);

		setMaskSize();

		var fullHeight = getViewportHeight();
		var fullWidth = getViewportWidth();


		if(stContainer.fixedYCoordinate != ""){
			stContainer.style.top = stContainer.fixedYCoordinate + 'px';
		}else{
			stContainer.style.top = (scTop + ((fullHeight - height) / 2)) + 'px';
		}
		
		stContainer.style.left = (scLeft + ((fullWidth - width) / 2)) + 'px';
	}
}

addEvent(window,'resize',centerModalDialog);
addEvent(window,'scroll',centerModalDialog);

// set modal dialog mask size
function setMaskSize() {
	var theBody = document.getElementsByTagName('BODY')[0];

	var fullHeight = getViewportHeight();
	var fullWidth = getViewportWidth();

	// determine what's bigger, scrollHeight or fullHeight / width
	if (fullHeight > theBody.scrollHeight) {popHeight = fullHeight}
	else {popHeight = theBody.scrollHeight}

	if (fullWidth > theBody.scrollWidth) {popWidth = fullWidth}
	else {popWidth = theBody.scrollWidth}

	stMask.style.height = popHeight + 'px';
	if (!window.attachEvent){stMask.style.height = (popHeight+16) + 'px';} // correct for scroll bars (FF)
	stMask.style.width = popWidth + 'px';
	if (!window.attachEvent){stMask.style.width = (popWidth-18) + 'px';} // correct for scroll bars (FF)
}

function hideModalDialog() {
	stIsShown = false;
	var theBody = document.getElementsByTagName('BODY')[0];
	theBody.style.overflow = '';
	if (stMask == null) {return}
	stMask.style.display = 'none';
	stContainer.style.display = 'none';
	stContainer.fixedYCoordinate = "";
	stMask.style.innerHTML = "";
	if (document.getElementById("mediaPanel")) {
		document.getElementById("mediaPanel").innerHTML = "";
	}
	
	// Close all calendars
	f_tcalHideAll();

	// display all SELECT boxes : IE 6 z-index bug
	showAllSelects();
	theBody.removeChild(stMask);
	stMask = null;
}

/* hide all SELECT boxes : IE 6 z-index bug */
function hideAllSelects() {
	var targets = document.getElementsByTagName('SELECT');
	if(document.getElementById("avatarPanel")){
		document.getElementById("avatarPanel").style.visibility = "hidden";
	}
	if(document.getElementById("360Panel")){
		document.getElementById("360Panel").style.visibility = "hidden";
	}
}

/* display all SELECT boxes : IE 6 z-index bug */
function showAllSelects() {
	var targets = document.getElementsByTagName('SELECT');
	for(var i=0; i<targets.length; i++){
		targets[i].style.visibility='visible';
	}
	if(document.getElementById("avatarPanel")){
		document.getElementById("avatarPanel").style.visibility = "visible";
	}
	if(document.getElementById("360Panel")){
		document.getElementById("360Panel").style.visibility = "visible";
	}
}

function opacity(id, opacStart, opacEnd, millisec) {
    //speed for each frame
    var speed = Math.round(millisec / 100);
    var timer = 0;
    var item = getOpacityItem(id);
    item[1] = -1;
    
    var transitionStep = 2;
    if(browserSpeed > 20){
    	transitionStep = 2;
    }
    if(browserSpeed > 30){
    	transitionStep = 4;
    }
    if(browserSpeed > 50 || isIE8()){
    	transitionStep = 6;
    }
    

    //determine the direction for the blending, if start and end are the same nothing happens
    if(opacStart > opacEnd) {
        for(i = opacStart; i >= opacEnd; i-=transitionStep) {
            setTimeout("changeOpac(" + i + ",'" + id + "', " + timer + ")",(timer * speed));
            timer++;
        }
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i+=transitionStep)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "', " + timer + ")",(timer * speed));
            timer++;
        }
    }
    setTimeout("internalOpacityComplete()",(timer * speed));
}

function internalOpacityComplete(){
	if(window.opacityCompleted){
		opacityCompleted();
	}
}

function getOpacityItem(id){
	var i = 0;
	for(i = 0; i < opacityList.length; i++){
		if(opacityList[i][0] == id){
			return opacityList[i];
		}
	}
	opacityList[i] = new Array(id, -1);
	return opacityList[i];
}

var opacityList = new Array();
//change the opacity for different browsers
function changeOpac(opacity, id, serial) {
	var item = getOpacityItem(id);
    if(serial < item[1])return;
    item[1] = serial;
    
    var object = document.getElementById(id).style;
    object.opacity = (opacity / 100);
    object.MozOpacity = (opacity / 100);
    object.KhtmlOpacity = (opacity / 100);
    object.filter = "alpha(opacity=" + opacity + ")";
	object.display="";
} 

function launchCollegeLink(url, value, colleges){
	if(value == ""){
		alert("Please Insert a valid college name");
		return;
	}
	for(i = 0; i < colleges.length; i++){
		if(colleges[i].shortname.toLowerCase() == value.toLowerCase() || colleges[i].name.toLowerCase() == value.toLowerCase()){
			window.location = url + "college=" + colleges[i].trail;
			return;
		}
	}
	alert("Could not find the school you are looking for. Please try a different name");
}

function launchtour(value, colleges){
	launchCollegeLink("yourcampus2.php?", value, colleges);
}

function insideElement(x, y, element)
{
	var coor = getElementCoordinates(element);
	return x >= coor["X"] && x <= element.clientWidth + coor["X"] &&
		   y >= coor["Y"] && y <= element.clientHeight + coor["Y"];
}

function fixMouseCoordinates(e)
{
	// Calculate pageX/Y if missing and clientX/Y available
	if ( e.pageX == null && e.clientX != null ) {
		var b = document.body;
	    e.pageX = e.clientX + (e && e.scrollLeft || getScrollLeft() || 0);
	    e.pageY = e.clientY + (e && e.scrollTop || getScrollTop() || 0);
	}
	return e;
}

function getElementCoordinates(element)
{
	var el = element;
	var x = 0;
	var y = 0;
	var result = new Array();

	//Walk up the DOM and add up all of the offset positions.
	while (el.offsetParent && el.tagName.toUpperCase() != 'BODY')
	{
		x += el.offsetLeft;
		y += el.offsetTop;
		el = el.offsetParent;
	}
	x += el.offsetLeft;
	y += el.offsetTop;
	result["X"] = x;
	result["Y"] = y;
	
	return result;
}

function FloatingLayer(name, width, height, hidden){
	var theBody = document.getElementsByTagName('BODY')[0];
	var obj = document.createElement('div');
	obj.id = name;
	theBody.appendChild(obj);
		
	this.hidden = hidden;
	
	this.name = name;
	this.closeOnClickFunc = null;
	this.originalClickFunc = null;
	
	this.layer = document.getElementById(name);
	this.layer.style.width = width + "px";
	this.layer.style.height = height + "px";
	this.layer.style.display = hidden?"none":"";
	this.layer.style.position = "absolute";
	
	this.layer.innerHTML = "<div id=" + name + "_body style=width:100%;height:100%;position:absolute:left:0px;top:0px></div>"
	this.bodyDiv = document.getElementById(name+ "_body");
	
	this.show = function(){
		this.hidden = false;
		this.layer.style.display = "";
		this.originalClickFunc = document.onclick;
		if(this.closeOnClickFunc){
			document.onclick = this.closeOnClickFunc;
		}
	}
	
	this.hide = function(){
		this.hidden = true;
		this.layer.style.display = "none";
		document.onclick = this.originalClickFunc;
	}
	
	this.setCoordinates = function(x, y, halign){
		if(halign =="right"){
			this.layer.style.right = x + "px";	
		}else{
			this.layer.style.left = x + "px";
		}		
		this.layer.style.top = y + "px";
	}
	
	this.setX = function(x){
		this.layer.style.left = x + "px";
	}
	
	this.setY = function(y){
		this.layer.style.top = y + "px";
	}
	
	this.setBody = function(html){
		this.bodyDiv.innerHTML = html;
	}
	
	this.getStyle = function(){
		return this.layer.style;
	}
	
	this.closeOnClick = function(owner){
		var me = this;
		this.closeOnClickFunc = function(e){
			e = e || event
			var target = e.target || e.srcElement
			var box = document.getElementById(me.name)
			do {
				if (box == target) {
					// Click occured inside the box, do nothing.
					return
				}
				target = target.parentNode
			} while (target)
			me.hide();
			if(owner.layerClosed){
				owner.layerClosed();
			}
		};
	}
	
	this.enableCloseButton = function(img, width, height, top, right, owner){
		var theBody = document.getElementsByTagName('BODY')[0];
		var obj = document.createElement('div');
		obj.id = this.name  + "_close";
		obj.innerHTML = "<img src=" + img + " width=" + width + " height=" + height + " style=cursor:pointer>";
		obj.style.position = "absolute";
		obj.style.right= right + "px";
		obj.style.top= top + "px";
		
		var me = this;
		obj.onclick = function(){
			me.hide();
			if(owner.layerClosed){
				owner.layerClosed();
			}
		};
		
		this.layer.appendChild(obj);
	}	
}

function getElementsByClass(searchClass, tag) {      
   var returnArray = [];
   tag = tag || '*';
   var els = document.getElementsByTagName(tag);
   var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');
   for (var i = 0; i < els.length; i++) {
      if ( pattern.test(els[i].className) ) {
         returnArray.push(els[i]);
      }
   }
   return returnArray;
}

function appendParamToUrl(url, param){
	if(url.toLowerCase().indexOf("javascript") < 0){
		var connector = "?";
		if(url.toLowerCase().indexOf(".php?") > -1){
			connector = "&";
		}
		url = url + connector + param;
	}
	return url;
}

function stripExtension(file){
	var pos = file.lastIndexOf(".");
	return file.substring(0, pos);
}

function getFileExtension(file){
	var pos = file.lastIndexOf(".");
	return file.substring(pos+1, file.length);
}

function insertSuffix(file, suffix){
	var pos = file.lastIndexOf(".");
	return file.substring(0, pos) + suffix + file.substring(pos, file.length);
}

function closeAnalyticsModule(userkey, session, moduleId, time){
	var url = "functions.php?method=closeAnalyticsModule&userkey=" + userkey + "&session=" + session + "&moduleid=" + moduleId + "&time=" + time;
	httpRequest(url, false);
}

function convertSecondsToTimeLabel(seconds){
	var hours = leftpad(Math.floor(seconds/3600)+'', "0", 2);
	var minutes = leftpad(Math.floor((seconds/60)%60)+'', "0", 2);
	var seconds = leftpad(Math.round(seconds%60)+'', "0", 2);
	return hours+":"+minutes+":"+seconds;
}

function leftpad(str, padString, length) {
    while (str.length < length)
        str = padString + str;
    return str;
}
 
function rightpad(str, padString, length) {
    while (str.length < length)
        str = str + padString;
    return str;
}

function setLaunchSource(college){
	var url = "functions.php?method=setLaunchSource&collegeid=" + college;
	httpRequest(url, false);
}