// ---------------
// Adapts the height of the news listing on the start page.
// ---------------
function adaptStartPageDivs()
{
	var leftDiv = document.getElementById('StartPageLeftDiv');
	var rightDiv = document.getElementById('StartPageRightDiv');
	var newsDiv = document.getElementById('StartPageNewsDiv');
	
	if (leftDiv && rightDiv && newsDiv)
	{
		if (leftDiv.clientHeight > rightDiv.clientHeight)
		{
			var topHeaderMargin = 29 + 17; // 29 is header height and 17 is padding on the div
			newsDiv.style.height = (leftDiv.clientHeight - topHeaderMargin) + 'px';
		}
	}
}

// ---------------
// Toggles visibility of the specified element.
// ---------------
function toggleVisibility(elemId)
{
	var elem = document.getElementById(elemId);
	
	if (elem)
	{
		if (elem.style.display == 'none')
		{		
			elem.style.display = 'block';
		}
		else
		{			
			elem.style.display = 'none';
		}
	}
}

// ------------------------------------------------------------
// This function will fire a click event on the specified control when the 
// enter key is pressed in a text field. Attach this function to the 
// onkeypress-event on the text field like this:
// <input type="text" onkeypress="return fireClickOnEnter(event, 'IdOfControlToFireClickOn');">
// ------------------------------------------------------------
function fireClickOnEnter(evt, controlId)
{
    var control = document.getElementById(controlId);
    var keyCode = (typeof window.event == 'object') ? window.event.keyCode : evt.keyCode;

    // If enter is pressed -> fire click-event on the control
    if (control && (keyCode == 13))
    {
        control.focus();
        control.click();
        return false;
    }
    else
    {
        return true;
    }
}

// ------------------------------------------------------------
// This function will fire a postbackon the specified control when the 
// enter key is pressed in a text field. Attach this function to the 
// onkeypress-event on the text field like this:
// <input type="text" onkeypress="return postbackOnEnter(event, 'IdOfControlToFirePostbackOn');">
// ------------------------------------------------------------
function postbackOnEnter(evt, controlId)
{
    var keyCode = (typeof window.event == 'object') ? window.event.keyCode : evt.keyCode;

    // If enter is pressed -> do a postback
    if (keyCode == 13)
    {
		__doPostBack(controlId,'');
		return false;
    }
    else
    {
        return true;
    }
}

// ------------------------------------------------------------
// Returns the x coordinate of the specified object
// ------------------------------------------------------------
function findPosX(obj)
{
    var curleft = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curleft += obj.offsetLeft
            obj = obj.offsetParent;
        }
    }
    else if (obj.clientLeft)
    {
        curleft += obj.clientLeft;
    }
    return curleft;
}

// ------------------------------------------------------------
// Encrypts the specfied string using the xor algorithm.
// The encrypted string can be decrypted by calling this method again
// with the same key.
// ------------------------------------------------------------
function xorEncryptString(str, key)
{
	var result = '';
	for (var i = 0; i < str.length; i++)
	{
		result += String.fromCharCode(key ^ str.charCodeAt(i));
	}
	return result;
}

// ------------------------------------------------------------
// Returns the y coordinate of the specified object
// ------------------------------------------------------------
function findPosY(obj)
{
    var curtop = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    }
    else if (obj.clientTop)
    {
        curtop += obj.clientTop;
    }
    return curtop;
}

// ------------------------------------------------------------
// Builds an html-page for printing
// ------------------------------------------------------------
function printPage(pagename, appRoot) 
{
	if (!window.print)
	{
		window.status = 'No print';
		return;
	}

	// Get the main content area and other stuff we need
	var contentdiv = document.getElementById('pagecontent');

	if (contentdiv)
	{
		var contentHtml = '<div style="width:475px;padding: 40px 40px 0 80px">';
		contentHtml += '<img src="/images/avantime/printmall_logotype.gif" border="0" alt="Optilon" />';
		contentHtml += '<img src="/images/avantime/printmall_streck.gif" border="0" alt="Optilon" />';
		contentHtml += '<div style="padding-top:40px;">';
		contentHtml += contentdiv.innerHTML + '</div></div>';

		var beginHtml = 
		      '<html>' +
			  '<head>' +
			  '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">' + 
			  '<link rel="stylesheet" type="text/css" href="' + appRoot + 'Templates/Optilon/Styles/all.css">' +
			  '<title>Optilon - ' + pagename + '</title>' +
			  '<style> .printExclude { visibility: hidden; position: absolute; top: 0px; height: 0px } </style>' +
			  '</head>' +
			  '<body style="margin: 0px; background-image: none; background-color: #fff;">';

		var endHtml = '</body></html>';

		var printWin = window.open('about:blank','','width=700,height=600,scrollbars=yes,toolbar=yes');
		printWin.document.open();
		printWin.document.write(beginHtml + 
		                        contentHtml + 
		                        endHtml);
		printWin.document.close();

		printWin.print();
		printWin.close();
	}
}

// ------------------------------------------------------------
//	Opens a new window that will login to SchoolSoft
// ------------------------------------------------------------
function schoolSoftLogin()
{
	var usertypeSelect = document.getElementById('SchoolSoftUsertype');
	var usernameTextbox = document.getElementById('SchoolSoftUsername');
	var passwordTextbox = document.getElementById('SchoolSoftPassword');
	
	if (usertypeSelect && usernameTextbox && passwordTextbox)
	{
		var usertype = usertypeSelect.options[usertypeSelect.selectedIndex].value;
		var username = usernameTextbox.value;
		var password = xorEncryptString(passwordTextbox.value, 31);
		var url = gAppRoot + 'Pages/SchoolSoftLogin.aspx?usertype=' + usertype + 
			'&username=' + encodeURIComponent(username) + 
			'&password=' + encodeURIComponent(password);
		
		var win = window.open(url, 'SchoolSoftWindow');
		win.focus();
	}
}

