var timeoutStartTime;
var browserSpeed;
var eventsAdded = false;

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;
}

// Not used
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. Used in buildMediaPanel
function getY(id){
    return getElementCoordinates(document.getElementById(id))["Y"];
}


// Deprecated. Used in setMaskSize(), tourScriptsBottom() [php]
function isIE(){
    return navigator.appName.toLowerCase().indexOf("explorer") > -1;
}

function isWindows7(){
	return navigator.appVersion.toLowerCase().indexOf("windows nt 6.1") > -1;
}

function isIE9(){
    return navigator.appVersion.toLowerCase().indexOf("msie 9") > -1;
}

function isIE8(){
    return navigator.appVersion.toLowerCase().indexOf("msie 8") > -1;
}

function isIE7(){
    return navigator.appVersion.toLowerCase().indexOf("msie 7") > -1;
}

function isFF(){
    return navigator.userAgent.toLowerCase().indexOf("firefox") > -1;
}

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 is set to true, make it async. async could otherwise be undefined/null
   	async = (async === true) ? true : false;
   	return ajaxRequest({
   		url: url,
   		async: async,
   		callback: func
   	});
}

function loadHtmlDoc_POST(url, params, async, func, request){  
    async = (async === true) ? true : false;
    
    return ajaxRequest({
   		url: url,
   		async: async,
   		params: params,
   		mode: "POST",
   		callback: func
   	});
    
}

