﻿var xmlhttp;
var currItem = 0,currScroll,scrollTimer,totalItems,makeScrollTo,scrollDelayTimer;
var barHeight = 20;
var timeout,globdoCin,globdiv,globcinemaName,globTheatreName,globDaily;
var weekdaysNames = ["Воскресенье","Понедельник","Вторник","Среда","Четверг","Пятница","Суббота"];
var monthsNames = ["января","февраля","марта","апреля","мая","июня","июля","августа","сентября","октября","ноября","декабря"];

function DEBUG(message)
{
	document.getElementById("debug").innerHTML += "<br>" + message;
}

function getXmlHttp2(url,handler){
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	} catch (e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		} catch (E) {
		xmlhttp = false;
		}
	}
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		xmlhttp = new XMLHttpRequest();
	}
	timeout = setTimeout( function(){ xmlhttp.abort(); handleError("Time over") }, 10000);
	xmlhttp.open("GET", url, true);
	xmlhttp.onreadystatechange = handler;
	xmlhttp.send("a = 4");
}

function continueLoading(){
  now = new Date;
  if (xmlhttp.readyState  !=  4) return
  clearTimeout(timeout) // очистить таймаут при наступлении readyState 4
  if (xmlhttp.status  ==  200) {
	if (globdoCin)
		parseXML("" + now.getDay());
	else
		parseXMLTheatre("" + now.getDay());
      return;
  } else {
      handleError(xmlhttp.statusText) // вызвать обработчик ошибки с текстом ответа
  }
}

function handleError(message) {
	return "<font color = 'red'>В настоящий момент идет обновление расписания, повторите попытку позже. Приносим извинения за временные неудобства</font>";
}

function print_r(theObj){
  if(theObj.constructor == Array ||
     theObj.constructor == Object){
    document.write("<ul>")
    for(var p in theObj){
      if(theObj[p].constructor == Array||
         theObj[p].constructor == Object){
document.write("<li>["+p+"] => "+typeof(theObj)+"</li>");
        document.write("<ul>")
        print_r(theObj[p]);
        document.write("</ul>")
      } else {
document.write("<li>["+p+"] => "+theObj[p]+"</li>");
      }
    }
    document.write("</ul>")
  }
}

function getAttributes(node){
	var ret = new Object();
	if(node.attributes)
		for(var i = 0; i<node.attributes.length; ++i)
		{
			var attr = node.attributes[i];
			ret[attr.name] = attr.value;
		}
	return ret;
}

function markSeances(seances){
	var seancesTime = seances.split(/[\s,]+/g);
	var now = new Date();
	var tmpTime = new Date();
	var res = "<span id='missed'>";
	var flag = true;
	for (var i = 0; i < seancesTime.length; ++i)
	{
		tmp = seancesTime[i].split(":");
		tmpTime.setHours(Number(tmp[0]));
		tmpTime.setMinutes(Number(tmp[1]));
		if (flag && (tmpTime > now))
		{
			res += "</span><span id='notMissed'>" + seancesTime[i] + '&nbsp; ';
			flag = false;
		}
		else
			res += seancesTime[i] + "&nbsp; ";
	}
	res = res.substr(0,res.length - 7);
	res += "</span>";
	return res;
}

