/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
 *       used when the cookie was set.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // CAUTION: Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};/**
 * jQuery.timers - Timer abstractions for jQuery
 * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com)
 * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/).
 * Date: 2009/08/13
 *
 * @author Blair Mitchelmore
 * @version 1.1.3
 *
 **/

jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.extend({
	timer: {
		global: [],
		guid: 1,
		dataKey: "jQuery.timer",
		regex: /^([0-9]+(?:\.[0-9]*)?)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'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(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseFloat(result[1]);
				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 (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.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;
			
			var timers = jQuery.data(element, this.dataKey) || jQuery.data(element, this.dataKey, {});
			
			if (!timers[label])
				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)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};
			
			handler.timerID = fn.timerID;
			
			if (!timers[label][fn.timerID])
				timers[label][fn.timerID] = window.setInterval(handler,interval);
			
			this.global.push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = jQuery.data(element, this.dataKey), 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 ) 
					jQuery.removeData(element, this.dataKey);
			}
		}
	}
});

jQuery(window).bind("unload", function() {
	jQuery.each(jQuery.timer.global, function(index, item) {
		jQuery.timer.remove(item);
	});
});// jQuery Cursor Message Plugin
//
// Version 0.1
//
// Tim de Koning
// Kingsquare Information Services (http://www.kingsquare.nl/)
//
// Visit http://www.kingsquare.nl/cursorMessage for usage and more information
//
// Terms of Use
//
// This file is released under the GPL, any version you like
//

// сиспользуем вот так $.cursorMessage('hello', {hideTimeout:0});

if(jQuery) {
	( function($) {
	$.cursorMessageData = {}; // needed for e.g. timeoutId
	//start registring mouse coöridnates from the start!

	$(window).ready(function(e) {
		if ($('#curDiv').length==0) {
			  $('body').append('<div id="curDiv">&nbsp;</div>');
			  $('#curDiv').hide();
		}

		$('body').mousemove(function(e) {
			$.cursorMessageData.mouseX = e.pageX;
			$.cursorMessageData.mouseY = e.pageY;
			if ($.cursorMessageData.options != undefined) $._showCursorMessage();
		});
	});
	$.extend({
		cursorMessage: function(message, options) {
			if( options == undefined ) options = {};
			if( options.offsetX == undefined ) options.offsetX = 5;
			if( options.offsetY == undefined ) options.offsetY = 5;
			if( options.hideTimeout == undefined ) options.hideTimeout = 1000;

			$('#curDiv').html(message).fadeIn('slow');
			if (jQuery.cursorMessageData.hideTimeoutId != undefined)  clearTimeout(jQuery.cursorMessageData.hideTimeoutId);
			if (options.hideTimeout>0) jQuery.cursorMessageData.hideTimeoutId = setTimeout($.hideCursorMessage, options.hideTimeout);
			jQuery.cursorMessageData.options = options;
			$._showCursorMessage();
		},
		hideCursorMessage: function() {
			$('#curDiv').fadeOut('slow');
		},
		_showCursorMessage: function() {
			$('#curDiv').css({ top: ($.cursorMessageData.mouseY + $.cursorMessageData.options.offsetY)+'px', left: ($.cursorMessageData.mouseX + $.cursorMessageData.options.offsetX) });
		}
	});
})(jQuery);
}/*!
 * jQuery corner plugin: simple corner rounding
 * Examples and documentation at: http://jquery.malsup.com/corner/
 * version 2.01 (08-SEP-2009)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */

/**
 *  corner() takes a single string argument:  $('#myDiv').corner("effect corners width")
 *
 *  effect:  name of the effect to apply, such as round, bevel, notch, bite, etc (default is round). 
 *  corners: one or more of: top, bottom, tr, tl, br, or bl. 
 *           by default, all four corners are adorned. 
 *  width:   width of the effect; in the case of rounded corners this is the radius. 
 *           specify this value using the px suffix such as 10px (and yes, it must be pixels).
 *
 * @author Dave Methvin (http://methvin.com/jquery/jq-corner.html)
 * @author Mike Alsup   (http://jquery.malsup.com/corner/)
 * @demo http://www.malsup.com/jquery/corner/
 */
