//
//  jsrsClient.js - javascript remote scripting client include
//
//  Author:  Brent Ashley [jsrs@megahuge.com]
//
//  make asynchronous remote calls to server without client page refresh
//
//  see license.txt for copyright and license information

/*
 see history.txt for full history
 2.0  26 Jul 2001 - added POST capability for IE/MOZ
 */

// callback pool needs global scope
var jsrsContextPoolSize = 0;
var jsrsContextMaxPool = 10;
var jsrsContextPool = new Array();
var jsrsBrowser = jsrsBrowserSniff();
var jsrsPOST = true;

// constructor for context object
function jsrsContextObj( contextID ){

    // properties
    this.id = contextID;
    this.busy = true;
    this.callback = null;
    this.container = contextCreateContainer( contextID );

    // methods
    this.GET = contextGET;
    this.POST = contextPOST;
    this.getPayload = contextGetPayload;
    this.setVisibility = contextSetVisibility;
}

//  method functions are not privately scoped
//  because Netscape's debugger chokes on private functions
function contextCreateContainer( containerName ){
    // creates hidden container to receive server data
    var container;
    switch( jsrsBrowser ) {
        case 'NS':
            container = new Layer(100);
            container.name = containerName;
            container.visibility = 'hidden';
            container.clip.width = 100;
            container.clip.height = 100;
            break;

        case 'IE':
            document.body.insertAdjacentHTML( "afterBegin", '<span id="SPAN' + containerName + '"></span>' );
            var span = document.all( "SPAN" + containerName );
            var html = '<iframe name="' + containerName + '" src=empty.html""></iframe>';
            span.innerHTML = html;
            span.style.display = 'none';
            container = window.frames[ containerName ];
            break;

        case 'MOZ':
            var span = document.createElement('SPAN');
            span.id = "SPAN" + containerName;
            document.body.appendChild( span );
            var iframe = document.createElement('IFRAME');
            iframe.name = containerName;
            span.appendChild( iframe );
            container = iframe;
            break;

    }
    return container;
}

function contextPOST( rsPage, func, parms ){

    var d = new Date();
    var unique = d.getTime() + '' + Math.floor(1000 * Math.random());
    var doc = (jsrsBrowser == "IE" ) ? this.container.document : this.container.contentDocument;
    doc.open();
    doc.write('<html><body>');
    doc.write('<form name="jsrsForm" method="post" target="" ');
    doc.write(' action="' + rsPage + '?U=' + unique + '">');
    doc.write('<input type="hidden" name="C" value="' + this.id + '">');

    // func and parms are optional
    if (func != null){
        doc.write('<input type="hidden" name="F" value="' + func + '">');

        if (parms != null){
            if (typeof(parms) == "string"){
                // single parameter
                doc.write( '<input type="hidden" name="P0" '
                        + 'value="[' + jsrsEscapeQQ(parms) + ']">');
            } else {
                // assume parms is array of strings
                for( var i=0; i < parms.length; i++ ){
                    doc.write( '<input type="hidden" name="P' + i + '" '
                            + 'value="[' + jsrsEscapeQQ(parms[i]) + ']">');
                }
            } // parm type
        } // parms
    } // func

    doc.write('</form></body></html>');
    doc.close();
    doc.forms['jsrsForm'].submit();
}

function contextGET( rsPage, func, parms ){

    // build URL to call
    var URL = rsPage;

    // always send context
    URL += "?C=" + this.id;

    // func and parms are optional
    if (func != null){
        URL += "&F=" + escape(func);

        if (parms != null){
            if (typeof(parms) == "string"){
                // single parameter
                URL += "&P0=[" + escape(parms+'') + "]";
            } else {
                // assume parms is array of strings
                for( var i=0; i < parms.length; i++ ){
                    URL += "&P" + i + "=[" + escape(parms[i]+'') + "]";
                }
            } // parm type
        } // parms
    } // func

    // unique string to defeat cache
    var d = new Date();
    URL += "&U=" + d.getTime();

    // make the call
    switch( jsrsBrowser ) {
        case 'NS':
            this.container.src = URL;
            break;
        case 'IE':
            this.container.document.location.replace(URL);
            break;
        case 'MOZ':
            this.container.src = '';
            this.container.src = URL;
            break;
    }
}

function contextGetPayload(){
    switch( jsrsBrowser ) {
        case 'NS':
            return this.container.document.forms['jsrs_Form'].elements['jsrs_Payload'].value;
        case 'IE':
            return this.container.document.forms['jsrs_Form']['jsrs_Payload'].value;
        case 'MOZ':
            return window.frames[this.container.name].document.forms['jsrs_Form']['jsrs_Payload'].value;
    }
}

function contextSetVisibility( vis ){
    switch( jsrsBrowser ) {
        case 'NS':
            this.container.visibility = (vis)? 'show' : 'hidden';
            break;
        case 'IE':
            document.all("SPAN" + this.id ).style.display = (vis)? '' : 'none';
            break;
        case 'MOZ':
            document.getElementById("SPAN" + this.id).style.visibility = (vis)? '' : 'hidden';
            this.container.width = (vis)? 250 : 0;
            this.container.height = (vis)? 100 : 0;
            break;
    }
}

// end of context constructor

function jsrsGetContextID(){
    var contextObj;
    for (var i = 1; i <= jsrsContextPoolSize; i++){
        contextObj = jsrsContextPool[ 'jsrs' + i ];
        if ( !contextObj.busy ){
            contextObj.busy = true;
            return contextObj.id;
        }
    }
    // if we got here, there are no existing free contexts
    if ( jsrsContextPoolSize <= jsrsContextMaxPool ){
        // create new context
        var contextID = "jsrs" + (jsrsContextPoolSize + 1);
        jsrsContextPool[ contextID ] = new jsrsContextObj( contextID );
        jsrsContextPoolSize++;
        return contextID;
    } else {
        alert( "jsrs Error:  context pool full" );
        return null;
    }
}

function jsrsExecute( rspage, callback, func, parms, visibility ){
    // call a server routine from client code
    //
    // rspage      - href to asp file
    // callback    - function to call on return
    //               or null if no return needed
    //               (passes returned string to callback)
    // func        - sub or function name  to call
    // parm        - string parameter to function
    //               or array of string parameters if more than one
    // visibility  - optional boolean to make container visible for debugging

    // get context

    //alert('Bongo: ' + rspage + ' ' +  callback + ' ' +  func + ' ' +  parms +  ' ' + visibility);
    var contextObj = jsrsContextPool[ jsrsGetContextID() ];
    contextObj.callback = callback;

    var vis = (visibility == null)? false : visibility;
    contextObj.setVisibility( vis );


    if ( jsrsPOST && ((jsrsBrowser == 'IE') || (jsrsBrowser == 'MOZ'))){
        contextObj.POST( rspage, func, parms );
    } else {
        contextObj.GET( rspage, func, parms );
    }

    return contextObj.id;
}

function jsrsLoaded( contextID ){
    // get context object and invoke callback
    var contextObj = jsrsContextPool[ contextID ];
    if( contextObj.callback != null){
        contextObj.callback( jsrsUnescape( contextObj.getPayload() ), contextID );
    }
    // clean up and return context to pool
    contextObj.callback = null;
    contextObj.busy = false;
}

function jsrsError( contextID, str ){
    alert( unescape(str) );
    jsrsContextPool[ contextID ].busy = false
}

function jsrsEscapeQQ( thing ){
    return thing.replace(/'"'/g, '\\"');
}

