/* -------------- block_auth_01 -------------- */
jQuery(function($) {
	$('#holod_add').click(function(e) {
		var items = $('#holod_element_marg').find('div.holod_element:hidden');
		if ( items.length ) items.eq(0).show();
		if ( items.length <= 1 ) $(this).attr('class', 'holod_add_none');
		e.preventDefault();
	});
				
	$('#block_auth_01').click(function() {
		$(this).css('display', 'none');
		$('#block_auth_02').css('display', '');
	});
	
	new $.menudrop({
		link : '#blueheader .more a.link_more',
		layer : '#portalMenu',
		dropEvent : 'click'
	});
	
	var menuHide = function() {
		$('.menu .jsdrop').each(function() { classChange(this); }).next().hide();
	},
	classChange = function(a, add) {
		$(a).parents('td:first').each(function() {
			var c = $(this).attr('class').replace('_on', '');
			$(this).attr('class', add || c == defaultMenu ? c + '_on' : c);
		});
	}
	defaultMenu = null;
	$('.menu .jsdrop').each(function() {
		var c = $(this).parent().parent().attr('class');
		if ( c && c.indexOf('_on') != -1 ) defaultMenu = c.replace('_on', '');
		if ( $(this).next() ) new $.menudrop({
			link  : this,
			layer : $(this).next(),
			onBeforeDrop : function() { menuHide(); classChange(this.link, true); },
			onHide : function() { classChange(this.link); }
		});
		else $(this).mouseover(menuHide);
	});
});
/* -------------- /block_auth_01 -------------- */



/* -------------- menudrop -------------- */

(function($) {
	$.menudrop = function(o) {
		$.extend(this, {
			link: '', layer: '',
			dropEvent: 'mouseover', hideEvent: 'mouseout', stopEvent: 'mousemove',
			onBeforeDrop: function() {}, onAfterDrop: function() {}, onHide: function() {},
			timer: null, delay: 500
		}, o || {});
		this.init();
	}
	$.menudrop.prototype = {
		init: function() {
			var t = this;
			$(this.link).bind(this.dropEvent, function(e){ t.show(); e.preventDefault(); e.stopPropagation()});
			$(this.link).add(this.layer)
				.bind(this.hideEvent,function(){ t.timer=setTimeout(function(){t.hide()},t.delay) })
				.bind(this.stopEvent,function(){ clearTimeout(t.timer) });
		},
		show: function() { this.onBeforeDrop(); $(this.layer).show(); this.onAfterDrop(); },
		hide: function() { $(this.layer).hide(); this.onHide(); }
	}
	
	$.ladyIndex = function(o) {
		$.extend(this, { bg: '', list: '', cur: 'on', images: [], index: 0, timer: null, interval: 5000 }, o || {});
		var t = this;
		$(function() { t.init(); });
	}
	$.ladyIndex.prototype = {
		init: function() {
			var t = this;
			if ( !this.bg || !this.list || !this.images.length ) return;
			$('<div></div>')
				.css({ position: 'absolute', top:0, left:0, visibility:'hidden' })
				.html('<img src="' + this.images.join('"><br><img src="') + '">')
				.appendTo('body');
			$(this.list).each(function(i) {
				$(this)
					.mouseover(function() { t.set(i); })
					.mousemove(function() { clearTimeout(t.timer); })
					.mouseout(function() { t.timer = setTimeout(function() { t.next(); }, t.interval); })
			});
			t.timer = setTimeout(function() { t.next(); }, t.interval);
		},
		set: function(i) {
			var href;
			$(this.list)
				.removeClass(this.cur)
				.eq(i)
				.addClass(this.cur)
				.find('a')
				.each(function() { href = this.href });
			if ( this.images[i] ) $(this.bg).css('background-image', 'url('+this.images[i]+')');
			if (href) $(this.bg)
				.unbind('click')
				.click(function() { location.href = href; });
			this.index = i;
			clearTimeout(this.timer);
		},
		next: function() {
			var t = this;
			this.set( (this.index + 1) % this.images.length );
			t.timer = setTimeout(function() { t.next(); }, t.interval);
		}
	}
})(jQuery);

/* -------------- /menudrop -------------- */



/* -------------- gallery -------------- */

