var menuTop = 45;
var menuLeft = 400;

var domSMenu = null;
var oldDomSMenu = null;
var t = 0;
var lDelay = 3;
var lCount = 0;
var pause = 100;

function popMenu(menuNum){
    if (isDHTML) {

        t = 2;
        if (oldDomSMenu) {
            oldDomSMenu.visibility = 'hidden'; 
            oldDomSMenu.zIndex = '0'; 
            t = 2; 
            lCount = 0;
        }

        var idMenu = 'menuHead';
        var domMenu = findDOM(idMenu,0);

        var idMenuOpt = 'menuHead' + menuNum;
        var domMenuOpt = findDOM(idMenuOpt,0);        

        var idSMenu = 'menu' + menuNum;
        var domSMenu = findDOM(idSMenu,1);

        if (isID || isAll) {     
            var menuLeft = (domMenu.offsetLeft) + (domMenuOpt.offsetLeft) + 5;
            var menuTop = (domMenu.offsetTop) + (domMenu.offsetHeight) + 5;
        }
        if (isLayers) {
            var menuLeft = document.layers[idMenu].layers[idMenuOpt].pageX - 5;
            var menuTop = domMenu.pageY + domMenu.clip.height - 5;
        }


        if (oldDomSMenu != domSMenu) {    
            domSMenu.left = menuLeft; 
            domSMenu.top = menuTop;
            domSMenu.visibility = 'visible';
            domSMenu.zIndex = '100';
            oldDomSMenu = domSMenu;
        }


        else { oldDomSMenu = null; }
    }

    else { return null; }
}

function delayHide() {

    if ((oldDomSMenu) && (t == 0)) {

        oldDomSMenu.visibility = 'hidden'; 
        oldDomSMenu.zIndex = '0';
        oldDomSMenu = null;
        lCount = 0; 
        return false;
    }


    if (t == 2) { lCount = 0; return false; }

    if (t == 1) { 
        lCount = lCount + 1;
        if (lDelay <= lCount) { t = 0; }
        if (lDelay >= lCount) { setTimeout('delayHide(' + t + ')',pause); }
    }
}



if (document.layers) {
    origWidth = innerWidth;
    origHeight = innerHeight;
}

function reloadPage() {
    if (innerWidth != origWidth || innerHeight != origHeight) 
        location.reload();
}

if (document.layers) onresize = reloadPage;

function hideDropdowns(){
    //hide the right-hand dropdowns on the edit-stats page
    for (counter = 0; counter <= 15; counter++){
        setVisibility('hide_me_' + counter, 'hidden');
    }
}

function showDropdowns(){
    for (counter = 0; counter <= 15; counter++){
        setVisibility('hide_me_' + counter, 'visible');
    }
    
    setVisibility('fontname_entryText', 'visible');
    setVisibility('fontsize_entryText', 'visible');
}

function setVisibility(objectID,state) {
    var dom = findDOM(objectID,1);
    if (dom != null){
        dom.visibility = state;
    }
}

function toggleVisibility(objectID) {
    var dom = findDOM(objectID,1);
    state = dom.visibility;
    if (state == 'hidden' || state == 'hide' )
        dom.visibility = 'visible';
    else {
        if (state == 'visible' || state=='show')
            dom.visibility = 'hidden'; 
        else 
            dom.visibility = 'visible';
    }
}


function loadIFrame(id, url) {
    //load the contents of a seperate page into a hidden iFrame
    elem = document.getElementById(id);
    if (elem) {
        elem.src = url;
    }
}
function showIFrame(targetId, sourceFrame) {
    document.getElementById(targetId).innerHTML = window.frames[sourceFrame].document.getElementById('theBody').innerHTML;
}



// For going to chat rooms
function goToChatURL(url) {
    if (window.name == 'tagged_chat') {
        window.location.href = url;
    }
    else {
        window.open(url,
            "tagged_chat",
            "height=670,width=985,menubar=no,toolbar=no,status=no,scrollbars=yes,resizable=1");
    }
}

function goToChatRoom(room_id) {
    goToChatURL('/chat.html?room_id=' + room_id);
}