function parseXML(currentDay){
    var xml = xmlhttp.responseXML;
	var div = globdiv;
	if(!xml) 
	{
		return "<font color = 'red'>В настоящий момент идет обновление расписания, повторите попытку позже. Приносим извинения за временные неудобства</font>";
	}
	now = new Date;
	tempdate = new Date;
	tempdate.setTime(86400000);
	var cinemas = xml.getElementsByTagName("cinema");
    var cinema = null;
	var rowscnt = 0;
	var cinemaUrl = "";
	output=""
	if (globDaily)
	{
		output += "<ul id = 'daysmenu'>"
		do
		{
			if (now.getDay() == currentDay)
			{
				output += "<a href='javascript:void(0)'><li id='current' onClick = 'parseXML(\"" + now.getDay() + "\"); return false;'>" + weekdaysNames[now.getDay()] + "<br/>&nbsp;&nbsp;&nbsp;" + now.getDate() + " "  +  monthsNames[now.getMonth()]  +  "</li></a>";
				tempdate.setTime(now.getTime());
			}
			else
				output += "<a href='javascript:void(0)'><li onClick = 'parseXML(\"" + now.getDay() + "\"); return false;'>" + weekdaysNames[now.getDay()] + "<br/>&nbsp;&nbsp;&nbsp;" + now.getDate() + " "  +  monthsNames[now.getMonth()]  +  "</li></a>";
			now.setTime(now.getTime()  +  86400000);
		}
		while (now.getDay() != 4)
		output += "</ul><br><p id='ScheduleHeader'>Расписание на " + weekdaysNames[tempdate.getDay()] + " " + tempdate.getDate() + " " + monthsNames[tempdate.getMonth()] + "</p>";
	}
	tempdate = new Date;
	var urls = new Object();
	for (var i = 0, max = cinemas.length;i<max;++i)
	{
		cinema = cinemas[i];
		var days = cinema.childNodes;
		for (var i2 = 0, max2 = days.length; i2<max2; ++i2)
		{
			var day = days[i2];
			var dayAttrs = getAttributes(day)
			//if (dayAttrs["numbers"] && (dayAttrs["numbers"].indexOf(currentDay) > -1))
			{
				var cinema_attrs = getAttributes(cinema);
				var films = day.childNodes;
				for (var i3 = 0, max3 = films.length; i3<max3 ; ++i3)
				{
					film = films[i3];
					var film_attrs = getAttributes(film);
					if (film_attrs["name"])
						if (film_attrs["url"])
							urls[film_attrs["name"]] = film_attrs["url"];
						
				}
			}
		}
	}
	
	output += "<table class = \"tbl1\"><tbody><tr><td class = \"MovieTableCinemaHeader\"><p>Кинотеатры</p></td><td class = \"MovieTableSeanceHeader\">";
	output += "<p>Сеансы</p></td><td class = \"MovieTablePriceHeader\"><p>Цены</p></td><td class = \"MovieTablePhoneHeader\"><p>Справка и    заказ билетов</p></td>";
	output += "</tr></tbody></table>";
	for (var i = 0, max = cinemas.length;i<max; ++i)
	{
		cinema = cinemas[i];
		days = cinema.childNodes;
		//alert(cinema);
		for (var i2 = 0, max2 = days.length; i2 < max2; ++i2)
		{
			var day = days[i2];
			var dayAttrs = getAttributes(day);
			if (dayAttrs["numbers"] && (!globDaily || (dayAttrs["numbers"].indexOf(currentDay) > -1)))
			{
				//alert(dayAttrs["numbers"]);
				var cinema_attrs = getAttributes(cinema);
				var films = day.childNodes;
				for (var i3 = 0, max3 = films.length; i3 < max3; ++i3)
				{
					film = films[i3];
					var film_attrs = getAttributes(film);
					if (film_attrs["name"])
						if (film_attrs["name"].toLowerCase() == globcinemaName.toLowerCase())
						{
							if (rowscnt%2)
								output += "<table class = \"tbl1\">";
							else
								output += "<table class = \"tbl2\">";
							output += "<tbody><tr><td class = \"MovieTableCinemaContent\"><p><a href = \""  +  cinema_attrs["url"]  +  "\">"  + cinema_attrs["name"] + "</a></p></td><td class = \"MovieTableSeanceContent\">";
							if (tempdate.getDay() == currentDay)
								output += "<p>" + markSeances(film_attrs["seance"]) + "</p>";
							else
								output += "<p>" + film_attrs["seance"].replace(/[\s,]+/g, '&nbsp; ') + "</p>";
							output += "</td><td class = \"MovieTablePriceContent\">";
							if (film_attrs["price"])
								output += "<p>" + film_attrs["price"] + "</p>";
							else
								output += "<p>" + cinema_attrs["price"] + "</p>";
							output += "</td><td class = \"MovieTablePhoneContent\"><p>" + cinema_attrs["telephone"] + "</p></td></tr></tbody></table>";
							if (film_attrs["url"])
								cinemaUrl = film_attrs["url"];
							++rowscnt;
						}
				}
			}
		}
	}
	if ((globcinemaName.toLowerCase().indexOf("3d") == -1)&&(globcinemaName.toLowerCase().indexOf("4d") == -1)&&urls[globcinemaName])
		output += "<div class='descr_button'><div><a href = '"  +  urls[globcinemaName]  +  "'><div></div></a></div></div>";
	div.innerHTML = output;
	return output;
}

