Query.init();

jQuery.extend( jQuery.easing, {
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	}
});

function show_all_left_menu(x) {
	var obj = $('#id_left_menu');
	var switcher_left_menu = $(x).find('a');
	if (obj.hasClass('opened_menu')) {
		obj.animate({height: "40px"}).removeClass('opened_menu');
		switcher_left_menu.removeClass('i_arrow_up').addClass('i_arrow_down').attr('stick', 'Еще');
		$.cookie("left_menu_status", 'close', {
			path: "/",
			domain: "." + serverName
		});
	} else {
		obj.animate({height: "85px"}).addClass('opened_menu');
		switcher_left_menu.removeClass('i_arrow_down').addClass('i_arrow_up').attr('stick', 'Свернуть');
		$.cookie("left_menu_status", 'open', {
			path: "/",
			domain: "." + serverName
		});
	}
}

function resetForm(a,b){if(!b){b='input,select,textarea'}$(document.forms[a]).find(b).val('')};
function submitForm(a){$(document.forms[a]).submit()};
function nl2br(str){return (str+'').replace(/([^>]?)\n/g,'$1<br />\n')};

(function($) {
	var popupsArray		= new Array();
	var popupTemplate	= '<div class="hide" style="position:relative"><table class="auto popup"><tr><td class="tl">&nbsp;</td><td class="t">&nbsp;</td><td class="tr">&nbsp;</td></tr><tr><td class="l">&nbsp;</td><td class="content"><div class="content"></div></td><td class="r">&nbsp;</td></tr><tr><td class="bl"><img src="/i/small/0.gif" width="13" heigth="13"/></td><td class="b">&nbsp;</td><td class="br"><img src="/i/small/0.gif" width="13" heigth="13"/></td></tr></table><i class="close_i imgs i_x_grey" style="position: absolute; right: 10px; top: 12px; z-index: 26000;"><i/></i></div>';
	var buttonWrapper	= '<div class="popup_wrapper"></div>';
	var duration 		= 100;
	var margin			= -18;
	var selfWindow		= $( window );
	
	$.fn.ShowAlert = function( text, auto_close, force_open ) {
		var autoclose = auto_close ? true : false;
		var forceopen = force_open ? true : false;
		
		this.each(function() {
			if( forceopen == false && this.alert_show instanceof Object ) {
				if( autoclose ) {
					$( this.alert_show ).remove();
					delete this.alert_show;
				} else {
				}
			} else {
				this.alert_show = ShowAlert( this, text );
			}
		});
		
		return $( this );
	}

	$.fn.HideAlert = function( delay ) {
		this.each(function() {
			if( this.alert_show ) {
				if( delay ) {
					window.setTimeout(function(){
						$( this.alert_show ).remove();
						delete this.alert_show;
					}, delay );
				} else {
					$( this.alert_show ).remove();
					delete this.alert_show;
				}
			}
		});

		return $( this );
	}
	
})(jQuery);

function ShowAlert( el, text ) {
	var element = $( el );
	var element_offset = element.offset();
	var alert_text = text || 'undefined';
	var alert_block = $( '<div class="info_stick"></div>' ).text( alert_text ).css({
		top: element_offset.top - 23,
		left: element_offset.left + 10
	});
		
	switch( element.attr( 'tagName' ).toLowerCase() ) {
		case 'textarea':
		case 'input':
			var event_key_down = function() {
				alert_block.remove();
				$( this ).unbind( 'keyup', event_key_down );
				$( this ).unbind( 'change', event_change );
			}
			
			var event_change = function() {
				alert_block.remove();
				$( this ).unbind( 'keyup', event_key_down );
				$( this ).unbind( 'change', event_change );
			}

			element.bind( 'keyup', event_key_down );
			element.bind( 'change', event_change );
		break;
		case 'select':
		case 'checkbox':
			var event_change = function() {
				alert_block.remove();
				$( this ).unbind( 'change', event_change );
			}
			element.bind( 'change', event_change );
		break;
		default:
			var event_click = function() {
				alert_block.remove();
				$( this ).unbind( 'click', event_click );
			}
			element.bind( 'click', event_click );
		break;
	}
	
	$( document.body ).append( alert_block );
	
	return alert_block.get( 0 );
}