function jsrsUnescape( str ){
    // payload has slashes escaped with whacks
    return str.replace( /\\\//g, "/" );
}

function jsrsBrowserSniff(){
    if (document.layers) return "NS";
    if (document.all) return "IE";
    if (document.getElementById) return "MOZ";
    return "OTHER";
}

/////////////////////////////////////////////////
//
// user functions

function jsrsArrayFromString( s, delim ){
    // rebuild an array returned from server as string
    // optional delimiter defaults to ~
    var d = (delim == null)? '~' : delim;
    return s.split(d);
}

function jsrsDebugInfo(){
    // use for debugging by attaching to f1 (works with IE)
    // with onHelp = "return jsrsDebugInfo();" in the body tag
    var doc = window.open().document;
    doc.open;
    doc.write( 'Pool Size: ' + jsrsContextPoolSize + '<br><font face="arial" size="2"><b>' );
    for( var i in jsrsContextPool ){
        var contextObj = jsrsContextPool[i];
        doc.write( '<hr>' + contextObj.id + ' : ' + (contextObj.busy ? 'busy' : 'available') + '<br>');
        doc.write( contextObj.container.document.location.pathname + '<br>');
        doc.write( contextObj.container.document.location.search + '<br>');
        doc.write( '<table border="1"><tr><td>' + contextObj.container.document.body.innerHTML + '</td></tr></table>' );
    }
    doc.write('</table>');
    doc.close();
    return false;
}

function doBongo(){
    alert('bongo');
}/*
 Do not remove or change this notice.
 overlibmws.js core module - Copyright Foteos Macrides 2002-2005. All rights reserved.
 Initial: August 18, 2002 - Last Revised: June 8, 2005
 This module is subject to the same terms of usage as for Erik Bosrup's overLIB,
 though only a minority of the code and API now correspond with Erik's version.
 See the overlibmws Change History and Command Reference via:

 http://www.macridesweb.com/oltest/

 Published under an open source license: http://www.macridesweb.com/oltest/license.html
 Give credit on sites that use overlibmws and submit changes so others can use them as well.
 You can get Erik's version via: http://www.bosrup.com/web/overlib/
 */

// PRE-INIT -- Ignore these lines, configuration is below.
var OLloaded=0,pmCnt=1,pMtr=new Array(),OLcmdLine=new Array(),OLrunTime=new Array(),OLv,OLudf,
        OLpct=new Array("83%","67%","83%","100%","117%","150%","200%","267%"),OLrefXY,
        OLbubblePI=0,OLcrossframePI=0,OLdebugPI=0,OLdraggablePI=0,OLexclusivePI=0,OLfilterPI=0,
        OLfunctionPI=0,OLhidePI=0,OLiframePI=0,OLovertwoPI=0,OLscrollPI=0,OLshadowPI=0,OLprintPI=0;
if(typeof OLgateOK=='undefined')var OLgateOK=1;
var OLp1or2c='inarray,caparray,caption,closetext,right,left,center,autostatuscap,padx,pady,'
        +'below,above,vcenter,donothing',OLp1or2co='nofollow,background,offsetx,offsety,fgcolor,'
        +'bgcolor,cgcolor,textcolor,capcolor,width,wrap,wrapmax,height,border,base,status,autostatus,'
        +'snapx,snapy,fixx,fixy,relx,rely,midx,midy,ref,refc,refp,refx,refy,fgbackground,bgbackground,'
        +'cgbackground,fullhtml,capicon,textfont,captionfont,textsize,captionsize,timeout,delay,hauto,'
        +'vauto,nojustx,nojusty,fgclass,bgclass,cgclass,capbelow,textpadding,textfontclass,'
        +'captionpadding,captionfontclass,sticky,noclose,mouseoff,offdelay,closecolor,closefont,'
        +'closesize,closeclick,closetitle,closefontclass,decode',OLp1or2o='text,cap,close,hpos,vpos,'
        +'padxl,padxr,padyt,padyb',OLp1co='label',OLp1or2=OLp1or2co+','+OLp1or2o,OLp1=OLp1co+','+'frame';
OLregCmds(OLp1or2c+','+OLp1or2co+','+OLp1co);
function OLud(v){return eval('typeof ol_'+v+'=="undefined"')?1:0;}

// DEFAULT CONFIGURATION -- See overlibConfig.txt for descriptions
if(OLud('fgcolor'))var ol_fgcolor="#e6edf5"; //#f0f0f0";
if(OLud('bgcolor'))var ol_bgcolor="#dfe8f6"; //"#333399";
if(OLud('cgcolor'))var ol_cgcolor="#dfe8f6"; //"#333399";
if(OLud('textcolor'))var ol_textcolor="#000000";
if(OLud('capcolor'))var ol_capcolor="#ffffff";
if(OLud('closecolor'))var ol_closecolor="#eeeeff";
if(OLud('textfont'))var ol_textfont="Verdana,Arial,Helvetica";
if(OLud('captionfont'))var ol_captionfont="Verdana,Arial,Helvetica";
if(OLud('closefont'))var ol_closefont="Verdana,Arial,Helvetica";
if(OLud('textsize'))var ol_textsize=3;
if(OLud('captionsize'))var ol_captionsize=3;
if(OLud('closesize'))var ol_closesize=3;
if(OLud('fgclass'))var ol_fgclass="";
if(OLud('bgclass'))var ol_bgclass="";
if(OLud('cgclass'))var ol_cgclass="";
if(OLud('textpadding'))var ol_textpadding=2;
if(OLud('textfontclass'))var ol_textfontclass="";
if(OLud('captionpadding'))var ol_captionpadding=2;
if(OLud('captionfontclass'))var ol_captionfontclass="";
if(OLud('closefontclass'))var ol_closefontclass="";
if(OLud('close'))var ol_close="Close";
if(OLud('closeclick'))var ol_closeclick=0;
if(OLud('closetitle'))var ol_closetitle="Click to Close";
if(OLud('text'))var ol_text="Default Text";
if(OLud('cap'))var ol_cap="";
if(OLud('capbelow'))var ol_capbelow=0;
if(OLud('background'))var ol_background="";
if(OLud('width'))var ol_width=200;
if(OLud('wrap'))var ol_wrap=0;
if(OLud('wrapmax'))var ol_wrapmax=0;
if(OLud('height'))var ol_height= -1;
if(OLud('border'))var ol_border=1;
if(OLud('base'))var ol_base=0;
if(OLud('offsetx'))var ol_offsetx=10;
if(OLud('offsety'))var ol_offsety=10;
if(OLud('sticky'))var ol_sticky=0;
if(OLud('nofollow'))var ol_nofollow=0;
if(OLud('noclose'))var ol_noclose=0;
if(OLud('mouseoff'))var ol_mouseoff=0;
if(OLud('offdelay'))var ol_offdelay=300;
if(OLud('hpos'))var ol_hpos=RIGHT;
if(OLud('vpos'))var ol_vpos=BELOW;
if(OLud('status'))var ol_status="";
if(OLud('autostatus'))var ol_autostatus=0;
if(OLud('snapx'))var ol_snapx=0;
if(OLud('snapy'))var ol_snapy=0;
if(OLud('fixx'))var ol_fixx= -1;
if(OLud('fixy'))var ol_fixy= -1;
if(OLud('relx'))var ol_relx=null;
if(OLud('rely'))var ol_rely=null;
if(OLud('midx'))var ol_midx=null;
if(OLud('midy'))var ol_midy=null;
if(OLud('ref'))var ol_ref="";
if(OLud('refc'))var ol_refc='UL';
if(OLud('refp'))var ol_refp='UL';
if(OLud('refx'))var ol_refx=0;
if(OLud('refy'))var ol_refy=0;
if(OLud('fgbackground'))var ol_fgbackground="";
if(OLud('bgbackground'))var ol_bgbackground="";
if(OLud('cgbackground'))var ol_cgbackground="";
if(OLud('padxl'))var ol_padxl=1;
if(OLud('padxr'))var ol_padxr=1;
if(OLud('padyt'))var ol_padyt=1;
if(OLud('padyb'))var ol_padyb=1;
if(OLud('fullhtml'))var ol_fullhtml=0;
if(OLud('capicon'))var ol_capicon="";
if(OLud('frame'))var ol_frame=self;
if(OLud('timeout'))var ol_timeout=0;
if(OLud('delay'))var ol_delay=0;
if(OLud('hauto'))var ol_hauto=0;
if(OLud('vauto'))var ol_vauto=0;
if(OLud('nojustx'))var ol_nojustx=0;
if(OLud('nojusty'))var ol_nojusty=0;
if(OLud('label'))var ol_label="";
if(OLud('decode'))var ol_decode=0;
// ARRAY CONFIGURATION - See overlibConfig.txt for descriptions.
if(OLud('texts'))var ol_texts=new Array("Text 0","Text 1");
if(OLud('caps'))var ol_caps=new Array("Caption 0","Caption 1");
// END CONFIGURATION -- Don't change anything below, all configuration is above.

// INIT -- Runtime variables.
var o3_text="",o3_cap="",o3_sticky=0,o3_nofollow=0,o3_background="",o3_noclose=0,o3_mouseoff=0,
        o3_offdelay=300,o3_hpos=RIGHT,o3_offsetx=10,o3_offsety=10,o3_fgcolor="",o3_bgcolor="",
        o3_cgcolor="",o3_textcolor="",o3_capcolor="",o3_closecolor="",o3_width=200,o3_wrap=0,
        o3_wrapmax=0,o3_height= -1,o3_border=1,o3_base=0,o3_status="",o3_autostatus=0,o3_snapx=0,
        o3_snapy=0,o3_fixx= -1,o3_fixy= -1,o3_relx=null,o3_rely=null,o3_midx=null,o3_midy=null,o3_ref="",
        o3_refc='UL',o3_refp='UL',o3_refx=0,o3_refy=0,o3_fgbackground="",o3_bgbackground="",
        o3_cgbackground="",o3_padxl=0,o3_padxr=0,o3_padyt=0,o3_padyb=0,o3_fullhtml=0,o3_vpos=BELOW,
        o3_capicon="",o3_textfont="Verdana,Arial,Helvetica",o3_captionfont="",o3_closefont="",
        o3_textsize=1,o3_captionsize=1,o3_closesize=1,o3_frame=self,o3_timeout=0,o3_delay=0,o3_hauto=0,
        o3_vauto=0,o3_nojustx=0,o3_nojusty=0,o3_close="",o3_closeclick=0,o3_closetitle="",o3_fgclass="",
        o3_bgclass="",o3_cgclass="",o3_textpadding=2,o3_textfontclass="",o3_captionpadding=2,
        o3_captionfontclass="",o3_closefontclass="",o3_capbelow=0,o3_label="",o3_decode=0,
        CSSOFF=DONOTHING,CSSCLASS=DONOTHING,OLdelayid=0,OLtimerid=0,OLshowid=0,OLndt=0,over=null,
        OLfnRef="",OLhover=0,OLx=0,OLy=0,OLshowingsticky=0,OLallowmove=0,OLcC=null,
        OLua=navigator.userAgent.toLowerCase(),
        OLns4=(navigator.appName=='Netscape'&&parseInt(navigator.appVersion)==4),
        OLns6=(document.getElementById)?1:0,
        OLie4=(document.all)?1:0,
        OLgek=(OLv=OLua.match(/gecko\/(\d{8})/i))?parseInt(OLv[1]):0,
        OLmac=(OLua.indexOf('mac')>=0)?1:0,
        OLsaf=(OLua.indexOf('safari')>=0)?1:0,
        OLkon=(OLua.indexOf('konqueror')>=0)?1:0,
        OLkht=(OLsaf||OLkon)?1:0,
        OLopr=(OLua.indexOf('opera')>=0)?1:0,
        OLop7=(OLopr&&document.createTextNode)?1:0;
if(OLopr){OLns4=OLns6=0;if(!OLop7)OLie4=0;}
var OLieM=((OLie4&&OLmac)&&!(OLkht||OLopr))?1:0,
        OLie5=0,OLie55=0;if(OLie4&&!OLop7){
    if((OLv=OLua.match(/msie (\d\.\d+)\.*/i))&&(OLv=parseFloat(OLv[1]))>=5.0){
        OLie5=1;OLns6=0;if(OLv>=5.5)OLie55=1;}if(OLns6)OLie4=0;}
if(OLns4)window.onresize=function(){location.reload();}
var OLchkMh=1,OLdw;
if(OLns4||OLie4||OLns6)OLmh();
else{overlib=nd=cClick=OLpageDefaults=no_overlib;}

/*
 PUBLIC FUNCTIONS
 */
// Loads defaults then args into runtime variables.
function overlib(){
    if(!(OLloaded&&OLgateOK))return;
    if((OLexclusivePI)&&OLisExclusive(arguments))return true;
    if(OLchkMh)OLmh();
    if(OLndt&&!OLtimerid)OLndt=0;if(over)cClick();
    OLload(OLp1or2);OLload(OLp1);
    OLfnRef="";OLhover=0;
    OLsetRunTimeVar();
    OLparseTokens('o3_',arguments);
    if(!(over=OLmkLyr()))return false;
    if(o3_decode)OLdecode();
    if(OLprintPI)OLchkPrint();
    if(OLbubblePI)OLchkForBubbleEffect();
    if(OLdebugPI)OLsetDebugCanShow();
    if(OLshadowPI)OLinitShadow();
    if(OLiframePI)OLinitIfs();
    if(OLfilterPI)OLinitFilterLyr();
    if(OLexclusivePI&&o3_exclusive&&o3_exclusivestatus!="")o3_status=o3_exclusivestatus;
    else if(o3_autostatus==2&&o3_cap!="")o3_status=o3_cap;
    else if(o3_autostatus==1&&o3_text!="")o3_status=o3_text;
    if(!o3_delay){return OLmain();
    }else{OLdelayid=setTimeout("OLmain()",o3_delay);
        if(o3_status!=""){self.status=o3_status;return true;}
        else if(!(OLop7&&event&&event.type=='mouseover'))return false;}
}

// Clears popups if appropriate
function nd(time){
    if(OLloaded&&OLgateOK){if(!((OLexclusivePI)&&OLisExclusive())){
        if(time&&over&&!o3_delay){if(OLtimerid>0)clearTimeout(OLtimerid);
            OLtimerid=(OLhover&&o3_frame==self&&!OLcursorOff())?0:
                      setTimeout("cClick()",(o3_timeout=OLndt=time));}else{
            if(!OLshowingsticky){OLallowmove=0;if(over)OLhideObject(over);}}}}
    return false;
}

// Close function for stickies
function cClick(){
    if(OLloaded&&OLgateOK){OLhover=0;if(over){
        if(OLovertwoPI&&over==over2)cClick2();OLhideObject(over);OLshowingsticky=0;}}
    return false;
}

// Sets page-specific defaults.
function OLpageDefaults(){
    OLparseTokens('ol_',arguments);
}

// For unsupported browsers.
function no_overlib(){return false;}

/*
 OVERLIB MAIN FUNCTION SET
 */
function OLmain(){
    o3_delay=0;
    if(o3_frame==self){if(o3_noclose)OLoptMOUSEOFF(0);else if(o3_mouseoff)OLoptMOUSEOFF(1);}
    if(o3_sticky)OLshowingsticky=1;OLdoLyr();OLallowmove=0;if(o3_timeout>0){
    if(OLtimerid>0)clearTimeout(OLtimerid);OLtimerid=setTimeout("cClick()",o3_timeout);}
    if(o3_ref){OLrefXY=OLgetRefXY(o3_ref);if(OLrefXY[0]==null){o3_ref="";o3_midx=0;o3_midy=0;}}
    OLdisp(o3_status);if(OLdraggablePI)OLcheckDrag();
    if(o3_status!="")return true;else if(!(OLop7&&event&&event.type=='mouseover'))return false;
}

// Loads o3_ variables
function OLload(c){var i,m=c.split(',');for(i=0;i<m.length;i++)eval('o3_'+m[i]+'=ol_'+m[i]);}

// Chooses LGF
function OLdoLGF(){
    return (o3_background!=''||o3_fullhtml)?OLcontentBackground(o3_text,o3_background,o3_fullhtml):
           (o3_cap=="")?OLcontentSimple(o3_text):
           (o3_sticky)?OLcontentCaption(o3_text,o3_cap,o3_close):OLcontentCaption(o3_text,o3_cap,'');
}

// Makes Layer
function OLmkLyr(id,f,z){
    id=(id||'overDiv');f=(f||o3_frame);z=(z||1000);var fd=f.document,d=OLgetRefById(id,fd);
    if(!d){if(OLns4)d=fd.layers[id]=new Layer(1024,f);else if(OLie4&&!document.getElementById){
        fd.body.insertAdjacentHTML('BeforeEnd','<div id="'+id+'"></div>');d=fd.all[id];
    }else{d=fd.createElement('div');if(d){d.id=id;fd.body.appendChild(d);}}if(!d)return null;
        if(OLns4)d.zIndex=z;else{var o=d.style;o.position='absolute';o.visibility='hidden';o.zIndex=z;}}
    return d;
}

// Creates and writes layer content
function OLdoLyr(){
    if(o3_background==''&&!o3_fullhtml){
        if(o3_fgbackground!='')o3_fgbackground=' background="'+o3_fgbackground+'"';
        if(o3_bgbackground!='')o3_bgbackground=' background="'+o3_bgbackground+'"';
        if(o3_cgbackground!='')o3_cgbackground=' background="'+o3_cgbackground+'"';
        if(o3_fgcolor!='')o3_fgcolor=' bgcolor="'+o3_fgcolor+'"';
        if(o3_bgcolor!='')o3_bgcolor=' bgcolor="'+o3_bgcolor+'"';
        if(o3_cgcolor!='')o3_cgcolor=' bgcolor="'+o3_cgcolor+'"';
        if(o3_height>0)o3_height=' height="'+o3_height+'"';else o3_height='';}
    if(!OLns4)OLrepositionTo(over,(OLns6?20:0),0);var lyrHtml=OLdoLGF();
    if(o3_sticky&&OLtimerid>0){clearTimeout(OLtimerid);OLtimerid=0;}
    if(o3_wrap&&!o3_fullhtml){OLlayerWrite(lyrHtml);
        o3_width=(OLns4?over.clip.width:over.offsetWidth);
        if(OLns4&&o3_wrapmax<1)o3_wrapmax=o3_frame.innerWidth-40;
        o3_wrap=0;if(o3_wrapmax>0&&o3_width>o3_wrapmax)o3_width=o3_wrapmax;lyrHtml=OLdoLGF();}
    OLlayerWrite(lyrHtml);o3_width=(OLns4?over.clip.width:over.offsetWidth);
    if(OLbubblePI)OLgenerateBubble(lyrHtml);
}

/*
 LAYER GENERATION FUNCTIONS
 */
// Makes simple table without caption
function OLcontentSimple(txt){
    var t=OLbgLGF()+OLfgLGF(txt)+OLbaseLGF();
    OLsetBackground('');return t;
}

// Makes table with caption and optional close link
function OLcontentCaption(txt,title,close){
    var closing=(OLprintPI?OLprintCapLGF():''),closeevent='onmouseover',caption,t,
            cC='javascript:return '+OLfnRef+(OLovertwoPI&&over==over2?'cClick2();':'cClick();');
    if(o3_closeclick)closeevent=(o3_closetitle?'title="'+o3_closetitle+'" ':'')+'onclick';
    if(o3_capicon!='')o3_capicon='<img src="'+o3_capicon+'" /> ';
    if(close){closing+='<td align="right"><a href="javascript:void(0);" '
            +closeevent+'="'+cC+'"'+(o3_closefontclass?' class="'+o3_closefontclass
            +'">':'>'+OLlgfUtil(0,'','span',o3_closecolor,o3_closefont,o3_closesize))+close
            +(o3_closefontclass?'':OLlgfUtil(1,'','span'))+'</a></td>';}
    caption='<table'+OLwd(0)+' border="0" cellpadding="'+o3_captionpadding+'" cellspacing="0"'
            +(o3_cgclass?' class="'+o3_cgclass+'"':o3_cgcolor+o3_cgbackground)+'><tr><td'+OLwd(0)
            +(o3_cgclass?' class="'+o3_cgclass+'">':'>')+(o3_captionfontclass?'<div class="'
            +o3_captionfontclass+'">':'<strong>'
            +OLlgfUtil(0,'','div',o3_capcolor,o3_captionfont,o3_captionsize))+o3_capicon+title
            +OLlgfUtil(1,'','div')+(o3_captionfontclass?'':'</strong>')+'</td>'+closing+'</tr></table>';
    t=OLbgLGF()+(o3_capbelow?OLfgLGF(txt)+caption:caption+OLfgLGF(txt))+OLbaseLGF();
    OLsetBackground('');return t;
}

// For BACKGROUND and FULLHTML commands
function OLcontentBackground(txt, image, hasfullhtml){
    var t;if(hasfullhtml){t=txt;}else{t='<table'+OLwd(1)
        +' border="0" cellpadding="0" cellspacing="0" '+'height="'+o3_height
        +'"><tr><td colspan="3" height="'+o3_padyt+'"></td></tr><tr><td width="'
        +o3_padxl+'"></td><td valign="top"'+OLwd(2)+'>'
        +OLlgfUtil(0,o3_textfontclass,'div',o3_textcolor,o3_textfont,o3_textsize)+txt+
                                        OLlgfUtil(1,'','div')+'</td><td width="'+o3_padxr+'"></td></tr><tr><td colspan="3" height="'
        +o3_padyb+'"></td></tr></table>';}
    OLsetBackground(image);return t;
}

// LGF utilities
function OLbgLGF(){
    return '<table'+OLwd(1)+o3_height+' border="0" cellpadding="'+o3_border+'" cellspacing="0"'
            +(o3_bgclass?' class="'+o3_bgclass+'"':o3_bgcolor+o3_bgbackground)+'><tr><td>';
}
function OLfgLGF(t){
    return '<table'+OLwd(0)+o3_height+' border="0" cellpadding="'+o3_textpadding
            +'" cellspacing="0"'+(o3_fgclass?' class="'+o3_fgclass+'"':o3_fgcolor+o3_fgbackground)
            +'><tr><td valign="top"'+(o3_fgclass?' class="'+o3_fgclass+'"':'')+'>'
            +OLlgfUtil(0,o3_textfontclass,'div',o3_textcolor,o3_textfont,o3_textsize)+t
            +(OLprintPI?OLprintFgLGF():'')+OLlgfUtil(1,'','div')+'</td></tr></table>';
}
function OLlgfUtil(end,tfc,ele,col,fac,siz){
    if(end)return ('</'+(OLns4?'font':ele)+'>');else return (tfc?'<div class="'+tfc+'">':
                                                             ('<'+(OLns4?'font color="'+col+'" face="'+OLquoteMultiNameFonts(fac)+'" size="'+siz:ele
                                                                     +' style="color:'+col+';font-family:'+OLquoteMultiNameFonts(fac)+';font-size:'+siz+';'
                                                                     +(ele=='span'?'text-decoration:underline;':''))+'">'));
}
function OLquoteMultiNameFonts(f){
    var i,v,pM=f.split(',');
    for(i=0;i<pM.length;i++){v=pM[i];v=v.replace(/^\s+/,'').replace(/\s+$/,'');
        if(/\s/.test(v) && !/['"]/.test(v)){v="\'"+v+"\'";pM[i]=v;}}
    return pM.join();
}
function OLbaseLGF(){
    return ((o3_base>0&&!o3_wrap)?('<table width="100%" border="0" cellpadding="0" cellspacing="0"'
            +(o3_bgclass?' class="'+o3_bgclass+'"':'')+'><tr><td height="'+o3_base
            +'"></td></tr></table>'):'')+'</td></tr></table>';
}
function OLwd(a){
    return(o3_wrap?'':' width="'+(!a?'100%':(a==1?o3_width:(o3_width-o3_padxl-o3_padxr)))+'"');
}

// Loads image into the div.
function OLsetBackground(i){
    if(i==''){if(OLns4)over.background.src=null;
    else{if(OLns6)over.style.width='';over.style.backgroundImage='none';}
    }else{if(OLns4)over.background.src=i;
    else{if(OLns6)over.style.width=o3_width+'px';over.style.backgroundImage='url('+i+')';}}
}

/*
 HANDLING FUNCTIONS
 */
// Displays layer
function OLdisp(s){
    if(!OLallowmove){if(OLshadowPI)OLdispShadow();if(OLiframePI)OLdispIfs();OLplaceLayer();
        if(OLndt)OLshowObject(over);else OLshowid=setTimeout("OLshowObject(over)",1);
        OLallowmove=(o3_sticky||o3_nofollow)?0:1;}OLndt=0;if(s!="")self.status=s;
}

// Decides placement of layer.
function OLplaceLayer(){
    var snp,X,Y,pgLeft,pgTop,pWd=o3_width,pHt,iWd=100,iHt=100,SB=0,LM=0,CX=0,TM=0,BM=0,CY=0,
            o=OLfd(),nsb=(OLgek>=20010505&&!o3_frame.scrollbars.visible)?1:0;
    if(!OLkht&&o&&o.clientWidth)iWd=o.clientWidth;
    else if(o3_frame.innerWidth){SB=Math.ceil(1.4*(o3_frame.outerWidth-o3_frame.innerWidth));
        if(SB>20)SB=20;iWd=o3_frame.innerWidth;}
    pgLeft=(OLie4)?o.scrollLeft:o3_frame.pageXOffset;
    if(OLie55&&OLfilterPI&&o3_filter&&o3_filtershadow)SB=CX=5;else
        if((OLshadowPI)&&bkdrop&&o3_shadow&&o3_shadowx){SB+=((o3_shadowx>0)?o3_shadowx:0);
            LM=((o3_shadowx<0)?Math.abs(o3_shadowx):0);CX=Math.abs(o3_shadowx);}
    if(o3_ref!=""||o3_fixx> -1||o3_relx!=null||o3_midx!=null){
        if(o3_ref!=""){X=OLrefXY[0];if(OLie55&&OLfilterPI&&o3_filter&&o3_filtershadow){
            if(o3_refp=='UR'||o3_refp=='LR')X-=5;}
        else if((OLshadowPI)&&bkdrop&&o3_shadow&&o3_shadowx){
            if(o3_shadowx<0&&(o3_refp=='UL'||o3_refp=='LL'))X-=o3_shadowx;else
                if(o3_shadowx>0&&(o3_refp=='UR'||o3_refp=='LR'))X-=o3_shadowx;}
        }else{if(o3_midx!=null){
            X=parseInt(pgLeft+((iWd-pWd-SB-LM)/2)+o3_midx);
        }else{if(o3_relx!=null){
            if(o3_relx>=0)X=pgLeft+o3_relx+LM;else X=pgLeft+o3_relx+iWd-pWd-SB;
        }else{X=o3_fixx+LM;}}}
    }else{
        if(o3_hauto){
            if(o3_hpos==LEFT&&OLx-pgLeft<iWd/2&&OLx-pWd-o3_offsetx<pgLeft+LM)o3_hpos=RIGHT;else
                if(o3_hpos==RIGHT&&OLx-pgLeft>iWd/2&&OLx+pWd+o3_offsetx>pgLeft+iWd-SB)o3_hpos=LEFT;}
        X=(o3_hpos==CENTER)?parseInt(OLx-((pWd+CX)/2)+o3_offsetx):
          (o3_hpos==LEFT)?OLx-o3_offsetx-pWd:OLx+o3_offsetx;
        if(o3_snapx>1){
            snp=X % o3_snapx;
            if(o3_hpos==LEFT){X=X-(o3_snapx+snp);}else{X=X+(o3_snapx-snp);}}}
    if(!o3_nojustx&&X+pWd>pgLeft+iWd-SB)
        X=iWd+pgLeft-pWd-SB;if(!o3_nojustx&&X-LM<pgLeft)X=pgLeft+LM;
    pgTop=OLie4?o.scrollTop:o3_frame.pageYOffset;
    if(!OLkht&&!nsb&&o&&o.clientHeight)iHt=o.clientHeight;
    else if(o3_frame.innerHeight)iHt=o3_frame.innerHeight;
    if(OLbubblePI&&o3_bubble)pHt=OLbubbleHt;else pHt=OLns4?over.clip.height:over.offsetHeight;
    if((OLshadowPI)&&bkdrop&&o3_shadow&&o3_shadowy){TM=(o3_shadowy<0)?Math.abs(o3_shadowy):0;
        if(OLie55&&OLfilterPI&&o3_filter&&o3_filtershadow)BM=CY=5;else
            BM=(o3_shadowy>0)?o3_shadowy:0;CY=Math.abs(o3_shadowy);}
    if(o3_ref!=""||o3_fixy> -1||o3_rely!=null||o3_midy!=null){
        if(o3_ref!=""){Y=OLrefXY[1];if(OLie55&&OLfilterPI&&o3_filter&&o3_filtershadow){
            if(o3_refp=='LL'||o3_refp=='LR')Y-=5;}else if((OLshadowPI)&&bkdrop&&o3_shadow&&o3_shadowy){
            if(o3_shadowy<0&&(o3_refp=='UL'||o3_refp=='UR'))Y-=o3_shadowy;else
                if(o3_shadowy>0&&(o3_refp=='LL'||o3_refp=='LR'))Y-=o3_shadowy;}
        }else{if(o3_midy!=null){
            Y=parseInt(pgTop+((iHt-pHt-CY)/2)+o3_midy);
        }else{if(o3_rely!=null){
            if(o3_rely>=0)Y=pgTop+o3_rely+TM;else Y=pgTop+o3_rely+iHt-pHt-BM;}else{
            Y=o3_fixy+TM;}}}
    }else{
        if(o3_vauto){
            if(o3_vpos==ABOVE&&OLy-pgTop<iHt/2&&OLy-pHt-o3_offsety<pgTop)o3_vpos=BELOW;else
                if(o3_vpos==BELOW&&OLy-pgTop>iHt/2&&OLy+pHt+o3_offsety+((OLns4||OLkht)?17:0)>pgTop+iHt-BM)
                    o3_vpos=ABOVE;}Y=(o3_vpos==VCENTER)?parseInt(OLy-((pHt+CY)/2)+o3_offsety):
                                     (o3_vpos==ABOVE)?OLy-(pHt+o3_offsety+BM):OLy+o3_offsety+TM;
        if(o3_snapy>1){
            snp=Y % o3_snapy;
            if(pHt>0&&o3_vpos==ABOVE){Y=Y-(o3_snapy+snp);}else{Y=Y+(o3_snapy-snp);}}}
    if(!o3_nojusty&&Y+pHt+BM>pgTop+iHt)Y=pgTop+iHt-pHt-BM;if(!o3_nojusty&&Y-TM<pgTop)Y=pgTop+TM;
    OLrepositionTo(over,X,Y);
    if(OLshadowPI)OLrepositionShadow(X,Y);if(OLiframePI)OLrepositionIfs(X,Y);
    if(OLns6&&o3_frame.innerHeight){iHt=o3_frame.innerHeight;OLrepositionTo(over,X,Y);}
    if(OLscrollPI)OLchkScroll(X-pgLeft,Y-pgTop);
}

// Chooses body or documentElement
function OLfd(f){
    var fd=((f)?f:o3_frame).document,fdc=fd.compatMode,fdd=fd.documentElement;
    return (!OLop7&&fdc&&fdc!='BackCompat'&&fdd&&fdd.clientWidth)?fd.documentElement:fd.body;
}

// Gets location of REFerence object
function OLgetRefXY(r){
    var o=OLgetRef(r),ob=o,rXY=[o3_refx,o3_refy],of;
    if(!o)return [null,null];
    if(OLns4){if(typeof o.length!='undefined'&&o.length>1){
        ob=o[0];rXY[0]+=o[0].x+o[1].pageX;rXY[1]+=o[0].y+o[1].pageY;
    }else{if((o.toString().indexOf('Image')!= -1)||(o.toString().indexOf('Anchor')!= -1)){
        rXY[0]+=o.x;rXY[1]+=o.y;}else{rXY[0]+=o.pageX;rXY[1]+=o.pageY;}}
    }else{rXY[0]+=OLpageLoc(o,'Left');rXY[1]+=OLpageLoc(o,'Top');}
    of=OLgetRefOffsets(ob);rXY[0]+=of[0];rXY[1]+=of[1];
    return rXY;
}
function OLgetRef(l){var r=OLgetRefById(l);return (r)?r:OLgetRefByName(l);}

// Seeks REFerence by id
function OLgetRefById(l,d){
    var r="",j;l=(l||'overDiv');d=(d||o3_frame.document);
    if(OLie4&&d.all){return d.all[l];}else if(d.getElementById){return d.getElementById(l);
    }else if(d.layers&&d.layers.length>0){if(d.layers[l])return d.layers[l];
        for(j=0;j<d.layers.length;j++){r=OLgetRefById(l,d.layers[j].document);if(r)return r;}}
    return null;
}

// Seeks REFerence by name (for img and a)
function OLgetRefByName(l,d){
    var r=null,j;d=(d||o3_frame.document);
    if(typeof d.images[l]!='undefined'&&d.images[l]){return d.images[l];
    }else if(typeof d.anchors[l]!='undefined'&&d.anchors[l]){return d.anchors[l];
    }else if(d.layers&&d.layers.length>0){
        for(j=0;j<d.layers.length;j++){r=OLgetRefByName(l,d.layers[j].document);
            if(r&&r.length>0)return r;else if(r)return [r,d.layers[j]];}}
    return null;
}

// Gets layer vs REFerence offsets
function OLgetRefOffsets(o){
    var c=o3_refc.toUpperCase(),p=o3_refp.toUpperCase(),W=0,H=0,pW=0,pH=0,of=[0,0];
    pW=(OLbubblePI&&o3_bubble)?o3_width:OLns4?over.clip.width:over.offsetWidth;
    pH=(OLbubblePI&&o3_bubble)?OLbubbleHt:OLns4?over.clip.height:over.offsetHeight;
    if((!OLop7)&&o.toString().indexOf('Image')!= -1){W=o.width;H=o.height;
    }else if((!OLop7)&&o.toString().indexOf('Anchor')!= -1){c=o3_refc='UL';}else{
        W=(OLns4)?o.clip.width:o.offsetWidth;H=(OLns4)?o.clip.height:o.offsetHeight;}
    if((OLns4||(OLns6&&OLgek))&&o.border){W+=2*parseInt(o.border);H+=2*parseInt(o.border);}
    if(c=='UL'){of=(p=='UR')?[-pW,0]:(p=='LL')?[0,-pH]:(p=='LR')?[-pW,-pH]:[0,0];
    }else if(c=='UR'){of=(p=='UR')?[W-pW,0]:(p=='LL')?[W,-pH]:(p=='LR')?[W-pW,-pH]:[W,0];
    }else if(c=='LL'){of=(p=='UR')?[-pW,H]:(p=='LL')?[0,H-pH]:(p=='LR')?[-pW,H-pH]:[0,H];
    }else if(c=='LR'){of=(p=='UR')?[W-pW,H]:(p=='LL')?[W,H-pH]:(p=='LR')?[W-pW,H-pH]:
                                                               [W,H];}
    return of;
}

// Gets x or y location of object
function OLpageLoc(o,t){
    var l=0;while(o.offsetParent&&o.offsetParent.tagName.toLowerCase()!='html'){
    l+=o['offset'+t];o=o.offsetParent;}l+=o['offset'+t];
    return l;
}

// Moves layer
function OLmouseMove(e){
    var e=(e||event);
    OLcC=(OLovertwoPI&&over2&&over==over2?cClick2:cClick);
    OLx=(e.pageX||e.clientX+OLfd().scrollLeft);OLy=(e.pageY||e.clientY+OLfd().scrollTop);
    if((OLallowmove&&over)&&(o3_frame==self||over==OLgetRefById())){
        OLplaceLayer();if(OLhidePI)OLhideUtil(0,1,1,0,0,0);}
    if(OLhover&&over&&o3_frame==self&&OLcursorOff())if(o3_offdelay<1)OLcC();else
    {if(OLtimerid>0)clearTimeout(OLtimerid);OLtimerid=setTimeout("OLcC()",o3_offdelay);}
}

// Capture mouse and chain other scripts.
function OLmh(){
    var fN,f,j,k,s,mh=OLmouseMove,w=(OLns4&&window.onmousemove),re=/function[ ]*(\w*)\(/;
    OLdw=document;if(document.onmousemove||w){if(w)OLdw=window;f=OLdw.onmousemove.toString();
    fN=f.match(re);if(!fN||fN[1]=='anonymous'||fN[1]=='OLmouseMove'){OLchkMh=0;return;}
    if(fN[1])s=fN[1]+'(e)';else{j=f.indexOf('{');k=f.lastIndexOf('}')+1;s=f.substring(j,k);}
    s+=';OLmouseMove(e);';mh=new Function('e',s);}
    OLdw.onmousemove=mh;if(OLns4)OLdw.captureEvents(Event.MOUSEMOVE);
}

/*
 PARSING
 */
function OLparseTokens(pf,ar){
    var i,v,md= -1,par=(pf!='ol_'),p=OLpar,q=OLparQuo,t=OLtoggle;OLudf=(par&&!ar.length?1:0);
    for(i=0;i< ar.length;i++){if(md<0){if(typeof ar[i]=='number'){OLudf=(par?1:0);i--;}
    else{switch(pf){case 'ol_':ol_text=ar[i];break;default:o3_text=ar[i];}}md=0;
    }else{
        if(ar[i]==INARRAY){OLudf=0;eval(pf+'text=ol_texts['+ar[++i]+']');continue;}
        if(ar[i]==CAPARRAY){eval(pf+'cap=ol_caps['+ar[++i]+']');continue;}
        if(ar[i]==CAPTION){q(ar[++i],pf+'cap');continue;}
        if(Math.abs(ar[i])==STICKY){t(ar[i],pf+'sticky');continue;}
        if(Math.abs(ar[i])==NOFOLLOW){t(ar[i],pf+'nofollow');continue;}
        if(ar[i]==BACKGROUND){q(ar[++i],pf+'background');continue;}
        if(Math.abs(ar[i])==NOCLOSE){t(ar[i],pf+'noclose');continue;}
        if(Math.abs(ar[i])==MOUSEOFF){t(ar[i],pf+'mouseoff');continue;}
        if(ar[i]==OFFDELAY){p(ar[++i],pf+'offdelay');continue;}
        if(ar[i]==RIGHT||ar[i]==LEFT||ar[i]==CENTER){p(ar[i],pf+'hpos');continue;}
        if(ar[i]==OFFSETX){p(ar[++i],pf+'offsetx');continue;}
        if(ar[i]==OFFSETY){p(ar[++i],pf+'offsety');continue;}
        if(ar[i]==FGCOLOR){q(ar[++i],pf+'fgcolor');continue;}
        if(ar[i]==BGCOLOR){q(ar[++i],pf+'bgcolor');continue;}
        if(ar[i]==CGCOLOR){q(ar[++i],pf+'cgcolor');continue;}
        if(ar[i]==TEXTCOLOR){q(ar[++i],pf+'textcolor');continue;}
        if(ar[i]==CAPCOLOR){q(ar[++i],pf+'capcolor');continue;}
        if(ar[i]==CLOSECOLOR){q(ar[++i],pf+'closecolor');continue;}
        if(ar[i]==WIDTH){p(ar[++i],pf+'width');continue;}
        if(Math.abs(ar[i])==WRAP){t(ar[i],pf+'wrap');continue;}
        if(ar[i]==WRAPMAX){p(ar[++i],pf+'wrapmax');continue;}
        if(ar[i]==HEIGHT){p(ar[++i],pf+'height');continue;}
        if(ar[i]==BORDER){p(ar[++i],pf+'border');continue;}
        if(ar[i]==BASE){p(ar[++i],pf+'base');continue;}
        if(ar[i]==STATUS){q(ar[++i],pf+'status');continue;}
        if(Math.abs(ar[i])==AUTOSTATUS){v=pf+'autostatus';
            eval(v+'=('+ar[i]+'<0)?('+v+'==2?2:0):('+v+'==1?0:1)');continue;}
        if(Math.abs(ar[i])==AUTOSTATUSCAP){v=pf+'autostatus';
            eval(v+'=('+ar[i]+'<0)?('+v+'==1?1:0):('+v+'==2?0:2)');continue;}
        if(ar[i]==CLOSETEXT){q(ar[++i],pf+'close');continue;}
        if(ar[i]==SNAPX){p(ar[++i],pf+'snapx');continue;}
        if(ar[i]==SNAPY){p(ar[++i],pf+'snapy');continue;}
        if(ar[i]==FIXX){p(ar[++i],pf+'fixx');continue;}
        if(ar[i]==FIXY){p(ar[++i],pf+'fixy');continue;}
        if(ar[i]==RELX){p(ar[++i],pf+'relx');continue;}
        if(ar[i]==RELY){p(ar[++i],pf+'rely');continue;}
        if(ar[i]==MIDX){p(ar[++i],pf+'midx');continue;}
        if(ar[i]==MIDY){p(ar[++i],pf+'midy');continue;}
        if(ar[i]==REF){q(ar[++i],pf+'ref');continue;}
        if(ar[i]==REFC){q(ar[++i],pf+'refc');continue;}
        if(ar[i]==REFP){q(ar[++i],pf+'refp');continue;}
        if(ar[i]==REFX){p(ar[++i],pf+'refx');continue;}
        if(ar[i]==REFY){p(ar[++i],pf+'refy');continue;}
        if(ar[i]==FGBACKGROUND){q(ar[++i],pf+'fgbackground');continue;}
        if(ar[i]==BGBACKGROUND){q(ar[++i],pf+'bgbackground');continue;}
        if(ar[i]==CGBACKGROUND){q(ar[++i],pf+'cgbackground');continue;}
        if(ar[i]==PADX){p(ar[++i],pf+'padxl');p(ar[++i],pf+'padxr');continue;}
        if(ar[i]==PADY){p(ar[++i],pf+'padyt');p(ar[++i],pf+'padyb');continue;}
        if(Math.abs(ar[i])==FULLHTML){t(ar[i],pf+'fullhtml');continue;}
        if(ar[i]==BELOW||ar[i]==ABOVE||ar[i]==VCENTER){p(ar[i],pf+'vpos');continue;}
        if(ar[i]==CAPICON){q(ar[++i],pf+'capicon');continue;}
        if(ar[i]==TEXTFONT){q(ar[++i],pf+'textfont');continue;}
        if(ar[i]==CAPTIONFONT){q(ar[++i],pf+'captionfont');continue;}
        if(ar[i]==CLOSEFONT){q(ar[++i],pf+'closefont');continue;}
        if(ar[i]==TEXTSIZE){q(ar[++i],pf+'textsize');continue;}
        if(ar[i]==CAPTIONSIZE){q(ar[++i],pf+'captionsize');continue;}
        if(ar[i]==CLOSESIZE){q(ar[++i],pf+'closesize');continue;}
        if(ar[i]==TIMEOUT){p(ar[++i],pf+'timeout');continue;}
        if(ar[i]==DELAY){p(ar[++i],pf+'delay');continue;}
        if(Math.abs(ar[i])==HAUTO){t(ar[i],pf+'hauto');continue;}
        if(Math.abs(ar[i])==VAUTO){t(ar[i],pf+'vauto');continue;}
        if(Math.abs(ar[i])==NOJUSTX){t(ar[i],pf+'nojustx');continue;}
        if(Math.abs(ar[i])==NOJUSTY){t(ar[i],pf+'nojusty');continue;}
        if(Math.abs(ar[i])==CLOSECLICK){t(ar[i],pf+'closeclick');continue;}
        if(ar[i]==CLOSETITLE){q(ar[++i],pf+'closetitle');continue;}
        if(ar[i]==FGCLASS){q(ar[++i],pf+'fgclass');continue;}
        if(ar[i]==BGCLASS){q(ar[++i],pf+'bgclass');continue;}
        if(ar[i]==CGCLASS){q(ar[++i],pf+'cgclass');continue;}
        if(ar[i]==TEXTPADDING){p(ar[++i],pf+'textpadding');continue;}
        if(ar[i]==TEXTFONTCLASS){q(ar[++i],pf+'textfontclass');continue;}
        if(ar[i]==CAPTIONPADDING){p(ar[++i],pf+'captionpadding');continue;}
        if(ar[i]==CAPTIONFONTCLASS){q(ar[++i],pf+'captionfontclass');continue;}
        if(ar[i]==CLOSEFONTCLASS){q(ar[++i],pf+'closefontclass');continue;}
        if(Math.abs(ar[i])==CAPBELOW){t(ar[i],pf+'capbelow');continue;}
        if(ar[i]==LABEL){q(ar[++i],pf+'label');continue;}
        if(Math.abs(ar[i])==DECODE){t(ar[i],pf+'decode');continue;}
        if(ar[i]==DONOTHING){continue;}
        i=OLparseCmdLine(pf,i,ar);}}
    if((OLfunctionPI)&&OLudf&&o3_function)o3_text=o3_function();
    if(pf=='o3_')OLfontSize();
}
function OLpar(a,v){eval(v+'='+a);}
function OLparQuo(a,v){eval(v+"='"+OLescSglQt(a)+"'");}
function OLescSglQt(s){return s.toString().replace(/'/g,"\\'");}
function OLtoggle(a,v){eval(v+'=('+v+'==0&&'+a+'>=0)?1:0');}
function OLhasDims(s){return /[%\-a-z]+$/.test(s);}
function OLfontSize(){
    var i;if(OLhasDims(o3_textsize)){if(OLns4)o3_textsize="2";}else
    if(!OLns4){i=parseInt(o3_textsize);o3_textsize=(i>0&&i<8)?OLpct[i]:OLpct[0];}
    if(OLhasDims(o3_captionsize)){if(OLns4)o3_captionsize="2";}else
        if(!OLns4){i=parseInt(o3_captionsize);o3_captionsize=(i>0&&i<8)?OLpct[i]:OLpct[0];}
    if(OLhasDims(o3_closesize)){if(OLns4)o3_closesize="2";}else
        if(!OLns4){i=parseInt(o3_closesize);o3_closesize=(i>0&&i<8)?OLpct[i]:OLpct[0];}
    if(OLprintPI)OLprintDims();
}
function OLdecode(){
    var re=/%[0-9A-Fa-f]{2,}/,t=o3_text,c=o3_cap,u=unescape,d=!OLns4&&(!OLgek||OLgek>=20020826)
            &&typeof decodeURIComponent?decodeURIComponent:u;if(typeof(window.TypeError)=='function'){
    if(re.test(t)){eval(new Array('try{','o3_text=d(t);','}catch(e){','o3_text=u(t);',
            '}').join('\n'))};if(c&&re.test(c)){eval(new Array('try{','o3_cap=d(c);','}catch(e){',
        'o3_cap=u(c);','}').join('\n'))}}else{if(re.test(t))o3_text=u(t);if(c&&re.test(c))o3_cap=u(c);}
}

/*
 LAYER FUNCTIONS
 */
// Writes to layer
function OLlayerWrite(t){
    t+="\n";
    if(OLns4){over.document.write(t);over.document.close();
    }else if(typeof over.innerHTML!='undefined'){if(OLieM)over.innerHTML='';over.innerHTML=t;
    }else{range=o3_frame.document.createRange();range.setStartAfter(over);
        domfrag=range.createContextualFragment(t);
        while(over.hasChildNodes()){over.removeChild(over.lastChild);}
        over.appendChild(domfrag);}
    if(OLprintPI)over.print=o3_print?t:null;
}

// Makes object visible
function OLshowObject(o){
    OLshowid=0;o=(OLns4)?o:o.style;
    if(((OLfilterPI)&&!OLchkFilter(o))||!OLfilterPI)o.visibility="visible";
    if(OLshadowPI)OLshowShadow();if(OLiframePI)OLshowIfs();if(OLhidePI)OLhideUtil(1,1,0);
}

// Hides object
function OLhideObject(o){
    if(OLshowid>0){clearTimeout(OLshowid);OLshowid=0;}
    if(OLtimerid>0)clearTimeout(OLtimerid);if(OLdelayid>0)clearTimeout(OLdelayid);
    OLtimerid=0;OLdelayid=0;self.status="";o3_label=ol_label;
    if(o3_frame!=self)o=OLgetRefById();
    if(o){if(o.onmouseover)o.onmouseover=null;
        if(OLscrollPI&&o==over)OLclearScroll();
        if(OLdraggablePI)OLclearDrag();
        if(OLfilterPI)OLcleanupFilter(o);if(OLshadowPI)OLhideShadow();
        var os=(OLns4)?o:o.style;os.visibility="hidden";
        if(OLhidePI&&o==over)OLhideUtil(0,0,1);if(OLiframePI)OLhideIfs(o);}
}

// Moves layer
function OLrepositionTo(o,xL,yL){
    o=(OLns4)?o:o.style;
    o.left=(OLns4?xL:xL+'px');
    o.top=(OLns4?yL:yL+'px');
}

// Handle NOCLOSE-MOUSEOFF
function OLoptMOUSEOFF(c){
    if(!c)o3_close="";
    over.onmouseover=function(){OLhover=1;if(OLtimerid>0){clearTimeout(OLtimerid);OLtimerid=0;}}
}
function OLcursorOff(){
    var o=(OLns4?over:over.style),pHt=OLns4?over.clip.height:over.offsetHeight,
            left=parseInt(o.left),top=parseInt(o.top),
            right=left+o3_width,bottom=top+((OLbubblePI&&o3_bubble)?OLbubbleHt:pHt);
    if(OLx<left||OLx>right||OLy<top||OLy>bottom)return true;
    return false;
}

/*
 REGISTRATION
 */
function OLsetRunTimeVar(){
    if(OLrunTime.length)for(var k=0;k<OLrunTime.length;k++)OLrunTime[k]();
}
function OLparseCmdLine(pf,i,ar){
    if(OLcmdLine.length){for(var k=0;k<OLcmdLine.length;k++){
        var j=OLcmdLine[k](pf,i,ar);if(j>-1){i=j;break;}}}
    return i;
}
function OLregCmds(c){
    if(typeof c!='string')return;
    var pM=c.split(',');pMtr=pMtr.concat(pM);
    for(var i=0;i<pM.length;i++)eval(pM[i].toUpperCase()+'='+pmCnt++);
}
function OLregRunTimeFunc(f){
    if(typeof f=='object')OLrunTime=OLrunTime.concat(f);
    else OLrunTime[OLrunTime.length++]=f;
}
function OLregCmdLineFunc(f){
    if(typeof f=='object')OLcmdLine=OLcmdLine.concat(f);
    else OLcmdLine[OLcmdLine.length++]=f;
}

OLloaded=1;
/*
 overlibmws_shadow.js plug-in module - Copyright Foteos Macrides 2003-2005
 For support of the SHADOW feature.
 Initial: July 14, 2003 - Last Revised: June 8, 2005
 See the Change History and Command Reference for overlibmws via:

 http://www.macridesweb.com/oltest/

 Published under an open source license: http://www.macridesweb.com/oltest/license.html
 */

OLloaded=0;
var OLshadowCmds='shadow,shadowx,shadowy,shadowcolor,shadowimage,shadowopacity';
OLregCmds(OLshadowCmds);

// DEFAULT CONFIGURATION
if(OLud('shadow'))var ol_shadow=0;
if(OLud('shadowx'))var ol_shadowx=5;
if(OLud('shadowy'))var ol_shadowy=5;
if(OLud('shadowcolor'))var ol_shadowcolor="#666666";
if(OLud('shadowimage'))var ol_shadowimage="";
if(OLud('shadowopacity'))var ol_shadowopacity=60;
// END CONFIGURATION

var o3_shadow=0,o3_shadowx=5,o3_shadowy=5,o3_shadowcolor="#666666",o3_shadowimage="";
var o3_shadowopacity=60,bkdrop=null;

function OLloadShadow(){
    OLload(OLshadowCmds);
}

function OLparseShadow(pf,i,ar){
    var k=i,p=OLpar,q=OLparQuo;
    if(k<ar.length){
        if(Math.abs(ar[k])==SHADOW){OLtoggle(ar[k],pf+'shadow');return k;}
        if(ar[k]==SHADOWX){p(ar[++k],pf+'shadowx');return k;}
        if(ar[k]==SHADOWY){p(ar[++k],pf+'shadowy');return k;}
        if(ar[k]==SHADOWCOLOR){q(ar[++k],pf+'shadowcolor');return k;}
        if(ar[k]==SHADOWIMAGE){q(ar[++k],pf+'shadowimage');return k;}
        if(ar[k]==SHADOWOPACITY){p(ar[++k],pf+'shadowopacity');return k;}}
    return -1;
}

function OLdispShadow(){
    if(o3_shadow){OLgetShadowLyrRef();if(bkdrop)OLgenerateShadowLyr();}
}

function OLinitShadow(){
    if(OLie55&&OLfilterPI&&o3_filter&&o3_filtershadow){o3_shadow=0;return}
    var o;if(!(o=OLmkLyr((OLovertwoPI&&over2&&over==over2?'backdrop2':'backdrop'),
        o3_frame,999))||bkdrop!=o){bkdrop=null;OLgetShadowLyrRef();}
}

function OLgetShadowLyrRef(){
    if(bkdrop||!o3_shadow)return;
    bkdrop=OLgetRefById((OLovertwoPI&&over2&&over==over2?'backdrop2':'backdrop'));
    if(!bkdrop){o3_shadow=0;bkdrop=null;}
}

function OLgenerateShadowLyr(){
    var wd=(OLns4?over.clip.width:over.offsetWidth),hgt=(OLns4?over.clip.height:over.offsetHeight);
    if(OLns4){bkdrop.clip.width=wd;bkdrop.clip.height=hgt;
        if(o3_shadowimage)bkdrop.background.src=o3_shadowimage;
        else{bkdrop.bgColor=o3_shadowcolor;bkdrop.zIndex=over.zIndex -1;}
    }else{var o=bkdrop.style;o.width=wd+'px';o.height=hgt+'px';
        if(o3_shadowimage)o.backgroundImage="url("+o3_shadowimage+")";
        else o.backgroundColor=o3_shadowcolor;
        o.clip='rect(0px '+wd+'px '+hgt+'px 0px)';o.zIndex=over.style.zIndex -1;
        if(o3_shadowopacity){var op=o3_shadowopacity;op=(op<=100&&op>0?op:100);
            if(OLie4&&!OLieM&&typeof o.filter=='string'){
                o.filter='Alpha(opacity='+op+')';if(OLie55)bkdrop.filters.alpha.enabled=1;}
            else{op=op/100;OLopBk(op);}}}
}

function OLopBk(op){
    var o=bkdrop.style;
    if(typeof o.opacity!='undefined')o.opacity=op;
    else if(typeof o.MozOpacity!='undefined')o.MozOpacity=op;
    else if(typeof o.KhtmlOpacity!='undefined')o.KhtmlOpacity=op;
}

function OLcleanUpShadow(){
    if(!bkdrop)return;
    if(OLns4){bkdrop.bgColor=null;bkdrop.background.src=null;}else{
        var o=bkdrop.style;o.backgroundColor='transparent';o.backgroundImage='none';
        if(OLie4&&!OLieM&&typeof o.filter=='string'){
            o.filter='Alpha(opacity=100)';if(OLie55&&typeof bkdrop.filters=='object')
            bkdrop.filters.alpha.enabled=0;}else OLopBk(1.0);
        if(OLns6){o.width=1+'px';o.height=1+'px';
            OLrepositionTo(bkdrop,o3_frame.pageXOffset,o3_frame.pageYOffset);}}
}

function OLshowShadow(){
    if(bkdrop&&o3_shadow){var o=(OLns4?bkdrop:bkdrop.style);o.visibility="visible";}
}

function OLhideShadow(){
    if(bkdrop&&o3_shadow){
        var o=OLgetRefById((OLovertwoPI&&over2&&over==over2?'backdrop2':'backdrop'));
        if(o&&o==bkdrop){var bks=(OLns4?bkdrop:bkdrop.style);
            if(typeof bks.visibility=='string')bks.visibility="hidden";OLcleanUpShadow();}}
}

function OLrepositionShadow(X,Y){
    if(bkdrop&&o3_shadow)OLrepositionTo(bkdrop,X+o3_shadowx,Y+o3_shadowy);
}

OLregRunTimeFunc(OLloadShadow);
OLregCmdLineFunc(OLparseShadow);

OLshadowPI=1;
OLloaded=1;
/*
 overlibmws_iframe.js plug-in module - Copyright Foteos Macrides 2003-2005
 Masks system controls to prevent obscuring of popops for IE v5.5 or higher.
 Initial: October 19, 2003 - Last Revised: May 15, 2005
 See the Change History and Command Reference for overlibmws via:

 http://www.macridesweb.com/oltest/

 Published under an open source license: http://www.macridesweb.com/oltest/license.html
 */

OLloaded=0;

var OLifsP1=null,OLifsSh=null,OLifsP2=null;

// IFRAME SHIM SUPPORT FUNCTIONS
function OLinitIfs(){
    if(!OLie55)return;
    if((OLovertwoPI)&&over2&&over==over2){
        var o=o3_frame.document.all['overIframeOvertwo'];
        if(!o||OLifsP2!=o){OLifsP2=null;OLgetIfsP2Ref();}return;}
    o=o3_frame.document.all['overIframe'];
    if(!o||OLifsP1!=o){OLifsP1=null;OLgetIfsRef();}
    if((OLshadowPI)&&o3_shadow){o=o3_frame.document.all['overIframeShadow'];
        if(!o||OLifsSh!=o){OLifsSh=null;OLgetIfsShRef();}}
}

function OLsetIfsRef(o,i,z){
    o.id=i;o.src='javascript:false;';o.scrolling='no';var os=o.style;
    os.position='absolute';os.top=0;os.left=0;os.width=1;os.height=1;os.visibility='hidden';
    os.zIndex=over.style.zIndex-z;os.filter='Alpha(style=0,opacity=0)';
}

function OLgetIfsRef(){
    if(OLifsP1||!OLie55)return;
    OLifsP1=o3_frame.document.createElement('iframe');
    OLsetIfsRef(OLifsP1,'overIframe',2);
    o3_frame.document.body.appendChild(OLifsP1);
}

function OLgetIfsShRef(){
    if(OLifsSh||!OLie55)return;
    OLifsSh=o3_frame.document.createElement('iframe');
    OLsetIfsRef(OLifsSh,'overIframeShadow',3);
    o3_frame.document.body.appendChild(OLifsSh);
}

function OLgetIfsP2Ref(){
    if(OLifsP2||!OLie55)return;
    OLifsP2=o3_frame.document.createElement('iframe');
    OLsetIfsRef(OLifsP2,'overIframeOvertwo',1);
    o3_frame.document.body.appendChild(OLifsP2);
}

function OLsetDispIfs(o,w,h){
    var os=o.style;
    os.width=w+'px';os.height=h+'px';os.clip='rect(0px '+w+'px '+h+'px 0px)';
    o.filters.alpha.enabled=true;
}

function OLdispIfs(){
    if(!OLie55)return;
    var wd=over.offsetWidth,ht=over.offsetHeight;
    if(OLfilterPI&&o3_filter&&o3_filtershadow){wd+=5;ht+=5;}
    if((OLovertwoPI)&&over2&&over==over2){
        if(!OLifsP2)return;
        OLsetDispIfs(OLifsP2,wd,ht);return;}
    if(!OLifsP1)return;
    OLsetDispIfs(OLifsP1,wd,ht);
    if((!OLshadowPI)||!o3_shadow||!OLifsSh)return;
    OLsetDispIfs(OLifsSh,wd,ht);
}

function OLshowIfs(){
    if(OLifsP1){OLifsP1.style.visibility="visible";
        if((OLshadowPI)&&o3_shadow&&OLifsSh)OLifsSh.style.visibility="visible";}
}

function OLhideIfs(o){
    if(!OLie55||o!=over)return;
    if(OLifsP1)OLifsP1.style.visibility="hidden";
    if((OLshadowPI)&&o3_shadow&&OLifsSh)OLifsSh.style.visibility="hidden";
}

function OLrepositionIfs(X,Y){
    if(OLie55){if((OLovertwoPI)&&over2&&over==over2){
        if(OLifsP2)OLrepositionTo(OLifsP2,X,Y);}
    else{if(OLifsP1){OLrepositionTo(OLifsP1,X,Y);if((OLshadowPI)&&o3_shadow&&OLifsSh)
        OLrepositionTo(OLifsSh,X+o3_shadowx,Y+o3_shadowy);}}}
}

OLiframePI=1;
OLloaded=1;
/*
 overlibmws_exclusive.js plug-in module - Copyright Foteos Macrides 2003-2005
 For support of the EXCLUSIVE feature.
 Initial: November 7, 2003 - Last Revised: June 8, 2005
 See the Change History and Command Reference for overlibmws via:

 http://www.macridesweb.com/oltest/

 Published under an open source license: http://www.macridesweb.com/oltest/license.html
 */

OLloaded=0;
var OLexclusiveCmds='exclusive,exclusivestatus,exclusiveoverride';
OLregCmds(OLexclusiveCmds);

// DEFAULT CONFIGURATION
if(OLud('exclusive'))var ol_exclusive=0;
if(OLud('exclusivestatus'))var ol_exclusivestatus='Please act on or close the open popup.';
if(OLud('exclusiveoverride'))var ol_exclusiveoverride=0;
// END CONFIGURATION

var o3_exclusive=0,o3_exclusivestatus='',o3_exclusiveoverride=0;

function OLloadExclusive(){
    OLload(OLexclusiveCmds);
}

function OLparseExclusive(pf,i,ar){
    var k=i,t=OLtoggle;
    if(k<ar.length){
        if(Math.abs(ar[k])==EXCLUSIVE){t(ar[k],pf+'exclusive');return k;}
        if(ar[k]==EXCLUSIVESTATUS){OLparQuo(ar[++k],pf+'exclusivestatus');return k;}
        if(Math.abs(ar[k])==EXCLUSIVEOVERRIDE){t(ar[k],pf+'exclusiveoverride');return k;}}
    return -1;
}

function OLisExclusive(args){
    if((args!=null)&&OLhasOverRide(args))o3_exclusiveoverride=(ol_exclusiveoverride==0)?1:0;
    else o3_exclusiveoverride=ol_exclusiveoverride;
    var rtnVal=(o3_exclusive&&!o3_exclusiveoverride&&OLshowingsticky&&
                over==OLgetRefById('overDiv'));
    if(rtnVal)self.status=o3_exclusivestatus;
    return rtnVal;
}

function OLhasOverRide(args){
    var rtnFlag=0;
    for(var i=0;i<args.length;i++){
        if(typeof args[i]=='number'&&args[i]==EXCLUSIVEOVERRIDE){
            rtnFlag=1;break;}}
    return rtnFlag;
}

OLregRunTimeFunc(OLloadExclusive);
OLregCmdLineFunc(OLparseExclusive);

OLexclusivePI=1;
OLloaded=1;


/*
 These cookie functions are downloaded from
 http://www.mach5.com/support/analyzer/manual/html/General/CookiesJavaScript.htm
 */
function Get_Cookie(name) {
    var start = document.cookie.indexOf(name+"=");
    var len = start+name.length+1;
    if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
    if (start == -1) return null;
    var end = document.cookie.indexOf(";",len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len,end));
}
// This function has been slightly modified
function Set_Cookie(name,value,expires,path,domain,secure) {
    expires = expires * 60*60*24*1000;
    var today = new Date();
    var expires_date = new Date( today.getTime() + (expires) );
    var cookieString = name + "=" +escape(value) +
                       ( (expires) ? ";expires=" + expires_date.toGMTString() : "") +
                       ( (path) ? ";path=" + path : "") +
                       ( (domain) ? ";domain=" + domain : "") +
                       ( (secure) ? ";secure" : "");
    document.cookie = cookieString;
}

/*
 iframecontentmws.js - Foteos Macrides
 Initial: October 10, 2004 - Last Revised: May 9, 2005
 Simple script for using an HTML file as iframe content in overlibmws popups.
 Include WRAP and TEXTPADDING,0 in the overlib call to ensure that the width
 arg is respected (unless the CAPTION plus CLOSETEXT widths add up to more than
 the width arg, in which case you should increase the width arg).  The name arg
 should be a unique string for each popup with iframe content in the document.
 The frameborder arg should be 1 (browser default if omitted) or 0.

 See http://www.macridesweb.com/oltest/IFRAME.html for demonstration.
 */

function OLiframeContent(src, width, height, name, frameborder) {
    return ('<iframe src="'+src+'" width="'+width+'" height="'+height+'"'
            +(name!=null?' name="'+name+'" id="'+name+'"':'')
            +(frameborder!=null?' frameborder="'+frameborder+'"':'')
            +' scrolling="auto">'
            +'<div>[iframe not supported]</div></iframe>');
}
/*
 overlibmws_scroll.js plug-in module - Copyright Foteos Macrides 2002-2005.
 For support of the SCROLL feature.
 Initial: October 20, 2002 - Last Revised: May 18, 2004
 See the Change History and Command Reference for overlibmws via:

 http://www.macridesweb.com/oltest/

 Published under an open source license: http://www.macridesweb.com/oltest/license.html
 */

OLloaded=0;
OLregCmds('scroll');

// DEFAULT CONFIGURATION
if(OLud('scroll'))var ol_scroll=0;
// END CONFIGURATION

var o3_scroll=0,OLscrollRefresh=100;

function OLloadScroll(){
    OLload('scroll');
}

function OLparseScroll(pf,i,ar){
    var k=i;
    if(k<ar.length){if(Math.abs(ar[k])==SCROLL){OLtoggle(ar[k],pf+'scroll');return k;}}
    return -1;
}

function OLchkScroll(X,Y){
    if(o3_scroll){if(!OLshowingsticky||
                     (OLovertwoPI&&over==over2&&!OLshowingsticky2)||
                     (OLdraggablePI&&o3_draggable&&o3_frame==self)||
                     (o3_relx==null&&o3_midx==null)||(o3_rely==null&&o3_midy==null))o3_scroll=0;
    else if(typeof over.scroll=='undefined'||over.scroll.canScroll)
        over.scroll=new OLsetScroll(X,Y,OLscrollRefresh);}
}

function OLsetScroll(X,Y,refresh){
    if(o3_scroll){this.canScroll=0;this.refresh=refresh;this.x=X;this.y=Y;
        this.timer=setTimeout("OLscrollReposition()",this.refresh);}
}

function OLclearScroll(){
    if(o3_scroll){if(typeof over.scroll=='undefined'){o3_scroll=0;return;}
        over.scroll.canScroll=1;if(over.scroll.timer){
        clearTimeout(over.scroll.timer);over.scroll.timer=null;}}
}

function OLscrollReposition(){
    var o=over,oD=(OLovertwoPI&&over==over2?'overDiv2':'overDiv');
    if(o3_scroll&&o&&o==OLgetRefById(oD)){var X,Y,pgLeft,pgTop;
        pgLeft=(OLie4)?OLfd().scrollLeft:o3_frame.pageXOffset;
        pgTop=(OLie4)?OLfd().scrollTop:o3_frame.pageYOffset;
        X=(o.pageX?o.pageX:o.style.left?o.style.left:0)-pgLeft;
        Y=(o.pageY?o.pageY:o.style.top?o.style.top:0)-pgTop;
        if(X!=o.scroll.x||Y!=o.scroll.y){
            OLrepositionTo(o,pgLeft+o.scroll.x,pgTop+o.scroll.y);
            if(OLshadowPI)OLrepositionShadow(pgLeft+o.scroll.x,pgTop+o.scroll.y);
            if(OLiframePI)OLrepositionIfs(pgLeft+o.scroll.x,pgTop+o.scroll.y);
            if(OLhidePI)OLhideUtil(0,1,1,0,0,0);}
        o.scroll.timer=setTimeout("OLscrollReposition()",o.scroll.refresh);}
}

OLregRunTimeFunc(OLloadScroll);
OLregCmdLineFunc(OLparseScroll);

OLscrollPI=1;
OLloaded=1;
var win=null;

function ShowHelp(mypage,myname,w,h,scroll,pos){
    if(pos=="random"){LeftPosition=(screen.width)?Math.floor(Math.random()*(screen.width-w)):100;TopPosition=(screen.height)?Math.floor(Math.random()*((screen.height-h)-75)):100;}
    if(pos=="center"){LeftPosition=(screen.width)?(screen.width-w)/2:100;TopPosition=(screen.height)?(screen.height-h)/2:100;}
    else if((pos!="center" && pos!="random") || pos==null){LeftPosition=0;TopPosition=20}
    settings='width='+w+',height='+h+',top='+TopPosition+',left='+LeftPosition+',scrollbars='+scroll+',location=no,directories=no,status=no,menubar=no,toolbar=no,resizable=yes';
    win=window.open(mypage,myname,settings);
}


function openNewmail(systemUserId)
{
    var action = "NewMail.do?mailRecipient=" + systemUserId;
    var mailWin = window.open(action, '','toolbar=no,location=no,directories=no,menubar=no,status=no,scrollbars=no,width=400,height=590');
    mailWin.moveTo(self.screen.width/2-200,self.screen.height/2-275);
}

function Get_Cookie(name) {
    var start = document.cookie.indexOf(name+"=");
    var len = start+name.length+1;
    if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
    if (start == -1) return null;
    var end = document.cookie.indexOf(";",len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len,end));
}

function Set_Cookie(name,value,expires,path,domain,secure) {
    expires = expires * 60*60*24*1000;
    var today = new Date();
    var expires_date = new Date( today.getTime() + (expires) );
    var cookieString = name + "=" +escape(value) +
                       ( (expires) ? ";expires=" + expires_date.toGMTString() : "") +
                       ( (path) ? ";path=" + path : "") +
                       ( (domain) ? ";domain=" + domain : "") +
                       ( (secure) ? ";secure" : "");
    document.cookie = cookieString;
}

/* Sub cookie format is "name1:value1/name2:value2" */

function setSubCookie( uName, name, value, expires )
{
    var uValue = Get_Cookie( uName );
    if( uValue ) {
        uValue = cleanUpCookieValue(uValue);
        // '/' is breaker for sub cookie each
        var uCookies = uValue.split( '/' );
        var found = -1; // whether sub-cookie for the name is present
        for( var c = 0; c < uCookies.length; c++ )
        {
            // ':' is identifier between name and value for sub cookie.
            var t = uCookies[c].split( ':' );
            var tName = t[0];
            var tValue = t[1];
            if( tName == name ) {
                found = 1;
                tValue = value;
                t[1] = tValue;
                uCookies[c] = t.join( ':' );
            }
        }
        if( found == -1 ) {
            uCookies[uCookies.length] = name + ':' + value;
        }
        uValue = uCookies.join( '/' );
    } else {
        uValue = name + ':' + value;
    }
    // update real cookie
    Set_Cookie( uName, uValue, expires );
}

// For some reason we get extra " in the start and at the end so we have to remove them...
function cleanUpCookieValue(cookieAttribute) {
    if (cookieAttribute && cookieAttribute.length > 0) {
        if (cookieAttribute[0] == '"') {
            cookieAttribute = cookieAttribute.substring(1);
        }
        if (cookieAttribute[cookieAttribute.length-1] == '"') {
            cookieAttribute = cookieAttribute.substring(0, cookieAttribute.length-2);
        }
    }
    return cookieAttribute;
}

function getSubCookie( uName, name )
{
    var uValue = Get_Cookie( uName );

    if (uValue) {
        var flag = uValue.indexOf( name + ':' )
        if( flag != -1 ) {
            flag += name.length + 1;
            var end = uValue.indexOf( '/', flag );
            if( end == -1 ) {
                end = uValue.length;
            }
            return uValue.substring( flag, end );
        }
    }
    return "";
}

function hideShowElement(elementId)
{
    var count = elementId.substring(elementId.indexOf("_")+1,elementId.length);
    var div = document.getElementById(elementId);
    if (div) {
        if (div.style.display=='block' || div.style.display=='') {
            div.style.display='none';
            theIcon=document.getElementById(elementId + "_imageDiv");
            if(theIcon!=null){
                theIcon.innerHTML='<img src="images/icons/16x16/blue_show.gif" alt="" border=0 onclick="hideShowElement(\'' + elementId + '\'); hideShowElement(\'paddingDiv_' + count +'\')">';
            }
            Set_Cookie("collapse" + elementId, "true", 365);
        } else {
            div.style.display='';
            theIcon=document.getElementById(elementId + "_imageDiv");
            if(theIcon!=null){
                theIcon.innerHTML='<img src="images/icons/16x16/blue_hide.gif" alt="" border=0 onclick="hideShowElement(\'' + elementId + '\'); hideShowElement(\'paddingDiv_' + count +'\')">';
            }
            Set_Cookie("collapse" + elementId, "false", 365);
        }
    }
}
//Hide or show div depending on if it i is visible or hidden
function hideShowDiv(divName) {
        var div = document.getElementById(divName);
    if (div.style.display=='block') {
        //Set hide
        div.style.display='none';
    } else {
        //Set visible
        div.style.display = 'block';
    }
}

function hideDiv(divName){
    var div = document.getElementById(divName);
    if(div != null && div != "undefined") {
        div.style.display='none';
    }
}

function showDiv(divName){
    var div = document.getElementById(divName);
    if(div != null && div != "undefined") {
            div.style.display = 'block';
    }
}


/*
 function showUserInformation(systemUserId)
 {
 if (systemUserId != "0") {
 jsrsExecute('RemoteUtilServlet', displayUserInformation, 'getUserInformation', systemUserId, false);
 }
 }
 */

function showUserInformation(systemUserId)
{
    if (systemUserId != "0") {
        jsrsExecute('RemoteUtilServlet', loadUserDialogContentCallback, 'getUserInformation', systemUserId, false);
    }
}

function displayUserInformation(htmlToShow)
{
    var myText3='<div class="xxfl">' + htmlToShow + '</div>';
    var title='User information';

    return overlib(myText3, BGCLASS,'xxbg', CGCLASS,'xxcg', FGCLASS,'xxfg',
            CAPTIONFONTCLASS,'xxcap', CLOSEFONTCLASS,'xxclo',
            TEXTFONTCLASS,'xxtxt', WRAP, TEXTPADDING,0, BORDER,2, STICKY, CLOSECLICK, CAPTIONPADDING,4, CAPTION, title,
            BELOW, OFFSETX, 10 , OFFSETY,20, LEFT, STATUS,'', SHADOW,SHADOWX,5,
            SHADOWY,5,SHADOWIMAGE,'js/semitrans.gif',SHADOWOPACITY,0);
}



/************************************************************************************************************
 (C) www.dhtmlgoodies.com, October 2005

 This is a script from www.dhtmlgoodies.com. You will find this and a lot of other scripts at our website.

 Terms of use:
 You are free to use this script as long as the copyright message is kept intact. However, you may not
 redistribute, sell or repost it without our permission.

 Thank you!

 www.dhtmlgoodies.com
 Alf Magne Kalleland

 ************************************************************************************************************/


var fromBoxArray = new Array();
var toBoxArray = new Array();
var selectBoxIndex = 0;
var arrayOfItemsToSelect = new Array();


function moveSingleElement()
{
    var selectBoxIndex = this.parentNode.parentNode.id.replace(/[^\d]/g,'');
    var tmpFromBox;
    var tmpToBox;
    if(this.tagName.toLowerCase()=='select'){
        tmpFromBox = this;
        if(tmpFromBox==fromBoxArray[selectBoxIndex])tmpToBox = toBoxArray[selectBoxIndex]; else tmpToBox = fromBoxArray[selectBoxIndex];
    }else{

        if(this.value.indexOf('>')>=0){
            tmpFromBox = fromBoxArray[selectBoxIndex];
            tmpToBox = toBoxArray[selectBoxIndex];
        }else{
            tmpFromBox = toBoxArray[selectBoxIndex];
            tmpToBox = fromBoxArray[selectBoxIndex];
        }
    }

    for(var no=0;no<tmpFromBox.options.length;no++){
        if(tmpFromBox.options[no].selected){
            tmpFromBox.options[no].selected = false;
            tmpToBox.options[tmpToBox.options.length] = new Option(tmpFromBox.options[no].text,tmpFromBox.options[no].value);

            for(var no2=no;no2<(tmpFromBox.options.length-1);no2++){
                tmpFromBox.options[no2].value = tmpFromBox.options[no2+1].value;
                tmpFromBox.options[no2].text = tmpFromBox.options[no2+1].text;
                tmpFromBox.options[no2].selected = tmpFromBox.options[no2+1].selected;
            }
            no = no -1;
            tmpFromBox.options.length = tmpFromBox.options.length-1;

        }
    }


    var tmpTextArray = new Array();
    for(var no=0;no<tmpFromBox.options.length;no++){
        tmpTextArray.push(tmpFromBox.options[no].text + '___' + tmpFromBox.options[no].value);
    }
    tmpTextArray.sort();
    var tmpTextArray2 = new Array();
    for(var no=0;no<tmpToBox.options.length;no++){
        tmpTextArray2.push(tmpToBox.options[no].text + '___' + tmpToBox.options[no].value);
    }
    tmpTextArray2.sort();

    for(var no=0;no<tmpTextArray.length;no++){
        var items = tmpTextArray[no].split('___');
        tmpFromBox.options[no] = new Option(items[0],items[1]);

    }

    for(var no=0;no<tmpTextArray2.length;no++){
        var items = tmpTextArray2[no].split('___');
        tmpToBox.options[no] = new Option(items[0],items[1]);
    }
}

function sortAllElement(boxRef)
{
    var tmpTextArray2 = new Array();
    for(var no=0;no<boxRef.options.length;no++){
        tmpTextArray2.push(boxRef.options[no].text + '___' + boxRef.options[no].value);
    }
    tmpTextArray2.sort();
    for(var no=0;no<tmpTextArray2.length;no++){
        var items = tmpTextArray2[no].split('___');
        boxRef.options[no] = new Option(items[0],items[1]);
    }

}
function moveAllElements()
{
    var selectBoxIndex = this.parentNode.parentNode.id.replace(/[^\d]/g,'');
    var tmpFromBox;
    var tmpToBox;
    if(this.value.indexOf('>')>=0){
        tmpFromBox = fromBoxArray[selectBoxIndex];
        tmpToBox = toBoxArray[selectBoxIndex];
    }else{
        tmpFromBox = toBoxArray[selectBoxIndex];
        tmpToBox = fromBoxArray[selectBoxIndex];
    }

    for(var no=0;no<tmpFromBox.options.length;no++){
        tmpToBox.options[tmpToBox.options.length] = new Option(tmpFromBox.options[no].text,tmpFromBox.options[no].value);
    }

    tmpFromBox.options.length=0;
    sortAllElement(tmpToBox);

}


/* This function highlights options in the "to-boxes". It is needed if the values should be remembered after submit. Call this function onsubmit for your form */
function multipleSelectOnSubmit()
{
    for(var no=0;no<arrayOfItemsToSelect.length;no++){
        var obj = arrayOfItemsToSelect[no];
        for(var no2=0;no2<obj.options.length;no2++){
            obj.options[no2].selected = true;
        }
    }

}

function createMovableOptions(fromBox,toBox,totalWidth,totalHeight,labelLeft,labelRight)
{
    fromObj = document.getElementById(fromBox);
    toObj = document.getElementById(toBox);

    arrayOfItemsToSelect[arrayOfItemsToSelect.length] = toObj;


    fromObj.ondblclick = moveSingleElement;
    toObj.ondblclick = moveSingleElement;


    fromBoxArray.push(fromObj);
    toBoxArray.push(toObj);

    var parentEl = fromObj.parentNode;

    var parentDiv = document.createElement('DIV');
    parentDiv.className='multipleSelectBoxControl';
    parentDiv.id = 'selectBoxGroup' + selectBoxIndex;
    parentDiv.style.width = totalWidth + 'px';
    parentDiv.style.height = totalHeight + 'px';
    parentEl.insertBefore(parentDiv,fromObj);


    var subDiv = document.createElement('DIV');
    subDiv.style.width = (Math.floor(totalWidth/2) - 15) + 'px';
    fromObj.style.width = (Math.floor(totalWidth/2) - 15) + 'px';

    var label = document.createElement('SPAN');
    label.innerHTML = labelLeft;
    subDiv.appendChild(label);

    subDiv.appendChild(fromObj);
    subDiv.className = 'multipleSelectBoxDiv';
    parentDiv.appendChild(subDiv);


    var buttonDiv = document.createElement('DIV');
    buttonDiv.style.verticalAlign = 'middle';
    buttonDiv.style.paddingTop = (totalHeight/2) - 50 + 'px';
    buttonDiv.style.width = '30px';
    buttonDiv.style.textAlign = 'center';
    parentDiv.appendChild(buttonDiv);

    var buttonRight = document.createElement('INPUT');
    buttonRight.type='button';
    buttonRight.value = '>';
    buttonDiv.appendChild(buttonRight);
    buttonRight.onclick = moveSingleElement;

    var buttonAllRight = document.createElement('INPUT');
    buttonAllRight.type='button';
    buttonAllRight.value = '>>';
    buttonAllRight.onclick = moveAllElements;
    buttonDiv.appendChild(buttonAllRight);

    var buttonLeft = document.createElement('INPUT');
    buttonLeft.style.marginTop='10px';
    buttonLeft.type='button';
    buttonLeft.value = '<';
    buttonLeft.onclick = moveSingleElement;
    buttonDiv.appendChild(buttonLeft);

    var buttonAllLeft = document.createElement('INPUT');
    buttonAllLeft.type='button';
    buttonAllLeft.value = '<<';
    buttonAllLeft.onclick = moveAllElements;
    buttonDiv.appendChild(buttonAllLeft);

    var subDiv = document.createElement('DIV');
    subDiv.style.width = (Math.floor(totalWidth/2) - 15) + 'px';
    toObj.style.width = (Math.floor(totalWidth/2) - 15) + 'px';

    var label = document.createElement('SPAN');
    label.innerHTML = labelRight;
    subDiv.appendChild(label);

    subDiv.appendChild(toObj);
    parentDiv.appendChild(subDiv);

    toObj.style.height = (totalHeight - label.offsetHeight) + 'px';
    fromObj.style.height = (totalHeight - label.offsetHeight) + 'px';


    selectBoxIndex++;

}



function validateRequired(form) {
    var isValid = true;
    var focusField = null;
    var i = 0;
    var fields = new Array();
    oRequired = new required();
    for (x in oRequired) {
        var field = form[oRequired[x][0]];

        if (field.type == 'text' ||
            field.type == 'textarea' ||
            field.type == 'file' ||
            field.type == 'select-one' ||
            field.type == 'radio' ||
            field.type == 'password' ||
            field.type == 'hidden') {

            //alert(oRequired[x][1] + ": '" + field.value + "'");

            var value = '';
            // get field's value
            if (field.type == "select-one") {
                var si = field.selectedIndex;
                if (si >= 0) {
                    value = field.options[si].value;
                    // 0 is not a valid option!
                    if (value == "0") {
                        value = "";
                    }
                }
            } else {
                value = field.value;
            }

            if (trim(value).length == 0) {

                if (i == 0) {
                    focusField = field;
                }
                fields[i++] = oRequired[x][1];
                isValid = false;
                if (field.type != 'hidden') {
                    field.style.background="lightyellow";
                }
            } else {
                if (field.type != 'hidden') {
                    field.style.background="white";
                }
            }
        }
    }
    if (fields.length > 0) {
        try {
            focusField.focus();
        } catch (e) {
            
        }
        Ext.Msg.alert('', fields.join('\n'), validateRequiredInternalCallback());
    }
    function validateRequiredInternalCallback(){};
    return isValid;
}

// Trim whitespace from left and right sides of s.
function trim(s) {
    return s.replace( /^\s*/, "" ).replace( /\s*$/, "" );
}

//Quicker than above on large strings
function trim2 (str) {
	var	str = str.replace(/^\s\s*/, ''),
		ws = /\s/,
		i = str.length;
	while (ws.test(str.charAt(--i)));
	return str.slice(0, i + 1);
}


function validateInteger(form) {
    var bValid = true;
    var focusField = null;
    var i = 0;
    var fields = new Array();
    oInteger = new IntegerValidations();
    for (x in oInteger) {
        var field = form[oInteger[x][0]];

        if (field.type == 'text' ||
            field.type == 'textarea' ||
            field.type == 'select-one' ||
            field.type == 'radio') {

            var value = '';
            // get field's value
            if (field.type == "select-one") {
                var si = field.selectedIndex;
                if (si >= 0) {
                    value = field.options[si].value;
                }
            } else {
                value = field.value;
            }

            if (value.length > 0) {

                if (!isAllDigits(value)) {
                    bValid = false;
                    if (i == 0) {
                        focusField = field;
                    }
                    fields[i++] = oInteger[x][1];

                } else {
                    var iValue = parseInt(value);
                    if (isNaN(iValue) || !(iValue >= -2147483648 && iValue <= 2147483647)) {
                        if (i == 0) {
                            focusField = field;
                        }
                        fields[i++] = oInteger[x][1];
                        bValid = false;
                    }
                }
            }
        }
    }
    if (fields.length > 0) {
        focusField.focus();
        Ext.Msg.alert('', fields.join('\n'), validateIntegerInternalCallback());
    }
    function validateIntegerInternalCallback(){};
    return bValid;
}

function isAllDigits(argvalue) {
    argvalue = argvalue.toString();
    var validChars = "0123456789";
    var startFrom = 0;
    if (argvalue.substring(0, 2) == "0x") {
        validChars = "0123456789abcdefABCDEF";
        startFrom = 2;
    } else if (argvalue.charAt(0) == "0") {
        startFrom = 1;
    } else if (argvalue.charAt(0) == "-") {
        startFrom = 1;
    }

    for (var n = startFrom; n < argvalue.length; n++) {
        if (validChars.indexOf(argvalue.substring(n, n+1)) == -1) return false;
    }
    return true;
}

function validateRange(form) {
    return validateIntRange(form);
}

function validateShort(form) {
    var bValid = true;
    var focusField = null;
    var i = 0;
    var fields = new Array();
    oShort = new ShortValidations();
    for (x in oShort) {
        var field = form[oShort[x][0]];

        if (field.type == 'text' ||
            field.type == 'textarea' ||
            field.type == 'select-one' ||
            field.type == 'radio') {

            var value = '';
            // get field's value
            if (field.type == "select-one") {
                var si = field.selectedIndex;
                if (si >= 0) {
                    value = field.options[si].value;
                }
            } else {
                value = field.value;
            }

            if (value.length > 0) {
                if (!isAllDigits(value)) {
                    bValid = false;
                    if (i == 0) {
                        focusField = field;
                    }
                    fields[i++] = oShort[x][1];

                } else {

                    var iValue = parseInt(value);
                    if (isNaN(iValue) || !(iValue >= -32768 && iValue <= 32767)) {
                        if (i == 0) {
                            focusField = field;
                        }
                        fields[i++] = oShort[x][1];
                        bValid = false;
                    }
                }
            }
        }
    }
    if (fields.length > 0) {
        focusField.focus();
        Ext.Msg.alert('', fields.join('\n'), validateShortInternalCallback());
    }
    function validateShortInternalCallback(){};
    return bValid;
}
function validateFloat(form) {
    var bValid = true;
    var focusField = null;
    var i = 0;
    var fields = new Array();
    oFloat = new FloatValidations();
    for (x in oFloat) {
        var field = form[oFloat[x][0]];

        if (field.type == 'text' ||
            field.type == 'textarea' ||
            field.type == 'select-one' ||
            field.type == 'radio') {

            var value = '';
            // get field's value
            if (field.type == "select-one") {
                var si = field.selectedIndex;
                if (si >= 0) {
                    value = field.options[si].value;
                }
            } else {
                value = field.value;
            }

            if (value.length > 0) {
                // remove '.' before checking digits
                var tempArray = value.split('.');
                var joinedString= tempArray.join('');

                if (!isAllDigits(joinedString)) {
                    bValid = false;
                    if (i == 0) {
                        focusField = field;
                    }
                    fields[i++] = oFloat[x][1];

                } else {
                    var iValue = parseFloat(value);
                    if (isNaN(iValue)) {
                        if (i == 0) {
                            focusField = field;
                        }
                        fields[i++] = oFloat[x][1];
                        bValid = false;
                    }
                }
            }
        }
    }
    if (fields.length > 0) {
        focusField.focus();
        Ext.Msg.alert('', fields.join('\n'), validateFloatInternalCallback());
    }
    function validateFloatInternalCallback(){};
    return bValid;
}
function validateEmail(form) {
    var bValid = true;
    var focusField = null;
    var i = 0;
    var fields = new Array();
    oEmail = new email();
    for (x in oEmail) {
        if ((form[oEmail[x][0]].type == 'text' ||
             form[oEmail[x][0]].type == 'textarea') &&
            (form[oEmail[x][0]].value.length > 0)) {
            if (!checkEmail(form[oEmail[x][0]].value)) {
                if (i == 0) {
                    focusField = form[oEmail[x][0]];
                }
                fields[i++] = oEmail[x][1];
                bValid = false;
            }
        }
    }
    if (fields.length > 0) {
        focusField.focus();
        Ext.Msg.alert('', fields.join('\n'), validateMailInternalCallback());
    }
    function validateMailInternalCallback(){};
    return bValid;
}

/**
 * Reference: Sandeep V. Tamhankar (stamhankar@hotmail.com),
 * http://javascript.internet.com
 */
function checkEmail(emailStr) {
    if (emailStr.length == 0) {
        return true;
    }
    var emailPat=/^(.+)@(.+)$/;
    var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]";
    var validChars="\[^\\s" + specialChars + "\]";
    var quotedUser="(\"[^\"]*\")";
    var ipDomainPat=/^(\d{1,3})[.](\d{1,3})[.](\d{1,3})[.](\d{1,3})$/;
    var atom=validChars + '+';
    var word="(" + atom + "|" + quotedUser + ")";
    var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
    var domainPat=new RegExp("^" + atom + "(\\." + atom + ")*$");
    var matchArray=emailStr.match(emailPat);
    if (matchArray == null) {
        return false;
    }
    var user=matchArray[1];
    var domain=matchArray[2];
    if (user.match(userPat) == null) {
        return false;
    }
    var IPArray = domain.match(ipDomainPat);
    if (IPArray != null) {
        for (var i = 1; i <= 4; i++) {
            if (IPArray[i] > 255) {
                return false;
            }
        }
        return true;
    }
    var domainArray=domain.match(domainPat);
    if (domainArray == null) {
        return false;
    }
    var atomPat=new RegExp(atom,"g");
    var domArr=domain.match(atomPat);
    var len=domArr.length;
    if ((domArr[domArr.length-1].length < 2) ||
        (domArr[domArr.length-1].length > 3)) {
        return false;
    }
    if (len < 2) {
        return false;
    }
    return true;
}
function validateMinLength(form) {
    var isValid = true;
    var focusField = null;
    var i = 0;
    var fields = new Array();
    oMinLength = new minlength();
    for (x in oMinLength) {
        var field = form[oMinLength[x][0]];

        if (field.type == 'text' ||
            field.type == 'textarea') {

            var iMin = parseInt(oMinLength[x][2]("minlength"));
            if ((trim(field.value).length > 0) && (field.value.length < iMin)) {
                if (i == 0) {
                    focusField = field;
                }
                fields[i++] = oMinLength[x][1];
                isValid = false;
            }
        }
    }
    if (fields.length > 0) {
        focusField.focus();
        Ext.Msg.alert('', fields.join('\n'), validateMinLengthInternalCallback());
    }
    function validateMinLengthInternalCallback(){};
    return isValid;
}
function validateDate(form) {
    var bValid = true;
    var focusField = null;
    var i = 0;
    var fields = new Array();
    oDate = new DateValidations();
    for (x in oDate) {
        var value = form[oDate[x][0]].value;
        var datePattern = oDate[x][2]("datePatternStrict");
        if ((form[oDate[x][0]].type == 'text' ||
             form[oDate[x][0]].type == 'textarea') &&
            (value.length > 0) &&
            (datePattern.length > 0)) {
            var MONTH = "MM";
            var DAY = "dd";
            var YEAR = "yyyy";
            var orderMonth = datePattern.indexOf(MONTH);
            var orderDay = datePattern.indexOf(DAY);
            var orderYear = datePattern.indexOf(YEAR);
            if ((orderDay < orderYear && orderDay > orderMonth)) {
                var iDelim1 = orderMonth + MONTH.length;
                var iDelim2 = orderDay + DAY.length;
                var delim1 = datePattern.substring(iDelim1, iDelim1 + 1);
                var delim2 = datePattern.substring(iDelim2, iDelim2 + 1);
                if (iDelim1 == orderDay && iDelim2 == orderYear) {
                    dateRegexp = new RegExp("^(\\d{2})(\\d{2})(\\d{4})$");
                } else if (iDelim1 == orderDay) {
                    dateRegexp = new RegExp("^(\\d{2})(\\d{2})[" + delim2 + "](\\d{4})$");
                } else if (iDelim2 == orderYear) {
                    dateRegexp = new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})(\\d{4})$");
                } else {
                    dateRegexp = new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})[" + delim2 + "](\\d{4})$");
                }
                var matched = dateRegexp.exec(value);
                if(matched != null) {
                    if (!isValidDate(matched[2], matched[1], matched[3])) {
                        if (i == 0) {
                            focusField = form[oDate[x][0]];
                        }
                        fields[i++] = oDate[x][1];
                        bValid =  false;
                    }
                } else {
                    if (i == 0) {
                        focusField = form[oDate[x][0]];
                    }
                    fields[i++] = oDate[x][1];
                    bValid =  false;
                }
            } else if ((orderMonth < orderYear && orderMonth > orderDay)) {
                var iDelim1 = orderDay + DAY.length;
                var iDelim2 = orderMonth + MONTH.length;
                var delim1 = datePattern.substring(iDelim1, iDelim1 + 1);
                var delim2 = datePattern.substring(iDelim2, iDelim2 + 1);
                if (iDelim1 == orderMonth && iDelim2 == orderYear) {
                    dateRegexp = new RegExp("^(\\d{2})(\\d{2})(\\d{4})$");
                } else if (iDelim1 == orderMonth) {
                    dateRegexp = new RegExp("^(\\d{2})(\\d{2})[" + delim2 + "](\\d{4})$");
                } else if (iDelim2 == orderYear) {
                    dateRegexp = new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})(\\d{4})$");
                } else {
                    dateRegexp = new RegExp("^(\\d{2})[" + delim1 + "](\\d{2})[" + delim2 + "](\\d{4})$");
                }
                var matched = dateRegexp.exec(value);
                if(matched != null) {
                    if (!isValidDate(matched[1], matched[2], matched[3])) {
                        if (i == 0) {
                            focusField = form[oDate[x][0]];
                        }
                        fields[i++] = oDate[x][1];
                        bValid =  false;
                    }
                } else {
                    if (i == 0) {
                        focusField = form[oDate[x][0]];
                    }
                    fields[i++] = oDate[x][1];
                    bValid =  false;
                }
            } else if ((orderMonth > orderYear && orderMonth < orderDay)) {
                var iDelim1 = orderYear + YEAR.length;
                var iDelim2 = orderMonth + MONTH.length;
                var delim1 = datePattern.substring(iDelim1, iDelim1 + 1);
                var delim2 = datePattern.substring(iDelim2, iDelim2 + 1);
                if (iDelim1 == orderMonth && iDelim2 == orderDay) {
                    dateRegexp = new RegExp("^(\\d{4})(\\d{2})(\\d{2})$");
                } else if (iDelim1 == orderMonth) {
                    dateRegexp = new RegExp("^(\\d{4})(\\d{2})[" + delim2 + "](\\d{2})$");
                } else if (iDelim2 == orderDay) {
                    dateRegexp = new RegExp("^(\\d{4})[" + delim1 + "](\\d{2})(\\d{2})$");
                } else {
                    dateRegexp = new RegExp("^(\\d{4})[" + delim1 + "](\\d{2})[" + delim2 + "](\\d{2})$");
                }
                var matched = dateRegexp.exec(value);
                if(matched != null) {
                    if (!isValidDate(matched[3], matched[2], matched[1])) {
                        if (i == 0) {
                            focusField = form[oDate[x][0]];
                        }
                        fields[i++] = oDate[x][1];
                        bValid =  false;
                    }
                } else {
                    if (i == 0) {
                        focusField = form[oDate[x][0]];
                    }
                    fields[i++] = oDate[x][1];
                    bValid =  false;
                }
            } else {
                if (i == 0) {
                    focusField = form[oDate[x][0]];
                }
                fields[i++] = oDate[x][1];
                bValid =  false;
            }
        }
    }
    if (fields.length > 0) {
        focusField.focus();
        Ext.Msg.alert('', fields.join('\n'), validateDateInternalCallback());
    }
    function validateDateInternalCallback(){};
    return bValid;
}

