﻿// Put any common admin javascript in this file

// ***********************
// Region "Public Methods"
// ***********************


// Decodes the HTML in a textbox with an id of elementId.
// Use to get around .net page validation without disabling it.
function decodeHTMLBox(elementId) {

   var oElem = $get(elementId);
   if (oElem) {
       var output = oElem.value;
       output = output.replace(/&amp;/gi, '&');
       output = output.replace(/&quot;/gi, '"');
       output = output.replace(/&lt;/gi, '<');
       output = output.replace(/&gt;/gi, '>');
       oElem.value = output;       
   }
}


// Encodes the HTML in a textbox with an id of elementId.
// Use to get around .net page validation without disabling it.
// Remember to decode the textbox again after posting back!
function encodeHTMLBox(elementId) {

   var oElem = $get(elementId);
   if (oElem) {
       var output = oElem.value;
       output = output.replace(/&/gi, '&amp;');
       output = output.replace(/\"/gi, '&quot;');
       output = output.replace(/</gi, '&lt;');
       output = output.replace(/>/gi, '&gt;');
       oElem.value = output;
   }
}


// Highlights an element with a border to show it has been edited
function highlightEditedControl(elementId) {
    var oElement = $get(elementId);
    if (oElement) {
        oElement.style.borderTop = "solid 2px red";
        oElement.style.borderBottom = "solid 2px red";
    }
}


// Re-positions the hover menu over the top of the content element
// Hover menu must have popupPosition="Right" for this to work correctly
function hmReposition(contentElementId, hoverElementId)
{
    var oContent = $get(contentElementId);
    var oMenu = $find(hoverElementId);
    var contentWidth = Sys.UI.DomElement.getBounds(oContent).width;
    var contentParentWidth = Sys.UI.DomElement.getBounds(oContent.parentNode).width;
    var contentX = Sys.UI.DomElement.getBounds(oContent).x;
    var locX = oMenu._popupBehavior.get_x();
       
    if (getStyleForElement(oContent).position == 'static') {
        if (contentX != locX)
            oMenu._popupBehavior.set_x(locX - contentParentWidth);
    }
    else {
        // Positioned element - get positions directly from set values
        
        // Read set positional values
        var elementStyle = getStyleForElement(oContent);
        var strTop = elementStyle.top;
        var strLeft = elementStyle.left;
        var strRight = elementStyle.right;
                
        if (strTop != 'auto') {
            // Top value set - position hover menu at same y position
            var intTop = parseInt(strTop.replace('px', ''));
            oMenu._popupBehavior.set_y(intTop);
        }
        if (strLeft != 'auto') {
            // Left value set - position hover menu at same x position
            var intLeft = parseInt(strLeft.replace('px', ''));
            oMenu._popupBehavior.set_x(intLeft);        
        }
        if (strRight != 'auto') {
            // Right value set - position hover menu where it is but over the content
            // TODO: Will only work at the moment when right is set to 0 (in order to right align div)
            var intRight = parseInt(strRight.replace('px', ''));
            oMenu._popupBehavior.set_x(locX - contentWidth);
        }                        
    }              
}


// Resizes hoverMenuExtender control to fit over the top of its target content control
// hoverElementId: client id of the hoverMenuExtender
// contentElementId: client id of element the hoverMenuExtender targets
// TODO: menu element offsetHeight is being read as zero during partial (AJAX) postbacks
// Tried reading it at later stage in AJAX process (see testControl.aspx) but still reads as zero.
function resizeHoverMenu(contentElementId, hoverElementId, isRefresh)
{
    // Get hardcoded values from hovermenu class found in adminScreen.css

    var hoverCSSPaddingHeight = 3;
    var hoverCSSPaddingWidth = 20;
    var hoverCSSBorderHeight = 2;
    var hoverCSSBorderWidth = 2;

    // debug mode?
    // Test code
    var db = false;

    // Get elements
    var oContent = $get(contentElementId);
    var oMenu = $get(hoverElementId);
    if ((!oContent) || (!oMenu)) {return;}

    // Test code, uncomment to see offsetHeights of two elements
    if (db == true) {
        alert(contentElementId + ' content height: ' + Sys.UI.DomElement.getBounds(oContent).height);
        alert(contentElementId + ' content old height: ' + oContent.offsetHeight);
        alert(contentElementId + ' menu height: ' + oMenu.offsetHeight);
        alert(contentElementId + ' content new width: ' + Sys.UI.DomElement.getBounds(oContent).width);
    }

    // Get width of contentElement.
    // The values returned will include its width, padding, margin and border sizes.
    var width = Sys.UI.DomElement.getBounds(oContent).width;
    width -= (hoverCSSPaddingWidth + hoverCSSBorderWidth);
    if (!isRefresh) {
        // Further level of adjustment needed to rectify the calculation bug in the AJAX HoverMenuExtender
        // Only needs to be run first time, not as part of refresh
        width -= (hoverCSSPaddingWidth - hoverCSSBorderWidth);
    }
    if (width < 0) {width = 0;} // width cannot be less than zero
    oMenu.style.width = width + 'px';

    // Get height of contentElement, which is the taller of the content panel and the hover panel
    var height = 0;
    var contentHeight = Sys.UI.DomElement.getBounds(oContent).height;
    var menuHeight = Sys.UI.DomElement.getBounds(oMenu).height;
    if (contentHeight >= menuHeight) {
        height = contentHeight;
        height -= (hoverCSSBorderHeight + hoverCSSPaddingHeight);
        oMenu.style.height = height + 'px';
    }
    
    // WDO - Commented out - not sure we should resize content if it's smaller than the hover panel
    //else {
        // TODO: Temporary fix to stop shrinking of Flash content element
        //if (contentElementId.toLowerCase().indexOf('flash') == -1)
        //{
        //    height = menuHeight;
        //    height -= (hoverCSSBorderHeight + hoverCSSPaddingHeight);
        //    height += (2*hoverCSSBorderHeight);
        //    oContent.style.height = height + 'px';
        //}
    //}
}


// Shows popup extender and sets the default control focus //
function showPopupExtender(ExtenderID, DefaultControlID)
{
    alert(DefaultControlID);
    $find(ExtenderID).show()
    $get(DefaultControlID).focus()
}


// **************************
// Region "Private Functions"
// **************************

// Gets a style for a given element in a cross-browser way
function getStyleForElement(oElement)
{    
    if (oElement.currentStyle) {
        return oElement.currentStyle;
    }
    else if (document.defaultView.getComputedStyle) {
        return document.defaultView.getComputedStyle(oElement, '');
    }
    else {
        return;
    }
}


// ***************
// FCKEditor HACKS
// ***************


var urlobj;


// Assigns font and background-color styles of a source element to an FCK Editor window that is used to edit it
// KNOWN ISSUE: Will not read inherited styles on fonts, etc
function assignElementStyleToFCK(SourceElementId, FCKClientId, bgColor) {

    // Get source element
    var oSourceElement = document.getElementById(SourceElementId);
    if (!oSourceElement) return;

    // Check specified element is an iFrame
    var oFCKIFrame = document.getElementById(FCKClientId);
    if (oFCKIFrame.tagName != 'IFRAME') return;
    
    // Get to iFrame containing editor panel and change default font and background colour
    var iFrameL1Window;
    var iFrameL2Window;
    var oEditBody;
    if (window.frames[FCKClientId]) {
        // IE
        iFrameL1Window = window.frames[FCKClientId].window;
        if (iFrameL1Window) {
            iFrameL2Window = iFrameL1Window.frames[0].window;
        }
    }
    else {
        // Not IE
        iFrameL1Window = document.getElementById(FCKClientId).contentWindow;
        if (iFrameL1Window) {
            iFrameL2Window = iFrameL1Window.frames[0];
        }
    }

    if (iFrameL2Window) {
        oEditBody = iFrameL2Window.document.getElementsByTagName('BODY')[0];
        if (oEditBody) {
            // If no background colour specified by the control, try to calculate background color
            if (bgColor == '') {
                oEditBody.style.backgroundColor = getStyleForElement(oSourceElement).backgroundColor;
                if (oEditBody.style.backgroundColor == 'transparent') {
                    // Look for background color on parent elements if no background color defined on this element
                    var oParentElement = oSourceElement.parentNode;
                    while ((oEditBody.style.backgroundColor == 'transparent') && (oParentElement.tagName)) {
                        oEditBody.style.backgroundColor = getStyleForElement(oParentElement).backgroundColor;
                        oParentElement = oParentElement.parentNode;
                    }
                }
            }
            else {
                oEditBody.style.backgroundColor = bgColor;
            }
                            
            oEditBody.style.color = getStyleForElement(oSourceElement).color;
            oEditBody.style.fontFamily = getStyleForElement(oSourceElement).fontFamily;
            oEditBody.style.fontSize = getStyleForElement(oSourceElement).fontSize;
            oEditBody.style.fontWeight = getStyleForElement(oSourceElement).fontWeight;
            oEditBody.style.letterSpacing = getStyleForElement(oSourceElement).letterSpacing;
            oEditBody.style.lineHeight = getStyleForElement(oSourceElement).lineHeight;
            oEditBody.style.textAlign = getStyleForElement(oSourceElement).textAlign;
            oEditBody.style.textDecoration = getStyleForElement(oSourceElement).textDecoration;
        }
    }
}


function BrowseServer(obj, type)
{
	urlobj = obj;
	
	OpenServerBrowser(
		'/FCKeditor/editor/filemanager/browser/default/browser.html?Type=' + type + '&Connector=../../connectors/aspx/connector.aspx',
		screen.width * 0.7,
		screen.height * 0.7 ) ;
}


// Fix to get FCK to maintain its value on partial AJAX postback
// See http://jlcoady.net/archive/2007/03/30/fckeditor-work-inside-updatepanel for source
function FCKUpdateLinkedField(id) {
    try {
        if (typeof(FCKeditorAPI) == "object") {
            FCKeditorAPI.GetInstance(id).UpdateLinkedField();
        }
    }
    catch(err) {
    }
}


function OpenServerBrowser( url, width, height )
{
	var iLeft = (screen.width  - width) / 2 ;
	var iTop  = (screen.height - height) / 2 ;

	var sOptions = "toolbar=no,status=no,resizable=yes,dependent=yes" ;
	sOptions += ",width=" + width ;
	sOptions += ",height=" + height ;
	sOptions += ",left=" + iLeft ;
	sOptions += ",top=" + iTop ;

	var oWindow = window.open( url, "BrowseWindow", sOptions ) ;
}

function SetUrl( url, width, height, alt )
{
	document.getElementById(urlobj).value = url ;
	oWindow = null;
}
