<!--

//2. Поиск подстроки  subString в строке fullString. Возвращает подстроку от первого знака subString до последнего знака в строке fullString.
function rightBackString(fullString, subString) {
	if (fullString.lastIndexOf(subString) == -1) {
		return "";
	} else {
		return fullString.substring(fullString.lastIndexOf(subString)+1, fullString.length);
	}
}


var include_once_cache={}, include_once_callback={};
function include_once(url, callback){
	//var ext=rightBackString(url,'.');
	//if (ext=='js') $.xLazyLoader({js: url});
	//else if (ext=='css') $.xLazyLoader({css: url});
	//else if (ext=='gif' || ext=='jpg'  || ext=='jpeg'  || ext=='png') $.xLazyLoader({image: url});
	
		

	if (!include_once_callback[url]) include_once_callback[url]=new Array();
	include_once_callback[url].push(callback); 

	
	if (include_once_cache[url]==2) callback(url);
	if (include_once_cache[url]) return; // запрос ущел, но еще не выполнился
	
	$.ajax({
			type: "GET",
			url: url,
			success://callback,
			
			function(){
				include_once_cache[url]=2;
				
				for (var i = 0; i < include_once_callback[url].length; i++){
					include_once_callback[url][i]();
				}
				
			},
			
			dataType: "script",
			cache: true
	});
	
	include_once_cache[url]=1;
}