function isValidDate(day, month, year) {
    if (month < 1 || month > 12) {
        return false;
    }
    if (day < 1 || day > 31) {
        return false;
    }
    if ((month == 4 || month == 6 || month == 9 || month == 11) &&
        (day == 31)) {
        return false;
    }
    if (month == 2) {
        var leap = (year % 4 == 0 &&
                    (year % 100 != 0 || year % 400 == 0));
        if (day>29 || (day == 29 && !leap)) {
            return false;
        }
    }
    return true;
}
function validateIntRange(form) {
    var isValid = true;
    var focusField = null;
    var i = 0;
    var fields = new Array();
    oRange = new intRange();
    for (x in oRange) {
        var field = form[oRange[x][0]];

        if ((field.type == 'text' ||
             field.type == 'textarea') &&
            (field.value.length > 0)) {

            var iMin = parseInt(oRange[x][2]("min"));
            var iMax = parseInt(oRange[x][2]("max"));
            var iValue = parseInt(field.value);
            if (!(iValue >= iMin && iValue <= iMax)) {
                if (i == 0) {
                    focusField = field;
                }
                fields[i++] = oRange[x][1];
                isValid = false;
            }
        }
    }
    if (fields.length > 0) {
        focusField.focus();
        Ext.Msg.alert('', fields.join('\n'), validateIntRangeInternalCallback());
    }
    function validateIntRangeInternalCallback(){};
    return isValid;
}
function validateMask(form) {
    var isValid = true;
    var focusField = null;
    var i = 0;
    var fields = new Array();
    oMasked = new mask();
    for (x in oMasked) {
        var field = form[oMasked[x][0]];

        if ((field.type == 'text' ||
             field.type == 'textarea') &&
            (field.value.length > 0)) {

            if (!matchPattern(field.value, oMasked[x][2]("mask"))) {
                if (i == 0) {
                    focusField = field;
                }
                fields[i++] = oMasked[x][1];
                isValid = false;
            }
        }
    }

    if (fields.length > 0) {
        focusField.focus();
        Ext.Msg.alert('', fields.join('\n'), validateMaskInternalCallback());
    }
    function validateMaskInternalCallback(){};
    return isValid;
}

