
var addthis_pub = 'macster2';
var addthis_options = 'livejournal, facebook, twitter, favorites, google, more';

var int = 0;


$(document).ready(function() {
	



	if($.browser.msie && $.browser.version == 6){
		x = function(){
			$(this).addClass('jshover');
		}
		
		y = function(){
			$(this).removeClass('jshover');
		}
		
		$(".wrap_icon").hover(x, y);
		

			
	}









	$('.itemlist').each(function(){
		//alert ($(this).find('div.switch_l').height());
		if ($(this).find('div.switch_l').height() > $(this).find('div.switch_r').height())
			$(this).height($(this).find('div.switch_l').height()+42);
		else
			$(this).height($(this).find('div.switch_r').height()+42);
			
		if ($.browser.msie && $.browser.version == 6) {
			$("img.png").ifixpng();
		}	
			
	});


	$('.content .itemlist h2').hover(function(){
		
		if (!$(this).hasClass('swl_active') && !$(this).hasClass('swr_active')) $(this).addClass('hov');
	}, function(){
		
		if (!$(this).hasClass('swl_active') && !$(this).hasClass('swr_active')) $(this).removeClass('hov');
	}).click(function(){
		$(this).removeClass('hov');
		if (!$(this).parent().find('div.switch_r, div.switch_l').is(':animated')) {
			if ($(this).hasClass('switch_r')) {
				$(this).addClass('swr_active');
				$(this).parent().children('h2').removeClass('swl_active');
				
				$(this).parent().children('div.switch_l').animate({
					left: '-356px'					 
				}, 300, function(){
					$(this).parent().children('div.switch_r').animate({
						left: '0px'				 
					}, 300);
				});
				
				
			}
			if ($(this).hasClass('switch_l')) {
				$(this).addClass('swl_active');
				$(this).parent().children('h2').removeClass('swr_active');
				
				$(this).parent().children('div.switch_r').animate({
					left: '-356px'					 
				}, 300, function(){
					$(this).parent().children('div.switch_l').animate({
						left: '0px'				 
					}, 300);
				});

			}
		}
				
	});
	
	$('.search input.text').blur(function() {
          if(this.value=='') this.value = this.defaultValue;
    }).focus(function() {
          if(this.value == this.defaultValue) this.value = '';
    });
	
	$('#topmenu td').each(function(){
		if ($(this).children('.submenu') != null) {
			$.subm = $(this).children('.submenu');
			$.subm.css('margin-left','-' + ($.subm.width()/2-$(this).width()/2 - 18) + 'px');
			td = $.subm.get(0);
			if (td) {
				var offLeft = td.offsetLeft;
				if (offLeft <= 0)  {
					//alert (offLeft);
					$.subm.css('margin-left', '8px').css('left','0px');
				}
			}
		}
	});
	$('#topmenu td').hover(mainMenu.mouseOver, mainMenu.mouseOut);
	
	$('.submenu').hover(function(){
		$('#topmenu').removeClass('topmenu_ia');
		$(this).parent().addClass('hover');
						
	}, function(){
		//$('#topmenu td').removeClass('hover');
		//$('#topmenu').addClass('topmenu_ia');
	});
	
	//alert ($(window).width());
	
	var w = $('#sideban_left img').width();
	$('#sideban_left').width(w).css('margin-left', -(w+$('#container').width()/2) + 'px');
	
	w = $('#sideban_right img').width();
	$('#sideban_right').width(w).css('margin-right', -(w+($('#container').width()/2)-1) + 'px');
	
	if ($.browser.msie && $.browser.version == 6) {
		
		$('.body_video #sideban_left').css('margin-left', -(w+28+$('#container').width()/2) + 'px');
		var maxWidth = ($('#sideban_right').width()*2)+$('#container').width()-2;
		var mRight =  -($('#sideban_right img').width()+$('#container').width()/2);
		if ($('body').hasClass('body_video')) maxWidth = maxWidth - 180;
		$(window).resize(function(){
			
			if ($('body').width()<=maxWidth) {
				$('#sideban_right').css({
					'right':'0px',
					'margin-right':'0px'					
				});
			} else {
				$('#sideban_right').css({
					'right':'50%',
					'margin-right': mRight+'px'					
				});
				$('.body_video #sideban_right').css({
					'margin-right': mRight+90+'px'					
				});
			}
			if ($(window).width() <= 918) $('body').css('width','916px');
			else $('body').css('width','auto')
		});
		$(window).resize();
	}
	
	try {
		if ($('.nslide').width() > $('.numlist').width()) {
			$.prec = $('.nslide span').prevAll('a');
			var precWidth = 0;
			$.prec.each(function(){
				precWidth = precWidth + $(this).width() + 3;			 
			});
			precWidth = precWidth + $('.nslide span').width();
			$('.nslide').css('left','-' + precWidth + 'px');
			$('.slider').slider({
				min:0,
				max:$('.nslide').width()-235,
				value: precWidth,
				slide: function(event, ui) {
					$('.nslide').css('left','-' + ui.value + 'px');
				}
		
			});
		} else $('.slider').html('<div class="ui-slider-handle"></div>');
		
		if ($('.nslide').width() < $('.numlist').width())
			$('.slider').slider('disable').children('.ui-slider-handle').css('opacity','0.5');
	}	catch(err){
		
        return false;
    }


	$('#leftmenu .wr').hover(function(){
		if (!$(this).parent().hasClass('active'))
			$(this).addClass('hov');
	}, function(){
		if (!$(this).parent().hasClass('active'))
			$(this).removeClass('hov');
	});
	
	$('.art_feat a.bci').click(function(){

		$.popup = $(this).closest('li').find('.miniPoPab');
		if ($.popup.css('display') == 'none') {
			$.popup.show();
			var txtArea = $('#txAreaBlogCode');
			txtArea.caret(0, txtArea.val().length);
		} else {
			$.popup.hide();
		}
			
		return false;
	});
	
	$('.addthis a').click(function(){
		return addthis_sendto();						   
	}).mouseover(function(){
		return addthis_open(this, '', $(this).attr('rev'), $(this).attr('name'));
	}).mouseout(function(){
		addthis_close();
	});
	
	$('.reglink').click(function(){
		if ($('#regform').css('display') == 'none') {
			regForm.open();
		} else {
			regForm.close();
		}
		return false;
	});
	
	$('.maillink').click(function(){
		if ($('#mailform').css('display') == 'none')
			$('#mailform').show();
		else
			$('#mailform').hide();
		return false;
	});
	
	$('.popform .close').click(function(){
		$(this).closest('.popform').hide();
		return false;
	});
	$('.miniPoPab_content .close').click(function(){
		$(this).closest('.miniPoPab').hide();
		return false;
	});
	
	
	
	/*$('.topic h3 a, .topic_pop').hover(function(){							
		$('.topic .topic_pop').hide();
		
		clearTimeout(int);
		$toshow = $(this).closest('.topic').children('.topic_pop').addClass('pop-active');
		$toshow.show();
		
	}, function(){

		$toshow = $(this).closest('.topic').children('.topic_pop').addClass('pop-active');
		int = setTimeout("$toshow.hide()", 1000);

	});*/

	$('.topic h3 a, .topic_pop').mouseover(topic_over);
	$('.topic h3 a, .topic_pop').mouseout(topic_out);

	$('.ok').click(function(){
		$(this).closest('form').get(0).submit();	
		return false;
	});
	
	
	
	try {
		$(".content a[href^='upload/tiny'] img").each(function() {
			$(this).closest('a').addClass('hsGroup').click(function() {
				return hs.expand(this);
			})
		})
		
	} catch (err) {
	}
	
	$('a[rel="blank"]').click(function(){
		window.open($(this).attr('href'));
		return false;
	});
	if ($('body').hasClass('print')) window.print();

	$('.forum-post .reply a').unbind('click').click(function(){
		
		
		if ($(this).parent().hasClass('delete-down')) {
			return true;
		}
		
		
		var t = $(this);
		var id = t.attr('rel');
		xbb_ta = $(window.xbb_editor.document.getElementById('xbb_textarea'));
		if ( ! t.parent().hasClass('reply-up')) {
			var post	= t.closest('div.forum-post-wrap');
			var nick	= $('div.avatar p a', post).text();
			var text	= posts[id];
			var oldVal	= xbb_ta.val();
			var newVal	= oldVal;
			
			if (oldVal != '') {
				newVal += '[hr]' + "\n";
			}
			newVal		+= '[quote="'+ nick +'"] '+ text +'[/quote] ' + "\n";
			
			xbb_ta.val(newVal);
			$('.post-reply input[name="name"]').val('Тема моего ответа');
			// XBB.innerText = 'test';
			setCaretPosition(xbb_ta.get(0), newVal.length);
			xbb_ta.scrollTo(10000);
			
		}
		
		xbb_ta.focus();
		$.scrollTo('.post-send',500);
		return false;
		
	});

	
	/*************************
	**		Для форума		**
	*************************/
	

	// Что бы в форме создания темы, при выборе первого пункта, цвет становился другим
	$('select.category').change(forumCatChange);
	forumCatChange();	// Что бы сразу поставился.
	
	
	
	
	
	
	
	// Сделать чтобы все создаваемые в тексте ссылки по умолчанию открывались в новом окне.
	$('div.context div.text a').each(function() {
		
		var t		= $(this);
		var href	= t.attr('href');
		var regex	= /^http([s]{0,1}):\/\//;
		var sregex	= /^http:\/\/www\.macster\.ru/;
		
		// alert('href='+href + '\ntarget=' + t.attr('target'));
		if (t.attr('target') == '' && t.attr('rel') != 'blank' && regex.test(href) && ! sregex.test(href)) {
			t.attr('target', '_blank');
			// alert('Сделали '+ href +' target="_blank"');
		}
		
	});
	
	
	$('.item p:not(:has(a))').each(function () {
		var t = $(this);
		var href = t.parent().find('h2 a, h3 a').attr('href');
		if (href) {
			t.html('<a href="'+ href +'">'+ t.html() +'</a>');
		}
		
	})
	
	
	
	
	
	if ($('div.marq-anonces').size() > 0) {	// Если есть список анонсов в виде бегущей строки.
		
		var marqueeDelay		= 10;
		var marqueeDelta		= 1;
		var marqueeInner		= $('.marq-inner');
		var marqueeOuterWidth	= $('div.marq-anonces').width();
		var marqueeInnerWidth	= marqueeInner.width();
		
		$('span', marqueeInner).each(function() {
			var t		= $(this);
			// alert(t.attr('class'));	// href
			t.replaceWith('<a href="'+ t.attr('class') +'">'+ t.text() +'</a>');
			
		})
		
		marqueeInner.css('left', marqueeOuterWidth/2 + 'px');
		
		setInterval(function() {
			var newVal = parseInt(marqueeInner.css('left')) - marqueeDelta;
			
			if (Math.abs(newVal) > marqueeInnerWidth) {
				newVal = marqueeOuterWidth;
			}
			
			marqueeInner.css('left', newVal + 'px');
		}, marqueeDelay);
		
	}
	
	
	
	
	
	
	
	
	
	
});