function acceptChatInvite(invite_id) {
    goToChatURL('/chat.html?inv_id=' + invite_id);
    //relaod this page (so the invite goes away) in a bit 
    //(long enough for the person to log on chat)
    setTimeout('location.reload()', 7000); 
}


function debugObj(obj) {
    var x = '';
    for (var el in obj) {
        x += (el + '->' + obj[el] + "\n");
    }
    alert (x);
}



/****************************************************************************/
/* code for AJAX loading of my alerts */
function createRequestObject() {
    if (window.XMLHttpRequest) {
        ro = new XMLHttpRequest();
    } else if (window.ActiveXObject) {
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return ro;
}

var req = createRequestObject();
//use this variable to allow us to skip updating the alert box if nothing
// has changed since last time. this won't help us the first time.
var previousAlertsString = "";

function Countdown(desc, daysAway) {
    this.desc = desc;
    this.daysAway = daysAway;
}

function ChatInvite(userId, displayName, invitationId) {
    this.userId = userId;
    this.displayName = displayName;
    this.invitationId = invitationId;
}

//called periodically by setInterval(). Responsible for initiating the
// XmlHttpRequest
function refreshAlerts() {
    var url = serverURI + '/alerts.html';
   
    // We have to create a new XMLHttpRequest object everytime we want to make a remote call. See Bug # 3461 
    req = createRequestObject();

    req.onreadystatechange = refreshAlertsCallback;
    req.open("GET", url, true);
    req.send(null);

    //var console = document.getElementById("js-messages");
    //console.innerHTML += "hello<br>";
}

//called by the XmlHttpRequest mechanism. responsible for parsing the data
// returned from tagged and calling the function that will actually display
// the alerts box
function refreshAlertsCallback() {
    var numMsg = 0;
    var numInvites = 0;
    var numQuizRes = 0;
    var numProps = 0;
    var numPhotoComments = 0;
    var firstPageProps = 1;
    var hasProps = false;
    var hasPhotoComments = false;    
    var hasTags = false;
    var cdArray = new Array();
    var chatArray = new Array();
 
    if (req.readyState == 4) {
        if (req.status == 200) {

            if (req.responseText === previousAlertsString) {
                return;
            }
            var alerts = req.responseXML.getElementsByTagName("alerts")[0];

            if (hasElt(alerts, "msg")) {
                numMsg = getElt(alerts, "msg");
            }
            if (hasElt(alerts, "inv")) {
                numInvites = getElt(alerts, "inv");
            }
            if (hasElt(alerts, "quiz-res")) {
                numQuizRes = getElt(alerts, "quiz-res");
            }
            if (hasElt(alerts, "props")) {
                numProps = getElt(alerts, "props");
                firstPageProps = getElt(alerts, "props-firstpage");
                if (numProps > 0) {
                    hasProps = true;
                }
            }
            // hasProps = hasElt(alerts, "props")
            if (hasElt(alerts, "photo-comments")) {
                numPhotoComments = getElt(alerts, "photo-comments");
                if (numPhotoComments > 0) {
                    hasPhotoComments = true;
                }
            }           
                       
            hasTags = hasElt(alerts, "tags");            
            
            if (hasElt(alerts, "chat-invites")) {
                var chats = alerts.getElementsByTagName("chat-invites")[0];
                if (chats) {
                    for (i = 0; i < chats.childNodes.length; i++){
                        //we need to skip empty text nodes in Mozilla
                        if (chats.childNodes[i].nodeType == 1) {
                            var chat = chats.childNodes[i];
                            var chatId = chat.getAttribute("invId");
                            var chatUserId = chat.getAttribute("userId");
                            var displayName = chat.getAttribute("displayName");
                            var chatObj = new ChatInvite(chatUserId, displayName, chatId);
                            chatArray[chatArray.length] = chatObj;
                        }
                    }
                }
            }
            
            if (hasElt(alerts, "countdowns")) {
                var countdowns = alerts.getElementsByTagName("countdowns")[0];
                if (countdowns) {
                    for (i = 0; i < countdowns.childNodes.length; i++){
                        //we need to skip empty text nodes in Mozilla
                        if (countdowns.childNodes[i].nodeType == 1) {
                            var countdown = countdowns.childNodes[i];
                            var desc = countdown.getAttribute("desc");
                            var daysAway = countdown.getAttribute("days");
                            var cntdwnObj = new Countdown(desc, daysAway);
                            cdArray[cdArray.length] = cntdwnObj;
                        }
                    }
                }
            }
            
            numBirthdays = hasElt(alerts, "birthdays");  
            
            displayAlerts(numInvites, numMsg, hasProps, hasPhotoComments, hasTags, cdArray, 
                    chatArray, numQuizRes, numProps, firstPageProps, numPhotoComments, numBirthdays);
            displayIfHasAlerts(numInvites, numMsg, hasProps, hasPhotoComments, hasTags, cdArray, 
                    chatArray, numQuizRes, numBirthdays);                    
                    
            previousAlertsString = req.responseText;
        }
    }

}

function displayAlerts(numInvites, numMsg, hasProps, hasPhotoComments, hasTags,
        countdowns, chatInvites, numQuizRes, numProps, firstPageProps, 
        numPhotoComments, numBirthdays) {
    var html = "";
    var alertsBox = document.getElementById("alerts");
    var alertsContainer = document.getElementById("alerts-box");
    var spacerForChatAlerts = "";

    if (!alertsBox || !alertsContainer) return;
 
    if (numInvites > 0 || numMsg > 0 || hasProps || hasPhotoComments || hasTags
            || countdowns.length > 0 || chatInvites.length > 0
            || numQuizRes > 0 || numBirthdays > 0) {
                
        
        //html += "<div id=\"alerts_title\">"
        //        + "<img src=\"" + staticURI + "/images/my_alerts_head.gif\""

        
        //Chat invitations
        for (i = 0; i < chatInvites.length; i++) {
            html += "<div class='invites'><img src=\"" + staticURI + "/images/alert_new_chat.gif\" alt='' border='0'>&nbsp;<a target=\"tagged_main\" href=\"/mypage.html?uid=" 
                    + chatInvites[i].userId + "\">"
                    + chatInvites[i].displayName + "</a> wants to "
                    + "<a href=\"javascript:acceptChatInvite(" 
                    + chatInvites[i].invitationId + ")\">chat</a></div>";
        }
        
        //Pending connections
        if (numInvites > 0) {
            var invitesStr = (numInvites > 1) ? "invites" : "invite";
            html += "<div class='invites'><img src=\"" + staticURI + "/images/alert_new_invites.gif\" alt='' border='0'>&nbsp;<strong>You have " 
                    + " <a target=\"tagged_main\" href=\"/new_invites.html\">" 
                    + numInvites + " " + invitesStr + " waiting!</a></div>";
        }
        
        //Countdowns
        for (i = 0; i < countdowns.length; i++) {
            html += "<div>" 
                    + spacerForChatAlerts
                    + countdowns[i].desc 
                    + " - " + countdowns[i].daysAway + "</div>";
        }
        
        //Messages
        if (numMsg > 0) {
            var msgStr = (numMsg > 1) ? "messages": "message";
            html += "<div class='invites'><img src=\"" + staticURI + "/images/alert_new_messages.gif\" alt='' border='0'>&nbsp;" 
                    + spacerForChatAlerts
                    + "You have "
                    + " <a target=\"tagged_main\" href=\"/inbox.html\">" + numMsg 
                    + " new " + msgStr + "</a></div>";

        }
        
        //Props
        if (hasProps && (numProps > 0)) {
            html += "<div class='invites'><img src=\"" + staticURI + "/images/alert_new_props.gif\" alt='' border='0'>&nbsp;"
                    + spacerForChatAlerts
                    + "<strong>You have "
                    + " <a target=\"tagged_main\" href=\"/myprops.html?pageNum=" + firstPageProps + "\">" + numProps + " new props</a> waiting!</div>";

        }
        
        //Photo Comments
        if (hasPhotoComments && (numPhotoComments > 0)) {
            html += "<div class='invites'><img src=\"" + staticURI + "/images/alert_new_photo_messages.gif\" alt='' border='0'>&nbsp;"
                    + spacerForChatAlerts
                    + "<strong>You have "
                    + " <a target=\"tagged_main\" href=\"/photo_gallery.html\">" + numPhotoComments + " new photo comment(s)</a> waiting!</div>";

        }        
        
        //Tags
        if (hasTags) {
            html += "<div class='invites'>"
                    + spacerForChatAlerts
                    + "<img src=\"" + staticURI + "/images/alert_new_tags.gif\" alt='' border='0'>&nbsp;<strong>You have "
                    + " <a target=\"tagged_main\" href=\"/accept_tags.html\">tags</a> waiting!</div>";

        }

        // Quiz results  
        if (numQuizRes > 0) {
            var quizResStr = (numQuizRes > 1) ? "results" : "result";
            html += "<div class='invites'>"
                    + spacerForChatAlerts
                    + "<img src=\"" + staticURI + "/images/alert_new_quizzes.gif\" alt='' border='0'>&nbsp;You have " 
                    + " <a target=\"tagged_main\" href=\"/my_quiz_takers.html\">" 
                    + numQuizRes + " quiz " + quizResStr + "</a> waiting!</div>";
        }
         
        // Birthdays
        if (numBirthdays > 0) {
            var birthdayStr = (numBirthdays > 1) ? "friends" : "friend";
            html += "<div class='invites'><img src=\"" + staticURI + "/images/alert_new_birthdays.gif\" alt='' border='0'>&nbsp;"
                    + spacerForChatAlerts
                    + "<strong>You have "
                    + " <a target=\"tagged_main\" href=\"/birthdays.html\">" + numBirthdays + " " + birthdayStr + "</a> with a birthday today!</div>";

        } 
        
        alertsBox.innerHTML = html;
        //restore visibility to the box if there was previous nothign
        // to display but now there is
        alertsContainer.style.display = "block";
        
    }
    else {
        //hide the box if there's no alerts to display
        alertsContainer.style.display = "none";
    }
            
}

function displayIfHasAlerts(numInvites, numMsg, hasProps, hasPhotoComments, hasTags,
        countdowns, chatInvites, numQuizRes, numBirthdays) {
    var alertsAreaContainer = document.getElementById("has_alerts_box");
    var alertsTopNavContainer = document.getElementById( "has_alerts_top_nav");
 
    if (numInvites > 0 || numMsg > 0 || hasProps || hasPhotoComments || hasTags
            || countdowns.length > 0 || chatInvites.length > 0
            || numQuizRes > 0 || numBirthdays > 0) {
            	
        if (alertsTopNavContainer) {
            html = '';

            // Pending connections
            if (numInvites > 0) {
                html +=  "&nbsp;<a target=\"tagged_main\" href=\"/new_invites.html\" "
                     + " onmouseover=\"writetxt('You have New Invites!')\" onmouseout=\"writetxt(0)\">" 
                     + "<img src=\"" + staticURI + "/images/main/nav_alert_new_invites.gif\" alt='' border='0'></a>";
            }

            // Messages
            if (numMsg > 0) {
                html += "&nbsp;<a target=\"tagged_main\" href=\"/inbox.html\" "
                     + " onmouseover=\"writetxt('You Have New Messages!')\" onmouseout=\"writetxt(0)\">" 
                     + "<img src=\"" + staticURI + "/images/main/nav_alert_new_messages.gif\" alt='' border='0'></a>";
            }

            // Props
            if (hasProps) {
                html += "&nbsp;<a target=\"tagged_main\" href=\"/myprops.html\" "
                     + " onmouseover=\"writetxt('You Have Props!')\" onmouseout=\"writetxt(0)\">" 
                     + "<img src=\"" + staticURI + "/images/main/nav_alert_new_props.gif\" alt='' border='0'></a>";
            }
            
            // Photo Comments
            if (hasPhotoComments) {
                html += "&nbsp;<a target=\"tagged_main\" href=\"/photo_gallery.html\" "
                     + " onmouseover=\"writetxt('You Have new Comments on your Photo(s)!')\" onmouseout=\"writetxt(0)\">" 
                     + "<img src=\"" + staticURI + "/images/main/nav_alert_new_photo_messages.gif\" alt='' border='0'></a>";
            }            

            // Tags
            if (hasTags) {
                html += "&nbsp;<a target=\"tagged_main\" href=\"/accept_tags.html\" "
                     + " onmouseover=\"writetxt('You Have Tags waiting!')\" onmouseout=\"writetxt(0)\">" 
                     + "<img src=\"" + staticURI + "/images/main/nav_alert_new_tags.gif\" alt='' border='0'></a>";
            }

            // Quiz results
            if (numQuizRes > 0) {
                html += "&nbsp;<a target=\"tagged_main\" href=\"/my_quiz_takers.html\" "
                     + " onmouseover=\"writetxt('Someone took your Quiz!')\" onmouseout=\"writetxt(0)\">" 
                     + "<img src=\"" + staticURI + "/images/main/nav_alert_new_quizzes.gif\" alt='' border='0'></a>";
            }

            // Chat invitations
            if (chatInvites.length > 0) {
                html += "&nbsp;<a target=\"tagged_main\" href=\"/mypage.html\" "
                     + " onmouseover=\"writetxt('Someone wants to chat with you!')\" onmouseout=\"writetxt(0)\">" 
                     + "<img src=\"" + staticURI + "/images/alert_new_chat.gif\" alt='' border='0'></a>";
            }
            
            // Birthdays
            if (numBirthdays > 0) {
                html += "&nbsp;<a target=\"tagged_main\" href=\"/birthdays.html\" "
                     + " onmouseover=\"writetxt('Someone has a birthday!')\" onmouseout=\"writetxt(0)\">" 
                     + "<img src=\"" + staticURI + "/images/alert_new_birthdays.gif\" alt='' border='0'></a>";
            }

            html = '<a class="online_num" href="/home.html"><img src="' + staticURI + '/images/new_alerts.gif" width="85" height="14" alt="" border="0"></a>&nbsp;' + html + "&nbsp;";

            alertsTopNavContainer.innerHTML = html; 
        }

        // restore visibility to the box if there was previous nothign
        // to display but now there is
        if (alertsAreaContainer)
            alertsAreaContainer.style.display = "block";
        if (alertsTopNavContainer)
             alertsTopNavContainer.style.visibility = "visible";
    }
    else {
        // hide the box if there's no alerts to display
        if (alertsAreaContainer)
            alertsAreaContainer.style.display = "none";
        if (alertsTopNavContainer) 
            alertsTopNavContainer.style.visibility = "hidden";            
    }
            
}


function getElt(parent, eltName) {
    var temp = parent.getElementsByTagName(eltName)[0];
    if (temp) {
        if (temp.childNodes.length > 1) {
            return temp.childNodes[1].nodeValue;
        } else {
            return temp.firstChild.nodeValue;            
        }
    }
}

function hasElt(parent, eltName) {
    var temp = parent.getElementsByTagName(eltName)[0];
    return (temp) ? true : false;
}

/**
 *  Function refreshIFrameDiv
 *  If we place an IFrame inside a div, and redeclare the div's inner html,
 *      the IFrame refreshes.
 *  @param String $iFrameDivId Name of Div object in which IFrame resides
 *  @return bool Was the div found?
 */
function refreshIFrameDiv(iFrameDivId) {
    var idiv = document.getElementById(iFrameDivId);
    if (idiv) {
        idiv.innerHTML = idiv.innerHTML;
        return 1;
    } else {
        return 0;
    }
}

var popUpWin=0;
function popUpWindow(URLStr, left, top, width, height) {
return;
   if(popUpWin) {
      if(!popUpWin.closed) popUpWin.close();
   }
   popUpWin = open(URLStr, 'popUpWin', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars,resizable=no,copyhistory=no,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
}

var popUnderWin=0;
function popUnderWindow(URLStr, left, top, width, height) {
return;

   if(popUnderWin) {
      if(!popUnderWin.closed) popUnderWin.close();
   }
   popUnderWin = window.open(URLStr, 'popUnderWin', 'scrollbars=1,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
   popUnderWin.blur();
   window.focus();
}

// toggle between hide and show a div or other element

function toggle(theDiv) {
	if (document.getElementById(theDiv).style.display == 'none')
		 {
			 document.getElementById(theDiv).style.display = 'block';
			 document.getElementById(theDiv).style.display = '';
		 }
	else
		{
		 document.getElementById(theDiv).style.display = 'none';
		 }
}

function showEl(elId) {
    var el =  document.getElementById(elId);
    if (el && el.style) el.style.display = 'block';
}
function hideEl(elId) {
    var el =  document.getElementById(elId);
    if (el && el.style) el.style.display = 'none';
}



  function toggleVis(theDiv) {
	if (document.getElementById(theDiv).style.visibility == 'hidden')
		 {
			 document.getElementById(theDiv).style.visibility = 'visible';
			 document.getElementById(theDiv).style.visibility = '';
		 }
	else
		{
		 document.getElementById(theDiv).style.visibility = 'hidden';
		 }
}

// FUNCTIONS ADDED BY MARK - USED FOR NEW REG PAGE  //
/* Comment 9/13/06: the entire functionality of the tooltip is way more complicated than necessary... due to requirement changes along the way. 
It works for now, but should be re-written into something easier to maintain... */

function showTooltip(inputEl) {
// set all to display none, except the one that has the focus:
	if (!isInteger(document.getElementById('mobile').value))
	{	document.getElementById('mobile').value =0;}
	
	var inputID=inputEl.getAttribute("id");
	//var allFields=document.getElementsByTagName("input");
	var allFields=document.forms[0].elements;
    var schoolSelected=(document.getElementById('ssta_school_id') &&
                        document.getElementById('ssta_school_id').value != 0);
	for (var i=0; i<allFields.length; i++) {
		var field=allFields[i];
		var fieldID=field.getAttribute("id");
		var toolID=String("tool_"+fieldID);
		var toolDiv=document.getElementById(toolID);		
        var dontChangeColors = ((fieldID == 'ssta_textfld_id') && schoolSelected);
                               
		if (fieldID==inputID) {
			if (field.type!="hidden") {
			    if (toolDiv) {
					toolDiv.style.display="block";
				}
			}
			if 	((field.type!='select-one') && (field.type!='checkbox')) {
                if (!dontChangeColors) {
    				field.style.background="#CCEBFF";
                }
				field.style.borderStyle="inset";
			}
		} else {
			if (field.type!="hidden") {
			    if (toolDiv) {
				    toolDiv.style.display="none";
				}
			}
			if 	((field.type!='select-one') && (field.type!='checkbox')) {
                if (!dontChangeColors) {
    				field.style.background="#FFF";
                }
				field.style.border="1px solid #7F9DB9";
			}
		}
	}
}

function hideTooltip(inputEl) {
	return; // temp solution, onBlur=hideTooltip() events should be removed from html code
}
function showTooltipWithLink(tooltipDiv) {
	return; // temp solution, onBlur=hideTooltip() events should be removed from html code
}
function hideTooltipWithLink(tooltipDiv) {
	return; // temp solution, onBlur=hideTooltip() events should be removed from html code
}


function showTooltipVis(inputEl) {
	var thisEl=inputEl;
	var thisId=thisEl.getAttribute("id");
	var tooltip=document.getElementById("tool_"+thisId);
	tooltip.style.visibility="visible";
	thisEl.style.background="#CCEBFF";
}
function hideTooltipVis(inputEl) {
	var thisEl=inputEl;
	var thisId=thisEl.getAttribute("id");	
	var tooltip=document.getElementById("tool_"+thisId);
	tooltip.style.visibility="hidden";	
	thisEl.style.background="#FFF";
}

// this function sets the focus to the first field of the first form of the page:
function focusFirstField() {
	var bFound = false;
	// for each form
	for (f=0; f < document.forms.length; f++)  {
		// for each element in each form
		for(i=0; i < document.forms[f].length; i++) {
			// if it's not a hidden element or checkbox
			if (document.forms[f][i].type != "hidden") {
				// and it's not a checkbox
				if (document.forms[f][i].type != "checkbox") {
					// and it's not disabled
					if (document.forms[f][i].disabled != true) {
						// set the focus to it
						document.forms[f][i].focus();
						var bFound = true;
					}
				}
			}
		// if found in this element, stop looking
		if (bFound == true)
		break;
		}
	// if found in this form, stop looking
	if (bFound == true)
	break;
	}
}
// END OF MARK'S CODE //