function matchPattern(value, mask) {
    return mask.exec(value);
}
function validateMaxLength(form) {
    var isValid = true;
    var focusField = null;
    var i = 0;
    var fields = new Array();
    oMaxLength = new maxlength();
    for (x in oMaxLength) {
        var field = form[oMaxLength[x][0]];

        if (field.type == 'text' ||
            field.type == 'textarea') {

            var iMax = parseInt(oMaxLength[x][2]("maxlength"));
            if (field.value.length > iMax) {
                if (i == 0) {
                    focusField = field;
                }
                fields[i++] = oMaxLength[x][1];
                isValid = false;
            }
        }
    }
    if (fields.length > 0) {
        focusField.focus();
        Ext.Msg.alert('', fields.join('\n'), validateMaxLengthInternalCallback());
    }
    function validateMaxLengthInternalCallback(){};
    return isValid;
}
function validateCreditCard(form) {
    var bValid = true;
    var focusField = null;
    var i = 0;
    var fields = new Array();
    oCreditCard = new creditCard();
    for (x in oCreditCard) {
        if ((form[oCreditCard[x][0]].type == 'text' ||
             form[oCreditCard[x][0]].type == 'textarea') &&
            (form[oCreditCard[x][0]].value.length > 0)) {
            if (!luhnCheck(form[oCreditCard[x][0]].value)) {
                if (i == 0) {
                    focusField = form[oCreditCard[x][0]];
                }
                fields[i++] = oCreditCard[x][1];
                bValid = false;
            }
        }
    }
    if (fields.length > 0) {
        focusField.focus();
        Ext.Msg.alert('', fields.join('\n'), validateCreditCardInternalCallback());
    }
    function validateCreditCardInternalCallback(){};
    return bValid;
}

/**
 * Reference: http://www.ling.nwu.edu/~sburke/pub/luhn_lib.pl
 */
function luhnCheck(cardNumber) {
    if (isLuhnNum(cardNumber)) {
        var no_digit = cardNumber.length;
        var oddoeven = no_digit & 1;
        var sum = 0;
        for (var count = 0; count < no_digit; count++) {
            var digit = parseInt(cardNumber.charAt(count));
            if (!((count & 1) ^ oddoeven)) {
                digit *= 2;
                if (digit > 9) digit -= 9;
            };
            sum += digit;
        };
        if (sum == 0) return false;
        if (sum % 10 == 0) return true;
    };
    return false;
}

function isLuhnNum(argvalue) {
    argvalue = argvalue.toString();
    if (argvalue.length == 0) {
        return false;
    }
    for (var n = 0; n < argvalue.length; n++) {
        if ((argvalue.substring(n, n+1) < "0") ||
            (argvalue.substring(n,n+1) > "9")) {
            return false;
        }
    }
    return true;
}
function validateByte(form) {
    var bValid = true;
    var focusField = null;
    var i = 0;
    var fields = new Array();
    oByte = new ByteValidations();
    for (x in oByte) {
        var field = form[oByte[x][0]];

        if (field.type == 'text' ||
            field.type == 'textarea' ||
            field.type == 'select-one' ||
            field.type == 'radio') {

            var value = '';
            // get field's value
            if (field.type == "select-one") {
                var si = field.selectedIndex;
                if (si >= 0) {
                    value = field.options[si].value;
                }
            } else {
                value = field.value;
            }

            if (value.length > 0) {
                if (!isAllDigits(value)) {
                    bValid = false;
                    if (i == 0) {
                        focusField = field;
                    }
                    fields[i++] = oByte[x][1];

                } else {

                    var iValue = parseInt(value);
                    if (isNaN(iValue) || !(iValue >= -128 && iValue <= 127)) {
                        if (i == 0) {
                            focusField = field;
                        }
                        fields[i++] = oByte[x][1];
                        bValid = false;
                    }
                }
            }

        }
    }
    if (fields.length > 0) {
        focusField.focus();
        Ext.Msg.alert('', fields.join('\n'), validateByteInternalCallback());
    }
    function validateByteInternalCallback(){};
    return bValid;
}
function validateFloatRange(form) {
    var isValid = true;
    var focusField = null;
    var i = 0;
    var fields = new Array();
    oRange = new floatRange();
    for (x in oRange) {
        var field = form[oRange[x][0]];

        if ((field.type == 'text' ||
             field.type == 'textarea') &&
            (field.value.length > 0)) {

            var fMin = parseFloat(oRange[x][2]("min"));
            var fMax = parseFloat(oRange[x][2]("max"));
            var fValue = parseFloat(field.value);
            if (!(fValue >= fMin && fValue <= fMax)) {
                if (i == 0) {
                    focusField = field;
                }
                fields[i++] = oRange[x][1];
                isValid = false;
            }
        }
    }
    if (fields.length > 0) {
        focusField.focus();
        Ext.Msg.alert('', fields.join('\n'), validateFloatRangeInternalCallback());
    }
    function validateFloatRangeInternalCallback(){};
    return isValid;
}

function getElementsByAttribute(parentDiv, attribute, attributeValue)
{
    var elementArray = new Array();
    var matchedArray = new Array();

    elementArray = parentDiv.getElementsByTagName("*");

    for (var i = 0; i < elementArray.length; i++) {
        if (attribute == "class") {
            var pattern = new RegExp("(^| )" + attributeValue + "( |$)");

            if (pattern.test(elementArray[i].className)) {
                matchedArray[matchedArray.length] = elementArray[i];
            }
        }
        else if (attribute == "for") {
            if (elementArray[i].getAttribute("htmlFor") || elementArray[i].getAttribute("for")) {
                if (elementArray[i].htmlFor == attributeValue) {
                    matchedArray[matchedArray.length] = elementArray[i];
                }
            }
        }
        else if (elementArray[i].getAttribute(attribute) == attributeValue) {
            matchedArray[matchedArray.length] = elementArray[i];
        }
    }
    return matchedArray;
}


function addOptionToSelect(selectElement, value, text) {
    var elOptNew = document.createElement('option');
    elOptNew.text = text;
    elOptNew.value = value;
    try {
        selectElement.add(elOptNew, null); // standards compliant; doesn't work in IE
    }
    catch(ex) {
        selectElement.add(elOptNew); // IE only
    }
}

function elementExists(element) {
    if (typeof(element)=='undefined' || element == null) {
        return false;
    }
    return true;
}

function getWindowWidth() {
    var myWidth = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myWidth = window.innerWidth;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
    }
    return myWidth;
}

function getWindowHeight() {
    var myHeight = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myHeight = document.body.clientHeight;
    }
    return myHeight;
}

function showPopup(text, param1, param2) {
    return overlib('<div class="popupclass">' + text + '</div>', param1, param2);
}


/*******************************************************************/
/***                                                             ***/
/***   Tokenizer.js - JavaScript String Tokenizer Function       ***/
/***                                                             ***/
/***   Version   : 0.2                                           ***/
/***   Date      : 01.05.2005                                    ***/
/***   Copyright : 2005 Adrian Zentner                           ***/
/***   Website   : http://www.adrian.zentner.name/               ***/
/***                                                             ***/
/***   This library is free software. It can be freely used as   ***/
/***   long as this this copyright notice is not removed.        ***/
/***                                                             ***/
/*******************************************************************/

String.prototype.tokenize = tokenize;

function tokenize()
{
    var input             = "";
    var separator         = " ";
    var trim              = "";
    var ignoreEmptyTokens = true;

    try {
        String(this.toLowerCase());
    }
    catch(e) {
        window.alert("Tokenizer Usage: string myTokens[] = myString.tokenize(string separator, string trim, boolean ignoreEmptyTokens);");
        return;
    }

    if(typeof(this) != "undefined")
    {
        input = String(this);
    }

    if(typeof(tokenize.arguments[0]) != "undefined")
    {
        separator = String(tokenize.arguments[0]);
    }

    if(typeof(tokenize.arguments[1]) != "undefined")
    {
        trim = String(tokenize.arguments[1]);
    }

    if(typeof(tokenize.arguments[2]) != "undefined")
    {
        if(!tokenize.arguments[2])
            ignoreEmptyTokens = false;
    }

    var array = input.split(separator);

    if(trim)
        for(var i=0; i<array.length; i++)
        {
            while(array[i].slice(0, trim.length) == trim)
                array[i] = array[i].slice(trim.length);
            while(array[i].slice(array[i].length-trim.length) == trim)
                array[i] = array[i].slice(0, array[i].length-trim.length);
        }

    var token = new Array();
    if(ignoreEmptyTokens)
    {
        for(var i=0; i<array.length; i++)
            if(array[i] != "")
                token.push(array[i]);
    }
    else
    {
        token = array;
    }

    return token;
}



/***** Context menu for project issue *****/

function setUpContextMenuForLinks(rootNode) {
    Ext.each(Ext.query("*[class=issueLink]", rootNode), function(elem){
        var linkElem = Ext.get(elem);
        var linkElemId = linkElem.id.split('|');
        var indexSubString = 6;
        if (linkElemId[0].indexOf('issue_key') > -1) {
            indexSubString = 10;
        }
        var projectIssueId = linkElemId[0].substring(indexSubString);
        var projectIssueName = Ext.get('issueName_' + projectIssueId).dom.innerHTML;
        linkElem.un('contextmenu', showIssueContextMenu);
        linkElem.on('contextmenu', showIssueContextMenu, null, {issueId: linkElemId[0].substring(indexSubString), projectId: linkElemId[1], projectName: linkElemId[2], issueName: projectIssueName});

    });

}

function onDoSomethingClick(item){
    //alert('Clicked ' + item.text + " id: " + item.id);
}

var currentContextMenuEvent;
var currentContextMenuFolderId;
var currentContextDocumentId;
var currentContextMenuDocumentName;
var currentContextMenuIssueId;
var currentContextMenuIssueName;
var currentContextMenuIssueProjectId;
var currentContextMenuIssueProjectName;
var currentExtGridRecord;
var currentExtGrid;
var currentContextMenu;

function showIssueContextMenu(e, target, options) {
    e.stopEvent();
    currentContextMenuEvent = e;
    currentContextMenuIssueId = options.issueId + '';
    currentContextMenuIssueName = options.issueName;
    currentContextMenuIssueProjectId = options.projectId || null;
    currentContextMenuIssueProjectName = options.projectName || null;
    currentExtGridRecord = options.extrecord || null;
    currentExtGrid = options.extgrid || null;
    ProjectIssueRemoteAction.getContextMenuForIssue(options.issueId, menuItemsReturned);
}

function menuItemsReturned(menuItemsAsString) {
    try {
        currentContextMenu = new Ext.menu.Menu({
            /*id: 'issueContextMenu',*/
            style: {
                overflow: 'visible'     // For the Combo popup
            },
            items: eval(menuItemsAsString)
        });

        var coords = currentContextMenuEvent.getXY();
        currentContextMenu.showAt([coords[0], coords[1]]);
    } catch(ex) {
        alert(ex.message);
    }
}

function loadIssueFromDoubleClick(e, target, options){
    e.stopEvent();
    currentContextMenuEvent = e;
    currentContextMenuIssueId = options.issueId;
    currentContextMenuIssueProjectId = options.projectId || null;
    currentContextMenuIssueProjectName = options.projectName || null;
    currentExtGridRecord = options.extrecord || null;
    currentExtGrid = options.extgrid || null;

    onEditIssueSelected();
}

function loadDocumentFolderFromDoubleClick(e, target, container){
    e.stopEvent();
    currentContextMenuEvent = e;
    //currentContextMenuIssueId = options.issueId;
    currentContextMenuIssueProjectId = container.projectId || null;
    currentContextMenuIssueProjectName = container.projectName || null;
    currentContextMenuFolderId = container.folderId || null;
    currentContextMenuDocumentId = container.documentId || null;
    currentContextMenuDocumentName = container.documentName || null;
    currentExtGridRecord = container.extrecord || null;
    currentExtGrid = container.extgrid || null;

    onOpenDocumentFolderInNewTab();
}

function openIssueInNewTabFromDoubleClick(e, target, options){
    e.stopEvent();
    currentContextMenuEvent = e;
    currentContextMenuIssueId = options.issueId;
    currentContextMenuIssueName = options.issueName;
    currentContextMenuIssueProjectId = options.projectId || null;
    currentContextMenuIssueProjectName = options.projectName || null;
    currentExtGridRecord = options.extrecord || null;
    currentExtGrid = options.extgrid || null;

    onOpenIssueInNewTabSelected();
}

function getDashboardModeFlag() {
    var dashboardModeElement = document.getElementById("dashboardMode");
    if (elementExists(dashboardModeElement)) {
        return dashboardModeElement.value == "1";
    } else {
        return false;
    }
}

function onEditIssueSelected(item) {
    if (currentExtGridRecord != null) {
        if (currentExtGridRecord.get('projectIssueId') == undefined) {
            var issueId = currentExtGridRecord.get('internalData').substring(0, currentExtGridRecord.get('internalData').indexOf("|"));
            loadProjectIssue(issueId, currentExtGridRecord.get('projectId'), currentExtGridRecord.get('projectName'), '');
        } else {
            loadProjectIssue(currentExtGridRecord.get('projectIssueId'), currentExtGridRecord.get('projectId'), currentExtGridRecord.get('projectName'), '');
        }
    } else {
        loadProjectIssue(currentContextMenuIssueId, currentContextMenuIssueProjectId, currentContextMenuIssueProjectName, '');
    }
}

function onOpenIssueInNewTabSelected(item) {
    if (currentContextMenu) {
        currentContextMenu.destroy();
    }
    if (currentExtGridRecord != null) {
        if (currentExtGridRecord.get('projectIssueId') == undefined) {
            openProjectIssueInNewTab(currentContextMenuIssueId, currentContextMenuIssueName, currentExtGridRecord.get('projectId'), currentExtGridRecord.get('projectName'), '', true);
        } else {
            openProjectIssueInNewTab(currentExtGridRecord.get('projectIssueId'), "[" + currentExtGridRecord.get('issueKey') + "] " + currentExtGridRecord.get('name'), currentExtGridRecord.get('projectId'), currentExtGridRecord.get('projectName'), '', true);
        }
    } else {
        openProjectIssueInNewTab(currentContextMenuIssueId, currentContextMenuIssueName, currentContextMenuIssueProjectId, currentContextMenuIssueProjectName, '', true);
    }
}

function onOpenDocumentFolderInNewTab(item) {
        loadDocumentFolder(currentContextMenuFolderId, currentContextMenuDocumentId, currentContextMenuDocumentName, currentContextMenuIssueProjectId, currentContextMenuIssueProjectName);
}

function onSetIssueStatusSelected(item) {
    var dashboardMode = getDashboardModeFlag();
    setAttributeOnIssue("issuestatus", item.itemId, dashboardMode);
}

function onSetIssueSeveritySelected(item) {
    var dashboardMode = getDashboardModeFlag();
    setAttributeOnIssue("issueseverity", item.itemId, dashboardMode);
}

function onSetIssueTypeSelected(item) {
    var dashboardMode = getDashboardModeFlag();
    setAttributeOnIssue("issuetype", item.itemId, dashboardMode);
}

function onSetIssuePrioritySelected(item) {
    var dashboardMode = getDashboardModeFlag();
    setAttributeOnIssue("issuepriority", item.itemId, dashboardMode);
}

function onSetIssuePriorityAsNumber(fieldId, value) {
    var dashboardMode = getDashboardModeFlag();    
    setAttributeOnIssue("issuepriority", value, dashboardMode);
    currentContextMenu.hide(true);
}


function onSetOwnerSelected(item) {
    var dashboardMode = getDashboardModeFlag();
    setAttributeOnIssue("owner", item.itemId, dashboardMode);
}

function onSetOwnerGroupSelected(item) {
    var dashboardMode = getDashboardModeFlag();
    setAttributeOnIssue("ownerGroup", item.itemId, dashboardMode);
}


function onSetDeveloperSelected(item) {
    var dashboardMode = getDashboardModeFlag();
    setAttributeOnIssue("developer", item.itemId, dashboardMode);
}

function onSetIssueVersionSelected(item) {
    var dashboardMode = getDashboardModeFlag();
    setAttributeOnIssue("version", item.itemId, dashboardMode);
}

function onSetComponentSelected(item) {
    var dashboardMode = getDashboardModeFlag();
    setAttributeOnIssue("component", item.itemId, dashboardMode);
}

function onSetIssueSourceSelected(item) {
    var dashboardMode = getDashboardModeFlag();
    setAttributeOnIssue("issuesource", item.itemId, dashboardMode);
}

function onSetCustomFieldSelected(item) {
    var dashboardMode = getDashboardModeFlag();
    setAttributeOnIssue("companyCustomField", item.itemId, dashboardMode);
}

function onSetCompanySelected(item) {
    var dashboardMode = getDashboardModeFlag();
    setAttributeOnIssue("company", item.itemId, dashboardMode);
}

function onEditProductSelected(item) {
    var idFields = item.itemId.split("|");
    var configItemSelectorDlg = showConfigItemSelectorDialog(false, '0', idFields[0], idFields[1], idFields[1], function(configItemId, configItemName) {
        var dashboardMode = getDashboardModeFlag();
        configItemSelectorDlg.hide();
        setAttributeOnIssue("product", configItemId, dashboardMode);        
    });
}

function onEditCompanyCustomFieldOfProductTypeSelected(item) {
    var idFields = item.itemId.split("|");
    var configItemTypeId = idFields[0];
    var customFieldIndex = idFields[1];
    var configItemRoot = idFields[2];
    var displayName = idFields[3];
    var configItemSelectorDlg = showConfigItemSelectorDialog(false, configItemRoot, configItemTypeId, displayName, displayName, function(configItemId, configItemName) {
        var dashboardMode = getDashboardModeFlag();
        configItemSelectorDlg.hide();
        setAttributeOnIssue("companyCustomField", customFieldIndex + "|" + configItemId, dashboardMode);
    });
}