function json_encode (mixed_val) {
    // Returns the JSON representation of a value  
    // 
    // version: 911.718
    // discuss at: http://phpjs.org/functions/json_encode
    // +      original by: Public Domain (http://www.json.org/json2.js)
    // + reimplemented by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +      improved by: Michael White
    // *        example 1: json_encode(['e', {pluribus: 'unum'}]);
    // *        returns 1: '[\n    "e",\n    {\n    "pluribus": "unum"\n}\n]'
    /*
        http://www.JSON.org/json2.js
        2008-11-19
        Public Domain.
        NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
        See http://www.JSON.org/js.html
    */
    var retVal, json = this.window.JSON;
    try {
        if (typeof json === 'object' && typeof json.stringify === 'function') {
            retVal = json.stringify(mixed_val); // Errors will not be caught here if our own equivalent to resource
                                                                            //  (an instance of PHPJS_Resource) is used
            if (retVal === undefined) {
                throw new SyntaxError('json_encode');
            }
            return retVal;
        }
 
        var value = mixed_val;
 
        var quote = function (string) {
            var escapable = /[\\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;
            var meta = {    // table of character substitutions
                '\b': '\\b',
                '\t': '\\t',
                '\n': '\\n',
                '\f': '\\f',
                '\r': '\\r',
                '"' : '\\"',
                '\\': '\\\\'
            };
 
            escapable.lastIndex = 0;
            return escapable.test(string) ?
                            '"' + string.replace(escapable, function (a) {
                                var c = meta[a];
                                return typeof c === 'string' ? c :
                                '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
                            }) + '"' :
                            '"' + string + '"';
        };
 
        var str = function (key, holder) {
            var gap = '';
            var indent = '    ';
            var i = 0;          // The loop counter.
            var k = '';          // The member key.
            var v = '';          // The member value.
            var length = 0;
            var mind = gap;
            var partial = [];
            var value = holder[key];
 
            // If the value has a toJSON method, call it to obtain a replacement value.
            if (value && typeof value === 'object' &&
                typeof value.toJSON === 'function') {
                value = value.toJSON(key);
            }
 
            // What happens next depends on the value's type.
            switch (typeof value) {
                case 'string':
                    return quote(value);
 
                case 'number':
                    // JSON numbers must be finite. Encode non-finite numbers as null.
                    return isFinite(value) ? String(value) : 'null';
 
                case 'boolean':
                case 'null':
                    // If the value is a boolean or null, convert it to a string. Note:
                    // typeof null does not produce 'null'. The case is included here in
                    // the remote chance that this gets fixed someday.
 
                    return String(value);
 
                case 'object':
                    // If the type is 'object', we might be dealing with an object or an array or
                    // null.
                    // Due to a specification blunder in ECMAScript, typeof null is 'object',
                    // so watch out for that case.
                    if (!value) {
                        return 'null';
                    }
                    if (value instanceof PHPJS_Resource) {
                        throw new SyntaxError('json_encode');
                    }
 
                    // Make an array to hold the partial results of stringifying this object value.
                    gap += indent;
                    partial = [];
 
                    // Is the value an array?
                    if (Object.prototype.toString.apply(value) === '[object Array]') {
                        // The value is an array. Stringify every element. Use null as a placeholder
                        // for non-JSON values.
 
                        length = value.length;
                        for (i = 0; i < length; i += 1) {
                            partial[i] = str(i, value) || 'null';
                        }
 
                        // Join all of the elements together, separated with commas, and wrap them in
                        // brackets.
                        v = partial.length === 0 ? '[]' :
                                gap ? '[\n' + gap +
                                partial.join(',\n' + gap) + '\n' +
                                mind + ']' :
                                '[' + partial.join(',') + ']';
                        gap = mind;
                        return v;
                    }
 
                    // Iterate through all of the keys in the object.
                    for (k in value) {
                        if (Object.hasOwnProperty.call(value, k)) {
                            v = str(k, value);
                            if (v) {
                                partial.push(quote(k) + (gap ? ': ' : ':') + v);
                            }
                        }
                    }
 
                    // Join all of the member texts together, separated with commas,
                    // and wrap them in braces.
                    v = partial.length === 0 ? '{}' :
                            gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
                            mind + '}' : '{' + partial.join(',') + '}';
                    gap = mind;
                    return v;
                case 'undefined': // Fall-through
                case 'function': // Fall-through
                default:
                    throw new SyntaxError('json_encode');
            }
        };
 
        // Make a fake root object containing our value under the key of ''.
        // Return the result of stringifying the value.
        return str('', {
            '': value
        });
    
    } catch(err) { // Todo: ensure error handling above throws a SyntaxError in all cases where it could
                            // (i.e., when the JSON global is not available and there is an error)
        if (!(err instanceof SyntaxError)) {
            throw new Error('Unexpected error type in json_encode()');
        }
        this.php_js = this.php_js || {};
        this.php_js.last_error_json = 4; // usable by json_last_error()
        return null;
    }
}




function ajaxExport(func, args, callback){
	var result;
	
	var data=new Array();
	
	for (i = 0; i < args.length; i++){ 
		if (typeof(args[i])=='function'){
			callback=args[i];
		}else{
			data.push(args[i]);
		}	
	}
	var d=json_encode(data);

	$.ajax({
		type: 'POST',
		data: {
			ajax : func, 
			args : d
		},
		dataType: 'jsonp',
		async:callback ? true:false,
		success:  function(data){
			if (callback) result=callback(data);
			else result=data;
		}
	});
	return result;
}



/*
Ajax loader
*/
function showLoader(loader){
	if (loader.ajaxTimerCount) return 0;
	loader.timer=setTimeout(function(){	
		$(loader).addClass('loading');
		loader.ajaxTimerCount++;

	}, 100);

	setTimeout(function(){
		hideLoader(loader);
	}, 600000);

	return 1;
}

function hideLoader(loader){
	if (loader.timer) clearTimeout(loader.timer);
	$(loader).removeClass('loading');
	loader.ajaxTimerCount=0;
}



/**
load('#content', '#trigger', 'index.php');
*/
function load(content, trigger, href, param){
	//Defaults
	var d = {
		success: function(){},
		error: function(){},
		hide_empty: 1
	};
	$.extend(d, param);
	
	
	
	
	if (typeof(trigger)=='string') trigger=$(trigger)[0];
	
	//if (!content.lenght()) return false; // если content не найден - ошибка
	if (!trigger) trigger=$(content)[0];
	if (!trigger) trigger=this;
	
	var url="";
	if (href==null){
		url=trigger.href;
		if (url==null) url=trigger.action;
	}else{
		if (href.indexOf('&')==0){
			url=window.location.href;			
			if (url.indexOf('?')==-1) url+='?'; else url+='&';
		}
		url+=href;
	}

	if (!url) url=document.location.href;
	if (url.indexOf('#')!=-1) url=url.substr(0,url.indexOf('#'));
		
	// добавляем параметры в вызов
	if (url.indexOf('?')==-1) url+='?'; else url+='&';
	
	
	if (typeof(content)=='string') url+="ajax="+escape(content);


	

	send='';
	if (trigger){
		trigger.ajaxContent=content;
		if (!showLoader(trigger)) return false;
		if (trigger.tagName=='FORM')  send['trigger']=trigger;
	}


		
		jQuery.ajax({
			url: url,
			dataType : "html",
			cache: false,
			success:
			function(responseText, statusText){
				if (statusText=="success"){
					
					var processed=false;
					
					if (d['success']){
						if(d['success'](responseText, statusText)==false){
							processed=true;
						}
					}
					
					
					
					if (!processed && d['hide_empty'] && !responseText) processed=true;
					
					if (!processed){ 
						//jQuery(content).css("opacity", "20%");
						jQuery(content).html(responseText);
						//jQuery(content).fadeIn("fast");
						//jQuery(content).show();
						
						OnDocumentLoad(content);
					}
					
					
					
					
					
					
					
					//jQuery(content).animate({opacity: "show"}, "fast");
					//if (this.textContent) document.title=this.textContent;
					
				}else{
					//document.location=a[1];
				}
				
				hideLoader(trigger);
				
			}
			,error:  function (XMLHttpRequest, textStatus, errorThrown){
				
				if (d['error']) d['error'](XMLHttpRequest, textStatus, errorThrown);
				
				
				hideLoader(trigger);
				alert(textStatus+' '+errorThrown);
			}


		});
	

	return false;
}





function loadForm(content, form, param){
	//Defaults
	var d = {
		success: function(){}
	};
	$.extend(d, param);

	var target=jQuery(content);
	var trigger=jQuery(form).find("button[type='submit']");
	if (!trigger.length) trigger=jQuery(form).find("input[type=submit]");
	if (!trigger.length) trigger=jQuery(form);
	trigger=trigger[0];

	jQuery(form).ajaxSubmit({
		forceSync: true,
		beforeSubmit: function(formData, jqForm, options){
             
			// добавляем параметры в вызов
			if (options['url'].indexOf('?')==-1) options['url']+='?'; else options['url']+='&';
			options['url']+="ajax="+escape(content);
           //  alert(options['url']);
			showLoader(trigger);
		}, // функция, вызываемая перед передачей
		success: function(responseText, statusText){
			if (statusText=="success"){
				if (d['success']){
					if(d['success'](responseText, statusText)==false) return;
				}
				target.hide();
				target.html(responseText);
				OnDocumentLoad(target);
				//target.animate({opacity: "show"}, "fast");
				target.toggle();
				//target.show();
				 alert("ok");
			}
			hideLoader(trigger);
		}, // функция, вызываемая при получении ответа
		error:  function (XMLHttpRequest, textStatus, errorThrown) {
			
			alert(errorThrown);
			hideLoader(trigger);
			
			if (d['error']){
				d['error'](XMLHttpRequest, textStatus, errorThrown);
			}
		}
		//,timeout: 60000 // тайм-аут
	});
	return false;
}



function OnDocumentLoad(parent){
	if (!parent){
		parent=document;
		// инициализируем историю
		//jQuery.history.init(LoadCallback);

		// предзагрузка индикатора загрузки ajax
		//include_once(CMS_URL+'includes/js/loader.gif');
		
		
		// по нажатию на ссылку, ее адрес будет загружен в контейнер loadto
		jQuery("A[loadto]").live("click", function(){
			return load(jQuery(this).attr("loadto"), this);
		});
		
		
	// подсказки для инпутов
	$('input[placeholder], textarea[placeholder]').placeholder();

		
		
		//jQuery(parent).find('A.dialog').live('click', function(){
		
	jQuery("A.dialog").live("click", function(){
		
		var title = jQuery(this).attr("title");
		
		if ($(this).attr('content')){
			var dialog=$($(this).attr('content'));
			
			dialog.dialog({
				title: title,
				height: 'auto',
				width: 'auto',
				modal: true,
				closeOnEscape: true
			});

			$(".ui-widget-overlay").bind("click", function(event){
				$(".ui-dialog-titlebar-close").trigger("click");
			});

			return false;
		}
		
		var url = this.href;
		var dialog = $("<div style=\'overflow:auto;display:none;\'></div>").appendTo("body");
		var trigger=this;
		
		if (!showLoader(trigger)) return false;
		
		//var x = jQuery(this).position().left + jQuery(document).outerWidth();
    	//var y = jQuery(this).position().top - jQuery(document).scrollTop();
		
		// load remote content
		dialog.load(
			url,
			{},
			function (responseText, textStatus, XMLHttpRequest){
				
				
				
				dialog.dialog({
					//position: [x,y],
					//overlay: { backgroundColor: "#000", opacity: 0.5 },
					title: title,
					height: 'auto',
					//width: 'auto',
					minWidth: 600,
					modal: true,
					closeOnEscape: true,
					close: function(ev, ui) {
						$(this).remove();
					},

					open: function(event, ui){
						

					}

				});
				OnDocumentLoad(dialog);
				
				$(".ui-widget-overlay").bind("click", function(event){ 
					$(".ui-dialog-titlebar-close").trigger("click");
				}); 
				
				hideLoader(trigger);
				
				
			}
		);
		
		
		
	
		//prevent the browser to follow the link
		return false;
	});	
		
   
			
	}
	// обработка форм с rel
	jQuery(parent).find("FORM[rel]").submit(function(){return loadForm(jQuery(this).attr("rel"), this);});

	jQuery(parent).find('.tooltip').tooltip();

	// обработка lightbox
	jQuery(parent).find("A.lightbox").lightBox();

}

$().ready(function(){
	OnDocumentLoad();	
});


/*
<a title='Пример подсказки' class='tooltip'>tooltip</a>

<a title='Пример AJAX окна' class='dialog' href='1.php'>Показать AJAX окно</a>

<div style='display:none;' id='dialog'>test</div>
<a title='Пример окна' class='dialog' content='#dialog' >Окно из DIV элемента</a>


<a loadto='div' href='1.php'> по нажатию на ссылку, ее адрес будет загружен в контейнер loadto</a>

*/


//-->
