// these are labels for the days of the week
cal_days_labels = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
cal_months_labels = ['January', 'February', 'March', 'April','May', 'June', 'July', 'August', 'September','October', 'November', 'December'];
cal_days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
cal_current_date = new Date();
var todays_date = cal_current_date.getDate();
var receive_id;
var month;
var year;
var html;
var calendar_complete = 0;
var submit_hour = '';
var global_display_div;

function Calendar(month, year)
{
  this.month = (isNaN(month) || month == null) ? cal_current_date.getMonth() : month;
  this.year  = (isNaN(year) || year == null) ? cal_current_date.getFullYear() : year;
  html = '';
}

function getMonthLength(int_month, int_year)
{
    var days_in_month = new Date(int_year, int_month + 1, 0); // int_month is 0 thru 11
    return(days_in_month.getDate());
}
function getCalendarRowHeight(int_month_length, int_starting_day)
{
    var calendar_row_height = Math.ceil((int_month_length + int_starting_day) / 7);
    return calendar_row_height;
}
function getStartDayOfMonth(int_month, int_year)
{
    var start_date_object = new Date(int_year, int_month, 1);
    var start_day = start_date_object.getDay();
    return start_day;   //0-6
}
function getDaysInMonth(int_requested_month_index, int_requested_year)
{   //---- This function only adjusts for february leapyear months (i.e. 29 days)
    month_length = cal_days_in_month[int_requested_month_index];
    if (int_requested_month_index == 1)
    { // February only!
        if ((int_requested_year % 4 == 0 && int_requested_year % 100 != 0) || int_requested_year % 400 == 0)
        {
            month_length = 29;
        }
    }
    return month_length;
}
function createCalendar(display_div, month, year, input_id, caption)
{
  if(month == 'x'){   month = cal_current_date.getMonth();}
  if(year == 'x' ){   year = cal_current_date.getFullYear();  }
  global_display_div = display_div;
  document.getElementById(display_div).innerHTML='';
  calendar_complete = 0;
    if(month >= 12)
    {
        year++;
        month = 0;
    }
    if(month <= -1)
    {
        year--;
        month = 11;
    }

  this.month = (isNaN(month) || month == null) ? cal_current_date.getMonth() : month;
  this.year  = (isNaN(year) || year == null) ? cal_current_date.getFullYear() : year;
  html = '';

    temp_month = month;
    var prev_month = month - 1;
    var next_month = temp_month++;
        next_month++;


    select_year = year;
    receive_id = input_id;
    var monthName = cal_months_labels[month];
    var html = '<table><tr><td><table class="outter-date-table"><tr><td>';
    html += '<table cellspacing="0" cellpadding="2" class="calendar-table">';
    html += '<tr class="calendar-label"><th valign="top" colspan="7">';
    html += '<center><table><tr><td><a onclick="createCalendar(\''+display_div+'\','+prev_month+','+select_year+',\''+input_id+'\',\''+caption+'\');"><img onmouseout=\'this.src="/assets/style/images/left-arrow-plain-up.png"\' onmouseover=\'this.src="/assets/style/images/left-arrow-plain-over.png"\' src="/assets/style/images/left-arrow-plain-up.png" alt="Select Previous Month"></a>&nbsp;&nbsp;</td><td>'+monthName + "&nbsp;" + this.year + '</td><td>&nbsp;&nbsp;<a href="#" onclick="createCalendar(\''+display_div+'\','+next_month+','+select_year+',\''+input_id+'\',\''+caption+'\');"><img onmouseout=\'this.src="/assets/style/images/right-arrow-plain-up.png"\' onmouseover=\'this.src="/assets/style/images/right-arrow-plain-over.png"\' src="/assets/style/images/right-arrow-plain-up.png" alt="Select Next Month"></a></td></tr></table></center>';
    html += '</th></tr>';
    html += '<tr class="calendar-header">';

    for (var i = 0; i <= 6; i++ )
    {
      if(i == 0 || i == 6)
      {
          html += '<td width="15px" class="calendar-header-weekendday">';
      }
      else
      {
          html += '<td width="15px" class="calendar-header-day">';
      }
      html += '<center>'+cal_days_labels[i]+'</center>';
      html += '</td>';
    }
    html += '</tr><tr>';

    var month_length = getDaysInMonth(this.month, this.year);
    var start_day = getStartDayOfMonth(this.month, this.year);
    var calendar_height = getCalendarRowHeight(month_length, start_day);

  // fill in the days
    var day = 1;
  // this loop is for is weeks (rows)
    for (i = 0; i < calendar_height; i++)
    {
    // this loop is for weekdays (cells)
        for (var j = 0; j <= 6; j++)
        {   // Create weekdays Sun - Sat
            if( j == 0 || j == 6)
            {   // if creating weekend days
                if(day == todays_date)
                {
                    if (day <= month_length && (i > 0 || j >= start_day))
                    {
                        html += '<td class="calendar-weekend-day" id="today" onclick="selectDate('+day+','+this.month+','+this.year+');">';
                        html += '<center><a onclick="selectDate('+day+','+this.month+','+this.year+')";>'+day+'</a></center>';
                        html += '</td>';
                        day++;
                    }
                    else
                    {
                        if(i==0 && j==0)
                        {
                            html += '<td id="first-td"></td>';
                        }
                        else if(day == month_length+1 && calendar_complete == 0)
                        {
                            html += '<td id="last-td"></td>';
                            calendar_complete = 1;
                        }
                        else
                        {
                            html += '<td class="empty-day"></td>';
                        }
                    }
                }
                else
                {

                    if (day <= month_length && (i > 0 || j >= start_day))
                    {
                        html += '<td class="calendar-weekend-day" onclick="selectDate('+day+','+this.month+','+this.year+');">';
                        html += '<center><a onclick="selectDate('+day+','+this.month+','+this.year+')";>'+day+'</a></center>';
                        html += '</td>';
                        day++;
                    }
                    else
                    {
                        if(i==0 && j==0)
                        {
                            html += '<td id="first-td"></td>';
                        }
                        else if(day == month_length+1 && calendar_complete == 0)
                        {
                            html += '<td id="last-td"></td>';
                            calendar_complete = 1;
                        }
                        else
                        {
                            html += '<td class="empty-day"></td>';
                        }
                    }

                }
            }
            else
            {
                if(day == todays_date)
                {
                    if (day <= month_length && (i > 0 || j >= start_day))
                    {
                        html += '<td class="calendar-day" id="today" onclick="selectDate('+day+','+this.month+','+this.year+');">';
                        html += '<center><a onclick="selectDate('+day+','+this.month+','+this.year+')";>'+day+'</a></center>';
                        html += '</td>';
                        day++;
                    }
                    else
                    {
                        if(i==0 && j==0)
                        {
                            html += '<td id="first-td"></td>';
                        }
                        else if(day == month_length+1 && calendar_complete == 0)
                        {
                            html += '<td id="last-td"></td>';
                            calendar_complete = 1;
                        }
                        else
                        {
                            html += '<td class="empty-day"></td>';
                        }
                    }
                }
                else
                {
                    if (day <= month_length && (i > 0 || j >= start_day))
                    {
                        html += '<td class="calendar-day" onclick="selectDate('+day+','+this.month+','+this.year+');">';
                        html += '<center><a onclick="selectDate('+day+','+this.month+','+this.year+')";>'+day+'</a></center>';
                        html += '</td>';
                        day++;
                    }
                    else
                    {
                        if(i==0 && j==0)
                        {
                            html += '<td id="first-td"></td>';
                        }
                        else if(day == month_length+1 && calendar_complete == 0)
                        {
                            html += '<td id="last-td"></td>';
                            calendar_complete = 1;
                        }
                        else
                        {
                            html += '<td class="empty-day"></td>';
                            //day++;
                        }
                    }
                }
            }
        }
        // stop making rows if we've run out of days
        if (day > month_length)
        {
          break;
        }
        else
        {
          html += '</tr><tr>';
        }
    }
    html += '</tr><tr><td class="time-td" colspan="7">';
    html += '<table class="time-table">';
    html += '<tr><td><input size="2" maxlength="2" type="textfield" id="hour">:<input size="2" maxlength="2" type="textfield" id="minute">&nbsp;<select name="am_pm"><option value="am" selected>AM</option><option value="pm">PM</option></select></td></tr>';
    html += '</table>'
    html += '</td></tr></table></td><td valign="top">';
    html += '<table width="100%" cellspacing="0" cellpadding="0"><tr><td class="date-time-td" valign="top">';
    html += '<center><span class="cal-title-span">'+caption+'</span></center>&nbsp;</td><td align="right"><a onclick="closeDiv(\''+display_div+'\');"><img onmouseout=\'this.src="/assets/style/images/close-btn-up.png"\' onmouseover=\'this.src="/assets/style/images/close-btn-over.png"\' src="/assets/style/images/close-btn-up.png" alt="Close"></a></td>';
    html += '</tr><td colspan="2"><br><table class="date-time-table"><tr><td valign="top"><center>Date:<input disabled="true"\\n\
 type="textfield" class="form-textfield" size="10" name="date-input" id="date-input"><br><span id="date-message"></span><br>Time:<input disabled="true" type="textfield" class="form-textfield" size="10" name="time-input" id="time-input"><br><span id="time-message"></span><br><input type="button" name="Submit" value="submit" onclick="sendDateTime();"></center></td></tr></table>';
    html += '</td></tr></table></td></tr></table>';
    document.getElementById(display_div).innerHTML=html;
}
function selectDate(date, month, year)
{
    month++;
    if(month < 10)
    {
        month = "0"+month;
    }
    if(date < 10)
    {
        date = "0"+date;
    }
    //document.getElementById(receive_id).value = month+"/"+date+"-"+year;
    document.getElementById('date-input').value = year+"-"+month+"-"+date;
    document.getElementById('date-message').innerHTML = "";
    if(document.getElementById('time-input').value == '')
    {
        document.getElementById('hour').focus();
    }
}
function selectTime()
{
    select_hour = document.getElementById('hour').value;
    select_minute = document.getElementById('minute').value;
    select_am_pm = document.getElementsByName('am_pm')[0].value;
    submit_time = '';
    if(select_hour != '' && select_minute != '')
    {
        if(select_hour.length < 2 && select_hour != '')
        {
            select_hour = "0" + select_hour;
            submit_hour = select_hour;
        }
        else
        {
            submit_hour = select_hour;
        }
        if(select_am_pm == "pm")
        {
            submit_hour = Number(select_hour) + 12;
        }
        if(Number(select_hour) == 12 && select_am_pm == "am")
        {
            submit_hour = "00";
        }
        if(select_minute >= 60)
        {
            select_hour = select_hour + 1;
            select_minute = select_minute - 60;
            submit_hour = select_hour;
        }
        if(select_minute.length < 2 && select_minute != '')
        {
            select_minute = "0" + select_minute;
        }
        submit_time = submit_hour + ":"+select_minute;
        document.getElementById('time-input').value = select_hour+":"+select_minute+" "+select_am_pm;
    }
}
function sendDateTime()
{
    time_complete = false;
    date_complete = false;
selectTime();
    if(document.getElementById('time-input').value == '' || document.getElementById('time-input').value == null)
    {
        document.getElementById('time-message').innerHTML = "<font color=#cc0000><blink>Please select time!</blink></font>";
        time_complete = false;
    }
    else
    {
        time_complete = true;
    }
    if(document.getElementById('date-input').value == '' || document.getElementById('date-input').value == null)
    {
        document.getElementById('date-message').innerHTML = "<font color=#cc0000><blink>Please select date!</blink></font>";
        date_complete = false
    }
    else
    {
        date_complete = true;
    }
    if(date_complete == true && time_complete == true)
    {        
        document.getElementById(receive_id).value = document.getElementById('date-input').value+" "+submit_time;
        document.getElementById(global_display_div).innerHTML='';
    }
}
//function addType(source, destination)
//{
//    var tag_select = document.getElementById("tags_list");
//    var source_field = document.getElementById(source);
//    if(source_field.value != -1)
//    {
//        var destination_field = document.getElementById(destination);
//        var source_text = source_field.value;
//        var new_element = document.createElement("option");
//
//        new_element.value = source_text +" ["+source_text.toLowerCase()+"]";
//        new_element.text = source_text;
//        new_element.setAttribute("selected", "true");
//        if(destination != "tags_list")
//        {
//            var second_element = document.createElement('option');
//            second_element.value = source_text.toLowerCase();
//            second_element.text = source_text;
//            second_element.setAttribute("selected", "true");
//            tag_select.appendChild(second_element);
//        }
//        destination_field.appendChild(new_element);
//        source_field.value = '';
//    }
//}
//function removeOption(destination)
//{
//    var destination_select = document.getElementById(destination);
//    var tag_select = document.getElementById("tags_list");
//
//    for(var i=0; i<destination_select.length; i++)
//    {
//        if(destination_select.options[i].selected)
//        {
//            if(destination != "tags_list")
//            {
//                for(var j=0; j<tag_select.length; j++)
//                {
//                    if(tag_select.options[j].value == destination_select.options[i].value)
//                    {
//                        tag_select.removeChild(tag_select.options[j]);
//                    }
//                }
//            }
//            destination_select.removeChild(destination_select.options[i]);
//        }
//    }
//}
//function addOption(source, destination)
//{
//    var selectct = source.length;
//    var destination_select = document.getElementById(destination);
//    var tag_select = document.getElementById("tags_list");
//    var source_select = document.getElementById(source);
//    var text;
//    var value;
//    var new_element;
//    var second_element;
//
//    if(source_select.value != -1)
//    {
//        for(var i=0; i<selectct; i++)
//        {
//            if(source_select.options[i].selected)
//            {
//                text = source_select.options[i].text;
//                value = source_select.options[i].value;
//                new_element = document.createElement('option');
//                second_element = document.createElement('option');
//                new_element.value = value;
//                new_element.text = text;
//                new_element.setAttribute("selected", "true");
//
//                if(destination != "tags_list")
//                {
//                    second_element.value = value;
//                    second_element.text = text;
//                    second_element.setAttribute("selected", "true");
//                    tag_select.appendChild(second_element);
//                }
//                destination_select.appendChild(new_element);
//            }
//        }
//    }
//}
function getWeek(dowOffset)
{
    /*getWeek() was developed by Nick Baicoianu at MeanFreePath: http://www.meanfreepath.com */

    dowOffset = typeof(dowOffset) == 'int' ? dowOffset : 0; //default dowOffset to zero
    var newYear = new Date(this.getFullYear(),0,1);
    var day = newYear.getDay() - dowOffset; //the day of week the year begins on
    day = (day >= 0 ? day : day + 7);
    var daynum = Math.floor((this.getTime() - newYear.getTime() -(this.getTimezoneOffset()-newYear.getTimezoneOffset())*60000)/86400000) + 1;
    var weeknum;
    //if the year starts before the middle of a week
    if(day < 4)
    {
        weeknum = Math.floor((daynum+day-1)/7) + 1;
        if(weeknum > 52)
        {
            nYear = new Date(this.getFullYear() + 1,0,1);
            nday = nYear.getDay() - dowOffset;
            nday = nday >= 0 ? nday : nday + 7;
            /*if the next year starts before the middle of
            the week, it is week #1 of that year*/
            weeknum = nday < 4 ? 1 : 53;
        }
    }
    else
    {
        weeknum = Math.floor((daynum+day-1)/7);
    }
    return weeknum;
};
