/*
*	Copyright (c) 2011 http://uniq-ip.com/
*
*	Built for jQuery library http://jquery.com
*/

//--------------- Вводные данные ---------------//

var HTTP= "";		//путь к API.
//Установить в http://uniq-ip.com, если подключение к API кроссдоменное;
//оставить пустым, если запросы к API идут через прокси Вашего сервера

var id_partner= "";		//ID партнера

var nameService= "Uniq-IP";		//краткое название Вашего сервиса

//--------------- Начальные установки ---------------//

var TIMEFILEKEYS= 30;	//время жизни куки авторизации через ключевой файл, минут [30]
var DATA, STOP=0, II=0, ID=0, _ID=0, IE=0, HTML=[], FORMS=[], JSONDATA={}, cook={}, PARAM={}, _RND={}, TH, WOREPLACES={};
var SETUP, OBJ, STYLE, V, NC, THEMA, PATH, LOCATION="a/account", REFERER, LIMIT=0, COUNT_OBJ, _DELOBJ, TOP=[], BOTTOM=[], RETURN=[], ONOFF={};

var CALLBACK= HTTP.length>1 ? "?callback=?" : "";

function _clearAll(){
	HTML=[], FORMS=[], JSONDATA={}; WOREPLACES={};
	STOP=0, LIMIT=0, COUNT_OBJ=null, TOP=[], BOTTOM=[], RETURN=[], ONOFF={};

	$("#helpdiv, #close_helpdiv, div.helpdiv").remove();
}

$.ajaxSetup({ cache: true });
if( jQuery.browser.msie ) jQuery.fx.off= true;	//останавливаем анимацию для тормознутого браузера

if(id_partner!="") cookSet('id_partner', id_partner);

//--------------- Общие функции ---------------//

