// *************
// portal
// *************

    var popupReady = false;
    var popupLoading = false;

    /* user clicks Change Location */
    function changeLocation() {
        if (popupReady) {
            showChangeLocation();
        } else {
            popupLoading = true;
            // do it early
            if (webBrowser.isSafari)
                showChangeLocation();
            window.locationPopup.location = '/Locations?event=displayPopup';
        }
    }

    /* called by LocationPopup onload */
    function loadLocationPopup() {
        if (!popupReady && popupLoading) {
            showChangeLocation();
            popupReady = true;
            popupLoading = false;
        }
    }

    /* shown on click if ready, or after a load cycle via frame onload via loadLocationPopup */
    function showChangeLocation() {
        var area = document.getElementById("setLocationArea");
        area.style.display = "";
        var pp = document.getElementById("helpArea");
        area.style.top = findPosY(pp) + "px";
        area.style.left = findPosX(pp) + "px";
        //window.locationPopup.document.form.locationText.focus();
    }

    function locationSelected(location) {
        if (location)
            window.top.location = "/Portal?location="+location;
       document.getElementById("setLocationArea").style.display = "none";
    }

    function locationChangeHandler(id, value) {
    }

// *************
// portlets
// *************

var portlets = new Array();
var offX = 0;
var offY = 0;
var activePortlet = "";
var saveQ = new Array();
var moveMode = false;
var pageWidth = 0;
var BASE_PAGE_HEIGHT = 930;
var pageHeight = BASE_PAGE_HEIGHT;
var collision = false;
var TOP_MARGIN = 135;
var LEFT_MARGIN = 30;

var SNAP_GRID_W = 10;
var SNAP_GRID_H = 10;


function dragGo(event) {
    getPortlet(activePortlet).dragGo(event);
}
function dragStop(event) {
    getPortlet(activePortlet).dragStop();
}

function getPortlet(name) {
    for (var i=0; i < portlets.length; i++)
        if (portlets[i].name == name)
            return portlets[i];
    return null;
}

function Portlet(pid, title, page, x, y, entityType, displayMode, resultCount, readOnly, canChange, titleImageSrc) {
    this.pid = pid;
    this.name = idToName(pid);
    this.page = page;
    this.entityType = entityType;
    this.editMode = false;
    this.titleImageSrc = titleImageSrc;
    moveMode = false;
    this.readOnly = readOnly;
    this.canChange = canChange;
    this.displayMode = displayMode;
    this.itemIndex = 0;

    // persistent vars
    this.title = this.prepareTitle(decode(title));
    this.resultCount = resultCount;
    this.x = x;
    this.y = y;

    this.oldTitle = this.title;
    this.oldResultCount = this.resultCount;
    this.oldX = this.x;
    this.oldY = this.y;

    portlets[portlets.length] = this;

    this.showText = (entityType != '2');
    this.renderPortlet();

    if (displayMode.indexOf('Slideshow') >= 0) {
        var html;
        if (displayMode == 'Large Slideshow') 
            new Slideshow(this.contentArea, "profile=" + pid, this.showText, this.entityType, this.getLargeSlideshowHtml(), 250, 190, false);
        else if (entityType == '2')
            new Slideshow(this.contentArea, "profile=" + pid, this.showText, this.entityType, this.getSmallSlideshowHtml(), 250, 190, false);
        else
            new Slideshow(this.contentArea, "profile=" + pid, this.showText, this.entityType, this.getSmallSlideshowHtml(), 100, 75, true);
    } else {
        new ResultList(this.contentArea, "profile=" + pid, resultCount);
    }

    this.renderFrame();
}

Portlet.prototype.getSmallSlideshowHtml = function() {
    var html = "";
    html += '<table cellspacing="0" cellpadding="0" width="255"><tr valign="top">';
    html += '<td width="210" height="26">&nbsp;<a id="titleAnchor" target="_top" style="font-weight:bold; font-size:13px;">Loading...</a></td>';
    html += '<td width="45" style="padding:3px" style="-moz-user-select:none" onselectionstart="return false"><nobr>';
    html += '<a href="#" onclick="return false" id="movePreviousButton"><img height="18" src="/ui/media/arrow-left-small.png" alt="Previous" border="0"/></a>&nbsp;';
    html += '<a href="#" onclick="return false" id="moveNextButton"><img height="18" src="/ui/media/arrow-right-small.png" alt="Next" border="0"/></a>';
    html += '</nobr></td></tr>';
    if (this.showText)
        html += '<tr><td style="padding:5px; font-size:13px;" colspan="2" id="textArea"></td></tr>'
    html += '<tr><td colspan="2" align="center"><div id="imageArea"></div></td></tr> </table>';
    return html;
}