function onPrintIssueSelected(item) {
    if (currentContextMenuIssueId.indexOf(",") < 0) {
        window.open('EditProjectIssue.do?printView=true&projectIssueId=' + currentContextMenuIssueId);
    } else {
        Ext.Msg.alert('', 'This feature is only available when selecting one issue.');
    }
}

function onShowDirectLinkToIssueSelected(item) {
    if (currentContextMenuIssueId.indexOf(",") < 0) {
        showDirectLinkToProjectIssue(currentContextMenuIssueId);
    } else {
        Ext.Msg.alert('', 'This feature is only available when selecting one issue.');
    }
}

function showDirectLinkToProjectIssue(projectIssueId) {
    ProjectIssueRemoteAction.getDirectLinkForIssue(projectIssueId, function(linkText) {
        Ext.Msg.alert(JSMessages.get("ext.project.documents.directLink"), linkText);
    });
}

Ext.namespace("Ext.ux.menu");
Ext.ux.menu.EditableItem = Ext.extend(Ext.menu.BaseItem, {
    itemCls : "x-menu-item",
    hideOnClick: false,
    fieldId: null,
    callback: null,
    textFieldWidth: null,

    initComponent: function(){
        this.addEvents({keyup: true});
        this.editor = this.editor || new Ext.form.TextField();
        if(this.text)
            this.editor.setValue(this.text);
    },

    onRender: function(container){
        var s = container.createChild({
            cls: this.itemCls,
            html: '<img src="' + (this.icon||Ext.BLANK_IMAGE_URL)+ '" class="x-menu-item-icon'+(this.iconCls?' '+this.iconCls:'')+'" style="margin: 3px 7px 2px 2px;" />'});;

        if (this.textFieldWidth) {
            Ext.apply(this.config, {width: this.textFieldWidth});
        } else {
            Ext.apply(this.config, {width: 125});
        }
        this.editor.render(s);
        this.el = s;
        //this.relayEvents(this.editor.el, ["keyup"]);
        this.editor.el.on('keyup', this.onKeyUp, this);

        if(Ext.isGecko)
            s.setStyle('overflow', 'auto');

        Ext.ux.menu.EditableItem.superclass.onRender.apply(this, arguments);
    },

    getValue: function(){
        return this.editor.getValue();
    },

    setValue: function(value){
        this.editor.setValue(value);
    },

    isValid: function(preventMark){
        return this.editor.isValid(preventMark);
    },

    onKeyUp: function(event){
        if(event.getKey() == event.ENTER){
            this.callback(this.fieldId, this.getValue());
        }
    }


});


function setCompanyCustomFieldTextField(fieldId, value) {
    var dashboardMode = getDashboardModeFlag();
    setAttributeOnIssue("companyCustomField", fieldId + "|" + value, dashboardMode);
    currentContextMenu.hide(true);
}

function onSetCompanyCustomFieldSelected(item) {
    var dashboardMode = getDashboardModeFlag();
    setAttributeOnIssue("companyCustomField", item.itemId, dashboardMode);
}

function onSetOriginalEstimatedTime(fieldId, value) {
    var dashboardMode = getDashboardModeFlag();
    setAttributeOnIssue("originalEstimatedTime", value, dashboardMode);
    currentContextMenu.hide(true);
}

function onSetActualTime(fieldId, value) {
    var dashboardMode = getDashboardModeFlag();
    setAttributeOnIssue("actualTime", value, dashboardMode);
    currentContextMenu.hide(true);
}

function onSetRemainingTime(fieldId, value) {
    var dashboardMode = getDashboardModeFlag();
    setAttributeOnIssue("remainingTime", value, dashboardMode);
    currentContextMenu.hide(true);
}

function onSetFixedTime(fieldId, value) {
    var dashboardMode = getDashboardModeFlag();
    setAttributeOnIssue("fixedTime", value, dashboardMode);
    currentContextMenu.hide(true);
}

function onSetBillingAmount(fieldId, value) {
    var dashboardMode = getDashboardModeFlag();
    setAttributeOnIssue("billingAmount", value, dashboardMode);
    currentContextMenu.hide(true);
}

function onSetCostAmount(fieldId, value) {
    var dashboardMode = getDashboardModeFlag();
    setAttributeOnIssue("costAmount", value, dashboardMode);
    currentContextMenu.hide(true);
}

function onSetFixedPrice(fieldId, value) {
    var dashboardMode = getDashboardModeFlag();
    setAttributeOnIssue("fixedPrice", value, dashboardMode);
    currentContextMenu.hide(true);
}

function onSetTitle(fieldId, value) {
    var dashboardMode = getDashboardModeFlag();
    setAttributeOnIssue("title", value, dashboardMode);
    currentContextMenu.hide(true);
}

function onEditTagsSelected(item) {
    if (currentExtGridRecord != null) {
        if (currentExtGridRecord.get('projectIssueId') == undefined) {
            EditIssueTagsDialog.showDialog(null, currentContextMenuIssueId);
        } else {
            EditIssueTagsDialog.showDialog(null, currentExtGridRecord.get('projectIssueId'));
        }
    } else {
        EditIssueTagsDialog.showDialog(null, currentContextMenuIssueId);
    }
}

function onEditPermissionsSelected(item) {
    if (currentExtGridRecord != null) {
        if (currentExtGridRecord.get('projectIssueId') == undefined) {
            showEditIssuePermissionsDialog(currentContextMenuIssueId);
        } else {
            showEditIssuePermissionsDialog(currentExtGridRecord.get('projectIssueId'));
        }
    } else {
        showEditIssuePermissionsDialog(currentContextMenuIssueId);
    }
}

function onNewSubIssueSelected(item) {
    if (currentExtGridRecord != null) {
        if (currentExtGridRecord.get('projectIssueId') == undefined) {
            NewIssueDialog.showDialog(null, true, currentContextMenuIssueId, currentExtGridRecord.get('projectId'));
        } else {
            NewIssueDialog.showDialog(null, true, currentExtGridRecord.get('projectIssueId'), currentExtGridRecord.get('projectId'));
        }
    } else {
        NewIssueDialog.showDialog(null, true, currentContextMenuIssueId, currentContextMenuIssueProjectId);
    }
}

function onChooseParentIssueSelected(item) {
    Ext.Msg.alert('', JSMessages.get("ext.project.issues.subissues.onlyImplementedInIssuesTab"));
}

function subIssueCreated() {
    NewIssueDialog.hideDlg();
}

function onReplyToCorrespondentSelected(item)  {

    if (currentExtGridRecord != null) {
        if (currentExtGridRecord.get('projectIssueId') == undefined) {
            loadReplyToCorrespondent(currentContextMenuIssueId, currentExtGridRecord.get('projectId'), currentExtGridRecord.get('projectName'));
        } else {
            loadReplyToCorrespondent(currentExtGridRecord.get('projectIssueId'), currentExtGridRecord.get('projectId'), currentExtGridRecord.get('projectName'));
        }
    } else {
        loadReplyToCorrespondent(currentContextMenuIssueId, currentContextMenuIssueProjectId, currentContextMenuIssueProjectName);
    }
}


function onCopyTransferSelected(item)  {
    if (currentExtGridRecord != null) {
        if (currentExtGridRecord.get('projectIssueId') == undefined) {
            loadCopyTransfer(currentContextMenuIssueId, currentExtGridRecord.get('projectId'), currentExtGridRecord.get('projectName'));
        } else {
            loadCopyTransfer(currentExtGridRecord.get('projectIssueId'), currentExtGridRecord.get('projectId'), currentExtGridRecord.get('projectName'));
        }
    } else {
        loadCopyTransfer(currentContextMenuIssueId, currentContextMenuIssueProjectId, currentContextMenuIssueProjectName);
    }
}


function onAddWorklogSelected(item)  {
    if (currentExtGridRecord != null) {
        if (currentExtGridRecord.get('projectIssueId') == undefined) {
            showWorkLogDialog(currentExtGridRecord.get('projectId'), currentContextMenuIssueId, 0, function(){}, false);
        } else {
            showWorkLogDialog(currentExtGridRecord.get('projectId'), currentContextMenuIssueId, 0, function(){}, false);
        }
    } else {
        showWorkLogDialog(currentContextMenuIssueProjectId, currentContextMenuIssueId, 0, function(){}, false);
    }
}


function onSpamIssueSelected(item) {
    Ext.Msg.confirm(' ',  JSMessages.get("ext.project.issues.script.areYouSureToDeleteIssuesAndUser"), function(buttonId) {
        if (buttonId == 'yes') {
            ProjectIssueRemoteAction.deleteIssue(currentContextMenuIssueId, true, 0, issueDeletedCallback);
        }
    });
}

function onDeleteIssueSelected(item) {
    Ext.Msg.confirm(JSMessages.get("ext.project.issues.script.delete"), JSMessages.get("ext.project.issues.script.areYouSureToDeleteIssues"),
        function(buttonId) {
            if (buttonId == 'yes') {
                ProjectIssueRemoteAction.deleteIssue(currentContextMenuIssueId, false, 2, issueDeletedCallback); // 2 means, do not delete subissues...
            }
        }
    );
}


Ext.form.Field.prototype.msgTarget = 'side';

function getGoodOldCalendarTimes(showStartdate, showDueDate) {

    var timeArr = ["00","01","02","03","04","05","06","07","08","09","10","11","12","13","14","15","16","17","18","19","20","21","22","23"];
    var minuteArr = ["00", "15", "30", "45"];
    var html = "<table>";
    if (showStartdate) {
        html += '<tr><td>' + JSMessages.get('ext.issuecontextmenu.startDate') + ': </td><td><input type=text name="contextMenuStartDate" id="contextMenuStartDate" class="editInputBox" style="width: 100px;" >' +
               '<img src="images/calendar/cal.gif" id="f_trigger_d" width="19" height="19" border="0" align="top">&nbsp;' +
               '<select name="contextMenuStartDateTime" id="contextMenuStartDateTime" class="selectBox" style="width: 64px">';
        for (var i=0; i < timeArr.length; i++) {
            for (var j=0; j < minuteArr.length; j++) {
                html += '<option value="' + timeArr[i] + ':' + minuteArr[j] + '">' + timeArr[i] + ':' + minuteArr[j] + '</option>';
            }
        }
        html += "</select></td></tr>";
    }

    if (showDueDate) {
        html += '<tr><td>' + JSMessages.get('ext.issuecontextmenu.dueDate') + ': </td><td><input type=text name="contextMenuDueDate" id="contextMenuDueDate" class="editInputBox" style="width: 100px;" >' +
               '<img src="images/calendar/cal.gif" id="f_trigger_c" width="19" height="19" border="0" align="top">&nbsp;' +
               '<select name="contextMenuDueDateTime" id="contextMenuDueDateTime" class="selectBox" style="width: 64px">';
        for (var i=0; i < timeArr.length; i++) {
            for (var j=0; j < minuteArr.length; j++) {
                html += '<option value="' + timeArr[i] + ':' + minuteArr[j] + '">' + timeArr[i] + ':' + minuteArr[j] + '</option>';
            }
        }
        html += "</select></td></tr>";
    }

    html += "</table>"

    return html;
}

var setDatesWin;
function showDialogDateDlg(showStartdate, showDueDate) {
    //if (!setDatesWin) {
        setDatesWin = new Ext.Window({
            width:400
            ,id:'setDatesWinId'
            ,height:150
            ,layout:'fit'
            ,border:false
            ,closable:false
            ,title: JSMessages.get('ext.issuecontextmenu.setdatedlgtitle')
            ,buttonAlign:'center'
            ,items: new Ext.Panel({
                baseCls: 'x-plain',
                bodyStyle: 'padding: 5px',
                html: getGoodOldCalendarTimes(showStartdate, showDueDate)
            })
            ,buttons:[{
                text: JSMessages.get('ext.button.submit')
                ,handler:function() {
                    saveDates();
                }
            },{
                text: 'Close' //JSMessages.get('ext.button.close')
                ,handler:function() {
                    setDatesWin.hide();
                    setDatesWin.destroy();
                }
            }
        ]});
    //}
    setDatesWin.show();
}




function onSetDates(item) {

    var dashboardMode = getDashboardModeFlag();

    var dueDate = item.itemId.substring(0, item.itemId.indexOf("|"));
    var startDate = item.itemId.substring(item.itemId.indexOf("|")+1);

    showDialogDateDlg(startDate != "NOACCESS", dueDate != "NOACCESS");

    if (startDate != "NOACCESS") {
        Calendar.setup({
            inputField     :    "contextMenuStartDate",     // id of the input field
            ifFormat       :    "%Y-%m-%d",     // format of the input field
            button         :    "f_trigger_d",  // trigger for the calendar (button ID)
            align          :    "Bl",           // alignment (defaults to "Bl")
            singleClick    :    true,
            firstDay	   :    1
        });
    }

    if (dueDate != "NOACCESS") {
        Calendar.setup({
            inputField     :    "contextMenuDueDate",     // id of the input field
            ifFormat       :    "%Y-%m-%d",     // format of the input field
            button         :    "f_trigger_c",  // trigger for the calendar (button ID)
            align          :    "Bl",           // alignment (defaults to "Bl")
            singleClick    :    true,
            firstDay	   :    1
        });
    }

    if (startDate != "NOACCESS") {
        if (startDate != "NULL") {
            //Ext.getCmp('contextMenuStartDate').setValue(Date.parseDate(startDate, "Y-m-d H:i"));
            document.getElementById('contextMenuStartDate').value = startDate.substring(0, startDate.indexOf(" "));
            var startDateTime = startDate.substring(startDate.indexOf(" ")+1);
            var sel = document.getElementById('contextMenuStartDateTime');
            for (i=0; i<sel.options.length; i++) {
                if (sel.options[i].text == startDateTime) {
                    sel.selectedIndex = i;
                }
            }
        }
    }
    if (dueDate != "NOACCESS") {
        if (dueDate != "NULL") {
            //Ext.getCmp('contextMenuDueDate').setValue(Date.parseDate(dueDate, "Y-m-d H:i"));
            document.getElementById('contextMenuDueDate').value = dueDate.substring(0, dueDate.indexOf(" "));
            var dueDateTime = dueDate.substring(dueDate.indexOf(" ")+1);
            var sel = document.getElementById('contextMenuDueDateTime');
            for (i=0; i<sel.options.length; i++) {
                if (sel.options[i].text == dueDateTime) {
                    sel.selectedIndex = i;
                }
            }
        }
    }
}

function saveDates() {
    var dashboardMode = getDashboardModeFlag();
    var returnData = "";
    if (elementExists(document.getElementById('contextMenuStartDate'))) {
        var startDate = document.getElementById('contextMenuStartDate').value;
        if (startDate != "" && startDate.length > 6) {
            returnData += startDate;
            var startDateTime = document.getElementById('contextMenuStartDateTime');
            returnData += " " + startDateTime.options[startDateTime.selectedIndex].value;
        } else {
            returnData += "NULL";
        }

    } else {
        returnData += "NULL";
    }
    returnData += "|";
    if (elementExists(document.getElementById('contextMenuDueDate'))) {
        var dueDate = document.getElementById('contextMenuDueDate').value;
        if (dueDate != "" && dueDate.length > 6) {
            returnData += dueDate;
            var dueDateTime = document.getElementById('contextMenuDueDateTime');
            returnData += " " + dueDateTime.options[dueDateTime.selectedIndex].value;
        } else {
            returnData += "NULL";
        }

    }

    setDatesWin.hide();
    setDatesWin.destroy();

    setAttributeOnIssue("dates", returnData, dashboardMode);
}


var addCommentWin;
function showAddCommentDlg() {
    addCommentWin = new Ext.Window({
        width:400
        ,id:'showAddCommentDlg'
        ,height:350
        ,layout:'fit'
        ,border:false
        ,closable:false
        ,title: JSMessages.get('ext.issuecontextmenu.addcommentdlgtitle')
        ,buttonAlign:'center'
        ,items:[{
            xtype:'form'
            ,labelAlign: 'top'
            ,frame:true
            ,labelWidth:100
            ,id:'form'
            ,items: [{
                xtype:'textarea',
                id:'contextMenuNewComment',
                hideLabel: true,
                layout: 'fit',
                anchor:'98% 98%'
            }]
        }]
        ,buttons:[{
            text: JSMessages.get('ext.button.submit')
            ,handler:function() {
                saveNewComment();
            }
        },{
            text: JSMessages.get('ext.button.close')
            ,handler:function() {
                addCommentWin.hide();
                addCommentWin.destroy();
            }
        }]
    });
    addCommentWin.show();
}




function onAddCommentSelected(item) {
    showAddCommentDlg();
}

function saveNewComment() {
    var dashboardMode = getDashboardModeFlag();
    var comment = Ext.getCmp('contextMenuNewComment').getValue();
    addCommentWin.hide();
    addCommentWin.destroy();
    setAttributeOnIssue("newcomment", comment, dashboardMode);
}

function onEditSolutionSelected(item) {
    ProjectIssueRemoteAction.getFields(currentContextMenuIssueId, new Array("solution"), loadSolutionCallback);
}

function loadSolutionCallback(issue) {
    var editSolutionWin = new Ext.Window({
        width:550
        ,id:'editSolutionDlg'
        ,height:350
        ,layout:'fit'
        ,border:false
        ,closable:false
        ,title: "Edit solution"
        ,buttonAlign:'center'
        ,items:[{
            xtype:'form'
            ,labelAlign: 'top'
            ,frame:true                        
            ,items: [{
                xtype:'htmleditor',
                id:'contextMenuEditSolution',
                value: issue.solution,
                hideLabel: true,
                layout: 'fit',
                anchor:'100% 100%'
            }]
        }]
        ,buttons:[{
            text: JSMessages.get('ext.button.submit')
            ,handler:function() {
                //saveNewComment();
                var solution = Ext.getCmp('contextMenuEditSolution').getValue();
                setAttributeOnIssue("editSolution", solution, getDashboardModeFlag());
                editSolutionWin.hide();
                editSolutionWin.destroy();
            }
        },{
            text: JSMessages.get('ext.button.close')
            ,handler:function() {
                editSolutionWin.hide();
                editSolutionWin.destroy();
            }
        }]
    });
    editSolutionWin.show();
}

function onEditDescriptionSelected(item) {
    ProjectIssueRemoteAction.getFields(currentContextMenuIssueId, new Array("description"), loadDescriptionCallback);
}

function loadDescriptionCallback(issue) {
    var editDescriptionWin = new Ext.Window({
        width:550
        ,id:'editDescriptionDlg'
        ,height:350
        ,layout:'fit'
        ,border:false
        ,closable:false
        ,title: "Edit description"
        ,buttonAlign:'center'
        ,items:[{
            xtype:'form'
            ,labelAlign: 'top'
            ,frame:true
            ,items: [{
                xtype:'htmleditor',
                id:'contextMenuEditDescription',
                value: issue.description,
                hideLabel: true,
                layout: 'fit',
                anchor:'100% 100%'
            }]
        }]
        ,buttons:[{
            text: JSMessages.get('ext.button.submit')
            ,handler:function() {
                //saveNewComment();
                var solution = Ext.getCmp('contextMenuEditDescription').getValue();
                setAttributeOnIssue("editDescription", solution, getDashboardModeFlag());
                editDescriptionWin.hide();
                editDescriptionWin.destroy();
            }
        },{
            text: JSMessages.get('ext.button.close')
            ,handler:function() {
                editDescriptionWin.hide();
                editDescriptionWin.destroy();
            }
        }]
    });
    editDescriptionWin.show();
}

var editIssuePermissionDialog;
function showEditIssuePermissionsDialog(issueId) {

    if (!editIssuePermissionDialog) {
        var title = JSMessages.get("ext.permissions.accessControl");

        editIssuePermissionDialog = new Ext.Window({
            title:title,
            height:300,
            width:500,
            maxWidth: 400,
            draggable:true,
            modal: true,
            autoScroll:true,
            closeAction: 'hide',
            layout: 'fit',
            buttonAlign:'center',
            fixedcenter:true,
            bodyStyle:'padding:5px;',
            plain:true,
            buttons: [{
                text: JSMessages.get("ext.button.save"),
                handler: saveIssuePermissions
            },{
                text: JSMessages.get("ext.button.close"),
                handler: hideIssuePermissionsDlg
            }],
            keys: [{
                key: 27,  // hide on Esc
                fn: this.hideDlg
            }],
            items : [{

                xtype: 'form',
                labelWidth: 75, // label settings here cascade unless overridden
                frame: true,
                width: 350,

                items: [{
                    xtype: 'panel',
                    bodyStyle: 'margin-bottom: 5px',
                    html: '<input type="radio" name="typeOfAccess" id="typeOfAccess1" value="1" onclick="typeOfAccessChanged2(1)"><span id="typeOfAccess1Text">' + JSMessages.get("ext.permissions.options.everyone") + '</span>' +
                          '<br>' +
                          '<input type="radio" name="typeOfAccess" id="typeOfAccess2" value="2" onclick="typeOfAccessChanged2(2)"><span id="typeOfAccess2Text">' + JSMessages.get("ext.permissions.options.justMe") + '</span>' +
                          '<br>' +
                          '<input type="radio" name="typeOfAccess" id="typeOfAccess3" value="3" onclick="typeOfAccessChanged2(3)"><span id="typeOfAccess3Text">' + JSMessages.get("ext.permissions.options.selectGroups") + '</span>' +
                          '<br>' +
                          '<div id="permissionsTableDivId" style="display:none;">' +
                          '<table border="0" cellspacing="0" cellpadding="0" width="100%" id="permissionsTableId">' +
                          '<tr class="boxhead">' +
                          '<TH align=left class="forumCategoryRowTD" nowrap>&nbsp;' + JSMessages.get("ext.permissions.name") + '</TH>' +
                          '<TH align=left class="forumCategoryRowTD" nowrap>&nbsp;' + JSMessages.get("ext.permissions.email") + '</TH>' +
                          '<TH align=center class="forumCategoryRowTD" nowrap width="60">' + JSMessages.get("ext.permissions.action") + '</TH>' +
                          '</tr>' +
                          '<tbody id="permissionTableBody"></tbody>' +
                          '</table>' +
                          '</div>' +
                          '<div id="permissionsButtons" style="display:none;">' +
                          '<br>' +
                          '<a href="#" onclick="addCurrentUserToPermissions();return false;" id="addCurrentUserToPermissionsId" style="margin-left: 2px;"><img src="images/icons/16x16/document_add.gif" border=0 align="absmiddle">&nbsp;' + JSMessages.get("ext.permissions.addMe") + '</a>' +
                          '&nbsp;' +
                          '<a href="#" onclick="addAnotherUserToPermissions(this);return false;" id="addAnotherUserToPermissionsId" style="margin-left: 2px;"><img src="images/icons/16x16/document_add.gif" border=0 align="absmiddle">&nbsp;' + JSMessages.get("ext.permissions.addAnotherUser") + '</a>' +
                          '&nbsp;' +
                          '<a href="#" onclick="addUserGroupToPermissions(this);return false;" id="addUserGroupToPermissionsId" style="margin-left: 2px;"><img src="images/icons/16x16/document_add.gif" border=0 align="absmiddle">&nbsp;' + JSMessages.get("ext.permissions.addAUserGroup") + '</a>' +
                          '</div>'
                }]
            }]
        });
    }

    editIssuePermissionDialog.show();

    document.getElementById("typeOfAccess1").checked = true;
    document.getElementById("typeOfAccess2").checked = false;
    document.getElementById("typeOfAccess3").checked = false;
    typeOfAccessChanged2(1);
    //groupAccessOptions.initGroupAccessOptions('');

}

function saveIssuePermissions(){
    var permissionType = 1;
    var permissionValue = "-";
    var permissionForUsers = "-";
    if (document.getElementById('typeOfAccess2').checked) {
        permissionType = 2;
    } else if (document.getElementById('typeOfAccess3').checked) {
        permissionType = 3;
        if (localPermissionValue.length > 0) {
            permissionValue = localPermissionValue; //groupAccessOptions.getInternalFormat();
        }
        if (localPermissionForUsers.length > 0) {
            permissionForUsers = localPermissionForUsers;
        }

    }
    setAttributeOnIssue("permission", permissionType + "#" + permissionValue + "#" + permissionForUsers, false, function(callbackResult){});
    editIssuePermissionDialog.hide();
};

function hideIssuePermissionsDlg() {
    editIssuePermissionDialog.hide();
}


function removeRowIncludingSubIssues(tblBody, pId) {
    var subtasksTR = getElementsByAttribute(tblBody, "class", 'pi_' + pId);
    if (subtasksTR && subtasksTR.length > 0) {
        for (var i=subtasksTR.length-1; i >= 0; i--) {
            removeRowForIssue(tblBody, subtasksTR[i].id.substring(subtasksTR[i].id.indexOf('_')+1) * 1);
            tblBody.removeChild(subtasksTR[i]);
        }
    }
    var existingTR = document.getElementById('tr_' + pId);
    if (!existingTR) {
        existingTR = document.getElementById('subtr_' + pId);
    }
    if(existingTR) {
        existingTR.parentNode.removeChild(existingTR);
    }
}

function issueDeletedCallback() {
    if (currentExtGridRecord != null) {
        currentExtGrid.getStore().remove(currentExtGridRecord);
    } else {
        var tblBody = document.getElementById("issueTableBody");
        var issueIds = currentContextMenuIssueId.split(",");
        for (var i=0; i < issueIds.length; i++) {
            removeRowIncludingSubIssues(tblBody, issueIds[i]);
        }
    }
}

function setAttributeOnIssue(operation, itemId, dashboardMode) {
    var level = 0;    
    if (elementExists(document.getElementById("BatchLevel_" + currentContextMenuIssueId))) {
        level = document.getElementById("BatchLevel_" + currentContextMenuIssueId).value;
    }
    ProjectIssueRemoteAction.setAttributeOnIssue(currentContextMenuIssueId, operation, itemId, level, dashboardMode, updateResult);
}

function updateResult(newTableRow) {


    if (!currentContextMenuIssueId || currentContextMenuIssueId.indexOf(",") < 0) {

        if (!newTableRow) return;

        var dashboardMode = newTableRow[0].indexOf("dashboardMode=1") >= 0;
        var issueLinksToUpdate = eval(newTableRow[0]);

        if (issueLinksToUpdate.length > 0) {            
            var updateAllActiveLinks = '<br><br><input type=checkbox id="_cbUpdateAllActiveLinks">&nbsp;' + JSMessages.get('ext.project.issues.links.updateChainedActiveReferences');
            Ext.Msg.confirm('Information', JSMessages.get("ext.project.issues.links.updateInfoDialogText") + updateAllActiveLinks, function(buttonId) {
                if (buttonId == 'yes') {
                    for(var i=0; i < issueLinksToUpdate.length; i++) {
                        var newValue = "updateReferencedActiveLinks:" + ((document.getElementById('_cbUpdateAllActiveLinks').checked) ? "true" : "false") + "|originIssueId:" + currentContextMenuIssueId + "|" + issueLinksToUpdate[i].value;
                        ProjectIssueRemoteAction.setAttributeOnIssue(issueLinksToUpdate[i].id, issueLinksToUpdate[i].attribute, newValue, 0, false, function(item) {
                            var issueId = item[1][1];
                            updateIssueRow(item[1], issueId, dashboardMode);
                        });
                    }
                }
            });
        }

        updateIssueRow(newTableRow[1], currentContextMenuIssueId, dashboardMode);

    } else {

        if (newTableRow) {
            var issueLinksToUpdate = eval(newTableRow[0]);
            if (issueLinksToUpdate.length > 0) {
                var updateAllActiveLinks = '<br><br><input type=checkbox id="_cbUpdateAllActiveLinks">&nbsp;' + JSMessages.get('ext.project.issues.links.updateChainedActiveReferences');
                Ext.Msg.confirm('Information', JSMessages.get("ext.project.issues.links.updateInfoDialogText") + updateAllActiveLinks, function(buttonId) {
                    if (buttonId == 'yes') {
                        for(var i=0; i < issueLinksToUpdate.length; i++) {
                            var newValue = "updateReferencedActiveLinks:" + ((document.getElementById('_cbUpdateAllActiveLinks').checked) ? "true" : "false") + "|originIssueId:" + issueLinksToUpdate[i].originIssueId + "|" + issueLinksToUpdate[i].value;
                            ProjectIssueRemoteAction.setAttributeOnIssue(issueLinksToUpdate[i].id, issueLinksToUpdate[i].attribute, newValue, 0, false, function(item) {                                
                                var issueId = item[1][1];
                                updateIssueRow(item[1], issueId, dashboardMode);
                            });
                        }
                    }
                });
            }
        }

        // Multiple issues
        var dashboardMode = false;
        var issueIds = currentContextMenuIssueId.split(",");
        for (var i=0; i < issueIds.length; i++) {
            ProjectIssueRemoteAction.getTableRowForIssue(issueIds[i], document.getElementById("BatchLevel_" + issueIds[i]).value, dashboardMode, updateTableRow);
        }
    }

    // Hide "update-link"
    try {
        if (elementExists(document.getElementById('updateSelectedIssuesLinkDiv'))) {
            document.getElementById('updateSelectedIssuesLinkDiv').style.display = 'none';
        }
        if (elementExists(document.getElementById('EnableDisableIssues'))) {
            document.getElementById("EnableDisableIssues").checked = false;
        }
    } catch(e) {}
}

function updateIssueRow(newTableRow, issueId, dashboardMode) {

    //newTableRow = newTableRow[1];

    try {
        var existingTRId = 'tr_' + issueId;
        var existingTR = document.getElementById(existingTRId);
        if (!existingTR) {
            existingTRId = 'subtr_' + issueId;
            existingTR = document.getElementById(existingTRId);
        }

        if (!elementExists(existingTR)) {
            if (currentExtGrid != null) {
                currentExtGrid.getStore().reload();
            }
            return;
        }

        //var dashboardMode = newTableRow[0].indexOf("dashboardMode=1") >= 0;

        if (dashboardMode) {
            for (var i = 2; i < newTableRow.length; i++) {
                var cell = existingTR.cells[i-2];
                cell.innerHTML = newTableRow[i];
            }
        } else {
            for (var i = 2; i < newTableRow.length; i++) {
                var cell = existingTR.cells[i-2];
                cell.innerHTML = newTableRow[i];
            }
        }

        /* Highlight every td in the row ... */
        Ext.each(Ext.query('td', existingTRId), function(elem){
            var linkElem = Ext.get(elem);
            linkElem.highlight("ffff9c", {
                attr: "background-color",
                easing: 'easeIn',
                duration: 2
            });
        });

    } catch(e) {
    }

    setUpContextMenuForLinks();


}

function updateTableRow(tableRow) {
    try {
        var existingTRId = 'tr_' + tableRow[1];
        var existingTR = document.getElementById(existingTRId);
        if (!existingTR) {
            existingTRId = 'subtr_' + tableRow[1];
            existingTR = document.getElementById(existingTRId);
        }

        for (var i = 2; i < tableRow.length; i++) {
            var cell = existingTR.cells[i-2];
            cell.innerHTML = tableRow[i];
        }

        /* Highlight every td in the row ... */
        Ext.each(Ext.query('td', existingTRId), function(elem){
            var linkElem = Ext.get(elem);
            linkElem.highlight("ffff9c", {
                attr: "background-color",
                easing: 'easeIn',
                duration: 2
            });
        });

    } catch(e) {
        alert(e);
    }

    setUpContextMenuForLinksIssuesTab();
}


