var _startTimer = (new Date()).getTime(),
	__scrollPoint = 0,
	Path = {
		'js': '/template/js/'
	},
	Intervals = [],
	stMap = {
		'mail': ['emoji.js','mail.js'],
		'arbour': ['emoji.js'],
		'photos': ['upload_file.js'],
		'id\\d+($|/)': ['emoji.js'],
		'blog': ['emoji.js']
	};

function isFunction(obj){return Object.prototype.toString.call(obj)==='[object Function]';}function isArray(obj){return Object.prototype.toString.call(obj)==='[object Array]';}function isEmpty(o){if(Object.prototype.toString.call(o)!=='[object Object]'){return false;}for(var i in o){if(o.hasOwnProperty(i)){return false;}}return true;}function eventsList(element){var events=element.data('events');if(events!==undefined)return events;events=$.data(element,'events');if(events!==undefined)return events;events = $._data(element, 'events');if(events!==undefined)return events;events=$._data(element[0],'events');if(events!==undefined)return events;return false;}function checkEvent(element,eventname){var events,ret=false;events=eventsList(element);if(events){$.each(events,function(evName,e){if(evName==eventname){ret=true;}});}return ret;}$.fn.hasAttr=function(name){return this.attr(name)!==undefined;};$.fn.extend({insertAtCaret:function(myValue){return this.each(function(i){if(document.selection){this.focus();var sel=document.selection.createRange();sel.text=myValue;this.focus();}else if(this.selectionStart||this.selectionStart=='0') {var startPos=this.selectionStart;var endPos=this.selectionEnd;var scrollTop=this.scrollTop;this.value=this.value.substring(0,startPos)+myValue+this.value.substring(endPos,this.value.length);this.focus();this.selectionStart=startPos+myValue.length;this.selectionEnd=startPos+myValue.length;this.scrollTop=scrollTop;}else{this.value+=myValue;this.focus();}})}});
var Linesoc = {
	countMessages: 0,
	activeWindow: true,
	delNote: function() {
		if($('.note-error')) { $('.note-error').remove(); }
		if($('.note-success')) { $('.note-success').remove(); }
	},
	addNote: function(m,e) {
		if(m != "") {
			var n = 'note-' + (e == true ? 'error' : 'success' );
			Linesoc.delNote();
			$( ($('#location').text() != undefined ? '#location' : '#main' )).after('<div class="' + n + '">' + m + '</div>');
		}
	},
	ajaxSave: function(a,e) {
		$.ajax({
			url: "",
			data: "",
			type: 'POST',
			beforeSend: function(data) {
				console.log("send..");
			},
			success: function(data) {
				console.log("success!");
			}
		});
	},
	StatusSelect: function(r){
		with(r) {
			if($("#select_partner") != undefined)  {
				if(options[selectedIndex].value >= 3 && options[selectedIndex].value <= 7) {
					$("#select_partner").css('display','block');
					$("#select_partner").html('<a href="/anketa?act=anketa/edit&amp;select_partner=1&amp;status='+options[selectedIndex].value+'" style="padding: 7px;" class="_action-link">Изменить партнёра</a>');
				} else {
					$("#select_partner").css('display','none');
				}
			}
		}
	}
}


var App = {
	taggerData: [],
	toggle: function(x) {
		if($(x)) {
			var d = $(x).attr('data-id');
			var cl = $(x).attr('data-class');
			if(!$(x).hasClass(cl)) { $(x).addClass(cl); } else { $(x).removeClass(cl); } 
			$("#" + d).css('display', ($("#" + d).css('display') == 'none' ? 'block' : 'none'));
		}
		event.preventDefault();
	},
	coverSelect: function() {
		$("input[name='cover_cancel']").on('click', function(e){
			if($(".cover-page--element")) {
				var el = $(this).attr('data-id');
				$(".cover-page--element").css('background',$("#cover--" + el).css('background'));
				$("input[name='cover']").val(el);
				$(".cover-page--floating").css('display','none');
			}
			e.preventDefault();
			return false;
		});
		$(".cover-select--items a").on('click', function(e){
			var a = $(this).attr('data-src');
			if($(".cover-page--element")) {
				$(".cover-page--element").css('background',($(this).attr('data-id') > 0 ? 'url("' + a + '")' : a ) );
				$("input[name='cover']").val($(this).attr('data-id'));
				$(".cover-page--floating").css('display','inline');
			}
			e.preventDefault();
		});
	},


}

