var request = null;
var requestLetter = null;
var httpAjaxBase;
var TIMEOUT;

if (document.location.href.indexOf("localhost") == -1 ) {
	httpAjaxBase = "http://www.angeldance.ru/";
	TIMEOUT = 30000;
} else {
	httpAjaxBase = "http://localhost/angeldance/";
	TIMEOUT = 5000;
}

if ( window.location.href.indexOf('page=foto') > 0 ) {
	// picassaweb
	$(document).ready(function() {
		var options = {
			username: '100897886820233047755',
			labels: {
				photo:"фотография",
				photos: "фотографий",
				albums: "&lt; вернуться к списку альбомов",
				slideshow: "Начать слайдшоу",
				loading: "PWI получение данных...",
				page: "Стр",
				prev: "Пред",
				next: "След",
				devider: "|"
			},
			months: ["Январь","Февраль","Март","Апрель","Май","Июнь","Июль","Август","Сентябрь","Октябрь","Ноябрь","Декабрь"]
		};
		$("#picassa").pwi(options);
	});

	$(document).ready(function() {
		$('#videos').youTubeChannel();
	});
}

$(document).ready(function() {
	// если нет запланированных тренингов перейдем на страницу о контактной импровизации
	// console.dir(window.location);
	if (
		(window.location.href == "http://www.angeldance.ru/" ||
			window.location.href == "http://www.angeldance.ru/default.aspx")
			&& $('div.trainingItem').length === 0
		) {
		window.location.href = "http://www.angeldance.ru/?page=what";
	}
/* 	var options2 = {
		username: '100897886820233047755',
		mode: 'album',
		// album: 'ffpeGB',
		album: 'Album1',
		authkey: 'Gv1sRgCPfmicm5r9jEyAE'

	};
	$("#picassa2").pwi(options2); */
});

function PageLoaded() {
	// document.body.onmousemove = _debug;
    if ( window.location.href.indexOf('http://angeldance.ru') >= 0 ) {
        window.location.href = "http://www.angeldance.ru";
    }

    document.getElementById("allCalendar").title = "";
    var aLinks = document.body.getElementsByTagName("a");
    for ( i = 0; i < aLinks.length; i++ )
    {
        if ( aLinks[i].title == "Go to the previous month" )
            aLinks[i].title = "Предыдущий месяц";
        if ( aLinks[i].title == "Go to the next month" )
            aLinks[i].title = "Следующий месяц";
    }
    if ( window.location.href.indexOf('page=contacts') > 0 )
    {
        document.contactform.style.visibility = 'visible';
    }

    setTimeout("ChangeTraining()", TIMEOUT);
}

function CreateXmlRequest() {
	try{ return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }catch(e){}
	try{ return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }catch(e){}
	try{ return new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){}
	try{ return new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){}
	throw new Error("Could not find an XMLHttpRequest alternative.");
}

function ChangeTraining() {
    request = window.XMLHttpRequest ? new XMLHttpRequest() : CreateXmlRequest();
    sInput = "task=nexttraining";
    request.open("POST", httpAjaxBase + "ajax.aspx", true);
   	request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	request.setRequestHeader("Content-length", sInput.length);
	request.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
	request.setRequestHeader("Connection", "close");

	request.onreadystatechange = TrainingComplete;
	request.send(sInput);
}

