var nowS;
var y, m, d, now;

//na wszelki wypadek jak nie powiedzie siê odczytanie daty z serwera
    now = new Date();
    y = now.getFullYear();
    m = ""+(now.getMonth()+1);
    if(m.length==1) m="0"+m;
    d = now.getDate();
    nowS = y+"-"+m+"-"+d;		

var days_pl = new Array("Pn", "Wt", "Åšr", "Cz", "Pt", "So", "N");
var days_en = new Array("Mo", "Tu", "We", "Th", "Fr", "Sa", "S");
var days = days_pl;
var currentLang = "pl";

var months_pl = new Array("StyczeÅ„", "Luty", "Marzec", "KwiecieÅ„", "Maj", "Czerwiec", "Lipiec", "SierpieÅ„", "WrzesieÅ„", "PaÅºdziernik", "Listopad", "GrudzieÅ„");
var months_en = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
var months = months_pl;

var mode = 1;  // tryb kalendarza (1=miesiÄ…c, 12=caÅ‚y rok)

//++++++++
function isHoliday() {
new Ajax.Request('now.jsp?'+Math.random(),   
{     method:'post',
onSuccess: function(transport){  
	var response = transport.responseText || "no response text";       
	nowS = response;
	//alert(nowS);
	//YYYY-MM-DD
	y=nowS.substring(0,nowS.indexOf("-"));
	nowS=nowS.substring(nowS.indexOf("-")+1);
	m=nowS.substring(0,nowS.indexOf("-"));
	nowS=nowS.substring(nowS.indexOf("-")+1);
	d=nowS;
	d++; d--; //hack
	//alert(y+' '+m+' '+d);
	now = new Date();
	now.setFullYear(y);
	now.setMonth(m);
	now.setDate(d);

	m++;
	if(m<10) m="0"+m;
	if(d<10) d="0"+d;	
	//alert(now);
	//alert("y="+y+" m="+m+" d="+d);
	nowS = y+"-"+m+"-"+d;
 
	//alert("Data z serwera: "+nowS);
	window.status='';
},     
onFailure: function(){
	window.status=('Data ze stacji roboczej/Date from workstation.');
},asynchronous:false
}
)

//alert("now & nowS: "+now+ ", "+nowS);
//sunday is 0
ret = false;
ret = now.getDay()==6 || now.getDay() == 0;
//alert("1:"+isHoliday);

//alert(extraRedDaysALL.join()+","+extraYellowDays.join());
ret = ret || ((extraRedDaysALL.join()+","+extraYellowDays.join()).indexOf(nowS)>-1);

//alert(isHoliday);

return ret;
}

//--------
function showTradingCalendar(lang, extraYellowDays, extraRedDaysALL, fullYear, month)
{
changeLanguage(lang);

var calendar = document.getElementById('myCalendar');
if(mode==1) 
{
    calendar.innerHTML = "";
    var a = document.createElement('div');
    calendar.appendChild(a);
    a.setAttribute('id', 'myMonth');
    a.setAttribute('class', 'myMonth');
    a.setAttribute('className', 'myMonth');
    a.style.cssFloat = "none";
    a.style.styleFloat = "none";

    renderOneMonth('myMonth', lang, extraYellowDays, extraRedDaysALL, fullYear, month);
}
else if(mode==12) 
{
    renderWholeYear(lang, extraYellowDays, extraRedDaysALL, fullYear);
}
}

