﻿

function changeFrame(frameid)
{
  var oIframe = self.frames[frameid];
  
  if( self.frames[frameid] )
	oIframe = self.frames[frameid];
  else if( document.frames )
	oIframe = document.frames[frameid];
  
  if(oIframe != null)
	oIframe.document.write('You need to upgrade your browser to support ajax') ;
	
  return true;
}

function DatePicker_Showpopup(uniqueid)
{
    var iframe = document.getElementById(uniqueid + '_Iframe');
    var panel = document.getElementById(uniqueid + '_Panel'); 

    if (panel.style.display != 'none')
    {
		DatePicker_Hidedropdowns(uniqueid);
        iframe.style.display = 'none';
        panel.style.display='none';
        DatePicker_EnableSelect();
        
    }
    else
    {
        iframe.style.display = 'block';
        panel.style.display='block';
        DatePicker_DisableSelect();
        changeFrame(uniqueid + '_Iframe');    
        
        DatePicker_RenderPeriodMonths(uniqueid, '');
    }
}

function DatePicker_AdaptIframe(uniqueid)
{
	var panel = document.getElementById(uniqueid + '_Panel');
	var iframe = document.getElementById(uniqueid + '_Iframe');
	
	iframe.style.height = (panel.clientHeight+2) + 'px';
	iframe.style.width = panel.clientWidth + 'px';	
}

function DatePicker_AdaptMonthIframe(uniqueid)
{
	var monthddn = document.getElementById(uniqueid + '_Hiddenmonth');
	var monthiframe = document.getElementById(uniqueid + '_HiddenmonthIframe');
	
	monthiframe.style.height = monthddn.clientHeight + 'px';
	monthiframe.style.width = monthddn.clientWidth + 'px';
}
            
function DatePicker_Showmonths(uniqueid)
{
    if(document.getElementById(uniqueid + '_Hiddenmonth').style.display != 'block')
    {
    	DatePicker_Hidedropdowns(uniqueid);
    	document.getElementById(uniqueid + '_Hiddenmonth').style.display = 'block';
    	document.getElementById(uniqueid + '_HiddenmonthIframe').style.display = 'block';
    	DatePicker_AdaptMonthIframe(uniqueid);
    	DatePick_BubbleEvent = false;
    	document.onclick = function () { DatePicker_DocumentClick(uniqueid); };
    }
    else
    {
    	document.getElementById(uniqueid + '_Hiddenmonth').style.display = 'none';              
    }
}

function DatePicker_Hidedropdowns(uniqueid)
{
	document.getElementById(uniqueid + '_HiddenmonthIframe').style.display = 'none';	
	document.getElementById(uniqueid + '_Fwdyear').style.display = 'none';                
	document.getElementById(uniqueid + '_FwdyearIframe').style.display = 'none';
	document.getElementById(uniqueid + '_Rewyear').style.display = 'none';                
   	document.getElementById(uniqueid + '_RewyearIframe').style.display = 'none';
   	document.getElementById(uniqueid + '_Hiddenmonth').style.display = 'none';   	
}

function DatePicker_DocumentClick(uniqueid)
{
	if(DatePick_BubbleEvent == true)
	{
		DatePicker_Hidedropdowns(uniqueid);
		document.onclick = null;
		document.onmouseup = null;
		document.onmousedown = null;
	}
	
	
	DatePick_BubbleEvent = true;
}

function DatePicker_Showfwdyears(uniqueid)
{
    var fwddiv = document.getElementById(uniqueid + '_Fwdyear');
    var fwdiframe = document.getElementById(uniqueid + '_FwdyearIframe');
	
    if(fwddiv.style.display != 'block')
    {
    	DatePicker_Hidedropdowns(uniqueid);
	    currdate_control = document.getElementById(uniqueid + '_CurrDate');
	    var curryear = new Date(currdate_control.value).getFullYear();

	    var dropdowndivs = '';
	    for(i = 1; i < 10; i++)
	    {
			dropdowndivs = dropdowndivs + '<div onmouseover="javascript:DatePicker_Mouseovercolorchange(this, 1);" onmouseout="javascript:DatePicker_Mouseoutcolorchange(this);" onclick="javascript:DatePicker_Callyears(\'' + uniqueid + '\', \'_Fwdyear\', ' + (curryear+i) + ');" class=\"DatePicker_yearitem DatePicker_Text\">' + (curryear+i) + '</div>';
	    }

	    fwddiv.innerHTML = dropdowndivs;
	    fwddiv.style.display = 'block';
		fwdiframe.style.display = 'block';
	    DatePicker_AdaptYearsIframe(fwddiv, fwdiframe);
	    
		DatePick_BubbleEvent = false;
    	document.onclick = function () { DatePicker_DocumentClick(uniqueid); };
    }
    else
    {
    	DatePicker_Hidedropdowns(uniqueid);
    }
}

