$(document).ready(function(){
	isAnim = 0;
	createWorks();

	$('.work_last .switcher').click( function () { 
		if (isAnim == 0)
			animateSwitcher($(this), showAnimateWorks);
	});
	$('.check, .work_link1, .work_link2, .work_link3').click( function () { 
		if ($(this).children('span').attr('type') == 'bonus') {
			animateBonusBg();
		} else if ($(this).children('span').attr('type') == 'baner') {
			var str = $(this).children('span').attr('banid');
			var ind = str.substr(6);
			showWin('banners', ind);
		} else if ($(this).children('span').attr('type') == 'mailru') {
			window.location = 'http://multiline.ru/mailru.php';
		} else {
			showWin($(this).children('span').attr('rel'), -1);
		}
	});

	$('.mailru_mode_img').click( function () { 
		showWin($(this).attr('rel'), -1);
	});

	
	var curTizer = 0;
	$('.portfolio_block div').hover( function () { 
		var pics_shows = $(this).parents('.portfolio_block').attr('shown');
		if ((typeof (pics_shows) == 'undefined') || (pics_shows == 'hidden')) {
			if ($(this).attr('class') == 'mode_txt hidden' || $(this).attr('class') == 'mode_txt') {
				if ($(this).children('a').attr('class') != curTizer) {
					stillNeedToHide = true;
					$(this).hideTizer();
				}
				if ($('.tizer').css('display') == 'none') $(this).showTizer();
				stillNeedToHide = false;
				curTizer = $(this).children('a').attr('class');
			}
			else if ($(this).attr('class') == 'mode_img hidden' || $(this).attr('class') == 'mode_img') {
				if ($(this).children('a').attr('class') != curTizer) {
					stillNeedToHide = true;
					$(this).hideTizer2();
				}
				if ($('.tizer2').css('display') == 'none') $(this).showTizer2();
				stillNeedToHide = false;
				curTizer = $(this).children('a').attr('class');
			}
		}
	}, function () { 
		var pics_shows = $(this).parents('.portfolio_block').attr('shown');
		if ((typeof (pics_shows) == 'undefined') || (pics_shows == 'hidden')) {
			if ($(this).attr('class') == 'mode_txt hidden' || $(this).attr('class') == 'mode_txt') {
				stillNeedToHide = true;
				setTimeout(function(){$(this).hideTizerIfNeeded();}, 1);
			}
			else if ($(this).attr('class') == 'mode_img hidden' || $(this).attr('class') == 'mode_img') {
				stillNeedToHide = true;
				setTimeout(function(){$(this).hideTizer2IfNeeded();}, 1);
			}
		}
	});
	$('.tizer, .tizer2').live('mouseover', function () {
		stillNeedToHide = false;
	});
	$('.tizer').live('mouseout', function () { 
		stillNeedToHide = true;
		setTimeout(function(){$(this).hideTizerIfNeeded();}, 1);
	});
	$('.tizer2').live('mouseout', function () { 
		stillNeedToHide = true;
		setTimeout(function(){$(this).hideTizer2IfNeeded();}, 1);
	});
	
	var timer;
	var stillNeedToHide = true;
	$.fn.setTizer = function () {
		$('.tizer').css('top', $(this).offset().top - 57 + 'px');
		$('.tizer').css('left', $(this).offset().left - 182 + 'px');
		$('.tizer').html('<img src="' + $(this).children('a').attr('img') + '" width="150" height="116" />');
	};
	$.fn.showTizer = function () {
		$(this).setTizer();
		timer = window.setTimeout(function() {
			$('.tizer').show();
		}, 300);
	};
	$.fn.setTizer2 = function () {
		$('.tizer2').css('top', $(this).offset().top + 27 + 'px');
		$('.tizer2').css('left', $(this).offset().left - 156 + 'px');
		$('.tizer2 a').text($(this).children('a').text());
		$('.tizer2 span').text($(this).children('span').text());
	};
	$.fn.showTizer2 = function () {
		$(this).setTizer2();
		timer = window.setTimeout(function() {
			$('.tizer2').show();
		}, 300);
	};
	$.fn.hideTizer = function () {
		$('.tizer').hide();
		$('.tizer').html('');
		clearTimeout(timer);
	};
	$.fn.hideTizerIfNeeded = function () {
		if (stillNeedToHide)
			$(this).hideTizer();
	};
	$.fn.hideTizer2 = function () {
		$('.tizer2').hide();
		$('.tizer2 a').text('');
		$('.tizer2 span').text('');
		clearTimeout(timer);
	};
	$.fn.hideTizer2IfNeeded = function () {
		if (stillNeedToHide)
			$(this).hideTizer2();
	};
	
	showFishka();

	$('.fishki .switcher').click( function () { 
		animateSwitcher($(this), showFishka);
	});
	
	curID = 0;
	nextID = 0;
	prevID = 0;
	maxID = 0;
	curBlock = '';

	$('.portfolio_block div.mode_txt').click( function () { 
		if ($(this).hasClass('mailru')) {
			window.location = 'http://multiline.ru/mailru.php';
			return false;
		} else if ($(this).children('a').attr('class') == 'banners') {
			var str = $(this).children('a').attr('id');
			var ind = str.substr(6);
		}
		showWin($(this).children('a').attr('class'), ind);
		return false;
	});

	$('.close, .window_bg').click( function () { 
		$('.window_content .photo').hide();
		$('.window_content').hide();
		$('.window .prev, .window .next').hide();
		$('.window').hide();
		$('.window_bg').hide();
	});
	
	$('.portfolio_block a.orange_link').click( function () { 
		var rel = $(this).attr('rel');
		var rels = rel.split("_");
		var block_id = $(this).parents('.portfolio_block').attr('id');

		if (block_id == 'banners_block') {
			showWin('banners', $(this).attr('moreid'));
		} else {
			var block_head = '';
			switch (block_id) {
				case 'sites_block':
					block_head = 'Сайты';
					break;
				case 'multimedia_block':
					block_head = 'Мультимедиа';
					break;
				case 'cards_block':
					block_head = 'Открытки';
					break;
				case 'offline_block':
					block_head = 'OFFLINE';
					break;			
			}
			var hidden = $(this).parents('.portfolio_block').children('div.hidden');
			var all_items = $(this).parents('.portfolio_block').children('div.mode_txt');
			if ($(hidden).size() != 0) {
				if ($(hidden).css('display') == 'none') {
					$(all_items).css({'height': '178px'});
					$(all_items).children('div.mode_img').show();
					$(this).text('Сокращенный список категории «' + block_head + '»');
					$(hidden).show();
					$(this).parents('.portfolio_block').attr({'shown': 'visible'});
				} else {
					$(all_items).css({'height': '45px'});
					$(all_items).children('div.mode_img').hide();
					$(this).text('Все работы категории «' + block_head + '»');
					$(hidden).hide();
					$(this).parents('.portfolio_block').attr({'shown': 'hidden'});
				}
			}
			var anchor = $(this).parents('.portfolio_block').attr('id');
			var redir = $('a[name="' + anchor + '"]');
			if ($(redir).length > 0) {
				if (document.location.href.indexOf(anchor) > -1) { // если тот же якорь, сначала редиректнемся вверх
					window.location = '#top';
				}
				window.location = '#' + anchor;
			}
		}
/*
		if (($(this).parents('.portfolio_block').attr('id') == 'banners_block') && (rels[1] != 'pics')) {
			showWin('banners', $(this).attr('moreid'));
		} else {
			var hidden = $(this).parents('.portfolio_block').children('div.hidden');
			if (rels[1] != 'pics') { // это линк "ещё..."
				if (hidden.size() != 0) {
					if (hidden.css('display') == 'none') {
						hidden.show();
						$(this).text('- поменьше');
						var block = $(this).parents('.portfolio_block').attr('id');
						switch(block)
						{
							case 'sites_block':
								$(this).text('- поменьше сайтов');
								break;
							case 'multimedia_block':
								$(this).text('- поменьше мультимедиа');
								break;
							case 'cards_block':
								$(this).text('- поменьше открыток');
								break;
							case 'offline_block':
								$(this).text('- поменьше offline');
								break;
							//case 'banners_block':
							//	$(this).text('- поменьше баннеров');
							//	break;
							default:
								$(this).text('- поменьше');
						}
						$(this).css('text-decoration', 'underline');
					} else {
						hidden.hide();
						var block = $(this).parents('.portfolio_block').attr('id');
							switch(block)
							{
							case 'sites_block':
								$(this).text('+ ещё сайты');
								break;
							case 'multimedia_block':
								$(this).text('+ ещё мультимедиа');
								break;
							case 'cards_block':
								$(this).text('+ ещё открытки');
								break;
							case 'offline_block':
								$(this).text('+ ещё offline');
								break;
							//case 'banners_block':
							//	$(this).text('+ ещё баннеры');
							//	break;
							default:
							  $(this).text('+ ещё');
						}
					}
				}
			} else {
				var all_items = $(this).parents('.portfolio_block').children('div.mode_txt');
				var pics_shows = $(this).parents('.portfolio_block').attr('shown');
				if ((typeof (pics_shows) == 'undefined') || (pics_shows == 'hidden')) {
					$(all_items).css({'height': '178px'});
					$(all_items).children('div.mode_img').show();
					$(this).text('+ скрыть картинки');
					$(this).parents('.portfolio_block').attr({'shown': 'visible'});
				} else {
					$(all_items).css({'height': '45px'});
					$(all_items).children('div.mode_img').hide();
					$(this).text('+ показать картинки');
					$(this).parents('.portfolio_block').attr({'shown': 'hidden'});
				}
			}
			var redir = $('a[name="' + $(this).parents('.portfolio_block').attr('id') + '"]');
			if ($(redir).length > 0) {
				window.location = '#' + $(this).parents('.portfolio_block').attr('id');
			}
		}
*/
	});
/*	
	$('#mode_img').click(function(){ switchMode('img'); });
	$('#mode_txt').click(function(){ switchMode('txt'); });
*/
});