topicInTL		= null;
topicOutTL		= null;
lastHoverTopic	= null

function topic_over () {
	lastHoverTopic = $(this);
	clearTimeout(topicInTL);
	topicInTL = setTimeout(topicTooltipOpen, 750);
	
}


function topic_out () {
	clearTimeout(topicInTL);
	$toshow = $(this).closest('.topic').children('.topic_pop').addClass('pop-active');
	int = setTimeout("$toshow.hide()", 750);
}



function topicTooltipOpen() {
	$('.topic .topic_pop').hide();
	$toshow = lastHoverTopic.closest('.topic').children('.topic_pop').addClass('pop-active');
	$toshow.show();
}



forumCatChange = function() {
	
	var t = $('select.category');
	if (t.val() == '') {
		t.css('color', '#CCCCCC');
		$('option, optgroup', t).css('color', '#000000');
		$('option:first', t).css('color', '#CCCCCC');
	} else {
		t.css('color', '#000000');
		$('option:first', t).css('color', '#CCCCCC');
	}
	
}



function postScrollTo(id) {
	
	
	var item = $('#postItem'+id);
	if (item.size() > 0) {
	
		var offsetX = ($(window).height()/4) * -1;
		$.scrollTo(item, 1000, {
			// easing : 'easeOutElastic',
			offset : {top:offsetX}
			}
		);
	}
}