function DatePicker_Showrewyears(uniqueid)
{
    var rewdiv = document.getElementById(uniqueid + '_Rewyear');
    var rewiframe = document.getElementById(uniqueid + '_RewyearIframe');
    
    if(rewdiv.style.display != 'block')
    {
	    DatePicker_Hidedropdowns(uniqueid);

	    currdate_control = document.getElementById(uniqueid + '_CurrDate');
	    var curryear = new Date(currdate_control.value).getFullYear();

	    var dropdowndivs = '';
	    for(i = 1; i < 10; i++)
	    {
		dropdowndivs = dropdowndivs + '<div onmouseover="javascript:DatePicker_Mouseovercolorchange(this, 1);" onmouseout="javascript:DatePicker_Mouseoutcolorchange(this);" onclick="javascript:DatePicker_Callyears(\'' + uniqueid + '\',\'_Rewyear\' ,' + (curryear-i) + ');" class=\"DatePicker_yearitem DatePicker_Text\">' + (curryear-i) + '</div>';
	    }

	    rewdiv.innerHTML = dropdowndivs;
	    rewdiv.style.display = 'block';
	    rewiframe.style.display = 'block';
	    DatePicker_AdaptYearsIframe(rewdiv, rewiframe);
	    
	    
	    DatePick_BubbleEvent = false;
    	document.onclick = function () { DatePicker_DocumentClick(uniqueid); };
    }
    else
    {
        DatePicker_Hidedropdowns(uniqueid);
    }
}

function DatePicker_AdaptYearsIframe(yeardiv, iframe)
{
	iframe.style.height = (yeardiv.clientHeight+2) + 'px';
	iframe.style.width = (yeardiv.clientWidth+2) + 'px';
}

function DatePicker_Callyears(uniqueid, controlid, year)
{
    var yearfield = document.getElementById(uniqueid + controlid);
    var datefield = document.getElementById(uniqueid + '_CurrDate');
    var newdate = new Date(datefield.value);
    newdate.setYear(year);
    datefield.value = (newdate.getMonth()+1) + '/1/' + newdate.getFullYear();

    yearfield.style.display = 'none';
    DatePicker_RenderPeriodMonths(uniqueid, 'year');
}

function DatePicker_Closeyears(uniqueid)
{
    var yearfield = document.getElementById(uniqueid);
    yearfield.style.display = 'none';
}            

function DatePicker_Callmonth(uniqueid, month)
{
    var datefield = document.getElementById(uniqueid + '_CurrDate');
    var newdate = new Date(datefield.value);
    newdate.setMonth(month);

    datefield.value = (newdate.getMonth()+1) + '/1/' + newdate.getFullYear();

    DatePicker_RenderPeriodMonths(uniqueid, 'year');
}


