var CurrentCalendar;
var CalendarHasPrefs;

function CreatePopupCalendar(iconID, textboxID, onSelection, otherTextBox, restriction) 
{
    var span = document.createElement('span');
    span.setAttribute('id', textboxID + "_calHolder");
    span.setAttribute('style', "position: absolute; z-index: 50;");

    var icon = $(iconID);
    icon.parentNode.insertBefore(span, icon);
    icon.className = "OpenCalendarButton";
    icon.onmouseup = function() { if (CurrentCalendar == null || CurrentCalendar.TextBoxID != textboxID || !$("calendar_Layer")) ShowCalendar(textboxID, this, "d-MMM-yyyy", onSelection, otherTextBox, restriction); }

    if ($(textboxID) && restriction) {
        if (document.attachEvent) {
            $(textboxID).attachEvent("onblur", function() { TestDateMutualDependency(textboxID, otherTextBox, restriction); });
        }
        else {
            $(textboxID).addEventListener("blur", function(e) { TestDateMutualDependency(textboxID, otherTextBox, restriction); }, false);
        }
    }
}

function TestDateMutualDependency(textboxID, otherTextBox, restriction)
{
     var txt1 = $(textboxID);
     var txt2 = $(otherTextBox);
     
     if (!txt1
        || !txt2
        || !restriction
        //|| txt1.value.length==0
        //|| txt2.value.length == 0
        )
        return;
    
    var date = parseDate(txt1.value, "d-MMM-yyyy");
    var otherDate = parseDate(txt2.value, "d-MMM-yyyy");
  
    switch(restriction)
    {
        case "Greater_Than_Other":
            if (!txt2.value || date < otherDate)
                txt2.value = txt1.value;
            break;
        case "Less_Than_Other":
            if (!txt2.value || date > otherDate)
                 txt2.value = txt1.value;
            break;
        case "None":
            if (!txt2.value && txt1.value)
                txt2.value = txt1.value;
            break;
    }

}
var ShowCalendarRequest = new Object();
function ShowCalendar(textboxID, iconElement, format, onSelection, otherTextBox, restriction)
{

    CloseCalendar();
    
    ShowCalendarRequest = new Object();
    ShowCalendarRequest.textboxID = textboxID;
    ShowCalendarRequest.iconElement = iconElement;
    ShowCalendarRequest.format = format;
    ShowCalendarRequest.onSelection = onSelection;
    ShowCalendarRequest.otherTextBox = otherTextBox
    ShowCalendarRequest.restriction = restriction;

    ShowCalendarContinue();
}

function ShowCalendarContinue()
{
    if (!ShowCalendarRequest)
        return;
        
        
    CurrentCalendar = new Calendar(ShowCalendarRequest.textboxID, 
        ShowCalendarRequest.iconElement, 
        ShowCalendarRequest.format, 
        ShowCalendarRequest.onSelection, 
        ShowCalendarRequest.otherTextBox, 
        ShowCalendarRequest.restriction);
    
    ShowCalendarRequest = null;
    
    CurrentCalendar.Render();
    
}

function CloseCalendar()
{
    if (CurrentCalendar)
    {
        // clear timeout
        CalendarMouseOver();
        
        CurrentCalendar.Close();
    }
    CurrentCalendar = null;
}

function TestCalendarMouseOut()
{
    var calDiv = $('calendar_Layer');
    if (!calDiv)
        return;
    
    CurrentCalendar.timeout = setTimeout("CloseCalendar()", 1000);
}

function DelayedCalendarMouseOut()
{
    CloseCalendar();
}

function CalendarMouseOver()
{
    if (CurrentCalendar.timeout)
        clearTimeout(CurrentCalendar.timeout);
    CurrentCalendar.timeout = null;
}


Calendar = function(textboxID, iconElement, format, onSelection, otherTextBox, restriction)
{
    this.HasTime = false;
    this.Format = format;
    this.TextBoxID = textboxID;
    this.TextBox = $(textboxID);
    this.IconElement = iconElement;
    this.Value = new Date();
    this.Value = parseDate(this.TextBox.value, this.Format);
    this.timeout;
    this.OnSelection = onSelection;
    this.OtherTextBoxID = otherTextBox;
    this.Restriction = restriction;
}

