//
// Flagatrip scripts
// Author: Alexey V. Ivanov <mail@aivanov.com>
// Author: Eugen Zhurakhovskyy <txc.work@gmail.com>
//

// Хак для подавления некритичной ошибки в IE6
window.onerror = function(str) { return (str.indexOf('container') >= 0) }

Flagatrip = { version: '1.0' }
/*
Object.extend(Hash, {
  toQueryString: function(obj) {
    var parts = [];

      this.prototype._each.call(obj, function(pair) {
      if (!pair.key) return;

      if (pair.value && pair.value.constructor == Array) {
        var values = pair.value.compact();
        if (values.length < 2) pair.value = values.reduce();
        else {
                key = encodeURIComponent(pair.key);
          values.each(function(value) {

            value = value || '';

            parts.push(key + '=' + encodeURIComponent(value));
          });
          return;
        }
      }
      if (pair.value == undefined) pair[1] = '';
      parts.push(pair.map(encodeURIComponent).join('='));
          });

    return parts.join('&');
  }
});
*/

FAjax = new Class({
    Extends: Request.JSON,
    initialize: function(url, options) {
        //this.addEvent('onSuccess', this.onComplete);
        this.options = options;
        this.options.url = url;
        this.options.method = 'post';

        this.parent(this.options);
        this.setHeader('Content-Type', 'application/x-www-form-urlencoded');

    },

    send: function(obj) {
    var k;
    if(!obj) return '';
    //console.log(obj);
    if ( $type(obj) == 'string' )
      k = obj
    else
      k = Hash.toQueryString(obj) ;

    var a = this.parent(k);
    return a;
    },

    onComplete: function(){
        this.fireEvent('onComplete', [JSON.decode(this.response.text, this.options.secure)]);
    }

});

FTooltip = new Class({

    options: {
        timeout : 2000
    },

    initialize: function(options){
        this.element = new Element('div').injectInside(document.body);
        this.setOptions(options);
        this.timeoutId = 0;
        this.fx = new Fx.Morph(this.element, {duration: 500, link: 'cancel'}).start({opacity : 0});
    },

    show: function(text, opts){
        clearTimeout(this.timeoutId);
        if (opts) {
            b = FUtils.getObjectBounds(opts.anchor);
            this.element.setStyles({
                left: b.left + opts.left || 0,
                top: b.top + opts.top || 0
            });
        }
        this.element.className = 'tooltip' + (opts && opts.altClass ? ' ' + opts.altClass : '');
        this.element.set('html',text);
        this.timeoutId = setTimeout(this.hide.bind(this), (opts && opts.timeout) || this.options.timeout);
        //this.fx.start(1);
        this.fx.start({opacity : 1});
    },

    hide: function(){
        this.fx.start({opacity : 0});
    }

});

FTooltip.implement(new Options);


Flagatrip.authRequired = function(link) {
    tooltip.show('Пожалуйста, авторизуйтесь сначала', {anchor:link, left:0, top:-30});
}


Flagatrip.notImplementedYet = function(link) {
    tooltip.show('Скоро', {anchor:link, left:0, top:-30});
}


FUserRating = {

    // Static method
    vote: function(link, postId, userClass, where) {
        new FAjax('/ajax.php?action=userrating.vote', {
            onComplete: function(data) {
                if (data.result) {
                    link.onclick = null;
                    var p = $(link).getParent();
                    p.addClass('voted');
                    document.getElements('.' + userClass).forEach(function(obj){
                        obj.firstChild.nodeValue = Number(obj.firstChild.nodeValue) + 1;
                    })
                    tooltip.show('Спасибо!', {anchor:link, left:0, top:-30});
                } else {
                    tooltip.show('Ваш голос уже учтён', {anchor:link, left:0, top:-30});
                }
            }.bind(this)
        }).send({'postId' : postId, 'where' : where});
    }

}


FReportRating = new Class({

    options: {
    },

    initialize: function(el, reportId){
        this.element = el;
        this.reportId = reportId;
        this.element.setStyle('cursor', 'pointer');
        // if (this.element.lastChild.nodeType != 3) {
        //      this.element.appendText(' ');
        // }
        this.starsSpan  = this.element.getFirst();
        this.maxX = this.starsSpan.offsetWidth;
        this.tempValue  = 0;
        this.ratedValue = 0;

        this.element.addEvents({
            'mouseenter': this.mouseEnterHandler.bindWithEvent(this),
            'mousemove':  this.mouseMoveHandler.bindWithEvent(this),
            'mouseleave': this.mouseLeaveHandler.bindWithEvent(this),
            'click': this.clickHandler.bindWithEvent(this)
        });
        this.fx = new Fx.Tween(this.starsSpan, {duration: 500, link: 'cancel'}).set('background-color', '#00A8EE');
    },

    mouseEnterHandler: function(e) {
        this.elementBounds = FUtils.getObjectBounds(this.element);
        this.fx.start('#FF0000');
    },

    mouseMoveHandler: function(e) {
        if (!this.request && this.elementBounds) {
            var x = e.client.x - this.elementBounds.left;
            var r = Math.max(1, Math.min(5, x * 5 / this.maxX));
            this.tempValue = r;
            this.drawValue(r);
        }
    },

    mouseLeaveHandler: function(e) {
        if (!this.request) {
            this.drawValue(0);
        }
    },

    drawValue: function(r) {
        this.starsSpan.setStyle('background-position', Math.round(r * this.maxX / 5)  + 'px 0');
        this.element.lastChild.nodeValue = r ? ' ' + r.toFixed(1) : '\xA0';
    },

    clickHandler: function(e) {
        this.fx.start('#00A8EE');
        this.request = new FAjax('/ajax.php?action=reportrating.vote', {
            onComplete: function(data) {
                this.request = null;
                if (data.errors) {
                    this.drawValue(0);
                    tooltip.show(data.errors, {altClass:'error', anchor:this.element, left:0, top:-30});
                } else if (data.result) {
                    //tooltip.show('Ваш голос засчитан!', {anchor:this.element, left:0, top:-30});
                    this.ratedValue = this.tempValue;
                    this.element.removeEvents();
                    this.element.setStyle('cursor', 'default');
                }
            }.bind(this)
        }).send({'reportId' : this.reportId, 'rating' : this.tempValue});
    }

});


FVideoRating = new Class({

    options: {
    },

    initialize: function(el, videoId){
        this.element = el;
        this.videoId = videoId;
        this.element.setStyle('cursor', 'pointer');
        // if (this.element.lastChild.nodeType != 3) {
        //      this.element.appendText(' ');
        // }
        this.starsSpan  = this.element.getFirst();
        this.maxX = this.starsSpan.offsetWidth;
        this.tempValue  = 0;
        this.ratedValue = 0;

        this.fx = new Fx.Tween(this.starsSpan, {duration: 500, link: 'cancel'}).set('background-color', '#00A8EE');

        this.element.addEvents({
            'mouseenter': this.mouseEnterHandler.bindWithEvent(this),
            'mousemove':  this.mouseMoveHandler.bindWithEvent(this),
            'mouseleave': this.mouseLeaveHandler.bindWithEvent(this),
            'click': this.clickHandler.bindWithEvent(this)
        });
    },

    mouseEnterHandler: function(e) {
        this.elementBounds = FUtils.getObjectBounds(this.element);
        this.fx.start('#FF0000');
    },

    mouseMoveHandler: function(e) {
        if (!this.request && this.elementBounds) {
            var x = e.client.x - this.elementBounds.left;
            var v = Math.max(1, Math.min(5, x * 5 / this.maxX));
            this.tempValue = v;
            this.drawValue(v);
        }
    },

    mouseLeaveHandler: function(e) {
        if (!this.request) {
            this.drawValue(0);
        }
    },

    drawValue: function(v) {
        this.starsSpan.setStyle('background-position', Math.round(v * this.maxX / 5)  + 'px 0');
        this.element.lastChild.nodeValue = v ? ' ' + v.toFixed(1) : '\xA0';
    },

    clickHandler: function(e) {
        this.fx.start('#00A8EE');
        this.request = new FAjax('/ajax.php?action=videorating.vote', {
            onComplete: function(data) {
                this.request = null;
                if (data.errors) {
                    this.drawValue(0);
                    tooltip.show(data.errors, {altClass:'error', anchor:this.element, left:0, top:-30});
                } else if (data.result) {
                    //tooltip.show('Ваш голос засчитан!', {anchor:this.element, left:0, top:-30});
                    this.ratedValue = this.tempValue;
                    this.element.removeEvents();
                    this.element.setStyle('cursor', 'default');
                }
            }.bind(this)
        }).send({'videoId' : this.videoId, 'rating' : this.tempValue});
    }

});


