/**
 * JsHttpRequest: JavaScript "AJAX" data loader
 * Minimized version: see debug directory for the complete one.
 *
 * @license LGPL
 * @author Dmitry Koterov, http://en.dklab.ru/lib/JsHttpRequest/
 * @version 5.x $Id$
 */
function JsHttpRequest(){
var t=this;
t.onreadystatechange=null;
t.readyState=0;
t.responseText=null;
t.responseXML=null;
t.status=200;
t.statusText="OK";
t.responseJS=null;
t.caching=false;
t.loader=null;
t.session_name="PHPSESSID";
t._ldObj=null;
t._reqHeaders=[];
t._openArgs=null;
t._errors={inv_form_el:"Invalid FORM element detected: name=%, tag=%",must_be_single_el:"If used, <form> must be a single HTML element in the list.",js_invalid:"JavaScript code generated by backend is invalid!\n%",url_too_long:"Cannot use so long query with GET request (URL is larger than % bytes)",unk_loader:"Unknown loader: %",no_loaders:"No loaders registered at all, please check JsHttpRequest.LOADERS array",no_loader_matched:"Cannot find a loader which may process the request. Notices are:\n%"};
t.abort=function(){
with(this){
if(_ldObj&&_ldObj.abort){
_ldObj.abort();
}
_cleanup();
if(readyState==0){
return;
}
if(readyState==1&&!_ldObj){
readyState=0;
return;
}
_changeReadyState(4,true);
}
};
t.open=function(_2,_3,_4,_5,_6){
with(this){
if(_3.match(/^((\w+)\.)?(GET|POST)\s+(.*)/i)){
this.loader=RegExp.$2?RegExp.$2:null;
_2=RegExp.$3;
_3=RegExp.$4;
}
try{
if(document.location.search.match(new RegExp("[&?]"+session_name+"=([^&?]*)"))||document.cookie.match(new RegExp("(?:;|^)\\s*"+session_name+"=([^;]*)"))){
_3+=(_3.indexOf("?")>=0?"&":"?")+session_name+"="+this.escape(RegExp.$1);
}
}
catch(e){
}
_openArgs={method:(_2||"").toUpperCase(),url:_3,asyncFlag:_4,username:_5!=null?_5:"",password:_6!=null?_6:""};
_ldObj=null;
_changeReadyState(1,true);
return true;
}
};
t.send=function(_7){
if(!this.readyState){
return;
}
this._changeReadyState(1,true);
this._ldObj=null;
var _8=[];
var _9=[];
if(!this._hash2query(_7,null,_8,_9)){
return;
}
var _a=null;
if(this.caching&&!_9.length){
_a=this._openArgs.username+":"+this._openArgs.password+"@"+this._openArgs.url+"|"+_8+"#"+this._openArgs.method;
var _b=JsHttpRequest.CACHE[_a];
if(_b){
this._dataReady(_b[0],_b[1]);
return false;
}
}
var _c=(this.loader||"").toLowerCase();
if(_c&&!JsHttpRequest.LOADERS[_c]){
return this._error("unk_loader",_c);
}
var _d=[];
var _e=JsHttpRequest.LOADERS;
for(var _f in _e){
var ldr=_e[_f].loader;
if(!ldr){
continue;
}
if(_c&&_f!=_c){
continue;
}
var _11=new ldr(this);
JsHttpRequest.extend(_11,this._openArgs);
JsHttpRequest.extend(_11,{queryText:_8.join("&"),queryElem:_9,id:(new Date().getTime())+""+JsHttpRequest.COUNT++,hash:_a,span:null});
var _12=_11.load();
if(!_12){
this._ldObj=_11;
JsHttpRequest.PENDING[_11.id]=this;
return true;
}
if(!_c){
_d[_d.length]="- "+_f.toUpperCase()+": "+this._l(_12);
}else{
return this._error(_12);
}
}
return _f?this._error("no_loader_matched",_d.join("\n")):this._error("no_loaders");
};
t.getAllResponseHeaders=function(){
with(this){
return _ldObj&&_ldObj.getAllResponseHeaders?_ldObj.getAllResponseHeaders():[];
}
};
t.getResponseHeader=function(_13){
with(this){
return _ldObj&&_ldObj.getResponseHeader?_ldObj.getResponseHeader(_13):null;
}
};
t.setRequestHeader=function(_14,_15){
with(this){
_reqHeaders[_reqHeaders.length]=[_14,_15];
}
};
t._dataReady=function(_16,js){
with(this){
if(caching&&_ldObj){
JsHttpRequest.CACHE[_ldObj.hash]=[_16,js];
}
responseText=responseXML=_16;
responseJS=js;
if(js!==null){
status=200;
statusText="OK";
}else{
status=500;
statusText="Internal Server Error";
}
_changeReadyState(2);
_changeReadyState(3);
_changeReadyState(4);
_cleanup();
}
};
t._l=function(_18){
var i=0,p=0,msg=this._errors[_18[0]];
while((p=msg.indexOf("%",p))>=0){
var a=_18[++i]+"";
msg=msg.substring(0,p)+a+msg.substring(p+1,msg.length);
p+=1+a.length;
}
return msg;
};
t._error=function(msg){
msg=this._l(typeof (msg)=="string"?arguments:msg);
msg="JsHttpRequest: "+msg;
if(!window.Error){
throw msg;
}else{
if((new Error(1,"test")).description=="test"){
throw new Error(1,msg);
}else{
throw new Error(msg);
}
}
};
t._hash2query=function(_1e,_1f,_20,_21){
if(_1f==null){
_1f="";
}
if((""+typeof (_1e)).toLowerCase()=="object"){
var _22=false;
if(_1e&&_1e.parentNode&&_1e.parentNode.appendChild&&_1e.tagName&&_1e.tagName.toUpperCase()=="FORM"){
_1e={form:_1e};
}
for(var k in _1e){
var v=_1e[k];
if(v instanceof Function){
continue;
}
var _25=_1f?_1f+"["+this.escape(k)+"]":this.escape(k);
var _26=v&&v.parentNode&&v.parentNode.appendChild&&v.tagName;
if(_26){
var tn=v.tagName.toUpperCase();
if(tn=="FORM"){
_22=true;
}else{
if(tn=="INPUT"||tn=="TEXTAREA"||tn=="SELECT"){
}else{
return this._error("inv_form_el",(v.name||""),v.tagName);
}
}
_21[_21.length]={name:_25,e:v};
}else{
if(v instanceof Object){
this._hash2query(v,_25,_20,_21);
}else{
if(v===null){
continue;
}
if(v===true){
v=1;
}
if(v===false){
v="";
}
_20[_20.length]=_25+"="+this.escape(""+v);
}
}
if(_22&&_21.length>1){
return this._error("must_be_single_el");
}
}
}else{
_20[_20.length]=_1e;
}
return true;
};
t._cleanup=function(){
var _28=this._ldObj;
if(!_28){
return;
}
JsHttpRequest.PENDING[_28.id]=false;
var _29=_28.span;
if(!_29){
return;
}
_28.span=null;
var _2a=function(){
_29.parentNode.removeChild(_29);
};
JsHttpRequest.setTimeout(_2a,50);
};
t._changeReadyState=function(s,_2c){
with(this){
if(_2c){
status=statusText=responseJS=null;
responseText="";
}
readyState=s;
if(onreadystatechange){
onreadystatechange();
}
}
};
t.escape=function(s){
return escape(s).replace(new RegExp("\\+","g"),"%2B");
};
}
JsHttpRequest.COUNT=0;
JsHttpRequest.MAX_URL_LEN=2000;
JsHttpRequest.CACHE={};
JsHttpRequest.PENDING={};
JsHttpRequest.LOADERS={};
JsHttpRequest._dummy=function(){
};
JsHttpRequest.TIMEOUTS={s:window.setTimeout,c:window.clearTimeout};
JsHttpRequest.setTimeout=function(_2e,dt){
window.JsHttpRequest_tmp=JsHttpRequest.TIMEOUTS.s;
if(typeof (_2e)=="string"){
id=window.JsHttpRequest_tmp(_2e,dt);
}else{
var id=null;
var _31=function(){
_2e();
delete JsHttpRequest.TIMEOUTS[id];
};
id=window.JsHttpRequest_tmp(_31,dt);
JsHttpRequest.TIMEOUTS[id]=_31;
}
window.JsHttpRequest_tmp=null;
return id;
};
JsHttpRequest.clearTimeout=function(id){
window.JsHttpRequest_tmp=JsHttpRequest.TIMEOUTS.c;
delete JsHttpRequest.TIMEOUTS[id];
var r=window.JsHttpRequest_tmp(id);
window.JsHttpRequest_tmp=null;
return r;
};
JsHttpRequest.query=function(url,_35,_36,_37){
var req=new this();
req.caching=!_37;
req.onreadystatechange=function(){
if(req.readyState==4){
_36(req.responseJS,req.responseText);
}
};
req.open(null,url,true);
req.send(_35);
};
JsHttpRequest.dataReady=function(d){
var th=this.PENDING[d.id];
delete this.PENDING[d.id];
if(th){
th._dataReady(d.text,d.js);
}else{
if(th!==false){
throw "dataReady(): unknown pending id: "+d.id;
}
}
};
JsHttpRequest.extend=function(_3b,src){
for(var k in src){
_3b[k]=src[k];
}
};
JsHttpRequest.LOADERS.xml={loader:function(req){
JsHttpRequest.extend(req._errors,{xml_no:"Cannot use XMLHttpRequest or ActiveX loader: not supported",xml_no_diffdom:"Cannot use XMLHttpRequest to load data from different domain %",xml_no_headers:"Cannot use XMLHttpRequest loader or ActiveX loader, POST method: headers setting is not supported, needed to work with encodings correctly",xml_no_form_upl:"Cannot use XMLHttpRequest loader: direct form elements using and uploading are not implemented"});
this.load=function(){
if(this.queryElem.length){
return ["xml_no_form_upl"];
}
if(this.url.match(new RegExp("^([a-z]+://[^\\/]+)(.*)","i"))){
if(RegExp.$1.toLowerCase()!=document.location.protocol+"//"+document.location.hostname.toLowerCase()){
return ["xml_no_diffdom",RegExp.$1];
}
}
var xr=null;
if(window.XMLHttpRequest){
try{
xr=new XMLHttpRequest();
}
catch(e){
}
}else{
if(window.ActiveXObject){
try{
xr=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
}
if(!xr){
try{
xr=new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
}
}
}
}
if(!xr){
return ["xml_no"];
}
var _40=window.ActiveXObject||xr.setRequestHeader;
if(!this.method){
this.method=_40&&this.queryText.length?"POST":"GET";
}
if(this.method=="GET"){
if(this.queryText){
this.url+=(this.url.indexOf("?")>=0?"&":"?")+this.queryText;
}
this.queryText="";
if(this.url.length>JsHttpRequest.MAX_URL_LEN){
return ["url_too_long",JsHttpRequest.MAX_URL_LEN];
}
}else{
if(this.method=="POST"&&!_40){
return ["xml_no_headers"];
}
}
this.url+=(this.url.indexOf("?")>=0?"&":"?")+"JsHttpRequest="+(req.caching?"0":this.id)+"-xml";
var id=this.id;
xr.onreadystatechange=function(){
if(xr.readyState!=4){
return;
}
xr.onreadystatechange=JsHttpRequest._dummy;
req.status=null;
try{
req.status=xr.status;
req.responseText=xr.responseText;
}
catch(e){
}
if(!req.status){
return;
}
try{
eval("JsHttpRequest._tmp = function(id) { var d = "+req.responseText+"; d.id = id; JsHttpRequest.dataReady(d); }");
}
catch(e){
return req._error("js_invalid",req.responseText);
}
JsHttpRequest._tmp(id);
JsHttpRequest._tmp=null;
};
xr.open(this.method,this.url,true,this.username,this.password);
if(_40){
for(var i=0;i<req._reqHeaders.length;i++){
xr.setRequestHeader(req._reqHeaders[i][0],req._reqHeaders[i][1]);
}
xr.setRequestHeader("Content-Type","application/octet-stream");
}
xr.send(this.queryText);
this.span=null;
this.xr=xr;
return null;
};
this.getAllResponseHeaders=function(){
return this.xr.getAllResponseHeaders();
};
this.getResponseHeader=function(_43){
return this.xr.getResponseHeader(_43);
};
this.abort=function(){
this.xr.abort();
this.xr=null;
};
}};
JsHttpRequest.LOADERS.script={loader:function(req){
JsHttpRequest.extend(req._errors,{script_only_get:"Cannot use SCRIPT loader: it supports only GET method",script_no_form:"Cannot use SCRIPT loader: direct form elements using and uploading are not implemented"});
this.load=function(){
if(this.queryText){
this.url+=(this.url.indexOf("?")>=0?"&":"?")+this.queryText;
}
this.url+=(this.url.indexOf("?")>=0?"&":"?")+"JsHttpRequest="+this.id+"-"+"script";
this.queryText="";
if(!this.method){
this.method="GET";
}
if(this.method!=="GET"){
return ["script_only_get"];
}
if(this.queryElem.length){
return ["script_no_form"];
}
if(this.url.length>JsHttpRequest.MAX_URL_LEN){
return ["url_too_long",JsHttpRequest.MAX_URL_LEN];
}
var th=this,d=document,s=null,b=d.body;
if(!window.opera){
this.span=s=d.createElement("SCRIPT");
var _49=function(){
s.language="JavaScript";
if(s.setAttribute){
s.setAttribute("src",th.url);
}else{
s.src=th.url;
}
b.insertBefore(s,b.lastChild);
};
}else{
this.span=s=d.createElement("SPAN");
s.style.display="none";
b.insertBefore(s,b.lastChild);
s.innerHTML="Workaround for IE.<s"+"cript></"+"script>";
var _49=function(){
s=s.getElementsByTagName("SCRIPT")[0];
s.language="JavaScript";
if(s.setAttribute){
s.setAttribute("src",th.url);
}else{
s.src=th.url;
}
};
}
JsHttpRequest.setTimeout(_49,10);
return null;
};
}};
JsHttpRequest.LOADERS.form={loader:function(req){
JsHttpRequest.extend(req._errors,{form_el_not_belong:"Element \"%\" does not belong to any form!",form_el_belong_diff:"Element \"%\" belongs to a different form. All elements must belong to the same form!",form_el_inv_enctype:"Attribute \"enctype\" of the form must be \"%\" (for IE), \"%\" given."});
this.load=function(){
var th=this;
if(!th.method){
th.method="POST";
}
th.url+=(th.url.indexOf("?")>=0?"&":"?")+"JsHttpRequest="+th.id+"-"+"form";
if(th.method=="GET"){
if(th.queryText){
th.url+=(th.url.indexOf("?")>=0?"&":"?")+th.queryText;
}
if(th.url.length>JsHttpRequest.MAX_URL_LEN){
return ["url_too_long",JsHttpRequest.MAX_URL_LEN];
}
var p=th.url.split("?",2);
th.url=p[0];
th.queryText=p[1]||"";
}
var _4d=null;
var _4e=false;
if(th.queryElem.length){
if(th.queryElem[0].e.tagName.toUpperCase()=="FORM"){
_4d=th.queryElem[0].e;
_4e=true;
th.queryElem=[];
}else{
_4d=th.queryElem[0].e.form;
for(var i=0;i<th.queryElem.length;i++){
var e=th.queryElem[i].e;
if(!e.form){
return ["form_el_not_belong",e.name];
}
if(e.form!=_4d){
return ["form_el_belong_diff",e.name];
}
}
}
if(th.method=="POST"){
var _51="multipart/form-data";
var _52=(_4d.attributes.encType&&_4d.attributes.encType.nodeValue)||(_4d.attributes.enctype&&_4d.attributes.enctype.value)||_4d.enctype;
if(_52!=_51){
return ["form_el_inv_enctype",_51,_52];
}
}
}
var d=_4d&&(_4d.ownerDocument||_4d.document)||document;
var _54="jshr_i_"+th.id;
var s=th.span=d.createElement("DIV");
s.style.position="absolute";
s.style.display="none";
s.style.visibility="hidden";
s.innerHTML=(_4d?"":"<form"+(th.method=="POST"?" enctype=\"multipart/form-data\" method=\"post\"":"")+"></form>")+"<iframe name=\""+_54+"\" id=\""+_54+"\" style=\"width:0px; height:0px; overflow:hidden; border:none\"></iframe>";
if(!_4d){
_4d=th.span.firstChild;
}
d.body.insertBefore(s,d.body.lastChild);
var _56=function(e,_58){
var sv=[];
var _5a=e;
if(e.mergeAttributes){
var _5a=d.createElement("form");
_5a.mergeAttributes(e,false);
}
for(var i=0;i<_58.length;i++){
var k=_58[i][0],v=_58[i][1];
sv[sv.length]=[k,_5a.getAttribute(k)];
_5a.setAttribute(k,v);
}
if(e.mergeAttributes){
e.mergeAttributes(_5a,false);
}
return sv;
};
var _5e=function(){
top.JsHttpRequestGlobal=JsHttpRequest;
var _5f=[];
if(!_4e){
for(var i=0,n=_4d.elements.length;i<n;i++){
_5f[i]=_4d.elements[i].name;
_4d.elements[i].name="";
}
}
var qt=th.queryText.split("&");
for(var i=qt.length-1;i>=0;i--){
var _63=qt[i].split("=",2);
var e=d.createElement("INPUT");
e.type="hidden";
e.name=unescape(_63[0]);
e.value=_63[1]!=null?unescape(_63[1]):"";
_4d.appendChild(e);
}
for(var i=0;i<th.queryElem.length;i++){
th.queryElem[i].e.name=th.queryElem[i].name;
}
var sv=_56(_4d,[["action",th.url],["method",th.method],["onsubmit",null],["target",_54]]);
_4d.submit();
_56(_4d,sv);
for(var i=0;i<qt.length;i++){
_4d.lastChild.parentNode.removeChild(_4d.lastChild);
}
if(!_4e){
for(var i=0,n=_4d.elements.length;i<n;i++){
_4d.elements[i].name=_5f[i];
}
}
};
JsHttpRequest.setTimeout(_5e,100);
return null;
};
}};

