/****************/
/** xp services */
/****************/

function Browser() {
    var ua, s, i;

    this.isSupported = false;
    this.isIE    = false;
    this.isNS    = false;
    this.isMacGecko    = false;
    this.isSafari    = false;
    this.isOpera    = false;
    this.version = null;

    ua = navigator.userAgent;

    s = "MSIE";
    if ((i = ua.indexOf(s)) >= 0) {
        this.isIE = true;
        this.version = parseFloat(ua.substr(i + s.length));
        if (this.version >= 6) 
            this.isSupported = true;
        return;
    }

    s = "Safari/";
    if ((i = ua.indexOf(s)) >= 0) {
        this.isSafari = true;
        this.version = parseFloat(ua.substr(i + s.length));
        this.isSupported = true;
        return;
    }

    s = "Opera/";
    if ((i = ua.indexOf(s)) >= 0) {
        this.isOpera = true;
        this.version = parseFloat(ua.substr(i + s.length));
        this.isSupported = true;
        return;
    }

    s = "Netscape6/";
    if ((i = ua.indexOf(s)) >= 0) {
        this.isNS = true;
        this.version = parseFloat(ua.substr(i + s.length));
        return;
    }

    // Treat any other "Gecko" browser as NS 6.1.
    s = "Gecko";
    if ((i = ua.indexOf(s)) >= 0) {
        var s2 = 'Firefox/';
        var j = ua.indexOf(s2);
        this.realVersion = parseFloat(ua.substr(j + s2.length));
        if (this.version >= 1.5)
            this.isSupported = true;
        this.isNS = true;
        this.version = 6.1;
        if (ua.indexOf("Mac") >= 0)
            this.isMacGecko = true;
    }
}

var webBrowser = new Browser();

if (webBrowser.isIE) {
    document.write('<link rel="stylesheet" href="/ui/styles/browser-ie.css"/>');
} else if (webBrowser.isSafari) {
    document.write('<link rel="stylesheet" href="/ui/styles/browser-safari.css"/>');
} else if (webBrowser.isMacGecko) {
    document.write('<link rel="stylesheet" href="/ui/styles/browser-mac-gecko.css"/>');
} else {
    document.write('<link rel="stylesheet" href="/ui/styles/browser-gecko.css"/>');
}

function getRealWindowWidth() {
    var size;
    if (window.innerWidth) {
        size = window.innerWidth;
        // if sb, they are not included, so adjust by 20.  later, consider sb, and
        if (size != document.body.clientWidth)
            size -= 20;
    } else if (document.documentElement && document.documentElement.clientWidth) {
        size = document.documentElement.clientWidth;
    } else {
        size = document.body.clientWidth;
    }

    return size;
}

function getWindowWidth() {
    var size = getRealWindowWidth();
//    var adArea = document.getElementById("adArea");
//    if (adArea && (adArea.className.indexOf("hidden") < 0))
//        size -= 140;
    size -= 51;
    return size;
}

function getRealWindowHeight() {
    var size;
    if (window.innerHeight) {
        size = window.innerHeight;
        // if sb, they are not included, so adjust by 20.  later, consider sb, and
        if (size != document.body.clientHeight)
            size -= 20;
    } else if (document.documentElement && document.documentElement.clientHeight) {
        size = document.documentElement.clientHeight;
    } else {
        size = document.body.clientHeight;
    }

    return size;
}

function getWindowHeight() {
    var size = getRealWindowHeight();
    if (document.getElementById("header"))
        size -= 125;
    return size;
}

function getPageWidth() {
    if (window.pageWidth)
        return window.pageWidth
    else
        return document.body.offsetWidth;
}

function getPageHeight() {
    if (window.pageHeight)
        return pageHeight + getFooterHeight() + 40;
    else
        return document.body.offsetHeight;
}

function openCalendar(conf_name, target_field) {
    showCalendar(conf_name, target_field, null, '', target_field.name, 0, 30, 1);
}

function showComStatus() {
    if (window.showStatus)
        window.showStatus();
}

function getKey(evt) {
    return String.fromCharCode(getKeyCode(evt));
}

