/*************************************************
Tournaments calendar
version: 1.1.1
modified: 2008.09.09
project: PokerNews
*************************************************/

/*
* Pavaizduoja PokerNews turnyru kalendoriu
* Pvz. var tc=new
************************************************/

function tourCalendar(cellspacing)
{
	this.cellspacing = cellspacing ? cellspacing : 0;

	//tik vienas kalendorius gali buti
    if(typeof(tourCalendar.instance)=="undefined") {
    	tourCalendar.instance = this;
	} else {
		return;
	}
	// ! ajax urlas duomenims gauti
	this.url='/en/2tour.calendar';

	var _self = this;
    this.ajax = new ajax('text/xml');
	this.ajax.outputToFunction(function (){ _self.getHTTP()});
    eventAdd(window, 'load', function() {_self.init(); });

	this.timer=null; //divai kad nemirgetu reikia su setTimeout zaisti
    this.monthLoaded=[]; //tu menesiu kuriu duomenis turime siusti nebereikia
	this.info=[]; //saugomi ajax gauti duomenys

	// ! vertimams skirti masyvai
	this.startSunday=false;
    this.weekDays = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat","Sun"];
	this.monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    this.words = ["Special PokerNews Freerolls","Poker room", "Time", "Buy in", "Prize", "Qualification points", "Qualification period"];

	//kalendorius
    document.writeln('<div id="tourCalendar"></div>');
	//info popup
	//document.writeln('<div id="tourCalendarInfo" class="eventPopup" style="position:absolute;display:none;z-index:10" onmouseover="tourCalendar.instance.infoShow()" onmouseout="tourCalendar.instance.infoHide()"></div>');
	document.close();

    //parodom kalendoriu be duomenu dar
	this.show();
}


/*
* inicializacija
************************************************/
tourCalendar.prototype.init=function()
{
	//sukuriam info diva
	var objBody = document.getElementsByTagName("body").item(0);
    var d = document.createElement("div");
	d.setAttribute('id','tourCalendarInfo');
	d.setAttribute('class','eventPopup');
	//d.setAttribute('onmouseover','tourCalendar.instance.infoShow()');
	//d.setAttribute('onmouseout','tourCalendar.instance.infoHide()');
	d.style.display = 'none';
	d.style.position = 'absolute';
	d.style.zIndex = '999';
	objBody.appendChild(d);
    eventAdd(d,'mouseover',function(){tourCalendar.instance.infoShow()});
	eventAdd(d,'mouseout',function(){tourCalendar.instance.infoHide()});
	//pakraunam duomenis
	this.reload();
}


/*
* funkcija, kuriai ajax perduoda duomenis
************************************************/
tourCalendar.prototype.getHTTP=function()
{
	var http=this.ajax.http;
	if(http.readyState==4 && typeof(http.responseXML)=="object") {
        var xmlDoc=http.responseXML;
        var a,day,month;

		//kokio menesio duomenys atejo
        var xitems = xmlDoc.getElementsByTagName('month');
		if (xitems && xitems[0]) month=parseInt(xitems[0].firstChild.nodeValue);

		//irasai
        xitems = xmlDoc.getElementsByTagName('item');
		if (xitems && xitems[0]) {
			for (var i = 0; i < xitems.length; i++) {
				var xitem = xitems[i].childNodes;
                a=[];
				for (var j = 0; j < xitem.length; j++) {
					var xtag=xitem[j];
					if (xtag.nodeName=='#text') continue;
                    a[xtag.nodeName]=xtag.firstChild ? xtag.firstChild.nodeValue : '';
					//alert(xtag.nodeName+'='+xtag.firstChild.nodeValue);
                    //var event_atr = events_xml[i].attributes;
                    //for (var i2 = 0; i2 < event_atr.length; i2++) if (event_atr[i2].name == 'id') event_id = event_atr[i2].value;
				}

				//turim vieno item duomenis
				if (a['day']) {
                    day=parseInt(a['day']);
					if (!this.info[day] || this.info[day].month!=month) {
						this.info[day]=[];
						this.info[day].text='';
						this.info[day].type=0;
						this.info[day].month=month;
					}
                    this.info[day].text+=this.infoItemConstruct(a);
					this.info[day].type= this.info[day].type | parseInt(a['type']);
				}
			}
		}
		this.monthLoaded[month]=1;
        this.show(month);
	}
}

