/**
 * Базовое окно
 */
function dialog_class(fixed_width, fixed_height, show_loader, position_type)
{
	this.dialog = null;
	this.show_loader = show_loader || false;
	this.width = fixed_width || 0;
	this.height = fixed_height || 0;
	this.position_type = position_type || "center"; // center, right
	this.elements = new Array();
	
	this.timer= null;
	this.interval = 10;
	this.loader = null;
	
	this.offset_x = 0;
	this.offset_y = 0;
	
	this.get_body = function()
	{
		return this.dialog;
	}
	
	this.show = function()
	{
		this.dialog.style.visibility = 'visible'; 
	}
	
	/* 
	 * Включить слежение за размером и положением окна
	 */
	this.actual_position = function()
	{
		this.set_in_place();
		this.set_timer();
		if(this.dialog)
			this.dialog.style.visibility = "visible";
	}
	
	this.set_offset = function(x, y)
	{
		this.offset_x = x;
		this.offset_y = y;
		this.set_in_place();
	}
	
	this.modify_offset = function(x, y)
	{
		this.offset_x += x;
		this.offset_y += y;
		this.set_in_place();
	}
	
	/* 
	 * Поставить наблюдатель за изменениями размера
	 */
	this.set_timer = function ()
	{
	    clearTimeout(this.timer);
	    var fc  = function(x) {
	    	return function(){x.actual_position();}
	    }(this); 
	    this.timer = setTimeout(fc, this.interval);
	}
	
	/*
	 * Очистить таймер
	 */
	this.clear_timer = function()
	{
		if(this.timer != null)
			clearTimeout(this.timer);
	}
	
	/*
	 * Выравнять по центру, для ie 6 эмуляция fixed
	 */
	this.set_in_place = function()
	{
		var elem_container = this.get_body();
		var left, top;
		if(this.position_type == "center") {
			var dialog_width = elem_container.clientWidth;
			var dialog_height = elem_container.clientHeight;
			
			if(dialog_width && dialog_height) {			
				left = (document_size()[0]/2) + document_scroll()[0] - dialog_width/2  + this.offset_x;
				top = (document_size()[1]/2) + document_scroll()[1] - dialog_height/2  + this.offset_y;
				this.move_dialog(left, top);
			}
		}
		else if(this.position_type == "right") {
			left = this.offset_x;
			top = this.offset_y;
			this.move_dialog(left, top);
		}
	}
	
	this.set_elements = function(element_args)
	{
		var element_set = this.elements;
		for(var elem in element_args) {
			element_set[elem] = element_args[elem];
		}
		this.elements = element_set;
	}
	
	this.get_element = function(name)
	{
		var elem = this.elements;
		if(elem[name] != undefined)
			return elem[name];
		else 
			return null;
	}
	
	this.clear_elements = function()
	{
		this.elements = new Array();
	}
	
	/* 
	 * Удалить окно 
	 */
	this.close = function()
	{
		if(this.dialog != null) {
			this.clear_timer ();
			this.dialog.parentNode.removeChild(this.dialog);
			
			this.dialog = null;
			this.offset_x = 0;
			this.offset_y = 0;
			
			this.remove_loader();
		}
	}
	
	/* 
	* Создать базовое окно
	*/
	this.create = function(id)
	{
		this.close();
		var elem_dialog = create_element("div",  {className: 'widget_dialog'}, null);
		this.dialog = elem_dialog;
		
		elem_dialog.style.visibility = "hidden";
		// Если есть фиксированые ширины - ставим
		if(this.width)
			elem_dialog.style.width = this.width;
		if(this.height)
			elem_dialog.style.height = this.height;
			
		// Добавляем в тел
		document.body.insertBefore(elem_dialog, document.body.firstChild);
		this.set_loder();
		
		return elem_dialog;
	}
	
	/* 
	 * Построить заглушку контента
	 */
	this.set_loder = function()
	{
		if(this.show_loader && this.loader == null){
			var loader = create_element("div", {className: 'widget_loader'}, null);
			if(is_ie(6)) {
				loader.style.position = "absolute";
				loader.style.height = document.body.clientHeight;
			}
			$(document.body).prepend(loader);
			this.loader = loader;
		}
	}
	
	/*
	 * Убрать заглушку
	 */
	this.remove_loader = function()
	{
		if(this.loader!=null) {
			document.body.removeChild(this.loader);
			this.loader = null;
		}
	}
	
	this.move_dialog = function(x, y) 
	{
		elem_container = this.get_body();
		if(elem_container) {
			elem_container.style.top = y + "px";
			elem_container.style.left = x + "px";
		}
	}
}