function getKeyCode(evt) {
    if (window.event)
        evt = window.event;
    return (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
}

function pressedEnter(evt) {
    var keyCode = getKeyCode(evt);
    // 63233 is safari
    return (keyCode == 13); // keyCode == 63233);  maybe arrow?
}

function toggleInfo(areaId) {
    if (!areaId)
        areaId = "infoArea";
    var infoArea = document.getElementById(areaId);
    if (infoArea.style.display == 'none')
        infoArea.style.display = "";
    else
        infoArea.style.display = "none";
}

function showInfo(areaId) {
    if (!areaId)
        areaId = "infoArea";
    document.getElementById(areaId).style.display="";
}

function hideInfo(areaId) {
    if (!areaId)
        areaId = "infoArea";
    document.getElementById(areaId).style.display="none";
}

/****************/
/** Portal Stuff */
/****************/

function hidePortal() {
    hidePortlets();
}

/********************/
/** common services */
/********************/

function cancelEvents(event) {
    if (window.event) {
        window.event.returnValue = false;
        window.event.cancelBubble = true;
    } else if (event) {
        event.preventDefault();
        event.stopPropagation();
    }
    return false;
}

function openMainWindow(href) {
    openWindow(href, 1000, 600);
}

function openWindow(href, width, height) {
    if (href == '')
        return null;
    var windex = "win" + Math.round(Math.random() * 1000);
    if (!width) width=800;
    if (!height) height=600;
    var win = window.open(href, windex, "width="+width+",height="+height+",scrollbars=yes,resizable=yes");
    //win.moveTo(window.screenX+20, window.screenY+10);
    return win;
}

function openNavWindow(href, width, height) {
    if (href == '')
        return null;
    var windex = "win" + Math.round(Math.random() * 1000);
    if (!width) width=800;
    if (!height) height=600;
    var win = window.open(href, windex, "width="+width+",height="+height+",scrollbars=yes,resizable=yes,toolbar=yes");
    //win.moveTo(window.screenX+20, window.screenY+10);
    return win;
}

function showMessage(msg) {
    var win = window.open("","Message","width=400,height=300");
    msg = "<div style='text-align:center;font-size:larger;'>Warning</div><br>" + msg;
    msg += "<BR><BR><div style='text-align:center'><button type='button' onclick='window.close()'>Close</button></div>";
    // for popups that dont popup
    if (win.document.body) {
        win.document.body.innerHTML = msg;
    } else {
        window.top.document.body.innerHTML = msg + window.top.document.body.innerHTML;
    }
    return win;
}

function showPropertiesList() {
    var entityType = document.form.entityType.value;
    var url = "Properties?event=displayList&entityType="+entityType;
    if (document.form.listingType) {
        var listingType = document.form.listingType.value;
        url += "&listingType=" + listingType;
    }
    openWindow(url);
}

function showRatingsList() {
    var entityType = document.form.entityType.value;
    var url = "Ratings?event=displayList&entityType="+entityType;
    if (document.form.listingType) {
        var listingType = document.form.listingType.value;
        url += "&listingType=" + listingType;
    }
    openWindow(url);
}

function findElementById(id, elem) {
    if (elem.id == id) 
        return elem;
    else
        return iFindElementById(id, elem);
}

function iFindElementById(id, elem) {
    var nodes = elem.childNodes;
    var node = null;
    for (var j=0; j < nodes.length; j++) {
        if (nodes[j].id == id)
            return nodes[j];
        node = iFindElementById(id, nodes[j]);
        if (node != null)
            return node;
    }
    return node;
}

function refreshAndClose() {
    window.opener.top.location.reload(true);
    window.close();
}

function closeRatings() {
    // special handling for inline popup
    if (window.parent.hideRatings) {
        window.parent.hideRatings();
    } else {
        cancel();
    }
}
    
function cancel() {
    if (window.location.search.indexOf("popup=true") >= 0)
        closeWindow();
    else if (document.form && document.form.returnToUrl.value != '')
        window.top.location = document.form.returnToUrl.value;
    else if (window.history.length == 0)
        closeWindow();
    else
        window.history.back();
}


function closeWindow() {
    if (window.opener)
        window.close();
    else
        window.top.location = "/";
}

function accessWarning() {
    valert("You have insufficient permissions to view this page!");
}

function submit() {
    document.form.submit();
}

function submitEvent(event) {
    document.form.event.value = event;
    submit();
}

function getField(evt) {
    if (window.event) {
        return window.event.srcElement;
    } else {
        return evt.target;
    }
}

/********************/
/** window services */
/********************/

var ready = false;
var onloads = new Array();
var lastOnloads = new Array();

window.onload = function() {
    for (var j=0; j < onloads.length; j++)
        onloads[j]();
    for (var j=0; j < lastOnloads.length; j++)
        lastOnloads[j]();
    ready = true;
}

function addOnload(funx) {
    onloads.push(funx);
}

function addOnloadLast(funx) {
    lastOnloads.push(funx);
}

window.initFields = function() {
    var fields = getFields();
    if (fields != null) {
        for (var j=0; j < fields.length; j++) {
            initField(fields[j]);
        }
    }
}

var pageFields = null;

// get [] of fields on a page (buttons and form fields, not anchors)
window.getFields = function() {
    if (!pageFields) {
        pageFields = new Array();
        if (!document.form)
            return null;
        var fields = document.form.elements;

        // add main fields
        for (var j=0; j < fields.length; j++) {
            if (fields[j].nodeName == "BUTTON")
                continue;
            else if (window.ignoreCheckboxes && fields[j].type == "checkbox")
                continue;
            else if (fields[j].type == "hidden")
                continue;
            else if (fields[j].className.indexOf("hidden") >= 0)
                continue;
            else if (fields[j].style.display == "hidden")
                continue;
            else
                pageFields.push(fields[j]);
        }

        // add buttons at the end
        for (j=0; j < fields.length; j++) {
            if (fields[j].className.indexOf("hidden") >= 0)
                continue;
            else if (fields[j].nodeName == "BUTTON")
                pageFields.push(fields[j]);
        }
    }
    return pageFields;
}

window.clearField = function(field) {
    if (field.addEventListener) {
        // highlight field
//        field.removeEventListener("focus", highlightField, false);

        // handle tabbing
        if (!window.noTabbing) {
            field.removeEventListener("keydown", handleTabbing, false);
            field.removeEventListener("keypress", handleTabbingPress, false);
        }
            
        if (field.className.indexOf("read-only") >= 0) {
            // read-only
            field.removeEventListener("focus", registerReadOnlyValue, false);
            field.removeEventListener("change", restoreReadOnlyValue, false);
            if (field.nodeName == "SELECT") {
                field.removeEventListener("keypress", restoreReadOnlyValue, false);
                field.removeEventListener("change", readOnlySignal, false);
                field.removeAttribute("onchange");
            } else {
                field.removeEventListener("keypress", readOnlySignal, false);
            }
 //       } else {
            // Type Into SELECT
 //           if (field.nodeName == "SELECT")
//	        field.removeEventListener("keypress", typeIntoSelect, false);
//            else if (field.className.indexOf("numeric") >= 0)
//	        field.removeEventListener("keypress", formatNumeric, false);
        }
    } else {
        // highlight field
//        field.detachEvent("onfocus", highlightField);
        // handle tabbing
        if (!window.noTabbing) {
            field.detachEvent("onkeydown", handleTabbing);
            field.detachEvent("onkeypress", handleTabbingPress);
        }

	if (field.className.indexOf("read-only") >= 0) {
            // read-only
            field.detachEvent("onfocus", registerReadOnlyValue);
            field.detachEvent("onchange", restoreReadOnlyValue);
            if (field.nodeName == "SELECT") {
                field.detachEvent("onkeypress", restoreReadOnlyValue);
                field.detachEvent("onchange", readOnlySignal);
                field.onchange = null;
            } else {
                field.detachEvent("onkeypress", readOnlySignal);
            }
//        } else {
            // Type Into SELECT
//	    if (field.nodeName == "SELECT")
//	        field.detachEvent("onkeypress", typeIntoSelect);
 //           else if (field.className.indexOf("numeric") >= 0)
//	        field.detachEvent("onkeypress", formatNumeric);
        }
	}
}

window.initField = function(field) {
    if (field.addEventListener) {
        // highlight field
//        field.addEventListener("focus", highlightField, false);

        // handle tabbing
/*
        if (!window.noTabbing) {
            field.addEventListener("keydown", handleTabbing, false);
            field.addEventListener("keypress", handleTabbingPress, false);
        }
*/
            
        if (field.className.indexOf("read-only") >= 0) {
            // read-only
            field.addEventListener("focus", registerReadOnlyValue, false);
            field.addEventListener("change", restoreReadOnlyValue, false);
            if (field.nodeName == "SELECT") {
                field.addEventListener("keypress", restoreReadOnlyValue, false);
                field.addEventListener("change", readOnlySignal, false);
                field.removeAttribute("onchange");
            } else {
                field.addEventListener("keypress", readOnlySignal, false);
            }
 //       } else {
            // Type Into SELECT
 //           if (field.nodeName == "SELECT")
//	        field.addEventListener("keypress", typeIntoSelect, false);
//            else if (field.className.indexOf("numeric") >= 0)
//	        field.addEventListener("keypress", formatNumeric, false);
        }
    } else {
        // highlight field
//        field.attachEvent("onfocus", highlightField);
        // handle tabbing
/*
        if (!window.noTabbing) {
            field.attachEvent("onkeydown", handleTabbing);
            field.attachEvent("onkeypress", handleTabbingPress);
        }
*/

	if (field.className.indexOf("read-only") >= 0) {
            // read-only
            field.attachEvent("onfocus", registerReadOnlyValue);
            field.attachEvent("onchange", restoreReadOnlyValue);
            if (field.nodeName == "SELECT") {
                field.attachEvent("onkeypress", restoreReadOnlyValue);
                field.attachEvent("onchange", readOnlySignal);
                field.onchange = null;
            } else {
                field.attachEvent("onkeypress", readOnlySignal);
            }
//        } else {
            // Type Into SELECT
//	    if (field.nodeName == "SELECT")
//	        field.attachEvent("onkeypress", typeIntoSelect);
 //           else if (field.className.indexOf("numeric") >= 0)
//	        field.attachEvent("onkeypress", formatNumeric);
        }
	}
}

/***********************/
/** Tabbing services */
/***********************/

function handleTabbing(evt) {
    var field = getField(evt);
    if (window.event)
        evt = window.event;

    var charCode = getKeyCode(evt);

    if (charCode == 3 || charCode == 9) {
        if (evt.shiftKey) {
            focusOnLastField(field);
        } else {
            focusOnNextField(field);
        }

        if (window.event) {
// done for captions.... reconsider
        //    evt.returnValue = false;
        //    evt.cancelBubble = true;
        } else {
            evt.preventDefault();
            evt.stopPropagation();
        }

        return false;
    }

    return true;
}

function handleTabbingPress(evt) {
    if (window.event)
        evt = window.event;
    var charCode = getKeyCode(evt);
    if (charCode == 3 || charCode == 9) {

        if (window.event) {
// done for captions.... reconsider
        //   evt.returnValue = false;
        //    evt.cancelBubble = true;
        } else {
            evt.preventDefault();
            evt.stopPropagation();
        }

        return false;
    }

    return true;
}

function focusOnNextField(field) {
    var fields = getFields();

    var j=0;
    if (field) {
        for (; j < fields.length; j++) {
            if (fields[j].name == field.name && fields[j].value == field.value) {
                    break;
            }
        }

        // move to next field
        j++;
        if (j == fields.length)
            j = 0;
    }

    fields[j].focus();
    phrase = "";
    return false;
}

function focusOnLastField(field) {
    var fields = getFields();
    for (j=0; j < fields.length; j++) {
        if (fields[j].name == field.name && fields[j].value == field.value) {
            break;
        }
    }

    // move to last field
    j--;
    if (j == -1)
        j = fields.length-1;

    fields[j].focus();
    phrase = "";
    return false;
}


/***********************/
/** Read-only services */
/***********************/

    var roValue; 

    function registerReadOnlyValue(evt) {
        var field = getField(evt);
        if (field.type == "checkbox")
            roValue = field.checked;
        else        
            roValue = field.value;
    }   

        
    function restoreReadOnlyValue(evt) {
        var field = getField(evt);
        if (field.type == "checkbox")
            field.checked = roValue;
        else
            field.value = roValue;
    }
    
    function readOnlySignal(evt) {
        if (window.event) {
            window.event.returnValue = false;
            window.event.cancelBubble = true;
        } else {
            evt.preventDefault();
            evt.stopPropagation();
        }
        return false;
    }


/************************/
/** class attr services */
/************************/

function renderClass(className, field, apply) {
    if (apply) {
        if (!field.className)
            field.className = className;
        else if (field.className.indexOf(className) < 0)
            field.className = field.className + " " + className;
    } else {
        if (field.className)
            field.className = field.className.replace(new RegExp(className,"g"), "");
    }
}

/***********************/
/** auto-save services */
/***********************/

var input = false;

function promptSave(form, href) {
    if (input) {
        if (confirm("Would you like to save the changes in this page?")) {
            document.form.nextUrl.value = href;
            document.form.submit();
            return false;
        }
    }
    return true;
}

function markInput() {
    input = true;
}

/*******************************************/
/** SELECT field service: type into select */
/*******************************************/

var phrase;

function typeIntoSelect(evt) {
    var field = getField(evt);
    if (window.event)
        evt = window.event;
    var charCode = getKeyCode(evt);

    // if arrows, skip
    if (charCode == 38 || charCode == 40)
        return true;
		
    // if tab or enter, skip
    if (charCode == 9 || charCode == 3 || charCode == 13)
        return true;

    // backspace
    if (charCode == 8) {
        phrase = phrase.substring(0,phrase.length - 1);
    } else {
	phrase += String.fromCharCode(charCode);
    }

	var options = field.options;
        var phraseExp = new RegExp("^"+phrase, "i");
	for (j=0; j < options.length; j++) {
            value = options[j].text.replace(/\W/,"");
	    if (value.match(phraseExp)) {
	        field.selectedIndex = j;
                break;
            }
	}

	// if there is no match
	if (j == options.length) {
		phrase = "";
		field.selectedIndex = 0;
	}
        window.status = "Input: "+phrase;
	if (window.event) {
        evt.returnValue = false;
		// IE doesnt consider this a change, so fire event manually
		// crucial for onchange events to process
		evt = document.createEventObject();
		field.fireEvent("onchange", evt);
    }
    return true;
}

/*******
 *** Standard Services to start with
 ********/

addOnload(registerLocationSelector);
addOnload(marginConfig);
addOnload(initFields);
addOnload(initRollovers);

var locationSelector, headerLocationSelector;

function registerLocationSelector() {
    if (document.form && document.form.location && document.form.locationText) {
        var max = 10;
        if (window.location.href.indexOf("Locations?event=displayPopup") > 0)
            max = 6;
        locationSelector = new LocationSelector(document.form.locationText, document.form.location, max);
    }
    if (document.formHeader && document.formHeader.locationHeader) {
        headerLocationSelector = new LocationSelector(document.formHeader.locationTextHeader, document.formHeader.locationHeader);
        headerLocationSelector.onsubmit = doHeaderSearch;
    }
}

/*******
 *** page setup
 ********/

function getFooterHeight() {
    var footer = document.getElementById("footerArea");
    if (footer)
        return footer.offsetHeight;
    else
        return 0;
}

function portalResize() {
    marginConfig();
}

function marginConfig() {
    var windowHeight = getRealWindowHeight();
    var height = getPageHeight();
    var footerHeight = getFooterHeight();

    if (height < windowHeight)
        height = windowHeight;

    height = height - footerHeight;

    var marginLeft = document.getElementById("marginLeft");
    var marginRight = document.getElementById("marginRight");
    if (marginLeft && marginRight) {
        marginLeft.width =  "21";
        marginLeft.height = height;
        marginLeft.src = "/ui/media/margin-left.png";
        marginLeft.style.visibility="visible";

        marginRight.width =  "20";
        marginRight.height = height;
        marginRight.src = "/ui/media/margin-right.png";
        marginRight.style.visibility="visible";
    }

    var footerArea = document.getElementById("footerArea");
    if (footerArea)
        footerArea.style.visibility = "visible";

    var header = document.getElementById("header");
    var marginBottom = document.getElementById("marginBottom");
    var width = getPageWidth();
    var windowWidth = getRealWindowHeight();
    if (width < windowWidth)
        width = windowWidth;
//    if (header)
//        header.style.width = (width-20) + "px";

    if (marginBottom) {
        if (header)
            marginBottom.style.width = (header.offsetWidth - 75) + "px";
        else
            marginBottom.width = "";
    }
/*
    if (window.pageWidth && (width+20 > getRealWindowWidth())) {
        if (webBrowser.isIE) {
            if (header)
                header.style.width = (width) + "px";
            if (marginBottom) {
                marginBottom.height = 1;
                marginBottom.width = width - 75;
            }
        } else {
            document.body.style.width = (width + 30) + "px";
        }
    } else {
//        if (!header && marginBottom)
//            marginBottom.width="0";
        if (webBrowser.isIE) {
        //    if (header)
        //        header.style.width = "";
        } else {
        }
    }
*/
}

    // pager

    function changeSortMode() {
        var sortMode = document.form.sortMode.value;
        var url = "/Search?event=changeSortMode&sortMode="+sortMode;
        go(url);
    }

    function changeResultDisplay() {
        var itemsPerPage = document.form.itemsPerPage;
        var resultType = document.form.resultType.value;
        var url = "/Search?event=changeResultDisplay&resultType="+resultType;
        if (itemsPerPage)
            url += "&itemsPerPage="+itemsPerPage.value;
        go(url);
    }

    function moveBackward() {
        go("/Search?event=moveBackward");
    }

    function moveForward() {
        go("/Search?event=moveForward");
    }

    function movePrevious() {
        go("/Search?event=movePrevious");
    }

    function moveNext() {
        go("/Search?event=moveNext");
    }

    function go(url) {
        var query = document.form.query.value;
        url = url + "&query=" + encode(query);

        var mode = document.form.mode.value;
        if (mode != '')
            url += "&mode=" + mode;

        var popup = document.form.popup.value;
        if (popup != '')
            url += "&popup=" + popup;

        var portlet = document.form.portlet.value;
        if (portlet != '')
            url += "&portlet=" + portlet;

        var returnToUrl = document.form.returnToUrl.value;
        if (returnToUrl != '')
            url += "&returnToUrl=" + returnToUrl;

        window.location = url;
    }

    function compare(a,b) {
        if (a.localeCompare) {
            return a.localeCompare(b);
        } else {
            if (a < b)
                return -1;
            else if (a > b)
                return 1;
            else
                return 0;
        }
    }

function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        } while (obj);
    } else if (obj.x)
        curleft += obj.x;
    return curleft;
}

