/* --- js/images.js -- start --------------------------------------- *
 * 
 * $Id: images.js 130 2010-07-13 22:58:23Z vugluskr $
 *
 * Require:
 *   jquery.blockUI.js
 *   jquery.json.js
 */

function imageUI(inf) {
    var bind = null;

    this.image_info = inf;
    this.image_id = inf.id;

    this.ui_binds = {
	url_process: null,
	input: {}
    };
    this.ui_modes = {
        hard: false
    };

    imageUI.prototype.bind_element = function(top_ent) {
	var ent, cls;

	cls = top_ent.parentNode.getAttribute('class');
	if (cls)
	    cls = cls.match(/\bimbgblock_wrap\b/);
	if (cls)
	    top_ent = top_ent.parentNode;

	this.bind = top_ent;

	ent = $('div[bind="image_editBox"]');
	if (! ent.length)
	    return;

	ent = ent[0]
	this.ui_binds['input']['form'] = ent;
	this.ui_binds['input']['tags'] = ent.querySelector('*[bind="tags"]');
	this.ui_binds['input']['comment'] = ent.querySelector('*[bind="comment"]');

	this.ui_binds['input']['commit_btn'] = ent.querySelector('*[bind="commit_btn"]');
	this.ui_binds['input']['drop_btn'] = ent.querySelector('*[bind="drop_btn"]');
	this.ui_binds['input']['cancel_btn'] = ent.querySelector('*[bind="cancel_btn"]');
    }

    imageUI.prototype.on_update = function(data) {
	if (this.ui_binds['tag_store']) {
	    var reply = $.evalJSON(data);
	    var tags = new Array();
	    var idx;
	    for (idx = 0; idx < reply.tags_raw.length; idx++) {
		var t = reply.tags_raw[idx];
		t = this.make_tagLink(t);

		if (idx)
		    tags.push(document.createTextNode(', '));
		tags.push(t);
	    }
	    
	    var ent = this.ui_binds['tag_store'];
	    $(ent).html('');
	    for (idx = 0; idx < tags.length; idx++) {
		ent.appendChild(tags[idx]);
	    }
	}

	var ent = document.createElement('div');
	ent.setAttribute('class', 'ui_info');
	ent.appendChild(document.createTextNode('Информация пазла успешно обновлена.'));
	$(".blockPage").html(ent);
	return true;
    }
    imageUI.prototype.on_delete = function(data) {
	var ent;

	ent = document.createElement('div');
	ent.setAttribute('class', 'ui_info');
	ent.appendChild(document.createTextNode('Пазл удален.'));
	$(".blockPage").html(ent);
	return true;
    }

    imageUI.prototype.make_tagLink = function(name) {
        var l = document.createElement('a');
	l.setAttribute('href', '/tag/' + name + '/');
	l.appendChild(document.createTextNode(name));
	return l;
    }

    imageUI.prototype.make_user_link = function(name) {
	c = document.createElement('a');
	c.setAttribute('href', '/users/' + name + '/');
	c.appendChild(document.createTextNode(name));
	return c;
    }

    imageUI.prototype.hndl_complSwitch = function() {
	var to_norm = this.ui_modes['hard'] == true;
	var link, ent;

	if (this.ui_binds['url_process']) {
	    ent = this.ui_binds['url_process'];
	    link = ent.getAttribute('href');
	    
	    if (to_norm) {
		ent.setAttribute('href', link.replace(/hard\/$/, ''));
	    } else {
		ent.setAttribute('href', link + 'hard/');
	    }
	}
    }
    
    imageUI.prototype.editStart = function() {
	if (! this.ui_binds['input']['form'])
	    throw Error('There is no binded from for image_ui');

	self = this;
	$.post("/ajax/user_imageparams/", {id:this.image_id},
	function(data) {
	    if (data != "false") {
		response = $.evalJSON(data);

		var self2 = self;
		$(self.ui_binds['input']['tags']).val(response.tags);
		$(self.ui_binds['input']['comment']).val(response.comment);
		$(self.ui_binds['input']['cancel_btn']).click(function(){ self2.editEnd() });
		$(self.ui_binds['input']['commit_btn']).click(function(){ self2.commit() });
		$(self.ui_binds['input']['drop_btn']).click(function(){ self2.drop() });

		$.blockUI({message: self.ui_binds['input']['form']});
	    } else {
		var ent;

		ent = document.createElement('div');
		ent.setAttribute('class', 'ui_error');
		ent.appendChild(document.createTextNode('Произошла ошибка в процессе получении информации о пазле.'));

		$.blockUI({message: ent});
		setTimeout("$.unblockUI()", 2000);
	    }
	});
    }
    imageUI.prototype.release_input = function() {
	$(this.ui_binds['input']['tags']).val("");
	$(this.ui_binds['input']['comment']).val("");
	$(this.ui_binds['input']['cancel_btn']).unbind("click");
	$(this.ui_binds['input']['commit_btn']).unbind("click");
	$(this.ui_binds['input']['drop_btn']).unbind("click");
    }

    imageUI.prototype.editEnd = function() {
	this.release_input();
	$.unblockUI();
    }
    imageUI.prototype.commit = function() {
	var req = {
	    id: this.image_id,
	    tags: $(this.ui_binds['input']['tags']).val(),
	    comment: $(this.ui_binds['input']['comment']).val()
	};

	var self = this;
	$.post('/ajax/user_imagesave/', req, function(data) {
	    self.release_input();

	    var release_id = setTimeout('$.unblockUI()', 2000);
	    if (data == 'false') {
		$.blockUI({
		    message: "<strong>Произошла ошибка в процессе редактирования пазла. Пожалуйста попробуйте еще раз.</strong>",
		    css: {color: "red", padding: "5px"}
		});
		return;
	    }
	    if (! self.on_update(data)) {
		clearTimeout(release_id);
	    }
        });
    }
    imageUI.prototype.drop = function() {
	if(! confirm("Вы действительно хотите удалить этот пазл?")) 
	    return;
	
	var self = this;
	$.post("/ajax/user_imagedel/", {id: this.image_id}, function(data) {
	    self.release_input();

	    var release_id = setTimeout('$.unblockUI()', 2000);
	    if (data == 'false') {
		$.blockUI({
		    message:"<strong>Произошла ошибка в процессе редактирования пазла. Пожалуйста попробуйте еще раз.</strong>",
		    css: {color:"red", padding: "5px"}
		});
		return;
	    }
	    if (! self.on_delete(data)) {
		clearTimeout(release_id);
	    }
	});
    }
}