function ShowCinemaTable(url, div,thisptr,cinemaName,daily){
	daily = !daily;
    var div = document.getElementById(div);
	globdoCin = true;
	globdiv = div;
	globcinemaName = cinemaName;
	globDaily = daily;
    if(!div) return;
    getXmlHttp2(url,continueLoading);
}	

function getNextSeance(seances){
	var seancesTime = seances.split(/[\s,]+/g);
	var now = new Date();
	var tmpTime = new Date();
	for (var i = 0; i < seancesTime.length; ++i)
	{
		tmp = seancesTime[i].split(":");
		tmpTime.setHours(Number(tmp[0]));
		tmpTime.setMinutes(Number(tmp[1]));
		if (tmpTime > now)
			return seancesTime[i] ;
	}
	return false;
}

function continueShowNextSeanceBar(){
	if (xmlhttp.readyState  !=  4) return
	clearTimeout(timeout) // очистить таймаут при наступлении readyState 4
	if (xmlhttp.status  ==  200) {
	} else {
		handleError(xmlhttp.statusText) // вызвать обработчик ошибки с текстом ответа
	}
    var xml = xmlhttp.responseXML;
	if(!xml) 
	{
		return "<font color = 'red'>В настоящий момент идет обновление расписания, повторите попытку позже. Приносим извинения за временные неудобства</font>";
	}
	var cinemas = xml.getElementsByTagName("cinema");

	var now = new Date;
	var currentDay = "" + now.getDay();
	var seances = new Object();
	var urls = new Object(), places = new Object;
	for (var i = 0, max = cinemas.length;i<max;++i)
	{
		cinema = cinemas[i];
		var days = cinema.childNodes;
		for (var i2 = 0, max2 = days.length; i2<max2; ++i2)
		{
			var day = days[i2];
			var dayAttrs = getAttributes(day)
			if (dayAttrs["numbers"] && (dayAttrs["numbers"].indexOf(currentDay) > -1))
			{
				var cinema_attrs = getAttributes(cinema);
				var films = day.childNodes;
				for (var i3 = 0, max3 = films.length; i3<max3 ; ++i3)
				{
					film = films[i3];
					var film_attrs = getAttributes(film);
					if (film_attrs["name"])
					{
						if (film_attrs["url"])
							urls[film_attrs["name"]] = film_attrs["url"];
						var nextSeance = getNextSeance(film_attrs["seance"]);
						if (nextSeance)
						{
							if (!seances[film_attrs["name"]]) 
								seances[film_attrs["name"]] = new Object;
							if (!seances[film_attrs["name"]]["seance"] || nextSeance < seances[film_attrs["name"]]["seance"])
							{
								seances[film_attrs["name"]]["seance"] = getNextSeance(film_attrs["seance"]);
								seances[film_attrs["name"]]["place"] = cinema_attrs["name"].replace(/\<br\>/igm," ");
								seances[film_attrs["name"]]["place_url"] = cinema_attrs["url"];
							}
						}
					}
				}
			}
		}
	}
	var output = "<div><a onClick='--currItem; liClick(currItem);' href='javascript:void(0)' class='left_arrow'> &lt; </a> <a onClick='++currItem; liClick(currItem);' href='javascript:void(0)' class='right_arrow'> &gt; </a><ul id='seance_list' class='seance_list'>";
	var i = 0;
	var flag = true, str;
	totalItems = 0;
	for (name in seances)
		if (seances[name])
		{
			//output += "<li onClick='liClick(" + i + ");'><a href='" + urls[name] + "'>" + name + "</a> " + seances[name] + "</li>";
			if (flag)
			{
				str = "<li><a href='" + urls[name] + "'>" + name.replace(/<br>/igm," ") + "</a><span> " + seances[name]["seance"] + " (<a href='" + seances[name]["place_url"] + "'>" + seances[name]["place"] + "</a>)</span></li>";
				flag = false;
			}
			output += "<li><a href='" + urls[name] + "'>" + name.replace(/<br>/igm," ") + "</a><span> " + seances[name]["seance"] + " (<a href='" + seances[name]["place_url"] + "'>" + seances[name]["place"] + "</a>)</span></li>";
			//alert("<li><a href='" + urls[name] + "'>" + name + "</a><span> " + seances[name]["seance"] + " (<a href='" + seances[name]["place_url"] + "'>" + seances[name]["place"] + "</a>)</span></li>");
			++totalItems;
		}
	if (!str) 
	{
		output = "На сегодня сеансов нет";
		globdiv.innerHTML = output;
		return output;
	}
	output += str;
	output += "</ul></div>";
	globdiv.innerHTML = output;
	//alert(output);
	setScrollDelayTimer();
	return output;
}

