//===========================================================
//  Interface
//===========================================================
api = {
    mouse:            {},
    screen:           {},
    hint:             {},
    ajax:             {},

    site_url:         "http://stranger/energy/",
    skin_set:         "1",
    error:            "",
    debug:            false,
    allow:            false,
    init:             null,

    getElementById:   null,
    getOffsetLeft:    null,
    getOffsetTop:     null,

    getCookie:        null,
    setCookie:        null,

    popup:            null,
    refresh:          null,

    applyClass:       null,
    disable:          null,
    enable:           null,

    prevous:          null,
    dateToString:     null,
    validateURL:      null
};

api.mouse = {
    posX:             0,
    posY:             0,
    cursor:           "default",
    lastButton:       0,

    disableLeftBtn:   false,
    disableRightBtn:  false
};

api.screen = {
    width:            0,
    height:           0
};

api.hint = {
    text:         "",
    init:         null,
    show:         null,
    hide:         null,

    allow:        false
};

api.ajax = {
    // Public
    debug:               false,
    error:               "",
    content:             {},
    resultHTML:          "",
    resultDOC:           null,

    init:                null,
    get:                 null,
    post:                null,

    // Private
    allow:               false,
    xmlReq:              null,

    newObject:           null,
    formattedPostData:   null
};

//===========================================================
//  Implementation
//===========================================================

api.init = function()
{
    this.screen.width  = screen.width;
    this.screen.height = screen.height;
    this.allow = true;
};

api.getElementById = function( id )
{
    itm = null;

    if ( kernel.document.getElementById ) itm = kernel.document.getElementById( id );
        else if ( kernel.document.all ) itm = kernel.document.all[ id ];
            else if ( kernel.document.layers ) itm = kernel.document.layers[ id ];

    return itm;
}

api.getOffsetLeft = function( elem, fStopOnAbsolute )
{
    if( !elem || elem == null )
    {
        if( this.debug ) alert( "API error (method getOffsetLeft): переданный элемент не найден или является null" );
        return;
    }

   var lLeftPixel = 0;
   var fSkipLast  = ( kernel.document.documentElement.dir == "rtl" );
   while(elem != null)
   {
	     var fIsAbsolute = ( elem.style.position == "absolute" );
  	   if( fSkipLast && elem.offsetParent == null ) break;
	     if( fIsAbsolute && fStopOnAbsolute ) break;
	     lLeftPixel += elem.offsetLeft;
	     elem = elem.offsetParent;
	     if( fIsAbsolute )
	     {
		       while(elem != null && elem.style.position != "absolute") elem = elem.offsetParent;
	     }
   }

   return lLeftPixel;
}

api.getOffsetTop = function( elem, fStopOnAbsolute )
{
    if( !elem || elem == null )
    {
        if( this.debug ) alert( "API error (method getOffsetTop): переданный элемент не найден или является null" );
        return;
    }

   var lTopPixel = 0;
   while(elem != null)
   {
  	   var fIsAbsolute = ( elem.style.position == "absolute" );
	     if( fIsAbsolute && fStopOnAbsolute ) break;
       lTopPixel += elem.offsetTop;
  	   elem = elem.offsetParent;
  	   if(fIsAbsolute)
	     {
		       while(elem != null && elem.style.position != "absolute") elem = elem.offsetParent;
	     }
   }
   return lTopPixel;
}


api.getCookie = function( name )
{
    var prefix = name + "=";
    var cookieStartIndex = kernel.document.cookie.indexOf( prefix );
    if ( cookieStartIndex == -1 ) return null;
    var cookieEndIndex = kernel.document.cookie.indexOf( ";", cookieStartIndex + prefix.length );
    if ( cookieEndIndex == -1 ) cookieEndIndex = document.cookie.length;
    return unescape( kernel.document.cookie.substring( cookieStartIndex + prefix.length, cookieEndIndex ) );
}

