
// ---------------
// 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 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();
}
function displayPositionEditor(containerid, returnbox, displaybox)
{
    var width = 340;
	var height = 540;
    var left = (screen.width - width) / 2;
    var top	= ((screen.height - height) / 2) - 30;
    var posid = document.getElementById(returnbox).value;
    
    var returnValue = window.showModalDialog('/Pages/Edit/PositionCreator.aspx?posid='+posid+'&rootId='+containerid, null, 'dialogHeight:'+height+'px;dialogWidth:'+width+'px;')

    if( returnValue && returnValue > 0 )
    {
    document.getElementById(returnbox).value = returnValue;
    document.getElementById(displaybox).value = '['+returnValue+']';
    }
    else if(returnValue == 0)
    {
        document.getElementById(returnbox).value = '';
        document.getElementById(displaybox).value = '';
    }
}
function displayGoogle(latitude, longitude)
{
    Map.displayMap(latitude, longitude);
}
function displayPosition(id)
{
    var res = Avantime.Classes.GlobalAjax.GetPosition(id);
    
    if( res.value && res.error == null )
    {
        Map.displayMap(res.value);
    }
    else if( res.error )
    {
        alert(res.error);
    }
}

// ---------------
// 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);
    }
}

/* xMenu1A Object Prototype

  Parameters:
    triggerId   - id string of trigger element.
    menuId      - id string of menu.
    mouseMargin - integer margin around menu;
                  when mouse is outside this margin the menu is hid.
    slideTime   - integer time for menu slide (in milliseconds).
    openEvent   - string name of event on which to open menu ('click', 'mouseover', etc).
*/

function xMenu1A(triggerId, menuId, mouseMargin, slideTime, openEvent)
{
  var isOpen = false;
  var trg = xGetElementById(triggerId);
  var mnu = xGetElementById(menuId);
  if (trg && mnu) {
    xHide(mnu);
    xAddEventListener(trg, openEvent, onOpen, false);
}
  function onOpen()
  {
    if (!isOpen) {
	
	//	alert(trg.clientHeight);
     // xMoveTo(mnu, (xPageX(trg)), (xPageY(trg)+h+2));
      xShow(mnu);
     // xSlideTo(mnu, xPageX(trg), xPageY(trg) + xHeight(trg), slideTime);
      xAddEventListener(document, 'mousemove', onMousemove, false);
      isOpen = true;
    }
  }
  function onMousemove(ev)
  {
    var e = new xEvent(ev);
    if (!xHasPoint(mnu, e.pageX, e.pageY, -mouseMargin) &&
        !xHasPoint(trg, e.pageX, e.pageY, -mouseMargin))
    {
      xRemoveEventListener(document, 'mousemove', onMousemove, false);
     // xSlideTo(mnu, xPageX(trg), xPageY(trg), slideTime);
      setTimeout("xHide('" + menuId + "')", slideTime);
      isOpen = false;
    }
  }
} // end xMenu1A

function createHoverLink( linkId, imageUrl )
{
    if( linkId.length > 0 && imageUrl.length > 0 )
    {
        //preload image into cache.
        var preloadImage = new Image();
        preloadImage.src = imageUrl;
        //--
        
        var link = document.getElementById(linkId);
        
        if( link )
        {
            link.onmouseover = function() { if(slide) slide.fastDisplayImage(imageUrl, 0.3); };
            link.onmouseout = function() { if(slide) slide.fastHideDisplayImage(); };
        }
    }
}



// ------------------------------------------------------------
// Sets the height of all the children of the specified element
// to the height of the highest child.
// ------------------------------------------------------------
function adaptChildHeight(parentId)
{
    //Don't run in Chrome... 
    // Chrome
    if( BrowserDetect.browser == 'Chrome' )
    {
        return;
    }
        
	// 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 = 100;

        // 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';
            }
        }
    }
}