$(document).ready( function(){

	var url= location.href.replace(/^https?:\/\//i, "").split(/#/);
	PATH= url[0].replace(/^[^\/]+/, "");
	PATH= PATH.replace(/\?[^?]+$/, "");
	PATH= PATH.replace(/[^\/]+$/, "");

	if( url[1]==null || url[1]=="" ){
		var quest= location.search.substring(1);
		if( quest!=null ) questParam(quest);

		if( PARAM['nc']!=null ){ LOCATION= "pay/terminal"; NC= PARAM['nc'] }
		if( PARAM['thema']!=null ){ LOCATION= "r/feedback"; THEMA= PARAM['thema'] }
	}

	if( url[1]!=null ){			//реф кука
		var idref= url[1].split(/idref\=/)[1];
		if( idref!=null ) cookSet('idref', idref, 3);
	}

	cookParam();
	if( url[1]==null) _get();

	//--------------- Топ ---------------//

	if( $("#top").size()>0 ){

		$("body").append("<div id='feedback' name='feedback' title='Обратная связь'></div>");	//обратная связь без авторизации

		setInterval(function(){

			cook={}; cookParam();

			if( cook['data']!=null && $("div.data").size()==0 ){	//выводим email, Общий счет

				$("#feedback").remove();

				$("#top").append("<div class='data'><a href='#/a/account'><img src='/i/icon/card.png' class='im16'/> <span id='email'>...</span></a><br/>" +
				"<a href='#/a/account' title='Общий счет'><img src='/i/icon/arrow-in.png' class='im16'/> <span id='balans'>...</span></a><br/> " +
				"<a href='#/a/message' onClick=\"this.href='#/a/message?\'+_rnd(0,1)+\''\" id='message'>0</a></div>");

				//выводим сообщения
				var id= cook['data'].replace(/^([0-9]+)\..+/,"$1");
				var img= "<img src='/i/icon/email.png' class='im16' title='нет новых сообщений'/>";
				var imgm= "<img src='/i/icon/email_mig.gif' class='im16' title='есть новые сообщения'/>";

				$("#message").html( jsonfileremote($("#message"), img+" 0", imgm+" ", "/json/message/"+ id +".json") );
				setInterval(function(){
					if( cook['data']!=null ) $("#message").html( jsonfileremote($("#message"), img+" 0", imgm+" ", "/json/message/"+ id +".json") );
				}, 60000);
			}

			//окрашиваем div.data зеленым, если есть кука filekeys
			if( cook['filekeys']!=null ){ $("div.data").addClass("data_filekeys") }
			else{ $("div.data").removeClass("data_filekeys") }

			$("#email").html(cook.email==null?"...":unescape(cook.email));
			$("#balans").html(cook.balans==null?"...":cook.balans);
		}, 1000);
	}

	//--------------- Меню ---------------//

	if( $("#menu_1").size()>0 ){

		var menu= "<a href='/' class='N small'><img src='/i/icon/home.png' class='im16'> Главная страница</a>", top="";

		$.getJSON(PATH+ "/base/menu.json", function(json){

			$.each( json, function(i, v1){
				menu+= "<div class='menu_item' id='menuitem_"+ i +"'>";
				menu+= "<span class='B'><img src='/i/icon/arrow-trans.png' class='im16'>&nbsp; "+ v1.title;
				menu+= "</span><div class='menu_item_ul'>";

				$.each( v1.item, function(i, v2){
					menu+= "<p><a href='"+ v2.href +"' "+ (v2.target==null?"":"target='"+v2.target+"'") +" class='N'>"+ v2.title +"</a></p>";
				});

				menu+= "</div></div>";
			});

			$("#menu_1").prepend(menu);
			menu= null;

			top= $("#menu_1").position().top;	//определям положение и устанавливаем его в меню
		});

		$("[id^=menuitem_] span").live( "click", function(){	//
			$(this).parent().find("div.menu_item_ul").slideToggle();
		});

		$(window).scroll( function(){	//скроллинг меню
			$(window).scrollTop()>top ?
				$("DIV#menu_1").css({position:'fixed', top:0}) :
				$("DIV#menu_1").css({position:'absolute', top:top+'px'});
		});
	}

	//--------------- Изменение хэша в URL ---------------//

	$(window).hashchange( function(){

		var newHash= location.hash.substring(1);
		LOCATION= newHash.split('?')[0];
		LOCATION= LOCATION.replace(/^\//,"");

		var quest= newHash.split('?')[1];
		if( quest==null ){ PARAM= {} }
		else{ questParam(quest) }

		_clearAll();
		_get();
	})

	if( url[1]!=null ) $(window).hashchange();

	//--------------- Авторизация ---------------//

	$("#enter").live( "click", function(e){

		var th= $(this);
		var val= th.html();
		var thFm= $(this).closest("form");

		var serial= thFm.serializeArray();
		serial.push( { name:'enter', value:1 } );

        $.ajax({
            url: HTTP+ "/api/a/enter" +CALLBACK,
			type: "POST",
			data: serial,
			dataType: "json",
			success: function(json){

				if( json['_warn'] ){		//if warn
					th.html(val);
					_warn(json['_warn'], th);
				}
				if( json['_error'] ){		//if error
					th.html(val);
					_error(json['_error'], th);
				}
				else{
					if( json['_email']!=null ) cookSet('email', json['_email'], 60);
					if( json['_data']!=null ) cookSet('data', json['_data'], 60);
					if( json['_balans']!=null ) cookSet('balans', json['_balans'], 60);
					if( json['_zerosurf']!=null ) cookSet('zerosurf', json['_zerosurf'], 30);

					_redirect(REFERER||"/a/account");
					return false
				}
			}
		});

		th.jImgLoad();
		e.stopImmediatePropagation();
		return false;
	})
});


function _redirect(path){

	REFERER= LOCATION;
	LOCATION= path;
	LOCATION= LOCATION.replace(/^\//,"");
	_clearAll();
	path= path.replace(/^\//,"");
	location.replace('#/'+path+'?'+_rnd(0,1));
}

function _get(){

	$.getScript(PATH+LOCATION, function(){

		HTML[0]= { setup:SETUP, url_js:PATH+LOCATION };
		getAPI($("#api"), {setup:SETUP, obj:OBJ, style:STYLE, top:TOP, bottom:BOTTOM}, {r:_rnd(_ID)});
	});
}


//--------------- Подключаемся к API ---------------//

function getAPI(th, set, pm){

	if( th.size()<1 ) return true;

	th.jImgLoad(50);
	var vv="";

	if( set.setup.url==null ){		//if нет setup.url

		$.each(set.top, function(key, val){		//разворачиваем TOP из javascript
			vv+= jsonOBJ({}, -1, val);
		});
		th.html( vv );
		if( set.style ) th.css(set.style);
		if( IE==0 && set.setup.title ) document.title= set.setup.title;

		return true;
	}

	if( LIMIT>0 ) $.extend(pm, {_limit: LIMIT} );		//добавляем NEXT и LIMIT
	$.extend(pm, PARAM);
	if( NC!=null ){ $.extend( pm, { nc:NC } ); NC=null }
	if( THEMA!=null ){ $.extend( pm, { thema:THEMA } ); THEMA=null }

	return $.getJSON(HTTP+ set.setup.url +CALLBACK, pm, function(json){

		if(!_verify(json)) return false;

		if( json['_error'] ){ _error(json['_error'], th); return false }		//if error
		if( json['_warn'] ) _warn(json['_warn'], th);		//if warn

		_ID= json['_id'] || 0;
		if( json['count_obj']!=null ) COUNT_OBJ=json['count_obj'];

		$.each(set.top, function(key, val){		//разворачиваем TOP из javascript
			vv+= jsonOBJ(json, -1, val);
		});

		if( set.style ) th.css(set.style);

		vv+= jsonHTML(set, json['obj']);

		if( set.bottom!=null ) $.each(set.bottom, function(key, val){	//разворачиваем BOTTOM из javascript
			vv+= jsonOBJ(json, -1, val);
		});

		th.html( vv );
		if( IE==0 ) document.title= set.setup.title || nameService;
		if( json['_balans']!=null ) cookSet('balans', json['_balans'], 30);
		if( json['_zerosurf']!=null ) cookSet('zerosurf', json['_zerosurf'], 30);
	})
	.error(function(){ alert("Ошибка подключения!") });
}


function jsonHTML(set, json, style){		//разворачиваем json в соотв. с HTML-объектом

	var vv="";

	if(json) $.each(json, function(n){

		_ID= json[n]['_id'] || 0;
		vv+= "<div class='obj' ie='"+ IE +"' _id='"+ _ID +"' style='"+ (style||"") +"'>";

		$.each(set.obj, function(key, val){		//разворачиваем OBJ из javascript
			vv+= jsonOBJ(json, n, val);
		});

		vv+= "</div>";
	});

	if( LIMIT>0 && $("a.first[ie="+ IE +"]").size()<1 ){		//добавляем кнопки: вперед-назад

		vv+= "<div class='limit'>";
		var pn= PARAM['_next']==null || parseInt(PARAM['_next'])==0 ? 1 : parseInt(PARAM['_next']);
		var next= pn + LIMIT;
		var back= pn - LIMIT;
		var href= IE==0 ? "href='#/" + LOCATION : "id='href' h='";

		if( back>=1 || COUNT_OBJ==LIMIT || COUNT_OBJ==null ) vv+= "<a "+ href +"' act='"+ (next-1>LIMIT?1:0) +"'class='first' ie='"+ IE +"' _id='"+ _ID +"' title='в начало'>&nbsp;</a> "
		if( back>=1 ) vv+= "<a "+ href +"?_next="+ back +"' class='back' ie='"+ IE +"' title='назад'>&nbsp;</a> ";
		if( COUNT_OBJ==LIMIT || COUNT_OBJ==null ) vv+= "<a "+ href +"?_next="+ next +"' class='next' ie='"+ IE +"' title='вперед'>&nbsp;</a>";
		vv+= "</div>";
	}

	return vv;
}


function jsonOBJ(json, n, obj){			//разворачиваем элемент OBJ или TOP из javascript

	var vv="";

	if( $.type(obj)=='object' ){
		$.each(obj, function(key, val){

			ID= n +'-'+ key;
			DATA= n==-1 ? json[key] : json[n][key];

			if( DATA!=null ){

				if( $.type(val)=="string" ){

					$.globalEval(val.search("(^[ ]*|;[ ]*|}[ ]*)return ")==-1 ? "function _valfn(){return "+ val +"}" : "function _valfn(){"+ val +"}");
					vv+= _valfn();
				}
				else{
					vv+= DATA;
				}
			}
		})
	}
	else{
		vv+= obj;
	}

	return vv;
}


//--------------- Другие ф-ции API ---------------//

function ADDING(txt, def, len){			//добавляемые данные
	if(IE>0) _ID= HTML[IE-1]['_id'];
	return "<div id='add' len='"+ (len||85) +"' default='"+ (def||"") +"' ie='"+ IE +"' _id='"+ _ID +"'><img src='/i/icon/plus-table.png' class='im16'/> &nbsp;"+ txt +"</div>";
}

function ADDFORM(txt, name){
	return "<div id='addform' ie='"+ IE +"' _id='"+ _ID +"' name='"+ name +"'><img src='/i/icon/plus-table.png' class='im16'/> &nbsp;"+ txt +"</div>";
}

function ADDONOPEN(txt, url){
	return "<div id='addnoopen' href='"+ url +"'><img src='/i/icon/plus-table.png' class='im16'/> &nbsp;"+ txt +"</div>";
}

function EDIT(txt, type, on, off){		//изменяемые данные

	if( type=="_checkbox" ){
		return "<div class='"+ (txt==1?'checkbox checkboxOn':'checkbox') +"' ie='"+ IE +"' id='"+ ID +"' _id='"+ _ID +"' hid='"+ (on||"") +"'>&nbsp;&nbsp;&nbsp;&nbsp;</div>";
	}
	else if( type=="_onoff" ){
		if( typeof(on)=="undefined" ) on="<span class='on'>включен</span>"; ONOFF[IE+ID]= {on: on};
		if( typeof(off)=="undefined" ) off="<span class='off'>выключен</span>"; $.extend(ONOFF[IE+ID], {off: off});

		return "<span class='edit' type='_onoff' ie='"+ IE +"' id='"+ ID +"' _id='"+ _ID +"' on='"+ txt +"'>"+ (txt==1?on:off) +"</span>";
	}
	else{
		if( typeof(txt)=="undefined"||txt.length==0 ) txt="&hellip;";

		return "<span class='edit' type='default' _type='"+ (type||"") +"' ie='"+ IE +"' id='"+ ID +"' _id='"+ _ID +"'>"+ txt +"</span>";
	}
}

function WINOPEN(txt, url_js, retrn){	//открытие окна в окне

	if( typeof(txt)=="undefined" || txt.length==0 ){ txt="&hellip;" } 
	else if( txt=="_report" ){ txt= "<img class='im16' style='float:right; margin-right:3px' src='/i/icon/report.png'>" }
	HTML[IE+1]= {_id: _ID}; II++;

	return "<span class='winopen' ie='"+ IE +"' _id='"+ _ID +"' ii='"+ II +"' url_js='"+ url_js +"' retrn='"+ (retrn||"") +"'>"+ txt +"</span>";
}

function WOREPLACE(html_1,html_2){

	WOREPLACES[_ID]= html_2;
	return "<span class='woreplace' _id='"+ _ID +"'>"+ html_1 +"</span>";
}

function DELOBJ(txt){		//удаляемый объект

	return txt ?
		"<div class='del_obj' ie='"+ IE +"' _id='"+ _ID +"' txt='"+ txt +"'>&nbsp;</div>" :
		"<div class='del_obj' ie='"+ IE +"' _id='"+ _ID +"'>&nbsp;</div>";
}

function EDITJSON(name){		//изменения json-объекта в окне

	JSONDATA[_ID]= DATA;
	return "<span class='editjson' ie='"+ IE +"' id='"+ ID +"' _id='"+ _ID +"' retrn='"+ (name||"") +"'>"+ (DATA[name]||"&hellip;") +"</span>";
}

function BUTTONSEND(edit,txt,style,conf){

	var confrm= conf ? " txt='"+ conf +"'" : "";

	return "<span class='buttonsend "+ (style||"") +"' ie='"+ IE +"' _id='"+ _ID +"' edit='"+ edit + "' "+ confrm +">"+ txt +"</span>";
}

function FILEUPLOAD(){

	if( PARAM['hash']!=null ){

		cookSet('filekeys', PARAM['hash']);
		setTimeout( function(){ cookSet('filekeys', '', -10) }, TIMEFILEKEYS*60000);
		PARAM['hash']= null;

		var regex= new RegExp(REFERER);
		_redirect(REFERER==null||regex.test(SETUP.url)?"/a/account":REFERER);
	}

	cookParam();

	return "<iframe id='rFrame' name='rFrame' style='display:none'></iframe>" +
		"<form action='"+ HTTP + SETUP.url +"' target='rFrame' method='POST' enctype='multipart/form-data'>" +
		"<input type='hidden' name='_data' value='"+ cook['data'] +"'><input type='file' name='file'>" +
		"<p><input type='submit' value='Загрузить'></form></p>";
}


function HELPDIV(div){

	return "<div id='helpdiv' href='"+ div +"' title='помощь по разделу'></div>";
}


function REFRESH(){

	return "<div id='refresh' title='обновить страничку'></div>";
}

//--------------- Добавление obj (add) ---------------//

$(document).ready( function(){

	$("#add").live( "click", function(){			//открываем окошко для добавления

		if(STOP==1) return false; STOP=1;
		var th= $(this);
		var _id= th.attr('_id') || 0;
		var len= th.attr('len') || 33;
		var def= th.attr('default') || "";

		var form= "<form name='my'>";
		form+= "<input type='text' size='"+ len +"' name='new' value='"+ def + "'/> ";
		form+= "<input type='hidden' name='_new' value='1'>";
		form+= "<input type='hidden' name='_id' value='"+ _id +"'>";
		form+= "<div id='addsubmit'>&raquo;</div>";
		form+= "</form>";

		th.append("<div class='window' id='w0'>"+ form +"</div>");
		var winth= $("#w0").fadeIn().uPosition(th).css('padding','20px');
		$('input[name=new]').focus();

		winth.live( "mouseleave", function(){ $("body").live( "click", function(){ STOP=0; uCloseWindow(winth) }) });
		return false;
	});

	$("#add").live( "keypress", function(e){		//защита от нажатия на Enter
		if(e.which==13) return false;
	});

	$("#addsubmit").live( "click", function(){		//отправляем данные формы из окошка, получаем и вставляем ответ

		STOP++;
		var th= $(this);
		var thFm= th.closest("form[name=my]");
		var thWin= th.closest("div.window");

		$.getJSON(HTTP+ HTML[IE]['setup']['url'] +CALLBACK, thFm.serializeArray(), function(json){

			if(!_verify(json)) return false;

			if( json['_warn'] ) _warn(json['_warn'], th);		//if warn

			if( json['_error'] ){ _error(json['_error'], th) }	//if error
			else{
				$.getScript(HTML[IE]['url_js'], function(){

					var rez= jsonHTML( {setup:SETUP, obj:OBJ}, json, "display:none" );

					var thObj= IE==0 ? $("#api") : $("div.winopen");
					var thApp= $("div.obj:first", thObj);
					thApp.size()>0 ? thApp.before( rez ) : thObj.append( rez );

					$("div.obj:hidden", thObj).show(600);
				});
			}

			uCloseWindow(thWin);
			STOP= 0;
		});

		thWin.jImgLoad();
		return false;
	});


//--------------- Добавление obj (addform) ---------------//

	$("#addform").live( "click", function(){			//открываем окошко для добавления формы

		if(STOP==1) return false; STOP=1;
		var th= $(this);
		var _id= th.attr('_id') || 0;
		var name= th.attr('name') || "";

		var form= "<form name='my'>";
		$.each( FORMS[name], function(i, val){
			form+= val + "<br/>";
		});
		form+= "<p><input type='button' id='addformsend' value='Отправить'/></p>";
		form+= "<input type='hidden' name='_id' value='"+ _id +"'/>";
		form+= "<input type='hidden' name='_new' value='1'/>";
		form+= "<input type='hidden' name='type' value='1'/>";
		form+= "</form>";

		th.append("<div class='window' id='f0'>"+ form +"</div>");
		var winth= $("#f0").fadeIn().uPosition(th).css('padding','20px');

		winth.live( "mouseleave", function(){ $("body").live( "click", function(){ STOP=0; uCloseWindow(winth) }) });
		return false;
	});

	$("#addformsend").live( "click", function(){		//отправляем данные формы из окошка, получаем и вставляем ответ

		STOP++;
		var th= $(this);
		var thFm= th.closest("form");
		var thWin= th.closest("div.window");

		$.getJSON(HTTP+ HTML[IE]['setup']['url'] +CALLBACK, thFm.serializeArray(), function(json){

			if(!_verify(json)) return false;

			if( json['_warn'] ) _warn(json['_warn'], th);		//if warn

			if( json['_error'] ){ _error(json['_error'], th) }	//if error
			else{
				$.getScript(HTML[IE]['url_js'], function(){

					var js= json['obj']==null ? json : json['obj'];
					var rez= jsonHTML( {setup:SETUP, obj:OBJ}, js, "display:none" );

					var thObj= IE==0 ? $("#api") : $("div.winopen");
					var thApp= $("div.obj:first", thObj);
					thApp.size()>0 ? thApp.before( rez ) : thObj.append( rez );

					$("div.obj:hidden", thObj).show(600);
				});
			}

			uCloseWindow(thWin);
			STOP= 0;
		});

		thWin.jImgLoad();
		return false;
	});

//--------------- Изменение данных в окошке ---------------//

	$("span.edit[type=default]").live( "click", function(){		//открываем окошко

		var th= $(this);
		var id= th.attr('id');
		var _id= th.attr('_id') || 0;
		var type= th.attr('_type');
		var txt= th.text() || "";
		var data= th.attr('data') || 0;
		$.extend(HTML[IE], { _id:_id });

		var form= "<form name='my'>";

		if( type.length>0 ){
			$.each(FORMS[type], function(key, val){
				form+= val
			});
		}
		else{
			var ln= txt && txt.length>0 ? Math.floor(txt.length * 1.3) : 10;
			if(ln<5) ln=5; if(ln>120) ln=120;

			form+= "<input type='text' size='"+ ln +"' id='f"+ id +"' name='edit' value=''/> ";
			form+= "<div class='submit'>&raquo;</div>";
		}

		for( var i=0; i<=IE; i++ ){
			form+= "<input type='hidden' name='_id' value='"+ HTML[i]['_id'] +"'>";
		}

		form+= "<input type='hidden' name='id' value='"+ id +"'>";
		form+= "<input type='hidden' name='_edit' value='1'>";
		form+= "</form>";

		th.append("<div class='window' id='w"+ id +"' _id='"+ _id +"'>"+ form +"</div>");
		var winth= $("#w"+ id).fadeIn().uPosition(th)._design();
		if( type=='' ) $('#f'+ id).focus();

		winth.live( "mouseleave", function(){ $("body").live( "click", function(){ STOP=0; uCloseWindow(winth) }) });
		return false;
	});

	$("span.edit").live( "keypress", function(e){		//защита от нажатия на Enter
		if(e.which==13) return false;
	});

	$("div.submit, div.radio").live( "click", function(e){		//отправляем данные формы из окошка, получаем и вставляем ответ
		STOP++;

		var th= $(this).closest("div.window");
		var thFm= $(this).closest("form[name=my]");
		var id= $("[name=id]", thFm).attr('value');
		var _id= th.attr('_id');

		if(IE>0) _rnd(HTML[IE-1]['_id'], 1);	//убираем кэширование

		var serial= thFm.serializeArray();
		if( $(this).attr('edit') ) serial.push( { name:'edit', value:$(this).attr('edit') } );
		if( $(this).attr('edit') ) serial.push( { name:'r', value:_rnd(0,1) } );

		$.getJSON(HTTP+ HTML[IE]['setup']['url'] +CALLBACK, serial, function(json){

			if(!_verify(json)) return false;

			if( json['_warn'] ) _warn(json['_warn'], th);		//if warn
			if( json['_error'] ){ _error(json['_error'], th) }	//if error
			else{
				RETURN[IE]= json.edit;

				$("span.edit[type!=_onoff][_id="+_id+"][id="+id+"][ie="+IE+"]").html(_edit(json.edit));

				if( json['edit_id']!=null ){	//if есть доп. изменения
					$("span.edit[type!=_onoff][_id="+_id+"][id=0-"+json['edit_id']+"][ie="+IE+"]").html(json['edit_val']);
				}
			}
			uCloseWindow(th);
			STOP= 0;
		});

		th.jImgLoad();
		e.stopImmediatePropagation();
		return false;
	});

	//----------------------------------------//

	$("div.checkbox, div.checkboxOn").live( "click", function(){		//отправляем данные из checkbox

		$("div.window").live( "click", function(){ STOP=1 });
		if( STOP==1 ){ STOP=0; return false }

		var th= $(this);
		var id= th.attr('id');
		var _id= th.attr('_id');
		var hid= th.attr('hid')||"";
		var on= th.hasClass("checkboxOn");
		$.extend(HTML[IE], { _id:_id });
		var num= $("div.checkbox[id="+ id +"]").index(th);

		if(IE>0) _rnd(HTML[IE-1]['_id'], 1);	//убираем кэширование

		var serial= serialPush({ _edit: 1, edit: on?0:1, hidden: hid, id: id+'-'+num });

		$.getJSON(HTTP+ HTML[IE]['setup']['url'] +CALLBACK, serial, function(json){

			if(!_verify(json)) return false;

			if( json['_error'] ){ _error(json['_error'], th) }	//if error
			else{ th.toggleClass("checkboxOn") }

			if( json['_warn'] ) _warn(json['_warn'], th);		//if warn

			if( json['_data']!=null ) cookSet('data', json['_data'], 60);

			RETURN[IE]= json.edit;
			uCloseWindow(winth);
		});

		th.append("<div class='window' id='w"+ id +"'></div>");
		var winth= $("#w"+ id).fadeIn().uPosition(th).jImgLoad();
		return false;
	});


	$("span.checkselect").live( "click", function(){			//отправляем данные из checkselect (группой)

		var thSel=$(this), _id, id_mas=[], edit_mas=[];
		var idsel= thSel.attr('select');

		$("checkselect[select="+ idsel +"] div.checkbox").each( function(key, val){

			var th= $(val);
			var id= th.attr('id');
			_id= th.attr('_id');
			var on= th.hasClass("checkboxOn");
			var num= $("div.checkbox[id="+ id +"]").index(th);

			id_mas.push( id+'-'+num );
			edit_mas.push( on?0:1 );
		});

		$.extend(HTML[IE], { _id:_id });
		if(IE>0) _rnd(HTML[IE-1]['_id'], 1);	//убираем кэширование

		var serial= serialPush({ _edit: 1, edit: edit_mas, id: id_mas });

		$.getJSON(HTTP+ HTML[IE]['setup']['url'] +CALLBACK, serial, function(json){

			if(!_verify(json)) return false;

			if( json['_error'] ){ _error(json['_error'], th) }	//if error
			else{
				$("checkselect[select="+ idsel +"] div.checkbox").toggleClass("checkboxOn");
			}

			if( json['_warn'] ) _warn(json['_warn'], th);		//if warn

			uCloseWindow(winth);
		});

		thSel.append("<div class='window' id='w"+ _id +"'></div>");
		var winth= $("#w"+ _id).fadeIn().uPosition(thSel).jImgLoad();
		return false;
	})


	$("span.edit[type=_onoff]").live( "click", function(e){		//отправляем данные _onoff

		var th= $(this);
		var id= th.attr('id');
		var _id= th.attr('_id');
		var on= th.attr('on');
		$.extend(HTML[IE], { _id:_id });

		//if(IE>0) _rnd(HTML[IE-1]['_id'], 1);	//убираем кэширование

		var serial= serialPush({ _edit: 1, edit: on==1?0:1, id: id });

		$.getJSON(HTTP+ HTML[IE]['setup']['url'] +CALLBACK, serial, function(json){

			if(!_verify(json)) return false;

			if( json['_error'] ){ _error(json['_error'], th) }	//if error
			else{
				th.html(json.edit==1 ? ONOFF[IE+id]['on'] : ONOFF[IE+id]['off']);
				th.attr('on', json.edit==1 ? 1 : 0 );
			}

			if( json['_warn'] ) _warn(json['_warn'], th);		//if warn

			uCloseWindow(winth);
		});

		th.append("<div class='window' id='w"+ id +"'></div>");
		var winth= $("#w"+ id).fadeIn().uPosition(th).jImgLoad();

		e.stopImmediatePropagation();
		return false;
	})
});


//--------------- Окно в окне ---------------//

$(document).ready( function(){

	var _id;

	$("span.winopen").live( "click", function(ee){

		var winopen;
		TH= $(this); 
		_id= TH.attr('_id') || 0;
		var ii= TH.attr('ii') || 0;
		var url_js= TH.attr('url_js');
		var retrn= TH.attr('retrn');
		var ie= parseInt( TH.attr('ie') ) || 0;
		$.extend(HTML[IE], { _id:_id });
		IE= ie + 1;
		if(PARAM['_id']!=null) delete PARAM['_id'];

		$("span.woreplace[_id="+_id+"]").html(WOREPLACES[_id]);		//замена html-кода в объекте при открытии окна

		$("#body").remove();
		var hd= $(document).height();
		var label= "winopen" + IE + ii;

		$("body").append("<div id='body' ie='"+ IE +"'></div>");
		$("#body").jOpacity(0.7).css('height', hd);

		if( $("div[id="+ label +"]").size()>0 && $("a.first[ie=1]").size()<1 ){	//if окно в DOM уже есть
			$("div[id="+ label +"]").fadeIn(600).jCenter();
		}
		else{		//if нет
			if(PARAM['_next']!=null) PARAM['_next']=0;
			$("div.winopen, a.first[ie=1], a.next[ie=1], a.back[ie=1]").remove();
			$("body").append("<div class='winopen' id='"+ label +"'></div>");

			var winopen= $("div[id="+ label +"]").fadeIn("fast").jImgLoad().jCenter();

			$.getScript(url_js, function(){

				$.extend(HTML[IE], {setup:SETUP, url_js:url_js});

				$.when(
					getAPI(winopen, {setup:SETUP, obj:OBJ, style:STYLE, top:TOP, bottom:BOTTOM}, {_id:_id, r:_rnd(_id)})
				).then( function(){
					winopen.append("<img src='/i/icon/del.gif' id='close' class='im16'/>").jCenter()
				})
			})
		}

		$("#close, #body").live( "click", function(){		//закрываем окно

			if( retrn && RETURN[IE] ) TH.html(RETURN[IE]);
			if( retrn && RETURN['_return']!=null ){
				TH.html(RETURN['_return']);
				RETURN['_return']= null;
			}

			uCloseWindow( $("div[id=body][ie="+ IE +"]").fadeOut(300) );
			$("div[id^=winopen"+ IE +"]").fadeOut(200);
			$("div.window, div#ej").remove();
			IE--; if( IE<0 ) IE=0;
		});


		ee.stopImmediatePropagation();
		return false;
	});

	$("#href").live( "click", function(e){			//псевдо хэш-навигация в окне

		COUNT_OBJ= null;
		var newHash= $(this).attr('h');
		var quest= newHash.split('?')[1];
		if( quest==null ){ PARAM= {} }
		else{ questParam(quest) }

		if( $(this).attr('act')==0 ) return false;

		$.when(
			getAPI($("div.winopen"), {setup:SETUP, obj:OBJ, style:STYLE, top:TOP, bottom:BOTTOM}, {_id:_id})
		).then( function(){
			$("div.winopen").append("<img src='/i/icon/del.gif' id='close' class='im16'/>").jCenter()
		});

		e.stopPropagation();
		return false;
	})
});


function uCloseWindow(th, th2){		//закрываем доп. окно

	setTimeout( function(){
		setTimeout( function(){
			$(th).fadeOut(0, function(){
				$(this).remove();
				STOP=0;
			});
		}, STOP?1500:1 )
	}, jQuery.browser.msie && !th2 ? 750 : 200 );

	if(th2){
		$(th2).fadeOut("fast", function(){
			$(this).remove()
		});
	};
}


//--------------- Удаление объекта ---------------//

$(document).ready( function(){

	$("div.del_obj").live( "click", function(){

		var th= $(this);
		var _id= th.attr('_id');
		var ie= parseInt( th.attr('ie') ) || 0;
		$.extend(HTML[IE], { _id:_id });

		_delobj(th).done( function(){

			th.addClass('del_obj_load');

			var serial= serialPush({ _del:1 });

			$.getJSON(HTTP+ HTML[IE]['setup']['url'] +CALLBACK, serial, function(json){

				if(!_verify(json)) return false;

				if( json['_error'] ){		//if error
					_error(json['_error'], th);
					th.removeClass('del_obj_load');
				}
				else{
					if( json['_warn'] ) _warn(json['_warn'], th);		//if warn
					$("div.obj[ie="+ ie +"][_id="+ _id +"]").hide(500, function(){ $(this).remove() })
				}
			})
			return false;
		})
	})
});

//--------------- Отправка формы методом POST ---------------//

$(document).ready( function(){

	$("form input").live( "keypress", function(e){		//защита от нажатия на Enter
		if(e.which==13) return false;
	});

	$("#sendform, #step_end").live( "click", function(e){

		var th= $(this);
		var val= th.html();
		var thFm= $(this).closest("form");

		var serial= thFm.serializeArray();
		serial.push( { name:'_edit', value:1 } );

        $.ajax({
            url: HTTP+ HTML[IE]['setup']['url'] +CALLBACK,
			type: "POST",
			data: serial,
			dataType: "json",
			success: function(json){

				if(!_verify(json,1)) return false;

				if( json['_warn'] ){		//if warn
					th.html(val);
					_warn(json['_warn'], th);
				}
				if( json['_error'] ){		//if error
					th.html(val);
					_error(json['_error'], th);
				}
				else{
					if( json['edit']!=null ) thFm.html(json['edit']);
					return false
				}
			}
		});

		th.jImgLoad();
		e.stopImmediatePropagation();
		return false;
	})
});

//--------------- Изменение json-структуры и json-данных в окне ---------------//

$(document).ready( function(){

	$("span.editjson").live( "click", function(){

		if(STOP==1) return""; STOP=1;
		var th= $(this);
		var _id= th.attr('_id');
		var id= th.attr('id');
		var retrn= th.attr('retrn');
		var ie= parseInt( th.attr('ie') ) || 0;

		DATA= JSONDATA[_id];
		$("body").append("<div class='win_editjson' id='ej' _id='"+ _id +"' style='display:none'>"+ _EDITJSON() +"<p><span id='editjson'>Сохранить</span></p></div>");
		$("#ej").append("<img src='/i/icon/del.gif' id='close_editjson' class='im16'/>").fadeIn(500).jCenter();
		var intID= setInterval(function(){$("#ej").jCenter()}, 700);

		$("#editjson").live( "click", function(e){

			var _id= $(this).closest("#ej").attr('_id');

			clearInterval(intID);
			$.extend(HTML[IE], { _id:_id });
			JSONDATA[_id]= DATA;
			uCloseWindow($("#ej").jImgLoad().jCenter());

			var serial= serialPush({ _edit: 1, edit: $.toJSON(DATA), id: id });

			$.getJSON(HTTP+ HTML[IE]['setup']['url'] +CALLBACK, serial, function(json){

				if( json['_warn'] ) _warn(json['_warn'], th);		//if warn

				if( json['_error'] ){ _error(json['_error'], th) }	//if error

				else if( retrn ){
					$("span.editjson[_id='"+ _id +"']").html(DATA[retrn])
				}
			})
			
			e.stopImmediatePropagation();
			return false;
		});

		$("#close_editjson").live( "click", function(){
			uCloseWindow($("#ej").fadeOut(300))
		})
	})
});
 

//--------------- Отправляем данные с кнопки button ---------------//

$(document).ready( function(){

	$("span.buttonsend").live( "click", function(e){

		var th= $(this);
		var _id= th.attr('_id');
		var edit= th.attr('edit');
		var val= th.html();
		$.extend(HTML[IE], { _id:_id });

		var serial= serialPush({ _edit:1, edit:edit });

		_delobj(th).done( function(){

			$.getJSON(HTTP+ HTML[IE]['setup']['url'] +CALLBACK, serial, function(json){

				if(!_verify(json)) return false;

				if( json['_warn'] ){		//if warn
					th.html(val);
					_warn(json['_warn'], th);
				}
				if( json['_error'] ){		//if error
					th.html(val);
					_error(json['_error'], th);
					return false;
				}
				else{
					if( json['edit']!=null ) th.html(json['edit']);
					return false
				}
			});

			th.jImgLoad();
		});

		e.stopImmediatePropagation();
		return false;
	});

	//--------------- Отправка сообщения feedback ---------------//

	$("#feedback").live( "click", function(){			//открываем окошко для добавления формы

		if(STOP==1) return false; STOP=1;
		var th= $(this);
		var name= th.attr('name') || "";

		var form= "<form>";
		form+= "<p><span class='B'>Ваш e-mail для связи:</span> <input type='email' size='40' name='email'/></p>";
		form+= "<p><span class='B'>Ваш вопрос:</span><br/><textarea cols='55' rows='7' name='message'></textarea></p>";
		form+= "<p><input type='button' id='feedbacksend' value='Отправить'/></p>";
		form+= "<input type='hidden' name='name' value='"+ name +"'/>";
		form+= "<input type='hidden' name='_new' value='1'/>";
		form+= "</form>";

		$("body").append("<div class='window' id='f3'>"+ form +"</div>");
		var winth= $("#f3").fadeIn().uPosition(th).css('padding','20px');

		winth.live( "mouseenter mouseleave", function(e){
			e.type=="mouseleave" ?
				$("body").bind( "click.ev", function(){ STOP=0; uCloseWindow(winth) }) :
				$("body").unbind("click.ev");
		 });

		return false;
	});

	$("#feedbacksend").live( "click", function(){		//отправляем данные формы из окошка, получаем и вставляем ответ

		STOP=1;
		var th= $(this);
		var thFm= th.closest("form");
		var thWin= th.closest("div.window");

		$.getJSON(HTTP+ "/api/r/message" +CALLBACK, thFm.serializeArray(), function(json){

			if(!_verify(json)) return false;

			if( json['_warn'] ) _warn(json['_warn'], th);		//if warn

			if( json['_error'] ){ _error(json['_error'], th); uCloseWindow(thWin) }	//if error
			else{
				thWin.html("Ваше сообщение отправлено.<p>Сохраните ссылку с перепиской: <a href='"+ json['link'] +"' target='_blank'>"+ json['link'] +"</a></p><p class='small jystify'>"+ json['message'] +"</p>")
			}
		});

		thWin.jImgLoad();
		return false;
	})
});


//--------------- Переадресовываем на другую страничку ---------------//

$(document).ready( function(){

	$("#addnoopen").live( "click", function(){
		var path= $(this).attr('href');
		location.replace(path+'?'+_rnd(0,1));
	});

	$("#refresh").live( "click", function(){
		location.replace('#'+ LOCATION +'?'+ _rnd(0,1));
	})
});


//--------------- Другие ф-ции ---------------//

function EXITSERVICE(){			//выход из сервиса

	cookSet('data', '', -10);
	cookSet('filekeys', '', -10);
	cookSet('email', '', -10);
	cookSet('balans', '', -10);
	cookSet('id_partner', '', -10);
	$("#message").html("");
}


function _verify(json, wr){			//проверяем есть ли редирект

	if( json['_warn']!=null && wr!=null ){ _warn(json['_warn']) }
	if( json['_function']!=null ){ _function(json) }
	if( json[0]!=null && json[0]['_return']!=null ) RETURN['_return']=json[0]['_return'];
	else if( json['_return']!=null ) RETURN['_return']=json['_return'];

	if( json['_email']!=null ) cookSet('email', json['_email'], 60);
	if( json['_data']!=null ) cookSet('data', json['_data'], 60);
	if( json['_balans']!=null ) cookSet('balans', json['_balans'], 30);
	if( json['_balans_redeem']!=null ) cookSet('balans_redeem', json['_balans_redeem']);
	if( json['_invoice']!=null ) cookSet('invoice', json['_invoice'], 30);

	if( json['_redirect']!=null ){	//if redirect

		$("#body").remove();
		$("div.winopen, a.first[ie=1], a.next[ie=1], a.back[ie=1]").remove();
		IE= 0; _redirect(json['_redirect']);
		return false
	}
	return true
}


function serialPush(e){		//создание массива параметров для передачи через ajax

	var serial= [];

	for( var i=0; i<=IE; i++ ){
		if(HTML[i]['_id']) serial.push({ name: '_id', value: HTML[i]['_id'] });
	}

	for( key in e ){
		serial.push({ name: key, value: e[key] });
	}

	serial.push( { name:'r', value:_rnd(0,1) } )

	return serial;
}


function _delobj(th){		//запрос на удаление объекта

	_DELOBJ= $.Deferred();

	var txt= th.attr('txt') || false;
	if( !txt ){ _DELOBJ.resolve(); return _DELOBJ }

	$("#confirm").remove();
	$("body").append("<div id='confirm'>"+ txt +"</div>");
	$("#confirm").append("<p class=T10><div><span id='confirm_true'>OK</span>&nbsp;&nbsp;&nbsp;<span id='confirm_false'>Отмена</span></div></p>").fadeIn().uPosition(th);

	$("#confirm_true").click( function(){
		$("#confirm").remove();
		_DELOBJ.resolve();
	});
	$("#confirm_false").click( function(){
		$("#confirm").remove();
		_DELOBJ.reject();
	});

	return _DELOBJ;
}

function _error(e, th){		//error

	alert(e);
}

function _warn(e, th){		//warn

	alert(e);
}


function _rnd(_id, up){		//управление кэшированием

	if( up||!_RND[_id] ) _RND[_id]= Math.ceil( Math.random()*1000000 );
	return _RND[_id];
}


function _edit(e){		//замена пустого значения

	if( typeof(e)=="undefined" || e==null ) e="&hellip;";
	return e;
}


function questParam(e){		//разделяем параметры в объект
	var qmas= e.split(/\&+/);
	for(i=0;i<qmas.length;i++){ var p=qmas[i].split('='); PARAM[p[0]]=p[1] }
}


function cookParam(){		//получаем кукисы
	var qmas= document.cookie.split(/;[ ]+/);
	for(i=0;i<qmas.length;i++){ var p=qmas[i].split('='); cook[p[0]]=p[1] }
}


function cookSet(name, val, days, path){		//устанавливаем кукисы

	var ed= new Date(); ed.setTime(ed.getTime() + days*24*3600*1000);
	var dom= document.domain.replace(/^www\./i, "");
	document.cookie= name +"="+ escape(val) +
		((days==null||days==0) ? "" : ("; expires="+ ed.toGMTString())) + ("; path="+ ((path==null) ? "/" : path)) +"; domain=."+ dom;
}


$.fn._design= function(){	//дизайн эл. формы

	$(this).find("input:radio").each( function(key, val){
		var v= $(val).val();
		var t= $(val).parent().text();
		$(val).parent().html("<div class='radio' edit='"+ v +"'>"+ t +"</div>");
	});

	$(this).find("select option").each( function(key, val){
		var v= $(val).val();
		var t= $(val).text();
		$(this).parent().parent().append("<p><div class='radio' edit='"+ v +"'>"+ t +"</div></p>");
	}).parent().remove();

	return this;
}

$.fn.uPosition= function(th){	//определяем абс. коорд. и позиционируем окно

	var os= $(th).offset(), winth= $(this), w= $(window);
	winth.css({top: os.top-w.scrollTop(), left: os.left+w.scrollLeft()});

	setTimeout( function(){		//смещаем, если вылазит за окно монитора
		var p= w.height()-winth.outerHeight()-os.top+w.scrollTop();
		if(p<0) winth.css('top', w.height()-winth.outerHeight());

		p= w.width()-winth.outerWidth()-os.left+w.scrollLeft();
		if(p<10) winth.css('left', os.left+p-7);
	}, 200 );

	setTimeout( function(){		//смещаем, если вылазит за окно монитора
		var p= w.height()-winth.outerHeight()-os.top+w.scrollTop();
		if(p<0) winth.css('top', w.height()-winth.outerHeight());

		p= w.width()-winth.outerWidth()-os.left+w.scrollLeft();
		if(p<10) winth.css('left', os.left+p-7);
	}, 1200 );

	return this;
}

$.fn.jCenter= function(){
	var w= $(window);
	$(this).css('position', 'absolute');
	$(this).css('left', (w.width()-$(this).width())/2+w.scrollLeft()+'px');

	var wScroll= w.scrollTop(); if(wScroll<=0) wScroll=1;
	var objH= $(this).outerHeight();
	var top= (w.height()-objH)/2 + wScroll;
	var maxH= parseInt(w.height()/1.07) + 'px';

	if( top<=0 ){ $(this).css({top: '1px', height: maxH}) }
	else if( top>0 && objH<=w.height() ){ $(this).css('top', top+'px') }
	else if( top>0 && objH>w.height() ){ $(this).css({height: maxH, top: wScroll+'px'}) }

	return this;
}

$.fn.jOpacity= function(p){
	$(this).css({'filter':'alpha(opacity='+p*100+')','-moz-opacity': p,'opacity': p});
	return this;
}

$.fn.jImgLoad= function(c){	//изображение загрузки
	this.html('<img style="z-index:101; margin-left:'+(c?c:0)+'%;" src="data:image/gif;base64,R0lGODlhCgAKAJEDAMzMzFJSUgAAAP///yH/C05FVFNDQVBFMi4wAwEAAAAh+QQFAAADACwAAAAACgAKAAACF5wncgaAGgJzJ647cWua4sOBFEd62VEAACH5BAUAAAMALAEAAAAIAAMAAAIKnBM2IoMDAFMQFAAh+QQFAAADACwAAAAABgAGAAACDJwHMBGofKIRItJYAAAh+QQFAAADACwAAAEAAwAIAAACChxgOBPBvpYQYxYAIfkEBQAAAwAsAAAEAAYABgAAAgoEhmPJHOGgEGwWACH5BAUAAAMALAEABwAIAAMAAAIKBIYjYhOhRHqpAAAh+QQFAAADACwEAAQABgAGAAACDJwncqi7EQYAA0p6CgAh+QQJAAADACwHAAEAAwAIAAACCpRmoxoxvQAYchQAOw=="/>');
	return this;
}


//--------------- Открываем-закрываем часть контента ---------------//

$(document).ready( function(){
	$('#hidden_click').live( 'click', function(){
		$('#hidden_view').toggle("slow");
		$('#hidden_click').toggleClass("hidden_click_on");
	});
});


//--------------- Plug and Play ---------------//

$(document).ready( function(){
	$('div.plugandplay').live( 'mousedown mouseup', function(e){
		if(e.type == "mousedown"){

			var th= $(this).closest("div.window");
			var p= th.offset();
			var dt= e.pageY - p.top, dl= e.pageX - p.left;

			$(document).bind( 'mousemove.ex', function(ee){ 
				th.css({position:'fixed', top: parseInt(ee.pageY-dt)+'px', left: parseInt(ee.pageX-dl)+'px'});
			})
		}
		else{ $(document).unbind('.ex') }
	});
});

//--------------- Всплывающая помощь при наведении на help ---------------//

$(document).ready( function(){

	$("i.help").live( "mouseenter mouseleave", function(e){

		var th= $(this);
		var wt= th.attr('width');

		if(e.type == "mouseenter"){
	
			$("#winhelp").remove();
			th.append("<div id='winhelp'></div>");
			$("#winhelp").fadeIn("fast").uPosition(this).jImgLoad();
			if( wt!=null ) $("#winhelp").css({maxWidth: wt+'px'});

			var href= th.attr("src").split("#");

			$.getJSON(PATH +'help/'+ href[0] +'.json', function(json){

				var vv= "";
				if( json && json[href[1]] ){
					if( $.type(json[href[1]]) == 'array' ){		//if array
						$.each(json[href[1]], function(key, val){
							vv+= val;
						});
					}
					else{ vv= json[href[1]] }
				}
				else{ vv= "По данному разделу пока нет помощи" }
				$("#winhelp").html(vv);
			})
		}
		else{
			setTimeout( function(){ $("#winhelp").remove() }, 50);
			$("#winhelp").fadeOut("fast")
		}
	})
});


//--------------- Помощь по разделу ---------------//

$(document).ready( function(){

	$("#helpdiv").live( "click", function(e){

		var href= $(this).attr('href');

		$("body").append("<div class='helpdiv'></div><img src='/i/icon/del.gif' id='close_helpdiv' class='im16'/>");
		$("div.helpdiv").jImgLoad();

		$.getJSON(PATH +'helpdiv/'+ href +'.json', function(json){

			var vv= "<div class='title'>Помощь по разделу</div>";

			for(var i=0;i<json.length;i++){

				vv+= "<p><img src='/i/icon/bullet_g.png' class='im16'/> <span id='helpdiv_"+ i +"' class='helpdiv'>"+ json[i]['question'] +"</span>";
				vv+= "<div class='helpdiv_none' id='helpdiv_"+ i +"'>";

				$.each( json[i]['answer'], function(ii, t){
					vv+= t
				})
				vv+= "</div></p>";
			}

			$("div.helpdiv").html(vv);
		})
	});

	$("span[id*=helpdiv_]").live( "click", function(){
		$("div[id="+ $(this).attr("id") +"]").slideToggle();
	});

	$("#close_helpdiv").live( "click", function(){
		$("div.helpdiv").remove();
		$("#close_helpdiv").remove();
	})
});


//--------------- Получение содержимого файла .json со своего сервера ---------------//
// JSONFILE(path, name), где: path - путь к файлу, name - имя в json (json[name])

function JSONFILE(path, name){

	var ir= _rnd(path);

	$.getJSON(path, {r: ir}, function(json){

		var vv="";
		if( json ){ vv= name==null ? json : json[name] }
		$("#jsonfile"+ ir).html(vv);

		return false;
	});

	return "<span id='jsonfile"+ ir +"'>&hellip;</span>";
}


//--------------- Получение содержимого файла .json с основного сервера ---------------//
// JSONFILE(th, h1, h2, path, name), где:
// h1, h2 - добавочный html до (или если нет файла) и после получения файла
// path - путь к файлу, name - имя в json (json[name])

function jsonfileremote(th, h1, h2, path, name){

	var ir= _rnd(path,1);
	var val= th.html();

	$.getJSON(HTTP+ path +CALLBACK, {r: ir}, function(json){

		var vv="";
		if( json ){ vv= name==null ? json : json[name] }
		th.html(h2+vv);

		return false;
	});

	return h1;
}


//--------------- Сериализация json ---------------//

(function($){$.toJSON=function(o){var type=typeof(o);if(o===null)return"null";if(type=="undefined")return undefined;if(type=="number"||type=="boolean")return o+"";if(type=="string")return $.quoteString(o);if(type=='object'){if(typeof o.toJSON=="function")return $.toJSON(o.toJSON());if(o.constructor===Array){var ret=[];for(var i=0;i<o.length;i++)ret.push($.toJSON(o[i])||"null");return"["+ret.join(",")+"]"}var pairs=[];for(var k in o){var name;var type=typeof k;if(type=="number")name='"'+k+'"';else if(type=="string")name=$.quoteString(k);else continue;if(typeof o[k]=="function")continue;var val=$.toJSON(o[k]);pairs.push(name+":"+val)}return"{"+pairs.join(", ")+"}"}};$.quoteString=function(string){if(string.match(_escapeable)){return'"'+string.replace(_escapeable,function(a){var c=_meta[a];if(typeof c==='string')return c;c=a.charCodeAt();return'\\u00'+Math.floor(c/16).toString(16)+(c%16).toString(16)})+'"'}return'"'+string+'"'};var _escapeable=/["\\\x00-\x1f\x7f-\x9f]/g;var _meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'&quot;','\\':'\\\\'}})(jQuery);

//--------------- Изменение хэша в URL ---------------//

(function($,e,b){var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);function a(j){j=j||location.href;return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")}$.fn[c]=function(j){return j?this.bind(c,j):this.trigger(c)};$.fn[c].delay=5;g[c]=$.extend(g[c],{setup:function(){if(d){return false}$(f.start)},teardown:function(){if(d){return false}$(f.stop)}});f=(function(){var j={},p,m=a(),k=function(q){return q},l=k,o=k;j.start=function(){p||n()};j.stop=function(){p&&clearTimeout(p);p=b};function n(){var r=a(),q=o(m);if(r!==m){l(m=r,q);$(e).trigger(c)}else{if(q!==m){location.href=location.href.replace(/#.*/,"")+q}}p=setTimeout(n,$.fn[c].delay)}$.browser.msie&&!d&&(function(){var q,r;j.start=function(){if(!q){r=$.fn[c].src;r=r&&r+a();q=$('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){r||l(a());n()}).attr("src",r||"javascript:0").insertAfter("body")[0].contentWindow;h.onpropertychange=function(){try{if(event.propertyName==="title"){q.document.title=h.title}}catch(s){}}}};j.stop=k;o=function(){return a(q.location.href)};l=function(v,s){var u=q.document,t=$.fn[c].domain;if(v!==s){u.title=h.title;u.open();t&&u.write('<script>document.domain="'+t+'"<\/script>');u.close();q.location.hash=v}}})();return j})()})(jQuery,this);

