var cont;

$(document).ready(function(){
	var menu = $('#menu'),
	    lines = $('#lines'),
	    jsWidth = $('#jsWidth'),
	    img1 = jsWidth.prev().find('> img'),
	    img2 = jsWidth.find('> img'),
	    img3 = jsWidth.next().find('> img'),
	    imgs = $(img1).add(img2).add(img3),
	    man = $('#man'),
	    pie = $('#pie'),
	    pack = $('#pack'),
	    board = $('#board'),
	    detail = $('#detail'),
	    rollup = $('div.rollup'),
	    medbrand = $('#medbrand'),
	    scroller = $('#scroller tr');
	
	cont = $('#content');


	if(lines.length)
	{
		var contents = $('#contents div'),
		    paper, 
		    drawLines = function()
			{
				var contTop = cont.offset().top,
				    item1 = contents.eq(0).offset(),
				    item2 = contents.eq(1),
				    item3 = contents.eq(2).offset(),
				    point1 = [0, item1.top - contTop + 25],
				    point2 = [cont.width() * 0.30, img1.offset().top - contTop + (img1.height() * 0.35)],
				    point3 = [item2.position().left + (item2.width() / 2), item2.offset().top - contTop + 23]
				    point4 = [cont.width(), item3.top - contTop + 25],
				    point5 = [cont.width() * 0.54, jsWidth.offset().top - contTop + (jsWidth.height() * 0.27)],
				    point6 = [cont.width() * 0.55, img3.offset().top - contTop + (img3.height() * 0.45)];
			
				var tang = (point4[0] - point1[0]) / (point4[1] - point1[1]),
				    point7 = [(item2.offset().left - cont.offset().left), 0];
				point7[1] = (point7[0] / tang) + point1[1];

				var point8 = [(item2.offset().left + item2.width() - cont.offset().left), 0];
				point8[1] = (point8[0] / tang) + point1[1];

				lines.html('');
				if(Raphael)
				{
					var paper = Raphael('lines', cont.width(), cont.height());

					var paths = [
						[paper.path(toPath(point1, point2)).attr('stroke', '#0018ff').attr('stroke-opacity', 0.5), point1, point2],
						[paper.path(toPath(point3, point5)).attr('stroke', '#ff0000').attr('stroke-opacity', 0.5), point3, point5],
						[paper.path(toPath(point4, point6)).attr('stroke', '#7900ff').attr('stroke-opacity', 0.5), point4, point6]
					];

					var html = '<div class="over">&nbsp;</div>';
					$(html).css({ left: point2[0], top: point2[1] }).data('n', 1).appendTo('#lines');
					$(html).css({ left: point5[0], top: point5[1] }).data('n', 2).appendTo('#lines');
					$(html).css({ left: point6[0], top: point6[1] }).data('n', 3).appendTo('#lines');
					lines.find('div.over').mouseenter(function(){
						var el = $(this),
						    n = el.data('n'),
						    path = paths[n - 1],
						    p = randomPoint(imgs.eq(n - 1));
						el.css({
							left: p[0],
							top: p[1]
						});
						path[0].animate({
							path: toPath(path[1], p)
						}, 200);
					});

					paper.path(toPath(point1, point7)).attr('stroke', '#0018ff').attr('stroke-opacity', 0.5);
					paper.path(toPath(point7, point8)).attr('stroke', '#ff0000').attr('stroke-opacity', 0.5);
					paper.path(toPath(point8, point4)).attr('stroke', '#7900ff').attr('stroke-opacity', 0.5);
				}
			},
		    drawLinesActivator = 0;
		jsWidth.parent().find('img').load(function(){
			if(drawLinesActivator++ == 2) drawLines();
		});
		$(window).resize(drawLines);
		drawLines();
	}
	

	if(jsWidth.length)
	{
		var imageScaling = [
			[0.345, 1, 0, 0.655],
			[0, 0.8, 0.2, 1],
			[0.195, 1, 0, 0.805]
		    ],
		    imageTriangles = function(obj, scaling)
			{
				var h = obj.height(),
				    w = obj.width();
				obj.data('triangles', [
					[0, h * scaling[0]],
					[w, h * scaling[3]],
					[w, h * scaling[2]],
					[0, h * scaling[1]]
				]);
			},
		    jsWidthControl = function()
		    	{
				var w = cont.offset().left,
				    l = img1.offset().left - w;
				jsWidth.css({
					left: l,
					width: img3.width() - l
				});
				imgs.each(function(i){
					imageTriangles($(this), imageScaling[i]);
					var t = $(this).data('triangles');
					/*for(var i = 0; i < 4; i++)
					{
						cont.append($('<div></div>', {
							css: {
								position: 'absolute',
								left: t[i][0] + $(this).offset().left - cont.offset().left,
								top: t[i][1] + $(this).offset().top - cont.offset().top,
								width: 3,
								height: 3,
								background: 'orange',
								overflow: 'hidden'
							}
						}));
					}*/
				});
			};
		jsWidth.parent().find('img').load(jsWidthControl);
		$(window).resize(jsWidthControl);
		jsWidthControl();
	}
	
	if(pie.length)
	{
		var pieLock = true;
		pie.find('div').mouseenter(function(){
			var orig = $(this),
			    sibl = orig.siblings('div'),
			    src;
			if(pieLock) sibl = sibl.filter(':gt(0)');
			sibl.sort(function(){
				return Math.round(Math.random());
			});
			sibl = sibl.eq(0).find('img');
			orig = orig.find('img');
			src = orig.attr('src');
			orig.attr('src', sibl.attr('src'));
			sibl.attr('src', src);
		}).filter(':gt(0)').trigger('mouseenter');
		pieLock = false;
	}
	
	if(board.length)
	{
		var pageWidth = $('#bodier').width(),
		    dayTime = $('#daytime > img'), 
		    roll = board.find('> div.roll'),
		    dupl = board.find('> div.duplicator > img'), 
		    small = board.find('div.small > div'),
		    big = board.find('div.big > div'),
		    dayTimeWidth, boardLeft,
		    boardRoll = function(p)
			{
				if(p > 1) p = 1;
				if(p < 0.01) p = 0.01;

				p = p * 0.66; // oops

				var percent = p,
				    yDiff = 0;
				if(percent > 0.66)
				{
					percent = percent - 0.66;
					yDiff = -580;
				}
				else if(percent > 0.33)
				{
					percent = percent - 0.33;
					yDiff = -290;
				}
				
				
				if(percent > 0.33) percent = 0.33;
				var percentX = percent / 0.33,
				    x = -520 * (1 - percentX),
				    y = (-295 * percentX) + yDiff - (58 * (1 - percentX));


				var blueH = ( 1 - ((percent - 0.02) / 0.036) );
				var orangeH = ( 1 - ((percent - 0.017) / 0.035) );
				
				var blueB = (7.6 + blueH) / 0.6;
				var orangeB = (7.9 + orangeH) / 0.85;
				
				if( blueB > 0 && blueB < 1 && p < 0.63)
				{
					big[1].style.height = (1 - blueB) * 30 + 'px';
					big[1].style.display = 'block';
				}
				else if(p > 0.33)
				{
					big[1].style.height = 30 + 'px';
					big[1].style.display = 'block';
				}
				else
				{
					big[1].style.display = 'none';
				}

				if( orangeB > 0 && orangeB < 1 && p > 0.63)
				{
					big[2].style.height = (1 - orangeB) * 30 + 'px';
					big[2].style.display = 'block';
				}
				else if(p < 0.63)
				{
					big[2].style.display = 'none';
				}
				else
				{
					big[2].style.height = 30 + 'px';
					big[2].style.display = 'block';
				}


				if(blueH > 0.05 && p < 0.3)
				{
					small[2].style.height = blueH * 26 + 'px';
					small[2].style.display = 'block';
				}
				else
				{
					small[2].style.display = 'none';
				}

				if(orangeH > 0.05 && p > 0.33)
				{
					small[1].style.height = orangeH * 26 + 'px';
					small[1].style.display = 'block';
				}
				else if(p < 0.33)
				{
					small[1].style.height = 26 + 'px';
					small[1].style.display = 'block';
				}
				else
				{
					small[1].style.display = 'none';
				}

				roll.css({
					backgroundPosition: x + 'px ' + y + 'px'
				});
				roll.find('img').css({
					top: (-290 * percentX) + yDiff
				})
			},
		    dayRoll = function(p)
		    	{
		    		var limit = pageWidth - dayTimeWidth - (pageWidth - (boardLeft * 6)) + (pageWidth * 0.05),
		    		    left = p * limit;
		    		dayTime.css({
		    			left: left
		    		});
		    		dupl.css({
		    			left: left - boardLeft - 190
		    		});
		    	};
		$(document).mousemove(function(event){
			var p = event.pageX ? ((event.pageX - (pageWidth * 0.05)) / pageWidth) : 0;
			boardRoll(p);
			dayRoll(p);
		});
		function detectVars()
		{
			pageWidth = cont.width();
			dayTimeWidth = dayTime.width();
			boardLeft = board.offset().left;
			dupl.css({
				top: dayTime.offset().top - dupl.parent().offset().top,
				width: dayTimeWidth
			});
			$(document).trigger('mousemove');
			//$('#daytime').height($('#bodier').height());
		};
		$(window).resize(detectVars);
		detail.load(detectVars);
		detectVars();
	}
	
	if(detail.length)
	{
		var line = $('#line'),
		    imageScaling = [0.57, 1.08, -0.08, 0.43],
		    imageTriangles = function(obj, scaling)
			{
				var h = obj.height(),
				    w = obj.width();
				obj.data('triangles', [
					[0, h * scaling[0]],
					[w, h * scaling[3]],
					[w, h * scaling[2]],
					[0, h * scaling[1]]
				]);
			},
		    jsWidthControl = function()
		    	{
				imageTriangles(detail, imageScaling);
				var t = detail.data('triangles');

				line.html('');
				if(Raphael)
				{
					var paper = Raphael('line', cont.width(), cont.height());

					var point1 = [board.offset().left - cont.offset().left + 175, board.find('> div.roll').offset().top - cont.offset().top + 10],
					    point2 = [cont.width() / 2, detail.offset().top - cont.offset().top + (detail.height() / 2)],
					    paths = [
						[paper.path(toPath(point1, point2)).attr('stroke', '#ff0000').attr('stroke-opacity', 0.5), point1, point2]
					];

					$('<div class="over">&nbsp;</div>').css({ left: point2[0], top: point2[1] }).data('n', 1).appendTo('#line');
					line.find('div.over').mouseenter(function(){
						var el = $(this),
						    n = el.data('n'),
						    path = paths[n - 1],
						    p = randomPoint(detail);
						el.css({
							left: p[0],
							top: p[1]
						});
						path[0].animate({
							path: toPath(path[1], p)
						}, 200);
					});
				}

				/*for(var i = 0; i < 4; i++)
				{
					cont.append($('<div></div>', {
						css: {
							position: 'absolute',
							left: t[i][0] + detail.offset().left - cont.offset().left,
							top: t[i][1] + detail.offset().top - cont.offset().top,
							width: 3,
							height: 3,
							background: 'orange',
							overflow: 'hidden'
						}
					}));
				}*/
			};
		detail.load(jsWidthControl);
		$(window).resize(jsWidthControl);
		jsWidthControl();
	}
	
	if(rollup.length)
	{
		rollup.each(function(){
			var el = $(this),
			    img = el.find('> img:eq(1)'),
			    timer;
			el.mouseenter(function(){
				if(timer) clearTimeout(timer);
				$(this).addClass('hover');
				img.fadeIn('fast');
			}).mouseleave(function(){
				$(this).removeClass('hover');
				img.fadeOut('fast');
			});
			if(!el.attr('pause')) timer = setTimeout(function(){
				el.trigger('mouseleave');
			}, 5000);
		});
	}
	
	if(pack.length)
	{
		var imgs = pack.find('> div > img');
		setInterval(function(){
			var na = imgs.filter(':not(:animated)'),
			    pw = pack.width(),
			    speed = ((pw / 200) * 1000),
			    src = [];
			
			na.each(function(){
				src.push(this.src);
			});
			src.sort(function(){ return Math.round(Math.random() * 100) - 50 });
			na.each(function(i){
				this.src = src[i];
			});
			
			var aimg = imgs.filter(':animated:last'),
			    img = aimg.length ? aimg.next().eq(0) : imgs.eq(0);
			if(!img.length) img = imgs.eq(0);

			if(!aimg.length || aimg.position().left - 300 > 60)
			img.animate({
				left: pw + img.width()
			}, speed + (Math.random() * (speed / 5)), 'linear', function(){
				img.css({
					left: 0
				});
			});
		}, 1000);
	}
	
	if(medbrand.length)
	{
		var colors = ['#957e5d', '#427c85', '#dbdbdb'],
		    last = 0;
		medbrand.mouseenter(function(){
			medbrand.css({
				backgroundColor: colors[last]
			});
			last++;
			if(last == colors.length) last = 0;
		});
	}
	
	if(scroller.length)
	{
		scroller.find('a:has(img)').live('click', function(event){
			event.preventDefault();
			var el = $(this);
			$('#wow').remove();
			if(el.hasClass('selected'))
			{
				el.removeClass('selected');
			}
			else
			{
				scroller.find('a.selected').removeClass('selected');
				el.addClass('selected');
				$('#bodier').find(' > :first').before('<img src="' + el.find('> img').attr('src').replace('_small', '') + '" id="wow" />');
			}
		});
		
		var path = '/uploads/';
		function loadImageList()
		{
			$.getJSON(path + 'list.php?r='+Math.random(), function(data){
				var i = 0;
				scroller.find('td[refresh]').remove();
				data.sort();
				while(data.length)
				{
					var img = path + data.shift();
					scroller.find('td:last').prev().before('<td refresh="true"><a href="' + img.replace('_small', '') + '"><img src="' + img + '" /></a></td><td refresh="true"><div class="th2">&nbsp;</div></td>');
					if(i++ == 20) break;
				}
				//setTimeout(loadImageList, 20000);
			});
		};
		loadImageList();
		
		/*var scroll = $('#scroller'),
		    speedmeter = 0,
		    last = 0;
		scroll.bind('scroll', function(){
			var sl = scroll.scrollLeft();
			if( (speedmeter += Math.abs(sl - last)) > 100 )
			{
				rollup.trigger(rollup.hasClass('hover') ? 'mouseleave' : 'mouseenter');
				speedmeter = 0;
			}
			last = sl;
		});*/
	}
	
	if(man.length)
	{
		var manEl = man[0], 
		    manHeight, 
		    manWidth,
		    docHeight,
		    headerHeight,
		    footerHeight,
		    limit
		    lines = $('#liner'),
		    points = [
			[0.5, 0.038],
			[0.48, 0.28],
			[0.54, 0.34],
			[0.35, 0.535],
			[0.6, 0.7]
		];
		function drawLines()
		{
			var div = lines.nextAll('div'),
			    t = [];
			
			lines.html('');
			if(Raphael)
			{
				var paper = Raphael('liner', man.width(), man.height());

				div.each(function(i){
					var el = $(this),
					    left = el.find('span').offset().left - man.offset().left,
					    point1 = [ points[i][0] * manWidth, points[i][1] * manHeight ],
					    point2 = [(left > manWidth / 2) ? (left - 4) : (left + el.find('span').width() + 4), el.position().top + 10];

					paper.path(toPath(point1, point2)).attr('stroke', '#000000');
				});
			}
		};
		
		function detectMan()
		{
			docHeight = $('#bodier').height();
			manWidth = man.width();
			manHeight = man.height();
			headerHeight = $('#header').height();
			footerHeight = $('#footer').height() + 115 + 35;
			limit = (headerHeight + manHeight) - docHeight;
			drawLines();
		};
		$(window).resize(detectMan);
		man.find('img').load(detectMan);
		detectMan();

		$(document).mousemove(function(event){
			var p = Math.min( ((event.pageY - 30) / (docHeight - 30)) * manHeight, limit + footerHeight);
			if(p < 0) p = 0;
			manEl.style.marginTop = (p * -1) + 'px';
		});
		
		man.find('div > a').mouseenter(function(){
			$(this).find('img').stop().animate({ opacity: 1 }, 'fast');
		}).mouseleave(function(){
			$(this).find('img').stop().animate({ opacity: 0 }, 'slow');
		}).find('img').css({ opacity: 0 });
		
	}
	
	$('div.flash').each(function(){
		var el = $(this),
		    img = el.find('img');
		el.html($.flash.create({
			swf: img.attr('src').match(/^(.+?)\.gif/)[1] + '.swf',
			wmode: 'transparent',
			width: img.width(),
			height: img.height(),
			flashvars: img.attr('flashvars')
		}));
		setTimeout(function(){
			el.find('a').remove();
		}, 1000);
	});

	if($('#logo a').length)
	{
		menu.mouseenter(function(){
			menu.stop().animate({ opacity: 1 }, 'fast');
		}).mouseleave(function(){
			menu.stop().animate({ opacity: 0.3 }, 'slow');
		});
	}
	else
	{
		menu.css({ opacity: 1 });
	}

	var premenu = [];
	for(var i = 1; i < 4; i++)
	{
		var pimg = new Image();
		pimg.src = '/static/all_menu' + i + '.png';
		premenu.push(pimg);
	}
	$('#submenu a[href$=all/]').mouseenter(function(){
		$('#allMenu').remove();
		var el = $(this),
		    p = el.offset(),
		    w = el.width(),
		    h = el.height();
		premenu.sort(function(){ return Math.round(Math.random() * 10) - 5 });
		var i = $('<img class="allMenu" src="' + premenu[0].src + '" style="position: absolute; z-index: 600; left: ' + (p.left + (w / 2)) + 'px; top: -300px; width: 100px; margin-left: -50px" />');
		i.appendTo('body').end().fadeOut(5, function(){
			i.css({ top: p.top + h + 5 }).fadeIn('fast');
		});
	}).mouseleave(function(){
		$('img.allMenu').fadeOut('slow', function(){
			$(this).remove();
		});
	});

	function visited()
	{
		$('#header > img.visited').remove();
		$('#submenu span.protected').each(function(i){
			var el = $(this);
			if($.cookie('visited' + i))
			{
				var p = el.offset(),
				    w = el.width();
				$('<img class="visited" src="/static/visited.png" style="left: ' + (p.left - $('#header > table').offset().left + w)+ 'px; top: ' + p.top + 'px" />').appendTo('#header');
			}
			if(!el.parent('a').length) $.cookie('visited' + i, '1', { expires: 30, path: '/' });
		
		});
	}
	
	$(window).resize(visited);
	setTimeout(visited, 10);
	
	if($('#company').length)
	{
		var els = $('#menu, #footer'),
		    timer,
		    fade = function(opacity){
			els.each(function(){
				var el = $(this);
				if(!el.data('locked'))
				{
					el.data('locked', true);
					el.stop().animate({opacity: opacity}, 'normal', function(){ el.data('locked', false); });
				}
			});
		};

		els.mouseenter(function(){
			var el = $(this);
			el.data('locked', true);
		}).mouseleave(function(){
			var el = $(this);
			el.data('locked', false);
		});
		
		
		timer = setTimeout(function(){ fade(0) }, 2000);
		$('#bodier').mousemove(function(){
			fade(1);
			if(timer) clearTimeout(timer);
			timer = setTimeout(function(){ 
				fade(0);
			}, 2000);
		});
	}
	
	
	window.gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
	$.getScript(gaJsHost + 'google-analytics.com/ga.js', function(){
		window.pageTracker = _gat._getTracker("UA-8684368-1");
		window.pageTracker._trackPageview();
	});
});