function setScrollDelayTimer()
{
	scrollDelayTimer = setInterval(function () {++currItem; liClick(currItem); return;},2000);
	return;
}


function liClick(index){
	clearInterval(scrollTimer);
	clearInterval(scrollDelayTimer);
	var ul = document.getElementById("seance_list");
	var currMargin = ul.style.marginTop;
	if (index > totalItems)
	{
		ul.style.marginTop = "0px";
		currScroll = 0;
		index = 1;
		currItem = 1;
	}
	else if (index < 0) {
		currScroll = totalItems * 22;
		index = totalItems - 1;
		currItem = totalItems - 1;
		ul.style.marginTop = "-" + currScroll * 22 + "px";
	}
	else
		currScroll = currMargin.substring(currMargin.indexOf('-') + 1, currMargin.length - 2);
	if (!currScroll) currScroll = 0;
	makeScrollTo = index * 22;
	scrollTimer = setInterval(function() {
											if (currScroll == makeScrollTo){ clearInterval(scrollTimer); setScrollDelayTimer(); return;};
											if (currScroll > makeScrollTo) --currScroll;
											else ++currScroll;
											var ul = document.getElementById("seance_list");
											ul.style.marginTop = "-" + currScroll + "px";
										},20);
	
}

function ShowNextSeanceBar(url,div)
{
	globdiv = document.getElementById(div);
	getXmlHttp2(url,continueShowNextSeanceBar);
}