//--------
function renderOneMonth(parent, lang, yellowDaysALL, extraRedDaysALL, fullYear, month)  // month=0..11
{
var monthDIV = document.getElementById(parent);
monthDIV.innerHTML = "";

//var addEvent;
//addEvent = function(element, type, handler)
//{
//    element.addEventListener(type, handler, null);
//}

//addEvent(monthDIV, "click", alert("addEvent"), false);

//monthDIV.setAttribute('onclick', 'alert("blabla")');

//monthDIV.onclick = 'alert("a")';
//monthDIV.addEventListener('onClick', 'alert("blabla")');


var headerDIV = document.createElement('div');
monthDIV.appendChild(headerDIV);
// var headerA = document.createElement('a');
// headerDIV.appendChild(headerA);
// headerA.innerHTML = months[month];
// headerA.href="#";
// headerA.className="headerMthA";
// headerA.setAttribute('onclick',"alert('aaa!'); changeMode(1); showTradingCalendar('"+lang+"', yellowDaysALL, extraRedDaysALL, '"+fullYear+"', '"+month+"'); changeMode(1); ");
// w IE zdarzenie onclick nie moze byc dodane dynamicznie!!! hahaha

//  hack: 
headerDIV.innerHTML = '<a href="#" class="headerMthA" id="headerMth_'+(month<10? "0"+month : month)+'" onclick="changeMode(1); showTradingCalendar(\''+lang+'\', extraYellowDays, extraRedDaysALL, \''+fullYear+'\', \''+month+'\'); setMonth('+month+');">'+months[month]+' '+fullYear+'</a>';

if(month<10)  month="0"+month;
// headerA.setAttribute('id', "headerMth_"+month)

var a;
for(var i=0; i < 7+42; i++)
{
    a = document.createElement('div');
    monthDIV.appendChild(a);
    if(i<7)
    {
        a.setAttribute('id', "mthDayHeader_"+month+"_"+i);
        a.innerHTML = days[i];
        a.setAttribute('className', (i<5?"headerMth":"headerMthRed") );
        a.setAttribute('class',     (i<5?"headerMth":"headerMthRed") );
        
    }
    else
    {
        a.setAttribute('class', "whiteDay");
        a.setAttribute('className', "whiteDay");
    }
}
var selectedMonthYear = new Date(fullYear, month, 1);
fillDates(selectedMonthYear, yellowDaysALL, extraRedDaysALL);

selectTodaysDate(); // zaznacz dzisiejszÄ… datÄ™
}

function renderWholeYear(lang, yellowDaysALL, extraRedDaysALL, fullYear)
{
changeMode(12);
var calendar = document.getElementById('myCalendar');
var a;
calendar.innerHTML = "";
//calendar.style.height = 850;
for(var i=0;i<12;i++)
{
//    a = document.createElement('div');
//    calendar.appendChild(a);
//    a.setAttribute('class', "myMonth");
//    a.setAttribute('className', "myMonth");
//    a.setAttribute('id', "myMonth"+i);
//    
//    renderOneMonth(a.getAttribute('id'), lang, yellowDaysALL, extraRedDaysALL, fullYear, i);
    
    calendar.innerHTML += '<div id="myMonth'+i+'" class="myMonth" onmouseover="this.style.backgroundColor=\'#fafaff\'" onmouseout="this.style.backgroundColor=\'#fff\'" onclick="changeMode(1); showTradingCalendar(\''+lang+'\', extraYellowDays, extraRedDaysALL, \''+fullYear+'\', \''+i+'\'); setMonth('+i+');"></div><div style="float:left; width:10px; ">&nbsp;</div>';
    
    renderOneMonth("myMonth"+i, lang, yellowDaysALL, extraRedDaysALL, fullYear, i);
    
}
}

