/* 
block_auth_01 
menudrop
gallery
usermenu
swfobject
*/


/* -------------- 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 -------------- */

/* -------------- mistake -------------- */
	(function($) {
		$.mistake = function(selector) {
			$(document).keydown(function(e) {
				if (e.keyCode == 27)
					$('#mistaker').hide();
				if (e.ctrlKey && e.keyCode == 13) {
					$('span.dirty-clipboard').remove();
					var txt = window.getSelection ? window.getSelection().toString() : document.selection.createRange().text,
						fadeInterval = 2000,
						screen,
						node;
								
					if (window.getSelection) {
						selection = window.getSelection();
						if(selection.getRangeAt) {
							range = selection.getRangeAt(0);
							
							prev = (window.opera)? selection.getRangeAt(0) : document.createRange();
				
							prev.setStartBefore(range.startContainer);
							prev.setEnd(range.startContainer,range.startOffset);
							prev = prev.toString();
				
							if (prev.length>20)
								prev = prev.substring(Math.max(prev.length-30,0),prev.length).replace(/^\S{1,10}\s+/,"");
				
							if (window.opera)
								next = selection.getRangeAt(0);
							else
								next = document.createRange();
				
							next.setStart(range.endContainer, range.endOffset);
							next.setEndAfter(range.endContainer);
							next = next.toString();
							if (next.length > 50)
								next = next.toString().substring(0,30).replace(/\s+\S{1,10}$/,"");
						}
			
					} else if (window.document.selection.createRange) {
						selection = window.document.selection.createRange();
				
						selection.expand("word");
				
						prev = window.document.selection.createRange();
						prev.moveStart("character",-20);
						prev.setEndPoint('EndToStart',selection);
						prev.expand("word");
						prev = prev.text;
				
						next = window.document.selection.createRange();
						next.moveEnd("character", 20);
						next.setEndPoint('StartToEnd',selection);
						next.expand("word");
						next = next.text;
				
						selection = selection.text;
					}
								
					if ( !$('#mistaker').length )
						$('<div id="mistaker" class="layerErrorReport"></div>')
							.appendTo('body')
							.hide();
					$('#mistaker')
						.html('<a class="close" title="Закрыть" href="#close">Закрыть</a>\
							<form method="get" name="send_mistake" action="#">\
							<div class="title">Отправка сообщения об ошибке на странице</div>\
							<input type="hidden" name="action" value="send" />\
							<table><tr>\
								<th>URL</th>\
								<td><input type="text" name="lnk" value="" readonly="readonly" /></td>\
							</tr><tr>\
								<th>Ошибка</th>\
								<td><textarea name="text" cols="10" rows="8" readonly="readonly"></textarea></td>\
							</tr><tr class="submit">\
								<th></th>\
								<td><input type="submit" name="send" value="Отправить" /><a href="#">Закрыть</a></td>\
							</tr></table>\
							</form>')
						.find('a')
						.click(function(e) {
							$('#mistaker').hide();
							e.preventDefault();
						})
						.end()
						.find('form')
						.submit(function(e) {
							var url = '/ext/mistake/params_utf2win?rand=' + Math.random() + '&' + $(this).serialize();
							$.ajax({
								url : url,
								type : 'GET',
								cache : false,
								complete : function() {
									$('#mistaker form').html('<div class="sent">Спасибо за помощь!</div>');
									setTimeout(function() {
										$('#mistaker').fadeOut();
									}, fadeInterval);
								},
								error : function() {
									$('#mistaker form').html('<div class="error">Ошибка при отправлении.</div>');
									setTimeout(function() {
										$('#mistaker').fadeOut();
									}, fadeInterval);
								}
							});
							e.preventDefault();
						});
					if ( txt ) {
						node = window.getSelection ? window.getSelection().anchorNode : document.selection.createRange().parentElement();
						if ( !($(node).parents(selector).length || $(node).is(selector)) ) {
							$('#mistaker').hide();
							return;
						}
						
						$('#mistaker input[name="lnk"]').val(location.href);
						$('#mistaker textarea').val(prev+'['+txt+']'+next);
						
						screen = {
							w : (window.innerWidth ? window.innerWidth : (document.documentElement.clientWidth ? document.documentElement.clientWidth : document.body.offsetWidth)),
							h : (window.innerHeight ? window.innerHeight : (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.offsetHeight))
						}
						
						$('#mistaker')
							.show()
							.css({
								left : ((screen.w - $('#mistaker').width ()) / 2) + 'px',
								top  : ((screen.h - $('#mistaker').height()) / 2 + $(document).scrollTop() ) + 'px'
							});
						e.preventDefault();
					}
				}
			});
		}
	})(jQuery);

jQuery(function($) {
    $.mistake('#art_text');
}); 

/* -------------- /mistake -------------- */


/* -------------- 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=lady"><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=lady"><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=lady"><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: '/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;
		}
	}
}

// Открываем и закрываем разные блоки 
function OnOffBlock (blockon,blockoff) {
	document.getElementById(blockon).style.display = '';
	document.getElementById(blockoff).style.display = 'none';
}

// Открываем и закрываем один блок
function OnBlock (id) {
	var div;
	if (div = document.getElementById(id))
	div.style.display = div.style.display == 'none' ? '' : 'none';
	return false;
}

Array.prototype.shuffle = function() {
	var len = this.length;
	var i = len;
	while (i--) {
		var p = parseInt(Math.random()*len);
		var t = this[i];
		this[i] = this[p];
		this[p] = t;
	}
};

/* -------------- /default -------------- */

