// auto | crosshair | default | pointer | move | e-resize | ne-resize | nw-resize | n-resize | se-resize | sw-resize | s-resize | w-resize| text | wait | help

var uagent    = navigator.userAgent.toLowerCase();
var is_safari = ((uagent.indexOf('safari') != -1) || (navigator.vendor == "Apple Computer, Inc."));
var is_opera  = (uagent.indexOf('opera') != -1);
var is_webtv  = (uagent.indexOf('webtv') != -1);
var is_ie     = ((uagent.indexOf('msie') != -1) && (!is_opera) && (!is_safari) && (!is_webtv));
var is_ie4    = ((is_ie) && (uagent.indexOf("msie 4.") != -1));
var is_moz    = ((navigator.product == 'Gecko')  && (!is_opera) && (!is_webtv) && (!is_safari));
var is_ns     = ((uagent.indexOf('compatible') == -1) && (uagent.indexOf('mozilla') != -1) && (!is_opera) && (!is_webtv) && (!is_safari));
var is_ns4    = ((is_ns) && (parseInt(navigator.appVersion) == 4));
var is_kon    = (uagent.indexOf('konqueror') != -1);
var ie        = document.all ? true : false;

var is_win    = ((uagent.indexOf("win") != -1) || (uagent.indexOf("16bit") !=- 1));
var is_mac    = ((uagent.indexOf("mac") != -1) || (navigator.vendor == "Apple Computer, Inc."));
var ua_vers   = parseInt(navigator.appVersion);

function $( id )
{
    itm = null;

    if ( document.getElementById ) itm = document.getElementById( id );
        else if ( document.all ) itm = document.all[ id ];
            else if ( document.layers ) itm = document.layers[ id ];

    return itm;
};


function $e( sourceObject, eventName, listener, paramsArray )
{
    if( is_ie || is_ie4 || ie )
    {
        sourceObject.attachEvent( "on" + eventName, listener );
    }
    else
    {
        sourceObject.addEventListener( eventName, listener, false );
    }
}

function $sv( id, text )
{
    var el = $( id );
    if( !el || el == null )
    {
        return;
    }
    el.value = text;
};


function $ol( el )
{
    if( !el || el == null )return 0;
    var ol = el.offsetLeft;
    while ( ( el = el.offsetParent ) != null ) ol += el.offsetLeft;
    return ol;
};


function $ot( el )
{
    if( !el || el == null )return 0;
    var ot = el.offsetTop;
    while( ( el = el.offsetParent ) != null ) ot += el.offsetTop;
    return ot;
};


function getCookie( name )
{
    var prefix = name + "=";
    var cookieStartIndex = document.cookie.indexOf( prefix );
    if ( cookieStartIndex == -1 ) return null;
    var cookieEndIndex = document.cookie.indexOf( ";", cookieStartIndex + prefix.length );
    if ( cookieEndIndex == -1 ) cookieEndIndex = document.cookie.length;
    return unescape( document.cookie.substring( cookieStartIndex + prefix.length, cookieEndIndex ) );
};


function setCookie( name, value, sticky )
{
  expire = "";
  domain = "";
  path   = "/";
  if ( sticky )
    expire = "; expires=Wed, 1 Jan 2050 00:00:00 GMT";
  document.cookie = name + "=" + value + "; " + expire +  ";";
};


function refresh( oWindow )
{
  if( !oWindow || oWindow == null ) oWindow = document;
	oWindow.location = oWindow.location;
};


function $ac( className, el, id )
{
    if( !el || el == null )
    {
        el = $( id ); if( !el || el == null ) return;
    }
    try
    {
        el.className = className;
    }
    catch(e)
    {
        this.error = e.message;
    }
};


function disable( el, id )
{
    if( !el || el == null )
    {
        el = $( id ); if( !el || el == null ) return;
    }
    try
    {
        el.disabled = true;
    }
    catch(e)
    {
        this.error = e.message;
    }
};


function enable( el, id )
{
    if( !el || el == null )
    {
        el = $( id ); if( !el || el == null ) return;
    }
    try
    {
        el.disabled = false;
    }
    catch(e)
    {
        this.error = e.toString();
    }
};


