// jsvascript for alexschneider.ru

var baseUrl = '/';

/*
// social_networks[] = [ DOMAIN, URL, TITLE, INDEX ];
// INDEX - icons position in sn.png starting 0
var social_networks = [], i = 0;
social_networks[i++] = [ '100zakladok.ru','save/?bmurl={url}&bmtitle={title}', 'Сто закладок', 0 ];
social_networks[i++] = ['delicious.com','post?url={url}&title={title}', 'Delicious', 6 ];
social_networks[i++] = [ 'google.com','bookmarks/mark?op=edit&bkmk={url}&title={title}', 'Google', 9 ];
social_networks[i++] = [ 'bobrdobr.ru','add.html?url={url}&title={title}', 'БобрДобр', 4 ];
social_networks[i++] = [ 'links.i.ua','mark/?url={url}&ename={title}', 'links.i.ua', 11 ];
social_networks[i++] = [ 'memori.ru','link/?sm=1&u_data[url]={url}&u_data[name]={title}', 'memori.ru', 14 ];
social_networks[i++] = [ 'moemesto.ru','post.php?url={url}&title={title}', 'МоёМесто', 16 ];
social_networks[i++] = [ 'mister-wong.ru','add_url/?bm_url={url}&bm_description={title}', 'Mister Wong', 15 ];
social_networks[i++] = [ 'linkstore.ru','servlet/LinkStore?a=add&url={url}&title={title}', 'linkstore', 12 ];
social_networks[i++] = [ 'lopas.ru','add_story.php?story_url={url}', 'lopas.ru', 13 ];
social_networks[i++] = [ 'myscoop.ru','add/?title={title}&URL={url}', 'MyScoop', 18 ];
social_networks[i++] = [ 'ruspace.ru','index.php?link=bookmark&action=bookmarkNew&bm=1&url={url}&title={title}', 'RuSpace.ru', 21 ];
social_networks[i++] = [ 'vaau.ru','submit/?action=step2&url={url}', 'Ваау!', 25 ];
social_networks[i++] = [ 'badabadu.com','?url={url}&posttitle={title}', 'БадаБаду!', 1 ];
social_networks[i++] = [ 'korica.info','add_story.php?story_url={url}&story_title={title}', 'kORICA.info', 10 ];
social_networks[i++] = [ 'news2.ru','add_story.php?url={url}', 'news2.ru', 19 ];
social_networks[i++] = [ 'newsland.ru','News/Add/type/news/', 'Newsland', 20 ];
social_networks[i++] = [ 'sloger.net','submit.php?url={url}', 'Sloger.Сеть', 22 ];
*/


