// ---------------
// 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
            }
        }
    }
    //
    // Initialize the header slideshow
    //
    $(function() {
        if ($("#slider").length > 0) {
            var total = $('#slider img').length;
            var rand = Math.floor(Math.random() * total);
            $('#slider').nivoSlider(
        { directionNav: false, // Next & Prev navigation       
            controlNav: false, // 1,2,3... navigation
            controlNavThumbs: false, // Use thumbnails for Control Nav
            controlNavThumbsFromRel: false, // Use image rel for thumbs
            pauseTime: 5000, // How long each slide will show
            effect: 'fade',
            startSlide: rand
        }
        );
        }
    });
    //
    // Initialize the customercase slideshow
    //
    $(function() {
       if ($("#customerSlider").length > 0) {
            var total = $('#customerSlider img').length;
            var rand = Math.floor(Math.random() * total);
            $('#customerSlider').nivoSlider(
        {   directionNav: false, // Next & Prev navigation       
            controlNav: false, // 1,2,3... navigation
            controlNavThumbs: false, // Use thumbnails for Control Nav
            controlNavThumbsFromRel: false, // Use image rel for thumbs
            pauseTime: 5000, // How long each slide will show
            effect: 'fade',
            startSlide: rand
        }
        );

        /*
          var maxHeight = 0;
            $('#sliderContainer .nivo-html-caption').each(function() {
                $(this).css("width", $('#customerSlider').width());
                $(this).css("display", "none");
                maxHeight = $(this).height() > maxHeight ? $(this).height() : maxHeight;
            });

             $('#customerSlider').css("height", $('#customerSlider').height() + maxHeight + 55);
            if ($('#sliderContainer').height() < $('#customerSlider').height()) {
                maxHeight = $('#sliderContainer').height() +  $('#customerSlider').height();
                $('#sliderContainer').css("height",maxHeight);
            }
         */
 }
    });