function prevous()
{
    history.back();
};


function validateURL( 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;
    }
};


makeGroup = function( _title, parent, width, height )
{
    width = parseInt( width );
    height = parseInt( height );

    var title = document.createElement('DIV');
    title.innerHTML = _title;
    title.style.width = ( width - 3 ) + 'px';
    title.style.padding = '3px';
    title.style.border = '#808080 1px solid';
    title.style.borderBottom = '0';
    title.style.textAlign = 'left';
    title.style.background = '#ffffff';
    parent.appendChild( title );

    var div = document.createElement('DIV');
    div.style.border = '#808080 1px solid';
    div.style.width = ( width - 7 ) + 'px';
    div.style.height = ( height - parseInt( title.offsetHeight ) ) + 'px';
    div.style.overflow = 'auto';
    div.style.padding = '5px';
    div.style.textAlign = 'left';
    parent.appendChild( div );
    return div;

};

//========================================================================
//                   Simple AJAX crossbrowser class
//========================================================================
/* -----------------------------------------------------------------------
                                INTERFACE
----------------------------------------------------------------------- */
ajax = {
    // PUBLIC DECLARATIONS
        // Variables
            url: '',
            method: 'post',
            async: false,
            events: {'Uninitialized':null,'Loading':null,'Loaded':null,'Interactive':null,'Complete':null},
            content: {},

            resultHTML: "",
            resultDOC: null,

            error: "",
        // Functions
            init: null,
            get: null,
            post: null,

    // PRIVATE DECLARATIONS
        // Variables
            instance: null,
            state: 'unable',
        // Functions
            // 0 - до того как запрос отправлен (uninitialized)
            // 1 - объект инициализирован (loading)
            // 2 - получен ответ от сервера (loaded)
            // 3 - соединение с сервером активно (interactive)
            // 4 - объект завершил работу (complete)
            onReadyStateChange: null,
            createInstance: null,
            openInstanceURL: null,
            setRequestHeaders: null,
            formatPostData: null,
            sendRequest: null
};
/* -----------------------------------------------------------------------
                             IMPLEMENTATION
----------------------------------------------------------------------- */
// ----------------------------------------
//         PRIVATE DECLARATIONS
// ----------------------------------------
ajax.onReadyStateChange = function()
{
    if( this.instance == null ) return;
    switch( this.instance.readyState )
    {
        case 0:        this.events['Uninitialized']; break;
        case 1:        this.events['Loading']; break;
        case 2:        this.events['Loades']; break;
        case 3:        this.events['Interactive']; break;
        case 4:        this.events['Complete']; break;
    }
};


ajax.createInstance = function()
{
    var instance = null;
    try
    {
        instance = new XMLHttpRequest();
    }
    catch(e)
    {
        try
        {
            instance = new ActiveXObject('Msxml2.XMLHTTP');
        }
        catch(e)
        {
            try
            {
                instance = new ActiveXObject('Microsoft.XMLHTTP');
            }
            catch(e)
            {
                instance = null;
            }
        }
    }

    this.state = instance != null ? 'free' : 'unable';
    if( this.state == 'unable' )
    {
        this.error = "AJAX.createInstance -> Can't create class instance";
        return false;
    }
    this.error = '';
    return instance;
};


ajax.openInstanceURL = function()
{
    if( this.state != 'busy' )
    {
        this.error = 'AJAX.openInstanceURL -> transport always busy';
        return false;
    }

    try
    {
        this.instance.open( this.method, this.url, this.async );
    }
    catch(e)
    {
        this.error = 'AJAX.openInstanceURL -> error with opening url';
        return false;
    }
    this.error = '';
    return true;
};