function spawnChat( userId ) {
	userId = parseInt( userId );
	if( !userId )
		return;
		
	var popupWin = window.open( siteRoot + "/messages/chat/" + userId, "chat" + userId, "status=0,toolbar=0,location=0,menubar=0,directories=0,scrollbars=0,resizable=0,location,width=520,height=520,fullscreen=0");

	if( popupWin )
		popupWin.focus();
}

function rateItem( _rate, _itemId, serviceName, _parentId, fields, url ) {
	var rate = parseInt( _rate ),
		itemId = parseInt( _itemId ),
		parentId = parseInt( _parentId );
		
	Query.add( siteRoot + '/vote/vote/',
		{ 
			rate: rate, 
			itemId: itemId,
			parentId: parentId,
			serviceName: serviceName
		}, function( response ) {
			if( response == 'ok' ) {
				if( fields == 'reload' ) {
					if( url )
						window.location.href = ( url.indexOf( 'http://' ) == -1 ? siteRoot : '') + url;
					else
						window.location.reload();
					return;
				}
				$( fields ).each(function() {
					var current_value = parseInt( $( this ).text() );
					var new_value = current_value + rate;
					$( this ).text( new_value );
				});
			}
		}
	);
}

function addToNotepad( element, id, author, type ) {
	element = $( element );
	
	Query.add( siteRoot + '/favorites/ajax/add/', { 'id': id, 'author': author, 'type':type }, function(data) {
		if(data == 'ok' && element.length ) {
			element.get(0).onclick = function() { 
				removeFromNotepad(element, id, author, type ); 
			};
			
			$(element).html( '<i class="imgs i_menu_favorite center"><i></i></i><span class="cb">Удалить из закладок</span>' );
		}
	});
}

function removeFromNotepad(element, id, author, type ) {
	element = $( element );
	
	Query.add( siteRoot + '/favorites/ajax/remove/', { 'id': id, 'author': author, 'type':type }, function(data) {
		if(data == 'ok' && element.length ) {
			element.get(0).onclick = function() { 
				addToNotepad( element, id, author, type ); 
			};
			
			$(element).html( '<i class="imgs i_menu_favorite center"><i></i></i><span class="cb">В закладки</span>' );
		}
	});
}

function aut_popup(){
	show_popup('autorization_popup');
}

function show_popup(z) {
	var a = $('#popup_window div.content').append($('#'+z).children()).attr('ids',z);

	$('#popup_window').find('.popup-tc, .popup-bc').css({'width':'auto'});
	$('#popup_window').removeClass('hide');

	var width_obj = Math.round(a.get(0).offsetWidth);
	var height_obj = Math.round(a.get(0).offsetHeight);

	$('#popup_window').find('.popup-tc, .popup-bc').css({'width':width_obj+'px'});
	$('#popup_window').css({
		'marginTop': -height_obj/2+'px',
		'marginLeft': -width_obj/2+'px'
	});
}

function close_popup() {
	$('#popup_window').addClass('hide');
	
	var a = $('#popup_window div.content');
	var b = a.attr('ids');
	
	$( '#' + b ).append( a.children() );
	$('#popup_window div.content').html('');
}

function switch_popup(z){
	var a=$('#popup_window').find('div.content');
	var b=a.attr('ids');
	
	$('#'+b).append(a.children());

	show_popup(z);
}

function TKN() {
	return '&tkn=' + Math.floor( Math.random() * 1000 );
}

function send_user_message_about_error() {
	var error_email = $('#error_user_message_name').val();
	var error_message = $('#error_user_message').val(); 
	if (error_email.length != 0 && error_message.length !=0) {
		Query.init();
		Query.add( siteRoot + '/feedback/ajax/?action=send', { 'email' : error_email, 'text' : error_message }, function(data) {
			if (data == 'OK') {
				switch_popup('user_answer_about_error_ok');
			}
		});
	}
}

