var my_host = base_url.replace(base_url_only_path,'');


var request = false;
try {
  request = new XMLHttpRequest();
} catch (trymicrosoft) {
  try {
    request = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (othermicrosoft) {
    try {
      request = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (failed) {
      request = false;
    }
  }
}

if (!request)
  alert("Error initializing XMLHttpRequest!");

//командная функция
function command_function(command,parameter,evented,objected)
{
var resultat = null;
var parameter = parameter.split(',');
if (evented != ""){var eventName = evented;};
if (objected != ""){var thisObject = objected;};

	switch (command)
	{
		//вывод флешки (путь до флешки,id той фигни куда записывать её,ширина,высота)
		case 'print_flash':
			resultat = print_flash(parameter[0],parameter[1],parameter[2],parameter[3],parameter[4],parameter[5]);
			break;
		//запись cookie(название,значение);
		case 'setCookie':
			resultat = setCookie(parameter[0],parameter[1],my_host,"/");
			break;
		//вывод значения cookie по названию(название)
		case 'getCookie':
			resultat = getCookie(parameter[0]);
			break;
		//удаляет cookie по названию(название)
		case 'deleteCookie':
			resultat = deleteCookie(parameter[0],'','');
			break;
		case 'ajax_post':
			resultat = ajax_post(parameter[0],parameter[1],parameter[2],parameter[3]);
			break;
		//выводит вопрос и в случае утверждения переводит на указанную страницу(char text,char ссылка)
		case 'confirm':
			resultat = confirm_location(parameter[0],parameter[1]);
			break;
        case 'pop_up':
			resultat = popup(parameter[0],parameter[1],parameter[2],parameter[3],parameter[4],parameter[5],parameter[6],parameter[7],parameter[8]);
			break;
		default:
			resultat = false;
			break;
   	};
return resultat;
};

function confirm_location(text,link){
	if(confirm(text)){
		window.location.href = link;
		return true;
	}else{
		return false;
	};
};



function popup(url,window_name,window_width,window_height,position_x,position_y,scroll,resize,menu)
{
	if (position_x == undefined){
		position_x = '0';
	};
	if (position_y == undefined){
		position_y = '0';
	};
	if (scroll == undefined){
		scroll = 'no';
	};
	if (resize == undefined){
		resize = 'no';
	};
	if (menu == undefined){
		menu = 'no';
	};
parseFloat(window_height);
parseFloat(window_width);

	if (position_x == '0' && position_y == '0'){
		if(navigator.appName == 'Microsoft Internet Explorer')	{
			position_y = window.document.body.clientHeight;
			position_x = window.document.body.clientWidth;
		}
		else{
			position_y = window.innerHeight;
			position_x = window.innerWidth;
		};
        parseFloat(position_y);
        parseFloat(position_x);

		position_y=(position_y-window_height)/2;
		position_x=(position_x-window_width)/2;
	};

	if (position_x != '0' || position_y == '0'){
		if(navigator.appName == 'Microsoft Internet Explorer'){
			position_y = window.document.body.clientHeight;
		}
		else{
			position_y = window.innerHeight;
		};
        parseFloat(position_y);
		position_y=(position_y-window_height)/2;
	};

	if (position_x == '0' || position_y != '0')
	{
		if(navigator.appName == 'Microsoft Internet Explorer'){
			position_x = window.document.body.clientWidth;
		}
		else{
			position_x = window.innerWidth;
		};
        parseFloat(position_x);
		position_x=(position_x-window_width)/2;
	};

window_name = window.open(base_url+url,window_name,"height="+window_height+" ,width="+window_width+",status=no,location=no,toolbar="+menu+",directories=no,menubar=no,screenY="+position_y+",screenX="+position_x+",top="+position_y+",left="+position_x+"titlebar=no,alwaysRaised=1,scrollbars="+scroll+",resizable="+resize+"");
window_name.focus();
return window_name;
};



var Selected_back_id = 0;

function selected(name,id,action)
{
	if (document.getElementById(name+Selected_back_id))
	{
		document.getElementById(name+Selected_back_id).style.background= 'white';
	};
	switch (action){
		case "forward":
			if (Selected_back_id >= 1){
				--Selected_back_id;
			}else{
				Selected_back_id = 4;
			};
			break;
		case "back":
			++Selected_back_id;
			if (!document.getElementById(name+Selected_back_id)) Selected_back_id = 1;
			break;
		case "submit":
			window.location.href = document.getElementById('club_src'+Selected_back_id).href;
			break;
		};

	if (document.getElementById(name+Selected_back_id))
	{
		document.getElementById(name+Selected_back_id).style.background = '#CCFBC8';
	};
};

var triggers = '1';

function print_flash(path,id,width,height,mytext,myurl)
{
	var so = new SWFObject(path, "to", width, height, "9", "FFFFFF");
	so.addVariable("mytext", mytext);
	so.addVariable("myurl", myurl);
	so.addVariable("baseurl", base_url);
	so.write(id);
	return false
};


var caution = false;

function setCookie(name, value, expires, path, domain, secure) {
        var curCookie = name + "=" + escape(value) +
                ((expires) ? "; expires=" + expires.toGMTString() : "") +
                ((path) ? "; path=" + path : "") +
                ((domain) ? "; domain=" + domain : "") +
                ((secure) ? "; secure" : "")
        if (!caution || (name + "=" + escape(value)).length <= 4000)
                document.cookie = curCookie
        else
                if (confirm("Cookie превышает 4KB и будет вырезан !"))
                        document.cookie = curCookie
}


function getCookie(name) {
        var prefix = name + "="
        var cookieStartIndex = document.cookie.indexOf(prefix)
        if (cookieStartIndex == -1)
                return null
        var cookieEndIndex = document.cookie.indexOf(";", cookieStartIndex + prefix.length)
        if (cookieEndIndex == -1)
                cookieEndIndex = document.cookie.length
        return unescape(document.cookie.substring(cookieStartIndex + prefix.length, cookieEndIndex))
}


function deleteCookie(name, query, domain) {
        if (getCookie(name)) {
                document.cookie = name + "=" +
                ((path) ? "; path=" + path : "") +
                ((domain) ? "; domain=" + domain : "") +
                "; expires=Thu, 01-Jan-70 00:00:01 GMT"
        }deleteCookie(name, path, domain)
}


function ajax_post(path,parameter,id_result,type) {
	if (request.readyState == 1)
	{
		request.abort();
	};
		var random_x = Math.random();
		var random_y = Math.random();
		random_result = random_x * random_y;
		request.open("GET", base_url + path + '?' + parameter + '&random=' + random_result, true);
    	request.onreadystatechange = updatePage;
    	request.send(null);
		var arr = ajax_post_result(id_result,type);
		return arr;

}


function ajax_post_result(id_result,type)
{
	if (request.readyState == 1)
	{
		setTimeout('ajax_post_result("'+id_result+'")','300');
		return false;
	};
	if (request.readyState == 4)
	{
		if (type == 'arr')
		{
			var far = xml2array(request.responseXML);
			return far;
		}
		else
		{
			document.getElementById(id_result).innerHTML = request.responseText + '';
		};
	}
	else
	{
		setTimeout('ajax_post_result('+id_result+')','300');
	};
	return true;
};




function dump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;

	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";

	if(typeof(arr) == 'object') { //Array/Hashes/Objects
		for(var item in arr) {
			var value = arr[item];

			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}













//////////////////////////////////// xml2array() ////////////////////////////////////////
//See http://www.openjs.com/scripts/xml_parser/
var not_whitespace = new RegExp(/[^\s]/);//This can be given inside the funciton - I made it a global variable to make the scipt a little bit faster.
var parent_count;
//Process the xml data
function xml2array(xmlDoc,parent_count) {
	var arr;
	var parent = "";
	parent_count = parent_count || new Object;

	var attribute_inside = 0; /*:CONFIG: Value - 1 or 0
	*	If 1, Value and Attribute will be shown inside the tag - like this...
	*	For the XML string...
	*	<guid isPermaLink="true">http://www.bin-co.com/</guid>
	*	The resulting array will be...
	*	array['guid']['value'] = "http://www.bin-co.com/";
	*	array['guid']['attribute_isPermaLink'] = "true";
	*
	*	If 0, the value will be inside the tag but the attribute will be outside - like this...
	*	For the same XML String the resulting array will be...
	*	array['guid'] = "http://www.bin-co.com/";
	*	array['attribute_guid_isPermaLink'] = "true";
	*/

	if(xmlDoc.nodeName && xmlDoc.nodeName.charAt(0) != "#") {
		if(xmlDoc.childNodes.length > 1) { //If its a parent
			arr = new Object;
			parent = xmlDoc.nodeName;

		}
	}
	var value = xmlDoc.nodeValue;
	if(xmlDoc.parentNode && xmlDoc.parentNode.nodeName && value) {
		if(not_whitespace.test(value)) {//If its a child
			arr = new Object;
			arr[xmlDoc.parentNode.nodeName] = value;
		}
	}

	if(xmlDoc.childNodes.length) {
		if(xmlDoc.childNodes.length == 1) { //Just one item in this tag.
			arr = xml2array(xmlDoc.childNodes[0],parent_count); //:RECURSION:
		} else { //If there is more than one childNodes, go thru them one by one and get their results.
			var index = 0;

			for(var i=0; i<xmlDoc.childNodes.length; i++) {//Go thru all the child nodes.
				var temp = xml2array(xmlDoc.childNodes[i],parent_count); //:RECURSION:
				if(temp) {
					var assoc = false;
					var arr_count = 0;
					for(key in temp) {
						if(isNaN(key)) assoc = true;
						arr_count++;
						if(arr_count>2) break;//We just need to know wether it is a single value array or not
					}

					if(assoc && arr_count == 1) {
						if(arr[key]) { 	//If another element exists with the same tag name before,
										//		put it in a numeric array.
							//Find out how many time this parent made its appearance
							if(!parent_count || !parent_count[key]) {
								parent_count[key] = 0;

								var temp_arr = arr[key];
								arr[key] = new Object;
								arr[key][0] = temp_arr;
							}
							parent_count[key]++;
							arr[key][parent_count[key]] = temp[key]; //Members of of a numeric array
						} else {
							parent_count[key] = 0;
							arr[key] = temp[key];
							if(xmlDoc.childNodes[i].attributes && xmlDoc.childNodes[i].attributes.length) {
								for(var j=0; j<xmlDoc.childNodes[i].attributes.length; j++) {
									var nname = xmlDoc.childNodes[i].attributes[j].nodeName;
									if(nname) {
										/* Value and Attribute inside the tag */
										if(attribute_inside) {
											var temp_arr = arr[key];
											arr[key] = new Object;
											arr[key]['value'] = temp_arr;
											arr[key]['attribute_'+nname] = xmlDoc.childNodes[i].attributes[j].nodeValue;
										} else {
										/* Value in the tag and Attribute otside the tag(in parent) */
											arr['attribute_' + key + '_' + nname] = xmlDoc.childNodes[i].attributes[j].nodeValue;
										}
									}
								} //End of 'for(var j=0; j<xmlDoc. ...'
							} //End of 'if(xmlDoc.childNodes[i] ...'
						}
					} else {
						arr[index] = temp;
						index++;
					}
				} //End of 'if(temp) {'
			} //End of 'for(var i=0; i<xmlDoc. ...'
		}
	}

	if(parent && arr) {
		var temp = arr;
		arr = new Object;

		arr[parent] = temp;
	}
	return arr;
}


/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}
if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}
if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}
deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){
	if(!document.getElementById){return;}
	this.DETECT_KEY=_a?_a:"detectflash";
	this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);
	this.params=new Object();this.variables=new Object();
	this.attributes=new Array();
	if(_1){this.setAttribute("swf",_1);}
	if(id){this.setAttribute("id",id);}
	if(w){this.setAttribute("width",w);}
	if(h){this.setAttribute("height",h);}
	if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}
	this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();
	if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}
	if(c){this.addParam("bgcolor",c);}
	var q=_7?_7:"high";
	this.addParam("quality",q);
	this.setAttribute("useExpressInstall",false);
	this.setAttribute("doExpressInstall",false);
	var _c=(_8)?_8:window.location;
	this.setAttribute("xiRedirectUrl",_c);
	this.setAttribute("redirectUrl","");
	if(_9){this.setAttribute("redirectUrl",_9);}};
	deconcept.SWFObject.prototype={
		useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);
		},setAttribute:function(_e,_f){this.attributes[_e]=_f;}
		,getAttribute:function(_10){return this.attributes[_10];}
		,addParam:function(_11,_12){this.params[_11]=_12;}
		,getParams:function(){return this.params;}
		,addVariable:function(_13,_14){this.variables[_13]=_14;}
		,getVariable:function(_15){return this.variables[_15];}
		,getVariables:function(){return this.variables;}
		,getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;}
		,getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){
			if(this.getAttribute("doExpressInstall")){
				this.addVariable("MMplayerType","PlugIn");
				this.setAttribute("swf",this.xiSWFPath);
				}
			_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";
			_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";
			var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";
			}
		var _1c=this.getVariablePairs().join("&");
		if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}
		_19+="/>";}else{
			if(this.getAttribute("doExpressInstall")){
				this.addVariable("MMplayerType","ActiveX");
				this.setAttribute("swf",this.xiSWFPath);}
				_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";
				_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";
				var _1d=this.getParams();
				for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";
				}
			var _1f=this.getVariablePairs().join("&");
			if(_1f.length>0){
				_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";
			}
			_19+="</object>";
		}return _19;
		},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65])
		;if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true)
		;this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";
		this.addVariable("MMdoctitle",document.title);
		}
		}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();
		return true;
		}else{
			if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));
			}}return false;
			}};
			deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);
			if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];
			if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));
			}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;
			var _26=3;while(axo){try{_26++;
			axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);
			_23=new deconcept.PlayerVersion([_26,0,0]);
			}catch(e){axo=null;
			}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
			}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
			_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";
			}catch(e){if(_23.major==6){return _23;
			}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
			}}}return _23;
			};
			deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;
			this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;
			}if(this.major>fv.major){return true;
			}if(this.minor<fv.minor){return false;
			}if(this.minor>fv.minor){return true;
			}if(this.rev<fv.rev){return false;
			}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;
			if(_2b==null){return q;
			}if(q){var _2d=q.substring(1).split("&");
			for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));
			}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");
			for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";
			for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};
			}}}};
			if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};
			__flash_savedUnloadHandler=function(){};
			window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);
			};
			window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);
			deconcept.unloadSet=true;
			}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];
			};
			}var getQueryParamValue=deconcept.util.getRequestParameter;
			var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;