function encodeURL(sStr) {
    return escape(sStr).
        replace(/\+/g, '%2B').
        replace(/\"/g,'%22').
        replace(/\'/g, '%27').
        replace(/\//g,'%2F');
}

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;
}

// Taken directly from jQuery 1.6.1 source
function preventEventDefault(e) {
    // if preventDefault exists run it on the original event
    if ( e.preventDefault ) {
        e.preventDefault();

    // otherwise set the returnValue property of the original event to false (IE)
    } else {
        e.returnValue = false;
    }
}

/**
 * Object for creating dialogs.
 */
var Dialog = {
    
    /**
     * Creates a basic dialog box with a dark mask overlay and a close button
     * 
     * @param {object} options
     * <pre>
     *  - content:      {string|HTMLElement} all the content that will go in the dialog. Can be a string or html element
     *  - width:        {int}        [optional] width of the dialog. Default = 600
     *  - style_prefix  {string}     [optional] Add id's to the container and content element with a prefix for css styling
     *  - top:          {int|string} [optional] Distance (px) from the top of the page or window. page/window is decided by top_relative parameter. Default = auto.
     *  - top_relative: {string}     [optional] page or window. Default = page 
     *  - onopen        {function}   [optional] this function will be executed right before the mask and dialog are appended to the document. Default = empty
     *  - onclose:      {function}   [optional] this function will be fired when the close button is clicked, but before the dialog is closed. default = nothing
     *  - maskBackground:{string}    [optional] background for the mask. Default = dark transparent gray. Use 'none' for no background.
     *  - modal:        {boolean}    [optional] Close the dialog when the user clicks on the close button. Default = true 
     * </pre>
     */
    create : function(options) {
        // Settings
        var content = options.content,
            width   = options.width || 600,
            top_px  = options.top || 'auto',
            top_relative = options.top_relative || 'page',
            onopen  = options.onopen || function() {},
            onclose = options.onclose || function() {},
            maskBackground = options.maskBackground,
            style_prefix = options.style_prefix,
            modal,
        // Variables
            body = document.getElementsByTagName('body')[0],
            mask = document.createElement('div'),
            leftMargin = (width / 2) * -1,
            maskHeight = (window.innerHeight > 1500) ? window.innerHeight : 1500,
            dialog_container = 'dialog_container',
            dialog_content = 'dialog_content',
            closeFunction = function(e) {
                onclose(e);
                preventEventDefault(e);
                Dialog.close();
                showObjectLayers();
            },
            openFunction = function() {
                onopen();
                if (Dialog.isOpen) {
                    Dialog.close();
                }
                // Make sure to close the old dialog
                hideModalDialog();
                hideObjectLayers();
            };
            
        // Handle boolean settings
        modal = options.modal === false ? false : true;

        // Mask
        // IE7 doesn't read element.setAttribute('style', 'mystyles') so we use the style object
        mask.setAttribute('id', 'dialog_mask');
        mask.style.height = maskHeight + 'px';
        if (maskBackground) {
            // IE will throw errors on rgba, so we set up a fallback
            try {
                mask.style.background = maskBackground;
            } catch (e) {
                mask.style.background = 'none';
            }
        }
        if (!modal) {
            addEvent(mask, 'click', closeFunction);
        }

        // Container
        var container = document.createElement('div');
        container.className = dialog_container;
        if (style_prefix) {
            container.setAttribute('id', style_prefix + '_' + dialog_container);
        }
        container.style.marginLeft = leftMargin + 'px';
        container.style.width = width + 'px';
        if (top_px !== 'auto') {
        	top_px = parseInt(top_px);
        	if(top_relative == "window"){
        		top_px += getScrollTop();
        	}
            container.style.top = top_px + 'px';
            container.style.marginTop = '0px';
            container.style.position = 'absolute';
        }

        // Close Link
        var x = document.createElement('a');
        x.setAttribute('href', '#');
        x.setAttribute('title', 'Close');
        x.setAttribute('id', 'dialog_close');
        addEvent(x, 'click', closeFunction);
        container.appendChild(x);

        // Content. Can't use appendChild on a string, so create a div to put everything in
        var div = document.createElement('div');
        div.className = dialog_content;
        if (style_prefix) {
            div.setAttribute('id', style_prefix + '_' + dialog_content);
        }else{
        	div.setAttribute('id', dialog_content);
        }
        if (typeof content == "string") {
            div.innerHTML = content;
            
        } else {
            div.appendChild(content);
        }
        content = div;
        container.appendChild(content);
        
        // Save mask and container for later access
        this._container = container;
        this._mask = mask;
        
        // Call our onopen function hook
        openFunction();

        // Show the dialog
        body.appendChild(mask);
        body.appendChild(container);
        
        this.isOpen = true;
        if (top_px == 'auto') {
        	this.centerVertically();
        }
    },
    
    /**
     * Removes the dialog from the page
     */
    close : function() {
        var body = document.getElementsByTagName('body')[0];
        body.removeChild(this.getMask());
        body.removeChild(this.getContainer());
        this.isOpen = false;
        this._mask = null;
        this._container = null;
        
        // Call any built up functions
        var i;
        for(i = 0; i < this.callbacks.length; i++) {
            this.callbacks[i]();
        }
    },
    
    /**
     * Adds a function to the callbacks array
     */
    addCallback : function(fn) {
    	if (typeof fn === "function") {
            this.callbacks.push = fn;
    	}
    },
    
    centerVertically : function() {
        var container = this.getContainer();
        container.style.height = "";
        container.style.height = container.offsetHeight + 'px';
        container.style.marginTop = (parseInt(container.style.height) / 2) * -1 + 'px';
    },
    
    callbacks : [],
    
    isOpen : false,
    
    _mask : null,
    getMask : function() {
        return this._mask;
    },
    
    _container : null,
    getContainer : function() {
        return this._container;
    }
};

function addEvent(obj, evType, fn, useCapture){
	var capture = false;
	if(useCapture){
		capture = true;
	}
    if (obj.addEventListener) {
        obj.addEventListener(evType, fn, capture);
        return true;
    }
    else if (obj.attachEvent) {
        var r = obj.attachEvent('on'+evType, fn);
        return r;
    }
    else {
        return false;
    }
}

function removeEvent(obj, evType, fn, useCapture){
	var capture = false;
	if(useCapture){
		capture = true;
	}
    if (obj.removeEventListener) {
        obj.removeEventListener(evType, fn, capture);
        return true;
    }
    else if (obj.detachEvent) {
        var r = obj.detachEvent('on'+evType, fn);
        return r;
    }
    else {
        return false;
    }
}


//-------------------------------------------------------------------------------------------------------
// 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 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 createMaskLayer(styleName, keepOpenWithOutsideClick, callback, keepObjects){
    createModalDialog(styleName, keepOpenWithOutsideClick);
    stIsShown = true;

    stMask.style.display = 'block';
    if(callback){
        stMask.callbackFunc = callback;
    }
    setMaskSize();

    // hide all SELECT boxes : IE 6 z-index bug
    if(keepObjects == undefined || !keepObjects){
    	hideObjectLayers();
    }
}

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;
        }
		
        if(!eventsAdded){
            addEvent(window,'resize',centerModalDialog);
            addEvent(window,'scroll',centerModalDialog);
            eventsAdded = 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;
    }

    // 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
    hideObjectLayers();
}

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';
    }
}

// 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';
    stMask.style.width = '100%';
    //if(!isIE()){stMask.style.width = (popWidth-18) + 'px';} // correct for scroll bars (FF)
}