FPhotoRating = new Class({

    options: {
    },

    initialize: function(el, photoId){
        this.element = el;
        this.photoId = photoId;
        this.element.setStyle('cursor', 'pointer');
        // if (this.element.lastChild.nodeType != 3) {
        //      this.element.appendText(' ');
        // }
        this.starsSpan  = this.element.getFirst();
        this.maxX = this.starsSpan.offsetWidth;
        this.tempValue  = 0;
        this.ratedValue = 0;

        this.element.addEvents({
            'mouseenter': this.mouseEnterHandler.bindWithEvent(this),
            'mousemove':  this.mouseMoveHandler.bindWithEvent(this),
            'mouseleave': this.mouseLeaveHandler.bindWithEvent(this),
            'click': this.clickHandler.bindWithEvent(this)
        });
        this.fx = new Fx.Tween(this.starsSpan, {duration: 500, link: 'cancel'}).set('background-color', '#00A8EE');
    },

    mouseEnterHandler: function(e) {
        this.elementBounds = FUtils.getObjectBounds(this.element);
        this.fx.start('#FF0000');
    },

    mouseMoveHandler: function(e) {
        if (!this.request && this.elementBounds) {
            var x = e.client.x - this.elementBounds.left;
            var r = Math.max(1, Math.min(5, x * 5 / this.maxX));
            this.tempValue = r;
            this.drawValue(r);
        }
    },

    mouseLeaveHandler: function(e) {
        if (!this.request) {
            this.drawValue(0);
        }
    },

    drawValue: function(r) {
        this.starsSpan.setStyle('background-position', Math.round(r * this.maxX / 5)  + 'px 0');
        this.element.lastChild.nodeValue = r ? ' ' + r.toFixed(1) : '\xA0';
    },

    clickHandler: function(e) {
        this.fx.start('#00A8EE');
        this.request = new FAjax('/ajax.php?action=photorating.vote', {
            onComplete: function(data) {
                this.request = null;
                if (data.errors) {
                    this.drawValue(0);
                    tooltip.show(data.errors, {altClass:'error', anchor:this.element, left:0, top:-30});
                } else if (data.result) {
                    //tooltip.show('Ваш голос засчитан!', {anchor:this.element, left:0, top:-30});
                    this.ratedValue = this.tempValue;
                    this.element.removeEvents();
                    this.element.setStyle('cursor', 'default');
                }
            }.bind(this)
        }).send({'photoId' : this.photoId, 'rating' : this.tempValue});
    }

});


/**
 * Полезные функции
 */
FUtils = {};
FUtils.getObjectBounds = function(element) {

    var left = element.offsetLeft;
    var top  = element.offsetTop;
    for (var parent = element.offsetParent; parent; parent = parent.offsetParent) {
        left += parent.offsetLeft - (parent.offsetParent ? parent.scrollLeft : 0);
        top  += parent.offsetTop -  (parent.offsetParent ? parent.scrollTop : 0);
    }
    return {left: left, top: top, width: element.offsetWidth, height: element.offsetHeight};
}


/**
 * Класс для создания ajax-окон
 */
FWindow = new Class({

    options: {
    },

    initialize: function(link, className) {
        //alert(FUtils.getObjectBounds(link))
        var bounds = FUtils.getObjectBounds(link);
        this.element = new Element('div', {'class': 'fwindow ' + (className || ''), 'styles': {'left': bounds.left + bounds.width / 2, 'top': bounds.top}}).injectInside(document.body);
        this.contentElement = new Element('div', {'class': 'content'});
        this.contentElement.addEvent('click', function (e) { (e || event).stopPropagation(); });
        this.element.appendChild(this.contentElement);
        this.shadow = new Element('div', {'class': 'shadow'});
        this.element.appendChild(this.shadow);
        this.removeFunction = this.remove.bindWithEvent(this);

        setTimeout(
            function() {
                $(document.body).addEvent('click', this.removeFunction);
            }.bind(this),
            0
        );
    },

    createIframe: function () {
        if (!this.iframe) {
            this.iframe = this.contentElement.appendChild(new Element('iframe', {'src': 'javascript:;', 'frameborder': 0}));
            this.addCloseButton();
        }
    },

    setHTML: function (html) {
        this.contentElement.set('html',html);
        this.addCloseButton();
    },

    load: function (url_val, iframe) {
        if (iframe) {
            this.createIframe();
            this.iframe.src = url_val;
        } else {
            new Request.HTML({url: url_val, method:'get', update:this.contentElement, evalScripts:true}).send();
        }
    },

    remove: function() {
        this.element.dispose();
        $(document.body).removeEvent('click', this.removeFunction);
        delete this.element;
    },

    addCloseButton: function() {
        this.contentElement.appendChild(new Element('span', {'class': 'close_button', title: 'Закрыть окно', events:{ click: this.removeFunction }}));
    }

});


/**
 * Диалог для создания приглашений
 * @example new InviteDialog($(anchor_element), 'profile')
 */
InviteDialog = new Class({
    Extends: FWindow,
    initialize: function(link, what, options) {
        this.parent(link, (options && options.style) || 'fwindow_map');
        this.location = (options && options.location) || location;
        var text = 'Приглашаю вас присоединиться к FLAGATRIP.';
        if (what == 'report') {
            text = 'Приглашаю на просмотр отчёта о поездке\n'; //+ location;
        } else if (what == 'plan_trip') {
            text = 'Приглашаю на просмотр планируемой поездки\n'; //+ location;
        } else if (what == 'photo') {
            text = 'Приглашаю просмотреть фотографии моей поездки\n'; //+ location;
        } else if (what == 'community') {
            text = 'Приглашаю присоединиться к сообществу «' + options.name + '» (' + location + '), созданному мной в сервисе FLAGATRIP.';
        } else {
            text += '\n\nFLAGATRIP – это место для любителей поездок и путешествий. Здесь можно завести свою страничку и карту поездок, делиться впечатлениями с друзьями, общаться в сообществах и просто приятно проводить время.';
        }
        //text += '\n\nFLAGATRIP – это место для любителей поездок и путешествий. Здесь можно завести свою страничку и карту поездок, делиться впечатлениями с друзьями, общаться в сообществах и просто приятно проводить время.';
        if((what != 'report') && (what != 'photo') && (what != 'community') && (what != 'plan_trip'))
        {
            this.setHTML('\
                <form id="invite_dialog_form" action="/ajax.php?action=invite.' + what + '" method="post">\
                    <input type="hidden" name="location"/>\
                    <div style="margin: 5px 0;">Введите адреса тех, кого хотите пригласить:</div>\
                    <div><textarea name="emails" class="emailes"></textarea></div>\
                    <br />\
                    <div style="margin: 0 0 5px 0;">Введите текст приглашения:</div>\
                    <div><textarea name="text" class="message">' + text + '</textarea></div>\
                    <div style="margin: 5px 0;">Все приглашенные автоматически будут добавлены в список ваших друзей.</div>\
                    <div style="margin-top: 10px; text-align: right; width: 98%;"><input type="submit" id="sendinvites_button" value="Пригласить"/></div>\
                </form>\
            ');
        } else {
            this.setHTML('\
                <form id="invite_dialog_form" action="/ajax.php?action=invite.' + what + '" method="post">\
                    <input type="hidden" name="location"/>\
                    <div style="margin: 5px 0;">Введите адреса тех, кого хотите пригласить:</div>\
                    <div><textarea name="emails" class="emailes"></textarea></div>\
                    <br />\
                    <div style="margin: 0 0 5px 0;">Введите текст приглашения:</div>\
                    <div><textarea name="text" class="message">' + text + '</textarea></div>\
                    <div style="margin: 5px 0;"></div>\
                    <div style="margin-top: 10px; text-align: right; width: 98%;"><input type="submit" id="sendinvites_button" value="Пригласить"/></div>\
                </form>\
            ');
        };

        this.form = $('invite_dialog_form');
        this.submitButton = $('sendinvites_button').addEvent('click', this.send.bindWithEvent(this));
    },

    send: function(e) {
        e.stop();
        this.submitButton.disabled = true;
        this.form.location.value = this.location;
        new FAjax(this.form.action, {
            onComplete: function(data) {
                this.submitButton.disabled = false;
                if (data.result > 0) {
                    if(data.long)
                    {
                        var wait = data.long;
                        tooltip.show(data.message, {anchor:this.submitButton, left:-210, top:-5, timeout:wait});
                    } else {
                        tooltip.show(data.message, {anchor:this.submitButton, left:-210, top:-5});
                    };
                    this.remove();
                } else {
                    tooltip.show(data.message, {anchor:this.submitButton, left:0, top:-30});
                }
            }.bind(this)
        }).send(this.form.toQueryString());
    }

});


/**
 * Диалог для обратной связи
 * @param HTMLElement link
 * @param String subj
 * @param String view
 * @example new FeedbackDialog($(anchor_element), 'profile')
 */
