/* --- js/ui.js -- start ------------------------------------------- *
 * 
 * $Id: ui.js 562 2011-09-26 23:16:02Z vugluskr $
 *
 * Require:
 *   jquery.js
 */

function _ui(root) {
    this.root = $(root);
}
mixin(_ui.prototype, {
    'dynupdate_apply': function(du) {
        var ep = '_ui.dynupdate_apply(): '
        var idx;
        for (idx = 0; idx < du.length; idx++) {
            var ent = du[idx];
            var dst;

            if (ent['rel']) {
                if (typeof(this.root) == 'undefined')
                    throw Error(ep +'Receive relative block, but root element not defined.');
                dst = this.root.find(ent['dst']);
            } else {
                dst = $(ent['dst']);
            }

            if (! dst.length)
                throw Error(ep +'Destination element not found. (rel='+ (ent['rel'] ? 'yes' : 'no') +', dst="'+ ent['dst'] +'"');
            dst.empty();
            while (ent['ent'].firstChild)
                dst.append(ent['ent'].firstChild);
        }
    }});

function ui_dialog(master, wrap, jqm_args) {
    ui_dialog.superclass.constructor.call(this);

    this.master = master;
    if (typeof(wrap) == 'undefined' || wrap === null)
        this.make_wrap();
    else
        this.wrap = $(wrap);

    this.data = {};
    this._form = null;

    var self = this;
    var args = {
        'onShow': function(h) { self.dialog_fetch(h); },
    };
    $.extend(args, this.jqm_args);
    $.extend(args, jqm_args);
    jqm_args = jqm_args || {};
    this.wrap.jqm(args);
}
extend(ui_dialog, _ui);
mixin(ui_dialog.prototype, {
    'jqm_args': {},

    'fetch_url': null,
    'fetch_data': null,
    'fetch_extra': null,

    'data_multi_map': {},

    'commit_class': 'ui_dialog_commit',
    'dynzone_class': 'commit_block',

    'dialog_wait_dummy': 'Загрузка формы... <img src="/res/wait.gif" alt="ожидание" />',
    'reply_add_close_btn': true,
    
    '_get_dynzone': function() {
        var cc = '.'+ this.dynzone_class;
        return this.wrap.find(cc);
    },

    'make_wrap': function() {
        var w = document.createElement('div');
        w.setAttribute('class', 'jqmWindow');
        $('body').append(w);
        this.wrap = $(w);
        return this.wrap;
    },

    'dialog_init': function(h) {
        var cc;
        var self = this;

        cc = '.' + h.c.closeClass;
        if (cc)
            h.w.jqmAddClose($(cc, h.w));
        cc = '.' + this['commit_class'];
        if (cc)
            h.w.find(cc).click(function() {self.commit()});
    },
    'dialog_fetch': function(jqm_hash) {
        if (! this.fetch_url)
            throw Error('ui_dialog: property "fetch_url" not defined.');

        // Reset stored data
        this.data = {};
        this._form = null;

        // Init dialog windor for "wait" mode
        jqm_hash.w.html(this.dialog_wait_dummy);
        jqm_hash.w.get(0)._dialog_owner = this;
        jqm_hash.w.show();
        this.dialog_init(jqm_hash);

        // Fecth dialog window content
        var self = this;
        var args = {
            'url': this.fetch_url,
            'success': function(r, stat, xhr) { 
                jqm_hash.w.html(r); 
                self.dialog_init(jqm_hash);
                self.dialog_load();
            },
            'error': function(xhr, stat, exc) { 
                var ent = document.createElement('p');
                ent.setAttribute('class', 'text_center');
                ent.appendChild(document.createTextNode(xhr.statusText));
                jqm_hash.w.html(ent);
                self.dialog_init(jqm_hash);
                self.dialog_load();
            }};
        $.extend(args, this.fetch_extra || {});
        if (this.fetch_data)
            args['data'] = this.fetch_data;
        $.ajax(args);
    },
    'dialog_load': function(jqm_hash) {
        var ent = this.wrap.find('form[action]');
        if (! ent.length)
            throw Error('ui_dialog: Received invalid dialog data - there is no "form" element');
        this._form = ent;
    },

    'dynupdate_extract': function(wrap) {
        var ep = 'ui_dialog.dynupdate_extract(): ';
        var idx, du = new Array();
        var ents = wrap.find('.ui_dynupdate > .dyn_ent[dst]');
        for (idx = 0; idx < ents.length; idx++) {
            var ent = ents.get(idx);
            var dst = ent.getAttribute('dst');
            if (! dst)
                throw Error(ep + 'Invalid synamic entity - missing "dst" attribute.');

            var du_ent = {
                'rel': false,
                'dst': dst,
                'ent': ent};
            if (dst.match(/^>\s*/)) {
                du_ent['rel'] = true;
                du_ent['dst'] = dst.replace(/^>\s*/, '');
            }
            du.push(du_ent);
        }

        wrap.find('.ui_dynupdate').remove();
        return du;
    },

    'input_disable': function() {
        var disable_tags = new Array('input', 'button', 'textarea');
        var idx;
        for (idx = 0; idx < disable_tags.length; idx++)
            this.wrap.find(disable_tags[idx]).attr('disabled', 'disabled');
    },
    
    'precommit': function() {
        var ent = document.createElement('p');
        ent.setAttribute('class', 'text_center');
        ent.appendChild(document.createElement('img'));
        ent = ent.firstChild;
        ent.setAttribute('src', '/res/wait.gif');
        ent.setAttribute('alt', 'ожидание');
        ent = ent.parentNode;

        var cb = this._get_dynzone();
        cb.html(ent);

        this.input_disable();
    },
    'postcommit': function() {},

    'collect_data': function() {
        this.data = {};
        for (var n in this.multi_map)
            this.data[n] = new Array();
        
        var raw = this._form.serializeArray();
        //var idx;
        //for (idx = 0; idx < raw.length; idx++) 
        //    this.store_value(raw[idx]['name'], raw[idx]['value']);
        var self = this;
        $.each(raw, function(idx, ent) { self.store_value(ent['name'], ent['value']) });
    },

    'store_value': function(name, val) {
        if (this.data_multi_map[name]) {
            this.data[name].append(val);
            return;
        }
        this.data[name] = val;
    },

    'data_extend': function() {},

    'reply_update_layout': function() {
        var cb = this._get_dynzone();
        var ent;
        
        ent = document.createElement('hr');
        ent.setAttribute('width', '75%');
        cb.prepend(ent);

        if (this.reply_add_close_btn) {
            ent = document.createElement('p');
            ent.setAttribute('class', 'text_center');
            ent.appendChild(document.createElement('button'));
            ent.firstChild.appendChild(document.createTextNode('Закрыть'));
            cb.append(ent);
            this.wrap.jqmAddClose(ent.firstChild);
        }
    },
    'reply_ok': function(r, stat, xhr) {
        var cb = this._get_dynzone();
        cb.html(r);
        var du = this.dynupdate_extract(cb);
        this.master.dynupdate_apply(du);
    },
    'reply_fail': function(xhr, stat, exc) {
        var ent = document.createElement('p');
        ent.setAttribute('class', 'text_center');
        ent.appendChild(document.createTextNode(xhr.statusText));
        this._get_dynzone().html(ent);
    },
    'reply_complete': function(is_ok) {},

    'commit': function() {
        if (! this._form)
            throw Error('ui_dialog.commit: There is no "form" element. Looks like dialog incorrectly inialized.');

        this.collect_data();
        this.data_extend();
        this.precommit();

        var self = this;
        $.ajax({
            'type': 'POST',
            'url': this._form.attr('action'),
            'data': this.data,
            'success': function(){
                self.reply_ok.apply(self, arguments);
                self.reply_update_layout();
                self.reply_complete(true);
            },
            'error': function(){
                self.reply_fail.apply(self, arguments);
                self.reply_update_layout();
                self.reply_complete(false);
            }});
        this.postcommit();
    }});