/*
* funkcija, kuria pradeda ajax duomenu gavima
************************************************/
tourCalendar.prototype.reload=function(day)
{
	this.infoClose();
    var m = new myDate();
	if (day) m.fromDays(day);
	m.change('d',1);
    day=0+m;
	if (this.monthLoaded[parseInt(day)]) this.show(day);
	else this.ajax.get(this.url + '?day=' + day);
}


/*
* funkcija, piesianti kalendoriu
************************************************/
tourCalendar.prototype.show=function(day)
{
	var m = new myDate();
	var today=0+m;
    m.change('d',1);
	var thisMonth1st=0+m;
	if (typeof(day)!="undefined") m.fromDays(day);
    m.change('d',1);


	var w = m.getWday();
	//jei prasideda savaite sekmadieniu, pastumkim per diena
	if (this.startSunday) w = (w==7) ? 1 : (w+1);
	var lastDay = m.getMdays();

    var prevMonth = new myDate();
    prevMonth.fromDays(0+m-1);
	var lastDayPrev = prevMonth.getMdays();

    var kiek = lastDay + w - 1 + 7;

	var s='<table cellpadding="0" cellspacing="'+this.cellspacing+'" id="minitable"><caption>';
	if (m>thisMonth1st) s+= '<a href="" onclick="tourCalendar.instance.reload('+(m-lastDayPrev)+');return false;"><img class="prev" src="/img/calendar_prev.gif" alt="prev" /></a> ';
	s+= this.monthNames[m.getMonth()-1] +' '+m.getYear();
	s+= ' <a href=""><img class="next" src="/img/calendar_next.gif" alt="next"  onclick="tourCalendar.instance.reload('+(m+lastDay)+');return false;" /></a>';
	s+= '</caption><tbody>';

	s+="<tr>";
    //jei prasideda savaite sekmadieniu, pastumkim per diena
	var shift = this.startSunday ? -1 : 0;
	for (var i=0;i<7;i++) s+='<th class="dayname">'+this.weekDays[(shift+i+7) % 7]+'</th>';

    s+="</tr>";

	var z,d,dd;
	for (var i=2-w; i<=kiek; i++) {
		z= i+w-1;
		if (i<1) d = lastDayPrev + i;
		else if(i>lastDay) d= i - lastDay;
		else d=i;
        if (z % 7 == 1) s+='<tr valign="top">';
		dd=i+m-1;
		if (dd==today) s+='<td class="today">';
		else s += '<td' + (d!=i ? ' class="other"' : '') + '>';
        if (this.info[dd]) {
        	s+='<div onmouseover="tourCalendar.instance.infoShow(this,'+dd+')" onmouseout="tourCalendar.instance.infoHide()">';
			if (this.info[dd].type & 1) s+='<div class="eventas fr"></div>';// general freeroll
			if (this.info[dd].type & 2) s+='<div class="eventas lt"></div>'; //buy-in tournament
			if (this.info[dd].type & 4) s+='<div class="eventas sf"></div>'; //special freeroll
		} else s+='<div>';
		s+= d + '</div></td>';
		if (z % 7 == 0) {
			s+='</tr>';
			if (i>=lastDay) break;
		}
	}
    s += '</tbody></table>';
    /*<div class="bottomFilter">
			<input type="checkbox" id="check_s" /> <label for="check_s" style="color: #1D9524;">Special freerolls</label><br />
			<input type="checkbox" id="check_f" /> <label for="check_f" style="color: #0A51AD;">General freerolls</label><br />
			<input type="checkbox" id="check_t" /> <label for="check_t" style="color: #E2171E;">Buy-in tournaments</label>
		</div>*/
	$('tourCalendar').innerHTML = s;

}


