/**
 *  Конструирует объект окна.
 *  
 *  @param String window_id идентификатор окна
 *  @param String window_title заголовок окна
 *  @param String plugin_name имя плагина
 *  @param Array plugin_params параметры плагина
 *  @param function callback_function функция, которая будет вызвана при создании окна
 *  @param array callback_params параметры для callback функции
 **/
var cHydraWindow = function(
        window_id,
        window_title,
        plugin_name,
        plugin_params,
        callback_function,
        callback_params
    )
{
    
    this.window_container_id = window_id + '_container';

    // Проверяем, а нет ли у нас сейчас такого запущенного окна.
	var exist_win_elem = document.getElementById(window_id);
	if (exist_win_elem)
	{
		// Проверка наличия контейнера
		var exit_container_elem = document.getElementById(this.window_container_id);
		if (exit_container_elem)
		{
			return this.window_container_id;
		}
	}
    
    var window_elem = document.createElement('DIV');
	window_elem.style.border = '1px solid black';
	//window_elem.style.width = width + 'px';
	//window_elem.style.height = height + 'px';
	window_elem.style.position = 'absolute';


    var width = 100;
    var height = 100;
  
    
	window_elem.style.left = (screen.width/2-width/2)+'px';
    //debugger;
	window_elem.style.top = (screen.height/2-height + elementWrapper.getScrollY())+'px';
	//window_elem.style.top = (screen.height/2-height + window.scrollY)+'px';
	window_elem.setAttribute('class', 'hydra_window');
	window_elem.setAttribute('id', window_id);
    //debugger;
    /*hydra_add_event(window_elem,'onmousedown',function onmousedown(event){
        //debugger;
        window_elem.x0 = event.clientX;
        window_elem.y0 = event.clientY;
        window_elem.divX0 = parseInt(window_elem.style.left);
        window_elem.divY0 = parseInt(window_elem.style.top);
        window_elem.moveState = true;
    })*/
    /*window_elem.onmousedown= function (event){
        if (!event)event=window.event;
        this.x0 = event.clientX;
        this.y0 = event.clientY;
        this.divX0 = parseInt(window_elem.style.left);
        this.divY0 = parseInt(window_elem.style.top);
        this.moveState = true;
    };
    window_elem.onmouseup = function (event) {
            if (!event)event=window.event;
           this.moveState = false;
    };

    window_elem.onmousemove = function(event) {
        if (!event)event=window.event; 
        if (this.moveState) {
            this.style.left = window_elem.divX0 + event.clientX- window_elem.x0 + 'px';
            this.style.top  = window_elem.divY0 + event.clientY - window_elem.y0 + 'px';
        }
    };*/
    //make_elem_drag_n_drop(window_elem);
    //
    // title
    var window_title_elem = hydra_create_element('DIV', {'class':'title'});
    window_elem.appendChild(window_title_elem);

    var span_elem = document.createElement('div');
    span_elem.innerHTML = window_title;
    window_title_elem.appendChild(span_elem);

	// create close window icon
	var img_elem = document.createElement('img');

	img_elem.setAttribute('src', '../_lib/window/i/close.gif');
    img_elem.style.position = 'absolute';
    img_elem.style.right = '0px';
	img_elem.setAttribute('onclick', 'destroy_window("'+window_id+'");');
	span_elem.appendChild(img_elem);

	// Контейнер содержимого окна
	var container_elem = document.createElement('DIV');
    container_elem.setAttribute('class', 'hydra_window_body');
	container_elem.setAttribute('id', this.window_container_id);
	window_elem.appendChild(container_elem);

    // Создаем само окно.
    document.body.appendChild(window_elem);

    // Загрузка плагина через ajax.
    // Если есть что запускать.
    if (plugin_name)
    {
	if (plugin_params == undefined)
	{
            plugin_params = new Array();
	}
	call_ajax(plugin_name, this.window_container_id, plugin_params);
    }

    // Запуск callback-функции
    if (callback_function != undefined)
    {
	if (typeof(callback_function) == 'function' )
	{
            if(callback_params)
            {
		// Вызов callback функции. с параметрами
		return callback_function(this.window_container_id,callback_params);
            }
            else
            {
		// Вызов callback функции.
		return callback_function(this.window_container_id);
            }
	}
    }

	
}