function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        do {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        } while (obj);
    } else if (obj.y)
        curtop += obj.y;
    return curtop;
}

function getMouseX(event) {
    if (webBrowser.isIE) { 
        return window.event.clientX + document.documentElement.scrollLeft
            + document.body.scrollLeft;
    } else {
        return event.clientX + window.scrollX;
    }
}

function getMouseY(event) {
    if (webBrowser.isIE) { 
        return window.event.clientY + document.documentElement.scrollTop
            + document.body.scrollTop;
    } else {
        return event.clientY + window.scrollY;
    }
}

function decode(str) {
    return decodeURIComponent(str).replace(/\+/g," ");
}

function encode(str) {
    return encodeURIComponent(str).replace(/\+/g," ");
}

function doHeaderSearch() {
    // if (!validateLocation(true))
    //     return false;
    var location = document.formHeader.locationHeader.value;
    var entityType = document.formHeader.entityTypeHeader.value;
    var url = "/Explorer?location=" + location + "&entityType=" + entityType;
    var words = document.formHeader.locationTextHeader.value;
    if (words.length > 0 && words.length < 3) {
        valert("Words must be more than 2 letters.")
        return false;
    }
//valert(getLocationText(location));
    if (location) {
        words = words.replace(headerLocationSelector.getLocationText(location), "");
        url += "&useMap=true";
    } else {
        url += "&useMap=false";
    }
    url += "&words=" + words;
    window.top.location = url;
    return false;
}