/*
* parodo info popupa
************************************************/
tourCalendar.prototype.infoShow=function(o,day)
{
	if (this.timer) {
		clearTimeout(this.timer);
		this.timer=0;
	}
	if (o) {

		var date=new myDate();
		if (day) date.fromDays(day);
		var s='<h3 class="title">'+this.words[0]+'<span class="date">'+this.weekDays[date.getWday()-1]+', '+this.monthNames[date.getMonth()-1] +' '+date.getDay()+', '+date.getYear()+'</span></h3>';//<span class="close"  onclick="tourCalendar.instance.infoClose()">x</span>
		s+=this.info[day].text;
		var div=$('tourCalendarInfo');

        var p=getOffset(o);

		div.innerHTML=s;
		div.style.left=(p.x-250)+'px';
		div.style.top=(p.y+10)+'px';
		div.style.display = 'block';

		//jeigu yra vietos tai i desine vaizduokim
        var scroll=this.get_window_scroll();
		var view=this.get_viewport_size();
		if (view.width + scroll.x <= p.x+div.offsetWidth+15) {
			div.style.left=(p.x-div.offsetWidth+Math.round(o.offsetWidth)/2)+'px';
		} else {
            div.style.left=(p.x+Math.round(o.offsetWidth)/2)+'px';
		}

	}
}

tourCalendar.prototype.get_viewport_size=function()
{
    var w = 0;
	var h = 0;
	/*window.navigator.userAgent.indexOf( 'Opera' )==-1 &&*/
    if( document.documentElement && (!document.compatMode || document.compatMode=="CSS1Compat")) {
		w = document.documentElement.clientWidth;
        h = document.documentElement.clientHeight;
	} else if (document.compatMode && document.body && document.body.clientWidth) {
        w = document.body.clientWidth;
        h = document.body.clientHeight;
	} else if(window.innerWidth) {
        w = window.innerWidth;
        h = window.innerHeight;
    }
	return {width: w, height: h};
}

tourCalendar.prototype.get_window_scroll=function()
{
    var _x = 0;
    var _y = 0;
	if(document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) {
        _x = document.documentElement.scrollLeft;
        _y = document.documentElement.scrollTop;
	} else if(document.body && (document.body.scrollLeft || document.body.scrollTop)) {
		_x = document.body.scrollLeft;
        _y = document.body.scrollTop;
	} else if(window.pageXOffset || window.pageYOffset) {
		_x = window.pageXOffset;
		_y = window.pageYOffset;
	}
	return {x: _x, y: _y};
}


/*
* perduoda info popup signala uzsidaryti
************************************************/
tourCalendar.prototype.infoHide=function()
{   //this.infoClose();
	var _self=this;
	if (!this.timer) this.timer=setTimeout(function (){_self.infoClose()}, 800);
}


/*
* uzdaro info popup
************************************************/
tourCalendar.prototype.infoClose=function()
{
	$('tourCalendarInfo').style.display = 'none';
}


/*
* sukonstruoja vieno turnyro iraso HTML
************************************************/
tourCalendar.prototype.infoItemConstruct=function(a)
{
	var names=[];
    names['room']=this.words[1];
    names['time']=this.words[2];
	names['buyin']=this.words[3];
	names['prize']=this.words[4];
	names['qpoints']=this.words[5];
	names['qperiod']=this.words[6];

	var css = 'freeroll';
	if (a['type']==2) css='tournament';
	else if (a['type']==4) css='special';
	var s = '<h2 class="'+css+'">'+a['name']+'</h2>'
	s+='<table class="tourtable">';
	for (i in a) {
		if (typeof(names[i])=="string" && a[i]!=='' && names[i]){
			s+='<tr>';
			s+='<td class="first">'+names[i]+'</td><td class="last">'+a[i]+'</td>';
			s+='<tr>';
		}
	}
	s+='</table>';
    return s;
}



/**********************************************************/
/**********************************************************/
/**********************************************************/