FeedbackDialog = new Class({
    Extends: FWindow,
    initialize: function(link, subj, view) {
        this.eventAnchor = link;
        this.parent(link, 'fwindow_feedback ' + (view || ''));
        var opts = [
            ['feedback', 'Сообщение администрации'],
            ['worlddb',  'Добавить город на карту'],
            ['suggest',  'Предложение по улучшению']
        ];
        var selectHtml = '<select name="subject" style="width: 98%;">';
        for (var i=0; i < opts.length; ++i) {
            selectHtml += '<option' + (opts[i][0] == subj ? ' selected="selected"' : '') + '>' + opts[i][1] + '</option>';
        }
        selectHtml += '</select>';
        this.setHTML('\
            <form id="feedback_dialog_form" action="ajax.php?action=develop.feedback" method="post" style="padding: 10px;">\
                <div style="margin: 5px 0;">Введите ваш e-mail:</div>\
                <div><input type="text" name="email" class="text" style="width: 95%;"/></div>\
                <br />\
                <div style="margin: 5px 0;">Выберите тему:</div>\
                <div>' + selectHtml + '</div>\
                <br />\
                <div style="margin: 5px 0;">Опишите проблему или предложение:</div>\
                <div><textarea name="text" style="width: 96%; height: 95px; overflow-y:scroll"></textarea></div>\
                <div style="margin-top: 10px; text-align: right; width: 98%;"><input type="submit" id="sendfeedback_button" value="Отправить"/></div>\
            </form>\
        ');

        this.form = $('feedback_dialog_form');
        this.submitButton = $('sendfeedback_button').addEvent('click', this.send.bindWithEvent(this));
    },

    send: function(e) {
        e.stop();
        this.submitButton.disabled = true;
        new FAjax(this.form.action, {
            onComplete: function(data) {
                this.submitButton.disabled = false;
                if (data.result > 0) {
                    tooltip.show('Спасибо!', {anchor:this.eventAnchor, left:0, top:15});
                    //this.form.reset();
                    this.remove();
                } else {
                    tooltip.show(data.errors, {altClass:'error', anchor:this.submitButton, left:0, top:-30});
                }
            }.bind(this)
        }).send(this.form.toQueryString() + '&location=' + encodeURIComponent(document.location));
    }

});


/**
 * Диалог для приватных сообщений
 * @param HTMLElement link
 * @param String subj
 * @param String view
 * @example new PrivateMailDialog($(anchor_element), 'profile')
 */
PrivateMailDialog = new Class({
    Extends: FWindow,
    initialize: function(link, id) {
        this.eventAnchor = link;
        this.recipient = id;

        this.parent(link, 'fwindow_feedback ');

        var linkX = this.element.offsetLeft - (document.documentElement.scrollLeft || document.body.scrollLeft);
        var linkY = this.element.offsetTop - (document.documentElement.scrollTop || document.body.scrollTop);

        var cx = this.shadow.offsetLeft;
        var cy = this.shadow.offsetTop;
        var w = this.shadow.offsetWidth;
        var h = this.shadow.offsetHeight;
        var scrW = document.documentElement.clientWidth || document.body.clientWidth;
        var scrH = document.documentElement.clientHeight || document.body.clientHeight;

        var rightX = linkX + w + cx;
        var bottomY = linkY + h + cy;
        var topY = linkY + cy;
        var leftX = linkX + cx;

        if (leftX < 0 && topY > 0) this.element.addClass('tt');//alert('x < 0 не уместился слева');
        if (topY < 0 && leftX > 0) this.element.addClass('tr');//alert('y < 0 не уместился сверху');
        if (leftX < 0 && topY < 0) this.element.addClass('tl');//alert('не уместился сверху и слева');

        //if (rightX > scrW) alert('x > width не уместился справа');
        //if (bottomY > scrH) alert('y > height не уместился снизу');


        this.setHTML('\
            <form id="privmes_dialog_form" action="ajax.php?action=private.message" method="post" style="padding: 10px;">\
                <br />\
                <div style="margin: 5px 0;">Напишите текст сообщения ниже:</div>\
                <div><textarea name="text" style="width: 96%; height: 175px; overflow-y:scroll"></textarea></div>\
                <div style="margin-top: 10px; text-align: right; width: 98%;"><input type="submit" id="sendprivmes_button" value="Отправить" title="Ctrl + Enter" /></div>\
            </form>\
        ');

        this.form = $('privmes_dialog_form');
        this.form.addEvent('keydown', this.keyHandler.bindWithEvent(this));
        this.submitButton = $('sendprivmes_button').addEvent('click', this.send.bindWithEvent(this));
    },

    keyHandler: function(e) {
        if ((e.key == 'enter') && e.control) {
            this.send(e);
        }
    },

    send: function(e) {
        e.stop();
        this.submitButton.disabled = true;
        new FAjax(this.form.action, {
            onComplete: function(data) {
                this.submitButton.disabled = false;
                if (data.result > 0) {
                    tooltip.show('Ваше сообщение отправлено', {anchor:this.eventAnchor, left:0, top:15});
                    //this.form.reset();
                    this.remove();
                } else {
                    tooltip.show(data.errors, {altClass:'error', anchor:this.submitButton, left:0, top:-30});
                }
            }.bind(this)
        }).send(this.form.toQueryString() + '&recipient=' + this.recipient);
    }

});


/**
 * Класс для создания текстовых полей с подсказкой внутри, которая исчезает при получении фокуса
 * По умолчанию устанавливается для всех элементов с class="compact_input"
 */
CompactInput = new Class({

    initialize: function(obj) {
        if(!obj) return false;
        if (obj.value == '') obj.value = obj.title;
        obj.addEvent('focus', this.ciFocusHandler);
        obj.addEvent('blur',  this.ciBlurHandler);
    },

    ciFocusHandler: function(e) {
        e = new Event(e);
        if (e.target.value == e.target.title) {
            e.target.value = '';
        }
        $(e.target).addClass('active');
    },

    ciBlurHandler: function(e) {
        e = new Event(e);
        if (e.target.value == '') {
            e.target.value = e.target.title;
        }
        $(e.target).removeClass('active');
    }

});


/**
 * Класс для управления формой комментария
 */
FReplyForm = new Class({

    initialize: function(form) {
        this.slide = new Fx.Slide(form.getFirst(), {onComplete:function(){}});
        this.slide.hide();
        this.isOpened = false;
        this.form = form;
        this.textarea = form.getElementsByTagName('textarea')[0];
        if (this.textarea && this.textarea.id) {
            tinyMCE.init({
                mode  : "exact",
                theme : "simple",
                plugins : "noneditable,contextmenu",
                noneditable_noneditable_class: 'image_container',
                extended_valid_elements : "object[width|height],param[name|value],embed[src|type|wmode|width|height]",
                relative_urls : false,
                elements: this.textarea.id,
                remove_script_host : false,
                oninit : function(){ this.editorInit = true }.bind(this)
            });
        } else {
            alert('В форме обязательно должна присутствовать textarea с уникальным id')
        }
    },

    move: function(target) {
        if (this.isOpened && this.formContainer == target) {
            this.hide();
            this.formContainer = null;
        } else {
            this.formContainer = target;

            // FF & Opera workaround

            var tmce = tinyMCE.getInstanceById(this.textarea.id);
            var hackEnabled = (!tinyMCE.isIE || tinyMCE.isOpera) && this.editorInit;

            if (hackEnabled && tmce) {
                tinyMCE.removeMCEControl(tmce.editorId);
            }

            this.form.setStyle('display', 'block').injectAfter($(target).getParent());

            if (hackEnabled) {
                tinyMCE.execCommand("mceAddControl", true, this.textarea.id);
            }

            this.show();
        }
    },

    hide: function() {
        this.slide.slideOut();
        this.isOpened = false;
    },

    show: function() {
        this.slide.slideIn();
        this.isOpened = true;
    },

    send: function(btn) {
        var c = this.textarea.value = tinyMCE.getContent(this.textarea.id);
        if (c == '') {
            tooltip.show('Введите текст комментария', {altClass:'error', anchor:btn, left:200, top:1});
            return false;
        }
        $('comment_form_loader').setStyle('display', 'block');
        new FAjax(this.form.action, {
            onComplete: function(data) {
                $('comment_form_loader').setStyle('display', 'none');
                if (data.result) {
                    this.hide();
                    document.body.innerHTML = '<div style="position:absolute; left:0; width:100%; top:11px; text-align:center;">Загрузка...</div>';
                    var l = location.href.split('#');
                    var h = data.href.split('#');
                    if (l[0] == h[0]) {
                        location.hash = '#' + h[1];
                        location.reload(true);
                    } else {
                        location = data.href;
                    }
                    //location = String(location).replace(/#answer.*/, '');
                } else {
                    tooltip.show(data.errors, {altClass:'error', anchor:btn, left:200, top:1, timeout:10000});
                }
            }.bind(this)
        }).send(this.form.toQueryString());
        return false;
    }

});

/**
 * Класс для управления формой комментария (новый редактор)
 */