var UI = {
	ajaxLoad: '',
	toggleMenu: function(t) {var b=$(".toggle-menu:eq("+$("."+$(t).attr("class")).index(t)+")");if(!b.hasClass("toggle-menu-open")){$(".toggle-menu-open").removeClass("toggle-menu-open");b.addClass("toggle-menu-open");}else{b.removeClass("toggle-menu-open");}},
	loadTagger: function(t) {
		var h = $(t).height();
		var w = $(t).width();
		var r = 0;
		var p = $(t).attr('data-source');

		var v1,v2,v3,v4;
		if(w > h) {
			r = h;
			v1 = p * (w/100);
			v2 = 0;
			v3 = v1 + r;
			v4 = r;
		} else {
			r = w;
			v1 = 0;
			v2 = p * (h/100);
			v3 = r;
			v4 = v2 + r;
		}
		console.log(v1);
		$(t).imgAreaSelect({
	        handles: false,
	        minWidth: r,
	        maxWidth: r,
	        minHeight: r,
	        maxHeight: r,
	        resizable: false,
	        disabled: true,
	        x1: v1, y1: v2, x2: v3, y2: v4,
	        onSelectEnd: function (img, selection) {
	        	App.taggerData = selection;
	        	$("#tagger-btn").css('display','block');
		    }
	    });
	    $("#tagger-btn input[name='tagger']").on('click', function(){
			var url = $(this).attr('data-url') + "?edit=1&tagger=1";
			event.preventDefault();
			console.log(App.taggerData.y1);
	    	$.ajax({
				url : url,
				data : {x1: App.taggerData.x1, 
						y1: App.taggerData.y1, 
						x2: App.taggerData.x2, 
						y2: App.taggerData.y2, 
						height: App.taggerData.height, 
						width: App.taggerData.width
					},
				beforeSend: function(s){
				}, 
				type : "POST",
				success: function (d){
					$("#tagger-btn").css('display','none');
				}
			});
		});
	},
	addScript: function(rr) {
		$("*[id='__js-delete']").remove();
		$(".__js-delete").remove();
					for(i in stMap) {
						r = new RegExp("" +i+ "");
						if(rr.match(r)) {
						stMap[i].forEach(function(item,i,arr){
								obj = document.createElement("script");
								obj.type = "text/javascript";	
								obj.src = Path.js + item;
								obj.id="__js-delete";
								obj.async = true;
								$("head").append(obj);
						});
						}
					}
	},
	clearInt: function(arr) {
		for (var i = 0; i < arr.length; i++) {
			clearTimeout(arr[i]);
		}
	},
	delNote: function() {
		if($('.note-error')) { $('.note-error').remove(); }
		if($('.note-success')) { $('.note-success').remove(); }
	},
	addNote: function(m,e) {
		if(m != "") {
			var n = 'note-' + (e == true ? 'error' : 'success' );
			UI.delNote();
			$( ($('#location').text() != undefined ? '#location' : '#main' )).after('<div class="' + n + '">' + m + '</div>');
		}
	},
	addStylerForm: function() {if(!Browser.mobile){$('input[type="radio"],input[type="file"],select,input[type="checkbox"]').styler();}},
	toTop: {
			hide: function() {__scrollPoint = 0;$('#scrollup').removeClass('-show');$('#scrollup').removeClass('-toCheckPoint');},
			__init: function() {
					$('#scrollup').on('click', function(){
					x = $(window).scrollTop();
					$(window).scrollTop($(window).scrollTop() > 100 ? 0 : __scrollPoint );
					if(x > 0) {
						$('#scrollup').addClass('-toCheckPoint');
						__scrollPoint = x;
					} else {
						$('#scrollup').removeClass('-toCheckPoint');
						__scrollPoint = 0;
					}
				});
				$(window).scroll(function(){ 
				    if ($(this).scrollTop() > 100) { 
				        $('#scrollup').addClass('-show'); 
				        $('#scrollup').removeClass('-toCheckPoint');
				    } else {$('#scrollup').removeClass('-show');} 
				});
			}

	},
	formFocus: function(e) {
		$(e).focus(); return false;
	}
}
$(function() {
	UI.toTop.__init();
	UI.addStylerForm();
	$(window).bind('focus', function() {
		Linesoc.activeWindow = true;
		$('title').html(USER.title);
	});
	$(window).bind('blur', function() {
		Linesoc.activeWindow = false;
	});
});