Portlet.prototype.getLargeSlideshowHtml = function() {
    var html = "";
    html += '<table cellspacing="0" cellpadding="5" width="533"><tr valign="top">';
    html += '<td align="center"><div id="imageArea"></div></td>';
    html += '<td> <table cellpadding="0" cellspacing="0"><tr valign="top">';
    html += '<td id="titleArea" width="198"><a id="titleAnchor" target="_top" style="font-weight:bold; font-size:13px;">Loading...</a></td>';
    html += '<td width="50" align="right" style="padding:3px" style="-moz-user-select:none" onselectionstart="return false"><nobr>';
    html += '<a href="#" onclick="return false" id="movePreviousButton"><img height="18" src="/ui/media/arrow-left-small.png" alt="Previous" border="0"/></a>&nbsp;';
    html += '<a href="#" onclick="return false" id="moveNextButton"><img height="18" src="/ui/media/arrow-right-small.png" alt="Next" border="0"/></a>';
    html += '</nobr></td></tr>';
    if (this.showText) {
        html += '<tr><td width="248" height="165" valign="top" class="';
        if (this.entityType == '6')
            html += 'guide-bg ';
        else if (this.entityType == '7')
            html += 'journal-bg ';
        html += 'portletText" colspan="2" id="textArea"></td></tr>';
        //html += '<tr id="userArea" style="display:none"><td align="right"><a><img id="userPicture" height="75"></a></td><td style="padding-left:10px"><nobr>Contributed by:</nobr><br><a id="usernameAnchor">user</a></td></tr>';
    }
    html += '</table> </td> </tr> </table>';
    return html;
}

function slideshowFrameRendering(slideshow, result) {
    if (slideshow.showText && !slideshow.smallMode) {
        var media = result.getElementsByTagName("media");
        if (media.length == 0) {
            findElementById("imageArea", slideshow.slideshowArea).parentNode.style.display = "none";
            findElementById("textArea", slideshow.slideshowArea).width = 532;
            findElementById("titleArea", slideshow.slideshowArea).width = 482;
        } else {
            findElementById("imageArea", slideshow.slideshowArea).parentNode.style.display = "";
            findElementById("imageArea", slideshow.slideshowArea).parentNode.width= 270;
            findElementById("textArea", slideshow.slideshowArea).width = 258;
            findElementById("titleArea", slideshow.slideshowArea).width = 218;
        }
/*
        if (slideshow.entityType == '7') {  // journals only
            var props = result.getElementsByTagName("property");
            for (var j=0; j < props.length; j++) {
                if (props[j].getAttribute("name") == 'Author') {
                    var author = props[j];
                    var userPicArea = findElementById("userArea", slideshow.slideshowArea);
                    userPicArea.style.display = "";
                    var photo = author.getAttribute("photo");
                    findElementById("userPicture", userPicArea).parentNode.href = author.getAttribute("link");
                    findElementById("userPicture", userPicArea).src = author.getAttribute("photo");
                    findElementById("usernameAnchor", userPicArea).href = author.getAttribute("link");
                    findElementById("usernameAnchor", userPicArea).innerHTML = decode(author.firstChild.data);
                }
            }
        } else {
            findElementById("userArea", slideshow.slideshowArea).style.display = "none";
        }
*/
    }
}