;(function($) { 

var moz = $.browser.mozilla && /gecko/i.test(navigator.userAgent);
var webkit = $.browser.safari && $.browser.version >= 3;

var expr = $.browser.msie && (function() {
    var div = document.createElement('div');
    try { div.style.setExpression('width','0+0'); }
    catch(e) { return false; }
    return true;
})();
    
function sz(el, p) { 
    return parseInt($.css(el,p))||0; 
};
function hex2(s) {
    var s = parseInt(s).toString(16);
    return ( s.length < 2 ) ? '0'+s : s;
};
function gpc(node) {
    for ( ; node && node.nodeName.toLowerCase() != 'html'; node = node.parentNode ) {
        var v = $.css(node,'backgroundColor');
        if (v == 'rgba(0, 0, 0, 0)')
            continue; // webkit
        if (v.indexOf('rgb') >= 0) { 
            var rgb = v.match(/\d+/g); 
            return '#'+ hex2(rgb[0]) + hex2(rgb[1]) + hex2(rgb[2]);
        }
        if ( v && v != 'transparent' )
            return v;
    }
    return '#ffffff';
};

function getWidth(fx, i, width) {
    switch(fx) {
    case 'round':  return Math.round(width*(1-Math.cos(Math.asin(i/width))));
    case 'cool':   return Math.round(width*(1+Math.cos(Math.asin(i/width))));
    case 'sharp':  return Math.round(width*(1-Math.cos(Math.acos(i/width))));
    case 'bite':   return Math.round(width*(Math.cos(Math.asin((width-i-1)/width))));
    case 'slide':  return Math.round(width*(Math.atan2(i,width/i)));
    case 'jut':    return Math.round(width*(Math.atan2(width,(width-i-1))));
    case 'curl':   return Math.round(width*(Math.atan(i)));
    case 'tear':   return Math.round(width*(Math.cos(i)));
    case 'wicked': return Math.round(width*(Math.tan(i)));
    case 'long':   return Math.round(width*(Math.sqrt(i)));
    case 'sculpt': return Math.round(width*(Math.log((width-i-1),width)));
    case 'dog':    return (i&1) ? (i+1) : width;
    case 'dog2':   return (i&2) ? (i+1) : width;
    case 'dog3':   return (i&3) ? (i+1) : width;
    case 'fray':   return (i%2)*width;
    case 'notch':  return width; 
    case 'bevel':  return i+1;
    }
};

$.fn.corner = function(options) {
    // in 1.3+ we can fix mistakes with the ready state
	if (this.length == 0) {
        if (!$.isReady && this.selector) {
            var s = this.selector, c = this.context;
            $(function() {
                $(s,c).corner(options);
            });
        }
        return this;
	}

    return this.each(function(index){
		var $this = $(this);
		var o = (options || $this.attr($.fn.corner.defaults.metaAttr) || '').toLowerCase();
		var keep = /keep/.test(o);                       // keep borders?
		var cc = ((o.match(/cc:(#[0-9a-f]+)/)||[])[1]);  // corner color
		var sc = ((o.match(/sc:(#[0-9a-f]+)/)||[])[1]);  // strip color
		var width = parseInt((o.match(/(\d+)px/)||[])[1]) || 10; // corner width
		var re = /round|bevel|notch|bite|cool|sharp|slide|jut|curl|tear|fray|wicked|sculpt|long|dog3|dog2|dog/;
		var fx = ((o.match(re)||['round'])[0]);
		var edges = { T:0, B:1 };
		var opts = {
			TL:  /top|tl|left/.test(o),       TR:  /top|tr|right/.test(o),
			BL:  /bottom|bl|left/.test(o),    BR:  /bottom|br|right/.test(o)
		};
		if ( !opts.TL && !opts.TR && !opts.BL && !opts.BR )
			opts = { TL:1, TR:1, BL:1, BR:1 };
			
		// support native rounding
		if ($.fn.corner.defaults.useNative && fx == 'round' && (moz || webkit) && !cc && !sc) {
			if (opts.TL)
				$this.css(moz ? '-moz-border-radius-topleft' : '-webkit-border-top-left-radius', width + 'px');
			if (opts.TR)
				$this.css(moz ? '-moz-border-radius-topright' : '-webkit-border-top-right-radius', width + 'px');
			if (opts.BL)
				$this.css(moz ? '-moz-border-radius-bottomleft' : '-webkit-border-bottom-left-radius', width + 'px');
			if (opts.BR)
				$this.css(moz ? '-moz-border-radius-bottomright' : '-webkit-border-bottom-right-radius', width + 'px');
			return;
		}
			
		var strip = document.createElement('div');
		strip.style.overflow = 'hidden';
		strip.style.height = '1px';
		strip.style.backgroundColor = sc || 'transparent';
		strip.style.borderStyle = 'solid';
	
        var pad = {
            T: parseInt($.css(this,'paddingTop'))||0,     R: parseInt($.css(this,'paddingRight'))||0,
            B: parseInt($.css(this,'paddingBottom'))||0,  L: parseInt($.css(this,'paddingLeft'))||0
        };

        if (typeof this.style.zoom != undefined) this.style.zoom = 1; // force 'hasLayout' in IE
        if (!keep) this.style.border = 'none';
        strip.style.borderColor = cc || gpc(this.parentNode);
        var cssHeight = $.curCSS(this, 'height');

        for (var j in edges) {
            var bot = edges[j];
            // only add stips if needed
            if ((bot && (opts.BL || opts.BR)) || (!bot && (opts.TL || opts.TR))) {
                strip.style.borderStyle = 'none '+(opts[j+'R']?'solid':'none')+' none '+(opts[j+'L']?'solid':'none');
                var d = document.createElement('div');
                $(d).addClass('jquery-corner');
                var ds = d.style;

                bot ? this.appendChild(d) : this.insertBefore(d, this.firstChild);

                if (bot && cssHeight != 'auto') {
                    if ($.css(this,'position') == 'static')
                        this.style.position = 'relative';
                    ds.position = 'absolute';
                    ds.bottom = ds.left = ds.padding = ds.margin = '0';
                    if (expr)
                        ds.setExpression('width', 'this.parentNode.offsetWidth');
                    else
                        ds.width = '100%';
                }
                else if (!bot && $.browser.msie) {
                    if ($.css(this,'position') == 'static')
                        this.style.position = 'relative';
                    ds.position = 'absolute';
                    ds.top = ds.left = ds.right = ds.padding = ds.margin = '0';
                    
                    // fix ie6 problem when blocked element has a border width
                    if (expr) {
                        var bw = sz(this,'borderLeftWidth') + sz(this,'borderRightWidth');
                        ds.setExpression('width', 'this.parentNode.offsetWidth - '+bw+'+ "px"');
                    }
                    else
                        ds.width = '100%';
                }
                else {
                	ds.position = 'relative';
                    ds.margin = !bot ? '-'+pad.T+'px -'+pad.R+'px '+(pad.T-width)+'px -'+pad.L+'px' : 
                                        (pad.B-width)+'px -'+pad.R+'px -'+pad.B+'px -'+pad.L+'px';                
                }

                for (var i=0; i < width; i++) {
                    var w = Math.max(0,getWidth(fx,i, width));
                    var e = strip.cloneNode(false);
                    e.style.borderWidth = '0 '+(opts[j+'R']?w:0)+'px 0 '+(opts[j+'L']?w:0)+'px';
                    bot ? d.appendChild(e) : d.insertBefore(e, d.firstChild);
                }
            }
        }
    });
};

$.fn.uncorner = function() { 
	if (moz || webkit)
		this.css(moz ? '-moz-border-radius' : '-webkit-border-radius', 0);
	$('div.jquery-corner', this).remove();
	return this;
};

// expose options
$.fn.corner.defaults = {
	useNative: true, // true if plugin should attempt to use native browser support for border radius rounding
	metaAttr:  'data-corner' // name of meta attribute to use for options
};
    
})(jQuery);/**
 * jQuery Maxlength plugin
 * @version		$Id: jquery.maxlength.js 18 2009-05-16 15:37:08Z emil@anon-design.se $
 * @package		jQuery maxlength 1.0.5
 * @copyright	Copyright (C) 2009 Emil Stjerneman / http://www.anon-design.se
 * @license		GNU/GPL, see LICENSE.txt
 */

(function($) 
{

	$.fn.maxlength = function(options)
	{
		var settings = jQuery.extend(
		{
			events:				      [], // Array of events to be triggerd
			maxCharacters:		  10, // Characters limit
			status:				      true, // True to show status indicator bewlow the element
			statusClass:		    "maxlength_status", // The class on the status div
			statusText:			    "символов осталось", // The status text
			notificationClass:	"notification",	// Will be added to the emement when maxlength is reached
			showAlert: 			    false, // True to show a regular alert message
			alertText:			    "Достигнуто максимальное кол-во символов этого поле", // Text in the alert message
			slider:				      false // Use counter slider
		}, options );
		
		// Add the default event
		$.merge(settings.events, ['keyup']);

		return this.each(function() 
		{
			var item = $(this);
			var charactersLength = $(this).val().length;
			
      // Update the status text
			function updateStatus()
			{
				var charactersLeft = settings.maxCharacters - charactersLength;
				
				if(charactersLeft < 0) 
				{
					charactersLeft = 0;
				}

				item.next("div").html(charactersLeft + " " + settings.statusText);
			}

			function checkChars() 
			{
				var valid = true;
				
				// Too many chars?
				if(charactersLength >= settings.maxCharacters) 
				{
					// Too may chars, set the valid boolean to false
					valid = false;
					// Add the notifycation class when we have too many chars
					item.addClass(settings.notificationClass);
					// Cut down the string
					item.val(item.val().substr(0,settings.maxCharacters));
					// Show the alert dialog box, if its set to true
					showAlert();
				} 
				else 
				{
					// Remove the notification class
					if(item.hasClass(settings.notificationClass)) 
					{
						item.removeClass(settings.notificationClass);
					}
				}

				if(settings.status)
				{
					updateStatus();
				}
			}
						
			// Shows an alert msg
			function showAlert() 
			{
				if(settings.showAlert)
				{
					alert(settings.alertText);
				}
			}

			// Check if the element is valid.
			function validateElement() 
			{
				var ret = false;
				
				if(item.is('textarea')) {
					ret = true;
				} else if(item.filter("input[type=text]")) {
					ret = true;
				} else if(item.filter("input[type=password]")) {
					ret = true;
				}

				return ret;
			}

			// Validate
			if(!validateElement()) 
			{
				return false;
			}
			
			// Loop through the events and bind them to the element
			$.each(settings.events, function (i, n) {
				item.bind(n, function(e) {
					charactersLength = item.val().length;
					checkChars();
				});
			});

			// Insert the status div
			if(settings.status) 
			{
				item.after($("<div/>").addClass(settings.statusClass).html('-'));
				updateStatus();
			}

			// Remove the status div
			if(!settings.status) 
			{
				var removeThisDiv = item.next("div."+settings.statusClass);
				
				if(removeThisDiv) {
					removeThisDiv.remove();
				}

			}

			// Slide counter
			if(settings.slider) {
				item.next().hide();
				
				item.focus(function(){
					item.next().slideDown('fast');
				});

				item.blur(function(){
					item.next().slideUp('fast');
				}); 
			}

		});
	};
})(jQuery);/**
*	@name							Elastic
*	@descripton						Elastic is Jquery plugin that grow and shrink your textareas automaticliy
*	@version						1.6.4
*	@requires						Jquery 1.2.6+
*
*	@author							Jan Jarfalk
*	@author-email					jan.jarfalk@unwrongest.com
*	@author-website					http://www.unwrongest.com
*
*	@licens							MIT License - http://www.opensource.org/licenses/mit-license.php
*/

(function(jQuery){ 
	jQuery.fn.extend({  
		elastic: function() {
		
			//	We will create a div clone of the textarea
			//	by copying these attributes from the textarea to the div.
			var mimics = [
				'paddingTop',
				'paddingRight',
				'paddingBottom',
				'paddingLeft',
				'fontSize',
				'lineHeight',
				'fontFamily',
				'width',
				'fontWeight'];
			
			return this.each( function() {
				
				// Elastic only works on textareas
				if ( this.type != 'textarea' ) {
					return false;
				}
				
				var $textarea	=	jQuery(this),
					$twin		=	jQuery('<div />').css({'position': 'absolute','display':'none','word-wrap':'break-word'}),
					lineHeight	=	parseInt($textarea.css('line-height'),10) || parseInt($textarea.css('font-size'),'10'),
					minheight	=	parseInt($textarea.css('height'),10) || lineHeight*3,
					maxheight	=	parseInt($textarea.css('max-height'),10) || Number.MAX_VALUE,
					goalheight	=	0,
					i 			=	0;
				
				// Opera returns max-height of -1 if not set
				if (maxheight < 0) { maxheight = Number.MAX_VALUE; }
					
				// Append the twin to the DOM
				// We are going to meassure the height of this, not the textarea.
				$twin.appendTo($textarea.parent());
				
				// Copy the essential styles (mimics) from the textarea to the twin
				var i = mimics.length;
				while(i--){
					$twin.css(mimics[i].toString(),$textarea.css(mimics[i].toString()));
				}
				
				
				// Sets a given height and overflow state on the textarea
				function setHeightAndOverflow(height, overflow){
					curratedHeight = Math.floor(parseInt(height,10));
					if($textarea.height() != curratedHeight){
						$textarea.css({'height': curratedHeight + 'px','overflow':overflow});
						
					}
				}
				
				
				// This function will update the height of the textarea if necessary 
				function update() {
					
					// Get curated content from the textarea.
					var textareaContent = $textarea.val().replace(/&/g,'&amp;').replace(/  /g, '&nbsp;').replace(/<|>/g, '&gt;').replace(/\n/g, '<br />');

					var twinContent = $twin.html();
					
					if(textareaContent+'&nbsp;' != twinContent){
					
						// Add an extra white space so new rows are added when you are at the end of a row.
						$twin.html(textareaContent+'&nbsp;');
						
						// Change textarea height if twin plus the height of one line differs more than 3 pixel from textarea height
						if(Math.abs($twin.height()+lineHeight - $textarea.height()) > 3){
							
							var goalheight = $twin.height()+lineHeight;
							if(goalheight >= maxheight) {
								setHeightAndOverflow(maxheight,'auto');
							} else if(goalheight <= minheight) {
								setHeightAndOverflow(minheight,'hidden');
							} else {
								setHeightAndOverflow(goalheight,'hidden');
							}
							
						}
						
					}
					
				}
				
				// Hide scrollbars
				$textarea.css({'overflow':'hidden'});
				
				// Update textarea size on keyup
				$textarea.keyup(function(){ update(); });
				
				// And this line is to catch the browser paste event
				$textarea.live('input paste',function(e){ setTimeout( update, 250); });				
				
				// Run update once when elastic is initialized
				update();
				
			});
			
        } 
    }); 
})(jQuery);/*

Title:		jShowOff: a jQuery Content Rotator Plugin
Author:		Erik Kallevig
Version:	0.1.2
Website:	http://ekallevig.com/jshowoff
License: 	Dual licensed under the MIT and GPL licenses.

jShowOff Options

animatePause :		whether to use 'Pause' animation text when pausing [boolean, defaults to true]
autoPlay :			whether to start playing immediately [boolean, defaults to true]
changeSpeed :		speed of transition [integer, milliseconds, defaults to 600]
controls :			whether to create & display controls (Play/Pause, Previous, Next) [boolean, defaults to true]
controlText :		custom text for controls [object, 'play', 'pause', 'previous' and 'next' properties]
cssClass :			custom class to add to .jshowoff wrapper [string]
effect :			transition effect [string: 'fade', 'slideLeft' or 'none', defaults to 'fade']
hoverPause :		whether to pause on hover [boolean, defaults to true]
links :				whether to create & display numeric links to each slide [boolean, defaults to true]
speed :				time each slide is shown [integer, milliseconds, defaults to 3000]

*/

(function($) {


	$.fn.jshowoff = function(settings) {

		// default global vars
		var config = {
			animatePause : true,
			autoPlay : true,
			changeSpeed : 600,
			controls : true,
			controlText : {
				play :		lang['slide-show'],
				pause :		lang['pause'],
				next :		lang['next'],
				previous :	lang['back']
			},
			effect : 'fade',
			hoverPause : true,
			links : true,
			speed : 3000
		};

		// merge default global variables with custom variables, modifying 'config'
		if (settings) $.extend(true, config, settings);

		// make sure speed is at least 20ms longer than changeSpeed
		if (config.speed < (config.changeSpeed+20)) {
			alert('jShowOff: Make speed at least 20ms longer than changeSpeed; the fades aren\'t always right on time.');
			return this;
		};

		// create slideshow for each matching element invoked by .jshowoff()
		this.each(function(i) {

			// declare instance variables
			var $cont = $(this);
			var gallery = $(this).children().remove();
			var timer = '';
			var counter = 0;
			var preloadedImg = [];
			var howManyInstances = $('.jshowoff').length+1;
			var uniqueClass = 'jshowoff-'+howManyInstances;
			var cssClass = config.cssClass != undefined ? config.cssClass : '';


			// set up wrapper
			$cont.css('position','relative').wrap('<div class="jshowoff '+uniqueClass+'" />');
			var $wrap = $('.'+uniqueClass);
			$wrap.css('position','relative').addClass(cssClass);

			// add first slide to wrapper
			$(gallery[0]).clone().appendTo($cont);

			// preload slide images into memory
			preloadImg();

			// add controls
			if(config.controls){
				addControls();
				if(config.autoPlay==false){
					$('.'+uniqueClass+'-play').addClass(uniqueClass+'-paused jshowoff-paused').text(config.controlText.play);
				};
			};

			// add slide links
			if(config.links){
				addSlideLinks();
				$('.'+uniqueClass+'-slidelinks a').eq(0).addClass(uniqueClass+'-active jshowoff-active');
			};

			// pause slide rotation on hover
			if(config.hoverPause){ $cont.hover(
				function(){ if(isPlaying()) pause('hover'); },
				function(){ if(isPlaying()) play('hover'); }
			);};

			// determine autoPlay
			if(config.autoPlay && gallery.length>1) {
				timer = setInterval( function(){ play(); }, config.speed );
			};

			// display error message if no slides present
			if(gallery.length<1){
				$('.'+uniqueClass).append('<p>For jShowOff to work, the container element must have child elements.</p>');
			};


			// utility for loading slides
			function transitionTo(gallery,index) {

				var oldCounter = counter;
				if((counter >= gallery.length) || (index >= gallery.length)) { counter = 0; var e2b = true; }
				else if((counter < 0) || (index < 0)) { counter = gallery.length-1; var b2e = true; }
				else { counter = index; }


				if(config.effect=='slideLeft'){
					var newSlideDir, oldSlideDir;
					function slideDir(dir) {
						newSlideDir = dir=='right' ? 'left' : 'right';
						oldSlideDir = dir=='left' ? 'left' : 'right';					
					};


					counter >= oldCounter ? slideDir('left') : slideDir('right') ;

					$(gallery[counter]).clone().appendTo($cont).slideIt({direction:newSlideDir,changeSpeed:config.changeSpeed});
					if($cont.children().length>1){
						$cont.children().eq(0).css('position','absolute').slideIt({direction:oldSlideDir,showHide:'hide',changeSpeed:config.changeSpeed},function(){$(this).remove();});
					};
				} else if (config.effect=='fade') {
					$(gallery[counter]).clone().appendTo($cont).hide().fadeIn(config.changeSpeed,function(){if($.browser.msie)this.style.removeAttribute('filter');});
					if($cont.children().length>1){
						$cont.children().eq(0).css('position','absolute').fadeOut(config.changeSpeed,function(){$(this).remove();});
					};
				} else if (config.effect=='none') {
					$(gallery[counter]).clone().appendTo($cont);
					if($cont.children().length>1){
						$cont.children().eq(0).css('position','absolute').remove();
					};
				};

				// update active class on slide link
				if(config.links){
					$('.'+uniqueClass+'-active').removeClass(uniqueClass+'-active jshowoff-active');
					$('.'+uniqueClass+'-slidelinks a').eq(counter).addClass(uniqueClass+'-active jshowoff-active');
				};
			};

			// is the rotator currently in 'play' mode
			function isPlaying(){
				return $('.'+uniqueClass+'-play').hasClass('jshowoff-paused') ? false : true;
			};

			// start slide rotation on specified interval
			function play(src) {
				if(!isBusy()){
					counter++;
					transitionTo(gallery,counter);
					if(src=='hover' || !isPlaying()) {
						timer = setInterval(function(){ play(); },config.speed);
					}
					if(!isPlaying()){
						$('.'+uniqueClass+'-play').text(config.controlText.pause).removeClass('jshowoff-paused '+uniqueClass+'-paused');
					}
				};
			};

			// stop slide rotation
			function pause(src) {
				clearInterval(timer);
				if(!src || src=='playBtn') $('.'+uniqueClass+'-play').text(config.controlText.play).addClass('jshowoff-paused '+uniqueClass+'-paused');
				if(config.animatePause && src=='playBtn'){
					$('<p class="'+uniqueClass+'-pausetext jshowoff-pausetext">'+config.controlText.pause+'</p>').css({ fontSize:'62%', textAlign:'center', position:'absolute', top:'40%', lineHeight:'100%', width:'100%' }).appendTo($wrap).addClass(uniqueClass+'pauseText').animate({ fontSize:'600%', top:'30%', opacity:0 }, {duration:500,complete:function(){$(this).remove();}});
				}
			};

			// load the next slide
			function next() {
				goToAndPause(counter+1);
			};

			// load the previous slide
			function previous() {
				goToAndPause(counter-1);
			};

			// is the rotator in mid-transition
			function isBusy() {
				return $cont.children().length>1 ? true : false;
			};

			// load a specific slide
			function goToAndPause(index) {
				$cont.children().stop(true,true);
				if((counter != index) || ((counter == index) && isBusy())){
					if(isBusy()) $cont.children().eq(0).remove();
					transitionTo(gallery,index);
					pause();
				};
			};	

			// load images into memory
			function preloadImg() {
				$(gallery).each(function(i){
					$(this).find('img').each(function(i){
						preloadedImg[i] = $('<img>').attr('src',$(this).attr('src'));					
					});
				});
			};

			// generate and add play/pause, prev, next controls
			function addControls() {
				$wrap.append('<p class="jshowoff-controls '+uniqueClass+'-controls"><a class="jshowoff-play '+uniqueClass+'-play" href="#null">'+config.controlText.pause+'</a> <a class="jshowoff-prev '+uniqueClass+'-prev" href="#null">'+config.controlText.previous+'</a> <a class="jshowoff-next '+uniqueClass+'-next" href="#null">'+config.controlText.next+'</a></p>');
				$('.'+uniqueClass+'-controls a').each(function(){
						if($(this).hasClass('jshowoff-play')) $(this).click(function(){ isPlaying() ? pause('playBtn') : play(); return false; } );
						if($(this).hasClass('jshowoff-prev')) $(this).click(function(){ previous(); return false; });
						if($(this).hasClass('jshowoff-next')) $(this).click(function(){ next(); return false; });

				});
			};	

			// generate and add slide links
			function addSlideLinks() {
				$wrap.append('<p class="jshowoff-slidelinks '+uniqueClass+'-slidelinks"></p>');
				$.each(gallery, function(i, val) {
					var linktext = $(this).attr('title') != '' ? $(this).attr('title') : i+1;
					$('<a class="jshowoff-slidelink-'+i+' '+uniqueClass+'-slidelink-'+i+'" href="#null">'+linktext+'</a>').bind('click', {index:i}, function(e){ goToAndPause(e.data.index); return false; }).appendTo('.'+uniqueClass+'-slidelinks');
				});
			};		


		// end .each
		});

		return this;

	// end .jshowoff
	};

// end closure
})(jQuery);




(function($) {

	$.fn.slideIt = function(settings,callback) {

		// default global vars
		var config = {
			direction : 'left',
			showHide : 'show',
			changeSpeed : 600
		};

		// merge default global variables with custom variables, modifying 'config'
		if (settings) $.extend(config, settings);

		this.each(function(i) {	
			$(this).css({left:'auto',right:'auto',top:'auto',bottom:'auto'});
			var measurement = (config.direction == 'left') || (config.direction == 'right') ? $(this).outerWidth() : $(this).outerHeight();
			var startStyle = {};
			startStyle['position'] = $(this).css('position') == 'static' ? 'relative' : $(this).css('position');
			startStyle[config.direction] = (config.showHide == 'show') ? '-'+measurement+'px' : 0;
			var endStyle = {};
			endStyle[config.direction] = config.showHide == 'show' ? 0 : '-'+measurement+'px';
			$(this).css(startStyle).animate(endStyle,config.changeSpeed,callback);
		// end .each
		});

		return this;

	// end .slideIt
	};

// end closure
})(jQuery);(function($){
     $.fn.extend({
          center: function (options) {
               var options =  $.extend({ // Default values
                    inside:window, // element, center into window
                    transition: 0, // millisecond, transition time
                    minX:0, // pixel, minimum left element value
                    minY:0, // pixel, minimum top element value
                    vertical:true, // booleen, center vertical
                    withScrolling:true, // booleen, take care of element inside scrollTop when minX < 0 and window is small or when window is big 
                    horizontal:true // booleen, center horizontal
               }, options);
               return this.each(function() {
                    var props = {position:'absolute'};
                    if (options.vertical) {
                         var top = ($(options.inside).height() - $(this).outerHeight()) / 2;
                         if (options.withScrolling) top += $(options.inside).scrollTop() || 0;
                         top = (top > options.minY ? top : options.minY);
                         $.extend(props, {top: top+'px'});
                    }
                    if (options.horizontal) {
                          var left = ($(options.inside).width() - $(this).outerWidth()) / 2;
                          if (options.withScrolling) left += $(options.inside).scrollLeft() || 0;
                          left = (left > options.minX ? left : options.minX);
                          $.extend(props, {left: left+'px'});
                    }
                    if (options.transition > 0) $(this).animate(props, options.transition);
                    else $(this).css(props);
                    return $(this);
               });
          }
     });
})(jQuery);// функции которые исполняем только после полной загрузки сайта
$(document).ready(function(){



	$("#search").corner("3px");
	
	$("textarea.elastic").elastic();
	$('textarea.max220').maxlength( {slider: true, maxCharacters: 220} );
	$('textarea.max160').maxlength( {status: false, maxCharacters: 160} );
	
	
	$("#left_user_box").corner("5px");
	$("#right_info_box").corner("5px");
	
	$("#right_info_box").find('p').corner("5px");
	$(".right_pic").corner("5px top").corner("10px bottom");
	//$(".uni_bot").corner("5px top");
	
	$("h1").corner("3px");

	
	$("#bottom").corner("3px");
	
	$("#link_on_page").corner("3px");
	

	
	
	// H2 -- H2 -- H2 //////////////////////////////////////
	var h2 = $("h2");
	h2.corner("3px");
	
	
	
	/// сворачиваем блоки
	var toktok = $("div.left-box-title, h2, div.right-box-title");
	
	toktok.click(function () {
		var tokid = $(this).attr('id');

		if (tokid!='') {
			var div_block = $(this).next();
			
			if ($.cookie('sh')==null) {
				var kuka_sh = '0';
			} else {
				var kuka_sh = $.cookie('sh');
			}			
				
				
			div_block.slideToggle(100, function () {
												 
				if (div_block.is(":hidden")) {
					$(this).prev().addClass("hide");
					
					if (kuka_sh.indexOf(tokid)!=-1) { } else {
						
						$.cookie('sh', kuka_sh+tokid, {
							expires: 356,
							path: "/",
							domain: cookie_site
						});
					}
				} else {				
					$(this).prev().removeClass("hide");
					$.cookie('sh', kuka_sh.replace(tokid, ''), {
						expires: 356,
						path: "/",
						domain: cookie_site
					});
				}
			
			});
		}
	});
	/////////////////////// H2 ////////////////////////
	
	
	
	
	
	
	// меняем цветовые схемы
	$("#design_color a").click(function () {
		var new_color = $(this).attr('class').substr(1,2);
		
		var new_css1 = $("#css1").attr('href').replace('/'+design_color+'/', '/'+new_color+'/');
		$("#css1").attr('href', new_css1);
		
		var new_css2 = $("#css2").attr('href').replace('/'+design_color+'/', '/'+new_color+'/');
		$("#css2").attr('href', new_css2);
		
		design_color = new_color;
		$.cookie("designColor", new_color, {
			expires: 356,
			path: "/",
			domain: cookie_site
		});
		return false;
	});
	

	/////////////////////////////////////////////////////////////
	friends_row = $(".friends .row");
	friends_row.find("a[rel*='fr_add'],a[rel*='fr_del'],a[rel*='fr_apply'],a[rel*='fr_cancel']").click(function () {
		var this_a = $(this);
		var w = this_a.attr('rel');
		var w = w.substring(3, w.length);
		var this_r = this_a.parent('p');
		
		if (w!='apply' && w!='cancel') {
			var fr_id = this_a.parent("div").parent("div").attr('id');
			var yTitle = 'Мои друзья';
			yes(yTitle, '', 1);
		} else {
			var fr_id = this_a.parent("p").parent("div").parent("div").attr('id');
			this_r.addClass('frRequests load');
			this_r.text('...');
		}
		var fr_id = fr_id.substring(2, fr_id.length);
		

		$.post(sefon+'/ajax/friends.php', { id: fr_id, w: w },
		function(data){
			if (w!='apply' && w!='cancel') {
				yes(yTitle, data, 1);
			} else {
				this_r.removeClass('load');
				this_r.text(data);
				var num = Number($("div.t_links strong.look_friends").find('span').text());
				var num = num-1;
				if (num==0) {
					$('.look_friends').remove();
				} else {
					$('.look_friends').find('span').text(num);
				}
			}
		});
		return false;
	});
	

	//// yes close //////////////////////////////////////////////////////////////////////
	$('#yClose').click(function () {
		yes('','',3);
	});
	
	


	
	///////////////////////////////////////////////////////////////////////////

	// 
	$("#fotoshow,#fotoshowNext,#fotoshowBack").click(function () {
		$('#fotoshow').fadeTo('fast', 0.7);
		if ($(this).attr('id')=='fotoshowBack') {
			var np = npic_now--;
			if (np<2) { npic_now = npic_num; }
		} else {
			var np = npic_now++;
			if (np >= npic_num) { npic_now = 1; }
		}
		$('#fotoshow').find('img').attr('src', npic[npic_now]);
		
		if (npic[npic_now+1]!=undefined) {
			$('#nextImg').attr('src', npic[npic_now+1]);
		}
		onajax('bottom_foto_blok', qw, npic_id[npic_now]);
		$('#now_foto').text(npic_now);
		$('#fotoshow').fadeTo('fast', 1);
		return false;
	});
	/////////////////////////////////////////////////////////////
	

	//
	//var row_stars_go = function() {
		//alert('ddd');
		row_stars = $("div.row_stars div.row p");

		row_stars.click(function () {									 
			var w = $(this).attr('class').substring(2, 3);
			var star_id = $(this).parent("div").attr('id');			
			var id = star_id.substring(1, star_id.length);
			love_hate(id, w);
			return false;
		});
	//}
	/////////////////////////////////////////////////////////////
	
	
	// показываем блок при наведении на исполнителей и песни
	var stars_box_a = $("a[rel*='s'],a[rel*='m']");
	var star_box = $("#star_box");
	var star_box_inner = $("#star_box_inner");
	star_showBox = '';
	star_hideBox = '';
	ms_id = '';
	what_is = '';
	var only_s =  $('#only_s');
	var only_m =  $('#only_m');
	star_box_p = star_box_inner.find('p');
	st_new_left = 0;
	this_a = '';
	
	stars_box_a.hover(function (e) {
		clearTimeout(star_hideBox);
		this_a = $(this);
		var star_rel = $(this).attr('rel');
		what_is = star_rel.substring(0, 1);
		ms_id = star_rel.substring(1, star_rel.length);
		
		
		//if (what_is=='s') { star_box.addClass('star_box_bg'); } else { star_box.removeClass('star_box_bg'); }

		star_showBox = setTimeout(function() {
			if (what_is=='m') { only_m.show(); only_s.hide(); } else { only_m.hide(); only_s.show() }
			//star_box_inner.css({'height':'', 'width':''});
			star_box_p.text('');
			star_box.fadeIn('slow');
			
			var position = this_a.position();
			var st_width = parseInt(star_box.width());
			var st_new_left = e.pageX - st_width/2;
			
			if (this_a.find('img').attr('id')!=undefined) {
				star_box.css({top:position.top-20, left:st_new_left});
			} else {
				star_box.css({top:position.top-30, left:st_new_left });
			}
		}, 500);
	}, function () {
		clearTimeout(star_showBox);
		star_hideBox = setTimeout(function() { star_box.fadeOut('fast'); }, 500);
				
		star_box.hover(function() {
			clearTimeout(star_hideBox);	
		},function() {
			star_hideBox = setTimeout(function() { star_box.fadeOut('fast'); }, 500);
		});
	});
	
	// показываем подсказку к иконкам у исполнителя в боксе
	stars_box_img = star_box_inner.find('img');
	
		
	stars_box_img.hover(function () {
		var img_alt = $(this).attr('alt');
		$.cursorMessage(img_alt, {hideTimeout:2000, offsetX:0, offsetY:-25});
	}, function() {
		 $('#curDiv').hide();
	});
	
	// кликаем по кнопке
	stars_box_img.click(function () {
		w = $(this).attr('id').substring(4, 5);
		what_is_click = what_is;
		this_a_click = this_a;
		//w = w.substring(3, w.length);
		yes('Предпочтения в музыке', '', 1);
		$.post(sefon+'/ajax/love_hate.php', { id: ms_id, w: w, ms: what_is },
		function(data){
			yes('', data, 2);
			setTimeout(function() { star_box_wait = 0; }, 500);
			if (pgd=='music' && (w=='3' || w=='5')) {		
				this_a_click.parent('div.row').remove();
			}
			else if (pgd=='stars' && w=='3') {
				this_a_click.parent('div.row').remove();
			}
		});
	});


	
	

	
	$('#nav').sideswap();
	
	
	
	
	
	
	
	
	/*


	
	

	
	
	
	
	
	////////// ajax поиск ////////////////////////
	var linesearch = 0;
	$("#line_search").click(function () {
		if (linesearch==0) {
			this.focus();
			this.select();
			$(this).css('color','#000');
			linesearch = 1;
		}
	});
	//////////////////////////////////////////////
	
	
	
	/// если пол такой-то то меням род у семейного положения
	$("#sex").change(function () {
		if ($(this).val()!=2) {
			$("#marital_1").css({"display":"block", "name":"marital"});
			$("#marital_2").css({"display":"none", "name":""});
		} else {
			$("#marital_1").css({"display":"none", "name":""});
			$("#marital_2").css({"display":"block", "name":"marital"});
		}
	});
	
	$("#us_sex").change(function () {
		$("#marital_box").css("display", "none");
		if ($(this).val()!=2) {
			$("#marital_1").css({"display":"block", "name":"us_marital"});
			$("#marital_2").css({"display":"none", "name":"us_marital_none"});
		} else {
			$("#marital_1").css({"display":"none", "name":"us_marital_none"});
			$("#marital_2").css({"display":"block", "name":"us_marital"});
		}
	});
	
	// семейное положение
	$("#marital_1, #marital_2").change(function () {
		if ($(this).val()>1 && $(this).val()<7) {
			
			$("#marital_box").css("display", "block");
			$("#info_marital").css("display", "block");
			
			if ($("#marital_1").css("display")!='none') {
				
				$("#marital_1 option:selected").each(function () {
					$("#marital_of").text($(this).text());
					
					if ($(this).val()==2) {
						g("marital_of").innerHTML += ' в...';
					} else if ($(this).val()==4) {
						g("marital_of").innerHTML += ' на...';
					} else if ($(this).val()==5) {
						g("marital_of").innerHTML += ' на...';
					} else if ($(this).val()==6) {
						g("marital_of").innerHTML += ' с...';
					}
				});
			
			} else {
				
				$("#marital_2 option:selected").each(function () {
					$("#marital_of").text($(this).text());
					
					if ($(this).val()==2) {
						g("marital_of").innerHTML += ' в...';
					} else if ($(this).val()==4) {
						g("marital_of").innerHTML += ' на...';
					} else if ($(this).val()==5) {
						g("marital_of").innerHTML += ' за...';
					} else if ($(this).val()==6) {
						g("marital_of").innerHTML += ' с...';
					}
				});
				
			}
			
		} else {
			$("#marital_box").css("display", "none");
			$("#marital_of").text("");
			$("#info_marital").css("display", "none");
		}
	});
	
	
	
	
	
	/// меняем блоки комментариев
	hover_com = 0;
	$(".new_comments").hover(function() {
		hover_com = 1;
	},
	function() {
		hover_com = 0;
	});
	$("#new_com1").everyTime(5000, function() {
		if (hover_com==0) {
			$("#new_com1, #new_com5").slideToggle("slow");
		}
	});
	/////////////////////////////


	
	$(".forma_blog .knopka").click(function () {
		var theme_length = $(".forma_blog input:name=[name]").attr('value').length;
		var text_length = $(".forma_blog textarea").attr('value').length;

		if (theme_length < 5) {
			alert('Введите тему (не менее 5 символов, сейчас '+theme_length+')');
			return false;
		}
		else if (text_length < 5) {
			alert('Введите текст (не менее 5 символов, сейчас '+text_length+')');
			return false;
		}
	});
	
	
	
	
	
	
	
	
	




	/// отправка личных сообщений
	$("#add_mp3 .knopka").click(function () {
		
		if ($("#add_mp3_singer").attr('value') == '') { alert('Введите название исполнителя'); return false; }
		else if ($("#add_mp3_song").attr('value') == '') { alert('Введите название песни'); return false; }
		else if ($("#add_mp3_url").attr('value').length < 17) { alert('Укажите ссылку на mp3'); return false; }

		addmp3($("#add_mp3_singer").attr('value'), $("#add_mp3_song").attr('value'), $("#add_mp3_url").attr('value'));
	});
	
	
	
	
	
	

	

	
	//function() { $.cursorMessage('hello', {hideTimeout:0}) }
	//$('#tttt').mouseout($.hideCursorMessage);
	
	//$('#fasting_form option').mouseover(function() { $.cursorMessage('hello', {hideTimeout:0}) });
	//$('#fasting_form option').mouseout($.hideCursorMessage);

	$("div.btm").find("a").corner("5px");
	
	

	$("#line_search").keyup(function(e) {
		if (e.which==13 || e.which==27 || e.which==37 || e.which==38 || e.which==39 || e.which==40 || e.which==40) { }
		else {
			
			var val = $('#line_search').attr('value');
			
			if (val.length < 2) {
				$(".ajax_search").hide();
				return false;
			}
	
			// проверяем кеш
			if (cache_se[val]!=undefined) {
				$(".ajax_search").show();
				$(".ajax_search").children("p").html(cache_se[val]+'<hr />');
				$(".ajax_search").animate({ height: $(".ajax_search").children("p").css('height') }, 500 );
				$("#ajax_search_load").hide();
				return false;
			}
	
			$("#line_search").stopTime('se_ajax');
			$("#line_search").oneTime(1000, 'se_ajax', function() {
				ajax_search();		
			});
		}
	});
	
	
	$(document).click(function() {
		$(".ajax_search").oneTime(200, function() {
			$(".ajax_search").hide();
		});				   
	});
	
	
	
	
	$("#star_img").hover(function() {see_prev = 1;}, function() {see_prev = 0;});
	
	starIMG = 1;
	$("#star_img").everyTime(6000, function() {
			if (see_prev==0) {
				see_prev = 1;
				
				$("#star_img"+starIMG).find("div").show();
				$("#star_img"+starIMG).find("div").fadeTo('slow', 0.60);
				
				
				$(this).find("img").fadeTo('slow', 0.25, function() {					
					starIMG = parseInt(starIMG) + 1;
					if ($("#star_img"+starIMG).attr("href")==undefined) { starIMG = 1; }					
					$(this).attr('src', sefon_pic+'/wh300/'+$("#star_img"+starIMG).find("img").attr('id'));
					
					$("#star_img").attr('href', $("#star_img"+starIMG).attr('href'));
					$(this).fadeTo('slow', 1);

					$("#star_img"+starIMG).find("div").fadeTo('slow', 0);
					
					if ($("#star_img").find("img").css('marginLeft')=='-1px') {
						var mrg_left = -90;
					} else {
						var mrg_left = -1;
					}
					$("#star_img").find("img").animate({
						marginLeft: mrg_left
						
					}, 4500, function () { see_prev = 0; });
				});
			}
	});
	////////////////////////////////////////////////////////////////
	

	if ($("#us_country").attr('value')!=undefined) {
	$("#us_country").autocomplete(country, {
		autoFill: true,
		max: 999,
		mustMatch: true,
		minChars: 0
	});
	}
	
	
	
	
	$(".corner_left").corner("left");
	$(".corner_right").corner("right");
	
	$(".panel_top_page a").corner("top 7px");
	
	
	///////////// работаем с фотками юзеров //////////////
	$(".album_edit_fotos textarea").focus(function() {
		if ($(this).next('input').attr('value')==0) {
			$(this).attr('value', '');
			$(this).css('color','#000');
			$(this).next('input').attr('value', 1);
		}
	});

	$(".album_edit_fotos textarea").blur(function() {
		if ($(this).attr('value')=='') {
			$(this).next('input').attr('value', 0);
			$(this).attr('value','введите описание к фотографии');
			$(this).css('color','#999');
		}
	});
	
	
	var css_label = {
		'background-color' : '',
		'color' : ''
	}
	var css_label_on = {
		'background-color' : '#66CC66',
		'color' : '#fff'
	}
	
	$(".album_edit_fotos label").hover(
		function() {
			if ($(this).attr('title')=='') {
				$(this).css('backgroundColor', '#FF977D');
			} else {
				$(this).css('backgroundColor', '#66CC66');
			}
			$(this).css('color', '#FFF');
		},
		function() {
			if ($(this).find("input").attr('checked')==false) {
				$(this).css(css_label);
			}
		}
	);
	
	$(".album_edit_fotos label[title!='']").click(function() {		
		
		$(".album_edit_fotos label[title!=''] input[checked=false]").parent().css(css_label);
		$(this).css(css_label_on);
	});
	
	$(".album_edit_fotos label").find("input:checked").parent().css(css_label_on);
	
	$(".album_edit_fotos textarea").keyup(function() {
		if ($(this).attr('value').length >= 250) { $(this).attr('value', $(this).attr('value').substr(0,250)); }
	});
	
	$(".album_edit_fotos label").corner("left");
	

	$("#del_album").click(function() {
		if ($(this).attr('checked')==true) {
			$(this).parent().css("backgroundColor", "#FF977D");
			$('#del_album_btm').text('УДАЛИТЬ АЛЬБОМ');
		} else {
			$(this).parent().css("backgroundColor", "#fff");
			$('#del_album_btm').text('Редактировать альбом');
		}
	});
	
	
	$("#add_user_foto").click(function() {
		$('.add_album').fadeOut('fast', function() {												 
			$('#process_add').fadeIn('fast', function() {
				$('.add_album').submit();
			});			
		});		
	});
	//////////////////////////////////////////////////////
*/
	
}); // end ready
function g(id) {
	if(document.getElementById) {
		return document.getElementById(id);
	}else if(document.all) {
		return document.all[id];
	}else if(document.layers) {
		return document.layers[id];
	}

	return null;
}




function brouser() {
  var ua = navigator.userAgent.toLowerCase();
  // Определим Internet Explorer
  if (ua.indexOf("msie") != -1 && ua.indexOf("opera") == -1 && ua.indexOf("webtv") == -1) {
    return "msie"
  }
  // Opera
  if (ua.indexOf("opera") != -1) {
    return "opera"
  }
  // Gecko = Mozilla + Firefox + Netscape
  if (ua.indexOf("gecko") != -1) {
    return "gecko";
  }
  // Safari, используется в MAC OS
  if (ua.indexOf("safari") != -1) {
    return "safari";
  }
  // Konqueror, используется в UNIX-системах
  if (ua.indexOf("konqueror") != -1) {
    return "konqueror";
  }
  return "unknown";
}




function anch() {
  if (event.srcElement.tagName=='A'
  && !event.srcElement.href.indexOf(document.location+'#')) {
    var id=event.srcElement.href;
    id=id.substr(id.indexOf('#')+1);
    document.all[id].scrollIntoView(true);
    return false;
    }
  return true;
}


function anchor_go(id) {
	document.all[id].scrollIntoView(true);
}







/// insert bbcode
function bbcode(f,txt,v1,v2) {

	f = g(f);
	//  Для MSIE,OPERA
	if (document.selection) {
		f.focus();
		sel = document.selection.createRange();
		var septext = sel.text;
		if (septext=='') { var septext = txt; }
		sel.text = v1+septext+v2;
	}
	// Для других браузеров
	else if (f.selectionStart || f.selectionStart == '0') {
		
		var startPos = f.selectionStart;
		var endPos = f.selectionEnd;
		var septext = f.value.substring(startPos, endPos);
		if (septext=='') { var septext = txt; }
		f.value = f.value.substring(0, startPos) + v1+sel_text+v2 + f.value.substring(endPos, f.value.length);
		
	}
	else {
		f.value += v;
	}
	
	return false;
}


///////////////////////


////////// online and user box
a_users = '';
cache_user_box = new Array();
function onlines_check(box) {

	if (box==undefined) {
		var el = $("a[rel*='u']");
	} else {
		var el = $("#"+box).find("a[rel*='u']");
	}
	
	var el_length = el.length;

	for (var i = 0; i < el_length; i++) {
		
		var aa = $(el[i]);
		var a_rel = aa.attr("rel");

			var id = a_rel.substring(1, a_rel.length); // обрезаем всё из rel и оставляем только номер юзера который в онлайне или нет

			// если такая переменная есть, значит юзер в онлайне
			if (onlines[id] != undefined) {	
				if (a_id==id) {
					// it's user
					aa.prepend('<div class="o"></div>');
					//aa.addClass("oai");
				} else {
					aa.prepend('<div class="o"></div>');
					//aa.addClass("oai");
				}
			} else {
				// offline
				//aa.prepend('<div class="o"></div>');
				//aa.addClass("oai");
			}

	} // for
	
	
	
	// это j-функция долнжа быть только внутри этой функции, так как a_users почему то быстро кешируется на стороне jquary и она никак не хочет обновляться, когда я добавляю на страницу новых юзеров
	// юезр бокс - показываем небольшое инфо о юзере при наведении на его ник или аватару
		a_users = el;
		user_box = $("#user_box");
		user_box_inner = $("#user_box_inner");
		showBox = '';
		hideBox = '';
		
		a_users.hover(
		function (e) {
			// если для некоторых юзеров в некоторых ситуациях не нужно показывать инфо всплвающее, то нужно там в ссылке указать id = 'not_box' и всё
			if ($(this).attr('id')!='not_box' && $(this).attr('id')=='Uberi-I-Budet_Block') {
			
				clearTimeout(hideBox);
				var user_rel = $(this).attr('rel');
				var user_id = user_rel.substring(1, user_rel.length);		
	
				showBox = setTimeout(function() {					
					user_box.fadeIn('fast');
					user_box.css({top:e.pageY, left:e.pageX});
					
					// проверяем кеш на стороне клиента
					if (cache_user_box[user_id]!=undefined) {
						user_box_inner.html(cache_user_box[user_id]);
						onlines_check('user_box_inner');
					// если кеша нет, то делаем аякс запрос
					} else {
						user_box_inner.html('<div class="loader"></div>');
						$.post(sefon+'/ajax/user_box.php', { user_id: user_id },
							function(data){								
								user_box_inner.html(data);
								onlines_check('user_box_inner');
								cache_user_box[user_id] = data;
							}
						);
					}					
				}, 1000);
			
			} // if not_box
			
			//if (user_box.is(":hidden")) {} else { clearTimeout(showBox); }
		},
		function () {
			if ($(this).attr('id')!='not_box') {
			
				clearTimeout(showBox);
				hideBox = setTimeout(function() { user_box.fadeOut('fast'); }, 500);
				
				user_box.hover(function() {
					clearTimeout(hideBox);	
				},function() {
					hideBox = setTimeout(function() { user_box.fadeOut('fast'); }, 500);
				});

			} // if not_box
		});
		////////////////////////////////////////////////////////////////////////////////////////////////
		
}
///////////////////////



/// comments
otvetCm = 'main_otvet';
function otvet(kuda,otvet) {
	var replyForm = g('forma_otveta');
	$('#forma_otveta').css('marginLeft', $('#'+kuda).css('marginLeft'));
	$('#forma_otveta').css('width', $('#'+kuda).css('width'));
	
	otvetCm = kuda;
	
	
	if (otvet != g('otvety').value) {
			var currentComment = g(kuda);
			g('otvety').value = otvet;			
		} else {
			var currentComment = g('main_otvet');
			g('otvety').value = 0;
			g('forma_otveta').style.marginLeft = 0;
			$('#forma_otveta').css('width', '610px');
		}
					
		currentComment.parentNode.insertBefore(replyForm, currentComment.nextSibling);
}
/// end











function poisk(s) {
	closed('change_search');	
	g('ishem').innerHTML = g('poisk'+s).innerHTML;
	g('se').value = s;
	
/*	if (brouser()=='opera') {
		g('change_search').style.marginTop = '40px';
	}*/
	
	opened('poisk1');
	opened('poisk2');
	opened('poisk3');
	opened('poisk4');
	opened('poisk5');
	
	closed('poisk'+s);
	poisk2();
	return false;
}

function poisk2() {
	if (g('up_down').innerHTML=='▼') {
		g('up_down').innerHTML = '▲';
	} else {
		g('up_down').innerHTML = '▼';
	}
}




function poisk_letters() {
	if (g('my_letters').value.length < 20) {
		window.location.href = sefon+'/letters/'+g('my_letters').value;
	} else {
		g('my_letters').style.border = '1px red solid';	
	}
	
	setTimeout("g('my_letters').style.border = '1px gray solid';", 2000);
}






//// голосование за фотографии, режим наведения мыши
function vote_mouse(n,r) {
	var url_star = sefon+'/img';
	
	if (n==0) {
		for (var i = 1; i <= 5; i++) {
			if (i<=r) {
				g('vote'+i).src = url_star+'/star.png';
			} else {
				g('vote'+i).src = url_star+'/star2.png';
			}
		}
	} else {
		
		for (var i = 1; i <= n; i++) {
				g('vote'+i).src = url_star+'/star3.png';
		}
		for (var i = i; i <= 5; i++) {
				g('vote'+i).src = url_star+'/star2.png';
		}
		
	}
}

//// голосование за фоторагфию
function vote(v) {

	var votText = $('#votes_status');
	votText.text('секунду...');

	$.post(sefon+'/ajax/votes_photo.php', { v: v, id: com_id, com_ch: com_ch, user_photo: user_photo },
		function(data){
			votText.text(data.q);
			if (data.rate>0) {
				$('#fotos_rate').text(data.rate);
				vote_mouse(0,data.rate2);
				$('#fotos_vote').text(data.votes);
			}
			for (var i = 1; i <= 5; i++) {
					g('vote'+i).onmouseover = '';
					g('vote'+i).onclick = '';
			}
			g('votes').onmouseout = '';
		}, 'json');
	return false;
}
/////////////////////////





function photo(id,w) {
	
	yes('Редактирование фотографий', '', 1);
	
	$.post(sefon+'/ajax/photo.php', { id: id, w: w, page: pagego },
		function(data){
			if (w=='del') {
				yes('', data, 2);
				$('#bottom_foto_blok').fadeTo('fast', 0.1);
				$('#fotoshow').find('img').attr('src', sefon_img+'/foto-delete.png');
			} else {
				yes('', data, 1);
			}
	});
}




/// добавялем mp3 ссылки
function addmp3(singer, song, url) {
	$(".add_mp3_status").text('Пожалуйста, подождите...');
	
	var req = new JsHttpRequest();
	req.onreadystatechange = function() {

		if (req.readyState == 4) {
			$(".add_mp3_status").html(req.responseJS.q);
		}
			
	}
	req.open(null, sefon+'/ajax/add_mp3.php', true);
	req.send( { singer: singer, song: song, url: url  } );
}


// ajax поиск
cache_se = new Array();
function ajax_search() {
		
	var val = $('#line_search').attr('value');	
	
	$("#ajax_search_load").show();
	
	$.post(sefon+'/ajax/search.php', { q: $('#line_search').attr('value') },
		function(data){
			
			$(".ajax_search").children("p").html(data);
			cache_se[val] = data;
			
			// msie
			if (brouser()=='msie') {
				$(".ajax_search").show();
			} else {
			
				if ($(".ajax_search").is(":hidden")) {
					$(".ajax_search").css('height', '1px');
					$(".ajax_search").show();
					//$(".ajax_search").fadeIn('slow');
					
					$(".ajax_search").animate({ height: $(".ajax_search").children("p").css('height') }, 500 );
				} else {
					$(".ajax_search").animate({ height: $(".ajax_search").children("p").css('height') }, 500 );
				}
			} // end brouser
			

			$("#ajax_search_load").hide();
	});
}



// ajax блоки, выводим информацию через ajax, ту которая уже кешированная, но которую не хочется показывать в самом html
function ajax_box(box, ch) {

	$("#"+box).html('<div class="loader"></div>');

	$.post(sefon+'/ajax/box.php', { box: box, ch: ch },
		function(data){
			$("#"+box).html(data);
			onlines_check(box);			
		}
	);
}


// ajax блоки
function onajax(box, n1, n2) {
	//$("#"+box).html('<div class="loader"></div>');
	$("#"+box).fadeTo('fast', 0.2);

	$.post(sefon+'/ajax/onajax.php', { box: box, n1: n1, n2: n2 },
		function(data){
			$("#"+box).html(data);
			$("#"+box).fadeTo('fast', 1);
			onlines_check(box);			
		}
	);
}

// любит не любит
function love_hate(id, w) {
	var preDiv = $('#s'+id);
	preDiv.addClass('loader2');
	preDiv.fadeTo('slow', 0.3);
	
	$.post(sefon+'/ajax/love_hate.php', { id: id, w: w },
		function(data){
			preDiv.removeClass('loader2');
			preDiv.addClass('cntr');
			preDiv.html(data);
			preDiv.parent('div').fadeTo('slow', 0, function() {
     			//$(this).remove();
				
				var num = Number($("div.t_links strong.look_fv_stars").find('span').text());
				var num = num-1;
				if (num==0) {
					$('.look_fv_stars').remove();
				} else {
					$('.look_fv_stars').find('span').text(num);
				}
    		});
			
		}
	);
}


/// друзья
function requests(id,w) {
	var yTitle = 'Мои друзья';
	yes(yTitle, '', 1);
	$.post(sefon+'/ajax/friends.php', { id: id, w: w },
		function(data){
			if (w=='del') {
				//$('#fr'+id).text('Участник удалён из Вашего списка друзей').addClass('cntr');
				$('#fr'+id).remove();
			}
			yes(yTitle, data, 2);		
		}
	);
}


//////////////// YES /////////////////////
function yes(yTitle, yText, p) {
	if (p==1 || p==2) {
		if (yText=='') { $('#yText').addClass('load'); } else { $('#yText').removeClass('load'); }
		$('#ground').css({height: $('body').height(), width: $('body').width() }).fadeIn();
		if (yTitle!='') { $('#yTitle').html(yTitle); }
		$('#yText').html(yText);
		$('#yes').center().fadeIn();
		if (p==2) { setTimeout(function() { $('#yes').fadeOut(); $('#ground').fadeOut(); }, 3000); }
	} else if (p==3) {
		$('#yes').fadeOut();
		$('#ground').fadeOut();
	}
}
//////////////////////////////////////////


///////////////// FRIENDS ////////////////
function friends(id, w) {
	yes('Друзья', '', 1);
	$.post(sefon+'/ajax/friends.php', { id: id, w: w },
		function(data){
			yes('', data, 1);
		});
	return false;
}
//////////////////////////////////////////


$.fn.preLoad = function() {
	if ($(this).hasClass("load")==false) {
		$(this).addClass('load');
	} else {
		$(this).removeClass('load');
	}
};

///////////////// EDIT COMMENT ////////////
function editCom(id, w) {
	
	var cm = $('#cm_'+id);
	if (w==5) { if(confirm('Вы уверены, что хотите удалить этот комментарий?')) { editCom(id, 4) } return false; }
	if (w==2 || w==3) { cm.find('textarea').preLoad(); } else { cm.preLoad(); }
	if (w==3) { var cmText = cm.find('textarea').val(); } else { var cmText = ''; }
	

	$.post(sefon+'/ajax/comment_edit.php', { id: id, w: w, text: cmText, iduser: iduser, ch: $('#ch_cm').val() },
		function(data){
			cm.html(data);
			if (w==1 || w==4) { $("textarea.elastic").elastic(); cm.preLoad(); }
			if (w==4) { $('#mes'+id).html(data); }
	});
	
	return false;
}
///////////////////////////////////////////


///////////////// EDIT STAR ///////////////
function editStar(id, w) {
	yes('Информация об исполнителе', '', 1);
	$.post(sefon+'/ajax/star_edit.php', { id: id, w: w },
		function(data){
			yes('', data, 1);
		});
	return false;
}
//////////////////////////////////////////

///////////////// LOVE STAR ///////////////
function love_star(id, w) {
		yes('Предпочтения в музыке', '', 1);
		$.post(sefon+'/ajax/love_hate.php', { id: id, w: w, ms: 's' },
		function(data){
			yes('', data, 2);
		});
	 return false;
}
//////////////////////////////////////////


function doLogin() {
	VK.Auth.login(
		null,
		VK.access.AUDIO// | VK.access.MATCHES | VK.access.QUESTIONS | VK.access.VIDEO | VK.access.FRIENDS | VK.access.WIKI | VK.access.PHOTOS
	);
	$('.vkLogin').hide();
}