function goToAuth() {
	
	$.scrollTo(0, 1000, {
		onAfter : function() {
			$('div.auth input[name="authLogin"]').focus();
		}
	});
	
}

function goToRegistration() {
	$.scrollTo(0, 1000, {
		onAfter : function() {
			regForm.open();
		}
	});
}

/**
 * Класс для работы с регистрационной формой
 * 
 */
regForm = {
	
	open : function() {
		
		if ($('#regSubmit').size() <= 0) {	// Если форма ещё не загружена
			$('#regFormId').load('getRegFormContent.php');
		}
		
		
		$('#regform').show();
	},
	
	close : function() {
		$('#regform').hide();
	}
}





function setCaretPosition (elem, caretPos) {
    if (document.selection) { // ie
        elem.focus();
        var range = document.selection.createRange();
        range.moveStart ('character', -elem.value.length);
        range.moveStart ('character', caretPos);
        range.moveEnd ('character', 0);
        range.select ();
    } else if (elem.selectionStart || elem.selectionStart == '0') { // Mozilla
        elem.selectionStart = caretPos;
        elem.selectionEnd = caretPos;
        elem.focus ();
    }
}






function addToClippboard(text)
{
	
	if (typeof(window.clipboardData) != 'undefined') {
		if (window.clipboardData.setData('Text', text)) {
			alert('Код скопирован в буфер обмена Windows.');
		} else {
			alert('Ваш браузер не поддерживает операции с буфером обмена.');
		}
	} else {
		alert('Ваш браузер не поддерживает операции с буфером обмена.');
	}
}