/*
function doWordSearch() {
    var newWords = document.wordForm.newWords.value;
    if (newWords.length < 3) {
        valert("Words must be more than 2 letters.")
    } else {
        var url = document.wordForm.currentSearch.value + " " + newWords.replace(/ /, "_");
        window.location = url;
    }
    return false;
}
*/

// credit: http://developer.apple.com/internet/webcontent/examples/styley_source.html
// setStyleByClass: given an element type and a class selector,
// style property and value, apply the style.
// args:
//  t - type of tag to check for (e.g., SPAN)
//  c - class name
//  p - CSS property
//  v - value
var ie = (document.all) ? true : false;

function setStyleByClass(t,c,p,v){
    var elements;
    if(t == '*') {
        // '*' not supported by IE/Win 5.5 and below
        elements = (ie) ? document.all : document.getElementsByTagName('*');
    } else {
        elements = document.getElementsByTagName(t);
    }
    for(var i = 0; i < elements.length; i++){
        var node = elements.item(i);
        if (node.className.indexOf(c) >= 0)
            eval('node.style.' + p + " = '" +v + "'");
    }
}

   function expandImageL(img) {
        img.style.position = "absolute";
        img.style.left = (findPosX(img) + img.offsetWidth/2 - img.offsetWidth * 75 / 90) + "px";
        img.style.top = (findPosY(img) + 45/2 - 75/2) + "px";
        img.height = "75";
    }

   function expandImage(img) {
if (webBrowser.isSafari || webBrowser.isOpera) return;
        img.style.position = "absolute";
        //img.style.left = (findPosX(img) + img.offsetWidth/2 - img.offsetWidth * 75 / 90) + "px";
        img.style.left = (findPosX(img) - img.offsetWidth * 75 / 90) + "px";
        img.style.top = (findPosY(img) + 45/2 - 75/2) + "px";
        img.height = "75";
    }

    function collapseImage(img) {
if (webBrowser.isSafari) return;
        img.style.position = "";
        img.style.left = "";
        img.style.top = "";
        img.height = "45";
    }