// ------------------------------------------------------------
// Opens the Tipsa-window
// ------------------------------------------------------------
function openTipPage(pageId)
{
	var width = 340;
	var height = 540;
    var left = (screen.width - width) / 2;
    var top	= ((screen.height - height) / 2) - 30;

    var win = window.open(gAppRoot + 'Pages/SendTip.aspx?pageid='+pageId, 'TipWindow', 'width='+width+',height='+height+',top='+top+',left='+left+',location=no,scrollbars=yes,menubar=no,toolbar=no,resizable=no,status=yes');
    win.focus();
}

// ---------------
// Displays the specified image. 
// Used by the image browser function.
// ---------------
function imageBrowserShowImage(index)
{
    // Roll over index if it's too high or low
    if (index < 0) 
    { 
		index = gImageBrowserUrls.length - 1;
	}
	else if (index >= gImageBrowserUrls.length)
	{
		index = 0;
	}
		
    // Change image on the image tag
    var imageTag = document.getElementById(gImageBrowserTagId);
    if (imageTag)
    {
        imageTag.src = gImageBrowserUrls[index];
        imageTag.alt = gImageBrowserDescriptions[index];
        gImageBrowserCurrentIndex = index;
    }
    
    // Change the image description
    var divText = document.getElementById('ImageBrowserDescription');
    if (divText)
    {
		divText.innerHTML = gImageBrowserDescriptions[index];
    }

    // Change the current image index label
    var spanTag = document.getElementById('ImageBrowserCurrentIndex');
    if (spanTag)
    {
        spanTag.innerHTML = (index + 1);
    }
}
    function doClick(buttonName,e)
    {
        //the purpose of this function is to allow the enter key to 
        //point to the correct button to click.
        var key;

         if(window.event)
              key = window.event.keyCode;     //IE
         else
              key = e.which;     //firefox
    
        if (key == 13)
        {
            //Get the button the user wants to have clicked
            var btn = document.getElementById(buttonName);
            if (btn != null)
            { //If we find the button click it
                btn.click();
                event.keyCode = 0
            }
        }
   }
// ------------------------------------------------------------
// Sets the height of all the children of the specified element
// to the height of the highest child.
// ------------------------------------------------------------
function adaptChildHeight(parentId)
{
	// This script messes up the page when it's displayed in EPi's
	// edit mode so we need this rather ugly work-around to prevent
	// the script from running when the page is viewed in edit mode.
	if (window.parent.name == 'EditPanel')
	{
		return;
	}

    var parentElement = document.getElementById(parentId);
    if (parentElement)
    {
        var maxHeight = 0;

        // Loop over all children to find the maxHeight
        for (i = 0; i < parentElement.childNodes.length; i++)
        {
            if (parentElement.childNodes[i].clientHeight > maxHeight)
            {
                maxHeight = parentElement.childNodes[i].clientHeight;
            }
        }

        // Loop over all children and set the height
        for (i = 0; i < parentElement.childNodes.length; i++)
        {
            if (parentElement.childNodes[i].style && 
                (parentElement.childNodes[i].style.clear != 'both'))
            {
                parentElement.childNodes[i].style.height = maxHeight + 'px';
            }
        }
    }
}

function addLoadEvent(func) 
{
    var oldonload = window.onload;
    if (typeof window.onload != 'function') 
    {
        window.onload = func;
    } 
    else 
    {
        window.onload = function()
        {
            if (oldonload)
            {
                oldonload();
            }
            func();
        }
    }
}

var getFFVersion=navigator.userAgent.substring(navigator.userAgent.indexOf("Firefox")).split("/")[1]
            	    var FFextraHeight=parseFloat(getFFVersion)>=0.1? 16 : 0 //extra height in px to add to iframe in FireFox 1.0+ browsers

        	        function resizeIframe(frameid)
                    {
                    
                        var currentfr=document.getElementById(frameid);
                        if (currentfr && !window.opera)
                        {
                            currentfr.style.display="block";
                            
                            if (currentfr.contentDocument && currentfr.contentDocument.body && currentfr.contentDocument.body.offsetHeight) //ns6 syntax
                                currentfr.height = currentfr.contentDocument.body.offsetHeight+FFextraHeight; 
                            else if (currentfr.Document && currentfr.Document.body && currentfr.Document.body.scrollHeight) //ie5+ syntax
                            {
                                if (currentfr.Document.body.scrollHeight == 35)	//Avantime fix for hiding iframe if empty.
	                                currentfr.style.display="none";
                                else
	                                currentfr.height = currentfr.Document.body.scrollHeight;
                            }
                            if (currentfr.addEventListener)
                                currentfr.addEventListener("load", readjustIframe, false);
                            else if (currentfr.attachEvent)
                            {
                                currentfr.detachEvent("onload", readjustIframe); // Bug fix line
                                currentfr.attachEvent("onload", readjustIframe);
                            }
                            
                        }
                    }
                    
                    
                    function readjustIframe(loadevt)
	                {
                        var crossevt=(window.event)? event : loadevt
                        var iframeroot=(crossevt.currentTarget)? crossevt.currentTarget : crossevt.srcElement
                        if (iframeroot)
                        resizeIframe(iframeroot.id);
                    }
