//************************************************//
//       Functions JS - Included in all pages     //
//************************************************//

//*** Browser Check
var ua = navigator.userAgent.toLowerCase();
var isStrict = document.compatMode == 'CSS1Compat',
  isOpera = ua.indexOf("opera") > -1,
  isIE = ((ua.indexOf("msie") != -1) && (ua.indexOf("opera") == -1) && (ua.indexOf("webtv") == -1)),
  isIE7 = ua.indexOf('msie 7') > -1,
  ieVersion = parseFloat(ua.substring(ua.indexOf('msie ') + 5)),
  isBorderBox = isIE && !isStrict,
  isSafari = (/webkit|khtml/).test(ua),
  isSafari3 = isSafari && !!(document.evaluate),
  isGecko = ua.indexOf('gecko') > -1,
  isWindows = (ua.indexOf('windows') != -1 || ua.indexOf('win32') != -1),
  isMac = (ua.indexOf('macintosh') != -1 || ua.indexOf('mac os x') != -1),
  isLinux = (ua.indexOf('linux') != -1),
  isNetscape = (ua.indexOf("netscape") != -1),
  netscapeVersion = parseFloat(ua.substring(ua.lastIndexOf('/') + 1)),
  isKonqueror = (ua.indexOf("konqueror") != -1),
  konquerorVersion = parseFloat(ua.substring(ua.indexOf('konqueror/') + 10));


//*** Page variables
var DivDynamicPageContainerId;
var QuickTimeChecked = false;

//*** Cursor Style
var MCursor = (document.all) ? 'cursor:hand;' : 'cursor:pointer;';

//*** Get Real TOP Position From Top Left Corner of the page
function getOffsetTopFromBody(DOMobj)
{
    return (DOMobj == null) ? 0 : (DOMobj == document.body) ? DOMobj.offsetTop : DOMobj.offsetTop + getOffsetTopFromBody(DOMobj.offsetParent);
}

//*** Get Real LEFT Position From Top Left Corner of the page
function getOffsetLeftFromBody(DOMobj)
{
    return (DOMobj == null) ? 0 : (DOMobj == document.body) ? DOMobj.offsetLeft : DOMobj.offsetLeft + getOffsetLeftFromBody(DOMobj.offsetParent);
}

//*** Get document full Width
function GetDocumentWidth()
{
    if (document.body.scrollWidth)
    {
        return parseInt(document.body.scrollWidth, 10);
    }

    var w = document.documentElement.offsetWidth;
    if (window.scrollMaxX)
    {
        w += window.scrollMaxX;
    }
    return parseInt(w, 10);
}

//*** Get document full height
function GetDocumentHeight()
{
    if (document.body.scrollHeight)
    {
        return parseInt(document.body.scrollHeight, 10);
    }
    else
    {
        return parseInt(document.documentElement.offsetHeight, 10);
    }
}

//*** Check if a string is not empty
function NotEmpty(testValue)
{
    return (!IsEmpty(testValue))
}

//*** Check if a string is empty
function IsEmpty(testValue)
{
    return (String(testValue) == "undefined" || String(testValue) == "null" || String(testValue).length == 0 || testValue == null || String(testValue).match(/^\s*$/))
}

//*** Check if a string is a valid url with :// header
function IsValidUrl(testValue)
{
    return (testValue.match(/.\:\/\/./))
}

//*** Replace an empty string
function NVL(testValue, defValue)
{
    return (NotEmpty(testValue)) ? testValue : defValue
}

//*** Remove the last char of a string
function MinOne(strInput)
{
    if (NotEmpty(strInput))
    {
        return strInput.substr(0, strInput.length - 1);
    }
    else
    {
        return '';
    }
}

