/**
 * OsoboMenu
 */
function OsoboMenu()
{
	this.menuItems = new Array('/projects', '/feedback', '/osobo', '/blog');
	this.linksEnabled = true;
	this.rolloversEnabled = true;
	this.menuLink = null;
	//top, left, bottom, right, active
	this.rollovers = new Array();
	this.curRollover = -1;
	this.curItem = 0;
	
	this.skipFunctions = new Array();

	this.computeRolloverRegions = function ()
	{
		var nx = this.getNX();
		var ny = this.getNY();

		for (var i = 0; i < ny; i++)
		{
			for (var j = 0; j < nx; j++)
			{
				var active = true;
				if (i == 0 && (j < 3 || j >= nx - 3))
					active = false;
				if (i == 1 && j >= nx - 2)
					active = false;
				if (i == 2 && j >= nx - 2)
					active = false;
				var top = 132 * i + 54;
				var left = 136 * j;
				if (i % 2 == 0)
					left = left + 60;
				this.rollovers.push(new Array(top, left, top + 72, left + 74, active));
			}
		}
	}

	// количество роловеров по оси X
	this.getNX = function ()
	{
		return Math.ceil(($(document).width()) / 140);
	}

	// количество роловеров по оси Y
	this.getNY = function ()
	{		
		return Math.ceil(($(document).height()) / 140);
	}

	// отключить или включить конкретные роловеры
	this.changeRolloversStatus = function (row, count, active)
	{
		var nx = this.getNX();
		for (var i = nx * row; i < nx * row + count; i++)
		{
			this.rollovers[i][4] = active;
			//console.log(i + ' disabled');
		}
	}

	// отключить или включить конкретные роловеры (отсчет снизу)
	this.changeRolloversStatusBottom = function (row, count, active)
	{
		var row = this.getNY() - row + 1;
		this.changeRolloversStatus(row, count, active);
	}

	this.getRollRegion = function (x, y)
	{
		for (var i = 0; i < this.rollovers.length; i++)
			if ( x >= this.rollovers[i][1] && x <= this.rollovers[i][3] && y >= this.rollovers[i][0] && y <= this.rollovers[i][2]
				 && this.rollovers[i][4]
			     )
				return i;
		return -1;
	}

	this.menu = function (e)
	{
		if (this.rolloversEnabled)
			osoboMenu.handlerOnMouseMove(e);
	}

	this.onDocResize = function (e)
	{
		this.computeRolloverRegions();
	}

	this.handlerOnMouseMove = function (e)
	{
		//var r = this.getRollRegion(e.clientX, e.clientY);
		var r = this.getRollRegion(e.pageX, e.pageY);
		if (r > -1 && this.curRollover < 0)
			this.onMouseOver(r);
		else if (r < 0 && this.curRollover > -1)
			this.onMouseOut(r);
		$('div#debug').text('client: ' + e.clientX + ' ' + e.clientY + ' ' + r);
		//console.log('client: ' + e.clientX + ' ' + e.clientY + ' ' + r);
	}

	this.onMouseOver = function (rollover)
	{
		//console.log(this.curItem);
		//console.log('over');
		this.curRollover = rollover;
		var roll = this.rollovers[this.curRollover];
		$('div#osoboMenu').css( { 'top': roll[0] + 3, 'left': roll[1] + 1 } )
						  .css('background-position', '0px ' + this.curItem * -128 + 'px')
						  .show();
		//this.menuLink = this.menuItems[this.curItem];
		$('div#osoboMenu a').attr('href', this.menuItems[this.curItem]);
		if (this.curItem + 1 > this.itemsCount() - 1)
			this.curItem = 0;
		else
			this.curItem++;
	}

	this.onMouseOut = function (rollover)
	{
		//console.log('out');
		this.curRollover = -1;
		$('div#osoboMenu').hide();
	}

	this.itemsCount = function ()
	{
		return this.menuItems.length;
	}

	this.go = function ()
	{
		if (this.linksEnabled)
			location.replace(this.menuLink);
	}

	this.addSkipFunction = function (fn)
	{
		this.skipFunctions.push(fn);
	}

	this.enableRollovers = function (enabled)
	{
		//console.log('enable rollovers ' + enabled);
		this.rolloversEnabled = enabled;
	}

	//@todo: пересчитывать при ресайзинге окна
	this.computeRolloverRegions();
	$('body').append('<div id="osoboMenu"><a href="#">&nbsp;</a></div>');
	//$('div#osoboMenu').click( function (e) {
	//	osoboMenu.go();
	//});
	//$(document).mousemove(this.onMouseMove);
	//console.log($(document).height());
}

