// HTML DOM helpers
// (c) SimX Corp. 2010

if( !base_loaded ) {

var ua = navigator;
var a = ua.userAgent;
ua.op  = window.opera?true:false;
ua.wk  = /WebKit/i.test(a);
ua.ie  = !ua.wk && !ua.op && (/MSIE/gi).test(a) && (/Explorer/gi).test(ua.appName);
if( !ua.ie && !window.event ) window.event = {};

Date.prototype.format = function() {
    var m = this.getMonth()+1;
    var d = this.getDate();
    var H = this.getHours();
    var M = this.getMinutes();
    var S = this.getSeconds()
    var ms = this.getMilliseconds()
    return "" + (m<10?"0":"") + m + "/" + (d<10?"0":"") + d + "/" + this.getFullYear() + " " + (H<10?"0":"") + H + ":" + (M<10?"0":"") + M + ":" + (S<10?"0":"") + S + "." + (ms<10?"00":ms<100?"0":"") + ms;
}

function getCookie( cname ) {
    var cookies = document.cookie.split("; ");
    for( c in cookies ) {
        var nv = cookies[c].split("=");
        if(nv[0] == cname )
            return nv[1];
    }
    return null;
}

function setCookie( cname, cval, edate ) {
    document.cookie = ( cname + "=" + cval + "; path=/;" + 
     ( typeof edate == "object" && edate.toGMTString ? " expires=" + edate.toGMTString() : "" ) );
}

if( ua.op ) {
    if( window.blkunk ) {
        alert("This site is not compatable with the Opera browser. Please use Internet Explorer or FireFox to access to this site.");
        location.replace('http://www.mozilla.com/firefox');
        throw 0;
    }
    else
    if( !getCookie("OPchk") ) {
        alert("This site is not fully compatable with the Opera browser. Please consider to use Internet Explorer or FireFox to access to this site.");

        var date = new Date();
        date.setDate( date.getDate() + 1 )
        setCookie( "OPchk", "done", date );
    }
}
else {
    var ff_ver_a = navigator.userAgent.match(/Firefox\/(\d.[^\ \.]+)/);
    if( ff_ver_a && ff_ver_a.length > 1 && parseFloat(ff_ver_a[1]) < 3.5 ) {
            if( window.blkunk ) {
                alert("This site is not compatable with this outdated FireFox browser. Please update FireFox to access to this site.");
                location.replace('http://www.mozilla.com/firefox');
                throw 0;
            }
            else
            if( !getCookie("FFchk") ) {
                alert("This site requires Firefox version 3.5 and newer. Please upgrade your browser.");
                var date = new Date();
                date.setDate( date.getDate() + 1 )
                setCookie( "FFchk", "done", date );
        }
    }
}

if( document.getElementById ) {
    var GetElem = function( id ) {
        return document.getElementById( id );
    }
    var GetElemsOf = function( obj, tag_name ) {
        return obj.getElementsByTagName( tag_name );
    }
}
else
if( document.all ) {
    var GetElem = function( id ) {
        return document.all[ id ];
    }
    var GetElemsOf = function( obj, tag_name ) {
        return obj.all.tags( tag_name );
    }
}
else {
    var GetElem = function( id ) {
        return document.forms[ 0 ].elements[ id ]; // Warning! For controls only!
    }
    var GetElemsOf = function( obj, tag_name ) {
        return null;
    }
}

function Elem( friendly_name )
{
    if( name_map )
        return GetElem( name_map[friendly_name] );
}

if( typeof loadFirebugConsole == 'function' ) loadFirebugConsole();
else
if( !window.console ) {
    window.console = {
        enable : getCookie( "console" ) ? true : false,
        on : function() { setCookie( "console", "on" ); console.enable=true; alert("Console enabled"); },
        wnd : null,
        checkOpen : function() {
            if( !this.enable ) return false;
            if( !this.wnd || this.wnd.closed ) {
             this.wnd = window.open( "", "Console", "width=600,height=800,scrollbars=yes,resizable=yes" );
             if( this.wnd )
                 this.wnd.document.writeln( "<div>" );
            }
            return this.wnd;
        },
        info : function(s) {
            if( !this.checkOpen() ) return;
            this.wnd.document.writeln( "<pre style='margin:0px;'>"+s+"</pre>" );
            this.wnd.scrollTo(0,9999999);
        },
        error : function(s) {
            if( !this.checkOpen() ) return;
            this.wnd.document.writeln( "<pre style='margin:0px; color: red;'>"+s+"</pre>" );
        },
        warn : function(s) {
            if( !this.checkOpen() ) return;
            this.wnd.document.writeln( "<pre style='margin:0px; color: orange;'>"+s+"</pre>" );
        },
        time : function(s) {},
        timeEnd : function(s) {},
        profile : function(s) {},
        profileEnd : function(s) {}
    }
}

function L( errlvl, descr, level ) {
    this.begin_at = new Date();
    this.level = level;
    this.children = [];
    this.duration = 0;
    this.errlevel = errlvl;
    this.descript = descr;
}

L.stack = [];

L.prototype.add = function( c ) {
    this.children.push( c );
}

L.prototype.finish = function() {
    this.duration = new Date().valueOf() - this.begin_at.valueOf();
}

L.prototype.toCSV = function( csva ) {
    var f = [];
    var d = this.begin_at;
    f.push( (d.getMonth()+1) + "/" + d.getDate() + "/" + d.getYear() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds() + "." + d.getMilliseconds() );
    f.push( this.duration );
    f.push( this.level );
    f.push( this.errlevel );
    f.push( this.descript );
    csva.push( f.join( ", " ) );
    for( var c in this.children )
        this.children[c].toCSV( csva );
}

L.Beg = function( descr, first ) {
    if( !p ) return;
    if( first ) L.stack.length = 0;
    var l = L.stack.length;
    var e = new L( 0, descr, l );
    if( l ) L.stack[l-1].add( e );
    L.stack.push( e );
}

L.INFO = 0;
L.WARN = 1;
L.ERROR = 2;
L.FATAL = 3;
L.Ev = function( msg, errlvl ) {
    if( !p ) return;
    var l = L.stack.length;
    if( l ) L.stack[l-1].add( new L( errlvl?errlvl:0, msg, l ) );
}

L.End = function( send ) {
    if( !p ) return;
    var e = L.stack.pop();
    if( e ) {
        e.finish();
        if( send ) {
            var a = [];
            if( L.stack.length ) e = L.stack[0];
            e.toCSV( a );
            //alert( "csv:\n" + a.join( "\n" ) );
            L.Send( a );
        }
    }
}

L.Send = function( a ) {
    try {
        var xmlhttp = createXMLHTTP();
        var url = location.pathname;
	    xmlhttp.open("POST", location.protocol + "//" + location.host + document.location.pathname + "?updateclientlog", false );
	    xmlhttp.setRequestHeader("Content-Type","text/csv");
	    xmlhttp.send( a.join( "\n" ) );
    }
    catch( e ) {
        ShowException( e );
    }
}

function ShowException( e ) {
    var msg = [];
    if( e.name ) { msg.push( e.name ); }
    msg.push( " Exception occured:\n" );
    if( e.message )    { msg.push( e.message ); } else
    if( e.description ){ msg.push( e.description ); }
    if( e.lineNumber ) { msg.push( "\nLine number: " ); msg.push( e.lineNumber );  }
    if( e.fileName )   { msg.push( "\nFile name: " ); msg.push( e.fileName );  }
    var s = msg.join( "" );
    if( p ) L.Ev( s.replace( "\n", ";" ) );
    alert( s );
}

function storeSinfo( sinfo )
{
    try {
        if( !ua.ie && window.sessionStorage )
            sessionStorage.setItem( "sinfoSS", window.sinfo_cookie + "_" + sinfo );
        else
            top.name = window.sinfo_cookie + "_" + sinfo;
    }
    catch( e ) {
        console.error("storeSinfo() exception: " + e.message );
    }
}

function restoreSinfo()
{
    try {
        var stored = "";
        if( !ua.ie && window.sessionStorage ) {
            var sssi = sessionStorage.getItem( "sinfoSS" );
            if( sssi ) stored += sssi;
        }
        if( stored.length <= 0 )
    	    stored = top.name;
		if( !stored ) return null;
		var re = new RegExp( window.sinfo_cookie + "_" + "SID_[\\w]{10,50}" );
        if( !re.test( stored ) ) return null;
        return stored.substr( window.sinfo_cookie.length + 1 );
    }
    catch( e ) {
        console.error("restoreSinfo() exception: " + e.message );
    }
    return "";
}

function createXMLHTTP()
{
    if( window.ActiveXObject && document.implementation ) {
        try { return new ActiveXObject("Msxml2.XMLHTTP.4.0"); } catch(e) { }
        try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) { }
        try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) { }
    }
    if( window.XMLHttpRequest ) {
        var req = new XMLHttpRequest();
        if( req.overrideMimeType )
            req.overrideMimeType('text/xml');
        return req;
    }
    console.error("Unable to create an XML HTTP object;");
    return null;
}