(function($) {
	$.ladyPrevlist = function(o) {
		$.extend(this, {
			inner: null,
			left: null,
			right: null,
			list: null,
			timer: null,
			interval: 1, // ms
			step: 10, // px
			required: ['inner', 'left', 'right'],
			move: false,
			one: false,
			classname: 'visibl_on',
			onclass: 'td.img_bord_on'
		}, o || {});
		this.init();
	}
	$.ladyPrevlist.prototype = {
		init: function() {
			var i, p, t = this;
			try {
				for (i = this.required.length; i--;)
					if ( !(p = this[this.required[i]]) )
						throw "Init: required property " + this.required[i];
					else this[this.required[i]] = $(p);
			} catch(e) { this.log(e); return; }
			this.right
				.mousedown(function(e) { t.move = 'rightMove'; t.startMove(); e.preventDefault(); })
				.click(function(e) { e.preventDefault(); });
			this.left
				.mousedown(function(e) { t.move = 'leftMove'; t.startMove(); e.preventDefault(); })
				.click(function(e) { e.preventDefault(); });
			$(document).mouseup(function() { t.move = false; clearInterval(t.timer); });
			$(window).resize(function() { t.checkMove(); });
			setTimeout( function() {
				if ($(t.inner).find(t.onclass).length) t.inner.scrollLeft(Math.max(0, $(t.inner).find(t.onclass)[0].offsetLeft - $(t.inner).width() / 2));
				t.checkMove();
			}, 10 ); // ie fix
			if (t.list) {
				$(t.list).mouseover(function() {
					$(t.list).removeClass('on');
					$(this).addClass('on');
				});
			}
		},
		startMove: function() {
			var t = this;
			if (t.move) {
				t[t.move]();
				t.timer = setInterval(function() { t[t.move](); }, t.interval);
			}
		},
		rightMove: function() {
			this.inner.scrollLeft( this.inner.scrollLeft() + this.step );
			this.checkMove();
		},
		leftMove: function() {
			this.inner.scrollLeft( this.inner.scrollLeft() - this.step );
			this.checkMove();
		},
		checkMove: function() {
			this.left.toggleClass(this.classname, this.inner.scrollLeft() > 0);
			this.right.toggleClass(this.classname, this.inner.scrollLeft() + this.inner.width() < this.inner[0].scrollWidth);
		},
		log: function() { if ( window.console && window.console.log ) console.log(arguments); }
	}
})(jQuery);

/* -------------- /gallery -------------- */


/* -------------- usermenu -------------- */

// Функция для определения размеров видимой области окна браузера
function screenSize() {
	var w, h; // Объявляем переменные, w - длина, h - высота
	w = (window.innerWidth) ? window.innerWidth : window.document.body.clientWidth;
	h = (window.innerHeight) ? window.innerHeight : window.document.body.clientHeight;
	return {w:w, h:h};
}
// Функция для добавления обработчика события
function addHandler(object, event, handler, useCapture) {
	if (object.addEventListener) {
		object.addEventListener(event, handler, useCapture ? useCapture : false);
	} else if (object.attachEvent) {
		object.attachEvent('on' + event, handler);
	} else alert("Add handler is not supported");
}
// Функция для удаления обработчика события
function removeHandler(object, event, handler) {
	if (object.removeEventListener) {
		object.removeEventListener(event, handler, false);
	} else if (object.detachEvent) {
		object.detachEvent('on' + event, handler);
	} else alert("Remove handler is not supported");
}
// Функция для предотвращения всплывания событий
function cancelBubbling(evt) {
	evt = evt || window.event;
	evt.cancelBubble = true;
}
// Функция показывает div с информацией
function userMenuShow(_link, evt) {
	// Заблокируем всплывание события
	cancelBubbling(evt);
	// Определение Gecko
	var ua = navigator.userAgent.toLowerCase();
	var isGecko = ua.indexOf("gecko") != -1;
	var mail = _link.href.substring(_link.href.indexOf("to=") + 3, _link.href.length);
	// Формируем HTML-код div-а
	var html = '<a href="http://www.mail.ru/agent?message&to=' + mail + '&from=horo"><img class="icon" src="http://img.mail.ru/mail/ru/images/mail-all.gif" width="16" height="16" alt="Добавить в агент">Добавить в агент</a><br><a href="http://win.mail.ru/cgi-bin/sentmsg?To=' + mail + '&from=horo"><img class="icon2" src="http://img.mail.ru/mail/ru/images/head2_2.gif" width="18" height="17" alt="Написать письмо">Написать письмо</a><br><a href="http://cards.mail.ru/?rcptemail=' + mail + '&from=horo"><img class="icon" src="http://img.mail.ru/mail/ru/images/cards2-all.gif" width="16" height="17" alt="Отправить открытку">Отправить открытку</a><br>';
	// Покажем div
	var div = document.getElementById("userDropDownId");
	div.innerHTML = html;
	// Задаем положение div-а
	div.style.top = absPosition(_link).y + _link.offsetHeight + 'px';
	div.style.left = ((screenSize().w - absPosition(_link).x - div.offsetWidth > 0) ? absPosition(_link).x : absPosition(_link).x - div.offsetWidth + _link.offsetWidth) + 'px';
	div.style.visibility = "visible";
	// Запрещаем всплывание событий при клике по ДИВу
	addHandler(div, "click", function(evt){cancelBubbling(evt);});
	return false;
}
// Функция для скрытий div-a по клику на документ
function userMenuHide() {
	var div = document.getElementById("userDropDownId");
	// Удаляем обработчик всплывания при клике по ДИВу
	if (div) {
		removeHandler(div, "click", function(evt){cancelBubbling(evt);});
		div.style.visibility = "hidden";
	}
}
// Опрелеляем top - left координаты блока obj
function absPosition(obj) {
	this.x = 0;
	this.y = 0;
	while(obj) {
		this.x += obj.offsetLeft;
		this.y += obj.offsetTop;
		obj = obj.offsetParent;
	}
	return {x:this.x,y:this.y};
}
// Добавим обработку клика 
addHandler(document, "click", userMenuHide);