ajax.setRequestHeaders = function()
{
    /* Force "Connection: close" for older Mozilla browsers to work
     * around a bug where XMLHttpRequest sends an incorrect
     * Content-length header. See Mozilla Bugzilla #246651. */
    var headers =
    {
        'X-Requested-With': 'XMLHttpRequest',
        'Accept': 'text/javascript, text/html, application/xml, text/xml, */*',
        'Content-type': "application/x-www-form-urlencoded; charset=utf-8",
        'Content-length': this.formatPostData( this.content ).length,
        'Connection': "close"
    };

    var uagent = navigator.userAgent.toLowerCase();
    var is_safari = ( ( uagent.indexOf('safari') != -1 ) || ( navigator.vendor == "Apple Computer, Inc." ) );
    var is_opera  = ( uagent.indexOf('opera') != -1 );
    var is_webtv  = ( uagent.indexOf('webtv') != -1 );
    var is_ie = ( ( uagent.indexOf('msie') != -1 ) && ( !is_opera ) && ( !this.is_safari ) && ( !this.is_webtv ) );
    if( is_ie )
    {
        headers["Pragma"] = "no-cache";
        headers["Cache-Control"] = "must-revalidate, no-cache, no-store";
    }

    try
    {
        for( var name in headers )
        {
            this.instance.setRequestHeader( name, headers[name] );
        }
    }
    catch(e)
    {
        this.error = 'AJAX.setResquestHeaders -> Error with setting request headers';
        return false;
    }

    this.error = '';
    return true;
};


ajax.formatPostData = function()
{
    var data = "";
    for( var i in this.content )
    {
        data += i + "=" + escape( this.content[i] ) + "&";
    }

    data += 'ajax-sended=1&';

    return data;
};


ajax.sendRequest = function()
{
    if( this.state != 'free' )
    {
        this.error = 'AJAX.sendRequest -> transport is not free';
        return false;
    }
    this.state = 'busy';

    var method = this.method.toLowerCase();
    if( ( method != 'post' && method != 'get' ) || this.url.length < 1 )
    {
        this.error = 'AJAX.sendRequest -> unknown method "'+ method +'" or URL is empty';
        return false;
    }

    if( !this.openInstanceURL() ) return false;
    if( !this.setRequestHeaders() ) return false;
    var post = this.formatPostData( this.content );

    try
    {
        if( method == 'get' ) this.instance.send( null );
        if( method == 'post' ) this.instance.send( post );
    }
    catch(e)
    {
        this.error = 'AJAX.sendRequest -> error with transporting data';
        return false;
    }

    this.resultHTML = this.instance.responseText;

    this.state = 'free';
    this.content = {};
    this.error = '';
    return true;
};

// ----------------------------------------
//         PUBLIC DECLARATIONS
// ----------------------------------------
ajax.init = function()
{
    this.instance = this.createInstance();

    if( this.instance == null ) return false;

    this.instance.onreadystatechange = this.onReadyStateChange;
    this.state = 'free';
    return true;
};


ajax.get = function( url )
{    if( this.instance == null || !this.instance ) this.init();
    this.url = url;
    this.method = 'get';
    return this.sendRequest();
};


ajax.post = function( url, content )
{
    if( this.instance == null || !this.instance ) this.init();
    if( !content || content == null ) content = null;
    if( content != null ) this.content = content;

    this.url = url;
    this.method = 'post';
    return this.sendRequest();
};