function goBack() {
    var entityType = document.form.entityType.value;
    window.location = "/Explorer?mode=back&entityType=" + entityType;
}

var activeButtons = new Object();
function turnOn(a) {
    var keys = a.className.match(/rokey-(\w+)/);
    if (keys) {
        var key = keys[1];
        var lastA = activeButtons[key];
        if (lastA)
            lastA.firstChild.src = lastA.firstChild.src.replace(/-on/, "-off");

        a.firstChild.src = a.firstChild.src.replace(/-off/, "-on");
        activeButtons[key] = a;
    }
}   
function rollover(a, key) {
    a.firstChild.src = a.firstChild.src.replace(/-off/, "-on");
    if (window.rolloverMonitor)
        window.rolloverMonitor(a, key);
}
function rollout(a, key) {
    if (a.firstChild.src.match(/-on/)) {
        if (!key || activeButtons[key] != a)
            a.firstChild.src = a.firstChild.src.replace(/-on/, "-off");
    }
    if (window.rolloutMonitor)
        window.rolloutMonitor(a, key);
}       

var rolloverIndex = 0;
function initRollovers() {
    var elements = document.getElementsByTagName("A");
    for (var i=0; i < elements.length; i++){
        var node = elements.item(i);
        if (node.className.indexOf("rollover") >= 0) {
            var key = node.className.match(/rokey-(\w+)/)[1];
            initRollover(node, key);
            if (node.firstChild.src.match(/-on/))
                activeButtons[key] = node;
        }
    }
}
function initRollover(node, key) {
    node.onmouseover = function() { rollover(this,key); };
    node.onmouseout = function() { rollout(this,key); };
}