/* -------------- /usermenu -------------- */

/* -------------- swfobject -------------- */

(function ($, flash) {
	var createAttrs = function (obj) {
		var aEach,
		aArray = [];

		for (aEach in obj) {
			if (/string|number/.test(typeof obj[aEach]) && obj[aEach] !== '') {
				aArray.push(aEach + '="' + obj[aEach] + '"');
			}
		}

		return aArray[j]('');
	},
	createParams = function (obj) {
		var aEach,
		bEach,
		aArray = [],
		bArray;

		if (typeof obj == 'object') {
			for (aEach in obj) {
				if (typeof obj[aEach] == 'object') {
					bArray = [];
					for (bEach in obj[aEach]) {
						bArray.push([bEach, '=', encodeURIComponent(obj[aEach][bEach])][j](''));
					}
					obj[aEach] = bArray[j]('&amp;');
				}
				if (obj[aEach]) {
					aArray.push(['<param name="', aEach, '" value="', obj[aEach], '" />'][j](''));
				}
			}
			obj = aArray[j]('');
		}
		return obj;
	},
	expressInstallIsActive = false,
	j = 'join';

	$[flash] = (function () {
		try {
			var flashVersion = '0,0,0',
			Plugin = navigator.plugins['Shockwave Flash'] || ActiveXObject;

			flashVersion = Plugin.description || (function () {
				try {
					return (new Plugin('ShockwaveFlash.ShockwaveFlash')).GetVariable('$version');
				}
				catch (eIE) {}
			}());
		}
		catch(e) {}

		flashVersion = flashVersion.match(/^[A-Za-z\s]*?(\d+)[\.|,](\d+)(?:\s+[d|r]|,)(\d+)/);

		return {
			available: flashVersion[1] > 0,

			activeX: Plugin && !Plugin.name,

			version: {
				major: flashVersion[1] * 1,
				minor: flashVersion[2] * 1, 
				release: flashVersion[3] * 1
			},

			hasVersion: function (version) {
				var versionCompare = this.version,
				major = 'major',
				minor = 'minor',
				release = 'release';

				version = (/string|number/.test(typeof version)) ? version.toString().split('.') : version || [0, 0, 0];

				version = [
					version[major] || version[0] || versionCompare[major],
					version[minor] || version[1] || versionCompare[minor],
					version[release] || version[2] || versionCompare[release]
				];

				return (version[0] < versionCompare[major]) || (version[0] == versionCompare[major] && version[1] < versionCompare[minor]) || (version[0] == versionCompare[major] && version[1] == versionCompare[minor] && version[2] <= versionCompare[release]);
			},

			expressInstall: 'http://lady.mail.ru/expressInstall.swf',

			create: function (obj) {
				if (!$[flash].available || expressInstallIsActive || !typeof obj == 'object' || !obj.swf) {
					return false;
				}

				if (obj.hasVersion && !$[flash].hasVersion(obj.hasVersion)) {
					obj = {
						swf: obj.expressInstall || $[flash].expressInstall,
						attrs: {
							id: obj.id || 'SWFObjectExprInst',
							name: obj.name,
							height: Math.max(obj.height || 137),
							width: Math.max(obj.width || 214)
						},
						params: {
							flashvars: {
								MMredirectURL: location.href,
								MMplayerType: ($[flash].activeX) ? 'ActiveX': 'PlugIn',
								MMdoctitle: document.title.slice(0, 47) + ' - Flash Player Installation'
							}
						}
					};

					expressInstallIsActive = true;
				}
				else {
					obj = $.extend(
						true,
						{
							attrs: {
								id: obj.id,
								name: obj.name,
								height: obj.height || 180,
								width: obj.width || 320
							},
							params: {
								wmode: obj.wmode || 'opaque',
								flashvars: obj.flashvars
							}
						},
						obj
					);
				}

				if ($[flash].activeX) {
					obj.attrs.classid = obj.attrs.classid || 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000';
					obj.params.movie = obj.params.movie || obj.swf;
				}
				else {
					obj.attrs.type = obj.attrs.classid || 'application/x-shockwave-flash';
					obj.attrs.data = obj.attrs.data || obj.swf;
				}

				return ['<object ', createAttrs(obj.attrs), '>', createParams(obj.params), '</object>'][j]('');
			}
		};
	}());

	$.fn[flash] = function (args) {
		if (typeof args == 'object') { 
			this.each(
				function () {
					var test = document.createElement(flash);


					var newFlash = $[flash].create(args);
					if (newFlash) {
						test.innerHTML = newFlash;
						if (test.childNodes[0]) {
							this.appendChild(test.childNodes[0]);
						}
					};
				}
			);
		}
		else if (typeof args == 'function') {
			this.find('object').andSelf().filter('object').each(
				function () {
					var elem = this,
					jsInteractionTimeoutMs = 'jsInteractionTimeoutMs';

					elem[jsInteractionTimeoutMs] = elem[jsInteractionTimeoutMs] || 0;

					if (elem[jsInteractionTimeoutMs] < 660) {
						if (elem.clientWidth || elem.clientHeight) {
							args.call(this);
						}
						else {
							setTimeout(
								function () {
									$(elem)[flash](args);
								},
								elem[jsInteractionTimeoutMs] + 66
							);
						}
					}
				}
			);
		}

		return this;
	};
}(jQuery, 'flash'));