Portlet.prototype.renderPortlet = function() {
    var portletArea = document.createElement("div");
    document.getElementById("mainBodyArea").appendChild(portletArea);
    portletArea.id = this.name;
    portletArea.style.position = "absolute";
    portletArea.style.top = this.y + "px";
    portletArea.style.width = "100px";
    portletArea.style.height = "100px";
    portletArea.style.left = this.x + "px";
    portletArea.className = "portlet plainPortlet";
    this.portletArea = portletArea;

    var confPart = '<table cellpadding="3" class="portletConfig"><tr valign="top"><td><nobr>Title: <input type="text" size="25" onKeyUp="getPortlet(\'' + this.name + '\').updateTitle()" id="title_input_' + this.pid + '" value="' + this.title + '"></nobr><br><br>';

    // conditional inclusion
    if (this.resultCount > -1)
        confPart += 'Result Count: <input type="text" size="2" id="result_count_input_' + this.pid + '" value="' + this.resultCount + '" onchange="getPortlet(\'' + this.name + '\').updateResultCount()"><br><br>';

    if (!this.readOnly)
        confPart += '<button onclick="getPortlet(\'' + this.name + '\').toggleEdit()" class="icon"><img id="' + this.name + '_editLink" src="ui/media/save-LG.png"></button>';
    confPart += '<button onclick="getPortlet(\'' + this.name + '\').remove()" class="icon"><img src="ui/media/remove-LG.png"></button></td></tr></table>';

    var startPart = '<table cellpadding="0" cellspacing="0"><tr class="Title"><td width="8"><img src="ui/media/portal-tl.png"></td><td class="titleCell" id="titleArea_'+this.name+'"';
    if (!this.readOnly)
        startPart += ' style="cursor:move;" onMouseDown="getPortlet(\'' + this.name + '\').dragStart(event)"';
    startPart += '><nobr><img src="' + this.titleImageSrc + '">&nbsp;<span id="title_' + this.pid + '">' + this.title + '</span></nobr></td><td width="44" class="titleCell">';
    if (!this.readOnly && this.canChange)
        startPart += '<a onclick="getPortlet(\'' + this.name + '\').toggleEdit()" class="editLink"><img id="' + this.name + '_editLink" src="/ui/media/portlet-edit-tb.png"></a>';
    else
        startPart += '&nbsp;';
    startPart += '</td><td width="9"><img src="ui/media/portal-tr.png"></td></tr><tr style="display:none" valign="top"><td colspan="4" id="' + this.name + '_conf">';
    // left frame
    var frame = '<table cellpadding="0" cellspacing="0"><tr><td bgcolor="#cecece" width="1"><img width="1" src="/ui/media/empty.gif"></td> <td width="266">';
    // content area
    frame += '<div style="padding:3px 5px" id="contentArea' + this.name + '"></div>';
    // right frame
    frame += '</td> <td bgcolor="#cecece" width="1"><img width="1" src="/ui/media/empty.gif"></td> </tr></table>';
    // bottom frame
    var bottomW = (this.displayMode == 'Large Slideshow') ? 528 : 251;
    frame += '<table cellspacing="0" cellpadding="0"> <tr id="portletFooterMoving" style="display:none"> <td><img src="/ui/media/portal-move-bl.png"></td> <td><img width="' + bottomW + '" height="9" src="/ui/media/portal-move-b.png"></td> <td><img src="/ui/media/portal-move-br.png"></td> </tr> <tr id="portletFooter"> <td><img src="/ui/media/portal-bl.png"></td> <td><img width="' + bottomW + '" height="9" src="/ui/media/portal-b.png"></td> <td><img src="/ui/media/portal-br.png"></td> </tr> </table>';

    var endPart = '</td></tr></table><table cellpadding="0" cellspacing="0"><tr><td colspan="4" id="' + this.name + '_body">' + frame + '</td></tr></table>';

    this.portletArea.innerHTML = startPart + confPart + endPart;
    this.contentArea = findElementById("contentArea" + this.name, this.portletArea);
}

Portlet.prototype.renderFrame = function() {
    if (this.displayMode == 'List') {
        this.height = (20 * this.resultCount + 10) + "px";
        this.width = "270px";
/*
    } else if (document.getElementById("helpArea")) {
        this.height = "150px";
        this.width = "547px";
*/
    } else {
        if (this.displayMode == 'Slideshow') {
            this.width = "270px"; 
        } else if (this.displayMode == 'Large Slideshow') {
            this.width = "547px"; 
        }
        this.height = "220px";

        var slideText = findElementById("slideArea", this.portletArea);
        if (slideText) {
            adjustTextToHeight(slideText.firstChild, slideText, 150);
        }
    }
    if (this.width) {
        this.portletArea.style.width = this.width;
        findElementById("titleArea_"+this.name, this.portletArea).style.width = parseInt(this.width)-63;
    }
    if (this.height)
        this.portletArea.style.height = this.height;

    this.setSize();
    window.marginConfig();
}