function toPath(point1, point2)
{
	return ['M', point1[0], ' ', point1[1], 'L', point2[0], ' ', point2[1]].join('');
};
function insideTriangle(p, p1, p2, p3)
{
	var vector = function(d, d1, d2)
	{
		return 	(
				(d[1] - d1[1]) * (d2[0] - d1[0])
			) - (
				(d[0] - d1[0]) * (d2[1] - d1[1])
			)
	};
	return vector(p, p1, p2) * vector(p, p2, p3) > 0 && vector(p, p3, p1) * vector(p, p2, p3) > 0;
};
function randomPoint(el)
{
	var ps = el.data('triangles'),
	    w = el.width(),
	    h = el.height(),
	    p, h1, h2;
	do
	{
		p = [Math.random()*w, Math.random()*h];
		h1 = insideTriangle(p, ps[0], ps[1], ps[2]);
		h2 = insideTriangle(p, ps[0], ps[3], ps[1]);
	}
	while(!(h1 || h2));
	p[0] += el.offset().left - cont.offset().left;
	p[1] += el.offset().top - cont.offset().top;
	return p;
};


function resizeIframe(w, h)
{
	$('iframe').css({
		width: w,
		height: h
	});
};

function appendUserImage(code)
{
	var tr = $('#scroller tr'),
	    td = $('<td refresh="true">' + code + '</td><td refresh="true"><div class="th2">&nbsp;</div></td>');
	tr.find('td:last').prev().before(td);
};