api.setCookie = function( name, value, sticky )
{
  expire = "";
  domain = "";
  path   = "/";
  if ( sticky )
    expire = "; expires=Wed, 1 Jan 2050 00:00:00 GMT";
  kernel.document.cookie = name + "=" + value + "; " + expire +  ";";
}

api.popup = function( url, name, width, height, center, resize, scroll, posleft, postop )
{
	showx = "";
	showy = "";
	if( posleft != 0 )
	{
		X = posleft
	}
	if( postop != 0 )
	{
		Y = postop
	}
	if( !scroll )
	{
		scroll = 1
	}
	if( !resize )
	{
		resize = 1
	}
	if( ( parseInt( navigator.appVersion ) >= 4 ) && ( center ) )
	{
		X = ( screen.width - width ) / 2;
		Y = ( screen.height - height ) / 2;
	}
	if( X > 0 )
	{
		showx = ',left=' + X;
	}
	if( Y > 0 )
	{
		showy = ',top=' + Y;
	}
	if( scroll != 0 )
	{
		scroll = 1
	}
	var Win = window.open( url, name, 'width=' + width + ',height=' + height + showx + showy + ',resizable=' + resize + ',scrollbars=' + scroll + ',location=no,directories=no,status=no,menubar=no,toolbar=no' );
};

api.refresh = function( oWindow )
{
  if( !oWindow || oWindow == null ) oWindow = kernel.document;
	oWindow.location = oWindow.location;
}

api.applyClass = function( className, el, id )
{
    if( !el || el == null )
    {
        el = api.getElementById( id );
        if( !el || el == null )
        {
            if( this.debug ) alert( "API error (method apllyClass): переданный элемент не найден или является null" );
            return;
        }
    }
    try
    {
        el.className = className;
    }
    catch(e)
    {
        this.error = e.toString();
        if( this.debug ) alert( "API error (method applyClass): " + this.error );
    }
};

api.disable = function( el, id )
{
    if( !el || el == null )
    {
        el = api.getElementById( id );
        if( !el || el == null )
        {
            if( this.debug ) alert( "API error (method disable): переданный элемент не найден или является null" );
            return;
        }
    }
    try
    {
        el.disabled = true;
    }
    catch(e)
    {
        this.error = e.toString();
        if( this.debug ) alert( "API error (method disable): " + this.error );
    }
};

api.enable = function( el, id )
{
    if( !el || el == null )
    {
        el = api.getElementById( id );
        if( !el || el == null )
        {
            if( this.debug ) alert( "API error (method enable): переданный элемент не найден или является null" );
            return;
        }
    }
    try
    {
        el.disabled = false;
        if( this.debug ) alert( "API error (method enable): " + this.error );
    }
    catch(e)
    {
        this.error = e.toString();
    }
};

api.prevous = function()
{
    history.back();
};

api.dateToString = function( ndate )
{
    if( !ndate || ndate == null ) ndate = new Date();
    var d = new Date( ndate );
    var s = d.toLocaleString();

    return s;
};

api.validateURL = function( strURL, str404URL )
{
  	var reValidURL = new RegExp( "^(hcp:|http:|https:|file:|ms-its:)", "i" );
	  if( reValidURL.test( strURL ) )
	  {
		    return strURL;
	  }
	  else
	  {
	      if( !str404URL || str404URL == null ) str404URL = "http://unknown.url";
	    	return str404URL;
  	}
};

//===========================================================
//  Hint
//===========================================================

