/*************************************************
Tournaments calendar
version: 2.0
modified: 2009.03.30
project: PokerNews
*************************************************/

/*
* Pavaizduoja PokerNews spec. turnyru kalendoriu
************************************************/

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.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"];
}


/*
* inicializacija
************************************************/
tourCalendar.prototype.init=function()
{
	//sukuriam info diva
	var objBody = document.getElementsByTagName("body").item(0);
	jQuery(objBody).append('<div id="tourCalendarInfo" class="eventPopup" style="display:none;position:absolute;z-index:999"></div>');
    jQuery('#tourCalendarInfo').bind('mouseover',function(){tourCalendar.instance.infoShow()});
	jQuery('#tourCalendarInfo').bind('mouseout',function(){tourCalendar.instance.infoHide()});
	//pakraunam duomenis
	this.reload();
}


/*
* funkcija, kuriai ajax perduoda duomenis
************************************************/
tourCalendar.prototype.getHTTP=function(xmlDoc)
{

        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 && this.monthLoaded[parseInt(day)]) this.show(day);
	else {
		var _self = this;
		jQuery.get(this.url, {day: day}, function(x){_self.getHTTP(x)}, "xml")
	}
}


/*
* 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>';
	jQuery('#tourCalendar').html(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=jQuery('#tourCalendarInfo').get(0);
        var p=jQuery(o).offset();

		div.innerHTML=s;
		div.style.left=(p.left-250)+'px';
		div.style.top=(p.top+10)+'px';
		div.style.display = 'block';
		if (trackOutgoing) {
			trackOutgoing(div);
		}

		//jeigu yra vietos tai i desine vaizduokim
		if (jQuery(window).width() + jQuery(window).scrollLeft() <= p.left+jQuery(div).outerWidth()+15) {
			div.style.left=(p.left-jQuery(div).outerWidth()+Math.round(jQuery(o).outerWidth())/2)+'px';
		} else {
            div.style.left=(p.left+Math.round(jQuery(o).outerWidth())/2)+'px';
		}
		/*var dif = (jQuery(window).height() + jQuery(window).scrollTop()) - (p.top+jQuery(div).outerHeight()+15);
		if (dif<0) {
			jQuery(window).scrollTop(0-dif);
		}*/
	}
}

/*
* 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()
{
	jQuery('#tourCalendarInfo').hide();
}


/*
* 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();
	}

	
}