function DatePicker_GetCalendarHTML(res)
{
    var uniqueid = res.value.Uniqueid;

    var Calendar = new Date(res.value.FromDate);
    var year = Calendar.getFullYear(); // Returns year
    var month = Calendar.getMonth();    // Returns month (0-11)
    var today = Calendar.getDate();    // Returns day (1-31)
    var weekday = Calendar.getDay();    // Returns day (1-31)

    var DAYS_OF_WEEK = 7;    // "constant" for number of days in a week
    var DAYS_OF_MONTH = 31;    // "constant" for number of days in a month
    var cal;    // Used for printing
    
    var Month_of_year = new Array ();
    Month_of_year = eval('DatePicker_month_of_year_' + uniqueid).split(',');
    var Day_of_week = new Array();
    Day_of_week = eval('DatePicker_day_of_week_' + uniqueid).split(',');
    var toolTip = eval('DatePicker_tooltip_' + uniqueid);
    
    
    Calendar.setDate(1);
    Calendar.setMonth(month);

    // Render table
    cal = '<table class="DatePicker_drop_down_calendar DatePicker_Text" border="0" cellspacing="0" cellpadding="0">';
    cal += '<tr class="DatePicker_datepick_daynames DatePicker_Text">';
	cal += '<td class="DatePicker_datepick_wk DatePicker_Text">Wk</td>'
  
    // Print weekdays
    for(index=0; index < DAYS_OF_WEEK; index++)
    {
        cal += '<td class="DatePicker_datepick_dayname DatePicker_Text">' + Day_of_week[index] + '</td>\r\n';
    }



    // If first day of the month isn't monday we need to take care of rendering the weeknr here
    // else it's handled in the loop below
    if(Calendar.getIsoDay() > 0)
    {
        cal += '</tr>\r\n';
	    cal += '<tr>\r\n';
		cal += '<td class="DatePicker_datepick_wknr DatePicker_Text">' + Calendar.getWeekNumber() + '</td>\r\n'
    }
    
    // Fill gaps so the first date starts on the correct day    
    for(index=0; index < Calendar.getIsoDay(); index++)
    {
        cal += '<td class=\"DatePicker_regular_date DatePicker_Text\"></td>\r\n';
    }
        
    for(index=0; index < DAYS_OF_MONTH; index++)
    {
        if( Calendar.getDate() > index )
        {
            week_day = Calendar.getIsoDay();

            // New firstday = new row
            if(week_day == 0)
            {
				cal += '</tr>\r\n';
				cal += '<tr>\r\n';
				cal += '<td class="DatePicker_datepick_wknr DatePicker_Text">' + Calendar.getWeekNumber() + '</td>\r\n'
            }
            

            if(week_day != DAYS_OF_WEEK)
            {
                var day  = Calendar.getDate();
                var now = new Date();

                // Set output to swedish dates.. this should be changed to a customizable setting
                
                var month_str = (month+1);
                var day_str = day;
                
                if(month_str.toString().length == 1)
					month_str = "0" + month_str;
                
                if(day_str.toString().length == 1)
					day_str = "0" + day_str;
                
                
                var date_str = year + "-" + month_str + "-" + day_str

                // Higlight todays date
                if(month == now.getMonth()&& day == now.getDate() && year == now.getFullYear() )
                {
                  cal += "<td class=\"DatePicker_regular_date DatePicker_todays_date DatePicker_Text " + DatePicker_TodayClassCSS + "\"><a class=\"DatePicker_clickable_date DatePicker_Text\" onmouseover=\"javascript:DatePicker_Showhelp('" + uniqueid + "','" + Day_of_week[week_day] + "," + Month_of_year[Calendar.getMonth()] + " " + day + "');\" onmouseout=\"javascript:DatePicker_Resethelp('" + uniqueid + "', '" + toolTip + "');\" onclick=\"DatePicker_SelectPeriod('" + uniqueid + "','" + date_str + "')\">" + day + "</a></td>\r\n"; 
                }
                else
                {
                  cal += "<td class=\"DatePicker_regular_date DatePicker_Text\" onmouseover=\"javascript:DatePicker_Mouseovercolorchange(this, 0); javascript:DatePicker_Showhelp('" + uniqueid + "','" + Day_of_week[week_day] + "," + Month_of_year[Calendar.getMonth()] + " " + day + "');\" onmouseout=\"javascript:DatePicker_Mouseoutcolorchange(this); javascript:DatePicker_Resethelp('" + uniqueid + "','" + toolTip + "');\" onclick=\"DatePicker_SelectPeriod('" + uniqueid + "','" + date_str + "')\">" + day + "</td>\r\n"; 
                }
            }
        }

        Calendar.setDate(Calendar.getDate()+1);
    }
    
    if(week_day < DAYS_OF_WEEK)
    {
		for(i = 1; i < (DAYS_OF_WEEK - week_day); i++)
		{
			cal += '<td class=\"DatePicker_regular_date DatePicker_Text\"></td>\r\n';
		}
		
		cal += '</tr>\r\n';	
	}
    cal += '</table>\r\n';

    return cal;
}


function disableselect(e)
{
    var omitformtags=["input", "textarea", "select"];
    omitformtags=omitformtags.join("|");
    
	if(e != null)
	{
		if (omitformtags.indexOf(e.target.tagName.toLowerCase())==-1)
			return false
	}
}

function DatePicker_DisableSelect()
{
	document.onmousedown = disableselect
	document.onmouseup = function () { false; };
	document.body.ondrag = function () { return false; };
	document.body.onselectstart = function () { return false; };	
}

function DatePicker_EnableSelect()
{
	document.body.ondrag = function () { return true; };
	document.body.onselectstart = function () { return true; };
	document.onmousedown = function () { return true; };
	document.onmouseup = function () { return true; };
}