/* -------------- /swfobject -------------- */

/* -------------- default -------------- */
// Листалка страницы через клавиатуру Ctrl+стрелка 
function listpage(event)
{
	if (!event) event = window.event;
	var key = event.keyCode;
	if (event.ctrlKey)
	{
		var tagName = (event.target || event.srcElement).tagName;
		if (tagName != 'INPUT' && tagName != 'TEXTAREA')
		{
			var doc;
			if (key == 37) doc = document.getElementById('previous_page');
			if (key == 39) doc = document.getElementById('next_page');
			if (doc) location.href = doc.href;
		}
	}
}
/* -------------- /default -------------- */

/* -------------- для блока персональных горосокопов -------------- */
(function($){

	$.slider = function(options) {
		this.options = $.extend(this.options, options);
		
		var this_ = this;
		$(function(){ this_.realInit(); });
	};
	
	$.slider.prototype = {
		options: {
			selectors: {
				container: '',
				prevLink: '',
				nextLink: '',
				blocks: '> div'
			},
            loop: true
		},
		currentPage: 1,	
		
		realInit: function() {
			this.container = $(this.options.selectors.container);
			if (!this.container) {
				return false;
			}
			
			var blocks = this.container.find(this.options.selectors.blocks);
			this.totalPages = blocks.length;
			this.blockWidth = blocks.eq(0).width();
			this.container.width(this.blockWidth * this.totalPages);
		
			var this_ = this;
			this.prevLink = $(this.options.selectors.prevLink);
			this.prevLink.click(function(){ this_.prev(this); return false; });
			this.nextLink = $(this.options.selectors.nextLink);
			this.nextLink.click(function(){ this_.next(this); return false; });
			
			this.updateLinks();		
		},
		
		prev: function(elem) {
			this.changePage(elem, -1);
		},
		
		next: function(elem) {
			this.changePage(elem, 1);
		},
	
		changePage: function(link, direction) {
			if ($(link).hasClass('disabled')) {
				return;
			}
            
            var shift = this.blockWidth;
            if ((this.currentPage == 1 && direction == -1) || (this.currentPage == this.totalPages && direction == 1)) {
                direction = -direction;
                shift *= this.totalPages-1;
                this.currentPage = direction < 0 ? 1 : this.totalPages;
                
            }
            else {
                this.currentPage += direction;
            }
			
			this.container.animate({'left': (direction < 0 ? '+' : '-') + '=' + shift + 'px'});
			this.updateLinks();
		},
		
		updateLinks: function() {
            if (this.options.loop) return;
			this.prevLink.toggleClass('disabled', this.currentPage == 1);
			this.nextLink.toggleClass('disabled', this.currentPage == this.totalPages);
		}
	};
	
	new $.slider({
		selectors: {
			container: '#personal_horo .links_container',
			prevLink: '#personal_horo .links_three_prev',
			nextLink: '#personal_horo .links_three_next',
			blocks: 'table'
		}
	});
	
})(jQuery);
/* -------------- /для блока персональных горосокопов -------------- */