//--------
function fillDates(date, yellowDaysALL, extraRedDaysALL) // date - zaznaczony miesiÄ…c i rok.
{
    var firstDay;  // Jaki dzien tygodnia to yyyy/mm/01. (kiedy zaczÄ…Ä‡ miesiÄ…c)
    var noDaysPrevMth; // ile dni miaÅ‚ poprzedni m-c
    var noDaysCurrMth; // ile dni ma ten m-c
    var tmp;   // iterowanie po el.
    var j, beginMth;
    var yellowL = yellowDaysALL.length, redL = extraRedDaysALL.length;
    var y=0, r=0; // iteratory tablic yellow & red
    var selectedMth = date.getMonth();
    if(selectedMth<10) selectedMth="0"+selectedMth;
    
    firstDay = date.getDay();
    if (firstDay==0) firstDay = 7
    
    noDaysPrevMth = noOfDaysInPrevMth(date.getFullYear(), date.getMonth() ); 
    noDaysCurrMth = noOfDaysInMth(date.getFullYear(), date.getMonth() );
//    alert(
//          "noDaysPrevMth: "+noDaysPrevMth + "\n" +  
//          "noDaysCurrMth: "+noDaysCurrMth + "\n"+ 
//          "firstDay: "+firstDay 
//         )
    
    // iterowanie po 42 el.
    tmp = document.getElementById("mthDayHeader_"+selectedMth+"_6").nextSibling;
    while (tmp.nodeType!=1) tmp = tmp.nextSibling;
    
    j=firstDay-1;
    beginMth=j-1;

for(var i=0; i<42; i++) 
{
           
if(j>0)  // przed bieÅ¼Ä…cym miesiÄ…cem
{
// alert("j="+j+",  typ:"+tmp.nodeName+", "+tmp.innerHTML)
//            if(mode==1)  // dni poza miesiacem widoczne tylko w trybie 1 m-c
//            {
//                tmp.innerHTML = (noDaysPrevMth - j+1);
//                if(i%7==5 || i%7==6) tmp.className = "redDayOtherMth";
//                else tmp.className = "otherMth";
//                
//                var day = tmp.innerHTML;
//                var tmpMonth = date.getMonth()+1-1; // +1(0..11) -1(zmniejszamy miesiac)
//                var tmpYear = date.getFullYear();
//                if(tmpMonth==0) { tmpMonth=12; tmpYear--; }
//                tmp.setAttribute('id', tmpYear+'-'+(tmpMonth<10 ? "0"+tmpMonth : tmpMonth) +'-'+(day<10 ? "0"+day : day) );

//                // sprawdÅº czy kolorowaÄ‡ dzieÅ„ na Å¼Ã³Å‚to.
//                    //alert("y: "+y+", tmp.getAttribute('id'): "+tmp.getAttribute('id')+", yellowDaysALL[y]: "+yellowDaysALL[y]);
//                while(yellowDaysALL[y]<tmp.getAttribute('id') && y<yellowL) 
//                    y++;
//                if(y<yellowL && tmp.getAttribute('id')==yellowDaysALL[y])
//                {   tmp.className="yellowDayOtherMth"; }
//                // sprawdÅº czy kolorowaÄ‡ dzieÅ„ na czerwono.
//                while(extraRedDaysALL[r]<tmp.getAttribute('id') && r<redL) 
//                    r++;
//                if(r<redL && tmp.getAttribute('id')==extraRedDaysALL[r])
//                {   tmp.className="redDayOtherMth"; }
//            }
//            else 
    tmp.className = "none";
    j--;
}
else if((i-beginMth) > noDaysCurrMth)  // wyszliÅ›my poza bieÅ¼Ä…cy miesiÄ…c
{
//            if(mode==1)  // dni poza miesiacem widoczne tylko w trybie 1 m-c
//            {
//                tmp.innerHTML = (i-beginMth - noDaysCurrMth);
//                if(i%7==5 || i%7==6) tmp.className = "redDayOtherMth";
//                else tmp.className = "otherMth";

//                var day = tmp.innerHTML;
//                var tmpMonth = date.getMonth()+1+1; // +1(0..11) +1(zwiÄ™kszamy miesiac)
//                var tmpYear = date.getFullYear();
//                if(tmpMonth>12) { tmpMonth=1; tmpYear++; }
//                tmp.setAttribute('id', tmpYear+'-'+(tmpMonth<10 ? "0"+tmpMonth : tmpMonth) +'-'+(day<10 ? "0"+day : day) );

//                // sprawdÅº czy kolorowaÄ‡ dzieÅ„ na Å¼Ã³Å‚to.
//                    //alert("y: "+y+", tmp.getAttribute('id'): "+tmp.getAttribute('id')+", yellowDaysALL[y]: "+yellowDaysALL[y]);
//                while(yellowDaysALL[y]<tmp.getAttribute('id') && y<yellowL) 
//                    y++;
//                if(y<yellowL && tmp.getAttribute('id')==yellowDaysALL[y])
//                {   tmp.className="yellowDayOtherMth"; }
//                // sprawdÅº czy kolorowaÄ‡ dzieÅ„ na czerwono.
//                while(extraRedDaysALL[r]<tmp.getAttribute('id') && r<redL) 
//                    r++;
//                if(r<redL && tmp.getAttribute('id')==extraRedDaysALL[r])
//                {   tmp.className="redDayOtherMth"; }
//            }
//            else 
        tmp.className = "none";

    }
    else // bieÅ¼Ä…cy miesiÄ…c
    {
        tmp.innerHTML = (i-beginMth);
        if(i%7==5 || i%7==6) tmp.className = "redDay";
        else tmp.className = "whiteDay";
        

        var day = tmp.innerHTML;
        var tmpMonth = date.getMonth()+1;
        tmp.setAttribute('id', date.getFullYear()+'-'+(tmpMonth<10 ? "0"+tmpMonth : tmpMonth) +'-'+(day<10 ? "0"+day : day) );

        // sprawdÅº czy kolorowaÄ‡ dzieÅ„ na Å¼Ã³Å‚to.
            // alert("y: "+y+", tmp.getAttribute('id'): "+tmp.getAttribute('id')+", yellowDaysALL[y]: "+yellowDaysALL[y]);
        while(yellowDaysALL[y]<tmp.getAttribute('id') && y<yellowL) 
        {    y++;
        }
        if(y<yellowL && tmp.getAttribute('id')==yellowDaysALL[y])
        {   tmp.className="yellowDay"; }
        // sprawdÅº czy kolorowaÄ‡ dzieÅ„ na czerwono.
        while(extraRedDaysALL[r]<tmp.getAttribute('id') && r<redL) 
            r++;
        if(r<redL && tmp.getAttribute('id')==extraRedDaysALL[r])
        {   tmp.className="redDay"; }
    }
    
    do
        tmp = tmp.nextSibling;
    while (tmp && tmp.nodeType!=1);   // przeszukuj aÅ¼ skoÅ„czy siÄ™ zakres lub trafisz na kolejnego DIVa 
}
  
}

