// JQuery

// $(document).ready(function(){
//  $("body").ScrollToAnchors('fast');
// });

function reminder()
{
email=document.getElementById('emailfield');
if (email.value!='')
	{
	toggle('passsent');
	}
else
	{
	toggle('fillmail');
	}	
}

function authorization(todo)
{
if (todo=='open')
	{
	button=document.getElementById('in-out-button');
	button.className='none';
	form=document.getElementById('in-out-form');
	form.className='block';
	}

if (todo=='close'&&whatHover()!='autho')
	{
	button=document.getElementById('in-out-button');
	button.className='block';
	form=document.getElementById('in-out-form');
	form.className='none';
	}

}

function toggle()
{
  var objectId = 'goalsContainer'
  
  var object = document.getElementById(objectId);
  
  if (object.className == 'none')
	{
	  object.className = 'block';
	}
  else
	{
	  object.className = 'none';
	}
}

// Легкая оптимизация для разных разрешений экрана ;-)

function load() 
{
if (document.body.clientWidth>1280) 
	{
	document.getElementById('body').style.width='1280px';
	}
	
	else 
	{
	if (document.body.clientWidth<1024) 
		{
		document.getElementById('body').style.width='1024px';
		}
	else
		{
		document.getElementById('body').style.width="100%";
		}
	}

if (document.body.clientWidth<1100) 
	{
	document.getElementById('journalcontainer').className='journalcontainer1024';
	}
}



// Поведение формы с комментарием

function commentFocus(textbox)
{
textbox.style.height='200px';
if (textbox.value=='Ваш комментарий')
	{		
	textbox.value=''; 
	}
}

function commentBlur(textbox)
{
if (textbox.value=='')
	{		
	textbox.value='Ваш комментарий'; 
	}
}

function comment(textbox, buttonid)
{
button=document.getElementById('button1');
if (textbox.value!='Ваш комментарий'&&textbox.value!='') 
	{
	button.disabled=false;
	}
else
	{
	button.disabled=true;
	}
}

function commentSubmit(textbox)
{
if (textbox.value=='Ваш комментарий'||textbox.value=='') 	
	{
	alert("Пожалуйста, напишите что-нибудь более содержательное! :-)"); 
	return false;
	}
}

function themeSubmit(themename, themetext)
{
if (themename.value==''||themetext.value=='') 	
	{
	alert("Пожалуйста, заполните все поля!"); 
	return false;
	}
}

// Подружиться

function makeFriend(who)
{
whom = document.getElementById(who);
whom.innerHTML='Ваш друг';
whom.className='nonpseudofriend';
}

// Дневник --- Подсветка

function highlight(day) 
{
today=day.id;
document.getElementById('body').setAttribute('over', today);
if (!isTodayActivated(day)) {day.className='highlight';}
}

function unlight(day, deact) 
{
if (!deact) 
	{
	document.getElementById('body').setAttribute('over', 'none');
	activated=whatActivated();
	if (activated!=day)
		{
		deact=true;
		}
	}

if (deact)
	{
	if (day.getAttribute('month')!='yes')
		{
		day.className='unlight';
		}
	else
		{
		day.className='monthstart';
		}
	}
}


/// Взятие нажатий клавиш и обработка нажатий Enter и Esc

function press(e) 
{

if (!e) 
	{
	e = window.event || null; 
	}

var n = e.keyCode?e.keyCode:e.charCode; // Код нажатой клавиши
	
switch(n) 
	{ 
	case 13: action('deact',null,'key','loud'); break;
	case 27: action('goback',null,'key','loud'); break;
	}

if (n==13||n==27)
	{
	// отключаем дефолтные функции для Мозиллы (if) и для ИЕ (else).
	if(e.stopPropagation) 
		{
		e.stopPropagation();
		}
	else 
		{
		e.cancelBubble = true;
		}
	if(e.preventDefault) 
		{
		e.preventDefault();
		}
	else 
		{
		e.returnValue = false;
		}
	}
}

// Shortcut для активации сегодняшнего дня

function shortcut(today)
{
action('deact',null,'key','loud');
day=document.getElementById(today);
action('act', day, null, null);
window.scrollBy(0, 150);
}

function shortcutover(cut)
{
hover = document.getElementById('body').setAttribute('over', 'shortcut');
cut.className='pseudohover';
}

function shortcutout(cut)
{
hover = document.getElementById('body').setAttribute('over', 'none');
cut.className='pseudocut';
}


// Функция, выполняющие все, что надо, для активации, деактивации или отмены действий в ячейках