$.fn.formValidate = function(settings)
{
	settings = jQuery.extend({

		ajax_checkform: null,
		min_length_passwd: 5,
		min_length_username: 4,
		max_length_up: 32

		}, settings);

	return $(this).each(function () {

		var o = $(this);

		if (o.hasClass('skip-validate')) return;

		o.bind('submit', function()
			{
//					var f = $(this);
				var f = o;
				var error = '';

				if (o.submit_oke) { return; }

				function submit_form (submt)
				{
					var err_el = $('.err', o);
		
					if (err_el.length)
					{
						if (error == '')
						{
							err_el.hide(150).text('');
//alert('oke');
//return false;
							o.submit_oke = true;
							if (submt)
							{
								o.submit();
							}
							return;
						}
						else
						{
							err_el.text(error).show(300);
							setTimeout( function()
								{
									err_el.hide(150);
								}, 3000);
						}
					}
					else
					{
						if (error == '')
						{
//alert('oke'); return false;
							o.submit_oke = true;
							if (submt) o.submit();
							return;
						}
						else
							alert(error);
					}
				
					return false;
				}

				function set_error (el, err)
				{
					if (err.length)
					{
						if (error == '') error = err[0];

						el.addClass('error');
						if (el.attr('id'))
						{
							$( '#'+el.attr('id')+'-label' ).addClass('error');
						}
					}
					else
					{
						el.removeClass('error');
						if (el.attr('id'))
							$( '#'+el.attr('id')+'-label' ).removeClass('error');
					}
				}

				$(':input', f).each(function()
					{
						var err = [];
						var inp = $(this);

						var vv = (inp.attr('type') == 'checkbox' && !inp.attr('checked')) ? '' : inp.val();

						if ($.isArray(vv)) vv = vv.join(', ');
						
						var v = $.trim(vv);

						if (inp.hasClass('required'))
						{
							if (inp.hasClass('rules') && v == '')
							{
								err.push('Вы не согласились с нашими правилами!');
							}
							else if (inp.hasClass('conditions') && v == '')
							{
								err.push('Вы не согласились с нашими условиями!');
							}
							else if (v == '')
							{
								err.push('Не заполнены обязательные поля!');
							}
						}
						
						if ( ! (err.length || v == ''))
						{
							if (inp.hasClass('email'))
							{
								if ( ! /^[\w_\-]+(\.[\w_\-]+)*@([\w_\-]+\.)+[a-zA-Z]{2,6}$/.test(v))
								{
									err.push('Неправильно указан e-mail адрес!');
								}
							}
							else if (inp.hasClass('passwd'))
							{
								var repasswd = $( '#' + inp.attr('id') + '_confirm' );
					
								if (repasswd && vv != repasswd.val())
								{
									err.push('Пароль не совпадает с повтором!');
								}
								else if (vv.length < settings.min_length_passwd)
								{
									err.push('Слишком короткий пароль!');
								}
								else if (vv.length > settings.max_length_up)
								{
									err.push('Пароль не должен превышать '+settings.max_length_up+'символов!');
								}
								
							}
							else if (inp.hasClass('username'))
							{
								if (/[\|\x7d'"!<\x7b>]/.test(v))
								{
									err.push('Логин содержит неразрешенные символы!');
								}
								else if (vv.length < settings.min_length_username)
								{
									err.push('Слишком короткий логин!');
								}
								else if (vv.length > settings.max_length_up)
								{
									err.push('Логин не должен превышать '+settings.max_length_up+'символов!');
								}
							}
						}

						set_error(inp, err);
					});

				if (error == '' && settings.ajax_checkform)
				{
					var buttn = $('input.submit', f)
						.addClass('disabled')
						.attr('disabled', 'disabled');
					var loadg = $('.loading', f).show();

					var fn_compl = function(res)
						{
							var data = null;
							try {
								eval('data = ' + res)
								}
							catch(e) {}

							if ( ! (data && data.response))
							{
								data = {response:"Ошибка!"};
							}
							buttn
								.removeClass('disabled')
								.attr('disabled', false)
							loadg.hide()
							error = data.response == 'oke' ? '' : data.response;
							submit_form(true);
						};

					jQuery.ajax({
//									timeout: 5000,
							type: "POST",
							url: settings.ajax_checkform,
							cache: false,
							data: f.serialize()+'&f='+f.attr('id'),
							success: fn_compl,
							error: function()
								{
									fn_compl('');
								}
						});

					return false;
				}

				return submit_form();
			});

		});
};


/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built in easing capabilities added In jQuery 1.1
 * to offer multiple easing options
*/

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	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;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});

(function($) {
    /*
     * Auto-growing textareas; technique ripped from Facebook
     */
    $.fn.autogrow = function(options) {

        this.filter('textarea').each(function() {

            var $this       = $(this),
                minHeight   = $this.height(),
                lineHeight  = $this.css('lineHeight');

            var shadow = $('<div></div>').css({
                position:   'absolute',
                top:        -10000,
                left:       -10000,
                width:      $(this).width(),
                fontSize:   $this.css('fontSize'),
                fontFamily: $this.css('fontFamily'),
                lineHeight: $this.css('lineHeight'),
                resize:     'none'
            }).appendTo(document.body);

            var update = function() {

                var val = this.value.replace(/</g, '&lt;')
                                    .replace(/>/g, '&gt;')
                                    .replace(/&/g, '&amp;')
                                    .replace(/\n/g, '<br/>');

                shadow.html(val);
                $(this).css('height', Math.max(shadow.height() + 20, minHeight));
            }

            $(this).change(update).keyup(update).keydown(update);

            update.apply(this);
        });

        return this;
    }
})(jQuery);

(function($) {
	$.fn.pk_fixed = function() {
		return this.each(function() {
		
			var $element = $(this);
			var $msie6 = $.browser.msie && parseInt($.browser.version) < 7;
		
			if(!$msie6) {
				var $top = $element.offset().top;

				$(window).scroll(function() {
					var $y = $(window).scrollTop();
		
					if ($y >= $top) {
						$element.addClass('fixed');
					} else {
						$element.removeClass('fixed');
					}
				});
			}
		});
	};
})(jQuery);