api.hint.init = function()
{
    if( this.allow ) return true;

    var HTML = "";
    HTML += "<style>";
    HTML += ".hint_canvas { background-color: #E7E4D4; border-left: #999999 1px solid; border-top: #999999 1px solid; border-right: #111111 1px solid; border-bottom: #111111 1px solid; font-family: Verdana, Tahoma; font-size: 8pt; color: #000000; position: absolute; display: none; visibility: hidden; padding: 3px 5px 3px 5px; }";
    // HTML += ".hint_canvas { background-color: #c7eefc; border: #000000 1px solid; font-family: Tahoma; font-size: 8pt; color: #000000; position: absolute; display: none; visibility: hidden; padding: 1px 2px 2px 2px; }";
    HTML += "</style>";
    HTML += "<div class='hint_canvas' id='java_hint_container' name='java_hint_container'>&nbsp;</div>";

    kernel.echo( HTML );

    this.allow = true;
    return true;
};

api.hint.show = function( text, align )
{
    if( !this.allow ) return;
    var oHint = api.getElementById( "java_hint_container" );
    if( typeof oHint == 'undefined' )
    {
        this.allow = false;
        return;
    }

    if( !align || align == null || ( align != 'left' && align != 'right' ) ) align = 'left';
    this.align = align;

    if( !text || text == null ) text = this.text;
    this.text = text;
    oHint.innerHTML = text;
    oHint.style.display = "inline";
    if( align == 'left' )  oHint.style.left = ( api.mouse.posX + 16 ) + "px";
    if( align == 'right' ) oHint.style.left = ( api.mouse.posX - 16 - parseInt( oHint.offsetWidth ) ) + "px";
    oHint.style.top =  ( api.mouse.posY + 16 ) + "px";
    oHint.style.visibility = "visible";
};

api.hint.hide = function()
{
    if( !this.allow ) return;
    var oHint = api.getElementById( "java_hint_container" );
    if( typeof oHint == 'undefined' )
    {
        this.allow = false;
        return;
    }
    oHint.style.display = "none";
    oHint.style.visibility = "hidden";
};