FReplyFormNew = new Class({

    initialize: function(form, uid) {
        this.slide = new Fx.Slide(form.getFirst(), {
            onComplete:function(){}
        });
        this.slide.hide();
        this.isOpened = false;
        this.form = form;
        this.textarea = form.getElementsByTagName('textarea')[0];
        var tmpdomain = document.domain;
        if (this.textarea && this.textarea.id) {
            tinyMCE.init({
                // General options
                mode : "none",
                theme : "advanced",
                skin : "flagatrip_mini",
                plugins : "flag_table,save,flag_advimage,flag_advlink,flag_emotions,flag_code,flag_inlinepopups,flag_media,paste, safari",
                language : "ru",
                // Theme options
                inlinepopups_skin : 'flagatrip2',
                paste_auto_cleanup_on_paste : 'true',
                paste_remove_spans : 'true',
                paste_remove_fonts : 'true',
                paste_remove_styles : 'true',
                paste_text_use_dialog :'false',
                theme_advanced_buttons1 : "bold,italic,underline,bullist,link,emotions,image",
                theme_advanced_buttons2 : "",
                theme_advanced_buttons3 : "",
                theme_advanced_buttons4 : "",
                theme_advanced_toolbar_location : "top",
                theme_advanced_toolbar_align : "left",
                theme_advanced_statusbar_location : "none",
                theme_advanced_resizing_min_height : 200,
                theme_advanced_resizing : true,
                theme_flagatrip_userhost : tmpdomain,
                object_resizing : false,
                user_id : uid
            });

        } else {
            alert('В форме обязательно должна присутствовать textarea с уникальным id')
        }
    },

    move: function(target, options) {
    	options = options || {};

        if (this.isOpened && this.formContainer == target) {
            this.hide();
            this.formContainer = null;
        } else {
            this.formContainer = target;
            var tmce = tinyMCE.getInstanceById(this.textarea.id);
            if(tmce) {
                tinyMCE.execCommand('mceFocus', true, this.textarea.id);
                tinyMCE.execCommand('mceRemoveControl', true, this.textarea.id);
            }
            this.form.setStyle('display', 'block').injectAfter($(target).getParent());
            tinyMCE.execCommand("mceAddControl", true, this.textarea.id);
            this.form.getElementById(this.textarea.id + '_parent').style.display = 'block';
            this.show();

            if (typeof options.setContent != 'undefined') {
                this.textarea.value = options.setContent;
                tinyMCE.updateContent('commentTextarea');
            }

        }
    },

    hide: function() {
        this.slide.slideOut();
        this.isOpened = false;
    },

    show: function() {
        this.slide.slideIn();
        this.isOpened = true;
    },

    send: function(btn) {
        var c = this.textarea.value = tinyMCE.get(this.textarea.id).getContent(); //");//tinymce.getContent(this.textarea.id);

        if (c == '') {
            tooltip.show('Введите текст комментария', {
                altClass:'error',
                anchor:btn,
                left:200,
                top:1
            });
            return false;
        }
        $('comment_form_loader').setStyle('display', 'block');
        new FAjax(this.form.action, {
            onComplete: function(data) {
                $('comment_form_loader').setStyle('display', 'none');
                if (data.result) {
                    this.hide();

                    if (!data.comment_id) {
                        document.body.innerHTML = '<div style="position:absolute; left:0; width:100%; top:11px; text-align:center;">Загрузка...</div>';
                        var l = location.href.split('#');
                        var h = data.href.split('#');
                        if (l[0] == h[0]) {
                            location.hash = '#' + h[1];
                            location.reload(true);
                        } else {
                            location = data.href;
                        }
                    } else {
						$('comment-'+data.comment_id).getElement('.report_body').innerHTML = c;
                    }

                    submited = false;

                } else {
                    tooltip.show(data.errors, {
                        altClass:'error',
                        anchor:btn,
                        left:200,
                        top:1,
                        timeout:10000
                    });
                }
            }.bind(this)
        }).send(this.form.toQueryString());

        return false;
    }

});

/**
 * Класс для управления формой стены
 */
FWallReplyForm = new Class({

    initialize: function(form) {
        this.slide = new Fx.Slide(form.getFirst(), {onComplete:function(){}});
        this.slide.hide();
        this.isOpened = false;
        this.form = form;
        this.textarea = form.getElementsByTagName('textarea')[0];
        if (this.textarea && this.textarea.id) {
            tinyMCE.init({
                mode  : "exact",
                theme : "simple",
                plugins : "noneditable,contextmenu",
                noneditable_noneditable_class: 'image_container',
                extended_valid_elements : "object[width|height],param[name|value],embed[src|type|wmode|width|height]",
                relative_urls : false,
                elements: this.textarea.id,
                remove_script_host : false,
                oninit : function(){ this.editorInit = true }.bind(this)
            });
        } else {
            alert('В форме обязательно должна присутствовать textarea с уникальным id')
        }
    },

    move: function(target) {
        if (this.isOpened && this.formContainer == target) {
            this.hide();
            this.formContainer = null;
        } else {
            this.formContainer = target;

            // FF & Opera workaround

            var tmce = tinyMCE.getInstanceById(this.textarea.id);
            var hackEnabled = (!tinyMCE.isIE || tinyMCE.isOpera) && this.editorInit;

            if (hackEnabled && tmce) {
                tinyMCE.removeMCEControl(tmce.editorId);
            }

            this.form.setStyle('display', 'block').injectAfter($(target).getParent());

            if (hackEnabled) {
                tinyMCE.execCommand("mceAddControl", true, this.textarea.id);
            }

            this.show();
        }
    },

    hide: function() {
        this.slide.slideOut();
        this.isOpened = false;
    },

    show: function() {
        this.slide.slideIn();
        this.isOpened = true;
    },

    send: function(btn) {
        var c = this.textarea.value = tinyMCE.getContent(this.textarea.id);
        if (c == '') {
            tooltip.show('Введите текст комментария', {altClass:'error', anchor:btn, left:200, top:1});
            return false;
        }
        $('comment_form_loader').setStyle('display', 'block');
        new FAjax(this.form.action, {
            onComplete: function(data) {
                $('comment_form_loader').setStyle('display', 'none');
                if (data.result) {
                    this.hide();

                    $('profile-wall').set('html',data.result);
                    this.textarea.value = '';
                    tinyMCE.updateContent('commentTextarea');
                    /*
                    document.body.innerHTML = '<div style="position:absolute; left:0; width:100%; top:11px; text-align:center;">Загрузка...</div>';
                    var l = location.href.split('#');
                    var h = data.href.split('#');
                    if (l[0] == h[0]) {
                        location.hash = '#' + h[1];
                        location.reload(true);
                    } else {
                        location = data.href;
                    }
                    */
                    //location = String(location).replace(/#answer.*/, '');
                } else {
                    tooltip.show(data.errors, {altClass:'error', anchor:btn, left:200, top:1, timeout:10000});
                }
            }.bind(this)
        }).send(this.form.toQueryString());
        return false;
    }

});


/**
 * Класс для управления формой стены (новый редактор)
 */
FWallReplyFormNew = new Class({

    initialize: function(form, uid) {
        this.slide = new Fx.Slide(form.getFirst(), {onComplete:function(){}});
        this.slide.hide();
        this.isOpened = false;
        this.form = form;
        this.textarea = form.getElementsByTagName('textarea')[0];
                var tmpdomain = document.domain;
        if (this.textarea && this.textarea.id) {
            tinyMCE.init({
                // General options
                mode : "none",
                theme : "advanced",
                skin : "flagatrip_mini",
                plugins : "flag_table,save,flag_advimage,flag_advlink,flag_emotions,flag_code,flag_inlinepopups,flag_media,paste, safari",
                language : "ru",
                // Theme options
                inlinepopups_skin : 'flagatrip2',
                paste_auto_cleanup_on_paste : 'true',
                paste_remove_spans : 'true',
                paste_remove_fonts : 'true',
                paste_remove_styles : 'true',
                paste_text_use_dialog :'false',
                theme_advanced_buttons1 : "bold,italic,underline,bullist,link,emotions,image",
                theme_advanced_buttons2 : "",
                theme_advanced_buttons3 : "",
                theme_advanced_buttons4 : "",
                theme_advanced_toolbar_location : "top",
                theme_advanced_toolbar_align : "left",
                theme_advanced_statusbar_location : "none",
                theme_advanced_resizing_min_height : 200,
                theme_advanced_resizing : true,
                theme_flagatrip_userhost : tmpdomain,
                object_resizing : false,
                user_id : uid
            });
        } else {
            alert('В форме обязательно должна присутствовать textarea с уникальным id')
        }
    },

    move: function(target) {

                if (this.isOpened && this.formContainer == target) {
                    this.hide();
                    this.formContainer = null;
                } else {
                    this.formContainer = target;
                    this.form.setStyle('display', 'block').injectAfter($(target).getParent());
                    tinyMCE.execCommand("mceAddControl", true, this.textarea.id);
                    this.show();
                }
    },

    hide: function() {
        this.slide.slideOut();
        this.isOpened = false;
    },

    show: function() {
        this.slide.slideIn();
        this.isOpened = true;
    },

    send: function(btn) {

                var c = this.textarea.value = tinyMCE.get(this.textarea.id).getContent();

                if (c == '') {
                        tooltip.show('Введите текст комментария', {altClass:'error', anchor:btn, left:200, top:1});
                        return false;
                }
        $('comment_form_loader').setStyle('display', 'block');
        new FAjax(this.form.action, {
            onComplete: function(data) {
                $('comment_form_loader').setStyle('display', 'none');
                                if (data.result) {
                                    this.hide();
                                    $('profile-wall').set('html',data.result);
                                    this.textarea.value = '';
                                    tinyMCE.activeEditor.load();
                                    submited = false;
                                } else {
                                    tooltip.show(data.errors, {altClass:'error', anchor:btn, left:200, top:1, timeout:10000});
                                }
                        }.bind(this)
        }).send(this.form.toQueryString());

            return false;
    }

});

/**
 * Класс для составления списка тегов
 * @param HTMLElement
 * @param HTMLElement
 * @param String
 */