/**
 * 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 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);/*
wwww.tigir.com - 06.07.2006

Source: http://www.tigir.com/js/opacity.js

Библиотека opacity.js к статье "CSS прозрачность (css opacity, javascript opacity)" - http://www.tigir.com/opacity.htm

setElementOpacity - установка прозрачности
getOpacityProperty - проверка, есть ли возможность менять прозрачность
fadeOpacity - плавное изменение прозрачности
*/

/* Функция кроссбраузерной установки прозрачности

Пример: setElementOpacity(document.body, 0.5); //сделать документ прозрачным на половину
*/
function setElementOpacity(oElem, nOpacity)
{
	var p = getOpacityProperty();
	(setElementOpacity = p=="filter"?new Function('oElem', 'nOpacity', 'nOpacity *= 100;	var oAlpha = oElem.filters["DXImageTransform.Microsoft.alpha"] || oElem.filters.alpha;	if (oAlpha) oAlpha.opacity = nOpacity; else oElem.style.filter += "progid:DXImageTransform.Microsoft.Alpha(opacity="+nOpacity+")";'):p?new Function('oElem', 'nOpacity', 'oElem.style.'+p+' = nOpacity;'):new Function)(oElem, nOpacity);
}

// Функция getOpacityProperty() возвращает свойство которое используется для смены прозрачности или undefined, и может использоваться для проверки возможности изменения прозрачности
function getOpacityProperty()
{
	var p;
	if (typeof document.body.style.opacity == 'string') p = 'opacity';
	else if (typeof document.body.style.MozOpacity == 'string') p =  'MozOpacity';
	else if (typeof document.body.style.KhtmlOpacity == 'string') p =  'KhtmlOpacity';
	else if (document.body.filters && navigator.appVersion.match(/MSIE ([\d.]+);/)[1]>=5.5) p =  'filter';
	
	return (getOpacityProperty = new Function("return '"+p+"';"))();
}