function resetSize() {
    pageHeight = BASE_PAGE_HEIGHT;
    pageWidth = 0;
    for (i=0; i < portlets.length; i++)
        portlets[i].setSize();
}

Portlet.prototype.setSize = function() {
    var right = parseInt(this.x) + parseInt(this.width);
    if (right > pageWidth) 
        pageWidth = right;

    var bottom = parseInt(this.y) + parseInt(this.height);
    if (bottom > pageHeight) 
        pageHeight = bottom;
}


Portlet.prototype.toggleEdit = function() {
    if (!this.readOnly) {
        if (this.editMode) {
            document.getElementById(this.name + "_body").parentNode.style.display = '';
            document.getElementById(this.name + "_conf").parentNode.style.display = 'none';
            this.save();
            this.editMode = false;
            activePortlet = "";
            this.portletArea.style.width = this.width;
            this.portletArea.style.height = this.height;
            document.getElementById("title_" + this.pid).style.cursor = "move";
            document.getElementById(this.name + "_editLink").src = "ui/media/portlet-edit-tb.png";
            //document.getElementById(this.name + "_editLink").innerHTML = "[edit]";
            this.portletArea.className = "portlet plainPortlet";
        } else {
/*
            // capture w/h
            this.width = this.portletArea.offsetWidth;
            this.height = this.portletArea.offsetHeight;
*/

            document.getElementById(this.name + "_body").parentNode.style.display = 'none';
            document.getElementById(this.name + "_conf").parentNode.style.display = '';
            this.editMode = true;
            if (activePortlet != "" && activePortlet != this.name)
                getPortlet(activePortlet).toggleEdit();
            activePortlet=this.name;

            this.portletArea.style.width = this.width;
            this.portletArea.style.height = 140;
            document.getElementById("title_" + this.pid).style.cursor = "default";
            document.getElementById(this.name + "_editLink").src = "ui/media/portlet-save-tb.png";
            this.portletArea.className = "portlet editPortlet";
        }
    }
}

Portlet.prototype.prepareTitle = function(title) {
    var maxLen = 25;
    if (this.displayMode == 'Large Slideshow')
        maxLen = 35;
    if (this.canChange)
        maxLen -= 4;
    if (title.length > maxLen)
        title = title.substring(0,maxLen);
    return title;
}

Portlet.prototype.updateTitle = function() {
    var titleField = document.getElementById("title_input_" + this.pid);
    this.title = this.prepareTitle(titleField.value);
    titleField.value = this.title;
    document.getElementById("title_" + this.pid).innerHTML = this.title;
}

Portlet.prototype.updateResultCount = function() {
    var field = document.getElementById("result_count_input_" + this.pid);
    if (field)
        this.resultCount = field.value;
}

Portlet.prototype.save = function() {
    this.updateTitle();
    this.updateResultCount();

    // if change, save
    if (this.oldX != this.x || this.oldY != this.y || this.oldResultCount != this.resultCount || this.oldTitle != this.title) {
if (this.resultCount == 0) valert("RC0:"+this.title);
        var params = "event=savePortlet&portlet=" + this.pid + "&name=" + encode(this.title) + "&x=" + this.x + "&y=" + this.y + "&resultCount=" + this.resultCount;
        sendRequest("/Portal", params, function() { } );

        this.oldResultCount = this.resultCount;
        this.oldTitle = this.title;
        this.oldX = this.x;
        this.oldY = this.y;
    }
}

Portlet.prototype.dragGo = function(event) {
    //if (moveMode || this.resizeMode) {
    if (moveMode) {
        if (webBrowser.isIE) {
            mouseX = event.clientX;
            mouseY = event.clientY;
        } else {
            mouseX = event.pageX;
            mouseY = event.pageY;
        }
        buttonDown = event.button;

        if (scrolling)
            return;
        drag();
    }
}