function ajaxLoad(href,tt) {
	var e = event;
if (href != undefined) {
			if($('#ixrf')) { $('#ixrf').remove(); }
			var el = document.createElement("iframe");
			el.id = 'ixrf';
			el.style.width = "0px";
			el.style.height = "0px";
			el.style.display = "none";
			el.src = href;
			$('#main').append(el);
			$('#ixrf').load(function() {
				if($(this).attr('src') == href) {
					var x = $(this).contents();
					var t = x.find('title').text();
					document.title = t;
					var l = x.find('#main').html();
					$('#main').html(l);
					$('.top--title').text(x.find('#location').text());
					window.history.replaceState(l, t);
					$(document).scrollTop('0');
					if(tt == true){ history.pushState(l, document.title, href); }
				}
			});
			e.preventDefault();
		}	
}
/*
function onRequestCompleted(xhr,textStatus) {
  if (xhr.status == 302) {
      //location.href = xhr.getResponseHeader("Location");
      console.log( xhr);
   }
}*/
var $AJAX = {
	H: '',
	hPush: false,
	Button: function(f,b) {
		try {
		var e = event;
		if(UI.ajaxLoad) { UI.ajaxLoad.abort(); NProgress.done(); }
		this.H = window.location.toString();
		$.ajax({
			'async': true,
			'url': this.H,
			'data': f.serialize()+"&"+b.attr('name')+"=1",
			'type': 'POST',
			'dataType': 'html',
			'beforeSend': function(){NProgress.start();},
			'success' : function(data,status,xhr){$AJAX.Success(data,status,xhr);},
			'error' : function(jqXHR, timeout, message){
				var c = jqXHR.getAllResponseHeaders();
				console.log(c);
			},
			'statusCode': {
			    404: function() {
			      $AJAX.Loader(USER.Page);
			    }
			   
			  }			
		});
		e.preventDefault();
		} catch(e) {debLog('error the connection to the server, try later');}
	},
	Loader: function(h,tt) {
		var e = event;
		this.H = h;
		this.hPush = tt;
		try {
		if(UI.ajaxLoad) { UI.ajaxLoad.abort(); NProgress.done(); }
		$.ajax({
			'async': true,
			'url': h,
			'type': 'GET',
			'dataType': 'text',
			'beforeSend': function(){NProgress.start();},
			'success' : function(data,status,xhr){$AJAX.Success(data,status,xhr);},
			'error' : function(jqXHR, timeout, message){
				var c = jqXHR.getAllResponseHeaders();
				console.log(c);
			},
			'statusCode': {
			    404: function() {
			      $AJAX.Loader(USER.Page);
			    }
			  }			
		});
		e.preventDefault();
		} catch(e) {debLog('error the connection to the server, try later');}
	},

	Success: function(data,status,xhr) {
		var c = xhr.getResponseHeader('Content-Length');
		if(!c || c > 0) {
		NProgress.done();
		UI.toTop.hide();
		main = data.match(/<div id="main">([\s\S]+?)<\/div data-id="main">/gmi);
		main = main[0].replace(/((<div id="main">)|(<\/div data-id="main">))/gmi,'');
		$("#main").html(main);	
		meta = data.match(/<meta name="ajax-link"'(.+?) \/>/gi);
		if(meta !== null) {
			console.log($(meta).attr('content'));
		}

		if(this.hPush==true){
			history.pushState(main,'',this.H);
		}
		title =  data.match(/<title>(.*)<\/title>/g);
		title = $(title[0]).text();
		document.title = title;
		USER.title = title;
		$('title').text(title);
		UI.clearInt(Intervals);
		UI.addScript(this.H);
		window.scrollTo(0,0);
		loc = main.match(/<div id="location">([\s\S]+?)<\/div>/gi);
		loc = (loc !== null ? $(loc[0]).text().trim() : '');
		back = main.match(/<div id='app-ajax-back'(.+?)>([\s\S]+?)<\/div>/gi);
		$("#app-ajax-back").hide();
		if(back !== null) {
			back = $(back[0]);
			back_a = back.find('a').attr('href');
			back_t = back.find('a').text().trim();
			loc = "<a href=\""+back_a+"\">" + loc + "</a>";			
		} else {loc = "<span>"+loc+"</span>";}
		$('#top .top--title').html(loc);
		UI.addStylerForm();
		if($("textarea[data-focus='1']")) {UI.formFocus($("textarea[data-focus='1']"));}
		}else{$AJAX.Loader(USER.Page,true);}		
	}
};
var $LP = {
		thisStatus: 0,
		status: {
			CLOSED: 0,
			RECONNECT: 1,
			CONNECT: 2
		},
		statuschange: function(s) {
			switch(s) {
				case $LP.status.CLOSED:
					debLog('LongPolling: disconnected');
				break;
				case $LP.status.RECONNECT:
					debLog('LongPolling: sending request..');
				break;
				case $LP.status.CONNECT:
					debLog('LongPolling: connection');
				break;
			}
			$LP.thisStatus = s;
		},
		
		        error: function(e) {
		        	$LP.statuschange($LP.status.RECONNECT);
		        	//setTimeout($LP.update(d), 30000);
		        	return false;
		        }
		    });
		    return true;
		},
		__init: function() { $LP.statuschange(($LP.status.CONNECT : $LP.status.CLOSED )); }
	};