function TrainingComplete() {
    if (request.readyState == 4 && request.status == 200)
    {
        if ( request.responseText )
        {
            var training   = request.responseXML.documentElement;
            if ( training !== null )
            {
				var items = training.childNodes;
				for ( j = 0; (items !== null) && (j < items.length); j++ )
				{
					if (!items[j].firstChild) {
						continue;
					}
				    if (items[j].nodeName == 'id')
				        document.getElementById("training_link").setAttribute('href', '?page=training&id=' + items[j].firstChild.nodeValue);
				    if (items[j].nodeName == 'picture')
				        document.getElementById("training_img").setAttribute('src', 'trainings/' + items[j].firstChild.nodeValue);
					if (items[j].nodeName == 'who')
					    SetDataToElement("training_who", items[j].firstChild.nodeValue );
				    if (items[j].nodeName == 'name')
				        SetDataToElement("training_name", '«' + items[j].firstChild.nodeValue + '»' );
				    if (items[j].nodeName == 'date')
				        SetDataToElement("training_date", items[j].firstChild.nodeValue );
				    if (items[j].nodeName == 'address')
				        SetDataToElement("training_address", "место: " + items[j].firstChild.nodeValue );
			    }
            }
        }
        setTimeout("ChangeTraining()", TIMEOUT);
    }
}

function SetDataToElement(sElement, sData) {
	var el = document.getElementById(sElement);
	el.innerText = el.textContent = sData;
}

function DateMouseOver(e, sText) {
	var _POPUPWIDTH = 300;
	var _OFFSET = 20;
	var posx = 0;
	var posy = 0;
	var evt = e || window.event;

	if (evt.pageX || evt.pageY)
	{
		posx = evt.pageX;
		posy = evt.pageY;
	}
	else if (evt.clientX || evt.clientY)
	{
		posx = evt.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
		posy = evt.clientY + document.documentElement.scrollTop + document.body.scrollTop;
	}
	posx = posx - _POPUPWIDTH - _OFFSET;
	posy = posy + _OFFSET;

	var popup = document.getElementById("training_container");
    popup.style.left = posx.toString() + 'px';
    popup.style.top = posy.toString() + 'px';
    popup.innerHTML = sText;
    popup.style.display = "block";
}

function DateMouseOut() {
    document.getElementById("training_container").innerText		= "";
	document.getElementById("training_container").style.display	= "none";
}

function trainingClick() {
    window.location.href = document.getElementById("training_link").getAttribute('href');
}

function send_letter(s) {
    if ( document.contactform.form_name.value.length < 5 || document.contactform.form_mail.value.length < 5 )
    {
        alert('Введите свое полное имя и настоящий e-mail!');
        return;
    }
    document.contactform.form_button.disabled = true;

    requestLetter = window.XMLHttpRequest ? new XMLHttpRequest() : CreateXmlRequest();
    sInput = "what=" + encodeURIComponent(s) +
             "&name=" + encodeURIComponent(document.contactform.form_name.value) + "&mail=" + encodeURIComponent(document.contactform.form_mail.value) +
             "&tel=" + encodeURIComponent(document.contactform.form_phone.value) + "&text=" + encodeURIComponent(document.contactform.form_comment.value);
    requestLetter.open("POST", httpAjaxBase + "send.aspx", true);
   	requestLetter.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
	requestLetter.setRequestHeader("Content-length", sInput.length);
	requestLetter.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
	requestLetter.setRequestHeader("Connection", "close");

	requestLetter.onreadystatechange = SendComplete;
	requestLetter.send(sInput);
}

function SendComplete() {
    if (requestLetter.readyState == 4 && requestLetter.status == 200)
    {
        if ( requestLetter.responseText == "OK" )
            alert('Принято, спасибо!');
        else
            alert('Ошибка, повторите попозже!');
        document.contactform.form_button.disabled = false;
    }
}

function _debug(e) {
	var posx = 0;
	var posy = 0;
	var evt = e || window.event;

	if (evt.pageX || evt.pageY)
	{
		posx = evt.pageX;
		posy = evt.pageY;
	}
	else if (evt.clientX || evt.clientY)
	{
		posx = evt.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
		posy = evt.clientY + document.documentElement.scrollTop + document.body.scrollTop;
	}
	var div = document.getElementById("debug");
	var popup = document.getElementById("training_container");
	div.innerHTML = posx + ' x ' + posy + '<br />' + popup.style.left + '<br />' + popup.style.top;
	// div.style.left = (posx - 0) + "px";
	// div.style.top = posy + "px";
	div.style.display = "block";
}