function drag() {
        var x = mouseX;        
        var y = mouseY;        

        var objRef = document.getElementById(activePortlet);
        if (!objRef)
            return;
        if (offX == 0 && offY == 0) {
            offX = x - objRef.offsetLeft;
            offY = y - objRef.offsetTop;
        }

/*
        if (this.resizeMode) {
            objRef.style.width = x - objRef.offsetLeft;
            objRef.style.height = y - objRef.offsetTop;
        } else {
*/
            x = x - offX;
            y = y - offY;

            if (y < TOP_MARGIN)
                y = TOP_MARGIN;

            goUp();
            goDown();

            y = TOP_MARGIN + Math.round((parseInt(y) - TOP_MARGIN) / SNAP_GRID_H) * SNAP_GRID_H;
            x = LEFT_MARGIN + Math.round((parseInt(x) - LEFT_MARGIN) / SNAP_GRID_W) * SNAP_GRID_W;

            collision = false;
	    for (i=0; i < portlets.length; i++) {
                if (activePortlet != portlets[i].name) {
                    var pref = document.getElementById(portlets[i].name);
                    var w = objRef.offsetWidth;
                    var h = objRef.offsetHeight;
                    var px = pref.offsetLeft;
                    var pw = pref.offsetWidth;
                    var py = pref.offsetTop;
                    var ph = pref.offsetHeight;

                    var startX = x >= px && x <= px+pw;
                    var endX = x+w >= px && x+w <= px+pw;
                    var allX = x <= px && x+w >= px+pw;
                    var startY = y >= py && y <= py+ph;
                    var endY = y+h >= py && y+h <= py+ph;
                    var allY = y <= py && y+h >= py+ph;
                    if (startX || endX || allX) {
                        if (startY || endY || allY) {
                            collision = true;
    //document.getElementById("title_" + this.pid).innerHTML = pref.style.zIndex;
                            break;
                        }
                    }
/*
                    if (startX || endX || allX)
                        if (startY) y=py+ph;
                        else if (endY) y=py;
                        else if (allY) return;
                    if (startY || endY || allY)   
                        if (startX) x=px+pw;
                        else if (endX) x=px;
                        else if (allX) return;
*/
                }
            }

            objRef.style.top = y;
            objRef.style.left = x;

            if (collision) {
                var cursor = document.getElementById("cursorNoDrop");
                cursor.style.top = mouseY;
                cursor.style.left = mouseX+10;
                cursor.style.display = "";
            } else {
                var cursor = document.getElementById("cursorNoDrop");
                cursor.style.display = "none";
            }
//        }
}

var scrollDelay = 1;
var scrollSize = 2;
var scrollEdge = 50;
var scrolling = false;

function goUp() {
    scrolling = true;
    var top = document.body.scrollTop;
    if (mouseY - top < scrollEdge) {
        window.scrollBy(0, -1 * scrollSize);
        mouseY -= scrollSize;
        setTimeout(drag, scrollDelay);
    } else {
        scrolling = false;
    }
}

function goDown() {
    scrolling = true;
    var top = document.body.scrollTop;
    var innerHeight;

    //document.getElementById("title_" +activePortlet.replace(/portlet_/,"")).innerHTML = mouseY+":"+top+":"+getWindowHeight();
    if (mouseY - top > getRealWindowHeight() - scrollEdge) {
        window.scrollBy(0, scrollSize);
        mouseY += scrollSize;
        setTimeout(drag, scrollDelay);
    } else {
        scrolling = false;
    }
}