/*
function getCaretPos(obj)
{
  if(obj.selectionStart) return obj.selectionStart;//Gecko
  else if (document.selection)//IE
  {zz
    var sel = document.selection.createRange();
    var clone = sel.duplicate();
    sel.collapse(true);
    clone.moveToElementText(obj);
    clone.setEndPoint('EndToEnd', sel);
    return clone.text.length;
  }

  return 0;
}
*/


function getCaretPos(obj)
{
  if(obj.selectionStart) return obj.selectionStart;//Gecko
  else if (document.selection)//IE
  {
    var sel = document.selection.createRange(obj);

	sel.text = '|';
    var num_sel = obj.value.indexOf('|');
	textsts =  obj.value.replace('|','');
	obj.value = textsts;
	obj.moveToElementText(2);
	return num_sel;
  }

  return 0;
}

function trim( str, charlist ) {    // Strip whitespace (or other characters) from the beginning and end of a string
    //
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: mdsjack (http://www.mdsjack.bo.it)
    // +   improved by: Alexander Ermolaev (http://snippets.dzone.com/user/AlexanderErmolaev)
    // +      input by: Erkekjetter
    //  improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)

    charlist = !charlist ? ' \s\xA0' : charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '\$1');
    var re = new RegExp('^[' + charlist + ']+|[' + charlist + ']+$', 'g');
    return str.replace(re, '');
}