//===========================================================
//  AJAX
//===========================================================
//------------------------------------------
//  Create a new ajax object
//------------------------------------------
api.ajax.newObject = function()
{
	var xmlReq = false;
	if ( !xmlReq && typeof XMLHttpRequest != 'undefined' )
	{
		try
		{
			xmlReq = new XMLHttpRequest();
		}
		catch(e)
		{
			xmlReq=false;
		}
	}
	if ( !xmlReq && window.ActiveXObject )
	{
		try
		{
			xmlReq = new ActiveXObject( ( navigator.userAgent.toLowerCase().indexOf( 'msie 5' ) != -1 ) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP' );
		}
		catch(e)
		{
			xmlReq=false;
			this.error = e.toString();
            if( this.debug ) alert( "Ajax Error: " + this.error );
		}
	}
	return xmlReq;
};

//------------------------------------------
//  Compile content array to post formated
//  string and translate russian characters
//------------------------------------------
api.ajax.formattedPostData = function()
{
    var data = "";
    for( var i in this.content )
    {
        data += i + "=" + escape( this.content[i] ) + "&";
    }
    return data;
};

api.ajax.init = function()
{
    if( this.allow )
    {
        if( this.debug ) alert( "Ajax Warning: class always was inited." );
        return true;
    }
    this.xmlReq = this.newObject();
    if( !this.xmlReq || this.xmlReq == null ) return false;

    this.allow = true;
    return true;
};

//------------------------------------------
//  Send GET method request to selected url.
//  Return boolean value of request result
//------------------------------------------
api.ajax.get = function( url )
{
    if( !this.allow )
    {
        if( this.debug ) alert( "Ajax error: use post method before class initing." );
        return false;
    }

    // Try to connect to url
    try
    {
        this.xmlReq.open( 'GET', url, false );
    }
    catch(e)
    {
        this.error = e.toString();
        if( this.debug ) alert( "Ajax error (open): " + this.error );
        return false;
    }

    // Try to send request to url
    try
    {
        this.xmlReq.send( null );
    }
    catch(e)
    {
        this.error = e.toString();
        if( this.debug ) alert( "Ajax error (send): " + this.error );
        return false;
    }

    // Store request result
    this.resultHTML = this.xmlReq.responseText;
    if( this.debug )
    {
        if( !this.resultHTML || this.resultHTML == null ) alert( "Ajax warning: request return empty page." );
    }
    this.resultDOC = this.xmlReq;
    return true;
};

//------------------------------------------
//  Send POST method request to selected url.
//  Return boolean value of request result
//------------------------------------------
api.ajax.post = function( url )
{
    if( !this.allow )
    {
        if( this.debug ) alert( "Ajax error: use post method before class initing." );
        return false;
    }

    var data = this.formattedPostData( this.content );

    // Try to connect to url
    try
    {
        this.xmlReq.open( 'POST', url, false );
    }
    catch(e)
    {
        this.error = e.toString();
        if( this.debug ) alert( "Ajax error (open): " + this.error );
        return false;
    }

    // Try to send headers to url
    try
    {
        this.xmlReq.setRequestHeader( "Content-type", "application/x-www-form-urlencoded;" );
        this.xmlReq.setRequestHeader( "Content-length", data.length );
        this.xmlReq.setRequestHeader( "Connection", "close" );
    }
    catch(e)
    {
        this.error = e.toString();
        if( this.debug ) alert( "Ajax error (header): " + this.error );
        return false;
    }

    // Try to send request to url
    try
    {
        this.xmlReq.send( data );
    }
    catch(e)
    {
        this.error = e.toString();
        if( this.debug ) alert( "Ajax error (send): " + this.error );
        return false;
    }

    // Store request result
    this.resultHTML = this.xmlReq.responseText;
    if( this.debug )
    {
        if( !this.resultHTML || this.resultHTML == null ) alert( "Ajax warning: request return empty page." );
    }
    this.resultDOC = this.xmlReq;
    return true;
};

//===========================================================
//  Processors
//===========================================================

function api_onMouseMove(e)
{
    if( !api.allow ) return;

    var tempX = 0;
    var tempY = 0;

    if( kernel.is_ie )
    {
        tempX = event.clientX + kernel.document.body.scrollLeft;
        tempY = event.clientY + kernel.document.body.scrollTop;
    }
    else
    {
        tempX = e.pageX;
        tempY = e.pageY;
	  }

    if( tempX < 0 ) tempX = 0;
    if( tempY < 0 ) tempY = 0;

    api.mouse.posX = tempX;
    api.mouse.posY = tempY;
};

function api_onClick(e)
{
    if( !api.allow ) return;
    api.mouse.lastButton = event.button;
    if( api.mouse.disableLeftBtn && api.mouse.lastButton == 0 )
    {
        alert( "API warning: левая кнопка мыши была отключена для данной страницы" );
        return false;
    }
    if( api.mouse.disableRightBtn && api.mouse.lastButton == 2 )
    {
        alert( "API warning: правая кнопка мыши была отключена для данной страницы" );
        return false;
    }
};

function hint_onMouseMove(e)
{
    if( !api.hint.allow ) return;
    var oHint = api.getElementById( "java_hint_container" );
    if( typeof oHint == 'undefined' ) return;
    if( oHint.style.display == 'none' ) return;

    if( api.hint.align == 'right' )
    {
        oHint.style.left = ( api.mouse.posX - 8 - parseInt( oHint.offsetWidth ) ) + "px";
    }
    else
    {
        oHint.style.left = ( api.mouse.posX + 16 ) + "px";
    }
    oHint.style.top =  ( api.mouse.posY + 16 ) + "px";
};

function hint_onMouseDown(e)
{
    if( !api.hint.allow ) return;
    api.hint.hide();
};

//===========================================================
//  Fast init
//===========================================================

kernel.onMouseMove['api'] = api_onMouseMove;
kernel.onClick['api'] = api_onClick;
api.init();

kernel.onMouseMove['hint'] = hint_onMouseMove;
kernel.onMouseDown['hint'] = hint_onMouseDown;
api.hint.init();

api.ajax.init();