FTags = new Class({

    initialize: function(input, container, elementsName) {
        this.input = input;
        this.container = container;
        this.elementsName = elementsName || 'tags[]';
        this.input.addEvent('keypress', this.keyHandler.bindWithEvent(this))
        this.input.addEvent('blur', this.blurHandler.bindWithEvent(this))
    },

    keyHandler: function(e) {
        if (e.key == 'enter') {
            this.run();
            e.stop();
            return false;
        }
    },

    blurHandler: function(e) {
        if (this.input.value && (this.input.value != this.input.title)) {
            this.run();
        }
    },

    run: function() {
        this.addTags(this.parseTags(this.input.value), true);
        this.input.value = '';
    },

    parseTags: function(str) {
        return str.replace(/^\s+/, '').replace(/\s+$/, '').split(/\s*,\s*/);
    },

    addTags: function(arr, effect) {
        for (var i=0; i<arr.length; ++i) {
            if (arr[i]) {
                var attrs = {'class':'tag'};
                if (effect) {
                    // Если нужен эффект, то задаём начальные стили анимации
                    attrs['styles'] = {
                        'background-color': '#9CD51D',
                        'color': '#FFFFFF'
                    };
                }

                var tag = new Element('span', attrs).set('text',arr[i]);
                new Element('span',  {'events': {'click': tag.dispose.bind(tag)}}).set('html','&nbsp;').injectInside(tag);
                new Element('input', {'type': 'hidden', 'name': this.elementsName, 'value': arr[i]}).injectInside(tag);
                this.container.appendText(' ').appendChild(tag);

                if (effect) {
                    // Через секунду, после добавления, тег белеет
                    setTimeout(
                        function() {
                            new Fx.Morph(this, {duration:1000, link: 'cancel'}).start({'background-color': '#FFFFFF', 'color' : '#464646'});
                        }.bind(tag),
                        1000
                    );
                }
            }
        }
    }

});


/**
 * Класс для серверной проверки введённых в input/textarea данных
 * @param String
 * @param HTMLElement
 * @param HTMLElement optional
 */
FValidator = new Class({

    initialize: function(url, input, externalIndicator, submitBtn) {
        this.url = url;
        this.input = input;
        this.indicator = externalIndicator || input;
        this.submitBtn = submitBtn ? submitBtn : undefined;
        this.timeoutHandler = 0;
        this.input.addEvent('keypress', this.keyHandler.bindWithEvent(this));
        this.input.addEvent('keyup', this.keyHandler.bindWithEvent(this));
    },

    keyHandler: function () {
        if (this.timeoutHandler) {
            clearTimeout(this.timeoutHandler);
        }
        this.indicator.removeClass('fvalidator-error');
        this.indicator.removeClass('fvalidator-ok');
        this.timeoutHandler = setTimeout(this.validatorRequest.bind(this), 1200);
    },

    validatorRequest: function () {
        new FAjax(this.url + encodeURIComponent(this.input.value), {
            onComplete: function(data) {
                if (data.result) {
                    this.indicator.removeClass('fvalidator-error');
                    this.indicator.addClass('fvalidator-ok');
                    this.indicator.title = 'Ок';
                    this.indicator.empty();
                    var elem = new Element('span', {'class':'ok'});
                    elem.set('html',data.truetext);
                    this.indicator.appendChild(elem);
                    if (this.submitBtn){
                        this.submitBtn.setStyle('visibility', 'visible');
                    }
                } else if (data.error) {
                    this.indicator.removeClass('fvalidator-ok');
                    this.indicator.addClass('fvalidator-error');
                    this.indicator.title = 'Недоступно';
                    this.indicator.empty();
                    var elem = new Element('span', {'class':'error'});
                    elem.set('html',data.error);
                    this.indicator.appendChild(elem);
                    if (this.submitBtn){
                        this.submitBtn.setStyle('visibility', 'hidden');
                    }
                } else {
                    this.indicator.removeClass('fvalidator-ok');
                    this.indicator.addClass('fvalidator-error');
                    this.indicator.title = 'Недоступно';
                    this.indicator.empty();
                }
            }.bind(this)
        }).send(this.input.value);
    }
});


/* *
 * Класс для управления ссылкой подписки.
 *
 * @param  URI
 * @param  integer
 * @param  integer
 * @param  HTMLElement
 *
 * @return void
 */
SubscribeValidator = new Class({
    initialize:  function(url, who, whom, link) {
        this.url  = url;
        this.who  = who;
        this.whom = whom;
        this.link = link;
        this.link.addEvent('click', this.validatorRequest.bind(this));
    },

    validatorRequest: function () {
        // Перегрузка актуального состояния линка.
        this.link = $('subscribe');
        this.type = this.link.get('text');
        this.cl   = this.link.getProperty('class');

        if(this.cl == 'unsubscribe')
        {
            quest  = 'Вы действительно хотите удалить из списка друзей?';
            this.answer = 'Пользователь удален из вашего списка друзей.';
        } else if (this.cl == 'subscribe') {
            quest  = 'Подтвердить добавление друга?';
            this.answer = 'Пользователь добавлен в ваш список друзей.';
        };
        if(this.cl != 'nosubscribe')
        {
            this.res = confirm(quest);
        };

        new FAjax(this.url, {
            onComplete: function(data) {
                if (data.cl) {
                    if(!this.link.hasClass(data.cl) && !data.cl.test("fake"))
                    {
                        if(this.res)
                        {
                            this.link.removeClass(this.cl);
                            this.link.addClass(data.cl);
                            this.link.set('text',data.text);
                            tooltip.show(this.answer, {anchor:this.link, left:30, top:0});
                        };
                    };
                    if(data.cl == 'notauth') {
                        tooltip.show("Пожалуйста, авторизируйтесь или <a href='/registration.html'>зарегистрируйтесь</a>.", {anchor:this.link, left:30, top:0});
                    };
                }
            }.bind(this)
        }).send('who=' + this.who + '&whom=' + this.whom + '&type=' + this.cl + '&res=' + this.res);
    }
});


/* *
 * Класс для управления ссылкой подписки.
 *
 * @param  URI
 * @param  integer
 * @param  integer
 * @param  HTMLElement
 *
 * @return void
 */
PeopleSearch = new Class({
    initialize:  function(url, places, rest, button) {
        this.url     = url;
        this.places  = places;
        this.rest    = rest;
        this.button  = button;
        this.button.addEvent('click', this.validatorRequest.bind(this));
    },

    validatorRequest: function () {
        // Перегрузка актуального состояния линка.
        this.link = $('subscribe');
        this.type = this.link.getText();
        this.cl   = this.link.getProperty('class');

        if(this.cl == 'unsubscribe')
        {
            quest  = 'Вы действительно хотите удалить из списка друзей?';
            this.answer = 'Пользователь удален из вашего списка друзей.';
        } else if (this.cl == 'subscribe') {
            quest  = 'Подтвердить добавление друга?';
            this.answer = 'Пользователь добавлен в ваш список друзей.';
        };
        if(this.cl != 'nosubscribe')
        {
            this.res = confirm(quest);
        };

        new FAjax(this.url, {
            onComplete: function(data) {
                if (data.cl) {
                    if(!this.link.hasClass(data.cl) && !data.cl.test("fake"))
                    {
                        if(this.res)
                        {
                            this.link.removeClass(this.cl);
                            this.link.addClass(data.cl);
                            this.link.set('text',data.text);
                            tooltip.show(this.answer, {anchor:this.link, left:30, top:0});
                        };
                    };
                    if(data.cl == 'notauth') {
                        tooltip.show("Пожалуйста, авторизируйтесь или <a href='/registration.html'>зарегистрируйтесь</a>.", {anchor:this.link, left:30, top:0});
                    };
                }
            }.bind(this)
        }).send('who=' + this.who + '&whom=' + this.whom + '&type=' + this.cl + '&res=' + this.res);
    }
});


/**
 *
 */

ShowAllFriends = new Class ({
    initialize: function(link, listfield, member) {
        this.link       = link;
        this.listfield  = listfield;
        this.member     = member;
        this.linkid     = this.link.getProperty('id');
        this.link.addEvent('click', this.friendsRequest.bind(this));
    },

    friendsRequest: function() {
        new Request({url: 'ajax.php?action=friends.' + this.linkid + '&member=' + this.member,
            onComplete: function(data) {
                data = JSON.decode(data);
                if(data.listfield) {
                    //location.hash = data.address;
                    this.listfield.set('html',data.listfield);
                    $(this.link.parentNode).dispose();
                };
            }.bind(this),
            method:'get'
        }).send();
    }
});


/**
 * Класс для управления состоянием стенки: отобразить/скрыть
 */
WallToogle = new Class({
    initialize: function(wallToogle) {
        this.wallToogle = wallToogle;
        this.wallToogle.addEvent('click', this.visio.bind(this));
    },

    visio: function() {
        var statusSW = 'showWall';
        var statusHW = 'hideWall';

        this.wallBlock = $('profile-wall');
        this.cl = this.wallBlock.getProperty('class');

        if(this.cl == statusSW) {
            this.wallBlock.removeClass(this.cl);
            this.wallBlock.addClass(statusHW);
        } else {
            this.wallBlock.removeClass(this.cl);
            this.wallBlock.addClass(statusSW);
        };
    }
});