function getElementsByName_iefix(tag, name) {
	if (navigator.appName == 'Microsoft Internet Explorer'){
	     var elem = document.getElementsByTagName(tag);
	     var arr = new Array();
	     for(i = 0,iarr = 0; i < elem.length; i++) {
	          att = elem[i].getAttribute("name");
	          if (att != null);
	          if(att == name) {
	               arr[iarr] = elem[i];
	               iarr++;
	          }
	     }
	     return arr;
	  }else{	  	return document.getElementsByName(name);;
	  };
}


function date ( format, timestamp ) {    // Format a local time/date
    //
    // +   original by: Carlos R. L. Rodrigues
    // +      parts by: Peter-Paul Koch (http://www.quirksmode.org/js/beat.html)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: MeEtc (http://yass.meetcweb.com)
    // +   improved by: Brad Touesnard

    var a, jsdate = new Date(timestamp ? timestamp * 1000 : null);
    var pad = function(n, c){
        if( (n = n + "").length < c ) {
            return new Array(++c - n.length).join("0") + n;
        } else {
            return n;
        }
    };
    var txt_weekdays = ["Sunday","Monday","Tuesday","Wednesday",
        "Thursday","Friday","Saturday"];
    var txt_ordin = {1:"st",2:"nd",3:"rd",21:"st",22:"nd",23:"rd",31:"st"};
    var txt_months =  ["", "January", "February", "March", "April",
        "May", "June", "July", "August", "September", "October", "November",
        "December"];

    var f = {
        // Day
            d: function(){
                return pad(f.j(), 2);
            },
            D: function(){
                t = f.l(); return t.substr(0,3);
            },
            j: function(){
                return jsdate.getDate();
            },
            l: function(){
                return txt_weekdays[f.w()];
            },
            N: function(){
                return f.w() + 1;
            },
            S: function(){
                return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th';
            },
            w: function(){
                return jsdate.getDay();
            },
            z: function(){
                return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0;
            },

        // Week
            W: function(){
                var a = f.z(), b = 364 + f.L() - a;
                var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;

                if(b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b){
                    return 1;
                } else{

                    if(a <= 2 && nd >= 4 && a >= (6 - nd)){
                        nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");
                        return date("W", Math.round(nd2.getTime()/1000));
                    } else{
                        return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);
                    }
                }
            },

        // Month
            F: function(){
                return txt_months[f.n()];
            },
            m: function(){
                return pad(f.n(), 2);
            },
            M: function(){
                t = f.F(); return t.substr(0,3);
            },
            n: function(){
                return jsdate.getMonth() + 1;
            },
            t: function(){
                var n;
                if( (n = jsdate.getMonth() + 1) == 2 ){
                    return 28 + f.L();
                } else{
                    if( n & 1 && n < 8 || !(n & 1) && n > 7 ){
                        return 31;
                    } else{
                        return 30;
                    }
                }
            },

        // Year
            L: function(){
                var y = f.Y();
                return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0;
            },
            //o not supported yet
            Y: function(){
                return jsdate.getFullYear();
            },
            y: function(){
                return (jsdate.getFullYear() + "").slice(2);
            },

        // Time
            a: function(){
                return jsdate.getHours() > 11 ? "pm" : "am";
            },
            A: function(){
                return f.a().toUpperCase();
            },
            B: function(){
                // peter paul koch:
                var off = (jsdate.getTimezoneOffset() + 60)*60;
                var theSeconds = (jsdate.getHours() * 3600) +
                                 (jsdate.getMinutes() * 60) +
                                  jsdate.getSeconds() + off;
                var beat = Math.floor(theSeconds/86.4);
                if (beat > 1000) beat -= 1000;
                if (beat < 0) beat += 1000;
                if ((String(beat)).length == 1) beat = "00"+beat;
                if ((String(beat)).length == 2) beat = "0"+beat;
                return beat;
            },
            g: function(){
                return jsdate.getHours() % 12 || 12;
            },
            G: function(){
                return jsdate.getHours();
            },
            h: function(){
                return pad(f.g(), 2);
            },
            H: function(){
                return pad(jsdate.getHours(), 2);
            },
            i: function(){
                return pad(jsdate.getMinutes(), 2);
            },
            s: function(){
                return pad(jsdate.getSeconds(), 2);
            },
            //u not supported yet

        // Timezone
            //e not supported yet
            //I not supported yet
            O: function(){
               var t = pad(Math.abs(jsdate.getTimezoneOffset()/60*100), 4);
               if (jsdate.getTimezoneOffset() > 0) t = "-" + t; else t = "+" + t;
               return t;
            },
            P: function(){
                var O = f.O();
                return (O.substr(0, 3) + ":" + O.substr(3, 2));
            },
            //T not supported yet
            //Z not supported yet

        // Full Date/Time
            c: function(){
                return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P();
            },
            //r not supported yet
            U: function(){
                return Math.round(jsdate.getTime()/1000);
            }
    };

    return format.replace(/[\\]?([a-zA-Z])/g, function(t, s){
        if( t!=s ){
            // escaped
            ret = s;
        } else if( f[s] ){
            // a date function exists
            ret = f[s]();
        } else{
            // nothing special
            ret = s;
        }

        return ret;
    });
}