function trim(str, chars)
{
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars)
{
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars)
{
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function JString(str)
{
    return str.replace(/\'/gi, "\\\'");
}

//*** StringBuilder Class
function StringBuilder(value)
{
    this.strings = new Array("");
    this.append(value);
}

StringBuilder.prototype.append = function(value) { if (value) { this.strings.push(value); } }
StringBuilder.prototype.clear = function() { this.strings.length = 1; }
StringBuilder.prototype.toString = function() { return this.strings.join(""); }

//*** Write flash tags
function WriteFlash(id, src, flashvars, width, height, bgcolor, isTransparent, allowFullScreen)
{
    var htmlFinal = '';
    var htmlParam = '';
    var htmlEmbed = '';

    //*** Param Quality
    htmlParam += '<param name="quality" value="high" />';
    htmlEmbed += ' quality="high"';

    //*** Param Allow Script Access
    htmlParam += '<param name="allowScriptAccess" value="sameDomain" />';
    htmlEmbed += ' allowScriptAccess="sameDomain"';

    //*** Param Source
    htmlParam += '<param name="movie" value="' + src + '" />';
    htmlEmbed = ' src="' + src + '"';

    //*** Param Background Color
    if (NotEmpty(bgcolor))
    {
        htmlParam += '<param name="bgcolor" value="' + bgcolor + '" />';
        htmlEmbed += ' bgcolor="' + bgcolor + '"';
    }

    //*** Param Fullscreen
    if (allowFullScreen == true)
    {
        htmlParam += '<param name="allowFullScreen" value="true">';
        htmlEmbed += ' allowfullscreen="true"';
    }

    //*** Transparent
    if (isTransparent == true)
    {
        htmlParam += '<param name="wmode" value="transparent">';
        htmlEmbed += ' wmode="transparent"';
    }

    //*** Param Flash Vars
    if (NotEmpty(flashvars))
    {
        htmlParam += '<param name="FlashVars" value="' + flashvars + '" />';
        htmlEmbed += ' FlashVars="' + flashvars + '"';
    }

    //*** Final HTML
    htmlFinal += '<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="' + width + '" height="' + height + '" id="' + id + '">';
    htmlFinal += htmlParam;
    htmlFinal += '<embed' + htmlEmbed + ' width="' + width + '" height="' + height + '" name="' + id + '" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
    htmlFinal += '</object>';

    //alert(htmlFinal);
    document.write(htmlFinal);
}

//*** Write movie tags and check if quicktime is installed
function WriteMovie(pSrc, pWidth, pHeight)
{
    var width = '320px';
    var height = '240px';
    var src = trim(pSrc, ' ');
    var quickTimeInstalled = false;
    var html = '';
    var isImage = false;
    var isVideo = true;
    var extension = '';

    if (pWidth != null && pWidth != undefined)
    {
        width = parseInt(pWidth, 10);
    }

    if (pHeight != null && pHeight != undefined)
    {
        height = (parseInt(pHeight, 10) + 15);
    }

    extension = src.substr(src.lastIndexOf('.') + 1).toLowerCase();

    if (extension == 'jpg' || extension == 'gif' || extension == 'png')
    {
        isImage = true;
        isVideo = false;
    }

    if (!QuickTimeChecked && isVideo)
    {
        if (isIE && isWindows)
        {
            quickTimeInstalled = DetectPluginIE("QuickTimeCheckObject.QuickTimeCheck.1", "QuickTime");
        }
        else
        {
            quickTimeInstalled = DetectPluginOther("video/quicktime", "QuickTime");
        }

        QuickTimeChecked = true;
    }

    if (isVideo && quickTimeInstalled)
    {
        html += '<center>';
        html += '<embed src="' + src + '" AutoPlay="True" playcount="0" controls="TRUE" width="' + width + '" height="' + height + '"> </embed>';
        html += '</center>';
    }
    else if (isVideo)
    {
        html += '<a href="http://www.apple.com/quicktime/download/" target="_blank"><img src="../../common/image/misc/quicktime-not-installed.gif" border="0" /></a>';
    }
    else if (isImage)
    {
        html += '<center>';
        html += '<img src="' + src + '" width="' + width + '" />';
        html += '</center>';
    }

    document.write(html);
}

function DetectPluginIE(ClassID, name)
{
    result = false;
    document.write('<SCRIPT LANGUAGE=VBScript>\n on error resume next \n result = IsObject(CreateObject("' + ClassID + '"))</SCRIPT>\n');
    if (result)
    {
        return true;
    }
    else
    {
        return false;
    }
}

function DetectPluginOther(ClassID, name)
{
    var nse = "";
    for (var i = 0; i < navigator.mimeTypes.length; i++)
    {
        nse += navigator.mimeTypes[i].type.toLowerCase();
    }

    if (nse.indexOf(ClassID) != -1)
    {
        if (navigator.mimeTypes[ClassID].enabledPlugin != null)
        {
            return true;
        }
    }
    return false;
}

function WriteCondorOrderButton(params)
{
    var html = '';

    html += '<br />';
    html += '<br />';
    html += '<div align=\"right\">';
    html += '<a href=\"../../brandportal/private/condor_order.aspx?' + params + '\" target="_blank">';
    html += '<img src=\"../../brandportal/image/misc/condororder.gif\" border=\"0\" />';
    html += '</a>';
    html += '</div>';

    document.write(html);
}

//*** Forbid the Enter Key usage in a OnMouseDown event 
//*** Usage: onkeypress="return WasEnterKeyPressed(event);"
function WasEnterKeyPressed(e)
{
    var iKeyCode = 0;
    if (window.event)
    {
        iKeyCode = window.event.keyCode;
    }
    else if (e)
    {
        iKeyCode = e.which;
    }

    if (iKeyCode != 13)
    {
        return false;
    }
    else
    {
        return true;
    }
}

function EnterKeyPressedAction(jsaction, e)
{
    if (WasEnterKeyPressed(e))
    {
        setTimeout(jsaction, 100);
        return false;
    }
    else
    {
        return true;
    }
}

//*** Return true if Caps Lock is ON or is pressed
//*** Usage: onkeypress="DetectCapsLock(event);"
function DetectCapsLock(e)
{
    if (!e) { e = window.event; } if (!e) { DetectCapsLockAction(false); return; }
    //what (case sensitive in good browsers) key was pressed
    var theKey = e.which ? e.which : (e.keyCode ? e.keyCode : (e.charCode ? e.charCode : 0));
    //was the shift key was pressed
    var theShift = e.shiftKey || (e.modifiers && (e.modifiers & 4)); //bitWise AND
    //if upper case, check if shift is not pressed. if lower case, check if shift is pressed
    DetectCapsLockAction((theKey > 64 && theKey < 91 && !theShift) || (theKey > 96 && theKey < 123 && theShift));
}

function DetectCapsLockAction(oC)
{
    if (oC)
    {
        alert('WARNING: Caps Lock is enabled\nThis field is case sensitive');
    }
}


//*** Debug functions
var JSdebug = new DebugClass();

function DebugClass()
{
    var divContainer;

    this.message = new Array();
    this.title = new Array();
    this.messageServer = new Array();
    this.titleServer = new Array();
    this.width = 620;
    this.visible = false;

    //*** Add a Javascript debug entry
    this.Add = function Add(Title, Message)
    {
        this.message[this.message.length] = Message;
        this.title[this.title.length] = Title;

        this.RenderJavascript();
    }

    //*** Add a server debug entry
    this.AddServer = function AddServer(Title, Message)
    {
        this.messageServer[this.messageServer.length] = Message;
        this.titleServer[this.titleServer.length] = Title;
    }

    //*** Clear Javascript entries
    this.Clear = function Clear()
    {
        this.message = new Array();
        this.title = new Array();

        this.RenderJavascript();
    }

    //*** Render Javascript entries
    this.RenderJavascript = function RenderJavascript()
    {
        var fld = DOM.get('InputDebuggerClient');

        if (fld)
        {
            fld.value = this.GetMessage(this.title, this.message);
        }
    }

    this.Render = function Render()
    {
        var html = '';

        html += '<table width="' + this.width + '" cellpadding="0" cellspacing="0" border="0">';

        html += '<tr>';
        html += '<td style="width: 10px;" rowspan="4">&nbsp;</td>';
        html += '<td style="width:' + (this.width - 20) + '; height: 20px;"><p style="color: white; font-weight: bold;">Debug Console - Server messages</p></td>';
        html += '<td style="width: 25px;" rowspan="4"><div id="DivDebuggerControl" style="width: 20px; text-align: center; color: white; font-weight: bold; cursor: pointer;" onclick="JSdebug.ShowHide();">&gt;<br>&gt;<br>&gt;</div></td>';
        html += '</tr>';

        html += '<tr>';
        html += '<td align="center">';
        html += '<textarea id="InputDebuggerServer" style="width: ' + (this.width - 37) + 'px; height: 250px; font-family: courier; font-size: 9px; background-color: black; color: white;">'
        html += this.GetMessage(this.titleServer, this.messageServer);
        html += '</textarea>';
        html += '</td>';
        html += '</tr>';

        html += '<tr>';
        html += '<td style="height: 20px;"><p style="color: white; font-weight: bold;">Debug Console - Client messages <a href="javascript:JSdebug.Clear();" style="color: white;">[CLEAR]</a></p></td>';
        html += '</tr>';

        html += '<tr>';
        html += '<td align="center">';
        html += '<textarea id="InputDebuggerClient" style="width: ' + (this.width - 37) + 'px; height: 250px; font-family: courier; font-size: 9px; background-color: black; color: white;"></textarea>';
        html += '</td>';
        html += '</tr>';

        html += '<tr>';
        html += '<td colspan="3" style="height: 20px; text-align: right;"><p style="color: white; font-weight: bold; text-align: right"><a href="javascript:document.location = document.location.href;" style="color: white;">[R]</a>&nbsp;</p></td>';
        html += '</tr>';

        html += '</table>';

        divContainer = DOM.get('DivDebuggerContainer');

        divContainer.innerHTML = html;
        DOM.setStyle(divContainer, 'top', '20px');
        DOM.setStyle(divContainer, 'left', (25 - this.width) + 'px');
        DOM.setStyle(divContainer, 'width', this.width + 'px');
        DOM.setStyle(divContainer, 'height', '560px');
        DOM.setStyle(divContainer, 'opacity', 0.75);
        DOM.setStyle(divContainer, 'visibility', 'visible');
    }

    this.GetMessage = function GetMessage(arrLabels, arrValues)
    {
        var html = '';

        for (var i = (arrLabels.length - 1); i >= 0; i--)
        {
            html += '> ' + arrLabels[i] + ': ' + arrValues[i] + '\r\n';
        }

        return html;
    }

    this.ShowHide = function ShowHide()
    {
        var divControl = DOM.get('DivDebuggerControl');

        if (this.visible)
        {
            //*** Hide
            divControl.innerHTML = '&gt;<br>&gt;<br>&gt;';
            DOM.setStyle(divContainer, 'left', (25 - this.width) + 'px');
            this.visible = false;
        }
        else
        {
            //*** Show
            divControl.innerHTML = '&lt;<br>&lt;<br>&lt;';
            DOM.setStyle(divContainer, 'left', '0px');
            this.visible = true;

            this.RenderJavascript();
        }
    }
}

//*** AJAX functions
function GetPageAjax(url, divId, minWidth, jsextra)
{
    var xmlHttp;
    var objDiv = document.getElementById(divId);
    var html = '';

    //Waiting Icon
    html += '<table border="0" style="width: 100%; height: 100%;">'
    html += '<tr>';
    html += '<td align="center" valign="middle"><img src="../../../Sites/Common/Image/Misc/waiting.gif" style="width: 30px; height: 30px;"><br/>Loading...</td>';
    html += '<tr>';
    html += '</table>';

    objDiv.innerHTML = html;

    if (window.ActiveXObject)
    {
        //*** Branch for IE/Windows ActiveX version
        xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
        if (xmlHttp)
        {
            xmlHttp.onreadystatechange = function() { DisplayContentsAjax(objDiv, xmlHttp, minWidth, jsextra); };
            xmlHttp.open('GET', url, true);
            xmlHttp.send();
        }
    }
    else if (window.XMLHttpRequest)
    {
        //*** Firefox, Safari,...
        xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function() { DisplayContentsAjax(objDiv, xmlHttp, minWidth, jsextra); };
        xmlHttp.open('GET', url, true);
        xmlHttp.send(null);
    }
    else
    {
        //*** Other
        alert('Your browser is not compatible with Ajax technology');
    }
}

function DisplayContentsAjax(objDiv, xmlHttp, minWidth, jsextra)
{
    var html = '';

    if (xmlHttp.readyState == 4)
    {
        //*** only if 'OK'
        if (xmlHttp.status == 200)
        {
            if (parseInt(objDiv.offsetWidth, 10) < minWidth)
            {
                html = 'Need more space to be displayed';
            }
            else
            {
                html = xmlHttp.responseText;

                html = html.replace(/<html.*>/, '');
                html = html.replace(/<head.*>/, '');
                html = html.replace(/<body.*>/, '');
                html = html.replace(/<form.*>/, '');
                html = html.replace(/<\/form>/, '');
                html = html.replace(/<\/body>/, '');
                html = html.replace(/<\/head>/, '');
                html = html.replace(/<\/html>/, '');
                html = html.replace(/<input.*VIEWSTATE".*>/, '');
                html = html.replace(/<input.*EVENTTARGET".*>/, '');
                html = html.replace(/<input.*EVENTARGUMENT".*>/, '');
            }
        }
        //        else
        //        {
        //            html = 'Unable to retrieve data ' + xmlHttp.status;
        //        }

        objDiv.innerHTML = html;

        //CheckDynamicContentHeight(objDiv.id)

        if (jsextra)
        {
            setTimeout(jsextra, 100);
        }
    }
}

function ExecScriptAjax(url)
{
    var xmlHttp;
    if (window.ActiveXObject)
    {
        //*** Branch for IE/Windows ActiveX version
        xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
        if (xmlHttp)
        {
            xmlHttp.onreadystatechange = function() { ReturnScriptAjax(xmlHttp); };
            xmlHttp.open('GET', url, true);
            xmlHttp.send();
        }
    }
    else if (window.XMLHttpRequest)
    {
        //*** Firefox, Safari,...
        xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function() { ReturnScriptAjax(xmlHttp); };
        xmlHttp.open('GET', url, true);
        xmlHttp.send(null);
    }
    else
    {
        //*** Other
        alert('Your browser is not compatible with Ajax technology');
    }
}


function ExecScriptAjaxPost(url, xmlPostData)
{
    var xmlHttp;
    if (window.ActiveXObject)
    {
        //*** Branch for IE/Windows ActiveX version
        xmlHttp = new ActiveXObject('Microsoft.XMLHTTP');
        if (xmlHttp)
        {
            xmlHttp.onreadystatechange = function() { ReturnScriptAjax(xmlHttp); };
            xmlHttp.open('POST', url, true);

            xmlHttp.setRequestHeader("Content-type", "text/xml");
            xmlHttp.setRequestHeader("Content-length", xmlPostData.length);
            xmlHttp.setRequestHeader("Connection", "close");

            xmlHttp.send(xmlPostData);
        }
    }
    else if (window.XMLHttpRequest)
    {
        //*** Firefox, Safari,...
        xmlHttp = new XMLHttpRequest();
        xmlHttp.onreadystatechange = function() { ReturnScriptAjax(xmlHttp); };
        xmlHttp.open('POST', url, true);

        xmlHttp.setRequestHeader("Content-type", "text/xml");
        xmlHttp.setRequestHeader("Content-length", xmlPostData.length);
        xmlHttp.setRequestHeader("Connection", "close");

        xmlHttp.send(xmlPostData);
    }
    else
    {
        //*** Other
        alert('Your browser is not compatible with Ajax technology');
    }
}


function ReturnScriptAjax(xmlHttp)
{
    if (xmlHttp.readyState == 4)
    {
        //*** only if 'OK'
        if (xmlHttp.status == 200)
        {
            eval(xmlHttp.responseText);
        }
        //        else
        //        {
        //            alert('Unable to retrieve data ' + xmlHttp.status);
        //        }
    }
}

function SendEmail(fromName, fromEmail, toNames, toEmails, subject, message, templateId, returnJS, pageUrl)
{ 
    var blnValid = true;
    var msg = '';

    if (IsEmpty(fromName))
    {
        blnValid = false;
        msg += 'Please enter a valid name for the sender.\r\n';
    }

    if (IsEmpty(fromEmail))
    {
        blnValid = false;
        msg += 'Please enter a valid email address for the sender.\r\n';
    }

    if (IsEmpty(toNames))
    {
        blnValid = false;
        msg += 'Please enter a valid name for the recipient(s).\r\n';
    }

    if (IsEmpty(toEmails))
    {
        blnValid = false;
        msg += 'Please enter a valid email address for the recipient(s).\r\n';
    }

    if (blnValid)
    {
        var url = 'ajax.axd?method=sendemail';
        url += '&fromName=' + encodeURIComponent(fromName);
        url += '&fromEmail=' + encodeURIComponent(fromEmail);
        url += '&toNames=' + encodeURIComponent(toNames);
        url += '&toEmails=' + encodeURIComponent(toEmails);
        url += '&subject=' + encodeURIComponent(subject);
        url += '&message=' + encodeURIComponent(message);
        url += '&templateId=' + encodeURIComponent(templateId);
        url += '&returnJS=' + encodeURIComponent(returnJS);
        url += '&pageUrl=' + encodeURIComponent(pageUrl);

        ExecScriptAjax(url); 
    }
    else
    {
        alert(msg);
    }
}

function AddToFavorites()
{
    if (document.all)
    {
        // IE
        window.external.AddFavorite(location.href, document.title);
    }
    else if (window.sidebar)
    {
        // Firefox
        window.sidebar.addPanel(document.title, location.href, "");
    }
    else if (window.opera && window.print)
    {
        // Opera
        var elem = document.createElement('a');
        elem.setAttribute('href', location.href);
        elem.setAttribute('title', document.title);
        elem.setAttribute('rel', 'sidebar');
        elem.click();
    }
}

function CopyToClipboard(copytext)
{
    if (document.all)
    {
        //IE
        window.clipboardData.setData('Text', copytext);
    }
    else if (window.sidebar)
    {
        //Firefox
        var str = Components.classes["@mozilla.org/supports-string;1"].
                               createInstance(Components.interfaces.nsISupportsString);
        if (!str) return false;

        str.data = copytext;

        var trans = Components.classes["@mozilla.org/widget/transferable;1"].
                               createInstance(Components.interfaces.nsITransferable);
        if (!trans) return false;

        trans.addDataFlavor("text/unicode");
        trans.setTransferData("text/unicode", str, copytext.length * 2);

        var clipid = Components.interfaces.nsIClipboard;
        var clip = Components.classes["@mozilla.org/widget/clipboard;1"].getService(clipid);
        if (!clip) return false;

        clip.setData(trans, null, clipid.kGlobalClipboard);
    }

    alert('Data has been copied to your clipboard');
}


//*** Check the height of a dynamic page content and resize it
function CheckDynamicContentHeightOnLoad(divContainerId)
{
    DivDynamicPageContainerId = divContainerId;
    AddWindowOnloadEvent(CheckDynamicContentHeightDelayed);
}

function CheckDynamicContentHeight(divContainerId)
{
    DivDynamicPageContainerId = divContainerId;
    setTimeout('CheckDynamicContentHeightDelayed()', 100);
}

function CheckDynamicContentHeightDelayed()
{
    var maxHeight = 400;
    var childHeight = 0;
    var originalHeight = 0;
    var divContainer = document.getElementById(DivDynamicPageContainerId);

    if (divContainer)
    {
        originalHeight = parseInt(divContainer.style.height, 10);
        var children = divContainer.childNodes;
        for (var i = 0; i < children.length; i++)
        {
            if (children[i].nodeName.toLowerCase() == 'div')
            {
                childHeight = parseInt(children[i].offsetTop) + parseInt(children[i].offsetHeight);
                if (childHeight > maxHeight)
                {
                    maxHeight = childHeight;
                }
            }
        }


        if (originalHeight < maxHeight)
        {
            divContainer.style.height = (maxHeight + 10) + 'px';
        }
    }
}

//*** Trigger the asp.net PostBack
function DoASPPostBack()
{
    try
    {
        __doPostBack('', '');
    }
    catch (e)
    {
        location.reload();
    }
}


//*** Select the content of a Text field
function SelectAllContentInputText(fld)
{
    try
    {
        var start = 0;
        var end = fld.value.length;

        fld.focus();

        if (fld.selectionStart)
        {
            fld.setSelectionRange(start, end);
        }
        else
        {
            var range = fld.createTextRange();
            range.move("character", start), range.moveEnd("character", end), range.select();
        }
    }
    catch (ex)
    {
        alert(ex);
    }
}


//*** creating cookies
function SetCookie(cName, value, expires, path, domain, secure)
{
    var strCookieData = cName + "=" + escape(value) +
     ((expires) ? ";expires=" + expires.toGMTString() : "") +
     ((path) ? ";path=" + path : ";path=" + "/") +
     ((domain) ? ";domain=" + domain : "") +
     ((secure) ? ";secure" : "");

    document.cookie = strCookieData;
}


//*** Read a cookie
function GetCookie(cName)
{
    var temp = document.cookie;
    var find = cName + "=";
    var start = temp.indexOf(find);

    if ((!start) && (cName != temp.substring(0, cName.length))) return null;

    if (start == -1) return null;

    start = start + cName.length + 1;

    var stop = temp.indexOf(";", start);

    if (stop == -1)
    {
        stop = temp.length;
    }

    return unescape(temp.substring(start, stop));
}


//*** Add a function call to the body/window onload event
function AddWindowOnloadEvent(functionName)
{
    if (window.addEventListener)
    {
        window.addEventListener('load', functionName, false);
        return true;
    }
    else if (window.attachEvent)
    {
        var r = window.attachEvent("onload", functionName);
        return r;
    }
    else
    {
        return false;
    }
}


//*** Language Class
function Language(id, name)
{
    this.Id = id;
    this.Name = name;
}

//*** Translation
function Translation(language, content)
{
    this.Language = language;
    this.Content = content;
}

//*** RichText Class
function RichText()
{
    this.Translations = new Array();
    this.ObjectId2 = 0;
    this.WysiwygMode = true;

    //*** Parse XML
    this.SetXML = function SetXML(rawXML)
    {
        var language;
        var languageId = 0;
        var content = '';
        var xmlDocument;
        var i, j;

        try
        {
            //*** Load XML
            if (isIE)
            {
                xmlDocument = new ActiveXObject("Microsoft.XMLDOM");
                xmlDocument.async = "false";
                xmlDocument.loadXML(rawXML);
            }
            else
            {
                var parser = new DOMParser();
                xmlDocument = parser.parseFromString(rawXML, "text/xml");
            }

            //*** Select the richtext node
            var nodes = xmlDocument.getElementsByTagName("richtext");
            if (nodes.length > 0)
            {
                this.ObjectId2 = parseInt(nodes[0].getAttribute("objectid2"), 10);
                this.WysiwygMode = nodes[0].getAttribute("wysiwygmode") == 'True';
            }

            //*** Trying to find the selected language node
            nodes = xmlDocument.getElementsByTagName("translation");

            for (i = 0; i < nodes.length; i++)
            {
                languageId = parseInt(nodes[i].getAttribute("language"), 10);

                if (languageId > 0)
                {
                    language = null;

                    //*** Find language
                    for (j = 0; j < LANGUAGES.length; j++)
                    {
                        if (LANGUAGES[j].Id == languageId)
                        {
                            language = LANGUAGES[j];
                        }
                    }

                    //*** Get Content
                    if (nodes[i].childNodes[0].nodeType == 4)
                    {
                        content = nodes[i].childNodes[0].data;
                    }

                    //*** Manage this.Translation
                    if (language != null)
                    {
                        this.SetContent(language, content);
                    }
                }
            }
        }
        catch (ex)
        { }
    }

    //*** Generate XML
    this.GetXML = function GetXML()
    {
        var rawXML = '';
        var xmlDocument;
        var i;
        var newTranslationNode;
        var newCDATANode;

        //*** Create XML
        rawXML = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?><richtext objectid2="' + this.ObjectId2 + '" wysiwygmode="' + ((this.WysiwygMode) ? 'True' : 'False') + '"></richtext>';

        //*** Load XML
        if (isIE)
        {
            xmlDocument = new ActiveXObject("Microsoft.XMLDOM");
            xmlDocument.async = "false";
            xmlDocument.loadXML(rawXML);
        }
        else
        {
            var parser = new DOMParser();
            xmlDocument = parser.parseFromString(rawXML, "text/xml");
        }

        //*** Create all the Nodes
        for (i = 0; i < this.Translations.length; i++)
        {
            if (this.Translations[i].Content != undefined && this.Translations[i].Content.length > 0)
            {
                newTranslationNode = xmlDocument.createElement("translation");
                newTranslationNode.setAttribute("language", this.Translations[i].Language.Id);

                newCDATANode = xmlDocument.createCDATASection(this.Translations[i].Content);
                newTranslationNode.appendChild(newCDATANode);

                nodes = xmlDocument.getElementsByTagName("richtext");
                if (nodes.length > 0)
                {
                    nodes[0].appendChild(newTranslationNode);
                }
            }
        }

        //*** Output
        if (isIE)
        {
            rawXML = xmlDocument.xml;
        }
        else
        {
            rawXML = (new XMLSerializer()).serializeToString(xmlDocument);
        }

        return rawXML;
    }

    this.SetContent = function SetContent(language, content)
    {
        var blnFound = false;

        for (var j = 0; j < this.Translations.length; j++)
        {
            if (this.Translations[j].Language.Id == language.Id)
            {
                this.Translations[j].Content = content;
                blnFound = true;
            }
        }

        if (!blnFound)
        {
            this.Translations[this.Translations.length] = new Translation(language, content);
        }
    }

    this.GetContent = function GetContent(language)
    {
        var content = '';

        for (var j = 0; j < this.Translations.length; j++)
        {
            if (this.Translations[j].Language.Id == language.Id)
            {
                content = this.Translations[j].Content;
            }
        }

        return content;
    }

    this.ToString = function ToString()
    {
        var content = this.GetContent(new Language(USERLANGUAGE, ''));

        if (content.length == 0)
        {
            content = this.GetContent(new Language(LANGUAGE_DEFAULT_ID, ''));
        }

        return content;
    }
}

/**
* HTML-Encode the supplied input
* 
* Parameters:
*
* (String)  source    The text to be encoded.
* 
* (boolean) display   The output is intended for display.
*
*                     If true:
*                     * Tabs will be expanded to the number of spaces 
*                       indicated by the 'tabs' argument.
*                     * Line breaks will be converted to <br />.
*
*                     If false:
*                     * Tabs and linebreaks get turned into &#____;
*                       entities just like all other control characters.
*
* (integer) tabs      The number of spaces to expand tabs to.  (Ignored 
*                     when the 'display' parameter evaluates to false.)
*
*/
function htmlEncode(source, display, tabs)
{
    function special(source)
    {
        var result = '';
        for (var i = 0; i < source.length; i++)
        {
            var c = source.charAt(i);
            if (c < ' ' || c > '~')
            {
                c = '&#' + c.charCodeAt() + ';';
            }
            result += c;
        }
        return result;
    }
    function format(source)
    {
        // Use only integer part of tabs, and default to 4
        tabs = (tabs >= 0) ? Math.floor(tabs) : 4;
        // split along line breaks
        var lines = source.split(/\r\n|\r|\n/);
        // expand tabs
        for (var i = 0; i < lines.length; i++)
        {
            var line = lines[i];
            var newLine = '';
            for (var p = 0; p < line.length; p++)
            {
                var c = line.charAt(p);
                if (c === '\t')
                {
                    var spaces = tabs - (newLine.length % tabs);
                    for (var s = 0; s < spaces; s++)
                    {
                        newLine += ' ';
                    }
                }
                else
                {
                    newLine += c;
                }
            }
            // If a line starts or ends with a space, it evaporates in html
            // unless it's an nbsp.
            newLine = newLine.replace(/(^ )|( $)/g, '&nbsp;');
            lines[i] = newLine;
        }
        // re-join lines
        var result = lines.join('<br />');
        // break up contiguous blocks of spaces with non-breaking spaces
        result = result.replace(/  /g, ' &nbsp;');
        // tada!
        return result;
    }
    var result = source;
    // ampersands (&)
    result = result.replace(/\&/g, '&amp;');
    // less-thans (<)
    result = result.replace(/\</g, '&lt;');
    // greater-thans (>)
    result = result.replace(/\>/g, '&gt;');
    if (display)
    {
        // format for display
        result = format(result);
    }
    else
    {
        // Replace quotes if it isn't for display,
        // since it's probably going in an html attribute.
        result = result.replace(new RegExp('"', 'g'), '&quot;');
    }
    // special characters
    result = special(result);
    // tada!
    return result;
}

//*** correctly handle PNG transparency in Win IE 5.5 & 6.
function correctPNG()
{
    var arVersion = navigator.appVersion.split("MSIE")
    var version = parseFloat(arVersion[1])
    if ((version >= 5.5) && (document.body.filters))
    {
        for (var i = 0; i < document.images.length; i++)
        {
            var img = document.images[i]
            var imgName = img.src.toUpperCase()
            if (imgName.substring(imgName.length - 3, imgName.length) == "PNG")
            {
                var imgID = (img.id) ? "id='" + img.id + "' " : ""
                var imgClass = (img.className) ? "class='" + img.className + "' " : ""
                var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
                var imgStyle = "display:inline-block;" + img.style.cssText
                if (img.align == "left") imgStyle = "float:left;" + imgStyle
                if (img.align == "right") imgStyle = "float:right;" + imgStyle
                if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
                var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>"
                img.outerHTML = strNewHTML
                i = i - 1
            }
        }
    }
}