HootelView = new Class({
    Extends: FWindow,
    initialize: function(link, img_src) {
        this.eventAnchor = link;
        this.parent(link, 'fwindow_feedback ');
        this.setHTML('\<div ><img style="width: 283px;" src="'+link.src+'"></div>\ ');
    },

    addCloseButton: function() {}
});

var searchId = 0;
window.flags = [];


function moveToCountry(cityId) {
    if (flags[cityId]) {
        var f = flags[cityId];
        showReportWindow(f);
    }
}


function showReportWindow(f, zoom) {
    if (f && f.options && f.options.cityId) {
        gmap.setCenter(f.options.point, zoom);
        new Request({url: 'ajax.php?action=planatrip.randomcoverbyowner&place=' + f.options.cityId + '&owner=' + f.options.ownerId,
            onComplete: function(data) {
                data = JSON.decode(data);
                if(data) {
                    if(data.photoId)
                    {
                        f.openInfoWindowHtml(
                            '<div style="padding:4px 6px;">' +
                                f.options.info +
                                '<div id="planatrip_left_right_col">' +
                                    '<div id="planatrip_left_col">' +
                                        '<div class="round_corners" style="margin-top:10px;">' +
                                            '<span class="wrap">' +
                                                '<a class="photo" href="/photo_files/id/' + data.folderId + '.html">' +
                                                    '<img alt="' + data.folderName + '" src="/photos/55!x55!/' + data.photoId + '.' + data.photoExt + '" height="55px" width="55px"/>' +
                                                '</a>' +
                                                '<span class="rc1"></span><span class="rc3"></span><span class="rc7"></span><span class="rc9"></span>' +
                                            '</span>' +
                                        '</div>' +
                                    '</div>' +
                                    '<div id="planatrip_right_col">' +
                                        '<div style="padding-top: 10px;">Отчётов: ' +
                                            f.options.rCnt +
                                        '</div>' +
                                    '</div>' +
                                '</div>' +
                            '</div>'
                        );
                    } else {
                        f.openInfoWindowHtml(
                            '<div style="padding:4px 6px">' +
                                f.options.info +
                                '<div style="padding-top: 10px">Отчётов: ' +
                                    f.options.rCnt +
                                '</div>' +
                            '</div>'
                        );
                    };
                };
            },
            method:'get'
        }).send();
    }
}


function errorFirebag(domain) {
    Cookie.write('error_firebug', 'ok', {domain: domain, duration: 365});
    $('error_firebug').setStyle('display', 'none');
}

function moreTags(col_namber)
{
    $('tags_sb' + col_namber).setStyles({overflow:'visible', height:'100%'});
    $('ml_' + col_namber).setStyle('display', 'none');
}

window.addEvent('domready', function(){
    tooltip = new FTooltip();
    $$('input.compact_input').each(function(obj){
        new CompactInput(obj)
    });

    // Анимационный логотип
    if ($('logo-c')) {
        var so = new SWFObject("/tl_files/swf/logo.swf", "logoswf", "325", "58", "6", "#FFFFFF");
        so.addParam("wmode", "opaque");
        if (so.write("logo-c")) {
            $('logo-c').setStyle('text-indent', 0);
            $(document).addEvent('mousemove', function(e){
                window._xmouse = e.client.x;
                window._ymouse = e.client.y;
            })
            setInterval(function(){
                try {
                    document.logoswf.SetVariable('jsX', _xmouse - $('wrapper').offsetLeft + '');
                    document.logoswf.SetVariable('jsY', _ymouse - 51 + '')
                }
                catch (e) {
                }
            }, 200);
        }
    }
});

/**
 * Класс для создания ajax окон c бэкграундом
 */
BackgrWindow = new Class({
    Extends: FWindow,
    initialize: function(className)
    {
        this.darkboxFrame = new Element('div', {'class': 'darkbox-frame'}).injectInside(document.body);
        this.darkboxShadow = new Element('div', {
            'class': 'darkbox-shadow',
            'styles': {
                'visibility': 'visible'
            }
        });
        this.darkboxContainer = new Element('div', {'class': className});
        this.contentElement = new Element('div', {'class': 'content'});
        this.shadowElement = new Element('div', {'class': 'shadow'});

        this.darkboxFrame.appendChild(this.darkboxShadow);
        this.darkboxFrame.appendChild(this.darkboxContainer);
        this.darkboxContainer.appendChild(this.contentElement);
        this.darkboxContainer.appendChild(this.shadowElement);

        this.removeFunction = this.remove.bindWithEvent(this);
    },

    remove: function() {

        this.darkboxFrame.dispose();
        this.darkboxFrame.removeEvent('click', this.removeFunction);

    },

    send: function(e) {
        e.stop();
        if(this.validate())
            new FAjax(this.form.action, {
            onComplete: function(data)
            {
                 if (data.result != 'success')
                    tooltip.show(data.result, {
                        altClass: 'error',
                        anchor: $('btn_block'),
                        left: 100,
                        top: -30,
                        timeout: 10000
                    });
                 else
                 {
                    tooltip.hide();
                    this.remove();
                 }

            }.bind(this)
        }).send(this.form.toQueryString());
    }
    ,

    addCloseButton: function() {
        this.contentElement.appendChild(new Element('span', {'class': 'close_button', title: 'Закрыть окно', events:{ click: this.removeFunction }}));
    }
});