function str_replace ( search, replace, subject ) {    // Replace all occurrences of the search string with the replacement string
    //
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni

    if(!(replace instanceof Array)){
        replace=new Array(replace);
        if(search instanceof Array){//If search    is an array and replace    is a string, then this replacement string is used for every value of search
            while(search.length>replace.length){
                replace[replace.length]=replace[0];
            }
        }
    }

    if(!(search instanceof Array))search=new Array(search);
    while(search.length>replace.length){//If replace    has fewer values than search , then an empty string is used for the rest of replacement values
        replace[replace.length]='';
    }

    if(subject instanceof Array){//If subject is an array, then the search and replace is performed with every entry of subject , and the return value is an array as well.
        for(k in subject){
            subject[k]=str_replace(search,replace,subject[k]);
        }
        return subject;
    }

    for(var k=0; k<search.length; k++){
        var i = subject.indexOf(search[k]);
        while(i>-1){
            subject = subject.replace(search[k], replace[k]);
            i = subject.indexOf(search[k],i);
        }
    }

    return subject;

}


//ДВА МАССИВА СООТНОСЯЩИЕ СМАЙЛЫ С ИЗОБРАЖЕНИЕМ
	var smileText = new Array(':)',':|',':(');
	var smileImg = new Array('emotions.gif','smiley-undecided.gif','smiley-cry.gif');
//
	var smile = new Array();

	x = 0;
	while(smileText[x]){		smile[x] = new Image();
		smile[x].src = base_url+'public/images/icons/'+smileImg[x];		++x;
	};

var table_smile = null;

//функция инициализирующая и показывающая таблицу смайлов (object event)
function open_table_smile(event){
	if (table_smile == null){		table_smile = document.createElement('div');
		table_smile.className = 'chat_table_smile';

		x = 0;
		while(smileText[x]){			Tag_A = document.createElement('a');
			Tag_A.onmousedown = function(){ submit_table_smile(this); };
            Tag_A.appendChild(smile[x]);
            Tag_A.title = smileText[x];
            table_smile.appendChild(Tag_A);
            ++x;
		};
		tagDiv = document.createElement('div');
		tagDiv.appendChild(document.createTextNode('закрыть'));
		tagDiv.onmousedown = function(){close_table_smile();};
		tagDiv.className = 'button_close_table_smile';

		table_smile.appendChild(tagDiv);
		document.body.appendChild(table_smile);
	}else{		table_smile.style.display = 'block';
	};
	if(navigator.appName == 'Microsoft Internet Explorer'){
		table_smile.style.left = window.event.x+'px';
		table_smile.style.top = window.event.y+'px';
	}else{		table_smile.style.left = event.pageX+'px';
		table_smile.style.top = event.pageY+'px';
	};
return table_smile;
};

function close_table_smile(){
	if (table_smile != null) table_smile.style.display = 'none';
	return true;
};

function submit_table_smile(obj){	document.getElementById('chat_submit').value += obj.title;
	return true;
};


//функция заменяющая текстовые смайлы в графические
function replaceForSmile(text){
	x = 0;
	while (smileImg[x]){		//smileImg[x] = '<img src="'+base_url+'public/images/icons/'+smileImg[x]+'" title="'+smileImg[x]+'" />';  -- str_replace наедается по условиям и виснет		smileImg[x] = '<img src="'+smile[x].src+'" />';
		++x;
	};

	text = str_replace(smileText,smileImg,text);
	return text;
};


//функция отвечающая за инициализацию чата
function initial_chat(obj){
	obj.status = 'initial';
	var generalDiv = document.getElementById(obj.id);
	generalDiv.appendChild(obj.myDiv);
	generalDiv.appendChild(obj.myStatus);
	generalDiv.appendChild(obj.myButton);
	generalDiv.appendChild(obj.myOpenSmileTable);
	generalDiv.className = 'chat_general_element';
};

var refresh_chat_temp_var = null;
var last_id_message = 0;
var refresh_timeout;
var chat_id_tree;
var limit_view_messages;