function imageUI_imgblock() {
    imageUI_imgblock.superclass.constructor.apply(this, arguments);

    imageUI_imgblock.prototype.bind_element = function(top_ent) {
	imageUI_imgblock.superclass.bind_element.apply(this, arguments);

	var self = this;
	var ent;
	var cls;

	ent = top_ent.querySelector('*[bind="tag_store"]');
	if (ent) {
	    this.ui_binds['tag_store'] = ent;
	}

	ent = top_ent.querySelector('*[bind="btn_complSwitch"]');
	cls = ent.getAttribute('class');
	cls = cls.match(/\bbg_(?:norm|hard)\b/);
	if (cls) {
	    this.ui_modes['hard'] = cls == 'bg_hard';
	}
	$(ent).click(function(){ self.hndl_complSwitch(); });
	$(ent).mouseover(function(){ 
	    var ent = this;
	    self.ui_modes['compl_tooltip_tout'] = setTimeout(function(){
	         self.hndl_complTooltip_in(ent);
	    }, 750) });
	$(ent).mouseout(function(){ self.hndl_complTooltip_out(this); });
	
	this.ui_binds['compl_sw'] = ent;
	this.ui_binds['compl_btn'] = new Array();
	this.ui_binds['compl_btn'].push(ent);
	this.ui_binds['compl_btn'].push(top_ent.querySelector('*[bind="btn_info"]'));
	
	ent = top_ent.querySelector('*[bind="btn_edit"]');
	if (ent) {
	    this.ui_binds['compl_btn'].push(ent);
	    this.ui_binds['btn_edit'] = ent;
	    $(ent).click(function(){ self.editStart() });
	}

	ent = top_ent.querySelector('*[bind="btn_process"]');
	this.ui_binds['btn_process'] = ent;
	for (var idx = 0; idx < ent.children.length; idx++) {
	    c = ent.children[idx];
	    if (c.tagName.toLowerCase() != 'a')
		continue;
	    this.ui_binds['url_process'] = c;
	    break;
	}

	this.ui_binds['moderator'] = new Array();
	ent = top_ent.querySelector('*[bind="moderation"]');
	if (ent) {
	    var ctrl = top_ent.querySelector('*[bind="moderation_ctrl"]');
	    $(ent).click(function(){
		$(ctrl).slideToggle('fast');
	    });

	    this.ui_binds['moderator']['ctrl']	    = ctrl;
	    this.ui_binds['moderator']['rm']	    = ctrl.querySelector('*[bind="moderator_remove"]');
	    this.ui_binds['moderator']['adult']	    = ctrl.querySelector('*[bind="moderator_adult"]');
	    this.ui_binds['moderator']['private']   = ctrl.querySelector('*[bind="moderator_private"]');

	    // replace "remove" link
	    ent = this.ui_binds['moderator']['rm'];
	    if (ent) {
		var btn = document.createElement('span');
		btn.setAttribute('class', 'link_emulator');
		$(btn).html($(ent).html());
		$(ent).after(btn);
		$(ent).remove();

		var self = this;
		$(btn).click(function(){ self.drop() });
	    }
	}
    }

    imageUI_imgblock.prototype.hndl_complSwitch = function() {
	imageUI_imgblock.superclass.hndl_complSwitch.apply(this, arguments);

	var to_norm = this.ui_modes['hard'] == true;
	var ent, idx;

	for (idx = 0; idx < this.ui_binds['compl_btn'].length; idx++) {
	    ent = this.ui_binds['compl_btn'][idx];
	    $(ent).toggleClass('bg_norm', to_norm);
	    $(ent).toggleClass('bg_hard', !to_norm);
	}

	var btn = this.ui_binds['btn_process'];
	if (to_norm) {
	    $(btn).css({backgroundPosition: '435px 50%'});
	    $(btn).removeClass('bg_hard');
	    $(btn).animate({backgroundPosition:"255px 50%"}, 1000);
	} else {
	    $(btn).css({backgroundPosition: '255px 50%'});
	    $(btn).removeClass('bg_norm');
	    $(btn).animate({backgroundPosition:"75px 50%"}, 1000);
	}

	this.ui_modes['hard'] = !this.ui_modes['hard'];
    }
    imageUI_imgblock.prototype.hndl_complTooltip_in = function(btn) {
	var ent;

	ent = document.createElement('div');
	ent.setAttribute('class', 'tooltip opacity_85');
	ent.appendChild(document.createElement('h3'));
	ent = ent.lastChild;
	ent.appendChild(document.createTextNode('Переключатель уровня сложности'));
	ent = ent.parentNode;

	ent.appendChild(document.createElement('hr'));
	ent.appendChild(document.createElement('div'));
	ent = ent.lastChild;
	ent.appendChild(document.createElement('p'));
	ent = ent.lastChild;
	
	if (this.ui_modes['hard']) {
	    $(ent).html('Сложность: <b>тяжелая</b> - включен переворот кусочков.');
	} else {
	    $(ent).html('Сложность: <b>простая</b> - переворот кусочков отключен.');
	}
	ent = ent.parentNode.parentNode;

	var encl = $('.page');
	encl[0].appendChild(ent);
	btn.tooltip = ent;

	var offs_x, offs_y, offs;
	offs = $(btn).offset();
	offs_x = offs.left + $(btn).width() + 5;
	offs_y = offs.top - $(ent).height() - 10;

	$(ent).css({
	    top: offs_y + 'px',
	    left: offs_x + 'px'});
    }
    imageUI_imgblock.prototype.hndl_complTooltip_out = function(btn) {
	if (btn.tooltip) {
	    $(btn.tooltip).remove();
	    delete btn.tooltip;
	} else {
	    clearTimeout(this.ui_modes['compl_tooltip_tout']);
	}
    }

    imageUI_imgblock.prototype.on_delete = function(data) {
	$(this.bind).remove();
	return imageUI_imgblock.superclass.on_delete.apply(this, arguments);
    }
}
extend(imageUI_imgblock, imageUI);