var imgs = new Array();
function newImage(src) {
    var img = new Image();
    img.src = "/ui/media/" + src;
    imgs.push(img);
    return img;
}

newImage("nav/portal-on.gif"); newImage("nav/portal-off.gif");
newImage("nav/profile-on.gif"); newImage("nav/profile-off.gif");
newImage("nav/photos-on.gif"); newImage("nav/photos-off.gif");
newImage("nav/journals-on.gif"); newImage("nav/journals-off.gif");
newImage("nav/guides-on.gif"); newImage("nav/guides-off.gif");
newImage("nav/messages-on.gif"); newImage("nav/messages-off.gif");
newImage("nav/members-on.gif"); newImage("nav/members-off.gif");
newImage("nav/discussions-on.gif"); newImage("nav/discussions-off.gif");

function showDialog(title, body) {
    var dialog = document.getElementById("dialog");
    findElementById("dialogTitle", dialog).innerHTML = title;
    findElementById("dialogBody", dialog).innerHTML = body;
    dialog.style.display = "";
}

function hideDialog() {
    var dialog = document.getElementById("dialog");
    dialog.style.display = "none";
}

function getRadioSelection(field) {
    for (var j=0; j < field.length; j++) {
        if (field[j].checked)
            return field[j].value;
    }
    return "";
}

    function getComFrameMessage() {
        var response = window.comFrame.document.body.innerHTML;
        response = response.replace(/<PRE>/i, '');
        response = response.replace(/<\/PRE>/i, '');
        return response;
    }


    function showMainMedia(href, event, popup) {
        var url = "/ui/PhotoZoomer.html?src=" + encode(href);
        window.open(url, "Original", "width=800,height=600,scrollbars=no,resizable=yes");
            
        cancelEvents(event);
        return false;
    }   

    function adjustTextToHeight(textNode, sizeNode, maxHeight) {
        var text = textNode.innerHTML;
        for (var j=0; j < 100 && sizeNode.offsetHeight > maxHeight; j++) {
            text = text.substring(0, text.length - 8);
            var k = text.lastIndexOf(" ");
            if (k > text.length * 19 / 20)
                text = text.substring(0,k);
            textNode.innerHTML = text + "...";
        }
    }