function find_dialog(ent) {
    if (! (ent instanceof jQuery) || ent.length != 1)
        throw Error('find_dialog: Illegal argument');
    while (ent.length) {
        if (ent.hasClass('jqmWindow'))
            break;
        ent = ent.parent();
    }
    if (! ent.length)
        throw Error('find_dialog: Dialog not found.');
    ent = ent.get(0);
    ent = ent._dialog_owner;
    if (typeof(ent) == 'undefined')
        throw Error('find_dialog: Dialog broken.');
    return ent;
}

function spoiler(owner) {
    this.wrap = owner;
    if (!this.wrap)
	throw Error('Got ' + this.wrap + ' instead of spoiler element.');
    
    this.head = owner.querySelector('.head');
    this.body = owner.querySelector('.body');
    if (!this.head || !this.body)
	throw Error('Incorrect spoiler constuction: ' + spoiler);

    var self = this;
    $(this.head).click(function(){ self.hndl_click(); });
}
extend(spoiler, _ui);
mixin(spoiler.prototype, {
    'hndl_click': function() {
	if ($(this.head).hasClass('folded')) {
	    $(this.head).toggleClass('folded', false);
	    $(this.head).toggleClass('unfolded', true);
	    $(this.body).slideDown();
	} else {
	    $(this.head).toggleClass('unfolded', false);
	    $(this.head).toggleClass('folded', true);
	    $(this.body).slideUp();
	}
    }});