function hideModalDialog(e, keepObjects) {
    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 = "";

    if (document.getElementById("mediaPanel")) {
            document.getElementById("mediaPanel").innerHTML = "";
    }
    if(stMask.callbackFunc){
            stMask.callbackFunc();
    }

    // Close all calendars
    f_tcalHideAll();

    if(keepObjects == undefined || !keepObjects){
    	// display all SELECT boxes : IE 6 z-index bug
    	showObjectLayers();
    }
    
    //stContainer.innerHTML = "";
    stMask.style.innerHTML = "";
    theBody.removeChild(stMask);
    theBody.removeChild(stContainer);
    stMask = null;
}

var modalDialogPausedAvatar = false;
function hideObjectLayers() {
    //var targets = document.getElementsByTagName('select');
    var objects = document.getElementsByTagName('object'),
        embed = document.getElementsByTagName('embed'),
        i,
        obj;
        
    for(i = 0; i < objects.length; i++) {
        /*objects[i].style.visibility = 'hidden'; /* Uncomment when all dialogs use Dialog object */
        obj = findParentNodeWithID(objects[i], "modalDialogBody");
        // Only hide objects that are not in the dialog
        if(obj == null){
            objects[i].style.visibility = 'hidden'; 
        }
    }
    for(i = 0; i < embed.length; i++) {
        /*embed[i].style.visibility = 'hidden'; /* Uncomment when all dialogs use Dialog object */
        obj = findParentNodeWithID(embed[i], "modalDialogBody");
        // ONly hide objects that are not in the dialog
        if(obj == null){
            embed[i].style.visibility = 'hidden';
        }
    }
    
    if(window.modalMaskWillDisplay){
    	modalMaskWillDisplay();
    }
    if(document.getElementById("360Panel")){
        document.getElementById("360Panel").style.visibility = "hidden";
    }
    if(document.getElementById("map3d")){
        document.getElementById("map3d").style.visibility = "hidden";
    }
}

function showObjectLayers() {
    //var targets = document.getElementsByTagName('select'),
    var objects = document.getElementsByTagName('object'),
        embed = document.getElementsByTagName('embed'),
        i;
        
    //for(i = 0; i < targets.length; i++){ targets[i].style.visibility = 'visible'; }
    for(i = 0; i < objects.length; i++){objects[i].style.visibility = 'visible';}
    for(i = 0; i < embed.length; i++){embed[i].style.visibility = 'visible';}
    
    if(window.modalMaskWillHide){
    	modalMaskWillHide();
    }
    if(document.getElementById("360Panel")){
        document.getElementById("360Panel").style.visibility = "visible";
    }
    if(document.getElementById("map3d")){
        document.getElementById("map3d").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++;
        }
        setTimeout("changeOpac(" + opacEnd + ",'" + id + "', " + timer + ")",(timer * speed));
    } else if(opacStart < opacEnd) {
        for(i = opacStart; i <= opacEnd; i+=transitionStep)
            {
            setTimeout("changeOpac(" + i + ",'" + id + "', " + timer + ")",(timer * speed));
            timer++;
        }
        setTimeout("changeOpac(" + opacEnd + ",'" + id + "', " + timer + ")",(timer * speed));
    }
    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 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 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 += 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 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 params = "method=setLaunchSource&collegeid=" + college;
    ajaxRequest({
            url: "/functions.php",
            params: params
    });
}

function findParentNodeWithID(obj, parentId){
    var parent = obj.parentNode;
    if(parent == null){
            return null;
    }
    if(parent.id == parentId){
            return parent;
    }
    return findParentNodeWithID(parent, parentId);
}

// Taken from http://www.quirksmode.org/js/cookies.html#script
var Cookie = {
    set : function(name, value, days) {
        var expires;
        if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            expires = "; expires="+date.toGMTString();
        }
        else expires = "";
        document.cookie = name+"="+value+expires+"; path=/";
    },
    
    get : function(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for(var i=0;i < ca.length;i++) {
            var c = ca[i];
            while (c.charAt(0)==' ') c = c.substring(1,c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
        }
        return null;
    },
    
    remove : function(name) {
        this.set(name, "", -1);
    }
};

//http://www.simonwhatley.co.uk/parsing-twitter-usernames-hashtags-and-urls-with-javascript
String.prototype.linkify = function() {
    return this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(url) {
        return url.link(url);
    });
};

String.prototype.atify = function() {
    return this.replace(/[@]+[A-Za-z0-9-_]+/g, function(u) {
        var username = u.replace("@","");
        return u.link("http://twitter.com/"+username);
    });
};