/**
 * Окно с функциями движения, закрытия по клику и базовой структурой
 */
function dialog_float_class(fixed_width, fixed_height, show_loader)
{
	this.base = new dialog_class(fixed_width, fixed_height, false, "right");
	this.actor = null;
	this.timer = null;
	
	this.create = function(actor, content)
	{
		if(this.actor != null && actor == this.actor) {
			if(this.timer)
				clearTimeout(this.timer);
		}
		else {
			if(this.actor != null)
				this.close();
	
			id = "dialog_float";
			var elem_dialog = this.base.create(id);
			
			var photo_container = create_element("div", {className: 'dialog_photo'}, null);
			var elem_container = create_element("div", {className: 'dialog_container'}, photo_container);
			
			// TODO - Класс со списком картинок, передается индекс, происходит выбор
			var image = create_element("img", {src: content}, null);
			photo_container.appendChild(image);
			
			var arg = new Array();
			arg['photo_container'] = photo_container;
			this.set_elements(arg);	
			
			this.set_move_action(actor);
			$(elem_dialog).append(elem_container);
		}
	}
	
	/* 
	 * Поставить наблюдатель за изменениями размера
	 */
	this.set_move_action = function(actor)
	{
		this.actor = actor;
	    this.fc_move  = function(x) {
	    	return function(e){x.make_move(e.pageX, e.pageY);}
	    }(this); 
	    $(document.body).bind("mousemove", this.fc_move);
	    
	    this.fc_suspended_close = function(x) {
	    	return function(){x.suspended_close();}
	    }(this); 
	    $(actor).bind("mouseout", this.fc_suspended_close);
	}
	
	this.make_move = function(x, y)
	{
		this.base.set_offset(x + 10, y + 10);
		this.base.show();
	}
	
	this.suspended_close = function()
	{
		this.fc_close = function(x) {
			return function(){x.close();}
		}(this); 
		this.timer = setTimeout(this.fc_close, 100);
	}
	
	this.set_elements = function(element_args)
	{
		this.base.set_elements(element_args);
	}
	
	this.get_element = function(name)
	{
		return this.base.get_element(name);
	}
	
	this.clear_elements = function()
	{
		this.base.clear_elements();
	}
	
	this.close = function()
	{
		$(document.body).unbind("mousemove", this.fc_move);
		clearTimeout(this.timer);
		$(this.actor).unbind("mouseout", this.fc_suspended_close);
		this.actor = null;
		this.base.close();
	}
}
var dialog_float = new dialog_float_class();

/**
 * Окно с функциями движения, закрытия по клику и базовой структурой
 */