function action(what, day, mean, type) 
{

todo=null;

if (what=='act'&&!isTodayActivated(day))
	{
	todo='1';
	}
if (what=='deact'&&isActivated())
	{
	todo='2';
	}
if (what=='goback'&&isActivated())
	{
	todo='3';
	}
if (what=='deact'&&!isActivated())
	{
	return true;
	}




if (todo=='1'||todo=='2'||todo=='3')
	{
	if (todo=='1')
		{
		if (action('deact', day, 'mouse', 'silent'))
			{
			goact=true;
			todo='1';
			}
		else
			{
			goact=false;
			}
		}

	if (todo=='2'||todo=='3')
		{
		if (day!=null)
			{
			actday=day;
			}
		else
			{
			actday='none';
			}

		day=whatActivated();
		}



	today=day.id; // текущий день
	cols = new Array('km','what','how'); // просто буквы
	len=cols.length;

	colsid = new Array(len); // ID ячейки таблицы
	colsidObj = new Array(len); // Объект ячейки таблицы
	current = new Array(len); // Нужное значение, которое должно быть в ячейке или текстэрии
	obj=new Array(len); // Объект текстэрии

	for (i=0; i<len; i++)
		{  	 
		colsid[i]=today+cols[i];
		colsidObj[i]=document.getElementById(colsid[i]);
		}

	if (todo=='1')
		{
		for (i=0; i<len; i++)
			{  	
			current[i]=colsidObj[i].innerHTML;
			}
		}
	else
		{
		for (i=0; i<len; i++)
			{  	
			obj[i] = document.getElementById(cols[i]+'text');
		}
		if (todo=='2')
			{
			for (i=0; i<len; i++)
				{  	
				current[i]=obj[i].value;
				}
			}
		if (todo=='3')
			{
			for (i=0; i<len; i++)
				{
				current[i]=obj[i].getAttribute('goback');
				}
			}
		}
		

	if (todo=='1') // Здесь производим действия, а выше определяли значения
		{
		if (goact)
			{ 			
			doActivate(day);

			formelement=new Array(len);

			for (i=0; i<len; i++)
				{

				colsidObj[i].innerHTML='';
		
				if (i==0)
					{
					formelement[i] = document.createElement("input");
					formelement[i].setAttribute("type", "text");
					formelement[i].setAttribute("value", current[i]);
					}
				if (i==1||i==2)
					{
					formelement[i] = document.createElement("textarea");
					formelement[i].innerHTML = current[i];
					}
		
				formelement[i].className=cols[i]+'text';
				formelement[i].setAttribute("id", cols[i]+'text');
				formelement[i].setAttribute("goback", current[i]);

				colsidObj[i].appendChild(formelement[i]);
				}	
			formelement[0].focus();

			return true;
			}
		else
			{
			return false;
			}		
		}

	if (todo=='2'||todo=='3')
		{
		if ((whatHover()!=today&&whatHover()!='shortcut')||mean=='key'||todo=='3') 
			{
			while (/\s/.test(current[0]))
				{
				current[0] = current[0].replace(' ', '');
				}
	
			if (isValid(current[0],type)||todo=='3')
				{
				for (i=0; i<len; i++)
					{
					colsidObj[i].removeChild(obj[i]);
					colsidObj[i].innerHTML=current[i];
					}
				doDeactivate();
				if (actday!='none')
					{
					day=actday;
					}
				return true;
				}
			else
				{
				return false;
				}
			}
		}
	}
	
else
	{
	return false;
	}

}




// Функции, выдающие информацию о состоянии ячеек

function isActivated() 
{
status=document.getElementById('body').getAttribute('activated');
	
if (status!='none') 
	{
	return true;
	}
else 
	{
	return false;
	}
}

function isTodayActivated(day) 
{
if (day==whatActivated()) 
	{
	return true;
	}
else 
	{
	return false;
	}
}

function whatActivated() 
{
today=document.getElementById('body').getAttribute('activated');
day=document.getElementById(today);
return day;
}

function whatHover() 
{
hover = document.getElementById('body').getAttribute('over');
return hover;
}

// Функции, непосредственно активирующие и деактивирующие ячейки (изменяется статус, подсветка и устанавливается перехват нажатия клавиш

function doActivate(day) 
{
today=day.id;
document.getElementById('body').setAttribute('activated', today);
day.className='active';

if (document.addEventListener) // IE
	{
	document.addEventListener("keydown", press, false);
	}
else if (document.attachEvent) // W3C (Gecko...)
	{
	document.attachEvent("onkeydown", press);
	}
else 
	{
	document.onkeypress = document.onkeydown = press;
	}

}

function doDeactivate()
{
day=whatActivated();
//day.className='unlight';
unlight(day, true);
document.getElementById('body').setAttribute('activated', 'none');

if (document.removeEventListener) // IE
	{
	document.removeEventListener("keydown", press, false);
	}
else if (document.detachEvent) // W3C (Gecko...)
	{
	document.detachEvent("onkeydown", press);
	}
else 
	{
	document.onkeypress = document.onkeydown = null;
	}
}

// Функции, проверяющие введенные пользователем данные

function isNumber(num, type)
{
reg = /^-?\d+$/;
	if (reg.test(num)||num=='') 
	{
	return true;
	}
else
	{
	if (type!='silent')
		{
		alert('Общий километраж за день должен быть натуральным числом \n\nНапример, «5», «10» или «21»');
		}
	return false;
	}
}

function nonWorldRecord(num, type)
{
if (num<304) 
	{
	return true;
	}
else
	{
	if (type!='silent')
		{
		alert('Вы только что побили мировой рекорд Янниса Куроса в суточном беге — 303 км 506 м (установлен 10 мая 1997 в Аделаиде). \n\nМы обязательно засчитаем этот результат после официального утверждения IAAF. \n\nА пока, пожалуйста, исправьте ваш километраж на более скромный');
		}
	return false;
	}
}

function isValid (kmvalue, type)
{
if (isNumber(kmvalue, type)&&nonWorldRecord(kmvalue, type))
	{
	return true;
	}
else
	{
	return false;
	}
}