function setUpKeyMaps(path, useParent) {
    var map = new Ext.KeyMap(document, [{
        key: Ext.EventObject.F5, fn: function(key, e){

        // First stop the event and then ask if the user would like to reload VP anyway
        e.preventDefault(); // for Firefox
        if (Ext.isIE){
            //cannot cancel F5 on IE so change to another key
            //that can be canceled (backspace in this case).
            e.browserEvent.keyCode = 8;
        }
        e.stopEvent();

        searchIssue(Ext.get('menuqsearch'), loadProjectIssue);

        /*
        Ext.Msg.confirm(' ', JSMessages.get("ext.f5.pressed"), function(buttonId) {
            if (buttonId == 'yes')
            {
                // Do reload...
                if (useParent) {
                    window.parent.document.location.href = path;
                } else {
                    document.location.href = path;
                }
            }
        });
        */
    }
    },{
        key: 119, fn: function(key, e){ // 114 = F8
        // First stop the event and then ask if the user would like to reload VP anyway
        e.preventDefault(); // for Firefox
        e.stopEvent();
        searchIssue(Ext.get('menuqsearch'), loadProjectIssue);
    }
    }]);
}

/**
 * Logger that is active when running on localhost,
 * otherwise nologging occurs, use as VPLog.error,
 * VPLog.info, VPLog.debug or VPLog.warn
 *
 * Firebug is used if FF is the browser otherwise
 * text is logged to the javaconsole (See "Tools"
 * --> "Sun Java Console")
 *
 */
var VPLogClass = function (basePath){
    //Public variables/methods, needed unless format return { methodA : function(){},methodA : function(){} } is used
    this.name = "VisionProject logger";
    this.info = info;
    this.warn = warn;
    this.error = error;
    this.debug = debug;
    var ielogger;
    var loggingdisabled;
    var loggerApplet;
    var okToLog = false;
    var forceJava = false;

    if(getCurrentFrameDocument().location.href.indexOf("localhost")>-1){
        okToLog = false;
        if(forceJava == true && (typeof console == "undefined" || typeof console == undefined || console == undefined || console == null)){
            printLoggerApplet(basePath);
        }
    } else {
        okToLog = false;
    }

    function info(mess){
        if(!okToLog){
            return;
        }
        //Firebug needed
        try{
            if(forceJava == true || typeof console == "undefined" || typeof console == undefined || console == undefined || console == null){
                if(typeof loggerApplet != "undefined" && loggerApplet != undefined && loggerApplet != null) {
                    loggerApplet.log("INF: " + getTime() + ': ' + getFunctionName(arguments.callee.caller) + ': ' + mess);
                } else {
                    loggerApplet = getCurrentFrameDocument().applets["UtilApplet"];
                    if(typeof loggerApplet != "undefined" && loggerApplet != undefined && loggerApplet != null) {
                        loggerApplet.log("INF: " + getTime() + ': ' + getFunctionName(arguments.callee.caller) + ': ' + mess);
                    } else {
                        //alert(' ', "Could not log in ie, UtilAppletNot available!");
                    }
                }
            }  else{
                console.info(getTime() + ': ' + getFunctionName(arguments.callee.caller) + ': ' + mess);
            }
        } catch(ex){
            alert('Exception in ' + getFunctionName(arguments.callee) + ' : '  + ex.message);
        }
    }

    function warn(mess){

        if(!okToLog){
            return;
        }
        try{
            if(forceJava == true  || typeof console == "undefined" || typeof console == undefined || console == undefined || console == null){
                if(typeof loggerApplet != "undefined" && loggerApplet != undefined && loggerApplet != null) {
                    loggerApplet.log("WRN: " + getTime() + ': ' + getFunctionName(arguments.callee.caller)+ ': ' + mess);
                } else {
                    loggerApplet = getApplet("UtilApplet");
                    if(typeof loggerApplet != "undefined" && loggerApplet != undefined && loggerApplet != null) {
                        loggerApplet.log("WRN: " + getTime() + ': ' + getFunctionName(arguments.callee.caller)+ ': ' + mess);
                    } else {
                        //alert(' ', "Could not log in ie, UtilAppletNot available!");
                    }
                }
            }  else{
                console.warn(getTime() + ': ' + getFunctionName(arguments.callee.caller) + ': ' + mess);
            }
        } catch(ex){
            alert('Exception in ' + getFunctionName(arguments.callee) + ' : '  + ex.message);
        }
    }

    function error(mess){

        if(!okToLog){
            return;
        }

        try{
            if(forceJava == true  || typeof console == "undefined" || typeof console == undefined || console == undefined || console == null){
                if(typeof loggerApplet != "undefined" && loggerApplet != undefined && loggerApplet != null) {
                    loggerApplet.log("ERR: " + getTime() + ': ' + getFunctionName(arguments.callee.caller) + ': ' + mess);
                } else {
                    loggerApplet = getApplet("UtilApplet");
                    if(typeof loggerApplet != "undefined" && loggerApplet != undefined && loggerApplet != null) {
                        loggerApplet.log("ERR: " + getTime() + ': '  + getFunctionName(arguments.callee.caller)+ ': ' + mess);
                    } else {
                        //alert(' ', "Could not log in ie, UtilAppletNot available!");
                    }
                }
            }  else{
                console.error(getTime() + ': ' + getFunctionName(arguments.callee.caller) + ': ' + mess);
            }
        } catch(ex){
            alert('Exception in ' + getFunctionName(arguments.callee) + ' : '  + ex.message);
        }
    }

    function debug(mess){
        if(!okToLog){
            return;
        }

        try {
            if(forceJava == true  || typeof console == "undefined" || typeof console == undefined || console == undefined || console == null){
                if(typeof loggerApplet != "undefined" && loggerApplet != undefined && loggerApplet != null) {
                    loggerApplet.log("DBUG: " + getTime() + ': ' + getFunctionName(arguments.callee.caller)+ ': ' +mess);
                }else {
                    loggerApplet = getApplet("UtilApplet");
                    if(typeof loggerApplet != "undefined" && loggerApplet != undefined && loggerApplet != null) {
                        loggerApplet.log("DBUG: " + getTime() + ': ' + getFunctionName(arguments.callee.caller)+ ': '+ mess);
                    } else {
                        //alert(' ', "Could not log in ie, UtilAppletNot available!");
                    }
                }
            }  else{
                console.debug(getTime() + ': '  + getFunctionName(arguments.callee.caller)+ ': ' + mess);
            }
        }catch(e){
            alert("warn : " + e.message );
        }
    }


    function getFunctionName(theFunction)
    {
        try {
            if(typeof theFunction != "undefined" && typeof theFunction != undefined && theFunction != null){
                // mozilla makes it easy. I love mozilla.
                if(theFunction.name)
                {
                    return theFunction.name;
                }

                // try to parse the function name from the defintion
                var definition = theFunction.toString();
                var name = definition.substring(definition.indexOf('function') + 8,definition.indexOf('('));
                if(typeof name != "undefined" && typeof name != undefined && name != null){
                    return name;
                }
            }
        } catch (ex){
            alert('Exception in ' + getFunctionName(arguments.callee) + ' : '  + ex.message);
        }
        // sometimes there won't be a function name
        // like for dynamic functions
        return "anonymous";
    }

    //Print to appletContainer div
    function printLoggerApplet(basePath){
        try{
            //if(typeof console == "undefined" || typeof console == undefined || console == undefined || console == null){
            var appletContainer = getCurrentFrameDocument().getElementById("appletContainer");

            if(typeof appletContainer != "undefined" && appletContainer != undefined && appletContainer != null){

                for (i=0; i<appletContainer.childNodes.length; i++){

                    var appletArr = appletContainer.childNodes;
                    if(appletArr != null && appletArr != undefined && appletArr.length>0){
                        for(i = 0; i < appletArr.length;i++ ){
                            //alert('' + appletArr[i].name + ' '+ appletArr[i].nodeName + ' ' + appletArr[i].attributes);
                            //alert('' + appletArr[i].name);

                            if(appletArr[i].attributes != undefined && appletArr[i].attributes != null && appletArr[i].attributes.length > 0){
                                if(appletArr[i].attributes.getNamedItem("Id")== "UtilAppletDiv")
                                    if(appletArr[i].childNodes[0].attributes.getNamedItem("Name").value  == "UtilApplet"){
                                        return;
                                    }
                            }
                        }
                    }
                }
            } else {
                appletContainer = getCurrentFrameDocument().createElement('div');
                appletContainer.setAttribute("id","appletContainer");
                appletContainer.style.visibility = 'hidden';
                //appletContainer.style.display='none';
                getCurrentFrameDocument().body.appendChild(appletContainer);
            }

            if(getApplet("UtilApplet")==null){
                /*deployJava.runApplet({codebase:"http://www.example.com/applets/", code:"se.visionera.visionproject.web.screenshotapplet.UtilApplet",
                 MAYSCRIPT:"MAYSCRIPT", width:"1", Height:"1"}, {name:"UtilApplet", cache_archive_ex:"screenshot.jar;preload;1.2.1.3", code:"se.visionera.visionproject.web.screenshotapplet.UtilApplet", codebase:"applet"}, "1.6");*/
                var appletString = '<APPLET CODEBASE="' + basePath + 'applet/" Name="UtilApplet" CODE="se.visionera.visionproject.web.screenshotapplet.UtilApplet" width="1" height="1" MAYSCRIPT="MAYSCRIPT" >' +
                                   + '<PARAM NAME = "CODE" VALUE="se.visionera.visionproject.web.screenshotapplet.UtilApplet" >'
                        + '<PARAM NAME = "cache_archive" VALUE="screenshot.jar">'
                        + '<PARAM NAME = "cache_archive_ex" VALUE="screenshot.jar;preload;1.2.3.9">'
                        + '<PARAM NAME = "type" value="application/x-java-applet;version=1.5">'
                        + '<PARAM NAME = "CODE" VALUE="se.visionera.visionproject.web.screenshotapplet.UtilApplet" >'
                        + '<PARAM NAME = "Name" VALUE="UtilApplet">'
                        + '<PARAM NAME = "CODEBASE" VALUE = "' + basePath + 'applet/" >'
                        + '<PARAM NAME = "java_type" VALUE="application/x-java-applet">'
                        + '</APPLET>';
                var dv = top.document.createElement('div');
                dv.setAttribute("id","UtilAppletDiv");
                dv.setAttribute("class", "x-hidden")
                dv.innerHTML = appletString;
                appletContainer.appendChild(dv);
            }
        } catch(ex){
            alert('Exception in ' + getFunctionName(arguments.callee) + ' : '  + ex.message);
        }
    }
}


/* Check if popups are blocked !! */
function popupsBlocked() {
    try {
        var myTest = window.open("about:blank","","directories=no,height=1,width=1,menubar=no,resizable=no,scrollbars=no,status=no,titlebar=no,top=0,location=no");
        if (!myTest) {
            //alert("A popup blocker was detected.");
            return true;
        } else {
            myTest.close();
            //alert("No popup blocker was detected.");
            return false;
        }
    }catch(ex){
        alert('Exception in ' + getFunctionName(arguments.callee) + ' : '  + ex.message);
    }
    return true;
}

function loadJavascriptInBackground(jfFilePath, callbackMethod){
    try{
        var arr = getCurrentFrameDocument().getElementsByTagName("script")[0].all;

        for(var i = 0; arr.length; i++){
            var obj = arr[i];
            //alert(obj.getAttribute("src"));
            if(obj.getAttribute("src")==jfFilePath){
                //alert(found);
                return;
            }
        }

        if(true){
            //document.write('<script src="http://localhost:8080/visionproject/js/deployJava.js" type="text/JavaScript"><\/script>');
            //Create a 'script' element
            var scrptE = getCurrentFrameDocument().createElement("script");
            // Set it's 'type' attribute
            scrptE.setAttribute("type", "text/javascript");
            // Set it's 'language' attribute
            scrptE.setAttribute("language", "JavaScript");
            // Set it's 'src' attribute
            scrptE.setAttribute("src", jfFilePath);
            // most browsers
            scrptE.onload = callbackMethod;

            // IE 6 & 7
            scrptE.onreadystatechange = function() {
                if (this.readyState == 'complete') {
                    callbackMethod();
                }
            }
            // Now add this new element to the head tag
            getCurrentFrameDocument().getElementsByTagName("head")[0].appendChild(scrptE);
            getCurrentFrameDocument().body.appendChild(scrptE);
        }
    }catch(ex){
        alert('Exception in ' + getFunctionName(arguments.callee) + ' : '  + ex.message);
    }
}

function getTime(){
    try{
        var curDateTime = new Date()
        var curHour = curDateTime.getHours()
        var curMin = curDateTime.getMinutes()
        var curSec = curDateTime.getSeconds()
        var curTime =
                ((curHour < 10) ? "0" : "") + curHour + ":"
                        + ((curMin < 10) ? "0" : "") + curMin + ":"
                        + ((curSec < 10) ? "0" : "") + curSec;
    }catch(ex){
        alert('Exception in ' + getFunctionName(arguments.callee) + ' : '  + ex.message);
    }

    return curTime;
}

//Get already created applet
function getApplet(theName){
    try{
        var arr = getCurrentFrameDocument().applets;

        if(typeof arr != "undefined" && arr.length>0){
            for(i = 0; i<arr.length; i++){
                if(typeof arr[i]  != "undefined" && arr[i].getAttribute('name')==theName){
                    return arr[i];
                }
            }
        } else {
            arr = getCurrentFrameDocument().applets;
            if(typeof arr != "undefined" && arr.length>0){
                for(i = 0; i<arr.length; i++){
                    if(typeof arr[i]  != "undefined" && arr[i].getAttribute('name')==theName){
                        return arr[i];
                    }
                }
            }
        }
    }catch(ex){
        alert('Exception in ' + getFunctionName(arguments.callee) + ' : '  + ex.message);
    }

    return null;
}

//Get the current document, nomatter if it's in an IFrame or regular document it's safe
function getCurrentFrameDocument(){
    try{
        if (self != top){
            if (frameElement.contentDocument) { // DOM
                return frameElement.contentDocument;
            } else if ( frameElement.contentWindow ) { // IE win
                return frameElement.contentWindow.document;
            }
        } else {
            return document;
        }
    }catch(ex){
        return document;
    }
}

function getDocumentWidth() {
    var myWidth = 0, myHeight = 0;
     if(  getCurrentFrameDocument().documentElement && ( getCurrentFrameDocument().documentElement.clientWidth || getCurrentFrameDocument().documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth =  getCurrentFrameDocument().documentElement.clientWidth;
    } else if(  getCurrentFrameDocument().body && (  getCurrentFrameDocument().body.clientWidth ||  getCurrentFrameDocument().body.clientHeight ) ) {
        //IE 4 compatible
        myWidth =  getCurrentFrameDocument().body.clientWidth;
    } else if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myWidth = window.innerWidth;
    }
    return myWidth

}

function getDocumentScrollingVerticalCenter(){
    var yOffset = getCurrentFrameDocument().body.scrollTop || getCurrentFrameDocument().documentElement.scrollTop || window.pageYOffset;

    return yOffset;
}