function imageUI_rating(inf) {
    imageUI_rating.superclass.constructor.apply(this, arguments);

    imageUI_rating.prototype.bind_element = function(top_ent) {
	imageUI_rating.superclass.bind_element.apply(this, arguments);

	this.ui_binds['rating'] = new Array();

	var ent = $('.puzzle_rating *[bind="author_comment"]');
	if (ent.length != 1)
	    throw Error('imageUI_rating.bind_element: unable to locate element \'*[bind="author_comment"]\'');
	this.ui_binds['rating']['author_comment'] = ent[0];
	this.ui_binds['rating']['author_comment_body'] = ent[0].querySelector('.body');
    };

    imageUI_rating.prototype.on_update = function(data) {
	reply = $.evalJSON(data);

	var enc_comment;
	exp = new RegExp('$', 'gm')
	enc_comment = reply.comment.replace(exp, '<br />');
	
	$(this.ui_binds['rating']['author_comment_body']).html(enc_comment);
	$(this.ui_binds['rating']['author_comment']).toggleClass('hidden', reply.comment.length == 0);

	return imageUI_rating.superclass.on_update.apply(this, arguments);
    }
    imageUI_rating.prototype.on_delete = function(data) {
	choises = new Array();

	// Проверяем и создаем возможные переходы.
	if (1 < history.length) {
	    c = document.createElement('li');
	    choises.push(c);

	    c.appendChild(document.createElement('a'));
	    c = c.lastChild;
	    c.setAttribute('href', 'javascript:history.back()');
	    c.appendChild(document.createTextNode('Вернуться на предыдущую страницу.'));
	}
	if (this.image_info.curr_user) {
	    c = document.createElement('li');
	    choises.push(c);

	    c.appendChild(document.createTextNode('Перейти к странице '));
	    c.appendChild(this.make_user_link(this.image_info.curr_user));
	}
	if (this.image_info.curr_user 
	    && this.image_info.owner
	    && this.image_info.curr_user != this.image_info.owner) {
	    c = document.createElement('li');
	    choises.push(c);

	    c.appendChild(document.createTextNode('Перейти к странице '));
	    c.appendChild(this.make_user_link(this.image_info.owner));
	    c.appendChild(document.createTextNode(', бывшего автором этого пазла.'));
	}
	c = document.createElement('li');
	choises.push(c);
	c.appendChild(document.createTextNode('Перейти к главной странице '));
	c.appendChild(document.createElement('a'));
	c = c.lastChild;
	c.setAttribute('href', '/');
	c.appendChild(document.createTextNode('PuzzleIt.'));

	// Теперь обвертка
	p = document.createElement('div');
	c = document.createElement('h3');
	c.appendChild(document.createTextNode('Пазл был удален.'));
	p.appendChild(c);
	p.appendChild(document.createElement('hr'));
	
	c = document.createElement('div');
	c.setAttribute('class', 'info_block');
	p.appendChild(c);
	p = c;
	p.appendChild(document.createTextNode('Вы находитесь перед следующим выбором:'));
	p.appendChild(document.createElement('ol'));
	c = p.lastChild

	for (idx = 0; idx < choises.length; idx++) {
	    c.appendChild(choises[idx]);
	}

	p = p.parentNode;
	$.blockUI({message: p});
	return false;
    }
}
extend(imageUI_rating, imageUI_imgblock);
/* --- js/images.js -- end ----------------------------------------- */