function noOfDaysInMth(fullYear, month)
{
    // co ciekawe, w konstruktorze Date() naleÅ¼y podaÄ‡ miesiÄ…c z przedziaÅ‚u 1..12,
    // zaÅ› funkcja getMonth() zwraca miesiÄ…c z przedziaÅ‚u 0..11!
        // alert("w fun: "+ month);
    var date = new Date(fullYear, month+1, 0);  // tu month 1..12!
        // alert("w fun, ale po Date(): "+ date.getMonth()  );
    return date.getDate();
}
function noOfDaysInPrevMth(fullYear, month) 
{
    if(month!=0) month--;
    else { fullYear--; month=11; }
    var date = new Date(fullYear, month+1, 0);  
    return date.getDate();
}

function changeLanguage(lang)
{
if(currentLang!=lang)
{
var headerDays;
var headerMth;

currentLang = lang;
// tÅ‚umacz nazwy miesiÄ™cy
if (lang=="pl")
{
    days = days_pl;
    months = months_pl;
}
else if(lang=="en")
{
    days = days_en;
    months = months_en;
}
// tÅ‚umacz nazwy dni tygodnia i nazwy miesiÄ™cy
for (var i=0; i<12; i++)
{
    if(i<10) i="0"+i;
    try 
    {
        headerMth = document.getElementById("headerMth_"+ i);
        headerMth.innerHTML = months[Math.abs(i)];
        
        headerDays = document.getElementById("mthDayHeader_"+i+"_0")
            // alert(headerDays.getAttribute('id') );
        headerDays.innerHTML = days[0];
        for (var j=1; j<7; j++)
        {
            do      // przesuÅ„ siÄ™ na nastÄ™pny DIV
                headerDays = headerDays.nextSibling;
            while(headerDays.nodeType!=1)
            headerDays.innerHTML = days[j];
        }
    }
    catch(ex) {}
}
}
}

function selectTodaysDate()
{
    var tmpTodayDate = now;
    var tmpMth = tmpTodayDate.getMonth()+1;
	var tmpDay = tmpTodayDate.getDate();
    var today = "" + tmpTodayDate.getFullYear()+'-' + (tmpMth<10 ? "0"+tmpMth : tmpMth) + '-'+(tmpDay<10 ? "0"+tmpDay : tmpDay);
	//alert("today: "+today);
    try{
        var todayCell = document.getElementById(today);
            // alert("znalazlem id: " + todayCell.innerHTML+",    className: "+todayCell.className)
        if(todayCell.className=="redDay")  { todayCell.className = "redDayCurrent";  }
        else if(todayCell.className=="yellowDay") { todayCell.className = "yellowDayCurrent";}
        else if(todayCell.className=="whiteDay") { todayCell.className = "whiteDayCurrent"; }
    }
    catch(ex) {}  // jeÅ›li element o tej dacie nie istniaÅ‚, nie rÃ³b nic.
}

function changeMode(dmode)
{
    mode = dmode;
    var calendar = document.getElementById('myCalendar');

    if(mode==1) 
    {
        $('months').style.display="inline";
        //calendar.style.height = 215;
    }
    else 
    {
        $('months').style.display="none";
        //calendar.style.height = 750;
    }
        
}

function setMonth(mth)
{
    document.getElementById('months').value= mth;
}