cHydraWindow.prototype.get_container_id = function()
{
    return this.window_container_id;
}

// Объявим функцию для определения координат мыши
function defPosition(event) {
    var x =0;
    var y = 0;
 /*   if (document.attachEvent != null) { // Internet Explorer & Opera
        x = window.event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
        y = window.event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
    }*/
//    if (!document.attachEvent && document.addEventListener) { // Gecko
        x = event.clientX + window.scrollX;
        y = event.clientY + window.scrollY;
//    }
    return {x:x, y:y};
}


// Функция инициализации движения
// Записываем всё параметры начального состояния
/*function initMove(div, event) {

    var event = event || window.event;
    x0 = defPosition(event).x;
    y0 = defPosition(event).y;
    divX0 = parseInt(div.style.left);
    divY0 = parseInt(div.style.top);
    moveState = true;
}



function moveHandler(div, event) {
    var event = event || window.event;
    if (moveState) {
        div.style.left = divX0 + defPosition(event).x - x0;
        div.style.top  = divY0 + defPosition(event).y - y0;
    }
}*/

/**
 * Создает окно.
 * @param String window_id
 * @param String window_title заголовок окна
 * @param int width ширина окна
 * @param int height высота окна
 * @param int left положение окна слева
 * @param int top положение окна сверху
 * @param String plugin_name имя плагина, который нужно запустить в окне
 * @param Array plugin_params параметры для плагина
 * @param Function callback_function функция, которую нужно вызвать после
 * создания окна и загрузки в него плагина.
 */
function create_window(
    window_id,
    window_title,
    width,
    height,
    left,
    top,
    plugin_name,
    plugin_params,
    callback_function
    )
{
	var window_container_id = window_id + '_container';

	// Проверяем, а нет ли у нас сейчас такого запущенного окна.
	var exist_win_elem = document.getElementById(window_id);
	if (exist_win_elem)
	{
		// Проверка наличия контейнера
		var exit_container_elem = document.getElementById(window_container_id);
		if (exit_container_elem)
		{
			return window_container_id;
		}
	}

	var window_elem = document.createElement('DIV');	
	window_elem.style.border = '1px solid black';
	window_elem.style.width = width + 'px';
	window_elem.style.height = height + 'px';
	window_elem.style.position = 'absolute';
	window_elem.style.left = 100;
	window_elem.style.top = 100;
	window_elem.setAttribute('class', 'hydra_window');
	window_elem.setAttribute('id', window_id);

	
	// title
	var window_title_elem = document.createElement('DIV');
    window_title_elem.setAttribute('class', 'title');
	window_elem.appendChild(window_title_elem);

	var span_elem = document.createElement('div');	
	span_elem.innerHTML = 'Заголовок окна';
	window_title_elem.appendChild(span_elem);
	
	// create close window icon
	var img_elem = document.createElement('img');
   
	img_elem.setAttribute('src', '../_lib/window/i/close.gif');
	
	img_elem.setAttribute('onclick', 'destroy_window("'+window_id+'");');
	span_elem.appendChild(img_elem);

	// Контейнер содержимого окна
	var container_elem = document.createElement('DIV');	
	container_elem.setAttribute('id', window_container_id);
	window_elem.appendChild(container_elem);

    // Создаем само окно.
	document.body.appendChild(window_elem);
	
	// Загрузка плагина через ajax.
	// Если есть что запускать.
	if (plugin_name)
	{
		if (plugin_params == undefined)
		{
			plugin_params = new Array();
		}

		call_ajax(plugin_name, window_container_id, plugin_params);
	}
	
	// Запуск callback-функции
	if (callback_function != undefined)
	{
		if (typeof(callback_function) == 'function' )
		{
			// Вызов callback функции.
			return callback_function(window_container_id);
		}
	}

	return window_container_id;
}

function destroy_window(window_id)
{
	var elem = document.getElementById(window_id);
	if (elem)
	{
        if (elem!=undefined)
            document.body.removeChild(elem);
	}
}