var $j = jQuery.noConflict();
(function($j) {
$j.fn.ajaxSubmit = function(options) {
    if (!this.length) {
        log('ajaxSubmit: skipping submit process - no element selected');
        return this;
    }
    if (typeof options == 'function')
        options = { success: options };
    options = $j.extend({
        url:  this.attr('action') || window.location.toString(),
        type: this.attr('method') || 'GET'
    }, options || {});
    var veto = {};
    this.trigger('form-pre-serialize', [this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-pre-serialize trigger');
        return this;
   }
    var a = this.formToArray(options.semantic);
    if (options.data) {
        options.extraData = options.data;
        for (var n in options.data)
            a.push( { name: n, value: options.data[n] } );
    }
    if (options.beforeSubmit && options.beforeSubmit(a, this, options) === false) {
        log('ajaxSubmit: submit aborted via beforeSubmit callback');
        return this;
    }    
    this.trigger('form-submit-validate', [a, this, options, veto]);
    if (veto.veto) {
        log('ajaxSubmit: submit vetoed via form-submit-validate trigger');
        return this;
    }    
    var q = $j.param(a);
    if (options.type.toUpperCase() == 'GET') {
        options.url += (options.url.indexOf('?') >= 0 ? '&' : '?') + q;
        options.data = null;
    }
    else
        options.data = q;
    var $form = this, callbacks = [];
    if (options.resetForm) callbacks.push(function() { $form.resetForm(); });
    if (options.clearForm) callbacks.push(function() { $form.clearForm(); });
    if (!options.dataType && options.target) {
        var oldSuccess = options.success || function(){};
        callbacks.push(function(data) {
            $j(options.target).html(data).each(oldSuccess, arguments);
        });
    }
    else if (options.success)
        callbacks.push(options.success);
    options.success = function(data, status) {
        for (var i=0, max=callbacks.length; i < max; i++)
            callbacks[i](data, status, $form);
    };
    var files = $j('input:file', this).fieldValue();
    var found = false;
    for (var j=0; j < files.length; j++)
        if (files[j])
            found = true;
   if (options.iframe || found) { 
       if ($j.browser.safari && options.closeKeepAlive)
           $j.get(options.closeKeepAlive, fileUpload);
       else
           fileUpload();
       }
   else
       $j.ajax(options);
    this.trigger('form-submit-notify', [this, options]);
    return this;
    function fileUpload() {
        var form = $form[0];
        if ($j(':input[@name=submit]', form).length) {
            alert('Error: Form elements must not be named "submit".');
            return;
        }
        var opts = $j.extend({}, $j.ajaxSettings, options);
        var id = 'jqFormIO' + (new Date().getTime());
        var $io = $j('<iframe id="' + id + '" name="' + id + '" />');
        var io = $io[0];
        if ($j.browser.msie || $j.browser.opera) 
            io.src = 'javascript:false;document.write("");';
        $io.css({ position: 'absolute', top: '-1000px', left: '-1000px' });
        var xhr = {
            responseText: null,
            responseXML: null,
            status: 0,
            statusText: 'n/a',
            getAllResponseHeaders: function() {},
            getResponseHeader: function() {},
            setRequestHeader: function() {}
        };
        var g = opts.global;
        if (g && ! $j.active++) $j.event.trigger("ajaxStart");
        if (g) $j.event.trigger("ajaxSend", [xhr, opts]);
        var cbInvoked = 0;
        var timedOut = 0;
        var sub = form.clk;
        if (sub) {
            var n = sub.name;
            if (n && !sub.disabled) {
                options.extraData = options.extraData || {};
                options.extraData[n] = sub.value;
                if (sub.type == "image") {
                    options.extraData[name+'.x'] = form.clk_x;
                    options.extraData[name+'.y'] = form.clk_y;
                }
            }
        }
        setTimeout(function() {
            var t = $form.attr('target'), a = $form.attr('action');
            $form.attr({
                target:   id,
                encoding: 'multipart/form-data',
                enctype:  'multipart/form-data',
                method:   'POST',
                action:   opts.url
            });
            if (opts.timeout)
                setTimeout(function() { timedOut = true; cb(); }, opts.timeout);
            var extraInputs = [];
            try {
                if (options.extraData)
                    for (var n in options.extraData)
                        extraInputs.push(
                            $j('<input type="hidden" name="'+n+'" value="'+options.extraData[n]+'" />')
                                .appendTo(form)[0]);
                $io.appendTo('body');
                io.attachEvent ? io.attachEvent('onload', cb) : io.addEventListener('load', cb, false);
                form.submit();
            }
            finally {
                $form.attr('action', a);
                t ? $form.attr('target', t) : $form.removeAttr('target');
                $j(extraInputs).remove();
            }
        }, 10);
        function cb() {
            if (cbInvoked++) return;
            io.detachEvent ? io.detachEvent('onload', cb) : io.removeEventListener('load', cb, false);
            var operaHack = 0;
            var ok = true;
            try {
                if (timedOut) throw 'timeout';
                var data, doc;
                doc = io.contentWindow ? io.contentWindow.document : io.contentDocument ? io.contentDocument : io.document;
                if (doc.body == null && !operaHack && $j.browser.opera) {
                    operaHack = 1;
                    cbInvoked--;
                    setTimeout(cb, 100);
                    return;
                }
                xhr.responseText = doc.body ? doc.body.innerHTML : null;
                xhr.responseXML = doc.XMLDocument ? doc.XMLDocument : doc;
                xhr.getResponseHeader = function(header){
                    var headers = {'content-type': opts.dataType};
                    return headers[header];
                };
                if (opts.dataType == 'json' || opts.dataType == 'script') {
                    var ta = doc.getElementsByTagName('textarea')[0];
                    xhr.responseText = ta ? ta.value : xhr.responseText;
                }
                else if (opts.dataType == 'xml' && !xhr.responseXML && xhr.responseText != null) {
                    xhr.responseXML = toXml(xhr.responseText);
                }
                data = $j.httpData(xhr, opts.dataType);
            }
            catch(e){
                ok = false;
                $j.handleError(opts, xhr, 'error', e);
            }
            if (ok) {
                opts.success(data, 'success');
                if (g) $j.event.trigger("ajaxSuccess", [xhr, opts]);
            }
            if (g) $j.event.trigger("ajaxComplete", [xhr, opts]);
            if (g && ! --$j.active) $j.event.trigger("ajaxStop");
            if (opts.complete) opts.complete(xhr, ok ? 'success' : 'error');
            setTimeout(function() {
                $io.remove();
                xhr.responseXML = null;
            }, 100);
        };
        function toXml(s, doc) {
            if (window.ActiveXObject) {
                doc = new ActiveXObject('Microsoft.XMLDOM');
                doc.async = 'false';
                doc.loadXML(s);
            }
            else
                doc = (new DOMParser()).parseFromString(s, 'text/xml');
            return (doc && doc.documentElement && doc.documentElement.tagName != 'parsererror') ? doc : null;
        };
    };
};
$j.fn.ajaxForm = function(options) {
    return this.ajaxFormUnbind().bind('submit.form-plugin',function() {
        $j(this).ajaxSubmit(options);
        return false;
    }).each(function() {
        $j(":submit,input:image", this).bind('click.form-plugin',function(e) {
            var $form = this.form;
            $form.clk = this;
            if (this.type == 'image') {
                if (e.offsetX != undefined) {
                    $form.clk_x = e.offsetX;
                    $form.clk_y = e.offsetY;
                } else if (typeof $j.fn.offset == 'function') { // try to use dimensions plugin
                    var offset = $j(this).offset();
                    $form.clk_x = e.pageX - offset.left;
                    $form.clk_y = e.pageY - offset.top;
                } else {
                    $form.clk_x = e.pageX - this.offsetLeft;
                    $form.clk_y = e.pageY - this.offsetTop;
                }
            }
            setTimeout(function() { $form.clk = $form.clk_x = $form.clk_y = null; }, 10);
        });
    });
};
$j.fn.ajaxFormUnbind = function() {
    this.unbind('submit.form-plugin');
    return this.each(function() {
        $j(":submit,input:image", this).unbind('click.form-plugin');
    });
};
$j.fn.formToArray = function(semantic) {
    var a = [];
    if (this.length == 0) return a;
    var form = this[0];
    var els = semantic ? form.getElementsByTagName('*') : form.elements;
    if (!els) return a;
    for(var i=0, max=els.length; i < max; i++) {
        var el = els[i];
        var n = el.name;
        if (!n) continue;
        if (semantic && form.clk && el.type == "image") {
            if(!el.disabled && form.clk == el)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
            continue;
        }
        var v = $j.fieldValue(el, true);
        if (v && v.constructor == Array) {
            for(var j=0, jmax=v.length; j < jmax; j++)
                a.push({name: n, value: v[j]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: n, value: v});
    }
    if (!semantic && form.clk) {
        var inputs = form.getElementsByTagName("input");
        for(var i=0, max=inputs.length; i < max; i++) {
            var input = inputs[i];
            var n = input.name;
            if(n && !input.disabled && input.type == "image" && form.clk == input)
                a.push({name: n+'.x', value: form.clk_x}, {name: n+'.y', value: form.clk_y});
        }
    }
    return a;
};
$j.fn.formSerialize = function(semantic) {
    return $j.param(this.formToArray(semantic));
};
$j.fn.fieldSerialize = function(successful) {
    var a = [];
    this.each(function() {
        var n = this.name;
        if (!n) return;
        var v = $j.fieldValue(this, successful);
        if (v && v.constructor == Array) {
            for (var i=0,max=v.length; i < max; i++)
                a.push({name: n, value: v[i]});
        }
        else if (v !== null && typeof v != 'undefined')
            a.push({name: this.name, value: v});
    });
    return $j.param(a);
};
$j.fn.fieldValue = function(successful) {
    for (var val=[], i=0, max=this.length; i < max; i++) {
        var el = this[i];
        var v = $j.fieldValue(el, successful);
        if (v === null || typeof v == 'undefined' || (v.constructor == Array && !v.length))
            continue;
        v.constructor == Array ? $j.merge(val, v) : val.push(v);
    }
    return val;
};
$j.fieldValue = function(el, successful) {
    var n = el.name, t = el.type, tag = el.tagName.toLowerCase();
    if (typeof successful == 'undefined') successful = true;
    if (successful && (!n || el.disabled || t == 'reset' || t == 'button' ||
        (t == 'checkbox' || t == 'radio') && !el.checked ||
        (t == 'submit' || t == 'image') && el.form && el.form.clk != el ||
        tag == 'select' && el.selectedIndex == -1))
            return null;
    if (tag == 'select') {
        var index = el.selectedIndex;
        if (index < 0) return null;
        var a = [], ops = el.options;
        var one = (t == 'select-one');
        var max = (one ? index+1 : ops.length);
        for(var i=(one ? index : 0); i < max; i++) {
            var op = ops[i];
            if (op.selected) {
                var v = $j.browser.msie && !(op.attributes['value'].specified) ? op.text : op.value;
                if (one) return v;
                a.push(v);
            }
        }
        return a;
    }
    return el.value;
};
$j.fn.clearForm = function() {
    return this.each(function() {
        $j('input,select,textarea', this).clearFields();
    });
};
$j.fn.clearFields = $j.fn.clearInputs = function() {
    return this.each(function() {
        var t = this.type, tag = this.tagName.toLowerCase();
        if (t == 'text' || t == 'password' || tag == 'textarea')
            this.value = '';
        else if (t == 'checkbox' || t == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};
$j.fn.resetForm = function() {
    return this.each(function() {
        if (typeof this.reset == 'function' || (typeof this.reset == 'object' && !this.reset.nodeType))
            this.reset();
    });
};
$j.fn.enable = function(b) { 
    if (b == undefined) b = true;
    return this.each(function() { 
        this.disabled = !b 
    });
};
$j.fn.select = function(select) {
    if (select == undefined) select = true;
    return this.each(function() { 
        var t = this.type;
        if (t == 'checkbox' || t == 'radio')
            this.checked = select;
        else if (this.tagName.toLowerCase() == 'option') {
            var $sel = $j(this).parent('select');
            if (select && $sel[0] && $sel[0].type == 'select-one') {
                $sel.find('option').select(false);
            }
            this.selected = select;
        }
    });
};
function log() {
    if ($j.fn.ajaxSubmit.debug && window.console && window.console.log)
        window.console.log('[jquery.form] ' + Array.prototype.join.call(arguments,''));
};
})($j);
//////////////////////////////
$j.fn.editInPlace = function(options) {
	var settings = {
		url:				"",
		params:				"",
		field_type:			"text",
		select_options:		"",
		textarea_cols:		"25",
		textarea_rows:		"10",
		bg_over:			"#ffc",
		bg_out:				"transparent",
		saving_text:		"Сохранение...",
		saving_image:		"",
		default_text:		"(Клик для редактирования)",
		select_text:		"Новое значение",
		value_required:		null,
		element_id:			"element_id",
		update_value:		"update_value",
		original_html:		"original_html",
		save_button:		'<input type="submit" class="inplace_save" value="ok"/>',
		cancel_button:		'<input type="submit" class="inplace_cancel" value="x"/>',
		show_buttons:		false,
		on_blur:			"save",
		callback:			null,
		success:			null,
		error:				null
	};
	if(options) {
		$j.extend(settings, options);
	}
	if(settings.saving_image != ""){
		var loading_image = new Image();
		loading_image.src = settings.saving_image;
	}
	String.prototype.trim = function() {
		return this.replace(/^\s+/, '')
							 .replace(/\s+$/, '');
	};
	String.prototype.escape_html = function() {
		return this.replace(/&/g, "&amp;")
							 .replace(/</g, "&lt;")
							 .replace(/>/g, "&gt;")
							 .replace(/"/g, "&quot;");
  };
	return this.each(function(){
		if($j(this).html() == "") $j(this).html(settings.default_text);
		var editing = false;
		var original_element = $j(this);
		var click_count = 0;
		$j(this)
		.mouseover(function(){
			$j(this).css("background", settings.bg_over);
		})
		.mouseout(function(){
			$j(this).css("background", settings.bg_out);
		})
		.click(function(){
			click_count++;
			if(!editing)
			{
				editing = true;
				var original_html = $j(this).html();
				var buttons_code  = (settings.show_buttons) ? settings.save_button + ' ' + settings.cancel_button : '';
				if (original_html == settings.default_text) $j(this).html('');
				if (settings.field_type == "textarea")
				{
					var use_field_type = '<textarea name="inplace_value" class="inplace_field" rows="' + settings.textarea_rows + '" cols="' + settings.textarea_cols + '">' + $j(this).text().trim().escape_html() + '</textarea>';
				}
				else if(settings.field_type == "text")
				{
					var use_field_type = '<input type="text" name="inplace_value" class="inplace_field" value="' +
											$j(this).text().trim().escape_html() + '" />';
				}
				else if(settings.field_type == "select")
				{
					var optionsArray = settings.select_options.split(',');
					var use_field_type = '<select name="inplace_value" class="inplace_field"><option value="">' + settings.select_text + '</option>';
						for(var i=0; i<optionsArray.length; i++){
							var optionsValuesArray = optionsArray[i].split(':');
							var use_value = optionsValuesArray[1] || optionsValuesArray[0];
							var selected = use_value == original_html ? 'selected="selected" ' : '';
							use_field_type += '<option ' + selected + 'value="' + use_value.trim().escape_html() + '">' + optionsValuesArray[0].trim().escape_html() + '</option>';
                        }
						use_field_type += '</select>';
				}
				$j(this).html('<form class="inplace_form" style="display: inline; margin: 0; padding: 0;">' + use_field_type + ' ' + buttons_code + '</form>');
			}
			if(click_count == 1)
			{
				function cancelAction()
				{
					editing = false;
					click_count = 0;
					original_element.css("background", settings.bg_out);
					original_element.html(original_html);
					return false;
				}
				function saveAction()
				{
					original_element.css("background", settings.bg_out);
                    var this_elem = $j(this);
					var new_html = (this_elem.is('form')) ? this_elem.children(0).val() : this_elem.parent().children(0).val();
					if(settings.saving_image != ""){
						var saving_message = '<img src="' + settings.saving_image + '" alt="Сохранение..." />';
					} else {
						var saving_message = settings.saving_text;
					}
					original_element.html(saving_message);
					if(settings.params != ""){
						settings.params = "&" + settings.params;
					}
					if(settings.callback) {
						html = settings.callback(original_element.attr("id"), new_html, original_html, settings.params);
						editing = false;
						click_count = 0;
						if (html) {
							original_element.html(html || new_html);
						} else {
							alert("Ошибка сохранения: " + new_html);
							original_element.html(original_html);
						}
					} else if (settings.value_required && (new_html == "" || new_html == undefined)) {
						editing = false;
						click_count = 0;
						original_element.html(original_html);
						alert("Ошибка: необходимо ввести значение!");
					} else {
						$j.ajax({
							url: settings.url,
							type: "POST",
							data: settings.update_value + '=' + new_html + '&' + settings.element_id + '=' + original_element.attr("id") + settings.params + '&' + settings.original_html + '=' + original_html,
							dataType: "html",
							complete: function(request){
								editing = false;
								click_count = 0;
							},
							success: function(html){
								var new_text = html || settings.default_text;
								original_element.html(new_text);
								if (settings.success) settings.success(html, original_element);
							},
							error: function(request) {
								original_element.html(original_html);
								if (settings.error) settings.error(request, original_element);
							}
						});
					}
					return false;
				}
				original_element.children("form").children(".inplace_field").focus().select();
				original_element.children("form").children(".inplace_cancel").click(cancelAction);
				original_element.children("form").children(".inplace_save").click(saveAction);
                if(!settings.show_buttons){
    				if(settings.on_blur == "save")
    					original_element.children("form").children(".inplace_field").blur(saveAction);
    				else
    					original_element.children("form").children(".inplace_field").blur(cancelAction);
                }
				$j(document).keyup(function(event){
				    if (event.keyCode == 27) {
						cancelAction();
				    }
				});
                original_element.children("form").submit(saveAction);
			}
		});
	});
};
///////////////////////////////////////////
$j.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			$j.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			$j.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			$j.timer.remove(this, label, fn);
		});
	}
});
$j.extend({
	timer: {
		guid: 1,
		global: {},
		regex: /^([0-9]+)\s*(.*s)?$/,
		powers: {
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec($j.trim(value.toString()));
			if (result[2]) {
				var num = parseInt(result[1], 10);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;
			if ($j.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			interval = $j.timer.timeParse(interval);
			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;
			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}
			times = times || 0;
			belay = belay || false;
			if (!element.$timers) 
				element.$timers = {};
			if (!element.$timers[label])
				element.$timers[label] = {};
			fn.$timerID = fn.$timerID || this.guid++;
			var handler = function() {
				if (belay && this.inProgress) 
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					$j.timer.remove(element, label, fn);
				this.inProgress = false;
			};
			handler.$timerID = fn.$timerID;
			if (!element.$timers[label][fn.$timerID]) 
				element.$timers[label][fn.$timerID] = window.setInterval(handler,interval);
			if ( !this.global[label] )
				this.global[label] = [];
			this.global[label].push( element );
		},
		remove: function(element, label, fn) {
			var timers = element.$timers, ret;
			if ( timers ) {
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.$timerID ) {
							window.clearInterval(timers[label][fn.$timerID]);
							delete timers[label][fn.$timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				for ( ret in timers ) break;
				if ( !ret ) 
					element.$timers = null;
			}
		}
	}
});
if ($j.browser.msie)
$j(window).one("unload", function() {
	var global = $j.timer.global;
	for ( var label in global ) {
		var els = global[label], i = els.length;
		while ( --i )
			$j.timer.remove(els[i], label);
	}
});
////////////////////////////////// sound
var soundEnable = 1;
$j(document).ready(function() {
	$j(document.body).append('<div id="soundContainer"></div>');
	$j(document.body).append('<div id="soundOff"></div>');
	$j(document.body).append('<div id="soundOn"></div>');
	if (!$j.browser.msie) {
		$j('#soundOff').css('position', 'fixed');
		$j('#soundOn').css('position', 'fixed');
	}
	var options = {
		target:"#chat_window",
		beforeSubmit: showRequest,
		success: showResponse,
		clearForm: false
   	};
	$j('#chat_form').ajaxForm(options);
});
function playSound(path) {
	var sound = path+'.swf';
	if (soundEnable) {
		if ($j.browser.msie) {
			document.getElementById('soundContainer').innerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,28,0"><param name="movie" value="'+sound+'"><param name="quality" value="high"></object>';
		} else {
			$j('#soundContainer').html('<embed src="'+sound+'" width="1" height="1" quality="high" pluginspage="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash"></embed>');
		}
	}
}
function enableSound() {
	if (soundEnable == 0) {
		soundEnable = 1;
		$j('#soundOff').stop().hide();
		$j('#soundOn').stop().css('opacity', 1).fadeIn(250).fadeOut(2000);
	}
}
function disableSound() {
	if (soundEnable == 1) {
		soundEnable = 0;
		$j('#soundOn').stop().hide();
		$j('#soundOff').stop().css('opacity', 1).fadeIn(250).fadeOut(2000);
	}
}
function toggleSound() {
	if (soundEnable) {
		disableSound();
	} else {
		enableSound();
	}
}
////////////////////// functions
	function stop_timers()
	{
		$j("#chat_window").stopTime();
	};
	function ipe_ok()
	{
	};
	function ipe_error()
	{
	};
	function isValidEmail(email)
	{
		return (/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test(email);
	};
	function write_nick(n)
	{
		var newval = $j("#msg").val()+n+": ";
		$j("#msg").val(newval);
		$j("#msg").focus();
	};
	function add_smile(n)
	{
		if(n == 0) smile = ":)";
		if(n == 1) smile = ":(";
		if(n == 2) smile = ":D";
		if(n == 3) smile = ":|";
		var newval = $j("#msg").val()+" "+smile;
		$j("#msg").val(newval);
		$j("#smiles").hide();
		$j("#msg").focus();
	};