AddNewHotelComment = new Class({
    Extends: BackgrWindow,
    initialize: function(className, hotelData, isUserAuth, tineEditor) {
        this.isUserAuth = isUserAuth;
        this.tineEditor = tineEditor;

        this.textarea = 'elm1';
        this.disableBodYScroll();
        this.comment = '';
        this.parent(className);

        if(hotelData[3])
        {
            var form_title = 'Редактировать отзыв по отелю';
            var btn_class =  'hotel_comment_edit_btn';
            //this.setCommentData(hotelData[3]);
            var comment_body = this.comment;
        }
        else
        {
            var form_title = 'Добавить отзыв по отелю';
            var btn_class =  'hotel_comment_btn';
            var comment_body = '';
        }

        if(hotelData[4])
            form_title += ' <span title="'+hotelData[5]+'">"'+hotelData[4]+'"</span>';

        this.setHTML('\
            <form id="hotel_comment_add" onsubmit="return false;" name="my_profile" method="post" action="ajax.php?action=add_city">\
                <h2 style="margin:0 0 10px;">'+form_title+'</h2>\
                <div style="margin: 0 0 4px 0 ; display: none;" id="hotel_city_block_title"><strong>Введите страну или город к которому относится место на карте:</strong></div>\
                <div id="hotel_city_block">\
                    <input class="dest_autocompleter autocompleter text plan"  type="text" value="" id="hotel_comment_city" name="city" autocomplete="off"/>\
                    <input type="hidden" value="0" id="hotel_comment_city_id" name="city_id"/>\
                    <input type="hidden" value="0" id="rating" name="rate"/>\
                    <input type="hidden" value="0" id="rating2" name="rate2"/>\
                    <input type="hidden" value="0" id="comment_id" name="comment_id"/>\
                </div>\
                <div id="hotel_select_block">\
                    <input type="text" id="hotel_comment_id" name="hotel_id">\
                </div>\
                <div id="new_hotel" >\
                    <div class="new_hotel_col">\
                        <div style="margin: 5px 0 4px 0;"><strong>Название отеля:</strong></div>\
                        <div><input type="text" value="" id="hotel_new_name" class="hotel_new_name" name="hotel_new_name"/></div>\
                    </div>\
                    <div class="new_hotel_col" style="margin-right: 0px;">\
                        <div style="margin: 5px 0 4px 0;"><strong>Физический и/или интернет адрес отеля:</strong></div>\
                        <div><input type="text" value="" id="hotel_new_adress" class="hotel_new_adress" name="hotel_new_adress"/></div>\
                    </div>\
                    <!--\
                    <div >\
                        <div style="margin: 5px 0 4px 0;"><strong>Количество звезд:</strong></div>\
                        <div style="#margin: 0 0 4px -95px; ">\
                            <strong id="r_rating3" class="rating" style="cursor: pointer;">\
                                <span class="stars" id="r_rating3_star" style="background-position: 0px 0pt; background-color: rgb(0, 168, 238);"><span></span> 0.0</span>\
                            </strong>\
                        </div>\
                        <input type="hidden" value="0" id="hotel_rate_ind" name="hotel_new_stars_num"/>\
                    </div>\
                    -->\
                    <input type="hidden" value="0" id="hotel_rate_ind" name="hotel_new_stars_num"/>\
                </div>\
                <div style="width: 290px; float: left; height:80px; #height: '+((hotelData==0)?'75':'65')+'px;">\
                    <div style="margin: 8px 10px 0 0;"><strong>Оцените отель:</strong></div>\
                    <div style="margin: 3px 20px 0 20px; "><span style="display:block; float:left; margin: 5px 22px 0 0;" >Комфорт и сервис:</span>\
                    <strong id="r_rating" class="rating_hotels" style="cursor: pointer;" ><span class="stars" style="background-position: 0px 0pt; background-color: #FF9201;"><span></span></span>&nbsp;0.0</strong>\
                    </div>\
                    <div style="margin: 3px 20px 0 20px; "><span style="display:block; float:left; margin: 5px 9px 0 0;">Месторасположение:</span>\
                    <strong id="r_rating2" class="rating_hotels" style="cursor: pointer;"><span class="stars" style="background-position: 0px 0pt; background-color: #FF9201;"><span></span></span>&nbsp;0.0</strong>\
                    </div>\
                </div>\
                <div style="width: 150px; float: right;">\
                    <div style="margin: 8px 10px 0 4px;"><strong>Дата поездки:</strong></div>\
                    <div id="date_picker">\
                        <select id="month"  name="month">\
                            <option value="0">Месяц</option>\
                            <option value="1">Январь</option>\
                            <option value="2">Февраль</option>\
                            <option value="3">Март</option>\
                            <option value="4">Апрель</option>\
                            <option value="5">Май</option>\
                            <option value="6">Июнь</option>\
                            <option value="7">Июль</option>\
                            <option value="8">Август</option>\
                            <option value="9">Сентябрь</option>\
                            <option value="10">Октябрь</option>\
                            <option value="11">Ноябрь</option>\
                            <option value="12">Декабрь</option>\
                        </select>\
                        <select id="year"  name="year">\
                            <option value="0">Год</option>\
                        </select>\
                    </div>\
                </div>\
                <div style="clear:both; float: none; ">\
                    <textarea  id="'+this.textarea+'" name="content" class="hotel_comment_textarea'+((hotelData==0)?'2':'')+'" >'+comment_body+' </textarea>\
                </div>\
                <div id="hotel_comment_btn">\
                    <a id="submitButton" class="'+btn_class+'" style="visibility: visible;"></a>\
                </div>\
            </form>\
    ');

        $('submitButton').addEvent('click', this.send.bindWithEvent(this));

        this.form = $('hotel_comment_add');
        this.hotel_id = $('hotel_comment_id');
        this.hotel_city_id = $('hotel_comment_city_id');
        this.hotel_city = $('hotel_comment_city');
        this.addCloseButton();

        window.addEvent('domready', function() {
            var url = '/ajax.php?action=cities.autocomplete';
            new Autocompleter.Ajax.Json2(this.hotel_city, this.hotel_city_id , url, { useSelection: false, zIndex: 4000 });
            this.commentRate = new CommentRating($('r_rating'));
            this.commentRate2 = new CommentRating($('r_rating2'));

            this.addNewHotel(hotelData);
            this.setWindowTop(hotelData);
            this.addYearsInSelect();
            try {
                this.tineEditor.viewEditor(this.textarea);
                }
            catch(e)
                {}

        }.bind(this));
    },

    addYearsInSelect: function(){
        var dt = new Date();
        for(i = 0; i<=12; i++)
        {
            year = dt.getFullYear() - i;
            $('year').options[i+1] = new Option(year, year);
        }
    },

    addNewHotel: function(hotelData){
        if(hotelData == 0) {
            $('new_hotel').style.display = 'block';
            $('hotel_city_block').style.display = 'block';
            $('hotel_city_block_title').style.display = 'block';

            var darkbox = $$('div.darkbox-container-hotel-comment');
            darkbox = darkbox[0];

            window.addEvent('domready', function() {
                if($('r_rating3'))
                    new HotelRating($('r_rating3'));
            });

            if (darkbox) {
                darkbox.className = 'darkbox-container-hotel-comment2';
            }
        }
        else{
            this.hotel_id.value = hotelData[0];
            this.hotel_city_id.value = hotelData[1];
            this.hotel_city.value = hotelData[2];

            if(hotelData[3])
                this.setCommentData(hotelData[3]);

            $('new_hotel').style.display = 'none';
            var darkbox = $$('div.darkbox-container-hotel-comment2');
            darkbox = darkbox[0];
            if (darkbox) {
                darkbox.className = 'darkbox-container-hotel-comment';
            }
        }
    },

    setCommentData: function(commentId){

    var ua = navigator.userAgent.toLowerCase();
    if (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1 && ua.indexOf("webtv") == -1)
        var async_value = false;
    else
        var async_value = true;

        new FAjax('/ajax.php?action=hotels.get_comment', {async: async_value,
                onComplete: function(data){
                    if (data.result != '') {
                        if (data) {
                            $('rating').value = data.result.rate;
                            $('rating2').value = data.result.rate2;
                            this.commentRate.drawHotelValue(data.result.rate);
                            this.commentRate2.drawHotelValue(data.result.rate2);
                            $('comment_id').value = data.result.id;
                            $('elm1').value = data.result.body;
                            this.tineEditor.setContent(data.result.body, 'elm1');
                            this.setSelectedOption('year', data.result.year);
                            this.setSelectedOption('month', data.result.month);
                        }
                    }
                }.bind(this)
            } ).send('comment_id='+commentId);
    },

    setSelectedOption: function (select_id, selected_value)
    {
        var select = $(select_id);
        var options = $(select_id).options;
        for(var i=1; i < options.length; i++ )
        {
            var opt_val = options[i].value;
            if(opt_val == selected_value)
                options[i].selected = true;
        }

    },

    disableBodYScroll: function(){
        var scroll_offset = (self.pageYOffset ||   (document.documentElement && document.documentElement.scrollTop) ||   (document.body && document.body.scrollTop));
        if(document.documentElement && document.documentElement.scrollTop!=0)
            document.documentElement.scrollTop = 0;
        else if(document.body && document.body.scrollTop!=0)
            document.body.scrollTop= 0;
        else if(self.pageYOffset)
            self.pageYOffset = 0;
        $('top').style.overflow = 'hidden';
    },

    enableBodYScroll: function(){
        $('top').style.overflow = 'visible';
    },

    validate: function() {
        if( $('rating').value == 0 ||
         $('rating2').value == 0 ||
         !this.tineEditor.getHtml('elm1') ||
         ($('new_hotel').style.display == 'block'  && $('hotel_new_name').value == '' )
        )
        {
            tooltip.show('Пожалуйста заполните все поля!', {altClass:'error', anchor: $('submitButton'), left:-210, top:5, timeout:3000});
            return false;
        }
        if(this.isUserAuth == 0)
        {
            tooltip.show('Для добавления коментария Вам необходимо авторизоваться!', {altClass:'error', anchor: $('submitButton'), left:-210, top:5, timeout:3000});
            return false;
        }
        return true;
    },

    remove: function() {

        this.tineEditor.removeEditor(this.textarea);
        this.darkboxFrame.dispose();
        this.darkboxFrame.removeEvent('click', this.removeFunction);
        this.enableBodYScroll();
    },

    send: function(e) {
        e.stop();
        $('elm1').value = this.tineEditor.getHtml('elm1');

        if (this.validate()) {
            new FAjax('/ajax.php?action=hotels.add_comment', {
                onComplete: function(data){
                    if (data.result) {
                        this.remove();
                        document.location = '/hotel/name/' + data.result + '.html';
                    }
                    else {
                        tooltip.show('Отель будет размещен на сайте после модерации!', {altClass:'error', anchor: $('submitButton'), left:-210, top:5, timeout:1500});
                        this.remove.delay(1000, this);
                    }
                }.bind(this)
            }).send(this.form.toQueryString());
            this.enableBodYScroll();
        }
    },

    setWindowTop: function(hotelData)
    {
        var window_height = 0;
        var document_height = (window.innerHeight)?window.innerHeight:((document.all)?document.documentElement.clientHeight:null);
        if (hotelData == 0) {
            var content = $$('.darkbox-container-hotel-comment2 div.content');
            window_height = 460;
        }
        else{
            var content = $$('.darkbox-container-hotel-comment div.content');
            window_height = 415;
        }

        content = content[0];
        darkbox = content.getParent();
        /*if (content) {
                window_height = content.offsetHeight;
        }*/
        offset = 20;

        if(window_height)
        {
            var height_offset = (document_height - (window_height))/2 - offset;
            if(height_offset <= -20)
                height_offset = -20;
            darkbox.style.top  = height_offset+'px';
        }
        darkbox.style.visibility = 'visible';
    }
});

CommentRating = new Class({

        options: {
    },

    initialize: function(el){
        this.element = el;
        this.element.setStyle('cursor', 'pointer');
        this.starsSpan  = this.element.getFirst();
        this.maxX = this.starsSpan.offsetWidth;
        this.tempValue  = 0;
        this.ratedValue = 0;
        destElId = el.id.replace('r_', '');
        this.destEl = $(destElId);

        this.element.addEvents({
            'mouseenter': this.mouseEnterHandler.bindWithEvent(this),
            'mousemove':  this.mouseMoveHandler.bindWithEvent(this),
            'mouseleave': this.mouseLeaveHandler.bindWithEvent(this),
            'click': this.clickHandler.bindWithEvent(this)
        });
        this.fx = new Fx.Tween(this.starsSpan, {duration: 500, link: 'cancel'}).set('background-color', '#FD8C02');
    },

    mouseEnterHandler: function(e) {
        this.elementBounds = FUtils.getObjectBounds(this.element);
        this.fx.start('#9ce407');
    },

    mouseMoveHandler: function(e) {
        if (!this.request && this.elementBounds) {
            var x = Math.abs(e.client.x - this.elementBounds.left);
            x = (x >= 90)?x-100:x;
            var v = Math.max(0, Math.min(5, x * 5 / this.maxX));
            this.tempValue = v;
            this.drawValue(v);
        }
    },

    mouseLeaveHandler: function(e) {
        if (!this.request) {
            this.drawValue(0);
        }
    },

    drawValue: function(v) {
        this.starsSpan.setStyle('background-position', Math.round(v * this.maxX / 5)  + 'px 0');
        this.element.lastChild.nodeValue = v ? ' ' + v.toFixed(1) : '\xA00.0';
    },


    drawHotelValue: function(v) {
        this.starsSpan.setStyle('background-position', Math.round(v * this.maxX / 5)  + 'px 0');
        this.element.lastChild.nodeValue = v ? ' ' + v : '\xA0';
    },

    clickHandler: function(e){
        this.fx.start('#FD8C02');
        this.element.removeEvents();
        this.element.setStyle('cursor', 'default');
        this.destEl.value = this.tempValue;
    }
});