String.prototype.hashify = function() {
    return this.replace(/[#]+[A-Za-z0-9-_]+/g, function(t) {
        var tag = t.replace("#","%23");
        return t.link("http://search.twitter.com/search?q="+tag);
    });
};

/**
 * Determines whether the current page is in an iframe
 * @returns {Boolean} isExternal 
 */
function isPageExternal() {
    var isExternal = false;
    try {
        if (top.location.href !== window.location.href) {
            isExternal = true;
        }
    } catch (e) {    
        // if you're in an iframe in a different domain, the top.location check results in a security exception
        isExternal = true;
    }

    return isExternal;
}

/**
 * Removes parameters from a url string
 * @param {string} url the url you wish to remove parameters from
 * @param {array} extraParamsArray 2d array of parameters
 * @param {boolean} isExternal is the page in an iframe or not
 * @return {string} url the new url without those parameters
 */
function removeOldExtraParams(url, extraParamsArray, isExternal) {
    var amp = (isExternal) ? escape('&') : '&';
    for(var j = 0; j < extraParamsArray.length; j++) {
        var parameter = '&'+extraParamsArray[j][0]+'=';
        var paramName = (isExternal) ? escape(parameter) : parameter;

        // Test to see if the parameter exists in the url
        var oldParamsStart = url.lastIndexOf(paramName);
        if (oldParamsStart != -1) {
            var key;
            // If there are still more parameters, find the index of the next one
            var nextParameterStart = url.indexOf(amp, oldParamsStart + 1);
            if (nextParameterStart != -1) {
                key = url.substring(oldParamsStart, nextParameterStart);
            } else {
                key = url.substr(oldParamsStart);
            }
            url = url.replace(key, '');
        }
    }
    return url;
}

/**
 * Takes an array like [['h', 340], ['blarg', true]] and builds a
 * string for the url
 * @param {array} extraParams 2d array with parameters
 * @returns {String} concatinated parameters
 */
function concatParams(extraParams) {
    var params = '';
    for(var i = 0; i < extraParams.length; i++) {
        params += '&' + extraParams[i][0] + '=' + extraParams[i][1];
    }
    return params;
}

function getUrlParameters() {
    var url = window.location.search,
        pairs = url.substr(url.lastIndexOf('?')+1).split('&'),
        params = {},
        i,
        arr;
        
    for(i in pairs) {
        arr = pairs[i].split('=');
        params[arr[0]] = arr[1];
    }

    return params;
}

function showHoverInfoPanel(obj){
    var tDIV = document.getElementById("hoverInfoPanel");             
    tDIV.style.cursor = "hand";
    tDIV.style.visibility = "visible";
    tDIV.style.display="";
    tDIV.style.width="330px";
	
    var url = getDirectUrlLink();
	
    tDIV.innerHTML = "<b>"+hoverText+"</b> <br><input type='text' onfocus='this.select()' style='margin-top:5px;width:300px' value='"+url+"'>";
    tDIV.style.top = getposOffset(obj, "top") + "px";
    tDIV.style.left = getposOffset(obj, "left")-280 + "px";//window.event.clientX
}

function hideHoverInfoPanel(e){
    var tDIV = document.getElementById("hoverInfoPanel");
    if(isEventOutsideElement(tDIV, e)){
        tDIV.style.display='none';
    }
}

function getDirectUrlLink() {
    // If there are extra parameters for this page, get them
    var extraParams = '';
    var extraParamsArray = [];
    if(typeof getSpecialUrlParams === 'function') {
        extraParamsArray = getSpecialUrlParams(); 
        extraParams = concatParams(extraParamsArray);
    }

    // Determine if we're in an iframe
    var isExternal = isPageExternal();

    // Build the url
    var url = '';
    if (isExternal) {
        url = directUrl;
    } else {
        url = window.location.href;
    }

    if(extraParamsArray!=""){
        // Remove old extra parameters
        url = removeOldExtraParams(url, extraParamsArray, isExternal);
    
        // Add new extra parameters
        if (isExternal) {
            url += escape(extraParams);
        } else {
            url += extraParams;
        }
    }
	
    return url;
}

function setClickEvent(obj, funcString){
	if(isIE7()){
		obj.href = "javascript:" + funcString;
	}else{
		obj.href = "javascript:void(0)";
		obj.setAttribute("onclick", funcString);
	}
}