Calendar.prototype.Close = function()
{
    $(this.TextBoxID+"_calHolder").innerHTML = "";
     
}

Calendar.prototype.Render = function()
{
        
    var s = "";
    s += "<div class=\"PopupCalendarHolder\" onmouseover=\"CalendarMouseOver()\" onmouseout=\"TestCalendarMouseOut();\" style=\"position: absolute;\" id=\"calendar_Layer\">";
    s += "<span id=\"calendar_main\" onmouseover=\"CalendarMouseOver()\"></span>";
     s += "</div>";
     
    if (ie)
        s += "<iframe id=\"calendar_fix\" scrolling='no' frameborder='0' style='position:absolute; margin-top: 24px; display:none; filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0);'></iframe>";
       
       
    $(this.TextBoxID+"_calHolder").innerHTML = s;
    
    //$("calendar_Layer").style.marginTop = "24px";
    
    //$("calendar_Layer").style.top = (PosY(this.IconElement)+GetHeight(this.IconElement))+"px";
    //$("calendar_Layer").style.left = PosX(this.IconElement)+"px";
    if (!indexes)
        indexes = 100;
        
    $("calendar_Layer").style.zIndex = 100 + (indexes++);
    
    this.RenderGuts();

}

function FixCalendarIE()
{
    if (ie)
    {
        var comboFix = $("calendar_fix");
        var layer = $("calendar_Layer");

        comboFix.style.width = layer.offsetWidth;
        comboFix.style.height = layer.offsetHeight;
       // comboFix.style.top = layer.style.top+'px';
        //comboFix.style.left = layer.style.left+'px';
        comboFix.style.zIndex = layer.style.zIndex - 1;
        comboFix.style.position = "absolute";
        comboFix.style.display = "block";
    }
}

Calendar.prototype.RenderGuts = function()
{
    $("calendar_main").innerHTML = DrawCalendar(this);
    FixCalendarIE();
}

function DatesMatch(a, b)
{
    return a.getDate()==b.getDate() && a.getMonth()==b.getMonth() && a.getYear()==b.getYear();
    
}

function SetDate(value) {
    
    CurrentCalendar.Value = new Date(value);
    CurrentCalendar.RenderGuts();    
}

function SetCalendarTime()
{
    var hours = parseInt($("calendar_hour").value,10);
    var mins = parseInt($("calendar_minute").value,10);
    var pm = $("calendar_ampm").selectedIndex==1;
    
    
    if (!isNaN(hours) && !isNaN(mins))
    {
        if (hours>12)
        {
            hours = hours%12;
            pm = true;
        }
        if (hours<1)
            hours = 1;
        
        CurrentCalendar.Value.setMinutes( parseInt(mins) );
        if (hours<13)
        {
            CurrentCalendar.Value.setHours(pm?hours+12:hours);
        }
    }
}

function ApplyCalendar(value)
{
    CurrentCalendar.Value = new Date(value);
    CurrentCalendar.TextBox.value = FormatDate(CurrentCalendar.Value, CurrentCalendar.Format); 
   
    if (CurrentCalendar.OtherTextBoxID && CurrentCalendar.Restriction)
        TestDateMutualDependency(CurrentCalendar.TextBoxID, CurrentCalendar.OtherTextBoxID, CurrentCalendar.Restriction);
   
    if (CurrentCalendar.OnSelection)
        eval(CurrentCalendar.OnSelection);
        
    CloseCalendar();
}