/**
 * OsoboQuote
 */
 function OsoboQuote()
 {
	 this.visible = false;

	 // переключать цитаты
	 this.switchQuotes = true;

	 this.persons = new Array();
	 this.persons[1] = { 'top': 150, 'right': 285,
						 'quotes':
							      [
								   'Osobo фанково.', 'Osobo продвинуто.', 'Osobo технологично.'								  
							      ]
								  ,
						 // отступ справа (right), отступ сверху (top) - координаты центра хвоста цитаты
					     'qAreas': { 2: [290, 180] },
						 'qAreasCount': 1,
						 'qaIndex': 2,
					     'qAreasFirst': 2,
						 'quoteIndex': 0
						 };
	 this.persons[2] = { 'top': 280, 'right': 750,
						 'quotes':
								  ['Osobo зрелищно!']
								  ,
					     'qAreas': { 3: [800, 330], 4: [660, 330], 1: [660, 330], 2: [735, 350] },
 						 'qAreasCount': 4,
					     'qAreasFirst': 1,
 						 'qaIndex': 2,
						 'quoteIndex': 0
						 };	 
	 
	 this.regions = new Array(
 								{ 'person': 1, 'width': 85, 'height': 125, 'top': 80, 'left': 0, 'bottom': 0, 'right': 0, 'right0': 225 },
								{ 'person': 2, 'width': 100, 'height': 135, 'top': 230, 'left': 0, 'bottom': 0, 'right': 0, 'right0': 670 }
							  );



	 this.defaultQuoteRegion = 1;
	 this.curQRegionIndex = 0;
	 this.autoSwitchEnabled = true;
	 this.autoSwitchTimer = null;

	 this.styles = new Array(
							 // цитата quote1
							 [
								 {								   
								   'arrowOffsetX': 410,
								   'arrowOffsetY': 0,
								   'fullWidth': 436,
								   'fullHeight': 143,
								   'width': 343,
								   'height': 66,
								   'background-position': '0px 0px',
								   'padding': '75px 45px 0px 45px'								
								   },
								 {
								   'arrowOffsetX': 25,
								   'arrowOffsetY': 0,
								   'fullWidth': 436,
								   'fullHeight': 143,
								   'width': 343,
								   'height': 66,
								   'background-position': '-433px 0px',
								   'padding': '75px 45px 0px 45px'
								   },
								 {								   
								   'arrowOffsetX': 25,
								   'arrowOffsetY': -143,
								   'fullWidth': 436,
								   'fullHeight': 143,
								   'width': 343,
								   'height': 91,
								   'background-position': '-866px 0px',
								   'padding': '50px 45px 0px 45px'								
								   },
								 {								   
								   'arrowOffsetX': 410,
								   'arrowOffsetY': -143,
								   'fullWidth': 436,
								   'fullHeight': 143,
								   'width': 343,
								   'height': 91,
								   'background-position': '-1299px 0px',
								   'padding': '50px 45px 0px 45px'								
								   }
							  ],
							 // цитата quote3
							 [
								 {
								   'arrowOffsetX': 250,
								   'arrowOffsetY': 0,
								   'fullWidth': 301,
								   'fullHeight': 199,
								   'width': 241,
								   'height': 35,
								   'background-position': '0px -141px',
								   'padding': '100px 30px 60px 30px'
								   },
								 {
								   'arrowOffsetX': 50,
								   'arrowOffsetY': 0,
								   'fullWidth': 301,
								   'fullHeight': 199,
								   'width': 241,
								   'height': 35,
								   'background-position': '-301px -141px',
								   'padding': '100px 30px 60px 30px'
								   },
								 {
								   'arrowOffsetX': 50,
								   'arrowOffsetY': -199,
								   'fullWidth': 301,
								   'fullHeight': 199,
								   'width': 241,
								   'height': 65,
								   'background-position': '-602px -141px',
								   'padding': '70px 30px 60px 30px'
								   },
								 {
								   'arrowOffsetX': 250,
								   'arrowOffsetY': -199,
								   'fullWidth': 301,
								   'fullHeight': 199,
								   'width': 241,
								   'height': 69,
								   'background-position': '-903px -141px',
								   'padding': '70px 30px 60px 30px'
								   }
							  ]/*,
							 // цитата quote2
							 [
								 {
								   'arrowOffsetX': 190,
								   'arrowOffsetY': 0,
								   'fullWidth': 199,
								   'fullHeight': 148,
								   'width': 139,
								   'height': 113,
								   'background-position': '0px -336px',
								   'padding': '65px 30px 0px 30px'
								   },
								 {
								   'arrowOffsetX': 0,
								   'arrowOffsetY': 0,
								   'fullWidth': 199,
								   'fullHeight': 148,
								   'width': 139,
								   'height': 113,
								   'background-position': '-198px -335px',
								   'padding': '65px 30px 0px 30px'
								   },
								 {
								   'arrowOffsetX': 0,
								   'arrowOffsetY': -148,
								   'fullWidth': 199,
								   'fullHeight': 148,
								   'width': 139,
								   'height': 108,
								   'background-position': '-395px -336px',
								   'padding': '60px 30px 0px 30px'
								   },
								 {
								   'arrowOffsetX': 190,
								   'arrowOffsetY': -148,
								   'fullWidth': 199,
								   'fullHeight': 148,
								   'width': 139,
								   'height': 108,
								   'background-position': '-593px -335px',
								   'padding': '60px 30px 0px 30px'
								   }
							  ]
							  */
						    );

	 // индекс в styles
	 this.curStyle = 0;
	 // индекс структур в соответствующем style
	 this.curStyleType = 0;

	 this.adjustRegions = function ()
	 {
		 for (var i = 0; i < this.regions.length; i++)
		 {
			 var r = this.regions[i];
			 this.regions[i].right = $(document).width() - r.right0;
			 this.regions[i].left = r.right - r.width;
			 this.regions[i].bottom = r.top + r.height;

			 var p = this.persons[this.regions[i].person];
			 this.persons[this.regions[i].person].centerX = p.right - (p.qRadius / 2);
			 this.persons[this.regions[i].person].centerY = p.top + (p.qRadius / 2);
		 }
	 }

	 this.onMouseClick = function (e)
	 {
		 osoboQuote.quote(e);
	 }

	 this.addQuote = function (personId, text)
	 {
		 personId = parseInt(personId);
		 if (this.persons[personId])
		 {
			 this.persons[personId].quotes.push(text);
		 }
	 }

	 this.showNextQuote = function ()
	 {
		 if (!this.autoSwitchEnabled)
			 return;

		 this.showQuote(this.regions[this.curQRegionIndex], false, true);
		 if (this.curQRegionIndex == this.regions.length - 1)
			 this.curQRegionIndex = 0;
		 else
			 this.curQRegionIndex++;
		 
		this.autoSwitchTimer = setTimeout('osoboQuote.showNextQuote()', 2500);
	 }

	 this.disableAutoSwitch = function ()
	 {
		 this.autoSwitchEnabled = false;
		 clearTimeout(this.autoSwitchTimer);		 
	 }

	 this.showQuote = function (r, visible, useAltLayout)
	 {
		 var p = this.persons[r.person];
		 var qArea = p.qAreas[p.qaIndex];
		 var style = this.styles[this.curStyle][p.qaIndex - 1];		 
		 var xRight = qArea[0] - style.arrowOffsetX;
		 var yTop = qArea[1] + style.arrowOffsetY;
		 var ret = this.isQuoteInScreen(style, xRight, yTop);
		 //console.log('quote in screnn ' + ret);
		 // если не влезает по x
		 if (ret == -1 || ret == -2)
		 {
			 if (useAltLayout)
			 {
				 if (p.qaIndex == 4)
					 p.qaIndex = 3;
				 else if (p.qaIndex == 3)
					 p.qaIndex = 4;
				 else if (p.qaIndex == 2)
					 p.qaIndex = 1;
				 else if (p.qaIndex == 1)
					 p.qaIndex = 2;
				 
				 qArea = p.qAreas[p.qaIndex];
				 style = this.styles[this.curStyle][p.qaIndex - 1];
				 xRight = qArea[0] - style.arrowOffsetX;
				 yTop = qArea[1] + style.arrowOffsetY;
			 }
			 else
				 return;
		 }

		 $('div#quote').css('background-position', style['background-position'])						  
					   .css('width', style['width'])
					   .css('height', style['height'])
					   .css('padding', style['padding'])
					   .css( { 'top': yTop, 'right': xRight } )
					   .html(p.quotes[p.quoteIndex])
					   .show();
		 //console.log('quoteInScreen ' + this.isQuoteInScreen(style, xRight, yTop));
		 this.visible = visible;
		 if (p.qaIndex + 1 > p.qAreasCount)
			 this.persons[r.person].qaIndex = p.qAreasFirst;
		 else
			 this.persons[r.person].qaIndex++;

		 if (this.curStyle + 1 > this.styles.length - 1)
			 this.curStyle = 0;
		 else
			 this.curStyle++;
		 if (p.quoteIndex + 1 > p.quotes.length - 1)
			 this.persons[r.person].quoteIndex = 0;
		 else
			 this.persons[r.person].quoteIndex++;
		 //console.log('set visible');
		 //return true;
	 }

	 this.quote = function (e)
	 {		 
		 if (!this.switchQuotes)
			 return false;

		 var r = this.getRegion(e.clientX, e.clientY);
		 if (r != null)
		 {
			 //console.log('region detected');
			 if (this.visible)
			 {
				 //console.log('already visible');
				 return true;
			 }

			// first of all - disable auto-switch
			 this.disableAutoSwitch();
			 this.showQuote(r, true, true);
			 return true;
		 }
		 else
		 {
			 //console.log('not in region');
			 if (this.visible)
			 {
				 //console.log('hide');
				 $('div#quote').hide();
				 this.visible = false;
				 this.autoSwitchEnabled = true;
				 this.showNextQuote();
			 }
			 return false;
		 }
	 }

	 this.getRegion = function (x, y)
	 {
		 for (var i = 0; i < this.regions.length; i++)
		 {
			 var r = this.regions[i];
			 if (x >= r.left && x <= r.right && y >= r.top && y <= r.bottom)
				return r;
		 }

		 return null;
	 }

	 this.onDocResize = function (e)
	 {
		 this.adjustRegions();
	 }

	 // помещается ли цитата в рабочую область дисплея - 1 да -1 - не влезает по x -2 не влезает по y
	 this.isQuoteInScreen = function (quoteStyle, xRight, yTop)
	 {
		 //console.log('test: ' + quoteStyle.fullHeight + ' ' + yTop);
		 if (quoteStyle.fullWidth + xRight >= $(document).width())
			 return -1;
		 //todo: точное значение высоты рабочей области viewport'а
		 else if (quoteStyle.yTop + quoteStyle.fullHeight >= $('body').height())
			 return -2;
		 else
			 return 1;
	 }

	 // получить случайные координаты появления цитаты
	 /*
	 this.getRandomQuoteXY = function (person)
	 {
		 var p = this.persons[person];
		 var x1 = this.regions[person - 1].left;
		 console.log('x1: ' + x1 + ' ' + p.width);
		 console.log('y1: ' + p.top + ' ' + p.height);
		 var x = x1 + ((Math.random() * 10000) % p.width);
		 var y = p.top + ((Math.random() * 10000) % p.height);
		 return { 'x': Math.ceil(x), 'y': Math.ceil(y) };
	 }
	 */

	 // получить квадрант цитирования - соответствует номеру структуру в соответствующем styles
	 /*
	 this.getPersonQuoteArea = function (person, xy)
	 {
		 var area = 0;
		 var p = this.persons[person];
		 if (xy.x > p.centerX)
			 if (xy.y > p.centerY)
				area = 1;
			 else
				area = 4;
		else
			if (xy.y > p.centerY)
				area = 2;
			else
				area = 3;				
	 }
	 */

	 this.adjustRegions();
	 //$(document).click(this.onMouseClick);
 }

 function onMouseMove(e)
 {
	 if (osoboQuote != null && osoboQuote.quote(e))
		return;

	for (var i = 0; i < osoboMenu.skipFunctions.length; i++)
		if (osoboMenu.skipFunctions[i](e))
			return;

	 osoboMenu.menu(e);
 }

 function onDocResize(e)
 {
	 osoboMenu.onDocResize(e);
	 if (osoboQuote != null)
		osoboQuote.onDocResize(e);
 }

/* вставить переносы между всеми буквами в тексте элементов, соответствующие css expr */
function wrapLetters(css)
{
	$(css).each( function (i) {
		var t = $(this).text();
		$(this).text('');
		var a = new Array();
		for (var i = 0; i < t.length; i++)
			a.push(t.charAt(i));
		$(this).html(a.join('<br />'));
	});
}

var osoboMenu  = null;
var osoboQuote = null;

$(document).ready(function () {
	osoboMenu = new OsoboMenu();
	osoboMenu.changeRolloversStatusBottom(2, 5, false);
	$(document).mousemove(onMouseMove);
	$(window).resize(onDocResize);
	wrapLetters('a.stdMenuItem');
});