/* Функции для плавного изменения прозрачности:

1) fadeOpacity.addRule('opacityRule1', 1, 0.5, 30); //вначале создаем правило, задаем имя правила, начальную прозрачность и конечную, необязательный параметр задержки, влийяющий на скорость смены прозрачности
2) fadeOpacity('elemID', 'opacityRule1'); // выполнить плавную смену прозрачности элемента с id равным elemID, по правилу opacityRule1
3) fadeOpacity.back('elemID'); //вернуться в исходное сотояние прозрачности
*/
function fadeOpacity(sElemId, sRuleName, bBackward)
{
	var elem = document.getElementById(sElemId);
	if (!elem || !getOpacityProperty() || !fadeOpacity.aRules[sRuleName]) return;
	
	var rule = fadeOpacity.aRules[sRuleName];
	var nOpacity = rule.nStartOpacity;
	
	if (fadeOpacity.aProc[sElemId]) {clearInterval(fadeOpacity.aProc[sElemId].tId); nOpacity = fadeOpacity.aProc[sElemId].nOpacity;}
	if ((nOpacity==rule.nStartOpacity && bBackward) || (nOpacity==rule.nFinishOpacity && !bBackward)) return;

	fadeOpacity.aProc[sElemId] = {'nOpacity':nOpacity, 'tId':setInterval('fadeOpacity.run("'+sElemId+'")', fadeOpacity.aRules[sRuleName].nDalay), 'sRuleName':sRuleName, 'bBackward':Boolean(bBackward)};
}

