// HTML DOM helpers
// (c) SimX Corp. 2010

if( !basic_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);

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 = {
        wnd : null,
        checkOpen : function() {
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 storeSinfo( sinfo )
{
    try {
        if( !ua.ie && window.sessionStorage )
            sessionStorage.setItem( "sinfo", sinfo );
        else
            top.name = sinfo;
    }
    catch( e ) {
        console.error("restoreSinfo() exception: " + e + "." );
    }
}

function restoreSinfo()
{
    try {
        if( !ua.ie && window.sessionStorage ) {
            var sinfo = sessionStorage.getItem( "sinfo" );
            if( sinfo ) return sinfo;
        }
        return top.name;
    }
    catch( e ) {
        console.error("restoreSinfo() exception: " + e + "." );
    }
    return "";
}

try {
    if( !navigator.cookieEnabled ) {
        alert("This site requires cookies to be enabled to work properly.");
    }
    if( sinfo_value ) {
        var sinfo_shouldbe = sinfo_value;
        var olds_cookie_name = "";
        
        if( window.sinfo_cookie ) {
            olds_cookie_name = window.sinfo_cookie;
            olds_cookie_name.replace( /sinfo/, "olds" );
        }        
        
        if( !ua.op && document.cookie.indexOf( olds_cookie_name ) < 0 ) {
            console.error("The 'olds' cookie is not defined. This should never be.");
            setCookie( "olds_cookie_name", "true" );
            storeSinfo( sinfo_shouldbe );
        }
        else {
            var  stored_sinfo = restoreSinfo();
            if( !stored_sinfo || stored_sinfo.indexOf( sinfo_shouldbe ) < 0 ) {
                if( window.force_sinfo && force_sinfo == 'true' ) {
                    storeSinfo( sinfo_shouldbe );
                    console.info("Server session forced: " + sinfo_shouldbe + "." );
                }
                else {
                    window.status = "";
                    if( document.cookie.indexOf( "split_" ) >= 0 )
                        console.error("session conflict!!!");
                    console.info("View was with session: '" + stored_sinfo + "'. Content with session: '" + sinfo_shouldbe + "'. reload" );
                    var cur_date = new Date();
                    cur_date.setSeconds( cur_date.getSeconds() + 2 );
                    if( !stored_sinfo || stored_sinfo == "" || !/SID_[\w]{16,96}/.test(stored_sinfo) ) {
                        setCookie( "split_" + sinfo_shouldbe, "TRUE", cur_date );
                        cur_date.setDate( cur_date.getDate() + 30 );
                        setCookie( window.sinfo_cookie, sinfo_shouldbe, cur_date );
                    }
                    else {
                        var ow_sfx_pos = stored_sinfo.indexOf( "_ow" )
                        if( ow_sfx_pos > 10 )
                            stored_sinfo = stored_sinfo.substr( 0, ow_sfx_pos );
                        setCookie( "split_" + stored_sinfo, sinfo_shouldbe, cur_date );
                        cur_date.setDate( cur_date.getDate() + 30 );
                        setCookie( window.sinfo_cookie, stored_sinfo, cur_date );
                    }
                    location.reload( true );
                }
            }
            else
                console.info("session seems as it should: " + sinfo_shouldbe + "." );
        }
        setCookie( "olds", "true" );
    }
} catch( e ) {
    alert( "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 )
{
    Sbt( { f:form_name, h:out_ctrl, t:trg_name, r:recid, e:ext_str, b:flags, c:cnf, d:pb_delay });
}

function Sbt( submit_struct ) {
    if( submit_struct.b & 0x80 && submit_struct.c && submit_struct.c.length && !window.confirm( submit_struct.c ) ) return false;
    if( window.event ) event.cancelBubble = true;

    var pgform = document.forms[submit_struct.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;
    }
    
    window.status = "Producing a data request to the server. please wait...";
    document.body.style.cursor='wait';
    
    
    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 = submit_struct.b & 2; // SUBMIT_SECURE
    if( ssl ) {
        if( URL_string.indexOf( "http://" ) == 0 )
            URL_string = "https://" + URL_string.substr( 7 );
    }


    pgform.action = URL_string;
    pgform.sbmctr.value = submit_struct.h ? submit_struct.h : "";
    pgform.recid.value = submit_struct.r ? submit_struct.r : "";

    if( submit_struct.e && submit_struct.t && submit_struct.t.length && submit_struct.t != '_self' &&
        ( !page_name || submit_struct.t != page_name ) &&
        top.frames[submit_struct.t] && submit_struct.e.substring(0, 4) == 'http' ) {
        top.frames[submit_struct.t].location = submit_struct.e;
        submit_struct.t = '';
    }
    else
        pgform.extra.value=submit_struct.e ? submit_struct.e : '';

    if( typeof submit_struct.d == 'undefined' ) submit_struct.d = 1000;

    if( !submit_only &&
        typeof DynamicUpdate != 'undefined' &&
               DynamicUpdate( pgform, submit_struct.t, ssl, submit_struct.b, null, submit_struct.d, submit_struct.p ) ) {
        if( submit_struct.b & 0x200 )
            window.closeParent( submit_struct.o );
        return;
    }
    pgform.cmode.value = "1";
    if( submit_struct.b & 0x40 ) pgform.sp.value="1";    // SUBMIT_SAFEPOST
    RealSubmit( pgform, submit_struct.t, submit_struct.p );
    if( submit_struct.b & 0x200 )
        window.closeParent( submit_struct.o );
    return;
}

function PrepareForParams( url )
{
    var lc = url.charAt( url.length-1 );
    if( lc == '?' || lc == '&' ) return url;
    return url + ( url.indexOf( '?' ) < 0 ? '?' : '&' );
}

function RealSubmit( 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 GetXPos( o )
{
    return o.offsetLeft;
}

function SetXPos( o, x )
{
    o.style.left = x;
}

function GetYPos( o )
{
    return o.offsetTop;
}

function SetYPos( o, y )
{
    o.style.top = 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;
}


function GetWidth(o)
{
    return o.offsetWidth;
}

function SetWidth(o,w)
{
    o.style.width=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()
{
    for( var u in updates) {
        if( typeof updates[u] == 'function' ) {
            try {
//                if(p) p.out('refreshing control ' + u);
                updates[u]();
            }
            catch( e ) {
                window.status = e;
            }
        }
    }
}

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;
                    }
                }
            }
// IE7 itself is a top frame for its opened tabs. In favor of Nikita's blocking subsystem this code was disabled.
            if( top_target_frame.Update )
                top_target_frame.Update(model_list, document.forms[0].name);
            if( window.opener && window.opener.Update )
                window.opener.Update( model_list, document.forms[0].name );
        }
    } catch( e ) {
        window.status = e;
        console.error();
    }
    progress_image = new Image();
    progress_image.src='/Target/WebResources/progress.gif';
    if( typeof Custom != "undefined" ) Custom();
}

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 submit_only = 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 basic_loaded = true;

//document.write("<input type='button' value='show cookies' onclick='alert(\"cookie: \"+document.cookie+\", stored sinfo: \"+restoreSinfo());'");

}