(function($) {
	$.fn.pk_slide_tabs = function(options) {
		var defaults = {
			tabs: ["#quick-search", "#social-networks"],
			buttons: ["#quick-search-button", "#social-networks-button"],
			icon_position: [ '0px 0px', '-20px 0px' ],
			close_icon_position: '-60px 0px',
			easing: 'easeOutExpo',
			speedIn: 1000,
			speedOut: 1000
		};
		
		var settings = $.extend({}, defaults, options);
		
		/**/
		
		return this.each(function() {
			
			var $root = $(this);
			var $width = $root.width();
			var $tab_search = $(settings.tabs[0], $root);
			var $tab_networks = $(settings.tabs[1], $root);
			var $button_search = $(settings.buttons[0]);
			var $button_networks = $(settings.buttons[1]);
			
			/**/
			
			$root.search = false;
			$root.networks = false;
			
			/**/

			$(document).click(function(ev)
				{
					if (
						($root.search || $root.networks)
						&&
						( ! $(ev.target).parents().is(options.wrapper) )
						)
					{
						if ($root.search)
							$button_search.click();
						if ($root.networks)
							$button_networks.click();
					}
				});

			function animateTabs($tab, $action, $button, icon_pos) {
				if($action == "open")
					$root.show();
				if($action == "open")
				{
					$tab.stop().css('right', -( $tab.outerWidth() + 1 ) ).show().animate({
						'right': 0
					}, settings.speedIn, settings.easing, function() {
						changeButtonImage($button, settings.close_icon_position);
						$root.width($tab.outerWidth());
						$root.height($tab.outerHeight());
					});
					var w = $tab.outerWidth();
					var h = $tab.outerHeight();
					if (w > $root.width())
						$root.width(w);
					if (h > $root.height())
						$root.height(h);
				} else {
					$tab.stop().animate({
						'right': -( $tab.outerWidth() + 1 )
					}, settings.speedOut, settings.easing, function () {
						if($root.search == false && $root.networks == false) {
							$root.hide();
						}
						changeButtonImage($button, icon_pos);
						$tab.hide();
					});
				}
			}
		
			function changeButtonImage($button, icon_pos)
			{
				$button.css('backgroundPosition', icon_pos);
			}
			
			/**/
		
			$button_search.click(function () {
				if($root.networks == true){
					$button_networks.click();
				}
				if($root.search == false) {
					$root.search = true;
					animateTabs($tab_search, "open", $(this), settings.icon_position[0]);
				} else {
					$root.search = false;
					animateTabs($tab_search, "close", $(this), settings.icon_position[0]);
				}

				return false;
			});
			
			$button_networks.click(function () {
				if($root.search == true){
					$button_search.click();
				}
				if($root.networks == false) {
					$root.networks = true;
					animateTabs($tab_networks, "open", $(this), settings.icon_position[1]);
				} else {
					$root.networks = false;
					animateTabs($tab_networks, "close", $(this), settings.icon_position[1]);
				}
				return false;
			});
			
			/*
			  * SOCIAL NETWORK: ROLLOVER
			*/
/*			
			$("#sn_list ul li", $root).hover(function () {
				var $label = $(this).find("img").attr('alt');
				$(".label", $root).text($label);
			}, function(e) {
				$(".label", $root).text("...");
			});
			
			$("#sn_list").pk_scroll();
			*/
		});
	};
})(jQuery);