//функция отвечающая за обновление контента чата
function refresh_chat(obj,action,speed){
	if (obj == ''){
		obj = refresh_chat_temp_var;
	}else{
		refresh_chat_temp_var = obj;
	};
	clearTimeout(refresh_timeout);

	switch(action){
		case 'send':
			request.open("GET", base_url + 'chat/?id='+chat_id_tree+'&id_message='+last_id_message+'&random='+Math.random(), true);
			request.onreadystatechange = function(){refresh_chat(obj,'reception',speed);};
			request.send(true);
		break;
		case 'reception':
   			if (request.readyState == 4){
		   	   if (request.status == 200){
                 var temparray = request.responseText.split('/%%%|%%%/'); //получаем 'сериализованный массив с данными'
                 var all_id = temparray[1].split('+%%%|%%%+');
                 var all_message = temparray[0].split('+%%%|%%%+');
                 var all_date = temparray[2].split('+%%%|%%%+');
                 var all_user_id = temparray[3].split('+%%%|%%%+');
                 var all_user_name = temparray[4].split('+%%%|%%%+');
                 var all_user_link = temparray[5].split('+%%%|%%%+');
                 var all_user_avatar = temparray[6].split('+%%%|%%%+');

                 var print_messages = '';
                 x = 0;
                 while (all_id[x]){
                 	print_messages += '<div>'+all_date[x]+'<a href="'+all_user_link[x]+'">'+'&nbsp;'+'<img src="'+all_user_avatar[x]+'" />'+all_user_name[x]+'</a>'+':'+all_message[x]+'</div>'; //в цикле формируем строки
                 	++x;
                 };

                 --x;
                 if (typeof(all_id[x]) != 'undefined') last_id_message = all_id[x];
    		     obj.myDiv.innerHTML += replaceForSmile(print_messages);
				 if (obj.myDiv.childNodes.length > limit_view_message){
				 	var LimitDistinct = obj.myDiv.childNodes.length - limit_view_message;
				 	var x = 0;
				  	while (LimitDistinct > x){
                        obj.myDiv.childNodes[x].innerHTML = '';
                        ++x;
				  	};

				 };
                 obj.myDiv.scrollTop = obj.myDiv.offsetHeight+9000;
				 if (typeof(speed) != 'undefined') refresh_timeout = setTimeout("refresh_chat('','send',"+speed+")",speed);
		       };
		 	};
		break;
		/*
		case 'reception':
   			if (request.readyState == 4){
		   	   if (request.status == 200){
                 var temparray = request.responseText.split('/%%%|%%%/'); //получаем 'сериализованный массив с данными'
                 var all_id = temparray[1].split('+%%%|%%%+');
                 var all_message = temparray[0].split('+%%%|%%%+');
                 var all_date = temparray[2].split('+%%%|%%%+');
                 var all_user_id = temparray[3].split('+%%%|%%%+');
                 var all_user_name = temparray[4].split('+%%%|%%%+');
                 var all_user_link = temparray[5].split('+%%%|%%%+');
                 var all_user_avatar = temparray[6].split('+%%%|%%%+');

                 var print_messages = '';
                 x = 0;
                 while (all_id[x]){//обрабатываем в цикле полученные данные
                 	textDiv = document.createElement('div'); //инициализируем <div> для сообщения
                 	textDiv.appendChild(document.createTextNode(all_date[x])); //добавляем див дату сообщения
                 	textALink = document.createElement('a'); //создаем ссылку
                 	textALink.href = all_user_link[x]; //указываем в ссылке путь до юзера
                 	textMyImg = new Image();
                 	textMyImg.src = all_user_avatar[x]; //создаем и инициализируем аватор
                 	textALink.appendChild(textMyImg); //добавляем аватор внутрь ссылки
                 	textALink.appendChild(document.createTextNode(all_user_name[x])); //добавляем имя юзера внутрь ссылки
                 	var myTextChat = ':'+replaceForSmile(all_message[x]);
                 	myTextChat = myTextChat.replace('<br />','');
                 	textDiv.appendChild(document.createTextNode(myTextChat)); //добавляем текст сообщения
                 	obj.myDiv.appendChild(textDiv); //всё это добавляем в общие данные
                 	++x;
                 };

                 --x;
                 if (typeof(all_id[x]) != 'undefined'){
                 										last_id_message = all_id[x];
										                obj.myDiv.scrollTop = obj.myDiv.offsetHeight+9000; //скроллинг делаем вниз (+9000 -> запас на погрешность)
														};


				 if (obj.myDiv.childNodes.length > limit_view_message){ //если количество видимых сообщений	больше разрешенных
				 	var LimitDistinct = obj.myDiv.childNodes.length - limit_view_message;
				 	var x = 0;
				  	while (LimitDistinct > x){
                        obj.myDiv.removeChild(obj.myDiv.childNodes[x]); //чистим самые старые сообщения
                        ++x;
				  	};

				 };

				 if (typeof(speed) != 'undefined') refresh_timeout = setTimeout("refresh_chat('','send',"+speed+")",speed);
		       };
		 	};
		break;
		*/
		case 'viewLastMessage':
			request.open("GET", base_url + 'chat/?id='+chat_id_tree+'&view_last_message=10'+'&random='+Math.random(), true);
			request.onreadystatechange = function(){refresh_chat(obj,'reception',speed);};
			request.send(true);
		break;
		case 'send_now':
		    clearTimeout(refresh_timeout);
			refresh_timeout = setTimeout("refresh_chat('','send',"+speed+")",500);
		break;
	};

};

//функция сохраняющая сообщение
function add_message_chat(limit,event){
	if(navigator.appName == 'Microsoft Internet Explorer'){
		if(window.event.keyCode != 10 && window.event.keyCode != 0) return false;
	}else{
		if(!(event.which == 13 && event.ctrlKey == true) && event.which != 1) return false;
	};

	var message = document.getElementById('chat_submit').value;
	if (message.length > limit){
		alert('сообщение не должно состоять из более чем '+limit+' символов');
		return false;
	};
	document.getElementById('chat_submit').value = '';

	request.open("GET", base_url + 'chat/?id='+chat_id_tree+'&message='+escape(message), true);
	request.send(true);
	refresh_chat('','send_now',10000);
};

//класс отвечающий за работу чата
function Chat(id,limit_message){

	this.id = id;

	this.myDiv = document.createElement('div'); //блок отображения текста чата
	this.myDiv.onclick = function(){alert(this.myDiv.scrollTo);};
	/*
	this.myDiv1 = document.createElement('div'); //блок отображения данных о юзвере внутри чата
	this.myDiv1.className = 'chat_info_user';
	this.myDiv2 = document.createElement('div'); //блок отображения текста юзверя внутри чата
	this.myDiv2.className = 'chat_dialog';
	*/

	this.myDiv.className = 'chat_view_text';

	this.myStatus = document.createElement('textarea'); //блок отображения поля ввода
	this.myStatus.setAttribute('id','chat_submit');
	this.myStatus.className = 'chat_textarea_window';
	this.myStatus.onkeypress = function(event){add_message_chat(200,event);};

	this.myButton = document.createElement('input'); //блок отображения кнопки отправки
	this.myButton.type = 'button';
	this.myButton.value = 'ok';
	this.myButton.onmousedown = function(event){add_message_chat(200,event);};
	this.myButton.className = 'chat_textarea_button';

	this.myOpenSmileTable = document.createElement('div');
	this.myOpenSmileTable.appendChild(document.createTextNode('смайлы'));
	this.myOpenSmileTable.onmousedown = function(event){open_table_smile(event);};
	this.myOpenSmileTable.className = 'button_open_smile_table';

	this.refreshStatus = false;
	this.status = 'not initial';

	this.initial = function(){initial_chat(this)};
	this.refresh = function(speed,command){this.speed = speed; refresh_chat(this,command,speed);};
	this.addMessage = function(limit){add_message_chat(limit);};
};


//самая главная функция для вызова и работы чата
//(char id элемента,int скорость обновления,int количество последних сообщений,int id дерева,int лимит олтображаемых сообщений,char внутренняя комманда функции)
function work_chat(id,speed,count_view_message,id_tree,limit_message,command){
	if (typeof(command) == 'undefined') command = 'viewLastMessage';
	chat_id_tree = id_tree;
	limit_view_message = limit_message;
	Chat = new Chat(id);
	Chat.initial();
	Chat.refresh(speed,command);
	//Chat.addMessage();
};