function ui_blog_news_anim() {
    var tmr;
    var loop_limit = 90;
    var abg = $('.side_right .blog_news .bg_a');

    if (! abg.length)
        return;
    var anim = function(){
        if (loop_limit <= 0) {
            clearInterval(tmr);
            return;
        }
        loop_limit -= 1;
        
        abg.css({'left': '-750px'});
        abg.animate({'left': '250px'}, 20000);
    };

    abg.css({'left': '250px'});
    tmr = setInterval(anim, 60000);
    anim();
}

function ac_tag_recfmt(row, i, num) {
    var cnt = Number(row[1]);
    var cnt_one = cnt % 10;
    var dim;

    if (cnt_one == 1 && (cnt < 10 || 20 < cnt))
        dim = 'пазл';
    else if (cnt_one < 5 && 0 < cnt && (cnt < 10 || 20 < cnt))
        dim = 'пазла';
    else
        dim = "пазлов";

    return row[0] +'<span class="qnt">'+ row[1] +' '+ dim +'</span>';
}

_cloak_mask = 'I:3c\x1akF`A(C#\x06MT\x0c^\x01\x13skc,pX1t?\x1d{0|\x18/[&\x19&4|a\x16:dge\x19XNno~&jk_zU\x00h55ydMCj\x16K(s\x01\x18\n\x13hap\x14wj[CCl\x1c\x14;!M^g\x1b\x02 \x051N\x07?dT6\x17\x01\x1b\x08xe70.%6\x12H1G2fWs\x05<\x00.\x1f';
function uncloak(inp, fake) {
    var idx;
    if (fake === undefined)
        fake = '';

    var data = '';
    var inp = eval(inp);
    var cml = _cloak_mask.length;
    for (idx = 0; idx < inp.length; idx++) {
        var ent = inp[idx];
        if (idx < fake.length) 
            ent ^= fake.charCodeAt(idx);
        ent ^= _cloak_mask.charCodeAt(idx % cml);
        if (! ent)
            break;
        data += String.fromCharCode(ent);
    }
    return data;
}

$(document).ready(function(){
    var encl;

    encl = document.createElement('div');
    encl.setAttribute('class', 'tooltip tooltip_imglink');

    function tooltip_in() {
	var id = this.getAttribute('image_id');
	var img;

	img = document.createElement('img');
        var src = '/image/' + id + '/preview.jpg';
	img.setAttribute('src', src);
	encl.appendChild(img);
	$('body').append(encl);

	var x, y, pos = $(this).offset();
	x = Math.floor(pos.left - $(encl).width() - 10);
	y = Math.floor(pos.top - $(encl).height() - 10);
	$(encl).css('left', x);
	$(encl).css('top', y);
    }
    function tooltip_out() {
	$(encl).remove();
	$(encl).html('');
    }

    $('.spoiler').each(function(){
	new spoiler(this);
    });
    $("a[image_id]").each(function(){
	$(this).mouseover(tooltip_in);
	$(this).mouseout(tooltip_out);
    });

    // uncloak links
    $('span.cloaked').each(function(){
        var a = document.createElement('a');
        $(this).find('>.data').each(function(){
            var d = $(this).find('>.val').text();
            var fake = $(this).find('>.pub').text();
            d = uncloak(d, fake);
            var ent = $(this).find('>.attr');
            if (ent.length)
                a.setAttribute(ent.text(), d);
            else
                $(a).append(document.createTextNode(d));
        });
        if (! a.childNodes.length) 
            $(ent).append(document.createTextNode(a.getAttribute('href')));
        $(this).replaceWith(a);
    });
}); 
/* --- js/ui.js -- end --------------------------------------------- */