function dialog_extend_class(fixed_width, fixed_height)
{
	this.base = new dialog_class(fixed_width, fixed_height, true);
	
	this.mouse_click_x = 0;
	this.mouse_click_y = 0;
	
	this.create = function(id, title)
	{
		var elem_dialog = this.base.create(id);
		
		var header_buttonset = create_element("div",  {className: 'dialog_buttonset'});
		var elem_title = create_element("div",  {className: 'dialog_title'}, title);
		var elem_header = create_element("div",  {className: 'dialog_header'}, [header_buttonset, elem_title]);
		var elem_body = create_element("div",  {className: 'dialog_body', id: id});
		var elem_container = create_element("div", {className: 'dialog_container'}, [elem_header, elem_body]);
		
		var arg = new Array();
		arg['container'] = elem_container;
		arg['body'] = elem_body;
		arg['header'] = elem_header;
		arg['title'] = elem_title;
		arg['buttonset'] = header_buttonset;
		this.set_elements(arg);
		
		this.set_title(title);
		this.add_button_close();
		this.add_effect_move(elem_header);
		
		$(elem_dialog).append(elem_container);
		this.base.actual_position();
	}
	
	this.set_elements = function(element_args)
	{
		this.base.set_elements(element_args);
	}
	
	this.get_element = function(name)
	{
		return this.base.get_element(name);
	}
	
	this.clear_elements = function()
	{
		this.base.clear_elements();
	}
	
	this.set_title = function(title)
	{
		var title_element = this.get_element('title');
		var title_text_node = create_text_element(title);
		$(title_element).empty();
		$(title_element).append(title_text_node);
	}
	
	/* 
	 * Добавить кнопку закрытия 
	 */
	this.add_button_close = function()
	{
		var buttonset = this.get_element('buttonset')
		if(buttonset != null) {
			var elem_button = create_element("a",  {className: 'button_close', href: 'javascript: void(0)'});
			this.add_effect_close(elem_button);
			$(buttonset).append(elem_button);
		}
	}
	
	/*
	 * Выставить элементу ф-ции перемещения
	 */
	this.add_effect_move = function(elem)
	{
		// При клике таскаем окно 
		var fc = function(x) {
			return function(e) {x.start_drag(e.pageX, e.pageY)}
		}(this);
		$(elem).bind("mousedown", fc);
	}
	
	/*
	 * Эффект закрытия на нажатие элемента
	 */
	this.add_effect_close = function(elem)
	{
		var fc = function(x)
		{
			return function() {x.close()};
		}(this);
		$(elem).bind("click", fc);
	}
	
	
	/*
	 * Поставить статус Drag
	 */
	this.start_drag = function(click_x, click_y)
	{
		if(is_ie(6))
			return;
		this.mouse_click_x = click_x;
		this.mouse_click_y = click_y;
		
		this.fc_move = function(x) {
			return function(e) {x.drag(e.pageX, e.pageY); return true;};
		}(this);
		
		$(document.body).bind("mousemove", this.fc_move);
		$(document.body).bind("mouseup", function(){
			$(document.body).unbind("mousemove", this.fc_move);
		});
	}
	
	/*
	 * Переместить окно
	 */
	this.drag = function(x, y)
	{
		var delta_x = x - this.mouse_click_x;
		var delta_y = y - this.mouse_click_y;
		this.mouse_click_x += delta_x;
		this.mouse_click_y += delta_y;
			
		this.base.modify_offset(delta_x, delta_y);
	}
	
	this.close = function()
	{	
		if(this.dialog) {
			this.clear_elements();
		}
		this.base.close();
	}
}
/**
 * Окно с сообщение EXTENDS dialog_extend_class
 */

function dialog_alert_class(fixed_width, fixed_height)
{	
	this.prototype = new dialog_extend_class(fixed_width, fixed_height, true);
	
	this.create = function(id, title, content)
	{
		title = title || "Ошибка";
		id = id || "dialod_alert"; 
		this.prototype.create(id, title);
		this.set_content(content);
	}
	
	this.set_content = function(content)
	{
		var elem_content = create_element("div",  {className: 'dialog_body'});
		elem_content.innerHTML = content;
		var elem_body = this.prototype.get_element('body');
		$(elem_body).empty();
		$(elem_body).append(elem_content);
	}	
}

var dialog_alert = new dialog_alert_class();

/**
 * Окно для вывода картинок EXTENDS dialog_extend_class
 */