primecms = new Object();
primecms.cmd = function(command,parameter,evented,linkObjected){command_function(command,parameter,evented,linkObjected);};


function sendIntervalTime(getURL,timeInterval){	getURL += '&random='+Math.random();	request.open("GET", getURL, true);
	request.send(true);
	setTimeout('sendIntervalTime("'+getURL+'",'+timeInterval+')',timeInterval);
};



megaTimerMenu = '';

/*
function view_submenu(nameSubMenu,intNumberOver){

	var myMenu = implodePartMenu[intNumberOver].split('|');
	var subMenu = document.getElementById(nameSubMenu + 'MMMM');

	if(navigator.appName == 'Microsoft Internet Explorer') var	x = 0;
	else var x = 1;

	while (subMenu.childNodes[x]){
		subMenu.childNodes[x].className = 'off_view_menu_node';
		if(navigator.appName == 'Microsoft Internet Explorer') ++x;
		else x += 2;
	};

	if(navigator.appName == 'Microsoft Internet Explorer') var	x = 0;
	else var x = 1;

	while (subMenu.childNodes[x]){
		var i = 0;
		while (myMenu[i]){
			if (subMenu.childNodes[x].childNodes[0].innerHTML == myMenu[i]) subMenu.childNodes[x].className= 'on_view_menu_node';
			++i;
		};
		if(navigator.appName == 'Microsoft Internet Explorer') ++x;
		else x += 2;
	};
};

function FixReturnDefaultSubMenu(nameGeneralMenu,nameSubMenu,numberActivePart,timeSleep){
	var subMenu = document.getElementById(nameSubMenu);
	subMenu.onmouseover = function(){clearTimeout(megaTimerMenu);};
	subMenu.onmouseout = function (){megaTimerMenu = setTimeout('view_submenu("'+nameSubMenu+'","'+numberActivePart+'")',timeSleep);	};
}


function title_menu(nameGeneralMenu,nameSubMenu,numberActivePart,timeSleep){
	if (typeof(timeSleep) == 'undefined') timeSleep = 2000;
	var genMenu = document.getElementById(nameGeneralMenu);
    defaultSubMenu = nameSubMenu;
    defaultActivePart = numberActivePart;

	FixReturnDefaultSubMenu(nameGeneralMenu,nameSubMenu,numberActivePart,timeSleep);

	if(navigator.appName == 'Microsoft Internet Explorer') var	x = 0;
	else var x = 1;

	var i = 0;

	outerLoop:
	while (genMenu.childNodes[x]){

		if (numberActivePart == i){

			genMenu.childNodes[x].childNodes[0].childNodes[0].childNodes[0].src = arMenuPartActive[i];
			view_submenu(nameSubMenu,i);
			genMenu.childNodes[x].className = 'container-active';
			genMenu.childNodes[x].onmouseover = function(){
															clearTimeout(megaTimerMenu);
															if(navigator.appName == 'Microsoft Internet Explorer') var	x = 0;
															else var x = 1;

														   var i = 0;
															 while (genMenu.childNodes[x]){
																if (genMenu.childNodes[x].innerHTML == this.innerHTML){
																	view_submenu(nameSubMenu,i);
																	break;
																};
																++i;
																if(navigator.appName == 'Microsoft Internet Explorer')	++x;
																else x += 2;

															 };
														   };
			genMenu.childNodes[x].onmouseout = function(){
														clearTimeout(megaTimerMenu);
														megaTimerMenu = setTimeout('view_submenu("'+nameSubMenu+'","'+numberActivePart+'")',timeSleep);
														if(navigator.appName == 'Microsoft Internet Explorer') var	x = 0;
														else var x = 1;

														 while (genMenu.childNodes[x]){
															if (genMenu.childNodes[x].innerHTML == this.innerHTML)	break;
															if(navigator.appName == 'Microsoft Internet Explorer')	++x;
															else x += 2;
														 };
													   };
			if(navigator.appName == 'Microsoft Internet Explorer')	++x;
			else x += 2;

			++i;
			continue outerLoop;
		};

		genMenu.childNodes[x].childNodes[0].childNodes[0].childNodes[0].src = arMenuPartStatic[i];
		genMenu.childNodes[x].onmouseover = function(){
														clearTimeout(megaTimerMenu);
														if(navigator.appName == 'Microsoft Internet Explorer') var	x = 0;
														else var x = 1;
													   var i = 0;
														 while (genMenu.childNodes[x]){
															if (genMenu.childNodes[x].innerHTML == this.innerHTML){
																this.childNodes[0].childNodes[0].childNodes[0].src = arMenuPartOnOver[i];
																view_submenu(nameSubMenu,i);
																break;
															};
															++i;
															if(navigator.appName == 'Microsoft Internet Explorer') ++x;
															else x += 2;
														 };
													   };
		genMenu.childNodes[x].onmouseout = function(){
														clearTimeout(megaTimerMenu);
														megaTimerMenu = setTimeout('view_submenu("'+nameSubMenu+'","'+numberActivePart+'")',timeSleep);
														if(navigator.appName == 'Microsoft Internet Explorer') var	x = 0;
														else var x = 1;
													  var i = 0;
														 while (genMenu.childNodes[x]){
															if (genMenu.childNodes[x].innerHTML == this.innerHTML){
																this.childNodes[0].childNodes[0].childNodes[0].src = arMenuPartStatic[i];
																break;
															};
															++i;
															if(navigator.appName == 'Microsoft Internet Explorer')	++x;
															else x += 2;
														 };
													   };
		++i;
		if(navigator.appName == 'Microsoft Internet Explorer')	++x;
		else x += 2;
	};
}

*/

number_active_scroll_element = 0;
count_scroll_element = 0;
var general_scroll_element;

//функция инициализирующая интерактивный просмотрщик
function initial_scrollbar(KeyBack,KeyForward,subHolder,tapBottom){
	if (navigator.appName == 'Microsoft Internet Explorer'){
		getElementsByName_iefix('a',KeyBack)[0].onmousedown = function(){scroll_back(KeyBack,subHolder,tapBottom);};
		getElementsByName_iefix('a',KeyForward)[0].onmousedown = function(){scroll_forward(KeyForward,subHolder,tapBottom);};
		cadr = getElementsByName_iefix('div',tapBottom);
		general_scroll_element = getElementsByName_iefix('div',subHolder)[0];
	}else{
		document.getElementsByName(KeyBack)[0].onmousedown = function(){scroll_back(KeyBack,subHolder,tapBottom);};
		document.getElementsByName(KeyForward)[0].onmousedown = function(){scroll_forward(KeyForward,subHolder,tapBottom);};
		cadr = document.getElementsByName(tapBottom);
		general_scroll_element = document.getElementsByName(subHolder)[0];
	};


	var x = 0;
	while (cadr[x]){
		++count_scroll_element;
		++x;
	};
	--count_scroll_element;


	number_active_scroll_element = count_scroll_element;
	var correct = (general_scroll_element.clientWidth/(1+count_scroll_element))-cadr[0].clientWidth;
	general_scroll_element.style.marginLeft = '0px';
};