/*
function switchMode(mode) {
	if (mode == 'img') {
		$('#mode_img').hide();
		$('#mode_txt').show();
		
		$('.portfolio_block div').each(function(){
			if ($(this).attr('class') == 'mode_txt hidden') 
				$(this).attr('class', 'mode_img hidden');
			else if ($(this).attr('class') == 'mode_txt')
				$(this).attr('class', 'mode_img');
			$(this).prepend('<img src="' + $(this).children('a').attr('img') + '" width="150" height="116" />');
		});
	}
	else if (mode == 'txt') {
		$('#mode_txt').hide();
		$('#mode_img').show();
		
		$('.portfolio_block div').each(function(){
			if ($(this).attr('class') == 'mode_img hidden') 
				$(this).attr('class', 'mode_txt hidden');
			else if ($(this).attr('class') == 'mode_img')
				$(this).attr('class', 'mode_txt');
			$(this).children('img').remove();
		});
	}
}
*/
function setWin (photoId) {
	if (curBlock == 'banners') {
		$('#banners .photo').eq(curID-1).html('');
		$('#banners .photo').eq(curID-1).hide();
		var shown = $('#banners .photo').eq(photoId-1);
	}
	else {
		$('#' + curBlock + '_' + curID).html('');
		$('#' + curBlock + '_' + curID).hide();
		var shown = $('#' + curBlock + '_' + photoId);
	}
	
	if (shown.attr('img')) {
		if (shown.attr('imgurl'))
			shown.html('<a href="' + shown.attr('imgurl') + '" target="_blank"><img src="' + shown.attr('img') + '" width="' + shown.attr('imgW') + '" height="' + shown.attr('imgH') + '" class="border_grey" /></a>');
		else
			shown.html('<img src="' + shown.attr('img') + '" width="' + shown.attr('imgW') + '" height="' + shown.attr('imgH') + '" class="border_grey" />');
	}
	else if (shown.attr('film')) {
		shown.html('У вас отключен JavaScript, или установлена старая версия Adobe Flash Player.<br /><a href="http://www.macromedia.com/go/getflashplayer/">Загрузите последнюю версию проигрывателя Flash</a>');
        var so = new SWFObject('/ml_new/mediaplayer/mediaplayer.swf','mediaplayerl','380','336','8');
        so.addParam('allowscriptaccess','always');
        so.addParam('allowfullscreen','true');
        so.addVariable('width','380');
        so.addVariable('height','336');
        so.addVariable('file',shown.attr('film'));
        so.addVariable('image',shown.attr('prefilm'));
        so.addVariable('showstop','true');
        so.write(shown.attr('id'));
	}
	else if (shown.attr('flash')) {
		shown.html('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="' + shown.attr('flashW') + '" height="' + shown.attr('flashH') + '"><param name="movie" value="' + shown.attr('flash') + '"><embed src="' + shown.attr('flash') + '" width="' + shown.attr('flashW') + '" height="' + shown.attr('flashH') + '" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></embed></object>');
	}

	shown.show();
	
	$('.sound').hide();
	$('.sound').text('включите звук');
	if (shown.attr('sound'))
		$('.sound').show();

	$('.window_top img').css('height', $('.window').height() - 36 + 'px');
	$('.window_top').css('height', $('.window').height() - 29 + 'px');

	$('.window').css('top', $(document).scrollTop() + ($(window).height() - $('.window').height()) / 2 + 'px');
	
	if (photoId == maxID) nextID = 1;
	else nextID = (photoId + 1)*1;
	
	if (photoId == 1) prevID = maxID;
	else prevID = (photoId - 1)*1;
	
	curID = photoId;
}