function showWalkingTourTooltip(){
	var panel = document.createElement("div");
	panel.id = "walkingtour_tooltip";
	panel.className = "main_tooltip";
	panel.innerHTML = "Click here to explore our campus through an interactive Walking Tour <a href='javascript:void(0)' onclick='hideWalkingTourTooltip()'>x</a>";
	var focus = document.getElementById("walkingtour_menu");
	focus.style.color = "#dc7903";
	focus.appendChild(panel);
	
	var obj = getElementsByClass("selectedSubmenu", "a");
	var i = 0;
	for(i;i<obj.length;i++){
		obj[i].style.color = "#4f6685";
	}
}

function hideWalkingTourTooltip(){
	obj = document.getElementById("walkingtour_tooltip");
	if(obj!=null){
		document.getElementById("walkingtour_menu").removeChild(obj);
	}
	document.getElementById("walkingtour_menu").style.color = "";
	var obj = getElementsByClass("selectedSubmenu", "a");
	var i = 0;
	for(i;i<obj.length;i++){
		obj[i].style.color = "";
	}
	Cookie.set("wt_tooltip_disabled", "1", 30);
}

//http://www.itnewb.com/v/Beginners-Guide-to-AJAX-Asynchronous-JavaScript-and-XML/page3
function ajaxRequest(options) {
    var mode = options.mode || 'GET',
        url = options.url,
        args = options.params || '',
        async,
        callback = options.callback || function(){},
        cArgs = options.cArgs || null,
        respType = options.respType || 'text',
        timeout = options.timeout || 30;
    
    async = (options.async === false) ? false : true;
    
    if (url == null) {
        console.error('url is required');
        return false;
    }
    
    var xhr = false;
    if (window.XMLHttpRequest) { // mozilla, safari, opera, chrome, ie7
        xhr = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // ie, avant, aol explorer
        try {
            xhr = new ActiveXObject("Msxml2.XMLHTTP"); // ie6
        }
        catch (e) {
            try {
                xhr = new ActiveXObject("Microsoft.XMLHTTP"); // ie5
            }
            catch(e) {
                xhr = false;
            }
        }
    }
    
    if (!xhr) {
        console.error("Error: unable to create httpRequest object");
        return false;
    }
 
    // if GET with arguments append query string to url
    if (mode == 'GET' && args.length) {
        url += '?' + args;
    }
 
    // establish connection
    xhr.open(mode, url, async);
 
    // boolean timedOut; start out true
    // the response handler sets to false on success
    var timedOut = true;
 
    // create a timer to check the value of timedOut in (timeout) seconds;
    // if timedOut is true, abort the request and clean up
    setTimeout(function() {
 
        // timedOut true?
        if (timedOut) {
            xhr.abort(); // abort request
            console.error("Error: ajax request timed out");
        }
 
        // nullify httpRequest
        xhr = null;
 
    }, timeout * 1000);
 
    
    if (mode == 'POST') {
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.setRequestHeader('Content-Length', args.length);
    }
 
    if (async) {
        xhr.onreadystatechange = function() {
            try {
                if (xhr.readyState == 4) {
                    if ( xhr.status == 200 ) {
                        // set timedOut to false
                        timedOut = false;

                        // set response
                        var response = respType == 'text' ? xhr.responseText : xhr.responseXML;

                        // pass to callback method
                        if(callback != undefined){
                        	cArgs != null ? callback(response, cArgs) : callback(response);
                        }
                    }
                }
            } catch(e) {
                console.error("Error: communication exception");
            }
        };
    }
    
    xhr.send(args);
    
    if (!async) {
        var response = respType == 'text' ? xhr.responseText : xhr.responseXML;
        timedOut = false;
        return response;
    }
}

/**
 * Returns the current domain (ex. 'http://dev.yourcampus360.com')
 * @return {string} the domain
 */
function getDomain() {
    return window.location.protocol + '//' + window.location.hostname;
}

function registerUsersClick(userkey, sessionid, action, moduleid){
	return ajaxRequest({
		url: "/functions.php",
		params: "method=registerUsersClick&userkey=" + userkey + "&sessionid=" + sessionid + "&action=" + action + "&moduleid=" + moduleid,
		async: false
	});
	return true;
}

function addClass(obj, className){
	if(obj.className.indexOf(className)>-1){
		return;
	}
	obj.className += (" " + className);
}

function removeClass(obj, className){
	var pos = obj.className.indexOf(className);
	if(pos<0)return;
	
	obj.className = obj.className.substring(0, pos) + obj.className.substring(pos + className.length);
}