function getDocumentHeight() {
    var myHeight = 0;

    if(getCurrentFrameDocument().documentElement.scrollHeight){
        myHeight =  getCurrentFrameDocument().documentElement.scrollHeight;
    } else if(  getCurrentFrameDocument().documentElement && (  getCurrentFrameDocument().documentElement.clientWidth ||  getCurrentFrameDocument().documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myHeight =  getCurrentFrameDocument().documentElement.clientHeight;
    } else if( document.body && (  getCurrentFrameDocument().body.clientWidth ||  getCurrentFrameDocument().body.clientHeight ) ) {
        //IE 4 compatible
        myHeight =  getCurrentFrameDocument().body.clientHeight;
    } else if( typeof( window.innerHeight) == 'number' ) {
        //Non-IE
        myHeight = window.innerHeight;
    }
    return myHeight;
}







//Quick Method to create a Ext.Window
function createExtWinWithButtons(width, height, applyTo, specifiedButtons, items){
    var theFunct = function(){
        var dialogImpl; //actual object
        var editDialogLoadMask; //actual object
        this.theWidth;
        this.theHeight;
        this.theApplyTo;

        this.theButtons = specifiedButtons;
        this.theItems = items;

        //DEFINE PUBLIC INTERFACE
        return {
            init : function(){ //METHOD
            },
            showDialog : function(){//METHOD
                if(!dialogImpl){ // lazy initialize the dialog and only create it once
                    //var htmlElement = Ext.DomHelper.append(document.body,{id : 'issueFieldGroupingDlg'}, true);
                    dialogImpl = new Ext.Window(
                    {
                        applyTo: this.theApplyTo,
                        width: this.theWidth,
                        height: this.theHeight,
                        shadow: true,
                        minWidth: 200,
                        minHeight: 200,
                        modal: true,
                        constrain: false,
                        resizable : true,
                        closeAction: 'hide',
                        shim:false,
                        bodyStyle:'padding:5px;',
                        buttonAlign:'center',
                        plain:true,
                        buttons: theButtons,
                        items:theItems,
                        keys: [{
                            key: 27,  // hide on Esc
                            fn: function(){
                                dialogImpl.hide();
                            }
                        }]
                    });
                }
                dialogImpl.x = getDocumentWidth()/2 - dialogImpl.width/2;
                dialogImpl.y = getDocumentHeight()/2 - dialogImpl.height/2;;
                dialogImpl.show();
            },
            //METHOD
            showLoadingMessage: function(){
                editDialogLoadMask = new Ext.LoadMask(dialogImpl.getEl(),{msg: JSMessages.get('ext.loading')});
                editDialogLoadMask.show();
            },
            //METHOD
            hideLoadingMessage: function(){
                if(editDialogLoadMask == null || editDialogLoadMask == "undefined"){
                editDialogLoadMask = new Ext.LoadMask(dialogImpl.getEl(),{msg: JSMessages.get('ext.loading')});
                }
                editDialogLoadMask.hide();
            },
            //METHOD
            hide: function(){
                dialogImpl.hide();
            },
            //METHOD
            show: function(){
                dialogImpl.show();
            },
            //METHOD
            setTitle: function(title){
                dialogImpl.setTitle(title);
            },
            alignTo : function(elementId, position) {
                dialogImpl.alignTo(elementId, position);
            }
        };
    }();

    theFunct.theWidth = width;
    theFunct.theHeight = height;
    theFunct.theApplyTo = applyTo

    //theFunct.additionalButtons = additionalButtons;
    return theFunct;
}

//Quick Method to create a Ext.Window
function createExtWin(width, height, applyTo, additionalButtons, closeCallBackFunction){
    var theWin;
    var theCallback = closeCallBackFunction;
    var extButtons =  [{ text: JSMessages.get('ext.button.close'),
        handler: function(){
            theWin.hide();
            if( theCallback != null){
                theCallback();
            }
        }
    }] ;
    extButtons = additionalButtons.concat(extButtons);

    theWin = createExtWinWithButtons(width, height, applyTo, extButtons);
    return theWin;
}

function createExtWinWithItems(width, height, additionalButtons, closeCallBackFunction, itemsToAddToWindow){
    var theWin;
    var theCallback = closeCallBackFunction;
    var extButtons =  [{ text: JSMessages.get('ext.button.close'),
        handler: function(){
            theWin.hide();
            if( theCallback != null){
                theCallback();
            }
        }
    }] ;
    extButtons = additionalButtons.concat(extButtons);

    theWin = createExtWinWithButtons(width, height, null, extButtons, itemsToAddToWindow);
    return theWin;

}

function handleBlurOnEstimatedTime(estimateTimeField) {
    if(document.getElementById('remainingTime') && (document.getElementById('remainingTime').value == '' || document.getElementById('remainingTime').value == '0.0')) {
        document.getElementById('remainingTime').value = estimateTimeField.value;
    }
}


//MINOR FIX FOR TABLE HEADER LEFT/RIGHT BORDER (IssuesTable, reports etc)
function    fixTableHeaderLeftRightBorder(rowIdToFix){
    var tableRow = document.getElementById(rowIdToFix);
    if (tableRow) {
        try {
            var tableCells = tableRow.getElementsByTagName('th');
            if(!tableCells){
                tableCells = tableRow.getElementsByTagName('td');
            }

            if (tableCells && tableCells.length > 0) {
                tableCells[0].style.className += " borderLeft";
                tableCells[tableCells.length - 1].style.className += " borderRight";

            }
        } catch(ex) {
            alert(ex.message);
        }
    }
}


//To show loading indicator
var loadingMessage = function(){
    var myMask;
    return {
        show : function(div){
            if(div == "undefined"){
                // Basic mask:
                myMask = new Ext.LoadMask(Ext.getBody() /* Ext.getDom("pageWrapperDiv")*/, {msg: JSMessages.get('ext.pleaseWait')});
            } else {
                myMask = new Ext.LoadMask(Ext.getDom(div), {msg: JSMessages.get('ext.pleaseWait')});
            }
            myMask.show();
        }
        ,
        hide: function(){
            if(myMask == null || myMask == "undefined"){
                myMask = new Ext.LoadMask(Ext.getBody(), {msg: JSMessages.get('ext.pleaseWait')});
            }
            myMask.hide();
        }
    }
}();



/************************************  EXT EXTENSION ******************************************'/
// vim: ts=4:sw=4:nu:fdc=4:nospell
/**
 * RowActions plugin for Ext grid
 *
 * Contains renderer for icons and fires events when an icon is clicked
 *
 * @author    Ing. Jozef Sakáloš
 * @date      22. March 2008
 * @version   $Id: Ext.ux.grid.RowActions.js 150 2008-04-08 21:50:58Z jozo $
 *
 * @license Ext.ux.grid.RowActions is licensed under the terms of
 * the Open Source LGPL 3.0 license.  Commercial use is permitted to the extent
 * that the code/component(s) do NOT become part of another Open Source or Commercially
 * licensed development library or toolkit without explicit permission.
 *
 * License details: http://www.gnu.org/licenses/lgpl.html
 */

/*global Ext */

Ext.ns('Ext.ux.grid');

/**
 * @class Ext.ux.grid.RowActions
 * @extends Ext.util.Observable
 *
 * CSS rules from Ext.ux.RowActions.css are mandatory
 *
 * Important general information: Actions are identified by iconCls. Wherever an <i>action</i>
 * is referenced (event argument, callback argument), the iconCls of clicked icon is used.
 * In another words, action identifier === iconCls.
 *
 * Creates new RowActions plugin
 * @constructor
 * @param {Object} config The config object
 */
Ext.ux.grid.RowActions = function(config) {
	Ext.apply(this, config);

	// {{{
	this.addEvents(
		/**
		 * @event beforeaction
		 * Fires before action event. Return false to cancel the subsequent action event.
		 * @param {Ext.grid.GridPanel} grid
		 * @param {Ext.data.Record} record Record corresponding to row clicked
		 * @param {String} action Identifies the action icon clicked. Equals to icon css class name.
		 * @param {Integer} rowIndex Index of clicked grid row
		 * @param {Integer} colIndex Index of clicked grid column that contains all action icons
		 */
		 'beforeaction'
		/**
		 * @event action
		 * Fires when icon is clicked
		 * @param {Ext.grid.GridPanel} grid
		 * @param {Ext.data.Record} record Record corresponding to row clicked
		 * @param {String} action Identifies the action icon clicked. Equals to icon css class name.
		 * @param {Integer} rowIndex Index of clicked grid row
		 * @param {Integer} colIndex Index of clicked grid column that contains all action icons
		 */
		,'action'
		/**
		 * @event beforegroupaction
		 * Fires before group action event. Return false to cancel the subsequent groupaction event.
		 * @param {Ext.grid.GridPanel} grid
		 * @param {Array} records Array of records in this group
		 * @param {String} action Identifies the action icon clicked. Equals to icon css class name.
		 * @param {String} groupId Identifies the group clicked
		 */
		,'beforegroupaction'
		/**
		 * @event groupaction
		 * Fires when icon in a group header is clicked
		 * @param {Ext.grid.GridPanel} grid
		 * @param {Array} records Array of records in this group
		 * @param {String} action Identifies the action icon clicked. Equals to icon css class name.
		 * @param {String} groupId Identifies the group clicked
		 */
		,'groupaction'
	);
	// }}}

	// call parent
	Ext.ux.grid.RowActions.superclass.constructor.call(this);
};

Ext.extend(Ext.ux.grid.RowActions, Ext.util.Observable, {

	// configuration options
	// {{{
	/**
	 * @cfg {Array} actions Mandatory. Array of action configuration objects. The following
	 * configuration options of action are recognized:
	 *
	 * - @cfg {Function} callback Optional. Function to call if the action icon is clicked.
	 *   This function is called with same signature as action event and in its original scope.
	 *   If you need to call it in different scope or with another signature use
	 *   createCallback or createDelegate functions. Works for statically defined actions. Use
	 *   callbacks configuration options for store bound actions.
	 *
	 * - @cfg {Function} cb Shortcut for callback.
	 *
	 * - @cfg {String} iconIndex Optional, however either iconIndex or iconCls must be
	 *   configured. Field name of the field of the grid store record that contains
	 *   css class of the icon to show. If configured, shown icons can vary depending
	 *   of the value of this field.
	 *
	 * - @cfg {String} iconCls. css class of the icon to show. It is ignored if iconIndex is
	 *   configured. Use this if you want static icons that are not base on the values in the record.
	 *
	 * - @cfg {Boolean} hide Optional. True to hide this action while still have a space in
	 *   the grid column allocated to it. IMO, it doesn't make too much sense, use hideIndex instead.
	 *
	 * - @cfg (string} hideIndex Optional. Field name of the field of the grid store record that
	 *   contains hide flag (falsie [null, '', 0, false, undefined] to show, anything else to hide).
	 *
	 * - @cfg {String} qtipIndex Optional. Field name of the field of the grid store record that
	 *   contains tooltip text. If configured, the tooltip texts are taken from the store.
	 *
	 * - @cfg {String} tooltip Optional. Tooltip text to use as icon tooltip. It is ignored if
	 *   qtipIndex is configured. Use this if you want static tooltips that are not taken from the store.
	 *
	 * - @cfg {String} qtip Synonym for tooltip
	 *
	 * - @cfg {String} textIndex Optional. Field name of the field of the grids store record
	 *   that contains text to display on the right side of the icon. If configured, the text
	 *   shown is taken from record.
	 *
	 * - @cfg {String} text Optional. Text to display on the right side of the icon. Use this
	 *   if you want static text that are not taken from record. Ignored if textIndex is set.
	 *
	 * - @cfg {String} style Optional. Style to apply to action icon container.
	 */

	/**
	 * @cfg {String} actionEvnet Event to trigger actions, e.g. click, dblclick, mouseover (defaults to 'click')
	 */
	 actionEvent:'click'

	/**
	 * @cfg {Boolean} autoWidth true to calculate field width for iconic actions only.
	 */
	,autoWidth:true

	/**
	 * @cfg {Array} groupActions Array of action to use for group headers of grouping grids.
	 * These actions support static icons, texts and tooltips same way as actions. There is one
	 * more action config recognized:
	 * - @cfg {String} align Set it to 'left' to place action icon next to the group header text.
	 *   (defaults to undefined = icons are placed at the right side of the group header.
	 */

	/**
	 * @cfg {Object} callbacks iconCls keyed object that contains callback functions. For example:
	 * callbacks:{
	 *      'icon-open':function(...) {...}
	 *     ,'icon-save':function(...) {...}
	 * }
	 */

	/**
	 * @cfg {String} header Actions column header
	 */
	,header:''

	/**
	 * @cfg {Boolean} menuDisabled No sense to display header menu for this column
	 */
	,menuDisabled:true

	/**
	 * @cfg {Boolean} sortable Usually it has no sense to sort by this column
	 */
	,sortable:false

	/**
	 * @cfg {String} tplGroup Template for group actions
	 * @private
	 */
	,tplGroup:
		 '<tpl for="actions">'
		+'<div class="ux-grow-action-item<tpl if="\'right\'===align"> ux-action-right</tpl> '
		+'{cls}" style="{style}" qtip="{qtip}">{text}</div>'
		+'</tpl>'

	/**
	 * @cfg {String} tplRow Template for row actions
	 * @private
	 */
	,tplRow:
		 '<div class="ux-row-action">'
		+'<tpl for="actions">'
		+'<div class="ux-row-action-item {cls} <tpl if="text">'
		+'ux-row-action-text</tpl>" style="{hide}{style}" qtip="{qtip}">'
		+'<tpl if="text"><span qtip="{qtip}">{text}</span></tpl></div>'
		+'</tpl>'
		+'</div>'

	/**
	 * @private {Number} widthIntercept constant used for auto-width calculation
	 */
	,widthIntercept:4

	/**
	 * @private {Number} widthSlope constant used for auto-width calculation
	 */
	,widthSlope:21
	// }}}

	// methods
	// {{{
	/**
	 * Init function
	 * @param {Ext.grid.GridPanel} grid Grid this plugin is in
	 */
	,init:function(grid) {
		this.grid = grid;

		// {{{
		// setup template
		if(!this.tpl) {
			this.tpl = this.processActions(this.actions);

		} // eo template setup
		// }}}

		// calculate width
		if(this.autoWidth) {
			this.width =  this.widthSlope * this.actions.length + this.widthIntercept;
			this.fixed = true;
		}

		// body click handler
		var view = grid.getView();
		var cfg = {scope:this};
		cfg[this.actionEvent] = this.onClick;
		grid.on({
			render:{scope:this, fn:function() {
				view.mainBody.on(cfg);
			}}
		});

		// setup renderer
		if(!this.renderer) {
			this.renderer = function(value, cell, record, row, col, store) {
				cell.css += (cell.css ? ' ' : '') + 'ux-row-action-cell';
				return this.tpl.apply(this.getData(value, cell, record, row, col, store));
			}.createDelegate(this);
		}

		// actions in grouping grids support
		if(view.groupTextTpl && this.groupActions) {
			view.interceptMouse = view.interceptMouse.createInterceptor(function(e) {
				if(e.getTarget('.ux-grow-action-item')) {
					return false;
				}
			});
			view.groupTextTpl =
				 '<div class="ux-grow-action-text">' + view.groupTextTpl +'</div>'
				+this.processActions(this.groupActions, this.tplGroup).apply()
			;
		}

	} // eo function init
	// }}}
	// {{{
	/**
	 * Returns data to apply to template. Override this if needed.
	 * @param {Mixed} value
	 * @param {Object} cell object to set some attributes of the grid cell
	 * @param {Ext.data.Record} record from which the data is extracted
	 * @param {Number} row row index
	 * @param {Number} col col index
	 * @param {Ext.data.Store} store object from which the record is extracted
	 * @returns {Object} data to apply to template
	 */
	,getData:function(value, cell, record, row, col, store) {
		return record.data || {};
	} // eo function getData
	// }}}
	// {{{
	/**
	 * Processes actions configs and returns template.
	 * @param {Array} actions
	 * @param {String} template Optional. Template to use for one action item.
	 * @return {String}
	 * @private
	 */
	,processActions:function(actions, template) {
		var acts = [];

		// actions loop
		Ext.each(actions, function(a, i) {
			// save callback
			if(a.iconCls && 'function' === typeof (a.callback || a.cb)) {
				this.callbacks = this.callbacks || {};
				this.callbacks[a.iconCls] = a.callback || a.cb;
			}

			// data for intermediate template
			var o = {
				 cls:a.iconIndex ? '{' + a.iconIndex + '}' : (a.iconCls ? a.iconCls : '')
				,qtip:a.qtipIndex ? '{' + a.qtipIndex + '}' : (a.tooltip || a.qtip ? a.tooltip || a.qtip : '')
				,text:a.textIndex ? '{' + a.textIndex + '}' : (a.text ? a.text : '')
				,hide:a.hideIndex ? '<tpl if="' + a.hideIndex + '">visibility:hidden;</tpl>' : (a.hide ? 'visibility:hidden;' : '')
				,align:a.align || 'right'
				,style:a.style ? a.style : ''
			};
			acts.push(o);

		}, this); // eo actions loop

		var xt = new Ext.XTemplate(template || this.tplRow);
		return new Ext.XTemplate(xt.apply({actions:acts}));

	} // eo function processActions
	// }}}
	// {{{
	/**
	 * Grid body actionEvent event handler
	 * @private
	 */
	,onClick:function(e, target) {

		var view = this.grid.getView();
		var action = false;

		// handle row action click
		var row = e.getTarget('.x-grid3-row');
		var col = view.findCellIndex(target.parentNode.parentNode);

		var t = e.getTarget('.ux-row-action-item');
		if(t) {
			action = t.className.replace(/ux-row-action-item /, '');
			if(action) {
				action = action.replace(/ ux-row-action-text/, '');
				action = action.trim();
			}
		}
		if(false !== row && false !== col && false !== action) {
			var record = this.grid.store.getAt(row.rowIndex);

			// call callback if any
			if(this.callbacks && 'function' === typeof this.callbacks[action]) {
				this.callbacks[action](this.grid, record, action, row.rowIndex, col);
			}

			// fire events
			if(true !== this.eventsSuspended && false === this.fireEvent('beforeaction', this.grid, record, action, row.rowIndex, col)) {
				return;
			}
			else if(true !== this.eventsSuspended) {
				this.fireEvent('action', this.grid, record, action, row.rowIndex, col);
			}

		}

		// handle group action click
		t = e.getTarget('.ux-grow-action-item');
		if(t) {
			// get groupId
			var group = view.findGroup(target);
			var groupId = group ? group.id.replace(/ext-gen[0-9]+-gp-/, '') : null;

			// get matching records
			var records;
			if(groupId) {
				var re = new RegExp(groupId);
				records = this.grid.store.queryBy(function(r) {
					return r._groupId.match(re);
				});
				records = records ? records.items : [];
			}
			action = t.className.replace(/ux-grow-action-item (ux-action-right )*/, '');

			// call callback if any
			if('function' === typeof this.callbacks[action]) {
				this.callbacks[action](this.grid, records, action, groupId);
			}

			// fire events
			if(true !== this.eventsSuspended && false === this.fireEvent('beforegroupaction', this.grid, records, action, groupId)) {
				return false;
			}
			this.fireEvent('groupaction', this.grid, records, action, groupId);
		}
	} // eo function onClick
	// }}}

});

// registre xtype
Ext.reg('rowactions', Ext.ux.grid.RowActions);

/************************************** Ext.ux.grid.RowActions END **************************************/


function hideTableRow(divId){
    hideShowTableRow(true, divId);
}
function showTableRow(divId){
    hideShowTableRow(false, divId);
}
function hideTableCell(divId){
    hideShowTableCell(true, divId);
}
function showTableCell(divId){
    hideShowTableCell(false, divId);
}

//Hide/show table row
function hideShowTableRow(visibleBoolean, divId){

    if(visibleBoolean){
        document.getElementById(divId).style.display = 'none';
    } else{
        if(navigator.appName.indexOf("Microsoft") > -1){
            document.getElementById(divId).style.display = 'block';
        } else {
            document.getElementById(divId).style.display = 'table-row';
        }
    }
}
//Hide/show table cell
function hideShowTableCell(visibleBoolean, divId){

    if(visibleBoolean   ){
        document.getElementById(divId).style.display = 'none';
    } else{
        if(navigator.appName.indexOf("Microsoft") > -1){
            document.getElementById(divId).style.display = 'block';
        } else {
            document.getElementById(divId).style.display = 'table-cell';
        }
    }
}


/*
 * Customised from SearchField by Martin 2008-02-27
 *(both trigger fields always active)
 */

Ext.app.UserSearchField = Ext.extend(Ext.form.TwinTriggerField, {
    initComponent : function(){
        Ext.app.UserSearchField.superclass.initComponent.call(this);
        this.on('specialkey', function(f, e){
            if(e.getKey() == e.ENTER){
                this.onTrigger2Click();
            }
        }, this);
    },

    validationEvent:false,
    validateOnBlur:false,
    trigger1Class:'x-form-clear-trigger',
    trigger2Class:'x-form-search-trigger',
    //hideTrigger1:true,
    width:180,
    //hasSearch : false,
    hasSearch : true,
    paramName:'nameSearchTerm',
	//paramName : 'query',

    onTrigger1Click : function(){
        if(this.hasSearch){
            this.el.dom.value = '';
            var o = {start: 0, limit:20};
            this.store.baseParams = this.store.baseParams || {};
            this.store.baseParams[this.paramName] = '';
            this.store.reload({params:o});
            //this.triggers[0].hide();
            this.hasSearch = false;
        }
    },

    onTrigger2Click : function(){
        var v = this.getRawValue();
        if(v.length < 1){
            this.onTrigger1Click();
            return;
        }
        var o = {start: 0, limit:20};
        this.store.baseParams = this.store.baseParams || {};
        this.store.baseParams[this.paramName] = v;
        this.store.reload({params:o});
        this.hasSearch = true;
        //this.triggers[0].show();
    }
});


/*
 * Ext JS Library 2.0.2
 * Copyright(c) 2006-2008, Ext JS, LLC.
 * licensing@extjs.com
 *
 * http://extjs.com/license
 */
/*
Ext.ux.Portal = Ext.extend(Ext.Panel, {
    layout: 'column',
    autoScroll:true,
    cls:'x-portal',
    defaultType: 'portalcolumn',

    initComponent : function(){
        Ext.ux.Portal.superclass.initComponent.call(this);
        this.addEvents({
            validatedrop:true,
            beforedragover:true,
            dragover:true,
            beforedrop:true,
            drop:true
        });
    },

    initEvents : function(){
        Ext.ux.Portal.superclass.initEvents.call(this);
        this.dd = new Ext.ux.Portal.DropZone(this, this.dropConfig);
    },

    addPortlet : function(columnIndex, portletConfig) {
        var p=new Ext.ux.Portlet(portletConfig);
        var col=this.items.itemAt(columnIndex);
        col.add(p);
    }



});
Ext.reg('portal', Ext.ux.Portal);


Ext.ux.Portal.DropZone = function(portal, cfg){
    this.portal = portal;
    Ext.dd.ScrollManager.register(portal.body);
    Ext.ux.Portal.DropZone.superclass.constructor.call(this, portal.bwrap.dom, cfg);
    portal.body.ddScrollConfig = this.ddScrollConfig;
};

Ext.extend(Ext.ux.Portal.DropZone, Ext.dd.DropTarget, {
    ddScrollConfig : {
        vthresh: 50,
        hthresh: -1,
        animate: true,
        increment: 200
    },

    createEvent : function(dd, e, data, col, c, pos){
        return {
            portal: this.portal,
            panel: data.panel,
            columnIndex: col,
            column: c,
            position: pos,
            data: data,
            source: dd,
            rawEvent: e,
            status: this.dropAllowed
        };
    },

    notifyOver : function(dd, e, data){
        var xy = e.getXY(), portal = this.portal, px = dd.proxy;

        // case column widths
        if(!this.grid){
            this.grid = this.getGrid();
        }

        // handle case scroll where scrollbars appear during drag
        var cw = portal.body.dom.clientWidth;
        if(!this.lastCW){
            this.lastCW = cw;
        }else if(this.lastCW != cw){
            this.lastCW = cw;
            portal.doLayout();
            this.grid = this.getGrid();
        }

        // determine column
        var col = 0, xs = this.grid.columnX, cmatch = false;
        for(var len = xs.length; col < len; col++){
            if(xy[0] < (xs[col].x + xs[col].w)){
                cmatch = true;
                break;
            }
        }
        // no match, fix last index
        if(!cmatch){
            col--;
        }

        // find insert position
        var p, match = false, pos = 0,
            c = portal.items.itemAt(col),
            items = c.items.items;

        for(var len = items.length; pos < len; pos++){
            p = items[pos];
            var h = p.el.getHeight();
            if(h !== 0 && (p.el.getY()+(h/2)) > xy[1]){
                match = true;
                break;
            }
        }

        var overEvent = this.createEvent(dd, e, data, col, c,
                match && p ? pos : c.items.getCount());

        if(portal.fireEvent('validatedrop', overEvent) !== false &&
           portal.fireEvent('beforedragover', overEvent) !== false){

            // make sure proxy width is fluid
            px.getProxy().setWidth('auto');

            if(p){
                px.moveProxy(p.el.dom.parentNode, match ? p.el.dom : null);
            }else{
                px.moveProxy(c.el.dom, null);
            }

            this.lastPos = {c: c, col: col, p: match && p ? pos : false};
            this.scrollPos = portal.body.getScroll();

            portal.fireEvent('dragover', overEvent);

            return overEvent.status;;
        }else{
            return overEvent.status;
        }

    },

    notifyOut : function(){
        delete this.grid;
    },

    notifyDrop : function(dd, e, data){
        delete this.grid;
        if(!this.lastPos){
            return;
        }
        var c = this.lastPos.c, col = this.lastPos.col, pos = this.lastPos.p;

        var dropEvent = this.createEvent(dd, e, data, col, c,
                pos !== false ? pos : c.items.getCount());

        if(this.portal.fireEvent('validatedrop', dropEvent) !== false &&
           this.portal.fireEvent('beforedrop', dropEvent) !== false){

            dd.proxy.getProxy().remove();
            dd.panel.el.dom.parentNode.removeChild(dd.panel.el.dom);
            if(pos !== false){
                c.insert(pos, dd.panel);
            }else{
                c.add(dd.panel);
            }

            c.doLayout();

            this.portal.fireEvent('drop', dropEvent);

            // scroll position is lost on drop, fix it
            var st = this.scrollPos.top;
            if(st){
                var d = this.portal.body.dom;
                setTimeout(function(){
                    d.scrollTop = st;
                }, 10);
            }

        }
        delete this.lastPos;
    },

    // internal cache of body and column coords
    getGrid : function(){
        var box = this.portal.bwrap.getBox();
        box.columnX = [];
        this.portal.items.each(function(c){
             box.columnX.push({x: c.el.getX(), w: c.el.getWidth()});
        });
        return box;
    }
});


Ext.ux.PortalColumn = Ext.extend(Ext.Container, {layout: 'anchor',autoEl: 'div',defaultType: 'portlet',cls:'x-portal-column'
});
Ext.reg('portalcolumn', Ext.ux.PortalColumn);


Ext.ux.Portlet = Ext.extend(Ext.Panel, {
    anchor: '100%',
    frame: true,
    collapsible: true,
    draggable: true,
    cls: 'x-portlet',
    //resizer properties
    heightIncrement:16,
    pinned:false,
    duration: .6,
    easing: 'backIn',
    transparent:false,

    onRender : function(ct, position) {
        Ext.ux.Portlet.superclass.onRender.call(this,ct,position);

        //2008.1.11 xm
        var createProxyProtoType=Ext.Element.prototype.createProxy;
        Ext.Element.prototype.createProxy=function(config){
	        return Ext.DomHelper.append(this.dom, config, true);
	    };

        this.resizer = new Ext.Resizable(this.el, {
            animate: true,
            duration: this.duration,
            easing: this.easing,
            handles: 's',
            transparent:this.transparent,
            heightIncrement:this.heightIncrement,
            minHeight: this.minHeight || 100,
            pinned: this.pinned
        });
        this.resizer.on('resize', this.onResizer, this);

        Ext.Element.prototype.createProxy=createProxyProtoType;
        //2008.1.11 xm
    },

    onResizer : function(oResizable, iWidth, iHeight, e) {
        this.setHeight(iHeight);
    },

    onCollapse : function(doAnim, animArg) {
        this.el.setHeight('');
        Ext.ux.Portlet.superclass.onCollapse.call(this, doAnim, animArg);
    }
});

Ext.reg('portlet', Ext.ux.Portlet);
*/

/////////////////////////// DATE MENU /////////////////////////

Ext.ns('Ext.ux.form');

/**
 * Creates new DateTime
 * @constructor
 * @param {Object} config A config object
 */
Ext.ux.form.DateTime = Ext.extend(Ext.form.Field, {
    /**
     * @cfg {Function} dateValidator A custom validation function to be called during date field
     * validation (defaults to null)
     */
     dateValidator:null
    /**
     * @cfg {String/Object} defaultAutoCreate DomHelper element spec
     * Let superclass to create hidden field instead of textbox. Hidden will be submittend to server
     */
    ,defaultAutoCreate:{tag:'input', type:'hidden'}
    /**
     * @cfg {String} dtSeparator Date - Time separator. Used to split date and time (defaults to ' ' (space))
     */
    ,dtSeparator:' '
    /**
     * @cfg {String} hiddenFormat Format of datetime used to store value in hidden field
     * and submitted to server (defaults to 'Y-m-d H:i:s' that is mysql format)
     */
    ,hiddenFormat:'Y-m-d H:i:s'
    /**
     * @cfg {Boolean} otherToNow Set other field to now() if not explicly filled in (defaults to true)
     */
    ,otherToNow:true
    /**
     * @cfg {Boolean} emptyToNow Set field value to now on attempt to set empty value.
     * If it is true then setValue() sets value of field to current date and time (defaults to false)
     */
    /**
     * @cfg {String} timePosition Where the time field should be rendered. 'right' is suitable for forms
     * and 'below' is suitable if the field is used as the grid editor (defaults to 'right')
     */
    ,timePosition:'right' // valid values:'below', 'right'
    /**
     * @cfg {Function} timeValidator A custom validation function to be called during time field
     * validation (defaults to null)
     */
    ,timeValidator:null
    /**
     * @cfg {Number} timeWidth Width of time field in pixels (defaults to 100)
     */
    ,timeWidth:100
    /**
     * @cfg {String} dateFormat Format of DateField. Can be localized. (defaults to 'm/y/d')
     */
    ,dateFormat:'m/d/y'
    /**
     * @cfg {String} timeFormat Format of TimeField. Can be localized. (defaults to 'g:i A')
     */
    ,timeFormat:'g:i A'
    /**
     * @cfg {Object} dateConfig Config for DateField constructor.
     */
    /**
     * @cfg {Object} timeConfig Config for TimeField constructor.
     */

    // {{{
    /**
     * @private
     * creates DateField and TimeField and installs the necessary event handlers
     */
    ,initComponent:function() {
        // call parent initComponent
        Ext.ux.form.DateTime.superclass.initComponent.call(this);

        // create DateField
        var dateConfig = Ext.apply({}, {
             id:this.id + '-date'
            ,format:this.dateFormat || Ext.form.DateField.prototype.format
            ,width:this.timeWidth
            ,selectOnFocus:this.selectOnFocus
            ,validator:this.dateValidator
            ,listeners:{
                  blur:{scope:this, fn:this.onBlur}
                 ,focus:{scope:this, fn:this.onFocus}
            }
        }, this.dateConfig);
        this.df = new Ext.form.DateField(dateConfig);
        this.df.ownerCt = this;
        delete(this.dateFormat);

        // create TimeField
        var timeConfig = Ext.apply({}, {
             id:this.id + '-time'
            ,format:this.timeFormat || Ext.form.TimeField.prototype.format
            ,width:this.timeWidth
            ,selectOnFocus:this.selectOnFocus
            ,validator:this.timeValidator
            ,listeners:{
                  blur:{scope:this, fn:this.onBlur}
                 ,focus:{scope:this, fn:this.onFocus}
            }
        }, this.timeConfig);
        this.tf = new Ext.form.TimeField(timeConfig);
        this.tf.ownerCt = this;
        delete(this.timeFormat);

        // relay events
        this.relayEvents(this.df, ['focus', 'specialkey', 'invalid', 'valid']);
        this.relayEvents(this.tf, ['focus', 'specialkey', 'invalid', 'valid']);

        this.on('specialkey', this.onSpecialKey, this);

    } // eo function initComponent
    // }}}
    // {{{
    /**
     * @private
     * Renders underlying DateField and TimeField and provides a workaround for side error icon bug
     */
    ,onRender:function(ct, position) {
        // don't run more than once
        if(this.isRendered) {
            return;
        }

        // render underlying hidden field
        Ext.ux.form.DateTime.superclass.onRender.call(this, ct, position);

        // render DateField and TimeField
        // create bounding table
        var t;
        if('below' === this.timePosition || 'bellow' === this.timePosition) {
            t = Ext.DomHelper.append(ct, {tag:'table',style:'border-collapse:collapse',children:[
                 {tag:'tr',children:[{tag:'td', style:'padding-bottom:1px', cls:'ux-datetime-date'}]}
                ,{tag:'tr',children:[{tag:'td', cls:'ux-datetime-time'}]}
            ]}, true);
        }
        else {
            t = Ext.DomHelper.append(ct, {tag:'table',style:'border-collapse:collapse',children:[
                {tag:'tr',children:[
                    {tag:'td',style:'padding-right:4px', cls:'ux-datetime-date'},{tag:'td', cls:'ux-datetime-time'}
                ]}
            ]}, true);
        }

        this.tableEl = t;
        this.wrap = t.wrap({cls:'x-form-field-wrap'});
//        this.wrap = t.wrap();
        this.wrap.on("mousedown", this.onMouseDown, this, {delay:10});

        // render DateField & TimeField
        this.df.render(t.child('td.ux-datetime-date'));
        this.tf.render(t.child('td.ux-datetime-time'));

        // workaround for IE trigger misalignment bug
        // see http://extjs.com/forum/showthread.php?p=341075#post341075
//        if(Ext.isIE && Ext.isStrict) {
//            t.select('input').applyStyles({top:0});
//        }

        this.df.el.swallowEvent(['keydown', 'keypress']);
        this.tf.el.swallowEvent(['keydown', 'keypress']);

        // create icon for side invalid errorIcon
        if('side' === this.msgTarget) {
            var elp = this.el.findParent('.x-form-element', 10, true);
            if(elp) {
                this.errorIcon = elp.createChild({cls:'x-form-invalid-icon'});
            }

            var o = {
                 errorIcon:this.errorIcon
                ,msgTarget:'side'
                ,alignErrorIcon:this.alignErrorIcon.createDelegate(this)
            };
            Ext.apply(this.df, o);
            Ext.apply(this.tf, o);
//            this.df.errorIcon = this.errorIcon;
//            this.tf.errorIcon = this.errorIcon;
        }

        // setup name for submit
        this.el.dom.name = this.hiddenName || this.name || this.id;

        // prevent helper fields from being submitted
        this.df.el.dom.removeAttribute("name");
        this.tf.el.dom.removeAttribute("name");

        // we're rendered flag
        this.isRendered = true;

        // update hidden field
        this.updateHidden();

    } // eo function onRender
    // }}}
    // {{{
    /**
     * @private
     */
    ,adjustSize:Ext.BoxComponent.prototype.adjustSize
    // }}}
    // {{{
    /**
     * @private
     */
    ,alignErrorIcon:function() {
        this.errorIcon.alignTo(this.tableEl, 'tl-tr', [2, 0]);
    }
    // }}}
    // {{{
    /**
     * @private initializes internal dateValue
     */
    ,initDateValue:function() {
        this.dateValue = this.otherToNow ? new Date() : new Date(1970, 0, 1, 0, 0, 0);
    }
    // }}}
    // {{{
    /**
     * Calls clearInvalid on the DateField and TimeField
     */
    ,clearInvalid:function(){
        this.df.clearInvalid();
        this.tf.clearInvalid();
    } // eo function clearInvalid
    // }}}
    // {{{
    /**
     * Calls markInvalid on both DateField and TimeField
     * @param {String} msg Invalid message to display
     */
    ,markInvalid:function(msg){
        this.df.markInvalid(msg);
        this.tf.markInvalid(msg);
    } // eo function markInvalid
    // }}}
    // {{{
    /**
     * @private
     * called from Component::destroy.
     * Destroys all elements and removes all listeners we've created.
     */
    ,beforeDestroy:function() {
        if(this.isRendered) {
//            this.removeAllListeners();
            this.wrap.removeAllListeners();
            this.wrap.remove();
            this.tableEl.remove();
            this.df.destroy();
            this.tf.destroy();
        }
    } // eo function beforeDestroy
    // }}}
    // {{{
    /**
     * Disable this component.
     * @return {Ext.Component} this
     */
    ,disable:function() {
        if(this.isRendered) {
            this.df.disabled = this.disabled;
            this.df.onDisable();
            this.tf.onDisable();
        }
        this.disabled = true;
        this.df.disabled = true;
        this.tf.disabled = true;
        this.fireEvent("disable", this);
        return this;
    } // eo function disable
    // }}}
    // {{{
    /**
     * Enable this component.
     * @return {Ext.Component} this
     */
    ,enable:function() {
        if(this.rendered){
            this.df.onEnable();
            this.tf.onEnable();
        }
        this.disabled = false;
        this.df.disabled = false;
        this.tf.disabled = false;
        this.fireEvent("enable", this);
        return this;
    } // eo function enable
    // }}}
    // {{{
    /**
     * @private Focus date filed
     */
    ,focus:function() {
        this.df.focus();
    } // eo function focus
    // }}}
    // {{{
    /**
     * @private
     */
    ,getPositionEl:function() {
        return this.wrap;
    }
    // }}}
    // {{{
    /**
     * @private
     */
    ,getResizeEl:function() {
        return this.wrap;
    }
    // }}}
    // {{{
    /**
     * @return {Date/String} Returns value of this field
     */
    ,getValue:function() {
        // create new instance of date
        return this.dateValue ? new Date(this.dateValue) : '';
    } // eo function getValue
    // }}}
    // {{{
    /**
     * @return {Boolean} true = valid, false = invalid
     * @private Calls isValid methods of underlying DateField and TimeField and returns the result
     */
    ,isValid:function() {
        return this.df.isValid() && this.tf.isValid();
    } // eo function isValid
    // }}}
    // {{{
    /**
     * Returns true if this component is visible
     * @return {boolean}
     */
    ,isVisible : function(){
        return this.df.rendered && this.df.getActionEl().isVisible();
    } // eo function isVisible
    // }}}
    // {{{
    /**
     * @private Handles blur event
     */
    ,onBlur:function(f) {
        // called by both DateField and TimeField blur events

        // revert focus to previous field if clicked in between
        if(this.wrapClick) {
            f.focus();
            this.wrapClick = false;
        }

        // update underlying value
        if(f === this.df) {
            this.updateDate();
        }
        else {
            this.updateTime();
        }
        this.updateHidden();

        this.validate();

        // fire events later
        (function() {
            if(!this.df.hasFocus && !this.tf.hasFocus) {
                var v = this.getValue();
                if(String(v) !== String(this.startValue)) {
                    this.fireEvent("change", this, v, this.startValue);
                }
                this.hasFocus = false;
                this.fireEvent('blur', this);
            }
        }).defer(100, this);

    } // eo function onBlur
    // }}}
    // {{{
    /**
     * @private Handles focus event
     */
    ,onFocus:function() {
        if(!this.hasFocus){
            this.hasFocus = true;
            this.startValue = this.getValue();
            this.fireEvent("focus", this);
        }
    }
    // }}}
    // {{{
    /**
     * @private Just to prevent blur event when clicked in the middle of fields
     */
    ,onMouseDown:function(e) {
        if(!this.disabled) {
            this.wrapClick = 'td' === e.target.nodeName.toLowerCase();
        }
    }
    // }}}
    // {{{
    /**
     * @private
     * Handles Tab and Shift-Tab events
     */
    ,onSpecialKey:function(t, e) {
        var key = e.getKey();
        if(key === e.TAB) {
            if(t === this.df && !e.shiftKey) {
                e.stopEvent();
                this.tf.focus();
            }
            if(t === this.tf && e.shiftKey) {
                e.stopEvent();
                this.df.focus();
            }
            this.updateValue();
        }
        // otherwise it misbehaves in editor grid
        if(key === e.ENTER) {
            this.updateValue();
        }

    } // eo function onSpecialKey
    // }}}
    // {{{
    /**
     * Resets the current field value to the originally loaded value
     * and clears any validation messages. See Ext.form.BasicForm.trackResetOnLoad
     */
    ,reset:function() {
        this.df.setValue(this.originalValue);
        this.tf.setValue(this.originalValue);
    } // eo function reset
    // }}}
    // {{{
    /**
     * @private Sets the value of DateField
     */
    ,setDate:function(date) {
        this.df.setValue(date);
    } // eo function setDate
    // }}}
    // {{{
    /**
     * @private Sets the value of TimeField
     */
    ,setTime:function(date) {
        this.tf.setValue(date);
    } // eo function setTime
    // }}}
    // {{{
    /**
     * @private
     * Sets correct sizes of underlying DateField and TimeField
     * With workarounds for IE bugs
     */
    ,setSize:function(w, h) {
        if(!w) {
            return;
        }
        if('below' === this.timePosition) {
            this.df.setSize(w, h);
            this.tf.setSize(w, h);
            if(Ext.isIE) {
                this.df.el.up('td').setWidth(w);
                this.tf.el.up('td').setWidth(w);
            }
        }
        else {
            this.df.setSize(w - this.timeWidth - 4, h);
            this.tf.setSize(this.timeWidth, h);

            if(Ext.isIE) {
                this.df.el.up('td').setWidth(w - this.timeWidth - 4);
                this.tf.el.up('td').setWidth(this.timeWidth);
            }
        }
    } // eo function setSize
    // }}}
    // {{{
    /**
     * @param {Mixed} val Value to set
     * Sets the value of this field
     */
    ,setValue:function(val) {
        if(!val && true === this.emptyToNow) {
            this.setValue(new Date());
            return;
        }
        else if(!val) {
            this.setDate('');
            this.setTime('');
            this.updateValue();
            return;
        }
        if ('number' === typeof val) {
          val = new Date(val);
        }
        else if('string' === typeof val && this.hiddenFormat) {
            val = Date.parseDate(val, this.hiddenFormat);
        }
        val = val ? val : new Date(1970, 0 ,1, 0, 0, 0);
        var da;
        if(val instanceof Date) {
            this.setDate(val);
            this.setTime(val);
            this.dateValue = new Date(Ext.isIE ? val.getTime() : val);
        }
        else {
            da = val.split(this.dtSeparator);
            this.setDate(da[0]);
            if(da[1]) {
                if(da[2]) {
                    // add am/pm part back to time
                    da[1] += da[2];
                }
                this.setTime(da[1]);
            }
        }
        this.updateValue();
    } // eo function setValue
    // }}}
    // {{{
    /**
     * Hide or show this component by boolean
     * @return {Ext.Component} this
     */
    ,setVisible: function(visible){
        if(visible) {
            this.df.show();
            this.tf.show();
        }else{
            this.df.hide();
            this.tf.hide();
        }
        return this;
    } // eo function setVisible
    // }}}
    //{{{
    ,show:function() {
        return this.setVisible(true);
    } // eo function show
    //}}}
    //{{{
    ,hide:function() {
        return this.setVisible(false);
    } // eo function hide
    //}}}
    // {{{
    /**
     * @private Updates the date part
     */
    ,updateDate:function() {

        var d = this.df.getValue();
        if(d) {
            if(!(this.dateValue instanceof Date)) {
                this.initDateValue();
                if(!this.tf.getValue()) {
                    this.setTime(this.dateValue);
                }
            }
            this.dateValue.setMonth(0); // because of leap years
            this.dateValue.setFullYear(d.getFullYear());
            this.dateValue.setMonth(d.getMonth(), d.getDate());
//            this.dateValue.setDate(d.getDate());
        }
        else {
            this.dateValue = '';
            this.setTime('');
        }
    } // eo function updateDate
    // }}}
    // {{{
    /**
     * @private
     * Updates the time part
     */
    ,updateTime:function() {
        var t = this.tf.getValue();
        if(t && !(t instanceof Date)) {
            t = Date.parseDate(t, this.tf.format);
        }
        if(t && !this.df.getValue()) {
            this.initDateValue();
            this.setDate(this.dateValue);
        }
        if(this.dateValue instanceof Date) {
            if(t) {
                this.dateValue.setHours(t.getHours());
                this.dateValue.setMinutes(t.getMinutes());
                this.dateValue.setSeconds(t.getSeconds());
            }
            else {
                this.dateValue.setHours(0);
                this.dateValue.setMinutes(0);
                this.dateValue.setSeconds(0);
            }
        }
    } // eo function updateTime
    // }}}
    // {{{
    /**
     * @private Updates the underlying hidden field value
     */
    ,updateHidden:function() {
        if(this.isRendered) {
            var value = this.dateValue instanceof Date ? this.dateValue.format(this.hiddenFormat) : '';
            this.el.dom.value = value;
        }
    }
    // }}}
    // {{{
    /**
     * @private Updates all of Date, Time and Hidden
     */
    ,updateValue:function() {

        this.updateDate();
        this.updateTime();
        this.updateHidden();

        return;
    } // eo function updateValue
    // }}}
    // {{{
    /**
     * @return {Boolean} true = valid, false = invalid
     * calls validate methods of DateField and TimeField
     */
    ,validate:function() {
        return this.df.validate() && this.tf.validate();
    } // eo function validate
    // }}}
    // {{{
    /**
     * Returns renderer suitable to render this field
     * @param {Object} Column model config
     */
    ,renderer: function(field) {
        var format = field.editor.dateFormat || Ext.ux.form.DateTime.prototype.dateFormat;
        format += ' ' + (field.editor.timeFormat || Ext.ux.form.DateTime.prototype.timeFormat);
        var renderer = function(val) {
            var retval = Ext.util.Format.date(val, format);
            return retval;
        };
        return renderer;
    } // eo function renderer
    // }}}

}); // eo extend

// register xtype
Ext.reg('xdatetime', Ext.ux.form.DateTime);



//This is also implemented in VelocityMacro, see VM_global_library.vm
function getContextHelp(articleId, catId){
    if(top.VPSettings.getContextHelpEnabled()) {
        if(articleId != "undefined" && articleId != null && articleId != ""){
            var urlA = "https://www.visionproject.se/ShowKBEx.do?id=" + articleId + "&supportCenter=" + top.VPSettings.getSuppportCenterHashCode();
            winContent = window.open(urlA, "VP_Support");
            winContent.focus();
        } else {
            var urlB =  "https://www.visionproject.se/ShowKBEx.do?cat=" + catId + "&supportCenter=" + top.VPSettings.getSuppportCenterHashCode();
            winContent = window.open(urlB, "VP_Support");
            return winContent.focus();
        }
    }
    return "";
}




var Balloon = function(){

    createBox = function(t, s) {
        return ["<div class=\"msg\">"
            , "<div class=\"x-box-tl\"><div class=\"x-box-tr\"><div class=\"x-box-tc\"></div></div></div>"
            , "<div class=\"x-box-ml\"><div class=\"x-box-mr\"><div class=\"x-box-mc\"><h3>"
            , t, "</h3>", s
            , "</div></div></div>"
            , "<div class=\"x-box-bl\"><div class=\"x-box-br\"><div class=\"x-box-bc\"></div></div></div>"
            , "</div>"].join("");
    }

    return {

        balloon : function(alignTarget,align, title, format){
            if(!this.balloonCt){
                this.balloonCt = Ext.DomHelper.insertFirst(document.body, {id:'demo-balloon-div'}, true);
            }
            this.balloonCt.alignTo(alignTarget||Ext.getBody(), align||'t-t');
            var s = String.format.apply(String, Array.prototype.slice.call(arguments, 3));
            var m = Ext.DomHelper.append(this.balloonCt, {html:createBox(title||'', s)}, true);
            m.slideIn('t').pause(1).ghost("t", {remove:true});
        }

    }
}();



//// AutoHide Menu
Ext.ux.AutoHideMenu = function(config) {
    Ext.ux.AutoHideMenu.superclass.constructor.call(this,config);
    //this.on("show",this.autoHide,this);
    //this.on("mouseover",this.resetTimer,this);
    this.on("mouseout",this.autoHide,this);
    this.on("mouseover",this.resetTimer,this);

};

Ext.extend(Ext.ux.AutoHideMenu, Ext.menu.Menu, {
    hideDelay:  this.hideDelay ? this.hideDelay : 500,

    //IE6 was giving some inconsistent errors when autoHideTimer wasn't listed here
    //so I threw it in here for good measure. No harm, no foul.
    autoHideTimer: null,

    autoHide: function() {
        if(!this.hidden && !this.autoHideTimer)
            this.autoHideTimer = this.hide.defer(this.hideDelay, this);
    },

    resetTimer: function() {
        if (this.autoHideTimer) {
            clearTimeout(this.autoHideTimer);
            delete this.autoHideTimer;
            //this.autoHideTimer = this.hide.defer(this.hideDelay, this);
        }
    }
});


// register xtype
Ext.reg('autohidemenu', Ext.ux.AutoHideMenu);


/* Enable/disable readonly mode in TinyMce */

function TinyMCEReadOnlySetup(EdInst, HideBars)
    /*
     * http://tinymce.moxiecode.com/punbb/viewtopic.php?id=13337
     *
     * EdInst                                The instance of the editor that is to
     *                                       be extended with the capability to
     *                                       toggle readonly mode.
     *
     * HideBars                              A boolean that, if true, indicates that
     *                                       the tool bars and/or status bar should
     *                                       also be hidden when readonly mode is
     *                                       set.  The default, if omitted is false.
     *
     * This function will add a method named switchReadOnly to the tinymce.Editor
     * class for the instance of the editor passed in EdInst.  Calling
     * switchReadOnly will cause readonly mode to be switched on/off.  If HideBars
     * is true, when this function is called, the call to switchReadOnly will also
     * cause the tool bars/status bar to be hidden/unhidden when readonly mode is
     * switched on/off.
     *
     * Typically, this function would be used at startup time to extend TinyMCE so
     * that readonly mode could be switched for all editor instances.  For example:
     *
     *      tinyMCE.init(
     *        {
     *             .
     *             .
     *             .
     *        setup : function(ed) { TinyMCEReadOnlySetup(ed, true); },
     *             .
     *             .
     *             .
     *        });
     *
     * Note that the initial, readonly state of the editors being set up in this
     * manner is irrelevant.  The editor must be initialized as editable for
     * toggling to work but this routine takes care of that detail so the readonly
     * flag may still be used in tinyMCE.init.
     *
     * If you wish to set up an individual editor, after the fact, the readonly
     * flag must not be set to true during tinyMCE.init.  If it is omitted or set to
     * false, you may call this routine as follows:
     *
     *      TinyMCEReadOnlySetup(tinyMCE.get('TextArea1'), true);
     *
     * Once an instance of the editor has been initialized with this extension, a
     * new method named switchReadOnly is added to the editor instance.  You may
     * call it something like this:
     *
     *      EdInst = tinyMCE.get('TextArea1');
     *      EdInst.switchReadOnly(true);
     *
     * If you already have the editor instance variable, there's no need to look it
     * up.  And, the single parameter passed to switchReadOnly is a boolean which
     * indicates, if true, that the editor instance should be made readonly.  If it
     * is false, the editor instance is made editable.  The toolbars and/or status
     * bar will be hidden/unhidden depending on the value that was passed to
     * TinyMCEReadOnlySetup on the setup call.
     *
     * If you'd like to start with all instances of TinyMCE set to readonly and
     * enable them depending on which one the user clicks on, you can do something
     * like this:
     *
     *      tinyMCE.init(
     *        {
     *             .
     *             .
     *             .
     *        handle_event_callback : "ReadonlyFocus",
     *             .
     *             .
     *             .
     *        });
     *           .
     *           .
     *           .
     *      function ReadonlyFocus(ev, ed)
     *      {
     *      if (ed.settings.readonly) { ed.switchReadOnly(false); }
     *      return (true);
     *      }
     *
     * And, if you'd like to then switch off readonly as the user navigates through
     * the various editor instances on a page, try this:
     *
     *      tinyMCE.init(
     *        {
     *             .
     *             .
     *             .
     *        ed.onDeactivate.add(function(ed)
     *          {
     *          if (!ed.settings.readonly) { ed.switchReadOnly(true); }
     *          }
     *             .
     *             .
     *             .
     *        });
     */
{

    // The user may pass the optional HideBars parameter to us to indicate that
    // we also should hide the toolbars and/or the status bar, when the control
    // is made readonly.
    if (typeof(HideBars) != undefined)
    {
        if (HideBars) { EdInst.settings.ROExtHideBars = true; }
        else { EdInst.settings.ROExtHideBars = false; }
    }
    else { EdInst.settings.ROExtHideBars = false; }

    // By assigning an unnamed function to the switchReadOnly variable, we set
    // up the method of the same name.
    EdInst.switchReadOnly = function(IsReadOnly)
    {
        var EdTable;

        // Cache the editor settings.
        var EdSettings = this.settings;

        // We need a pointer to the table that the editor is built in.
        if (document.all && !document.getElementById)
        { EdTable = document.all[this.id+'_tbl']; }
        else { EdTable = document.getElementById(this.id+'_tbl'); }

        // If the current editor setting is editable and the user wishes the mode
        // to be read only, set it that way.
        if (!EdSettings.readonly && IsReadOnly)
        {
            var TBContainer = null, TBContainerHeight = 0, SBContainerHeight = 0;
            var ToolBar, TBNum;

            // Make the content read only.
            //
            // This code will fail on Gecko if the editor is placed in a hidden
            // container element.  If that happens, design mode will be set once the
            // editor is given focus.
            if (!tinymce.isIE)
            {
                var EdDoc = this.getDoc();        // Look this up outside the try

                try { EdDoc.designMode = 'Off'; } catch (Except) { }
            }

            // Otherwise, do it differently for IE.
            else
            {
                // The editor won't steal focus if we hide it while setting
                // contentEditable.
                var DOM = tinymce.DOM, EdBody = this.getBody();

                DOM.hide(EdBody);
                EdBody.contentEditable = false;
                DOM.show(EdBody);
            }

            // Make a note to ourselves that the editor is now readonly.
            EdSettings.readonly = true;

            // If the user wants us to hide toolbars and/or the status bar, let's
            // do it.
            if (EdSettings.ROExtHideBars)
            {
                // Begin by making any toolbars disappear.
                for (TBNum = 1; TBNum <= 4; TBNum++)
                {
                    if (document.all && !document.getElementById)
                    { ToolBar = document.all[this.id+'_toolbar'+TBNum]; }
                    else { ToolBar = document.getElementById(this.id+'_toolbar'+TBNum); }

                    // If this toolbar exists, take care of it.
                    if (ToolBar)
                    {
                        // If this is the top toolbar, we need to save the height of the
                        // table row that contains it so that we can reduce the table by
                        // that much, later on.  We need to do this first, since
                        // disappearing the toolbars reduces the height.
                        if (!TBContainer)
                        {
                            if (ToolBar.offsetParent) { TBContainer = ToolBar.offsetParent; }
                            else if (ToolBar.parentNode) { TBContainer = ToolBar.parentNode; }
                            else { TBContainer = ToolBar; }

                            if (typeof(TBContainer.clientHeight) == 'number')
                            { TBContainerHeight = TBContainer.clientHeight; }
                        }

                        // Now, we can make it disappear.
                        ToolBar.style.display = 'none';
                    }
                }

                // If there is a status bar, we need to make it disappear too.
                if (document.all && !document.getElementById)
                { ToolBar = document.all[this.id+'_path_row']; }
                else { ToolBar = document.getElementById(this.id+'_path_row'); }

                if (ToolBar)
                {
                    // To find the table data for the status bar, we need to move up from
                    // the <div>.
                    ToolBar = ToolBar.parentNode;

                    // We need to save the height of the table row that contains the
                    // status bar so that we can reduce the table by that much, later on.
                    // Note that we said table row but really we get the height of the
                    // table data because IE seems to have a funny idea of what the table
                    // row's height should be.  Also, we need to do this first, since
                    // disappearing the status bar reduces the height.
                    if (typeof(ToolBar.clientHeight) == 'number')
                    { SBContainerHeight = ToolBar.clientHeight; }

                    // Now, we can make the table row disappear.  We make the row
                    // disappear because making the table data disappear causes strange
                    // artifacts on redisplay under Mozilla (nice one, Smiley).
                    ToolBar.parentNode.style.display = 'none';
                }

                // Get the height of the editor table now.  We'll reduce it by the
                // height of the toolbar and status bar.  But, we also need to save it
                // so that we can restore it when we switch it to editable, later on.
                TBNum = parseInt(EdTable.style.height);
                EdSettings.ROExtHeightWithBars = TBNum;

                // The editor table was given a fixed height.  To get rid of any
                // artifacts caused by this, we need to reduce the height of the table
                // to account for the height of the stuff that we just disappeared.
                //
                // But, first, we'll reduce the height of the table row that encloses
                // the toolbar to three pixels.  This gives us the hint of a toolbar so
                // that the user knows there's something there (i.e. its not just
                // another text box).  I suppose, if you didn't like this, you could
                // just disappear the whole table row (above, instead of the table
                // data).
                if (TBContainer) { TBContainer.style.height = '3px'; }

                EdTable.style.height
                        = (TBNum-TBContainerHeight-SBContainerHeight+3)+'px';
            }
        }

        // Otherwise, if the current editor setting is read only and the user
        // wishes the mode to be editable, set it that way.
        else if (EdSettings.readonly && !IsReadOnly)
        {
            var TBStyleCleared = false;
            var ToolBar, TBNum;

            // Make the content editable.
            //
            // This code will fail on Gecko if the editor is placed in a hidden
            // container element.  If that happens, design mode will be set once the
            // editor is given focus.
            if (!tinymce.isIE)
            {
                var EdDoc = this.getDoc();        // Look this up outside the try

                try { EdDoc.designMode = 'On'; } catch (Except) { }
            }

            // Otherwise, do it differently for IE.
            else
            {
                // The editor won't steal focus if we hide it while setting
                // contentEditable.
                var DOM = tinymce.DOM, EdBody = this.getBody();

                DOM.hide(EdBody);
                EdBody.contentEditable = true;
                DOM.show(EdBody);
            }

            // Make a note to ourselves that the editor is now editable.
            EdSettings.readonly = false;

            // If the user had us hide toolbars and/or the status bar, now's the time
            // to undo it.
            if (EdSettings.ROExtHideBars)
            {
                // Begin by making any toolbars reappear.
                for (TBNum = 1; TBNum <= 4; TBNum++)
                {
                    if (document.all && !document.getElementById)
                    { ToolBar = document.all[this.id+'_toolbar'+TBNum]; }
                    else { ToolBar = document.getElementById(this.id+'_toolbar'+TBNum); }

                    // If this toolbar exists, take care of it.
                    if (ToolBar)
                    {
                        // If we haven't yet cleared the height that we set on the table
                        // row that contains the toolbar, we should do so now.  We set its
                        // height to use it for a placeholder but now we need it to
                        // automatically adjust for however many toolbar rows we make
                        // appear.
                        if (!TBStyleCleared)
                        {
                            if (ToolBar.offsetParent)
                            { ToolBar.offsetParent.style.height = ''; }
                            else if (ToolBar.parentNode)
                            { ToolBar.parentNode.style.height = ''; }

                            TBStyleCleared = true;
                        }

                        // Now, we can make the toolbar reappear by setting the display
                        // style to '', which puts it back to whatever it was before.
                        ToolBar.style.display = '';
                    }
                }

                // If there is a status bar, we need to make it reappear too.
                if (document.all && !document.getElementById)
                { ToolBar = document.all[this.id+'_path_row']; }
                else { ToolBar = document.getElementById(this.id+'_path_row'); }

                if (ToolBar)
                {
                    // To find the table row for the status bar, we need to move up from
                    // the <div>.  Then, we can make it reappear by setting the display
                    // style to '', which puts it back to whatever it was before.
                    ToolBar.parentNode.parentNode.style.display = '';
                }

                // The editor table was given a fixed height.  To get rid of any
                // artifacts caused by this, we reduced the height of the table to
                // account for the height of the toolbars and/or status bar that we
                // disappeared, when we switched to readonly mode.  Now, we need to
                // put the height back the way it was.
                if (typeof(EdSettings.ROExtHeightWithBars) == 'number')
                { EdTable.style.height = EdSettings.ROExtHeightWithBars+'px'; }
            }
        }

        // Let the caller know how the editor is set.
        return (EdSettings.readonly);
    };

    // If we don't initialize the editor with read only mode turned off, there
    // will be no toolbars drawn at the top of the box and no status bar.  So,
    // upon startup, if the editor is set to read only, it is switched to
    // editable (temporarily).  This draws the toolbars and/or status bar.  Then,
    // an onInit routine is shoved into the startup work queue that flips the
    // mode back to read only.
    if (EdInst.settings.readonly)
    {
        EdInst.settings.readonly = false;
        EdInst.onInit.add(function() { this.switchReadOnly(true); });
    }
}


/*==================================================*
$Id: filterlist.js,v 1.3 2003/10/08 17:13:49 pat Exp $
Copyright 2003 Patrick Fitzgerald
http://www.barelyfitz.com/webdesign/articles/filterlist/

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*==================================================*/

function filterlist(selectobj) {

  //==================================================
  // PARAMETERS
  //==================================================

  // HTML SELECT object
  // For example, set this to document.myform.myselect
  this.selectobj = selectobj;

  // Flags for regexp matching.
  // "i" = ignore case; "" = do not ignore case
  // You can use the set_ignore_case() method to set this
  this.flags = 'i';

  // Which parts of the select list do you want to match?
  this.match_text = true;
  this.match_value = false;

  // You can set the hook variable to a function that
  // is called whenever the select list is filtered.
  // For example:
  // myfilterlist.hook = function() { }

  // Flag for debug alerts
  // Set to true if you are having problems.
  this.show_debug = false;

  //==================================================
  // METHODS
  //==================================================

  //--------------------------------------------------
  this.init = function() {
    // This method initilizes the object.
    // This method is called automatically when you create the object.
    // You should call this again if you alter the selectobj parameter.

    if (!this.selectobj) return this.debug('selectobj not defined');
    if (!this.selectobj.options) return this.debug('selectobj.options not defined');

    // Make a copy of the select list options array
    this.optionscopy = new Array();
    if (this.selectobj && this.selectobj.options) {
      for (var i=0; i < this.selectobj.options.length; i++) {

        // Create a new Option
        this.optionscopy[i] = new Option();

        // Set the text for the Option
        this.optionscopy[i].text = selectobj.options[i].text;

        // Set the value for the Option.
        // If the value wasn't set in the original select list,
        // then use the text.
        if (selectobj.options[i].value) {
          this.optionscopy[i].value = selectobj.options[i].value;
        } else {
          this.optionscopy[i].value = selectobj.options[i].text;
        }

      }
    }
  }

  //--------------------------------------------------
  this.reset = function() {
    // This method resets the select list to the original state.
    // It also unselects all of the options.

    this.set('');
  }


  //--------------------------------------------------
  this.set = function(pattern) {
    // This method removes all of the options from the select list,
    // then adds only the options that match the pattern regexp.
    // It also unselects all of the options.

    var loop=0, index=0, regexp, e;

    if (!this.selectobj) return this.debug('selectobj not defined');
    if (!this.selectobj.options) return this.debug('selectobj.options not defined');

    // Clear the select list so nothing is displayed
    this.selectobj.options.length = 0;

    // Set up the regular expression.
    // If there is an error in the regexp,
    // then return without selecting any items.
    try {

      // Initialize the regexp
      regexp = new RegExp(pattern, this.flags);

    } catch(e) {

      // There was an error creating the regexp.

      // If the user specified a function hook,
      // call it now, then return
      if (typeof this.hook == 'function') {
        this.hook();
      }

      return;
    }

    // Loop through the entire select list and
    // add the matching items to the select list
    for (loop=0; loop < this.optionscopy.length; loop++) {

      // This is the option that we're currently testing
      var option = this.optionscopy[loop];

      // Check if we have a match
      if ((this.match_text && regexp.test(option.text)) ||
          (this.match_value && regexp.test(option.value))) {

        // We have a match, so add this option to the select list
        // and increment the index

        this.selectobj.options[index++] =
          new Option(option.text, option.value, false);

      }
    }

    // If the user specified a function hook,
    // call it now
    if (typeof this.hook == 'function') {
      this.hook();
    }

  }


  //--------------------------------------------------
  this.set_ignore_case = function(value) {
    // This method sets the regexp flags.
    // If value is true, sets the flags to "i".
    // If value is false, sets the flags to "".

    if (value) {
      this.flags = 'i';
    } else {
      this.flags = '';
    }
  }


  //--------------------------------------------------
  this.debug = function(msg) {
    if (this.show_debug) {
      alert('FilterList: ' + msg);
    }
  }


  //==================================================
  // Initialize the object
  //==================================================
  this.init();

}


function getTopFrame(){
    var ok = true;
    try {
        var v = "" +top.document.location.href;
        v = "" + top.location.href;
    } catch(e) {
        ok = false;
    }

    if(!ok){
        try {
            var v = "" + parent.location.href;
            return parent;
        } catch(e) {
            return self;
        }
    } else {
        return top;
    }
}


function showBlockedLinksInDescription(textAreaId) {
    var content = tinyMCE.get(textAreaId).getContent();
    content = content.replace(/blocked::/g, "");
    tinyMCE.get(textAreaId).setContent(content);
}

function showBlockedLinksInReadOnlyDescription(divId) {
    var content = document.getElementById(divId).innerHTML;
    content = content.replace(/blocked::/g, "");
    document.getElementById(divId).innerHTML = content;
}

function showMenu(hrefLink, menuItems) {
    // This check is needed because of IE
    if (OLgateOK == 1 || !Ext.isIE) {
        var currentContextMenu = new Ext.ux.AutoHideMenu({            
            style: {
                overflow: 'visible'     // For the Combo popup
            },
            items: menuItems,
            hrefLink: hrefLink
        });

        var extHrefLink = Ext.get(hrefLink);
        var coords = extHrefLink.getXY();
        currentContextMenu.showAt([coords[0]+10, coords[1]+20]);

        extHrefLink.un("mouseover", currentContextMenu.resetTimer);
        extHrefLink.un("mouseout", currentContextMenu.autoHide);
        extHrefLink.on("mouseover", currentContextMenu.resetTimer, currentContextMenu);
        extHrefLink.on("mouseout", currentContextMenu.autoHide, currentContextMenu);
    }
}


function showConfigItemSelectorDialog(noDecendantsFlagParam, currentConfigItemId, configItemTypeId, rootNodeName, windowTitle, configItemClickedCallback) {
    var configItemSelectorPanel = new VPConfigItemSelectorPanel(noDecendantsFlagParam, currentConfigItemId, configItemTypeId, rootNodeName, configItemClickedCallback);

    var configItemSelectorDialog = new Ext.Window({
        title: JSMessages.get("ext.button.select") + ' ' + windowTitle,
        width: 400,
        height: 500,
        shadow: true,
        modal: true,        
        resizable : true,
        closeAction: 'hide',
        buttonAlign:'center',
        layout: 'fit',
        plain:true,
        buttons: [{
            text: JSMessages.get("ext.button.select"),
            handler: function() {
                configItemClickedCallback(configItemSelectorPanel.getSelectedConfigItemId(), configItemSelectorPanel.getSelectedConfigItemName());
            },
            scope: this
        },{
            text: JSMessages.get("ext.button.close"),
            handler: function() {
                configItemSelectorDialog.hide();
            },
            scope: this
        }],
        items: configItemSelectorPanel,
        keys: [{
            key: 27,  // hide on Esc
            fn: function() {
                configItemSelectorDialog.hide();
            },
            scope: this
        }]
    });

    configItemSelectorDialog.show();
    return configItemSelectorDialog;
}

VPConfigItemSelectorPanel = function(noDecendantsFlagParam, currentConfigItemIdParam, configItemTypeId, rootNodeName, configItemClickedCallback){

    this.selectedConfigItemId = '0';
    this.selectedConfigItemName = '';
    this.noDecendantsFlag = noDecendantsFlagParam;
    this.currentConfigItemId = currentConfigItemIdParam;
    this.configItemTypeId = configItemTypeId;

    this.configItemTree = new Ext.tree.TreePanel({
        //title: rootNodeName,
		loader: new Ext.tree.TreeLoader({dataUrl:'GetConfigItemTreeNodes.do?noDecendants=' + this.noDecendantsFlag}),
		border:false,
        header: true,
        autoScroll: true,
        //rootVisible: false,
        tools: [{
            id:'plus',
            handler: function(event, toolEl, panel){
                this.configItemTree.expandAll();
            },
            scope: this
        },{
            id:'minus',
            handler: function(event, toolEl, panel){
                this.configItemTree.collapseAll();
            },
            scope: this
        }],
 		root:new Ext.tree.AsyncTreeNode({leaf:false,expanded:true,text: rootNodeName,id: '0'})
  	});

    this.configItemTree.loader.on("beforeload", function(treeLoader, node) {
        treeLoader.baseParams.currentConfigItemId = this.currentConfigItemId;
        treeLoader.baseParams.configItemTypeId = this.configItemTypeId;
    }, this);

  	this.configItemTree.on('click',function(node){
        //configItemClickedCallback(node.id, node.text);
        this.selectedConfigItemId = node.id;
        this.selectedConfigItemName = node.text;
  	}, this);



    VPConfigItemSelectorPanel.superclass.constructor.call(this, {
        /*id:'vpconfigitemselectorpanel',*/
        /*title: 'Config item selector',*/
        layout:'fit',        
        closable: true,
        hideMode:'offsets',
        items: this.configItemTree
    });

}

Ext.extend(VPConfigItemSelectorPanel, Ext.Panel, {
    getSelectedConfigItemId : function() {
        return this.selectedConfigItemId;
    },

    getSelectedConfigItemName : function() {        
        return this.selectedConfigItemName;
    }
});

Ext.reg('vpconfigitemselectorpanel', VPConfigItemSelectorPanel);

Ext.ux.StaticTextField = Ext.extend(Ext.form.TextField, {
    fieldClass: 'x-static-text-field',

    onRender: function() {
        this.readOnly = true;
        this.disabled = !this.initialConfig.submitValue;
        Ext.ux.StaticTextField.superclass.onRender.apply(this, arguments);
    }
});

Ext.reg('statictextfield', Ext.ux.StaticTextField);


//================================
// Base64
//================================

var END_OF_INPUT = -1;

var base64Chars = new Array(
    'A','B','C','D','E','F','G','H',
    'I','J','K','L','M','N','O','P',
    'Q','R','S','T','U','V','W','X',
    'Y','Z','a','b','c','d','e','f',
    'g','h','i','j','k','l','m','n',
    'o','p','q','r','s','t','u','v',
    'w','x','y','z','0','1','2','3',
    '4','5','6','7','8','9','+','/'
);

var reverseBase64Chars = new Array();
for (var i=0; i < base64Chars.length; i++){
    reverseBase64Chars[base64Chars[i]] = i;
}

var base64Str;
var base64Count;
function setBase64Str(str){
    base64Str = str;
    base64Count = 0;
}
function readBase64(){
    if (!base64Str) return END_OF_INPUT;
    if (base64Count >= base64Str.length) return END_OF_INPUT;
    var c = base64Str.charCodeAt(base64Count) & 0xff;
    base64Count++;
    return c;
}
function encodeBase64(str){
    setBase64Str(str);
    var result = '';
    var inBuffer = new Array(3);
    var lineCount = 0;
    var done = false;
    while (!done && (inBuffer[0] = readBase64()) != END_OF_INPUT){
        inBuffer[1] = readBase64();
        inBuffer[2] = readBase64();
        result += (base64Chars[ inBuffer[0] >> 2 ]);
        if (inBuffer[1] != END_OF_INPUT){
            result += (base64Chars [(( inBuffer[0] << 4 ) & 0x30) | (inBuffer[1] >> 4) ]);
            if (inBuffer[2] != END_OF_INPUT){
                result += (base64Chars [((inBuffer[1] << 2) & 0x3c) | (inBuffer[2] >> 6) ]);
                result += (base64Chars [inBuffer[2] & 0x3F]);
            } else {
                result += (base64Chars [((inBuffer[1] << 2) & 0x3c)]);
                result += ('=');
                done = true;
            }
        } else {
            result += (base64Chars [(( inBuffer[0] << 4 ) & 0x30)]);
            result += ('=');
            result += ('=');
            done = true;
        }
        lineCount += 4;
        if (lineCount >= 76){
            result += ('\n');
            lineCount = 0;
        }
    }
    return result;
}
function readReverseBase64(){
    if (!base64Str) return END_OF_INPUT;
    while (true){
        if (base64Count >= base64Str.length) return END_OF_INPUT;
        var nextCharacter = base64Str.charAt(base64Count);
        base64Count++;
        if (reverseBase64Chars[nextCharacter]){
            return reverseBase64Chars[nextCharacter];
        }
        if (nextCharacter == 'A') return 0;
    }
    return END_OF_INPUT;
}

function ntos(n){
    n=n.toString(16);
    if (n.length == 1) n="0"+n;
    n="%"+n;
    return unescape(n);
}

function decodeBase64(str){
    setBase64Str(str);
    var result = "";
    var inBuffer = new Array(4);
    var done = false;
    while (!done && (inBuffer[0] = readReverseBase64()) != END_OF_INPUT
        && (inBuffer[1] = readReverseBase64()) != END_OF_INPUT){
        inBuffer[2] = readReverseBase64();
        inBuffer[3] = readReverseBase64();
        result += ntos((((inBuffer[0] << 2) & 0xff)| inBuffer[1] >> 4));
        if (inBuffer[2] != END_OF_INPUT){
            result +=  ntos((((inBuffer[1] << 4) & 0xff)| inBuffer[2] >> 2));
            if (inBuffer[3] != END_OF_INPUT){
                result +=  ntos((((inBuffer[2] << 6)  & 0xff) | inBuffer[3]));
            } else {
                done = true;
            }
        } else {
            done = true;
        }
    }
    return result;
}



Ext.ux.TwinTriggerCombo = Ext.extend(Ext.form.ComboBox, {
    initComponent: function() {
        this.triggerConfig = {
            tag:'span', cls:'x-form-twin-triggers', cn:[
                {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger1Class},
                {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger " + this.trigger2Class}
            ]};
        this.onTrigger2Click = this.onTrigger2Click.createInterceptor(function() {
            this.collapse();
        });
        Ext.ux.TwinTriggerCombo.superclass.initComponent.call(this);
    },
    getTrigger: Ext.form.TwinTriggerField.prototype.getTrigger,
    initTrigger: Ext.form.TwinTriggerField.prototype.initTrigger,
    onTrigger1Click: Ext.form.ComboBox.prototype.onTriggerClick,
    trigger1Class: Ext.form.ComboBox.prototype.triggerClass
});

Ext.reg('combotrigger',Ext.ux.TwinTriggerCombo);

Ext.ns('VisionProject');


//http://www.sencha.com/forum/showthread.php?44199-2.2-CheckboxGroup-Struggling-with-item-search/page3
// add type flag to RadioGroup
Ext.override(Ext.form.RadioGroup, {
    //private
    isRadioGroup: true
});

// add type flag to CheckboxGroup
Ext.override(Ext.form.CheckboxGroup, {
    //private
    isCheckboxGroup: true
});

//Override for finding fields in checkboxgroups or radiogroups
Ext.override(Ext.BasicForm, {
    findField: function(id) {
        var field = this.items.get(id);

        if (!Ext.isObject(field)) {
            //searches for the field corresponding to the given id. Used recursively for composite fields
            var findMatchingField = function(f) {
                if (f.isFormField) {
                    if (f.dataIndex == id || f.id == id || f.getName() == id) {
                        field = f;
                        return false;
                    } else if (f.isComposite && f.rendered) {
                        return f.items.each(findMatchingField);
                    } else if (f.isRadioGroup && f.rendered) {
                        return f.items.each(findMatchingField);
                    } else if (f.isCheckboxGroup && f.rendered) {
                        return f.items.each(findMatchingField);
                    }
                }
            };

            this.items.each(findMatchingField);
        }
        return field || null;
    }
});
// END //http://www.sencha.com/forum/showthread.php?44199-2.2-CheckboxGroup-Struggling-with-item-search/page3

function getDateTimeComponent(renderTo, fieldName, fieldValue, show12HourTime) {
    var tmpHiddenFormat;
    if (typeof(VPjavascriptDateFormat) == "undefined") {
        tmpHiddenFormat = parent.VPjavascriptDateFormat;
    } else {
        tmpHiddenFormat = VPjavascriptDateFormat;
    }
    var tmpDateFormat;
    if (typeof(VPjavascriptDateFormatDateOnly) == "undefined") {
        tmpDateFormat = parent.VPjavascriptDateFormatDateOnly;
    } else {
        tmpDateFormat = VPjavascriptDateFormatDateOnly;
    }
    return new Ext.ux.form.DateTime({
        name: fieldName,
        width: 249,
        timeConfig: {
            allowBlank:true
        },
        hiddenFormat: tmpHiddenFormat,
        dateFormat: tmpDateFormat,
        dateConfig: {
            allowBlank:true
        },
        timeFormat: show12HourTime ? 'h:i A' : 'H:i',
        renderTo: renderTo,
        value: fieldValue
    });
}