function DrawCalendar(cal)
{
    var _selectedDate = cal.Value;
    var s = new StringBuilder();
    var showWeeks = true;

    //s.Append("<table cellpadding=0 cellspacing=0 border=0><tr><td>");
    
    s.Append("<div class=\"DatePickerHead\" onmouseover=\"CalendarMouseOver()\">");
    
    s.Append("<div class=\"PopupCalendarHeadYear\">");
    s.Append("<a class=\"DatePickerLeftArrow\" href=\"javascript:;\" onmouseup=\"SetDate('" + AddYears(_selectedDate, -1) + "');\">&nbsp;</a>");
    s.Append("<a class=\"DatePickerRightArrow\" href=\"javascript:;\" onmouseup=\"SetDate('" + AddYears(_selectedDate, +1) + "');\">&nbsp;</a>");
    s.Append(_selectedDate.getFullYear());
    s.Append("</div>");
    
    s.Append("<div class=\"PopupCalendarHeadMonth\">");
    s.Append("<a class=\"DatePickerLeftArrow\" href=\"javascript:;\" onmouseup=\"SetDate('" + AddMonths(_selectedDate, -1) + "');\">&nbsp;</a>");
    s.Append("<a class=\"DatePickerRightArrow\" href=\"javascript:;\" onmouseup=\"SetDate('" + AddMonths(_selectedDate, +1) + "');\">&nbsp;</a>");
    s.Append(UserInfo.MonthNames[_selectedDate.getMonth()]);
    s.Append("</div>");

    s.Append("</div>");


    if (cal.HasTime)
    {
        s.Append("<table cellpadding=\"0\" cellspacing=\"4\" border=\"0\" align=\"center\"><tr><td>");
        var h = _selectedDate.getHours();
        var pm = h>11;
        if (pm && h>12)
         h = h-12;
        s.Append("<input type=\"text\" id=\"calendar_hour\" style=\"width:30px;\" onkeyup=\"SetCalendarTime();\" value=\""+h+"\"/>")
        s.Append("</td><td>");
        s.Append(":");
        s.Append("</td><td>");
        s.Append("<input type=\"text\" id=\"calendar_minute\" style=\"width:30px;\" onkeyup=\"SetCalendarTime();\" value=\"" + padZero(_selectedDate.getMinutes()) + "\"/>");
        s.Append("</td><td>");
        s.Append("<select id=\"calendar_ampm\" onchange=\"SetCalendarTime();\">");
        s.Append("<option value=\"am\" "+(pm?"":"selected")+">AM</option>");
        s.Append("<option value=\"pm\" "+(pm?"selected":"")+">PM</option>");
        s.Append("</select></td>");
        s.Append("</tr>");
        s.Append("</table>");
    }
   

    s.Append("<table onmouseover=\"CalendarMouseOver()\" class=\"DatePickerMonth\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">");

    s.Append("<tr>");

    for (var i = 1; i < 8; i++)
    {
        s.Append("<th class=\"DatePickerDayHeader\" style='padding: 2px !important;'>");
        s.Append(UserInfo.DayNames[i % 7]);
        s.Append("</th>");
    }
    // s.Append("</tr>");

    var month = new Date(_selectedDate.getFullYear(), _selectedDate.getMonth(), 1);
    var year = new Date(_selectedDate.getFullYear(), 0, 1);
    
    month.setMinutes(0);
    month.setHours(0);
    month.setSeconds(0);
    year.setMinutes(0);
    year.setHours(0);
    year.setSeconds(0);
    
    var startWeek = month.getWeekOfYear();

    if (month.getMonth() == 0)
       startWeek = 1;
   // window.status = month + ' = ' + _selectedDate.getMonth() + ' ' + month.getDay() + ' week ' + startWeek;
    var c = DayOfWeek.Monday - month.getDay();
     
    if (c == 1)
        c -= 7;
        
    var start = (startWeek-1) * 7;
    var end = start; 
    while (AddDays(year, end+c ) < AddMonths(month, 1))
    {
        end += 7;
    }

    for (var i = start; i < end; i++)
    {
        var date = AddDays(month, c);
        
        //date.setMinutes(_selectedDate.getMinutes());
        //date.setHours(_selectedDate.getHours());
        
        if (i % 7 == 0)
        {

            s.Append("</tr>");
            s.Append("<tr>");
        }

        var isSelected = DatesMatch(date, _selectedDate);
        
        s.Append("<td class=\""+(isSelected?"DatePickerSelectedDay":"DatePickerDay")+"\" ");
        s.Append("onmouseup=\"ApplyCalendar('" + date + "')\" style='padding: 2px !important;'>");
        s.Append(date.getDate());
        s.Append("</td>");

        c++;

    }
    s.Append("</tr>");
    s.Append("</table>");

    return s.ToString();
}