Portlet.prototype.dragStart = function(event) {
    if (this.editMode)
        return;

    // turn footer/margin off
    var header = document.getElementById("header");
    header.style.width = header.offsetWidth + "px";
    document.getElementById("footer").style.visibility = "hidden";
    document.getElementById("marginRightArea").style.display = "none";

    // add height
    pageHeight += 500;
    marginConfig();

    for (var j=0; j < saveQ.length; j++) {
        // if follow-on drag, cancel the save
        if (saveQ[j] == this.name)
            saveQ.splice(j, 1);
    }

    var x, y;

        if (webBrowser.isIE) {
            x = window.event.clientX + document.documentElement.scrollLeft
                + document.body.scrollLeft;
            y = window.event.clientY + document.documentElement.scrollTop
                + document.body.scrollTop;
        } else {
            x = event.clientX + window.scrollX;
            y = event.clientY + window.scrollY;
        }

//        if ((objRef.offsetWidth - (x - objRef.offsetLeft)) + (objRef.offsetHeight - (y - objRef.offsetTop)) < 20) {
//		    this.resizeMode = true;
//            document.body.style.cursor = "se-resize";
//        }

        if ((y - this.portletArea.offsetTop < 20) && ((this.portletArea.offsetWidth - (x - this.portletArea.offsetLeft)) > 15))
            moveMode = true;

	if (moveMode) {
            offX = 0;
	    offY = 0;

            if (webBrowser.isIE) {
	        document.attachEvent("onmousemove", dragGo);
	        document.attachEvent("onmouseup", dragStop);
            } else {
	        document.addEventListener("mousemove", dragGo, true);
	        document.addEventListener("mouseup", dragStop, true);
	        event.preventDefault();
            }

            this.portletArea.style.opacity="0.8";
            this.portletArea.style.filter="alpha(opacity=80)";
            this.portletArea.style.zIndex=5;

            findElementById("portletFooter", this.portletArea).style.display="none";
            findElementById("portletFooterMoving", this.portletArea).style.display="";

            activePortlet=this.name;
            for (i=0; i < portlets.length; i++) {
                var objRef = document.getElementById(portlets[i].name);
                if (portlets[i].name == activePortlet) {
                    objRef.className = "portlet movePortlet";
                } else {
                    objRef.className = "portlet nomovePortlet";
                }
            }
        }
}

Portlet.prototype.dragStop = function(event) {
    if (moveMode) {
        if (collision) {
            this.portletArea.style.left = this.x;
            this.portletArea.style.top = this.y;
        } else {
    	    this.x = parseInt(this.portletArea.style.left);
            this.y = parseInt(this.portletArea.style.top);
        }
        this.portletArea.style.opacity="1.0";
        this.portletArea.style.filter="alpha(opacity=100)";
        this.portletArea.style.zIndex=1;
        var cursor = document.getElementById("cursorNoDrop");
        cursor.style.display = "none";
	moveMode = false;
    }
/*
    if (this.resizeMode) {
//        document.body.style.cursor = "auto";
        this.width = parseInt(objRef.style.width);
        this.height = parseInt(objRef.style.height);
        this.resizeMode = false;
    }
*/
	
    offX = 0;
    offY = 0;

    if (webBrowser.isIE) {
        document.detachEvent("onmousemove", dragGo);
        document.detachEvent("onmouseup", dragStop);
    } else {
        document.removeEventListener("mousemove", dragGo, true);
        document.removeEventListener("mouseup", dragStop, true);
    }

    if (!collision) {
        // prepare to save it
        saveQ.push(activePortlet);

        // delay 1s or so to save
        setTimeout(moveSave, 1500);
    }

    findElementById("portletFooter", this.portletArea).style.display="";
    findElementById("portletFooterMoving", this.portletArea).style.display="none";

    // finish moveMode
    activePortlet="";

    //this.portletArea.className = "portlet";
    for (i=0; i < portlets.length; i++)
        document.getElementById(portlets[i].name).className = "portlet plainPortlet";

    // turn footer on
    document.getElementById("footer").style.visibility = "";
    document.getElementById("marginRightArea").style.display = "";

    // regnerate height
    resetSize();
    marginConfig();

    var header = document.getElementById("header");
    header.style.width = "";

}

function moveSave() {
    while (saveQ.length > 0) {
    //if (!moveMode)
        //this.save();
        getPortlet(saveQ.pop()).save();
    }
}

function idToName(id) {
    return "portlet_" + id;
}

Portlet.prototype.remove = function() {
    this.portletArea.parentNode.removeChild(this.portletArea);

    for (i=0; i < portlets.length; i++)
        if (portlets[i].name == activePortlet)
            portlets.splice(i, 1);
    activePortlet = "";

    sendRequest("/Portal?event=removePortlet&portlet="+this.pid, null, portletRemoved);
}

function portletRemoved() { 
}