$(document).ready(function()
{

	if ($.browser.msie && parseInt($.browser.version) < 8)
	{
		// Add onfocus on inputs
		$('.form1 .input, .form1 .textarea').focus(function()
			{
				$(this).css('backgroundColor', '#efefef');
			});
		$('.form1 .input, .form1 .textarea').blur(function()
			{
				$(this).css('backgroundColor', 'transparent');
			});
	}

	$('.form1 .textarea').autogrow();

	// Add the click event handler on the list item with sub list
	$('ul.months-tree li:has(ul) a').click(function(event)
		{
			var li = $(event.target).parent('li');

			if (li.find('ul').length)
			{
				$('ul.months-tree li:has(ul)').each(function()
					{
						if (this != li.get(0))
							// Hide all the children of the other lists
							$(this).children('ul').hide(200);
						else
							$(this).children('ul').animate({opacity:'toggle',height:'toggle'},200);
					})
				return false;
			}
		});

	$('form[method=post]').formValidate({
		ajax_checkform: baseUrl + 'ajax_checkform.php'
		});

	$('#quick-search').each(function()
		{
			var seach_word = 'Поиск...';
			var inp = $(this).find('input[name=query]');
			inp
				.focus(function(){ if (inp.val() == seach_word) inp.val(''); })
				.blur(function(){ if (inp.val() == '') inp.val(seach_word); })
				.val(seach_word);
			$(this).submit(function(){ if (inp.val() == seach_word ) inp.val(''); });
			
		});

/*
	var sn = $('<ul class="z"></ul>');
	$.each(social_networks, function (i, v)
		{
			var url = encodeURIComponent(window.location.href);
			var title = encodeURIComponent(document.title);
			var bg_x = 16 * v[3];
			v[1] = v[1].replace('{url}', url).replace('{title}', title);
			sn.append('<li><a title="'+v[2]+'" target="_blank" href="http://'+v[0]+'/'+v[1]+'" style="background: url('+baseUrl+'images/sn.png) -'+bg_x+'px 0 no-repeat;"></a></li>');
		});
	$('#social-networks').append(sn).append('<p id="social-networks-title">&hellip;</p>');
	$('#social-networks li a')
		.mouseover(function()
			{
				$('#social-networks-title').html(this.title);
			})
		.mouseout(function()
			{
				$('#social-networks-title').html('&hellip;');
			});
*/

	$('#float-buttons').pk_fixed();
	$('#float-buttons-blocks').pk_slide_tabs({wrapper:'#float-buttons'});

	$("a[rel=lightbox]").fancybox({
		'titleShow': false,
		'opacity': 0.3,
		'hideOnContentClick': true,
		'speedIn': 150,
		'speedOut': 50,
		'changeFade': 'fast'
	});

	 $('#entry-rating input[type=radio]').rating({
	 	'required': true,
	 	'focus': function ()
			{
				$('#entry-rating-title').html(this.title);
			},
	 	'blur': function ()
			{
				$('#entry-rating-title').html('Рейтинг');
			},
	 	'callback': function (el, v)
			{
				$('#entry-rating').submit();
			}
	 	});


	// run galleria and add some options
	Galleria.loadTheme('/js/galleria/themes/alexs/galleria.alexs.js');
	
	var galleria_rgx = new RegExp('^(.+)\\.(png|gif|jpg)$', 'i');
	$('.galleria').each(function()
		{
			$('#'+this.id).galleria({
				height: 400,
				max_scale_ratio: 1,
				image_crop: false,
				thumb_crop: false,
				transition: 'fade',
				thumb_quality: true,
				data_config: function(img)
					{
						var thumb, big_url, m;
						var parent = $(img).parents('.galleria-row');
						var anchor = img.parentNode;
						if (anchor && anchor.nodeName == 'A' && (m = galleria_rgx.exec(anchor.href)))
						{
							big_url = anchor.href;
							thumb = m[1] + '_thumb.' + m[2];
						}
						var descr = parent ? parent.find('.descr').text() : '';
						return {
							'title': descr || img.alt,
							'description': '',
							'image': img.src,
							'thumb': thumb || img.src,
							'link': '',
							'big_url': big_url
							};
					}
				});
		});



/*
	$("a[rel=lightbox]").lightbox({
		fileLoadingImage : baseUrl + 'js/lightbox/images/loading.gif',
		fileBottomNavCloseImage : baseUrl + 'js/lightbox/images/closelabel.gif',
		overlayOpacity: 0.3,
		resizeSpeed: 150,
		displayTitle: false,
		fitToScreen: true,
		imageClickClose: true,
		strings: {
			help: 'help',
			prevLinkTitle: 'предыдущая картинка',
			nextLinkTitle: 'следующая картинка',
			prevLinkText:  '&laquo; Предыдущая',
			nextLinkText:  'Следующая &raquo;',
			closeTitle: 'закрыть',
			image: 'Картинка ',
			of: ' из '
			}
		});
*/

/*
	$('#entry-rating').each(function()
		{
			var button = $(this);
			var wrap = $('#entry-rating-select-wrap').eq(0);
			var panel = $('#entry-rating-select').eq(0);

			button.show = false;
			wrap.hide();
			
			var width = 0;

			$(document).click(function(ev)
				{
					if (
						button.show
						&&
						( ! $(ev.target).parents().is('#entry-rating-select-wrap') )
						)
					{
						button.click();
					}
				});
		
			button.click(function()
				{
					if ( ! button.show)
					{
						button.show = true;
						wrap.show();
						if ( ! width)
						{
							width = panel.outerWidth();
							wrap.width(width);
							wrap.height(panel.outerHeight());
						}
						panel.stop().animate({
							'right': 0
							}, 150);
					}
					else
					{
						button.show = false;
						panel.stop().animate({
							'right': -width
							}, 150, function(){ wrap.hide(); });
					}
					return false;
				});
		});
*/


});