//внутренняя функция для работы с просмотрщиком (перемещение налево)
function scroll_back(Key,MovieName,ClipElements){
	if (navigator.appName == 'Microsoft Internet Explorer'){
		cadr = getElementsByName_iefix('div',ClipElements);
		var startX = parseInt(general_scroll_element.style.marginLeft);
		var endX = startX+cadr[0].clientWidth;
	    ++number_active_scroll_element;
		if (!getElementsByName_iefix('div',ClipElements)[number_active_scroll_element]){
		    number_active_scroll_element = 0;
			scrollRight(0,-1*(cadr[0].clientWidth*count_scroll_element));
	        return false;
		}else{
			scrollLeft(startX,endX);
		};
	}else{
		cadr = document.getElementsByName(ClipElements);
		var startX = parseInt(general_scroll_element.style.marginLeft);
		var endX = startX+cadr[0].clientWidth;

	    ++number_active_scroll_element;
		if (!document.getElementsByName(ClipElements)[number_active_scroll_element]){
		    number_active_scroll_element = 0;
			scrollRight(0,-1*(cadr[0].clientWidth*count_scroll_element));
	        return false;
		}else{
			scrollLeft(startX,endX);
		};
	};

};

//внутренняя функция для работы с просмотрщиком (перемещение вперед)
function scroll_forward(Key,MovieName,ClipElements){
	if (navigator.appName == 'Microsoft Internet Explorer'){
		cadr = getElementsByName_iefix('div',ClipElements);
		var startX = parseInt(general_scroll_element.style.marginLeft);
		var endX = startX-cadr[0].clientWidth;

		--number_active_scroll_element;
		if (number_active_scroll_element < 0){
			number_active_scroll_element = count_scroll_element;
	   		scrollLeft(-1*(cadr[0].clientWidth*count_scroll_element),0);
	        return false;
		}else{
			scrollRight(startX,endX);
		};
	}else{
		cadr = document.getElementsByName(ClipElements);
		var startX = parseInt(general_scroll_element.style.marginLeft);
		var endX = startX-cadr[0].clientWidth;


		--number_active_scroll_element;
		if (number_active_scroll_element < 0){
			number_active_scroll_element = count_scroll_element;
	   		scrollLeft(-1*(cadr[0].clientWidth*count_scroll_element),0);
	        return false;
		}else{
			scrollRight(startX,endX);
		};
	};
};

//функция которая переключает кадры просмотрщика (назад ~ влево)
function scrollLeft(startX,endX,speedX,iterator,width){
	shot = ((endX - startX)/80);
	if (width >= endX) return false;

	if (typeof(iterator) == 'undefined') iterator = 1;
	if (typeof(speedX) == 'undefined') speedX = 1;
	if (typeof(width) == 'undefined') width = startX;
    if (speedX > -1*width) speedX = width;
	width += speedX;

    if (speedX >= -1*width){
    	general_scroll_element.style.marginLeft = endX+'px';
    	return false;
    };

    if (width > endX){
    	general_scroll_element.style.marginLeft = endX+'px';
    	return false;
    };

	general_scroll_element.style.marginLeft = width+'px';
	if (width >= startX+((endX - startX)/2)) speedX -= shot;
	else speedX += shot;
	if (speedX < 1) speedX = 1;

	++iterator;
	setTimeout('scrollLeft('+startX+','+endX+','+speedX+','+iterator+','+width+')',50);
};

//функция которая переключает кадры просмотрщика (назад ~ вправо)
function scrollRight(startX,endX,speedX,iterator,width){
	shot = ((endX - startX)/80);

	if (width <= endX) return false;
	if (typeof(iterator) == 'undefined') iterator = 1;
	if (typeof(speedX) == 'undefined') speedX = 1;
	if (typeof(width) == 'undefined') width = startX;

	width -= speedX;

	if (width < endX) {general_scroll_element.style.marginLeft = endX+'px';
	                    return false;
						}
	general_scroll_element.style.marginLeft = width+'px';

    if (width >= startX+((endX - startX)/2)) speedX -= shot;
	else speedX += shot;
	if (speedX < 1) speedX = 1;

	++iterator;
	setTimeout('scrollRight('+startX+','+endX+','+speedX+','+iterator+','+width+')',50);
};


function mark_game_fix(url, id_game, mark_game){
	var url = base_url + 'system/game/?id=' + id_game + '&mark=' + mark_game;
	request.open("GET", url, true);
    request.send(null);
}

//функция реагирующая на перемещение по элементам рейтинга
function mouseOverRatingStars(){
	myName = this.parentNode.getAttribute("name");
	i = 0;
	while (stars_name[i]){
		if (myName == stars_name[i]){
			var i2 = 0;
			while (this.parentNode.childNodes[i2]){
				this.parentNode.childNodes[i2].childNodes[0].src = rating_stars[i][0].src;
				if (this.parentNode.childNodes[i2] == this) break;
				++i2;
			};
			++i2;
			while (i2 < 5){
				this.parentNode.childNodes[i2].childNodes[0].src = rating_stars[i][1].src;
				++i2;
			};
		};
		++i;
	};
};

//функция реагирующая на нажатие по элементу рейтинга
function mouseDownRatingStars(){
	myName = this.parentNode.getAttribute("name");
	i = 0;
	while (stars_name[i]){
		if (myName == stars_name[i]){
		var i2 = 0;
		while (this.parentNode.childNodes[i2]){
			if (this.parentNode.childNodes[i2] == this){
				mark_game_fix(base_url+'/bukabuk/bukabuk/',parseInt(this.id.replace('rating_stars_id_','')),i2);
				break;
			};
			++i2;
		};
		++i2;
	};
	++i;
};

};

//функция реагирующая на покидание элементов рейтинга
function mouseOutRatingStars(){
	myName = this.getAttribute("name");
	i = 0;
	while (stars_name[i]){
		if (myName == stars_name[i]){
			var i2 = 0;
			while (this.childNodes[i2]){
				this.childNodes[i2].childNodes[0].src = rating_stars[i][0].src;
				++i2;
				if (i2 > this.point) break;
			};
			++i2;
			while (i2 < 5){
				this.childNodes[i2].childNodes[0].src = rating_stars[i][1].src;
				++i2;
			};
		};
		++i;
	};
};