function fixBrowsers()
{
	var secret = ['a', 'b', 'e', 'e', 'm', 'n', 'r', 'w'];
	$('span.protected:contains(××××××××), a.cufoned > span:contains(××××××××)').each(function(){
		var str = '';
		do
		{
			secret.sort(function(){ return Math.round(Math.random() * 100) - 50 });
			str = secret.join('');
		}
		while(str == 'newmerba');
		str = str.substr(0, 1).toUpperCase() + str.substr(1);
		this.innerHTML = this.innerHTML.replace('××××××××', str);
	});

	Cufon.replace('.cufoned');
	$('.cufoned a, a.cufoned').mouseenter(function(){
		$(this).css({ color: 'blue' });
		Cufon.refresh();
	}).mouseleave(function(){
		$(this).css({ color: 'red' });
		Cufon.refresh();
	});
	
	var magick = $('img[magick]');
	if(magick.length)
	{
		magick.each(function(){
			this.original = this.src.match(/([a-z0-9_\.]+)$/)[1];
			this.lastw = null;
		});
		var makeMagick = function(){
			magick.each(function(){
				var el = this,
				    w = el.clientWidth;
				if(w == 0 && el.style.display == 'none')
				{
					el.style.display = 'block';
					w = el.clientWidth;
					el.style.display = 'none';
				}
				if(w > 0 && (!el.lastw || el.lastw != w))
				{
					el.newImg = new Image();
					el.newImg.onload = function(){
						el.src = el.newImg.src;
					};
					el.newImg.src = '/resize.php?file=' + this.original + '&width=' + w;
				}
				this.lastw = w;
			});
		};
		$(window).bind('resize load', makeMagick);
	}
	
};