HotelRating = new Class({
    Extends: FVideoRating,

    initialize: function(el, videoId){
        this.element = el;
        this.videoId = videoId;
        this.element.setStyle('cursor', 'pointer');
        this.starsSpan  = this.element.getFirst();
        this.maxX = this.starsSpan.clientWidth;
        this.tempValue  = 0;
        this.ratedValue = 0;
        this.defValue = ' 0.0';

        this.fx = new Fx.Tween(this.starsSpan, {duration: 500, wait: false}).set('background-color', '#00A8EE');
        this.element.addEvents({
            'mouseenter': this.mouseEnterHandler.bindWithEvent(this),
            'mousemove':  this.mouseMoveHandler.bindWithEvent(this),
            'mouseleave': this.mouseLeaveHandler.bindWithEvent(this),
            'click': this.clickHandler.bindWithEvent(this)
        });

        if(!this.element.lastChild.nodeValue || this.element.lastChild.nodeValue == 0.0)
            this.element.lastChild.nodeValue = this.defValue;
    },

    mouseMoveHandler: function(e) {
        if (!this.request && this.elementBounds) {
            var x = Math.abs(e.client.x - this.elementBounds.left);
            x = (x >= 90)?x-100:x;
            x = (x >= 90)?x-100:x;
            var v = Math.ceil(Math.max(1, Math.min(5, x * 5 / this.maxX)));
            this.tempValue = v;
            this.drawValue(v);
        }
    },
    clickHandler: function(e){
        this.fx.start('#00A8EE');
        this.element.removeEvents();
        this.element.setStyle('cursor', 'default');
        $('hotel_rate_ind').value = this.tempValue;
    },

    mouseLeaveHandler: function(e) {
        this.drawValue(0);
        $('hotel_rate_ind').value = 0;
    },

    drawHotelValue: function(v) {
        this.starsSpan.setStyle('background-position', Math.round(v * this.maxX / 5)  + 'px 0');
        this.element.lastChild.nodeValue = v ? ' ' + v : '\xA0';
    },

    drawValue: function(v) {
        this.starsSpan.setStyle('background-position', Math.round(v * this.maxX / 5)  + 'px 0');
        this.element.lastChild.nodeValue = v ? ' ' + v.toFixed(1) : this.defValue;
    }
});

AddNewSityDialog = new Class({
    Extends: BackgrWindow,
    initialize: function() {
        this.parent();
        this.setHTML('\
            <form id="city_add" onsubmit="return false;" name="my_profile" method="post" action="ajax.php?action=add_city">\
                    <strong>Добавление нового города:</strong>\
                    <br/>\
                    <br/>\
                    <br/>\
                    <br/>\
                    <div>Название на русском</div>\
                    <input id="ctrl_name_ru" class="tl_text" type="text" value="" name="name_ru"/>\
                    <br/>\
                    <br/>\
                    <div>Название на английском</div>\
                    <input id="ctrl_name_en" class="tl_text" type="text" value="" name="name_en"/>\
                    <br/>\
                    <br/>\
                    <div>Родительский регион/страна</div>\
                    <input id="ctrl_parent" class="tl_text" style="border:1px solid #7F9DB9; padding: 2px;" type="text" value="" name="parent" autocomplete="off"/>\
                    <input id="ctrl_pid" type="hidden" value="86054" name="pid"/>\
                    <br/>\
                    <br/>\
                    <div>Координаты lat/lng<br>(или ссылка на maps.google.ru)</div>\
                    <input id="ctrl_coords" class="tl_text" type="text" value="" name="coords"/>\
                    <br/>\
                    <br/>\
                    <br/>\
                    <br/>\
                    <br/>\
                    <div style="margin-left: 70px; width: 480px;" id="btn_block">\
                        <a id="submitButton" class="domaincheck_btn2" style="visibility: visible;"></a>\
                        <a id="cancelButton" class="domaincheck_btn1"></a>\
                    </div>\
                    <br/>\
                    <br/>\
                </form>\
    ');
        $('cancelButton').addEvent('click', this.removeFunction);
        $('submitButton').addEvent('click', this.send.bindWithEvent(this));

        this.form = $('city_add');

        window.addEvent('domready', function() {
            var url = '/ajax.php?action=cities.autocomplete';
            new Autocompleter.Ajax.Json2($('ctrl_parent'), $('ctrl_pid'), url, { useSelection: false, zIndex: 4000 });
                                                });
    },

    validate: function() {
        if($('ctrl_name_ru').value == ''
        || $('ctrl_name_en').value == ''
        || $('ctrl_parent').value == ''
        || $('ctrl_coords').value == ''
          )
        {
            tooltip.show('Пожалуйста заполните все поля!', {altClass:'error', anchor: $('btn_block'), left:100, top:-30, timeout:10000});
            return false;
        }
        return true;
    }

});

function viewApprovedComment(el)
{
    var div = $(el.id+'_div');

    var re =/_hidden/;
    if (re.test(div.className)) {
        div.className = div.className.replace(/_hidden/, '');
        div.style.color = '#464646';
    }
    else {
        div.className = div.className + '_hidden';
        div.style.color = '#464646';
    }
}

function deleteApprovedComment(el_id, cnt_id)
{
    this.request = new FAjax('/ajax.php?action=approved.comment.delete', {
        onComplete: function(data){
                $(el_id).style.display = 'none';
                if($(cnt_id))
                    $(cnt_id).innerHTML = $(cnt_id).innerHTML*1 - 1;
        }
    }).send({'commentId' : el_id});
}

function deleteComment(id)
{
    this.request = new FAjax('/ajax.php?action=approved.comment.delete', {
        onComplete: function(data){
            document.location.reload();
        }
    }).send({'commentId' : id});
}

function submitSerchGuideisFromWithData(url, form, city_url)
{
    $(url).value = city_url;
    $(form).submit();
}

function submitSerchGuideisFrom(address, url, form, dropdown)
{
        new FAjax('/ajax.php?action=search.address', {
            onComplete: function(data) {
                if (data.result && data.result.length > 0) {
                    if (data.result.length == 1) {
                        url.value = data.result[0].url;
                        form.submit();
                    } else {
                        var el = dropdown.set('html','<div>Уточните, что из этого вы ищите?</div>').setStyle('display', 'block');
                        for (var i = 0; i < data.result.length; ++i) {
                            var city = data.result[i];
                            div_class = 'color1';
                            dropdown.set('html',dropdown.innerHTML+'<div class="'+div_class+'" onclick="submitSerchGuideisFromWithData(\''+url.id+'\', \''+form.id+'\', \''+city.url+'\'); return false;">'+data.result[i].name+'</div>');
                        }
                    }
                } else {
                    url.value = '';
                    form.submit();
                }

            }.bind(this)
        }).send({'address' : address.value});
}


MessageWin = new Class({
    Extends: BackgrWindow,
    initialize: function(text) {
        this.parent('darkbox-container');
        this.setHTML('\
            <form id="msg_block" onsubmit="return false;" name="my_profile" method="post" >\
                <div style="margin: 0 0 4px 10px ; " >\
                    '+text+'\
                </div>\
                <div id="msg_next_btn" >\
                    <a id="submitButton" class="small_cancel_btn"  ></a>\
                </div>\
            </form>\
    ');
        $('submitButton').addEvent('click', this.send.bindWithEvent(this));
        this.addCloseButton();
    },

    send: function(e) {
        this.remove();
    }
});


/* ei */
// need for debug
//-------------------------
function Dump(d, l, t) {
 if (typeof(t) == "undefined") t = "\n";

    if (l == null) l = 1;
    var s = '';
    if (typeof(d) == "object") {
        s += typeof(d) + " {"+t;
        for (var k in d) {
            for (var i=0; i<l; i++) s += "  ";
            s += k+": " + Dump(d[k],l+1, t);
        }
        for (var i=0; i<l-1; i++) s += "  ";
        s += "}"+t;
    } else {
        s += "" + d + t;
    }
    return s;
}

function mprint(o) {
 alert(Dump(o, 1));
}

function DumpView(d,l) {
 var rekl = get_el("reklama");
 if (rekl) rekl.innerHTML = DumpHTML(d,l);
}

function DumpHTML(d,l) {
 return Dump(d,l, "<br />");
}

/* */