ajax.getResultArray = function()
{
    var content = this.resultHTML;

    var result = {};
    var j = 0;

    while( content.match( /(.*?)###/i ) )
    {
        var elem = content.match( /(.*?)###/i );
        result[j] = elem[1]; j++;
        content = content.replace( elem[0], '' );
    }

    result[j] = content;

    return result;
};


var trans = [];
for (var i = 0x410; i <= 0x44F; i++)
    trans[i] = i - 0x350; // А-Яа-я
trans[0x401] = 0xA8;      // Ё
trans[0x451] = 0xB8;      // ё

// Сохраняем стандартную функцию escape()
var escapeOrig = window.escape;

// Переопределяем функцию escape()
window.escape = function( str )
{
    if( !str || str == null || str == '' ) return '';
    var ret = [];
    // Составляем массив кодов символов, попутно переводим кириллицу
    for( var i = 0; i < str.length; i++ )
    {
        var n = str.charCodeAt( i );
        if( typeof trans[n] != 'undefined' ) n = trans[n];
        if( n <= 0xFF ) ret.push( n );
    }
    return escapeOrig( String.fromCharCode.apply( null, ret ) );
}


contextMenu = { ids : {} };

contextMenu.make = function( index, allow )
{    if( allow == 0 ) return false;
    var div = document.createElement('DIV');
    div.style.display = 'none';
    div.style.width = '200px';
    div.style.border = '#808080 1px solid';
    div.style.backgroundColor = '#f0f0f0';
    div.id = 'tree_context_menu_'+ index;
    document.body.appendChild( div );


    var item = document.createElement('DIV');
    item.innerHTML = 'Добавить подзадачу';
    item.className = 'contextmenu-item';
    $e( item, 'mouseover', function(e){ this.className = 'contextmenu-itemh'; } );
    $e( item, 'mouseout', function(e){ this.className = 'contextmenu-item'; } );
    $e( item, 'click', function(e){ addTaskChild( index ); } )
    div.appendChild( item );

    var item = document.createElement('DIV');
    item.innerHTML = 'Добавить несколько подзадач';
    item.className = 'contextmenu-item';
    $e( item, 'mouseover', function(e){ this.className = 'contextmenu-itemh'; } );
    $e( item, 'mouseout', function(e){ this.className = 'contextmenu-item'; } );
    $e( item, 'click', function(e){ addTaskAnyChilds( index ); } )
    div.appendChild( item );


    if( allow == 1 )
    {	    var separator = document.createElement('DIV');
	    separator.style.height = '0';
	    separator.style.borderTop = '#333 1px solid';
	    separator.style.borderBottom = '#fff 1px solid';
	    separator.style.marginLeft = '2px';
	    separator.style.marginRight = '2px';
	    div.appendChild( separator );


	    var item = document.createElement('DIV');
	    item.innerHTML = 'Свойства';
	    item.className = 'contextmenu-item';
	    $e( item, 'mouseover', function(e){ this.className = 'contextmenu-itemh'; } );
	    $e( item, 'mouseout', function(e){ this.className = 'contextmenu-item'; } );
	    $e( item, 'click', function(e){ propertiesDialog( index ); } )
	    div.appendChild( item );

	    var item = document.createElement('DIV');
	    item.innerHTML = 'Исполнители/Владельцы';
	    item.className = 'contextmenu-item';
	    $e( item, 'mouseover', function(e){ this.className = 'contextmenu-itemh'; } );
	    $e( item, 'mouseout', function(e){ this.className = 'contextmenu-item'; } );
	    $e( item, 'click', function(e){ _propertiesBox( index, saveOwners ); } )
	    div.appendChild( item );


	    var separator = document.createElement('DIV');
	    separator.style.height = '0';
	    separator.style.borderTop = '#333 1px solid';
	    separator.style.borderBottom = '#fff 1px solid';
	    separator.style.marginLeft = '2px';
	    separator.style.marginRight = '2px';
	    div.appendChild( separator );


	    var item = document.createElement('DIV');
	    item.innerHTML = 'Удалить ветвь';
	    item.className = 'contextmenu-item';
	    $e( item, 'mouseover', function(e){ this.className = 'contextmenu-itemh'; } );
	    $e( item, 'mouseout', function(e){ this.className = 'contextmenu-item'; } );
	    $e( item, 'click', function(e){ deleteChild( index ); } )
	    div.appendChild( item );
    }

    this.ids[index] = true;};


contextMenu.show = function( index, allow )
{    if( allow == 0 ) return false;
    if( $('tree_context_menu_'+index) == null ) this.make( index, allow );

    var menu = $( 'tree_context_menu_'+ index );
    menu.style.position = 'absolute';
    menu.style.left = windows.mouseX + 'px';
    menu.style.top  = windows.mouseY + 'px';
    menu.style.display = '';

    return false;
};

contextMenu.hideAll = function()
{    for( var i in this.ids ) $( 'tree_context_menu_'+ i ).style.display = 'none';}


var _LAST_DELETE_POST = 0;
deleteChild = function( index )
{
    _LAST_DELETE_POST = index;
    _confirm( "Вы действительно хотите удалить эту ветвь?", deleteChildEx );

};

deleteChildEx = function(e)
{    if( !ajax.init() ) return;
    if( !ajax.get( site_url + 'tasks/delete/' + _LAST_DELETE_POST ) ) return;
    refresh();
};