function DatePicker_AlterContent(elementid, content)
{
  //if IE 4+
  if (document.all) document.getElementById(elementid).innerHTML = content;
  
  //else if NS 6 (supports new DOM)
  else if (document.getElementById)
  {
    rng = document.createRange();
    el = document.getElementById(elementid);
    rng.setStartBefore(el);
    htmlFrag = rng.createContextualFragment(content);
    
    while (el.hasChildNodes()) el.removeChild(el.lastChild);
		el.appendChild(htmlFrag);
  }
}

function DatePicker_SelectPeriod(uniqueid, txtValue)
{
  document.getElementById(uniqueid + '_DateBox').value = txtValue;
  document.getElementById(uniqueid + '_Panel').style.display='none';
  document.getElementById(uniqueid + '_Iframe').style.display='none';
  DatePicker_EnableSelect();
}

function callback_RenderPeriodMonths(res)
{
    var uniqueid = res.value.Uniqueid;
    var Month_of_year = new Array ();
    Month_of_year = eval('DatePicker_month_of_year_' + uniqueid).split(',');
    
    currdate_control = document.getElementById(uniqueid + '_CurrDate');
	
	currdate_control.value =  res.value.FromDate;
	
	var tmpDate = new Date(currdate_control.value);
	
	// set current month label
	document.getElementById(uniqueid + '_CurrMonth').innerHTML = Month_of_year[(tmpDate.getMonth())];
	
	// set current year label
	var currdate = new Date(res.value.FromDate);
	document.getElementById(uniqueid + '_CurrYear').innerHTML = currdate.getFullYear();
		
	DatePicker_AlterContent(uniqueid + '_Periods', DatePicker_GetCalendarHTML(res));
	DatePicker_AdaptIframe(uniqueid);
}


function DatePicker_RenderPeriodMonths(uniqueid, direction)
{
  
  DatePicker_AlterContent(uniqueid + '_Periods', "<div style='text-align:center'>Loading</div><div class='DatePicker_loading_icon'>&nbsp;</div>");
  
  var test = uniqueid + '_CurrDate';
  currdate_control = document.getElementById(uniqueid + '_CurrDate');
  
  if (direction == 'next') 
  { 
    MightyLittle.DatePickerAjax.GetNextMonthPeriods(currdate_control.value, uniqueid, callback_RenderPeriodMonths); 
  }
  else if (direction == 'prev') 
  { 
    MightyLittle.DatePickerAjax.GetPrevMonthPeriods(currdate_control.value, uniqueid, callback_RenderPeriodMonths); 
  }
  else if (direction == 'month')
  {
    MightyLittle.DatePickerAjax.GetThisMonthPeriod( currdate_control.value, uniqueid, callback_RenderPeriodMonths);
  }
  else if(direction == 'year')
  {
    MightyLittle.DatePickerAjax.GetThisMonthPeriod(currdate_control.value, uniqueid, callback_RenderPeriodMonths); 
  }
  else if(direction == 'prevyear')
  {
    var datevar = new Date(currdate_control.value);
    datevar.setYear( (datevar.getFullYear() - 1) );
    MightyLittle.DatePickerAjax.GetThisMonthPeriod( (datevar.getMonth()+1) +'/1/'+datevar.getFullYear(), uniqueid, callback_RenderPeriodMonths);
  }
  else if(direction == 'nextyear')
  {
    var datevar = new Date(currdate_control.value);
    datevar.setYear( (datevar.getFullYear() + 1) );
    MightyLittle.DatePickerAjax.GetThisMonthPeriod( (datevar.getMonth()+1) +'/1/'+datevar.getFullYear(), uniqueid, callback_RenderPeriodMonths);
  }
  else 
  { 
    MightyLittle.DatePickerAjax.GetThisMonthPeriod(currdate_control.value, uniqueid, callback_RenderPeriodMonths); 
  }
}


/* Returns the number of the week in year, as defined in ISO 8601. */
Date.prototype.getWeekNumber = function() {
	var d = new Date(this.getFullYear(), this.getMonth(), this.getDate(), 0, 0, 0);
	var DoW = d.getDay();
	d.setDate(d.getDate() - (DoW + 6) % 7 + 3); // Nearest Thu
	var ms = d.valueOf(); // GMT
	d.setMonth(0);
	d.setDate(4); // Thu in Week 1
	return Math.round((ms - d.valueOf()) / (7 * 864e5)) + 1;
};

Date.prototype.getIsoDay = function() {
		if(this.getDay() == 0)
			return 6;
		else
			return (this.getDay()-1)	
};