function addButtonAddClippboard()
{
	
	if (typeof(window.clipboardData) != 'undefined') {
		document.write('<a class="kopirovat" href="javascript:void(0);" onclick="addToClippboard($(\'#txAreaBlogCode\').val());" >Копировать</a>');
	}
	
}



function setPodProductBoxDivHeight()
{
	$(document).ready(function() {
		var h = $('.context .round_box').height();
		$('.context .text .hidden').height(h+10);
	})
}







mainMenu = {
	
	timeOut : null,
	t : null,
	
	mouseOver : function()
	{
		
		// pr2('open: ' + (new Date().getMilliseconds()));
		
		
		if (mainMenu.timeOut != null) {
			mainMenu.close();
		}
		
		mainMenu.t = $(this);
		mainMenu.open();
		
	},
	
	mouseOut : function()
	{
		
		// pr2('close: ' + (new Date().getMilliseconds()), 500, 100, 'dump2');
		
		mainMenu.t = $(this);
		
		if (mainMenu.t.children('.submenu').html() != null) {
			mainMenu.timeOut = setTimeout(mainMenu.close, 2000);
		} else {
			mainMenu.close();
		}
		
		
	},
	
	open : function()
	{
		
		if (mainMenu.t.children('.submenu').html() != null) {
			$('#topmenu').removeClass('topmenu_ia');
		}
		mainMenu.t.addClass('hover');
						
	},
	
	close : function()
	{
		
		if (mainMenu.timeOut != null) {
			clearTimeout(mainMenu.timeOut);
			mainMenu.timeOut = null;
		}
		
		
		$('#topmenu td').removeClass('hover');
		if (mainMenu.t.children('.submenu').html() != null) {
			$('#topmenu').addClass('topmenu_ia');
		}
		
	}
	
	
	
	
}















function scrollToArticle() {
	
	$(document).ready(function() {
		var item = $('#articleTitleH');
		if (item.size() > 0) {
		
			var offsetX = ($(window).height()/2) * -1;
			$.scrollTo(item, 500, {
					// easing : 'easeOutElastic',
					offset : {top:offsetX}
				}
			);
		}
	});
}








/**
 * Аналог для print_r()
 * 
 * @param	mixed	variable	Переменная любого типа
 */
function WFpr(variable) {
	if ($.dump) {
		if (typeof(myAlert) != 'undefined') {
			myAlert('<pre>' + $.dump(variable) + '</pre>');
		} else {
			alert($.dump(variable));
		}
	} else {
		myAlert('Не подключено расширение jQuery.dump');
	}
}



function pr2(variable, x, y, id) {
	
	id = id || 'dump';
	
	if ( ! $.dump) {
		alert('Не подключено расширение jQuery.dump');
	}
	
	
	if ($('#' + id).size() <= 0) {
		x = x || 200;
		y = y || 200;
		$('body').append('<pre style="min-width: 150px; position:absolute; top:'+ y +'px; left:'+ x +'px; border:1px solid #000000; background-color: #FFFFFF; padding:5px;" id="'+ id +'"></pre>');
	}
	
	
	
	var t = $.dump(variable);
	t = t.replace(/	/g, '    ');
	
	
	$('#' + id).text(t);
}

/**
*
*  Javascript trim, ltrim, rtrim
*  http://www.webtoolkit.info/
*
**/
 
function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}


// -->