function resolveProxyRec( wrongSinfo, split )
{
    try {
        var xhr = createXMLHTTP();
        var baseUrl = location.href.replace( /[?#].*/, "" );
        if( split )
            var urlToSend = baseUrl + "?sr_split=" + wrongSinfo;
        else
            var urlToSend = baseUrl + "?sr_forget=" + wrongSinfo;
        xhr.open("GET", urlToSend, false );
        xhr.send( null );
        if( split ) { 
            if( xhr.responseText.length > 30 ) {
                console.error( "Received unexpexted response on a sr_forget request:  " + xhr.responseText.substring( 0, 300 ) );
                return null;
            }
            else
                return xhr.responseText;
        }
        else {
            if( xhr.responseText == "FAIL" )
                console.error( "Forget calls for a proxyless record" );
        }
    }
    catch( e ) {
        console.error( "resolveProxyRec() exception: " + e.message );
    }
}

try {
    if( !navigator.cookieEnabled ) {
        alert("This site requires cookies to be enabled to work properly.");
    }

    var resp_id = getCookie( "resp_id" );
    if( window.resp_id != resp_id )
        console.error( "Slow down please!!!" );
    if( window.sinfo_value != null ) {
        var proxy_made  = window.no_proxy != "true";
        var force_sinfo = window.force_sinfo == "true";
        var sinfo_shouldbe = window.sinfo_value;
        var stored_sinfo = restoreSinfo();
        if( force_sinfo || proxy_made ) {
            var occ = sinfo_shouldbe == "";
            if( !stored_sinfo || occ || stored_sinfo.indexOf( sinfo_shouldbe ) < 0 ) {
            	if( force_sinfo ) {
                    storeSinfo( sinfo_shouldbe );
                    console.info("Server session forced: " + sinfo_shouldbe + "." );
                }
                else {
                    window.status = "";
                    console.info("View was with session: '" + stored_sinfo + "'. Content with session: '" + sinfo_shouldbe + "'. reload" );
                    if( window.popup && popup.length )
                        alert(popup);
                    var cur_date = new Date();
                    var this_sinfo = "";
                    cur_date.setSeconds( cur_date.getSeconds() + 2 );
                    if( !stored_sinfo || stored_sinfo == "" || !/SID_[\w]{10,50}/.test(stored_sinfo) ) {
                        if( !occ ) {
                            console.info("Split required! stored_sinfo='" + stored_sinfo + "'" );
                            this_sinfo = resolveProxyRec( sinfo_shouldbe, true ); // split
                            if( this_sinfo )
                                storeSinfo(this_sinfo);
                            else
                                throw new Error();
                        }
                    }
                    else {
                        if( !occ )
                            resolveProxyRec( sinfo_shouldbe, false )
                        var ow_sfx_pos = stored_sinfo.indexOf( "_ow" )
                        if( ow_sfx_pos > 10 )
                            stored_sinfo = stored_sinfo.substr( 0, ow_sfx_pos );
                        this_sinfo = stored_sinfo
                    }
                    cur_date.setDate( cur_date.getDate() + 30 );
                    var reload_func = function() { 
                        setCookie( window.sinfo_cookie, this_sinfo, cur_date ); location.reload( true ); 
                    }
                    if( occ )
                        setTimeout( reload_func, 3000 )
                    else
                        reload_func();
                }
            }
        } else if( !stored_sinfo || stored_sinfo == "" || !/SID_[\w]{10,50}/.test(stored_sinfo) ) {
            storeSinfo(sinfo_shouldbe); // this point for a frame in a frameset only
        }
    }
} catch( e ) {
    console.error( "Session exception: " + e.message );
}

function StopEvent( e )
{
    if( !e ) e = window.event;
    if( !e ) return;
    e.cancelBubble = true;
    if( e.stopPropagation ) e.stopPropagation();
}

function changeHandler( control_id, event )
{
    StopEvent( event );
    dirty_too[control_id]=true;
}

function Sbm( form_name, out_ctrl, trg_name, recid, ext_str, flags, cnf, pb_delay )
{
    // used from the table headers
    Sbt( { f:form_name, h:out_ctrl, t:trg_name, r:recid, e:ext_str, b:flags, c:cnf, d:pb_delay });
}

function Sbt( ss ) {
    if( ss.b & 0x80 && ss.c && ss.c.length ) {
        if( !window.confirm( ss.c ) )
            return false;
        else
            ss.c = null;
    }
    if( window.event ) event.cancelBubble = true;

    var pgform = document.forms[ss.f];
    if( !pgform ) pgform = document.forms[0];    // includes do not provide their form to avoid nesting

    if( !pgform ) {
        alert("Error on the page. HTML form is unknown. Please contact the site's administrator.");
        return;
    }
    if( !pgform.action ) {
        if( pgform.length > 0 )
            pgform = pgform[0];
        else
            return;
    }

    if( window.PreSubmit ) window.PreSubmit();
    
    var host_used = location.href.substr( 0, location.href.indexOf( '/', 8 ) );
    var form_path = pgform.action.substr( pgform.action.indexOf( '/', 8 ) )
    var URL_string = host_used + form_path;
    var ssl = ss.b & 2; // SUBMIT_SECURE
    if( ssl ) {
        if( URL_string.indexOf( "http://" ) == 0 )
            URL_string = "https://" + URL_string.substr( 7 );
    }
    if( !(ss.t && ss.t.length) && ss.h ) {
        window.status = "Producing a data request to the server. please wait...";
        document.body.style.cursor='wait';
    }
    pgform.action = URL_string;
    pgform.sbmctr.value = ss.h ? ss.h : "";
    pgform.recid.value = ss.r ? ss.r : "";

    if( ss.e && ss.t && ss.t.length && ss.t != '_self' &&
        ( !page_name || ss.t != page_name ) &&
        top.frames[ss.t] && ss.e.substring(0, 4) == 'http' ) {
        top.frames[ss.t].location = ss.e;
        ss.t = '';
    }
    else {
        pgform.extra.value=ss.e ? ss.e : '';
    }

    if( wait_timer ) 
        clearTimeout(wait_timer);
    if( typeof ss.d == 'undefined' ) ss.d = 1000;
    if( ss.h && ss.d && WaitMessage && !(ss.t && ss.t.length && ss.t != "_self") ) {
        if( ss.d < 100 ) WaitMessage(ss.c); else
            wait_timer = setTimeout( function() { wait_timer=0; WaitMessage(ss.c); }, ss.d );
    }

    // attention: trg_name==_self means switch to another component, but empty trg_name does not

    if( pgform.encoding != "multipart/form-data" && ( !ss.t || ss.t == '' ) &&
        typeof DynamicUpdate != 'undefined' &&
               DynamicUpdate( pgform, ssl, ss.b, null, ss.d, ss.p ) ) {
        if( ss.b & 0x200 )
            window.closeParent( ss.o );
        return;
    }
    pgform.cmode.value = ss.b & 0x40 ? "safe" : "full";

    FullSubmit( pgform, ss.t, ss.p );
    if( ss.b & 0x200 )
        window.closeParent( ss.o );
    return;
}

function PrepareForParams( url )
{
    var lc = url.charAt( url.length-1 );
    if( lc == '?' || lc == '&' ) return url;
    return url + ( url.indexOf( '?' ) < 0 ? '?' : '&' );
}

function FullSubmit( pgform, trg_name, custom_params )
{
    pgform.target = trg_name ? trg_name : "" ;
    var URL_string = PrepareForParams( pgform.action );
    if( trg_name == '' || trg_name == "_self" || ( custom_params && custom_params.length ) ) {
        URL_string += "comp="    + pgform.comp.value +
                      "&recid="  + pgform.recid.value +
                      "&uiinfo=" + pgform.uiinfo.value +
                      "&mvars="  + pgform.mvars.value +
                      "&extra="  + pgform.extra.value;
        if( custom_params && custom_params.length )
            URL_string += "&" + custom_params;
        if( /sinfo=/.test( location.search ) )
            URL_string += "&sinfo=" + pgform.sinfo.value;
        pgform.action = URL_string;
    } else {
        if( /sinfo=/.test( location.search ) )
            pgform.action = URL_string + "sinfo=" + pgform.sinfo.value;
    }
    pgform.submit();
}

function FindRecId( elem, iter_n, recid_n, iter )
{
    var pnt = elem.parentNode;
    if( !pnt ) return "";
    if( !pnt.id.indexOf( iter_n ) ) {
        var recid_id = recid_n + "_" + iter;
        var inputs = pnt.getElementsByTagName('INPUT');
        if( !inputs.length )
             inputs = document.getElementsByTagName('INPUT');
        for( var i = 0; i < inputs.length; i++ ) {
            if( inputs.item(i).id == recid_id  )
                return inputs.item(i).value;
        }
        return;
    }
    return FindRecId( pnt, iter_n, recid_n, iter );
}

function GetParent( from, tagName )
{
    var pnt = from.parentNode;
    if( !pnt ) return null;
    if( pnt.tagName.toUpperCase() == tagName )
        return pnt;
    return GetParent( pnt, tagName );
}

function AddClass(o,c)
{
    var class_names = o.className.split(/\s+/);
    for( n in class_names ) if(class_names[n]==c) return;
    o.className += " "+c;
}

function GetText(o)
{
    if( o.value ) return o.value;
    if( o.textContent ) return o.textContent;
    if( o.innerText ) return o.innerText;
    return null;
}

function SetText(o,t)
{
    if( o.value != null )
        o.value = t;
    else
    if( o.textContent != null )
        o.textContent = t;
    else
    if( o.innerText != null )
        o.innerText = t;
}

function Trim( s )
{
    try {
        if( s == null || typeof(s) != "string" || !s.length ) return "";
        if( s.trim ) return s.trim();
        return /^\s*(.*)\s*$/.exec(s)[1];
    }
    catch(e) {}
    return "";
}

function GetXPos( o )
{
    return o.offsetLeft;
}

function SetXPos( o, x )
{
    o.style.left = typeof(x) == "number" ? x + "px" : x;
}

function GetYPos( o )
{
    return o.offsetTop;
}

function SetYPos( o, y ) 
{
    o.style.top = typeof(y) == "number" ? y + "px" : y;
}

function GetPageXPos( o )
{
    var x=0;
    while(eval(o)) {
        x+=o.offsetLeft;
        o=o.offsetParent;
    }
    return x;
}

function GetPageYPos(o)
{
    var y=0;
    while(eval(o)) {
        y+=o.offsetTop;
        o=o.offsetParent;
    }
    return y;
}


function GetHeight(o)
{
    return o.offsetHeight;
}

function GetPageWidth()
{
    if(!ua.ie || ua.op) // all except Explorer
	    return window.innerWidth;
    else if (document.documentElement && document.documentElement.clientHeight) // Explorer 6 Strict Mode
	    return document.documentElement.clientWidth;
    else if (document.body) // other Explorers
	    return document.body.clientWidth;
}

function SetHeight(o,h) {
    o.style.height = h + "px";
}

function GetWidth(o)
{
    return o.offsetWidth;
}

function SetWidth(o,w)
{
    o.style.width = typeof(w)=="number" ? "" + w + "px" : w;
}

function GetPageHeight()
{
    if(!ua.ie || ua.op) // all except Explorer
	    return window.innerHeight;
    else if (document.documentElement && document.documentElement.clientHeight) // Explorer 6 Strict Mode
	    return document.documentElement.clientHeight;
    else if(document.body) // other Explorers
	    return document.body.clientHeight;
}

function GetXScroll()
{
    if(self.pageYOffset) // all except Explorer
	    return window.scrollX;
    else if(document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
	    return document.documentElement.scrollLeft;
    else if(document.body) // all other Explorers
	    return document.body.scrollLeft;
}

function GetYScroll()
{
    if(self.pageYOffset) // all except Explorer
	    return window.scrollY;
    else if(document.documentElement && document.documentElement.scrollTop) // Explorer 6 Strict
	    return document.documentElement.scrollTop;
    else if(document.body) // all other Explorers
	    return document.body.scrollTop;
}

function RefreshControls()
{
    try {
        L.Beg( "RefreshControls()" );
        for( var u in updates) {
            if( typeof updates[u] == 'function' ) {
                try {
    //                if(p) p.out('refreshing control ' + u);
                    updates[u]();
                }
                catch( e ) {
                    console.error("RefreshControls() exception: " + e.message );
                }
            }
        }
    } catch( e ) {
        ShowException( e );
    } finally {
        L.End();
    }
}

if( window.stat_string ) {
    window.p = true;
    L.Beg( stat_string, true );
}
else window.p = false;

onload = function()
{
    if( window.popup && popup.length )
        alert(popup);
    RefreshControls();
    try {
        if( window.model_list && model_list.length ) {
            var top_target_frame = top;
            if( !top.Update ) {
                for( var i=0; i< top.frames.length; i++ ) {
                    if( top.frames[i].Update ) {
                        top_target_frame = top.frames[i];
                        break;
                    }
                }
            }
            if( top_target_frame!= window && top_target_frame.Update )
                top_target_frame.Update(model_list, document.forms[0].name);
            if( window.opener && window.opener.Update && window.name.indexOf( "_ow", 15 ) > 15 )
                window.opener.Update( model_list, document.forms[0].name );
        }
    } catch( e ) {
        console.error("onload exception: " + e.message );
    }
    progress_image = new Image();
    progress_image.src='/Target/WebResources/rot.gif';
    if( typeof Custom != "undefined" ) Custom();

    L.End( true );
}

console.info( "<br>" + location.href + " is loading. Cookie: " + document.cookie );

var IsTrue = function( q ) { return q==true||q=="true"||q=='1'||q==1; }

function getImg(c) { return c.getElementsByTagName('img')[0]; }

var DataHolder = function( data ) {
    this.data = data;
    if( this.data ) this.data["disabled"]=this.data.getAttribute("disabled");
}
DataHolder.prototype.GetDataElem = function() { return this.data; }
DataHolder.prototype.set   = function(dirty) { if( this.data ) { this.data.value='1'; if( dirty ) changeHandler(this.data.id); } }
DataHolder.prototype.clear = function(dirty) { if( this.data ) { this.data.value='';  if( dirty ) changeHandler(this.data.id); } }
DataHolder.prototype.isOn = function() { return this.data?IsTrue(this.data.value):false; }
DataHolder.prototype.isDisabled = function() { return this.data?IsTrue(this.data.disabled ):false; }

var ctrl_drty = new Array;
var dirty_too = new Array;
var name_map  = new Array;
var varheight = new Array;
var offheight = new Array;
var recids  = new Array;
var models  = new Array;
var updates = new Array;
var ow = null;

var base_loaded = true;

}