jQuery(document).ready(function() {
	$.ajaxPrefilter(function(options,original_Options,jqXHR){options.async=true;});
	if($("textarea[data-focus='1']")) {UI.formFocus($("textarea[data-focus='1']"));}
	if(USER.id > 0){ $LP.__init(); }
	if (Browser.iphone||Browser.ipad||Browser.ipod){$("body").css({webkitTextSizeAdjust:'none'});}
	if (history.pushState){
		debLog('AJAX: starting the connection to the server');
	$(window).on('popstate', function(event){
	var loc = event.location || ( event.originalEvent && event.originalEvent.location )|| document.location;
		UI.ajaxLoad = $AJAX.Loader(loc.href, false);
	});
	}
	$(document).on('click', 'a[href][prevent!=1]', function(e) {
		var href = $(this).attr('href');
		if(!checkEvent($(this),'click') && !$(this).hasAttr('onclick')){
			UI.ajaxLoad = $AJAX.Loader(href,true);
		}
	});
	$(document).on('click', 'input[type="submit"][load!="1"]', function(e) {
		var f = $(this).closest('form');
		if(!checkEvent($(this),'click') && !$(this).hasAttr('onclick') && !checkEvent(f,'submit')){
			UI.ajaxLoad = $AJAX.Button(f,$(this));
		}
	});
	UI.addScript(document.location.pathname);

	

});

function debLog(msg){try{var t='['+(((new Date()).getTime()-_startTimer)/1000) + '] ';if(window.console&&console.log){var args=Array.prototype.slice.call(arguments);args.unshift(t);if(Browser.msie||Browser.mobile){console.log(args.join(' '));}else{console.log.apply(console,args);}}}catch(e){}}

if (!window._ua) {
  var _ua = navigator.userAgent.toLowerCase();
}
var Browser = {
  version: (_ua.match( /.+(?:me|ox|on|rv|it|era|opr|ie|edge)[\/: ]([\d.]+)/ ) || [0,'0'])[1],
  opera: (/opera/i.test(_ua) || /opr/i.test(_ua)),
  vivaldi: /vivaldi/i.test(_ua),
  msie: (/msie/i.test(_ua) && !/opera/i.test(_ua) || /trident\//i.test(_ua)) || /edge/i.test(_ua),
  msie6: (/msie 6/i.test(_ua) && !/opera/i.test(_ua)),
  msie7: (/msie 7/i.test(_ua) && !/opera/i.test(_ua)),
  msie8: (/msie 8/i.test(_ua) && !/opera/i.test(_ua)),
  msie9: (/msie 9/i.test(_ua) && !/opera/i.test(_ua)),
  msie_edge: (/edge/i.test(_ua) && !/opera/i.test(_ua)),
  mozilla: /firefox/i.test(_ua),
  chrome: /chrome/i.test(_ua) && !/edge/i.test(_ua),
  safari: (!(/chrome/i.test(_ua)) && /webkit|safari|khtml/i.test(_ua)),
  iphone: /iphone/i.test(_ua),
  ipod: /ipod/i.test(_ua),
  iphone4: /iphone.*OS 4/i.test(_ua),
  ipod4: /ipod.*OS 4/i.test(_ua),
  ipad: /ipad/i.test(_ua),
  android: /android/i.test(_ua),
  bada: /bada/i.test(_ua),
  mobile: /iphone|ipod|ipad|opera mini|opera mobi|iemobile|android/i.test(_ua),
  msie_mobile: /iemobile/i.test(_ua),
  safari_mobile: /iphone|ipod|ipad/i.test(_ua),
  opera_mobile: /opera mini|opera mobi/i.test(_ua),
  opera_mini: /opera mini/i.test(_ua),
  mac: /mac/i.test(_ua),
  search_bot: /(yandex|google|stackrambler|aport|slurp|msnbot|bingbot|twitterbot|ia_archiver|facebookexternalhit)/i.test(_ua)
};







var $NOTIFER = {
	
};