function showWin (blockId, ind) {
	$('.window_bg').height($(document).height() + 'px');
	$('.window_bg').width($(window).width() + 'px');
	
	if (blockId == 'banners') {
		curID = $('#banners .photo').index($('#banners_' + ind*1)) + 1;
	} else {
		curID = 1;
	}
	curBlock = blockId;
	maxID = $('.window_content#' + blockId + ' .photo').size();
	
	$('.window_content#' + curBlock).show();
	
	if (maxID > 1) {
		$('.window .prev, .window .next').show();
		$('.window .prev').html('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="60" height="60" id="prev_flash"><param name="allowScriptAccess" value="sameDomain" /><param name="allowFullScreen" value="false" /><param name="movie" value="/ml_new/img/kruti_prev.swf" /><param name="quality" value="high" /><param name="wmode" value="opaque" /><param name="bgcolor" value="#ffffff" /><embed src="/ml_new/img/kruti_prev.swf" quality="high" wmode="opaque" bgcolor="#ffffff" width="60" height="60" name="prev_flash" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed></object>');
		$('.window .next').html('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8,0,0,0" width="60" height="60" id="next_flash"><param name="allowScriptAccess" value="sameDomain" /><param name="allowFullScreen" value="false" /><param name="movie" value="/ml_new/img/kruti_next.swf" /><param name="quality" value="high" /><param name="wmode" value="opaque" /><param name="bgcolor" value="#ffffff" /><embed src="/ml_new/img/kruti_next.swf" quality="high" wmode="opaque" bgcolor="#ffffff" width="60" height="60" name="next_flash" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed></object>');
	}

	$('.window_bg').show();
	$('.window').show();
	
	setWin(curID);
}