/*****************************/
/** XML Web Services */
/*****************************/

if (window.ActiveXObject && !window.XMLHttpRequest) {
  window.XMLHttpRequest = function() {
    var msxmls = new Array(
      'Msxml2.XMLHTTP.5.0',
      'Msxml2.XMLHTTP.4.0',
      'Msxml2.XMLHTTP.3.0',
      'Msxml2.XMLHTTP',
      'Microsoft.XMLHTTP');
    for (var i = 0; i < msxmls.length; i++) {
      try {
        return new ActiveXObject(msxmls[i]);
      } catch (e) {
      }
    }
    return null;
  };
}

function sendRequest(url, data, callback) {
    document.body.style.cursor = "wait";

    var method = 'POST';
    var async = true;

    var xport = new XMLHttpRequest();
    xport.open(method, url, async);
    xport.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xport.onreadystatechange = function() {
        if (xport.readyState == 4 && xport.status == 200) {
            var response = xport.responseXML;
            if (response == null) {
                // nice to tell user when it fails, but this shows during normal nav interrupting process
                //valert("There was a problem connecting to the server!");
            } else {
                if (callback) {
                    callback(response);
                } else {
                    var result = response.getElementsByTagName('result')[0];
                    var error = getElementText("error", response);
                    error = decode(error);
                    var event = getElementText("event", response);
                    eval(event + "Handler(result, error);");
                }
            }
            if (window.document)
                window.document.body.style.cursor = "auto";
        }
    }
    xport.send(data);
}