function calcDate(a,b,c,d){var _return='';if(a!=0){_return=a+' ';var e=a%100;if(e>5&&e<=20)_return+='лет';else{e=e%10;if(e==1)_return+='год';else if(e>=2&&e<=4)_return+='года';else _return+='лет'}_return+=' '}if(b!=0){_return+=b+' ';var e=b%100;if(e>5&&e<=20)_return+='месяцев';else{e=e%10;if(e==1)_return+='месяц';else if(e>=2&&e<=4)_return+='месяца';else _return+='месяцев'}_return+=' '}if(c!=0&&a==0&&b==0){_return+=c+' ';var e=c%100;if(e>5&&e<=20)_return+='недель';else{e=e%10;if(e==1)_return+='неделя';else if(e>=2&&e<=4)_return+='недели';else _return+='недель'}_return+=' '}if(c==0&&d!=0){_return+=d+' ';var e=d%100;if(e>5&&e<=20)_return+='дней';else{e=e%10;if(e==1)_return+='день';else if(e>=2&&e<=4)_return+='дня';else _return+='дней'}}return _return}

function showChildPopup( id, x, y ) {
	if( divs[id] ) return false;
	var offset = calendar.offset(), itration = CALENDAR_PARAMS.child[id].twins;
	if( !itration ) itration = [ CALENDAR_PARAMS.child[id] ];
	var windowWeight = _window.width(),
		leftOffset = offset.left + x + 15,
		topOffset = offset.top + y + 15;
	if( leftOffset + 270 > windowWeight )
		leftOffset = leftOffset - 275;
	divs[id] = $('<div></div>').css({
			zIndex: 24000,
			position: 'absolute',
			top: topOffset,
			left: leftOffset,
			width: 270,
			overflow: 'hidden'
	});
	$( '#main' ).before( divs[id] );
	for( var iterator in itration ) {
		(function(iterator){
			var child = itration[iterator];
			if (child.sex == 'w') {
					var child_type = '_g';
					var color_user_pic = '_pink';
					var header_style_color ='style="color:#ae6b9d"';
					var txt_color ='style="color:#90487e"';
			} else {
					var child_type = '';
					var color_user_pic='';
					var header_style_color='';
					var txt_color='';
			}
			divs[id].append(
				$('<div id="title_stick_big_top'+child_type+'"></div>').css({
					position: 'relative'
				}).append( $('<div class="fl avatar"><div class="avatar1"><a href="#" class="userpic_65_65'+color_user_pic+' fl margin_0_10_0_0"><img src="' + siteRoot + ( child.hasUserpic == 't' ? child.avatarPath : '/images/icons/child_no_photo.gif' ) + '" /><b></b></a></div></div>') )
				  .append( 
				  	$('<div class="fl" style="width:111px;height:75px;padding:10px 4px 5px 5px;overflow: hidden"></div>') 
				  	.append( $('<font class="thm bb" '+header_style_color+'></font>').text( child.name ) )
				  	.append( $('<small class="thm" '+txt_color+'></small>').text( calcDate( child.b.year, child.b.month, child.b.week, child.b.day ) ) )
				  	.append( $('<i class="thm" '+txt_color+'></i>').text( child.about ) )
				  )
			);
		})(iterator);
	}
	var close = function() {
		hideChildPopup( id );
		window.onblur = '';
	};
	divs[id].mouseover(close);
	window.onblur = close;
}

function hideChildPopup(a){if(a&&divs[a]){divs[a].remove();delete divs[a]}}

function quickForm( url, key, value ) {
	var form = $( '<form />' ).attr({
		action: url || window.location.href,
		method: 'post'
	});
	form.append( $( '<input />' ).attr({ type: 'hidden', name: key, value: value }) );
	form.appendTo( document.body ).submit();
}

function Paginator( link, dom_element ) {
	$(dom_element).load(link,function() {
		var offset = $(dom_element).offset();

		window.scrollTo(offset.left,offset.top-50);	
	});
}