function parseXMLTheatre(currentDay){
    var xml = xmlhttp.responseXML;
	var div = globdiv;
    if(!xml) 
	{
		return "<font color = 'red'>В настоящий момент идет обновление расписания, повторите попытку позже. Приносим извинения за временные неудобства</font>";
	}
	var output = "";
    var cinemas = xml.getElementsByTagName("cinema");
    var cinema = null;
	var rowscnt = 1;
	var now = new Date;
	var tempdate = new Date;
	//alert(globDaily);
	if (globDaily)
	{
		output += "<ul id='daysmenu'>"
		do
		{
			if (now.getDay() == currentDay)
			{
				output += "<a href='javascript:void(0)'><li id='current' onClick = 'parseXMLTheatre(\"" + now.getDay() + "\"); return false;'>" + weekdaysNames[now.getDay()] + "<br/>&nbsp;&nbsp;&nbsp;" + now.getDate() + " "  +  monthsNames[now.getMonth()]  +  "</li></a>";
				tempdate.setTime(now.getTime());
			}
			else
				output += "<a href='javascript:void(0)'><li onClick = 'parseXMLTheatre(\"" + now.getDay() + "\"); return false;'>" + weekdaysNames[now.getDay()] + "<br/>&nbsp;&nbsp;&nbsp;" + now.getDate() + " "  +  monthsNames[now.getMonth()]  +  "</li></a>";
			now.setTime(now.getTime()  +  86400000);
		}
		while (now.getDay() != 4)
		output += "</ul><br><p id='ScheduleHeader'>Расписание на " + weekdaysNames[tempdate.getDay()] + " " + tempdate.getDate() + " " + monthsNames[tempdate.getMonth()] + "</p>";
	}
	tempdate = new Date;
    var urls = new Object();
	for (var i = 0, max = cinemas.length;i<max;++i)
	{
		cinema = cinemas[i];
		var days = cinema.childNodes;
		for (var i2 = 0, max2 = days.length; i2<max2; ++i2)
		{
			var day = days[i2];
			var dayAttrs = getAttributes(day)
			//if (dayAttrs["numbers"] && (dayAttrs["numbers"].indexOf(currentDay) > -1))
			{
				var cinema_attrs = getAttributes(cinema);
				var films = day.childNodes;
				for (var i3 = 0, max3 = films.length; i3<max3 ; ++i3)
				{
					film = films[i3];
					var film_attrs = getAttributes(film);
					if (film_attrs["name"])
						if (film_attrs["url"])
							urls[film_attrs["name"]] = film_attrs["url"];
						
				}
			}
		}
	}
	for (var i = 0, max = cinemas.length;i<max;++i)
	{
		cinema = cinemas[i];
		var days = cinema.childNodes;
		for (var i2 = 0, max2 = days.length; i2<max2; ++i2)
		{
			var day = days[i2];
			var dayAttrs = getAttributes(day)
			if (dayAttrs["numbers"] && (!globDaily || (dayAttrs["numbers"].indexOf(currentDay) > -1)))
			{
				var cinema_attrs = getAttributes(cinema);
				var films = day.childNodes;
				if (cinema_attrs["name"].toLowerCase() == globcinemaName.toLowerCase())
				for (var i3 = 0, max3 = films.length;i3<max3;++i3)
				{
					film = films[i3];
					var film_attrs = getAttributes(film);
					if (film_attrs["name"])
						{
							if (rowscnt%2)
								output += "<table class = \"tblTheatre1\">";
							else
								output += "<table class = \"tblTheatre2\">";
							output += "<tbody><tr><td class = \"MovieTableCinemaContent\">";
							if (urls[film_attrs["name"]])
								output += "<p><a href = \""  +  urls[film_attrs["name"]]  +  "\">" + film_attrs["name"] + "</a></p>";
							else
								output += "<p>"  +  film_attrs["name"] + "</p>";
							output += "</td><td class = \"MovieTableSeanceContent\">";
							if (tempdate.getDay() == currentDay)
								output += "<p>" + markSeances(film_attrs["seance"]) + "</p>";
							else
								output += "<p>" + film_attrs["seance"].replace(/[\s,]+/g, '&nbsp; ') + "</p>";
							output += "</td></tr></tbody></table>";
							++rowscnt;
						}
				}
			}
		}
	}
	//output += "<p style = \"text-align: center;\"><a href = \"index.php?option = com_content&amp;view = article&amp;id = 235:2010-07-31-17-51-39&amp;catid = 1:2010-03-15-13-01-43&amp;Itemid = 4\"><img border = \"0\" src = \"images/stories/cinema/ops.gif\"/></a></p>";
    //div.innerHTML = output;
	div.innerHTML = output;
	return output;
}

function ShowTheatreTable(url, div,thisptr,cinemaName,daily){
	daily = !daily;
	var div = document.getElementById(div);
	globdoCin = false;
	globdiv = div;
	globcinemaName = cinemaName;
	globDaily = daily;
    if(!div) return;
    getXmlHttp2(url,continueLoading);
}