function animateSwitcher(obj, func) {
	if(obj.parent().attr('class') == 'work_last') isAnim = 1;
	obj.animate({'backgroundPosition': '0 -338px'}, 50)
	.animate({'backgroundPosition': '0 -676px'}, 50)
	.animate({'backgroundPosition': '0 -1014px'}, 50)
	.animate({'backgroundPosition': '0 -1352px'}, 50)
	.animate({'backgroundPosition': '0 -1690px'}, 50)
	.animate({'backgroundPosition': '0 -1352px'}, 50)
	.animate({'backgroundPosition': '0 -1014px'}, 50)
	.animate({'backgroundPosition': '0 -676px'}, 50)
	.animate({'backgroundPosition': '0 -338px'}, 50)
	.animate({'backgroundPosition': '0 0'}, 50, func);
}

var showFishka = function () {
	var size = $('.fishka').size();
	if (size > 0) {
		var num = Math.floor(Math.random()*size);
		while ($('.fishka').eq(num).css('display') != 'none') {
			num = Math.floor(Math.random()*size);
		}
		
		$('.fishka_photo').html('');
		$('.fishka').hide();
		
		var curFishka = $('.fishka').eq(num);
		var curFishkaPhoto = curFishka.children('.fishka_photo');
		curFishka.show();
		curFishkaPhoto.html('<img src="' + curFishkaPhoto.attr('img') + '" width="156" height="188" /><b class="iePNG"></b>');
		
		$('.fishki p a').attr('class', curFishka.attr('rel'));
	}
}