function dialog_image_class(fixed_width, fixed_height)
{	
	this.prototype = new dialog_extend_class(fixed_width, fixed_height);

	this.picture_list = new Array();
	this.index = 0;
	
	/* Элементы окна */
	this.link_left;
	this.link_right;
	this.photo;
	this.text;
	
	/* Настройки */
	this.id = 'dialod_image';
	this.title = 'Галерея';
	
	/*
	 * Показать окно, выбрав один из элементов списка
	 */
	this.show = function(index, id, title)
	{
		id = id || this.id;
		title = title || this.title;
		this.prototype.create(id, title);
		
		this.create_structure();
		this.select_index(index);
		this.fill();
	}
	
	/*
	 * Создать структуру контейнеров, для распределения элементов
	 */
	this.create_structure = function()
	{
		var elem_body = this.prototype.get_element('body');
					
		var link_left = create_element('div', {className: 'item_left'});
		var link_right = create_element('div', {className: 'item_right'});
		var link_container = create_element('div', {className: 'dialog_link'}, [link_left, link_right] );
		
		var photo_container = create_element('div', {className: 'dialog_photo'});
		var fc = function(x) {
			return function() {x.close()};
		}(this);
		$(photo_container).bind("click", fc);
		
		var describe_container = create_element('div', {className: 'dialog_description'});
		
		var arg = new Array();
		arg['link_left'] = link_left;
		arg['link_right'] = link_right;
		arg['photo_container'] = photo_container;
		arg['describe_container'] = describe_container;
		this.prototype.set_elements(arg);
		
		$(elem_body).empty();
		$(elem_body).append(link_container).append(photo_container).append(describe_container);
	}
	
	this.close = function ()
	{
		this.prototype.close();
	}
	
	/*
	 * Добавить список картинок
	 */
	this.add_list = function(img_array)
	{
		if(is_array(img_array)) {
			for(var i=0; i<img_array.length; i++) {
				this.add(img_array[i]);
			}
		}
	}
	
	/*
	 * Добавить элемент в список
	 * {url: ,img_width:, img_height: ,title: }
	 */
	this.add = function(elem) 
	{
		this.picture_list[this.picture_list.length] = elem;
	}
	
	/*
	 * Переместить указатель
	 */
	this.select_index = function(index)
	{
		if(index<0) {
			this.index = 0;
			return true;
		}
		
		var pl = this.picture_list;
		if(index>(pl.length-1)) {
			this.index = pl.length-1;
			return true;
		}
		
		this.index = index;
		return true;
	}
	/*
	 * Сменить индекс и перестроить окно
	 */
	this.change_index = function(index)
	{
		this.select_index(this.index+index);	
		this.fill();
	}
	
	/*
	 * Построить элемент ссылка 
	 */
	this.build_link = function(index) 
	{
		var pl = this.picture_list;
		var new_index = this.index + index;
		if(new_index>=0 && new_index< pl.length) {
			var title="";
			if(index==-1)
				title = "<< Предыдущее фото";
			else
				title = "Следующее фото >>"; // Ниже по списку
			var a = create_element('a', {href:'#'}, title);
			a.onclick = function(x){
				return function(){ x.change_index(index)}
			}(this);
			return a;
		}
		else
			return null;
	}
	
	/*
	 * Выставить элементы в поля
	 */
	this.fill = function()
	{
	
		var record_dom = this.build_select_state();
		
		this.replace_dom(this.prototype.get_element('link_left'), record_dom.link_left);
		this.replace_dom(this.prototype.get_element('link_right'), record_dom.link_right);
		this.replace_dom(this.prototype.get_element('photo_container'), record_dom.photo);
		this.replace_dom(this.prototype.get_element('describe_container'), record_dom.text);
	}
	
	/*
	 * Вставить элемент в контейнер, заменив старый
	 */
	this.replace_dom = function(container, element)
	{
		$(container).empty().append(element);
	}
	
	/*
	 * Получит дом набор текущего элемента списка
	 */
	this.build_select_state = function() 
	{
		return {link_left: this.build_link(-1), link_right: this.build_link(1), photo: this.build_photo(), text: this.build_describe()};
	}
	
	/*
	 * Построить лемент фото
	 */
	this.build_photo = function()
	{
		var pl = this.picture_list;
		var record = pl[this.index];
		if(record != undefined) {
			return create_element('img', {src: record.url, width: record.width, height: record.height});
		}
		else 
			return null;
	}
	
	/*
	 * Построить элемент текст
	 */
	this.build_describe = function()
	{
		var pl = this.picture_list;
		var record = pl[this.index];
		var elem_title;
		if(record!=undefined && record.title != null && record.title != "") {
			elem_title = create_element('div', {className: 'title'}, record.title);
		}
		else
			elem_title = null;
		
		/* temp	 */
		var elem_text;
		if(record!=undefined && record.text != null && record.text != "") {
			elem_text = create_element('div', {style: 'margin-top: 5px'}, record.text);
		}
		else
			elem_text = null;
		
		var container;
		if(elem_title != null || elem_text != null) {
			container = create_element('div', null, [elem_title, elem_text]);
			if(record.max_width) {
				container.style.width = record.max_width + 'px';
			}
		}
		else
			container = null;
	
		return container;
	}
}

var dialog_image = new dialog_image_class();