fadeOpacity.addRule = function(sRuleName, nStartOpacity, nFinishOpacity, nDalay){fadeOpacity.aRules[sRuleName]={'nStartOpacity':nStartOpacity, 'nFinishOpacity':nFinishOpacity, 'nDalay':(nDalay || 30),'nDSign':(nFinishOpacity-nStartOpacity > 0?1:-1)};};

fadeOpacity.back = function(sElemId){fadeOpacity(sElemId,fadeOpacity.aProc[sElemId].sRuleName,true);};

fadeOpacity.run = function(sElemId)
{
	var proc = fadeOpacity.aProc[sElemId];
	var rule = fadeOpacity.aRules[proc.sRuleName];
	
	proc.nOpacity = Math.round(( proc.nOpacity + .1*rule.nDSign*(proc.bBackward?-1:1) )*10)/10;
	setElementOpacity(document.getElementById(sElemId), proc.nOpacity);
	
	if (proc.nOpacity==rule.nStartOpacity || proc.nOpacity==rule.nFinishOpacity) clearInterval(fadeOpacity.aProc[sElemId].tId);
}
fadeOpacity.aProc = {};
fadeOpacity.aRules = {};// функции которые исполняем только после полной загрузки сайта
$(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
//Step Carousel Viewer: By Dynamic Drive, at http://www.dynamicdrive.com
//** Created: March 19th, 08'
//** Aug 16th, 08'- Updated to v 1.4:
	//1) Adds ability to set speed/duration of panel animation (in milliseconds)
	//2) Adds persistence support, so the last viewed panel is recalled when viewer returns within same browser session
	//3) Adds ability to specify whether panels should stop at the very last and first panel, or wrap around and start all over again
	//4) Adds option to specify two navigational image links positioned to the left and right of the Carousel Viewer to move the panels back and forth

//** Aug 27th, 08'- Nav buttons (if enabled) also repositions themselves now if window is resized

//** Sept 23rd, 08'- Updated to v 1.6:
	//1) Carousel now stops at the very last visible panel, instead of the last panel itself. In other words, no more white space at the end.
	//2) Adds ability for Carousel to auto rotate dictated by the new parameter: autostep: {enable:true, moveby:1, pause:3000}
	//2i) During Auto Rotate, Carousel pauses onMouseover, resumes onMouseout. Clicking Carousel halts auto rotate.

//** Oct 22nd, 08'- Updated to v 1.6.1, which fixes functions stepBy() and stepTo() not stopping auto stepping of Carousel when called.

var stepcarousel={
	ajaxloadingmsg: '<div style="margin: 1em; font-weight: bold"><img src="ajaxloadr.gif" style="vertical-align: middle" /> Fetching Content. Please wait...</div>', //customize HTML to show while fetching Ajax content
	defaultbuttonsfade: 0.4, //Fade degree for disabled nav buttons (0=completely transparent, 1=completely opaque)
	configholder: {},

	getCSSValue:function(val){ //Returns either 0 (if val contains 'auto') or val as an integer
		return (val=="auto")? 0 : parseInt(val)
	},

	getremotepanels:function($, config){ //function to fetch external page containing the panel DIVs
		config.$belt.html(this.ajaxloadingmsg)
		$.ajax({
			url: config.contenttype[1], //path to external content
			async: true,
			error:function(ajaxrequest){
				config.$belt.html('Error fetching content.<br />Server Response: '+ajaxrequest.responseText)
			},
			success:function(content){
				config.$belt.html(content)
				config.$panels=config.$gallery.find('.'+config.panelclass)
				stepcarousel.alignpanels($, config)
			}
		})
	},

	getoffset:function(what, offsettype){
		return (what.offsetParent)? what[offsettype]+this.getoffset(what.offsetParent, offsettype) : what[offsettype]
	},

	getCookie:function(Name){ 
		var re=new RegExp(Name+"=[^;]+", "i"); //construct RE to search for target name/value pair
		if (document.cookie.match(re)) //if cookie found
			return document.cookie.match(re)[0].split("=")[1] //return its value
		return null
	},

	setCookie:function(name, value){
		document.cookie = name+"="+value
	},

	fadebuttons:function(config, currentpanel){
		config.$leftnavbutton.fadeTo('fast', currentpanel==0? this.defaultbuttonsfade : 1)
		config.$rightnavbutton.fadeTo('fast', currentpanel==config.lastvisiblepanel? this.defaultbuttonsfade : 1)
	},

	addnavbuttons:function(config, currentpanel){
		config.$leftnavbutton=$('<img alt="влево" onmouseover="this.src=\'http://www.sefon.ru/img/left.png\';" onmouseout="this.src=\''+config.defaultbuttons.leftnav[0]+'\';" src="'+config.defaultbuttons.leftnav[0]+'">').css({zIndex:50, position:'absolute', left:config.offsets.left+config.defaultbuttons.leftnav[1]+'px', top:config.offsets.top+config.defaultbuttons.leftnav[2]+'px', cursor:'hand', cursor:'pointer'}).attr({title:'Предыдущие '+config.defaultbuttons.moveby+' фотографий'}).appendTo('body')
		config.$rightnavbutton=$('<img alt="вправо" onmouseover="this.src=\'http://www.sefon.ru/img/right.png\';" onmouseout="this.src=\''+config.defaultbuttons.rightnav[0]+'\';" src="'+config.defaultbuttons.rightnav[0]+'">').css({zIndex:50, position:'absolute', left:config.offsets.left+config.$gallery.get(0).offsetWidth+config.defaultbuttons.rightnav[1]+'px', top:config.offsets.top+config.defaultbuttons.rightnav[2]+'px', cursor:'hand', cursor:'pointer'}).attr({title:'Следующие '+config.defaultbuttons.moveby+' фотографий'}).appendTo('body')
		config.$leftnavbutton.bind('click', function(){ //assign nav button event handlers
			stepcarousel.stepBy(config.galleryid, -config.defaultbuttons.moveby)
		})
		config.$rightnavbutton.bind('click', function(){ //assign nav button event handlers
			stepcarousel.stepBy(config.galleryid, config.defaultbuttons.moveby)
		})
		if (config.panelbehavior.wraparound==false){ //if carousel viewer should stop at first or last panel (instead of wrap back or forth)
			this.fadebuttons(config, currentpanel)
		}
		return config.$leftnavbutton.add(config.$rightnavbutton)
	},

	stopautostep:function(config){
		clearTimeout(config.steptimer)
		clearTimeout(config.resumeautostep)
	},

	alignpanels:function($, config){
		var paneloffset=0
		config.paneloffsets=[paneloffset] //array to store upper left offset of each panel (1st element=0)
		config.panelwidths=[] //array to store widths of each panel
		config.$panels.each(function(index){ //loop through panels
			var $currentpanel=$(this)
			$currentpanel.css({float: 'none', position: 'absolute', left: paneloffset+'px'}) //position panel
			$currentpanel.bind('click', function(e){return config.onpanelclick(e.target)}) //bind onpanelclick() to onclick event
			paneloffset+=stepcarousel.getCSSValue($currentpanel.css('marginRight')) + parseInt($currentpanel.get(0).offsetWidth || $currentpanel.css('width')) //calculate next panel offset
			config.paneloffsets.push(paneloffset) //remember this offset
			config.panelwidths.push(paneloffset-config.paneloffsets[config.paneloffsets.length-2]) //remember panel width
		})
		config.paneloffsets.pop() //delete last offset (redundant)
		var addpanelwidths=0
		var lastpanelindex=config.$panels.length-1
		config.lastvisiblepanel=lastpanelindex
		for (var i=config.$panels.length-1; i>=0; i--){
			addpanelwidths+=(i==lastpanelindex? config.panelwidths[lastpanelindex] : config.paneloffsets[i+1]-config.paneloffsets[i])
			if (config.gallerywidth>addpanelwidths){
				config.lastvisiblepanel=i //calculate index of panel that when in 1st position reveals the very last panel all at once based on gallery width
			}
		}
		config.$belt.css({width: paneloffset+'px'}) //Set Belt DIV to total panels' widths
		config.currentpanel=(config.panelbehavior.persist)? parseInt(this.getCookie(window[config.galleryid+"persist"])) : 0 //determine 1st panel to show by default
		config.currentpanel=(typeof config.currentpanel=="number" && config.currentpanel<config.$panels.length)? config.currentpanel : 0
		if (config.currentpanel!=0){
			var endpoint=config.paneloffsets[config.currentpanel]+(config.currentpanel==0? 0 : config.beltoffset)
			config.$belt.css({left: -endpoint+'px'})
		}
		if (config.defaultbuttons.enable==true){ //if enable default back/forth nav buttons
			var $navbuttons=this.addnavbuttons(config, config.currentpanel)
			$(window).bind("load resize", function(){ //refresh position of nav buttons when page loads/resizes, in case offsets weren't available document.oncontentload
				config.offsets={left:stepcarousel.getoffset(config.$gallery.get(0), "offsetLeft"), top:stepcarousel.getoffset(config.$gallery.get(0), "offsetTop")}
				config.$leftnavbutton.css({left:config.offsets.left+config.defaultbuttons.leftnav[1]+'px', top:config.offsets.top+config.defaultbuttons.leftnav[2]+'px'})
				config.$rightnavbutton.css({left:config.offsets.left+config.$gallery.get(0).offsetWidth+config.defaultbuttons.rightnav[1]+'px', top:config.offsets.top+config.defaultbuttons.rightnav[2]+'px'})
			})
		}
		if (config.autostep && config.autostep.enable){ //enable auto stepping of Carousel?		
			var $carouselparts=config.$gallery.add(typeof $navbuttons!="undefined"? $navbuttons : null)
			$carouselparts.bind('click', function(){
				stepcarousel.stopautostep(config)
				config.autostep.status="stopped"
			})
			$carouselparts.hover(function(){ //onMouseover
				stepcarousel.stopautostep(config)
				config.autostep.hoverstate="over"
			}, function(){ //onMouseout
				if (config.steptimer && config.autostep.hoverstate=="over" && config.autostep.status!="stopped"){
					config.resumeautostep=setTimeout(function(){
						stepcarousel.autorotate(config.galleryid)
						config.autostep.hoverstate="out"
					}, 500)
				}
			})
			config.steptimer=setTimeout(function(){stepcarousel.autorotate(config.galleryid)}, config.autostep.pause) //automatically rotate Carousel Viewer
		} //end enable auto stepping check
		this.statusreport(config.galleryid)
		config.oninit()
		config.onslideaction(this)
	},

	stepTo:function(galleryid, pindex){ /*User entered pindex starts at 1 for intuitiveness. Internally pindex still starts at 0 */
		var config=stepcarousel.configholder[galleryid]
		if (typeof config=="undefined"){
			alert("There's an error with your set up of Carousel Viewer \""+galleryid+ "\"!")
			return
		}
		stepcarousel.stopautostep(config)
		var pindex=Math.min(pindex-1, config.paneloffsets.length-1)
		var endpoint=config.paneloffsets[pindex]+(pindex==0? 0 : config.beltoffset)
		if (config.panelbehavior.wraparound==false && config.defaultbuttons.enable==true){ //if carousel viewer should stop at first or last panel (instead of wrap back or forth)
			this.fadebuttons(config, pindex)
		}
		config.$belt.animate({left: -endpoint+'px'}, config.panelbehavior.speed, function(){config.onslideaction(this)})
		config.currentpanel=pindex
		this.statusreport(galleryid)
	},

	stepBy:function(galleryid, steps){ //isauto if defined indicates stepBy() is being called automatically
		var config=stepcarousel.configholder[galleryid]
		if (typeof config=="undefined"){
			alert("There's an error with your set up of Carousel Viewer \""+galleryid+ "\"!")
			return
		}
		stepcarousel.stopautostep(config)
		var direction=(steps>0)? 'forward' : 'back' //If "steps" is negative, that means backwards
		var pindex=config.currentpanel+steps //index of panel to stop at
		if (config.panelbehavior.wraparound==false){ //if carousel viewer should stop at first or last panel (instead of wrap back or forth)
			pindex=(direction=="back" && pindex<=0)? 0 : (direction=="forward")? Math.min(pindex, config.lastvisiblepanel) : pindex
			if (config.defaultbuttons.enable==true){ //if default nav buttons are enabled, fade them in and out depending on if at start or end of carousel
				stepcarousel.fadebuttons(config, pindex)
			}	
		}
		else{ //else, for normal stepBy behavior
			if (pindex>config.lastvisiblepanel && direction=="forward"){
				//if destination pindex is greater than last visible panel, yet we're currently not at the end of the carousel yet
				pindex=(config.currentpanel<config.lastvisiblepanel)? config.lastvisiblepanel : 0
			}
			else if (pindex<0 && direction=="back"){
				//if destination pindex is less than 0, yet we're currently not at the beginning of the carousel yet
				pindex=(config.currentpanel>0)? 0 : config.lastvisiblepanel /*wrap around left*/
			}
		}
		if (galleryid=='prev_foto') { var left_otstup = 0; var right_otstup = 0; } else { var left_otstup = -30; var right_otstup = 100; } /// IT'S MY OPTIONS задаем отсуп при прокрутке к началу или концу
		var endpoint=config.paneloffsets[pindex]+(pindex==0? 0 : config.beltoffset) //left distance for Belt DIV to travel to
		if (pindex==0 && direction=='forward' || config.currentpanel==0 && direction=='back' && config.panelbehavior.wraparound==true){ //decide whether to apply "push pull" effect
			config.$belt.animate({left: -config.paneloffsets[config.currentpanel]-(direction=='forward'? right_otstup : left_otstup)+'px'}, 'normal', function(){
				config.$belt.animate({left: -endpoint+'px'}, config.panelbehavior.speed, function(){config.onslideaction(this)})
			})
		}
		else
			config.$belt.animate({left: -endpoint+'px'}, config.panelbehavior.speed, function(){config.onslideaction(this)})
		config.currentpanel=pindex
		this.statusreport(galleryid)
	},

	autorotate:function(galleryid){
		var config=stepcarousel.configholder[galleryid]
		if (config.$gallery.attr('_ismouseover')!="yes"){
			this.stepBy(galleryid, config.autostep.moveby)
		}
		config.steptimer=setTimeout(function(){stepcarousel.autorotate(galleryid)}, config.autostep.pause)
	},

	statusreport:function(galleryid){
		var config=stepcarousel.configholder[galleryid]
		var startpoint=config.currentpanel //index of first visible panel 
		var visiblewidth=0
		for (var endpoint=startpoint; endpoint<config.paneloffsets.length; endpoint++){ //index (endpoint) of last visible panel
			visiblewidth+=config.panelwidths[endpoint]
			if (visiblewidth>config.gallerywidth){
				break
			}
		}
		startpoint+=1 //format startpoint for user friendiness
		endpoint=(endpoint+1==startpoint)? startpoint : endpoint //If only one image visible on the screen and partially hidden, set endpoint to startpoint
		var valuearray=[startpoint, endpoint, config.panelwidths.length]
		for (var i=0; i<config.statusvars.length; i++){
			window[config.statusvars[i]]=valuearray[i] //Define variable (with user specified name) and set to one of the status values
			config.$statusobjs[i].text(valuearray[i]+" ") //Populate element on page with ID="user specified name" with one of the status values
		}
	},

	setup:function(config){
		//Disable Step Gallery scrollbars ASAP dynamically (enabled for sake of users with JS disabled)
		document.write('<style type="text/css">\n#'+config.galleryid+'{overflow: hidden;}\n</style>')
		jQuery(document).ready(function($){
			config.$gallery=$('#'+config.galleryid)
			config.gallerywidth=config.$gallery.width()
			config.offsets={left:stepcarousel.getoffset(config.$gallery.get(0), "offsetLeft"), top:stepcarousel.getoffset(config.$gallery.get(0), "offsetTop")}
			config.$belt=config.$gallery.find('.'+config.beltclass) //Find Belt DIV that contains all the panels
			config.$panels=config.$gallery.find('.'+config.panelclass) //Find Panel DIVs that each contain a slide
			config.panelbehavior.wraparound=(config.autostep && config.autostep.enable)? true : config.panelbehavior.wraparound //if auto step enabled, set "wraparound" to true
			config.onpanelclick=(typeof config.onpanelclick=="undefined")? function(target){} : config.onpanelclick //attach custom "onpanelclick" event handler
			config.onslideaction=(typeof config.onslide=="undefined")? function(){} : function(beltobj){$(beltobj).stop(); config.onslide()} //attach custom "onslide" event handler
			config.oninit=(typeof config.oninit=="undefined")? function(){} : config.oninit //attach custom "oninit" event handler
			config.beltoffset=stepcarousel.getCSSValue(config.$belt.css('marginLeft')) //Find length of Belt DIV's left margin
			config.statusvars=config.statusvars || []  //get variable names that will hold "start", "end", and "total" slides info
			config.$statusobjs=[$('#'+config.statusvars[0]), $('#'+config.statusvars[1]), $('#'+config.statusvars[2])]
			config.currentpanel=0
			stepcarousel.configholder[config.galleryid]=config //store config parameter as a variable
			if (config.contenttype[0]=="ajax" && typeof config.contenttype[1]!="undefined") //fetch ajax content?
				stepcarousel.getremotepanels($, config)
			else
				stepcarousel.alignpanels($, config) //align panels and initialize gallery
		}) //end document.ready
		jQuery(window).bind('unload', function(){ //clean up
			if (config.panelbehavior.persist){
				stepcarousel.setCookie(window[config.galleryid+"persist"], config.currentpanel)
			}
			jQuery.each(config, function(ai, oi){
				oi=null
			})
			config=null
		})
	}
}

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,id) {

	g('votes_status').innerHTML = 'секунду...';

	
	var req = new JsHttpRequest();
	req.onreadystatechange = function() {

		if (req.readyState == 4) {
			g('votes_status').innerHTML = req.responseJS.q;
			if (req.responseJS.rate>0) {
				g('fotos_rate').innerHTML = req.responseJS.rate;
				vote_mouse(0,req.responseJS.rate2);
				g('fotos_vote').innerHTML = req.responseJS.votes;
			}
			for (var i = 1; i <= 5; i++) {
					g('vote'+i).onmouseover = '';
					g('vote'+i).onclick = '';
			}
			g('votes').onmouseout = '';
		}
		
	}
    req.open(null, sefon+'/ajax/vote_foto.php', true);
    req.send( { v: v, id: id } );		

}
/////////////////////////

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

	g('votes_status').innerHTML = 'секунду...';
	
	var req = new JsHttpRequest();
	req.onreadystatechange = function() {

		if (req.readyState == 4) {
			g('votes_status').innerHTML = req.responseJS.q;
			if (req.responseJS.rate>0) {
				g('fotos_rate').innerHTML = req.responseJS.rate;
				vote_mouse(0,req.responseJS.rate2);
				g('fotos_vote').innerHTML = req.responseJS.votes;
			}
			for (var i = 1; i <= 5; i++) {
					g('vote'+i).onmouseover = '';
					g('vote'+i).onclick = '';
			}
			g('votes').onmouseout = '';
		}
		
	}
    req.open(null, sefon+'/ajax/vote_user_foto.php', true);
    req.send( { v: v, id: id } );		

}
/////////////////////////




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;
}

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