function myDate(stamp)
/* gauna tekstine data (pvz 2004-05-29, arba 2004.05.29) 
   pavirsta i datos objekta
*/
{


//methods definitions
this.getYear = function ()
{
	return(this.y);
}

this.getMonth = function ()
{
	return(this.m);
}

this.getDay = function ()
{
	return(this.d);
}

this.getWday = function ()
//kelinta svaites diena 1 - pirmadienis, 7 - sekmadienis
{
	var M=(this.m>2 ? (this.m-2):(this.m+10)) ;
	var c=Math.floor(this.y/100);
	var Y=this.y % 100;
	if (this.m<=2) Y-- ;
	var s=this.d+Math.floor( (13*M-1)/5 )+Y+Math.floor(c/4)+Math.floor(Y/4)-2*c;
	s=s % 7;
	if (s<1) s+=7;
	return s;
}

this.getMdays = function ()
//kiek sis menuo turi dienu
{
    var s =( ( Math.floor(this.m+this.m/8) % 2 ) ? 31:30);
	if (this.m==2) { //jei vasaris
		var Y=this.y;
		s= (Y % 400==0 || ((Y % 4==0) && (Y % 100)) ) ? 29 : 28;
	}
   return s;
}
	
this.toDays = function ()
//pasako kiek dienu praejo nuo metu pradzios (kaip analogiska mysql funkcija)
{
	var y,m,d,c,k;
	y=this.y;
	m=this.m;
	d=this.d;
	c=Math.floor((y-1)/100);//simtmeciu skaicius
	k=y*365+Math.floor((y-1)/4)+Math.floor(c/4)-c;
	var mon=new Array('', 0,31,59,90,120,151,181,212,243,273,304,334);
	k+=mon[m]+d;
	if (m>2 && (y % 4 == 0)) {
		if	(y % 100 !=0 || (Math.floor(y/100) % 4 ==0) ) k+=1;
	}
	return k;
}

this.fromDays = function (days)
//atvirkstine toDays funkcija
{
	days=Math.abs(parseInt(days,10));
	if (days<366 || days>3652424) {
		this.y=this.m=this.d=0;
		return (false);
	}
	var mon=new Array(0, 0,31,59,90,120,151,181,212,243,273,304,334);
	var c,y,m,d,hasd,i;
	y=Math.floor(days*100/36525);
	c=Math.floor((y-1)/100);
	d=days-y*365-Math.floor((y-1)/4)-Math.floor(c/4)+c;
	while (d > (hasd=((y % 4==0 && (y % 400==0 || y % 100)) ? 366:365)) ) {
		d-=hasd;	y++;
	}
	while (d<1) d+=(--y % 4==0 && (y % 400==0 || y % 100)) ? 366:365;
	if (hasd===366) for (i=3;i<=12;i++) mon[i]+=1;
	for (i=12;i>=1;i--) {
    	if (mon[i]<d) {
			m=i;
			d=d-mon[i];
			break;
		}
	}
	this.y=y;
	this.m=m;
	this.d=d;
}

this.show = function (delim)
{
	if (delim==null) delim='-';
	var s='';
	if (this.y<10) s+='0';
	if (this.y<100) s+='0';
	if (this.y<1000) s+='0';
	return s+this.y+delim+(this.m<10 ? '0':'')+this.m+delim+(this.d<10 ? '0':'')+this.d;
}

this.change = function (key,value)
{
	if (key=='y') this.y=value;
	else if (key=='m') this.m=value;
	else if (key=='d') this.d=value;
	if (this.getMdays() < this.d) this.d=this.getMdays();
}

this.valueOf = function ()
{
	return this.toDays();
}

this.toString = function ()
{
	return this.show('-');
}


	
	//properties
	this.y=0;
	this.m=0;
	this.d=0;
	
	//contructor
    if (typeof(stamp)=="undefined") {
		var time=new Date();
		stamp=((2000+time.getYear()%100)+'.'+(time.getMonth()+1)+'.'+time.getDate());
	}

    //if (typeof(stamp)!="string") alert(stamp);
	stamp=stamp.replace(/-/g,'.');
	var re_date = /^(\d+)\.(\d+)\.(\d+)$/;
    var myMatch = re_date.exec(stamp);
	if (!myMatch) {
	  	alert("Blogas datos formatas: "+ stamp);
        this.y=this.m=this.d=0;
    } else {
		this.y=parseInt(myMatch[1],10);
		this.m=parseInt(myMatch[2],10);
		this.d=parseInt(myMatch[3],10);
		if (this.getMdays() < this.d) this.d=this.getMdays();
	}

	
}