function createWorks () {
	var size = $('.check_content').size();
	for (i=0; i<size; i++) {
		$('.work_lines div').each(function() {
			$(this).append('<img src="' + $('.check_content img').eq(i).attr('src') + '" check="' + $('.check_content').eq(i).attr('rel') + '" />');
		});
	}
	showWorks();
}

function setWorksParam (line, id) {
	$('.work_link' + line + ' span').attr('rel', id);
	$('.work_link' + line + ' span').attr('banid', $('.check_content[rel=' + id + ']').attr('banid'));
	$('.work_link' + line + ' span').attr('type', $('.check_content[rel=' + id + ']').attr('type'));
	$('.check' + line + ' span').attr('rel', id);
	$('.check' + line + ' span').attr('banid', $('.check_content[rel=' + id + ']').attr('banid'));
	$('.check' + line + ' span').attr('type', $('.check_content[rel=' + id + ']').attr('type'));
	$('.check' + line + ' span').html($('.check_content[rel=' + id + ']').html());
}

function random3 (size) {
	if (size > 0) {
		var num1 = Math.floor(Math.random()*size);
		var id1 = $('.work_line1 img').eq(num1).attr('check');
		
		var num2 = Math.floor(Math.random()*size);
		var id2 = $('.work_line2 img').eq(num2).attr('check');
		while (id2 == id1) {
			num2 = Math.floor(Math.random()*size);
			id2 = $('.work_line2 img').eq(num2).attr('check');
		}
		
		var num3 = Math.floor(Math.random()*size);
		var id3 = $('.work_line3 img').eq(num3).attr('check');
		while (id3 == id1 || id3 == id2) {
			num3 = Math.floor(Math.random()*size);
			id3 = $('.work_line3 img').eq(num3).attr('check');
		}
	} else {
		var num1 = 0;
		var num2 = 0;
		var num3 = 0;
	}
	return {"num1":num1, "num2":num2, "num3":num3};
}

var randNums = [];
var count = [];
var counter = [];

var showAnimateWorks = function () {
	var size = $('.check_content').size();
	var nums = random3(size);
	
	counter = [0, 0, 0];
	randNums = [nums.num1, nums.num2, nums.num3];
	
	$('.check').animate({'top': '-196px'}, 500);
	
	for(var i=0; i<3; i++) {
		count[i] = size*(i+1) - randNums[i];
		animateWorks(i+1, size);
	}
}

function animateWorks (line, size) { 
	var block = $('.work_line' + line);
	var last = block.children('img').eq(size-1);
	last.remove();
	last.prependTo(block);
	var id = $('.work_line' + line + ' img + img').attr('check');
	block.css('top', block.position().top - 168 + 'px');
	block.animate({'top': '+=168px'}, 50, function(){
		counter[line-1]++;
		if (counter[line-1] <= count[line-1]) {
			animateWorks(line, size);
		}
		else {
			setWorksParam(line, id);
			$('.check' + line).animate({'top': '-13px'}, 500, function(){
				if (line == 3) isAnim = 0;
			});
		}
	});
}

var showWorks = function () {
	var size = $('.check_content').size();
	var nums = random3(size);

	randNums = [nums.num1, nums.num2, nums.num3];
	counter = [0, 0, 0];
	
	for(var i=0; i<3; i++) {
		count[i] = size*(i+1) - randNums[i];
		setWorks(i+1, size);
	}
}

function setWorks (line, size) { 
	var block = $('.work_line' + line);
	var last = block.children('img').eq(size-1);
	last.remove();
	last.prependTo(block);
	var id = $('.work_line' + line + ' img + img').attr('check');
	counter[line-1]++;
	if (counter[line-1] <= count[line-1]) {
		setWorks(line, size);
	}
	else {
		setWorksParam(line, id);
		$('.check' + line).css({'top': '-13px'});
		if (line == 3) isAnim = 0;
	}
}

function soundOn () {
	$('.sound').text('выключите звук');
	//текущий блок - $('#' + curBlock + '_' + curID)
}

function soundOff () {
	$('.sound').text('включите звук');
	//текущий блок - $('#' + curBlock + '_' + curID)
}

// Отправляет ссылку другу - открывает письмо с адресом + ?work_id=$id
function send_link (id) {
        location.href="mailto:?SUBJECT="+document.title+"&BODY="+SITE_URL+"?work_id="+id;
}