function getElementText(name, node)  {
    var elems = node.getElementsByTagName(name);
    if (elems.length == 0)
        return "";
    else
        return elems[0].firstChild.data;
}

    function delegateCallback(obj, method) {
        if (! (method instanceof Function))
            method = obj[method];

        return function() {
            method.apply(obj, arguments);
        };
    }

function validateLocation() {
    return locationSelector.isValid();
}

function showLocationSelector() {
    locationSelector.showLocationSelector();
}

function valert(s) {
    alert(s);
/*
    var area = document.createElement("DIV");
    window.document.body.appendChild(area);
    area.style.border = "solid 2px #4a760a";
    area.style.backgroundColor = "#ffffff";
    area.style.margin = "10px";
    area.style.padding = "10px";
    area.style.position = "absolute";
    area.style.top = "200px";
    area.style.left = "400px";
    s += '<br><br><button type="button" onclick="window.close();"><img src="/ui/media/ok.png"></button>';
    area.innerHTML = s;
*/
}


var monthLabels = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];

function formatDate(d) {
    var mon = monthLabels[d.getMonth()];
    var s = mon + " " + d.getDate();
    if (new Date().getFullYear() != d.getFullYear())
        s += ", " + d.getFullYear();
    return s;
}

function formatDateRecent(d) {
    var mon = monthLabels[d.getMonth()];
    var day = d.getDate();
    var h = d.getHours();
    var m = d.getMinutes();
    if (day < 10) day = "&nbsp;" + day;
    if (h < 10) h = "&nbsp;" + h;
    if (m < 10) m = "0" + m;
    return mon + " " + day + " " + h + ":" + m;
}


function parseDate(s) {
    s.match(/(..)-(..)-(..) (..):(..)/);
    var d = new Date();
    var y = parseInt(RegExp.$1);
    if (y < 50) 
        y += 2000;
    else y += 1900;
    d.setYear(y);
    d.setMonth(RegExp.$2 - 1);
    d.setDate(RegExp.$3);
    d.setHours(RegExp.$4);
    d.setMinutes(RegExp.$5);
    return d;
}