// функция генераций изображений.
function generate_rating_stars(stars_name,rating,stars){
	rating_stars = new Array();
	dirIMG = './images/'; //директория изображений

	x = 0;
	while (stars_name[x]){// проходим по именам рейтингов
		rating_stars[x] = new Array();
		rating_stars[x][0] = new Image;
		rating_stars[x][0].src = dirIMG+stars[x][0];
		rating_stars[x][1] = new Image;
		rating_stars[x][1].src = dirIMG+stars[x][1];
		var elements = getElementsByName_iefix('div',stars_name[x]);

		var borderImage = document.createElement('div');
		borderImage.style.display = 'inline';

		a = 0;
        while (rating[x][a]){// проходим по массиву рейтингов
        	point = 0;

			while (point < parseInt(rating[x][a])){ // проходим по зачтенным баллам
				myBorderImage = borderImage.cloneNode(true);
				myBorderImage.id = 'rating_stars_id_'+idgames[x][a];

				if (ready[x][a] != '0') myBorderImage.onmouseover = mouseOverRatingStars;
				if (ready[x][a] != '0') myBorderImage.onmousedown = mouseDownRatingStars;

				elements[a].point = point;
				myBorderImage.appendChild(rating_stars[x][0].cloneNode(true));
				elements[a].appendChild(myBorderImage);
				++point;
			};
			while (point < 5){  //проходим по незачтенным баллам
				myBorderImage = borderImage.cloneNode(true);
				if (ready[x][a] != '0') myBorderImage.onmouseover = mouseOverRatingStars;
				if (ready[x][a] != '0') myBorderImage.onmousedown = function(){alert(this.id); mouseDownRatingStars;};

				myBorderImage.appendChild(rating_stars[x][1].cloneNode(true));
				elements[a].appendChild(myBorderImage);
				++point;
			};
			if (ready[x][a] != '0')  elements[a].onmouseout = mouseOutRatingStars;
			++a;
		};

	++x;
	};

};

// генерируем ссылку
function generate_invite_link(id_user){	//alert(base_url);
	var from_link = document.getElementById('from_my_link');
	var text_link = document.getElementById('generate_my_link');

	var bbcode_link = document.getElementById('generate_my_link_bbcode');
	var url_text_link = document.getElementById('generate_my_link_url');

    from_text = from_link.value;

	if(from_text != ''){		if(from_text.indexOf(base_url) + 1){			to_text = '';			if(from_text.indexOf('?') + 1) to_text = from_text + '&id_invite=' + id_user;			else to_text = from_text + '?id_invite=' + id_user;

			text_link.value = '<a href="' + to_text + '">Я в Букабук.ру</a>';
			bbcode_link.value = '[url=' + to_text + ']Я в Букабук.ру[/url]';
			url_text_link.value = to_text;		}
		else alert('неверная ссылка');
	}
}



function activate_sub_menu(){	//alert('document.location.href = ' + document.location.href);

	sub_menu_numb = -1;
	it_submenu_arr = new Array();
	for(i = 0; i < implodeNumbersMenu.length; i++){
		//alert('implodeNumbersMenu[' + i + '] = ' + implodeNumbersMenu[i]);
		sub_numbers_menu = implodeNumbersMenu[i].split(',');

		for(j = 0; j < sub_numbers_menu.length; j++){			id_num = sub_numbers_menu[j];			div_obj = document.getElementById('submenu_item_' + id_num);
			a_obj = document.getElementById('submenu_a_' + id_num);

			if(document.location.href.indexOf(a_obj.href) + 1){				//alert('sovpalo');				menu_num = i;
				pnum = 0;
				if(menu_num == 0) pnum = 13;
				if(menu_num == 1) pnum = 15;
				if(menu_num == 2) pnum = 17;
				if(menu_num == 3) pnum = 19;
				if(menu_num == 4) pnum = 21;
				if(pnum){					document.getElementById('main_menu_pic_' + menu_num).src = base_url + 'public/images/site/mainmenu-but-active-_' + pnum + '.jpg';
					document.getElementById('mm_container_' + menu_num).className= 'container-active';				}
				sub_menu_numb = j;
                it_submenu_arr = sub_numbers_menu;
                //alert('work!' + menu_num);

                for(n = 0; n < it_submenu_arr.length; n++){                	if(document.location.href.indexOf(document.getElementById('submenu_a_' + it_submenu_arr[n]).href) + 1){                		document.getElementById('submenu_item_' + it_submenu_arr[n]).className= 'on_view_menu_node_active';                	}else document.getElementById('submenu_item_' + it_submenu_arr[n]).className= 'on_view_menu_node';
                    //alert('n = ' + n);                }
			}
		}

	}}



function show_item_sub_menu(id){	for(i = 0; i < implodeNumbersMenu.length; i++){
		//alert('implodeNumbersMenu[' + i + '] = ' + implodeNumbersMenu[i]);
		sub_numbers_menu = implodeNumbersMenu[i].split(',');
		for(j = 0; j < sub_numbers_menu.length; j++){			if(i == id)	document.getElementById('submenu_item_' + sub_numbers_menu[j]).className= 'on_view_menu_node';			else document.getElementById('submenu_item_' + sub_numbers_menu[j]).className= 'off_view_menu_node';
			if(i == id && document.location.href.indexOf(document.getElementById('submenu_a_' + sub_numbers_menu[j]).href) + 1) document.getElementById('submenu_item_' + sub_numbers_menu[j]).className= 'on_view_menu_node_active';		}
        pnum = 0;
		if(i == 0) pnum = 13;
		if(i == 1) pnum = 15;
		if(i == 2) pnum = 17;
		if(i == 3) pnum = 19;
		if(i == 4) pnum = 21;


		if(i == id)	document.getElementById('main_menu_pic_' + i).src = base_url + 'public/images/site/mainmenu-but-over-_' + pnum + '.jpg';
		if(i != id) document.getElementById('main_menu_pic_' + i).src = base_url + 'public/images/site/mainmenu-but-_' + pnum + '.jpg';

		//if(i == menu_num && id != menu_num) document.getElementById('main_menu_pic_' + i).src = base_url + 'public/images/site/mainmenu-but-active-_' + pnum + '.jpg';
        if(i == menu_num) document.getElementById('main_menu_pic_' + i).src = base_url + 'public/images/site/mainmenu-but-active-_' + pnum + '.jpg';

	}
}


// Cookies

function setCookie(name, value, expires, path, domain, secure){
      document.cookie = name + "=" + escape(value) +
      ((expires) ? "; expires=" + expires : "") +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      ((secure) ? "; secure" : "");
}



function getCookie(name){
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}











