﻿
function geoDatePicker()  {  };

geoDatePicker.prototype = {

    dayArrayShort: new Array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'),
    dayArrayMed: new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'),
    dayArrayLong: new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'),
    monthArrayShort: new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'),
    monthArrayMed: new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'),
    monthArrayLong: new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'),

    dateSeparator: "/",
    dateFormat: "mdy",

    displayDatePicker: function (dateFieldId, parentDivId, dtFormat, dtSep) {

        if (this.targetDateField != null)
            return;

        this.targetDateField = null;

        // if a date separator character was given, update the dateSeparator variable
        if (dtSep)
            this.dateSeparator = dtSep;

        // if a date format was given, update the dateFormat variable
        if (dtFormat)
            this.dateFormat = dtFormat;

        this.targetDateField = document.getElementById(dateFieldId);

        this.picker = document.createElement("div");
        this.picker.id = "datepicker";
        this.picker.className = "dpDiv";


        //either show as popup or render on page.  
        this.isPopup = true;
        if (parentDivId) {
            this.isPopup = false;
            this.parentDiv = document.getElementById(parentDivId);
            this.parentDiv.appendChild(this.picker);
        }
        else {
            //this.picker.style.visibility = "hidden";
            document.body.appendChild(this.picker);

            //create shim for dropdowns and objects
            this.shim = document.createElement("iFrame");
            this.shim.setAttribute("src", "javascript:false;");
            this.shim.setAttribute("scrolling", "no");
            this.shim.setAttribute("frameborder", "0");
            document.body.appendChild(this.shim);

            //locate under target field.
            var x = this.targetDateField.offsetLeft;
            var y = this.targetDateField.offsetTop + this.targetDateField.offsetHeight;

            // deal with elements inside tables and such
            var parent = displayBelowThisObject;
            while (parent.offsetParent) {
                parent = parent.offsetParent;
                x += parent.offsetLeft;
                y += parent.offsetTop;
            }

            // move the datepicker div to the proper x,y coordinate and toggle the visiblity
            this.picker.style.position = "absolute";
            this.picker.style.left = x + "px";
            this.picker.style.top = y + "px";
            //            this.picker.style.visibility = "visib(this.picker.style.visibility == "visible" ? "hidden" : "visible");
            //            this.picker.style.display = (this.picker.style.display == "block" ? "none" : "block");
            this.picker.style.zIndex = 10000;
        }

        var dt = this.getFieldDate(this.targetDateField.value);
        this.selectedDate = dt;
        this.refreshDatePicker(dt.getFullYear(), dt.getMonth(), dt.getDate());

    },

    /**
    This is the function that actually draws the datepicker calendar.
    */
    refreshDatePicker: function (year, month, day) {
        // if no arguments are passed, use today's date; otherwise, month and year
        // are required (if a day is passed, it will be highlighted later)
        var thisDay = new Date();

        if ((month >= 0) && (year > 0)) {
            thisDay = new Date(year, month, 1);
        } else {
            day = thisDay.getDate();
            month = thisDay.getMonth();
            year = thisDay.getFullYear();
            thisDay.setDate(1);
        }

        if (month == this.selectedDate.getMonth() && year == this.selectedDate.getFullYear())
            day = this.selectedDate.getDate();

        // the calendar will be drawn as a table
        // you can customize the table elements with a global CSS style sheet,
        // or by hardcoding style and formatting elements below
        var crlf = "\r\n";
        var TABLE = "<table cols=7 class='dpTable'>" + crlf;
        var xTABLE = "</table>" + crlf;
        var TR = "<tr class='dpTR'>";
        var TR_title = "<tr class='dpTitleTR'>";
        var TR_days = "<tr class='dpDayTR'>";
        var TR_todaybutton = "<tr class='dpTodayButtonTR'>";
        var xTR = "</tr>" + crlf;
        var TD_title = "<td colspan=5 class='dpTitleTD'>";
        var TD_buttons = "<td class='dpButtonTD'>";
        var TD_todaybutton = "<td colspan=7 class='dpTodayButtonTD'>";
        var TD_days = "<td class='dpDayTD'>";
        var TD = "<td class='dpTD' onMouseOut='this.className=\"dpTD\";' onMouseOver=' this.className=\"dpTDHover\";' ";    // leave this tag open, because we'll be adding an onClick event
        var TD_selected = "<td class='dpDayHighlightTD' onMouseOut='this.className=\"dpDayHighlightTD\";' onMouseOver='this.className=\"dpTDHover\";' ";    // leave this tag open, because we'll be adding an onClick event
        var TD_enabled = "<td class='dpDayEnabledTD' onMouseOut='this.className=\"dpDayEnabledTD\";' onMouseOver='this.className=\"dpTDHover\";' ";    // leave this tag open, because we'll be adding an onClick event
        var TD_disabled = "<td class='dpDayDisabledTD' onMouseOut='this.className=\"dpDayDisabledTD\";' onMouseOver='this.className=\"dpTDHover\";' ";    // leave this tag open, because we'll be adding an onClick event
        var xTD = "</td>" + crlf;
        var DIV_title = "<div class='dpTitleText'>";
        //var DIV_selected = "<div class='dpDayHighlight'>";
        //var DIV_enabled = "<div class='dpDayEnabled'>";
        //var DIV_disabled = "<div class='dpDayDisabled'>";
        var xDIV = "</div>";

        // start generating the code for the calendar table
        var html = TABLE;

        // this is the title bar, which displays the month and the buttons to
        // go back to a previous month or forward to the next month
        html += TR_title;
        html += TD_buttons + this.getButtonCode(thisDay, -1, "&lt; prev") + xTD;
        html += TD_title + DIV_title + this.monthArrayLong[thisDay.getMonth()] + " " + thisDay.getFullYear() + xDIV + xTD;
        html += TD_buttons + this.getButtonCode(thisDay, 1, "next &gt;") + xTD;
        html += xTR;

        // this is the row that indicates which day of the week we're on
        html += TR_days;
        for (i = 0; i < this.dayArrayShort.length; i++)
            html += TD_days + this.dayArrayShort[i] + xTD;
        html += xTR;

        // now we'll start populating the table with days of the month
        html += TR;

        // first, the leading blanks
        for (i = 0; i < thisDay.getDay(); i++)
            html += TD + "&nbsp;" + xTD;

        // now, the days of the month
        do {
            dayNum = thisDay.getDate();

            var enabled = this.isEnabled(year, month, dayNum);

            TD_onclick = " onclick=\"datepicker.updateDateField('" + this.getDateString(thisDay) + "');\">";
            if (!enabled)
                TD_onclick = ">";

            if (dayNum == day)
                html += TD_selected + TD_onclick + dayNum + xTD;
            else if (!enabled)
                html += TD_disabled + TD_onclick + dayNum + xTD;
            else
                html += TD_enabled + TD_onclick + dayNum + xTD;

            // if this is a Saturday, start a new row
            if (thisDay.getDay() == 6)
                html += xTR + TR;

            // increment the day
            thisDay.setDate(thisDay.getDate() + 1);
        } while (thisDay.getDate() > 1)

        // fill in any trailing blanks
        if (thisDay.getDay() > 0) {
            for (i = 6; i > thisDay.getDay(); i--)
                html += TD + "&nbsp;" + xTD;
        }
        html += xTR;

        // add a button to allow the user to easily return to today, or close the calendar
        var today = new Date();
        var todayString = "Today is " + this.dayArrayMed[today.getDay()] + ", " + this.monthArrayMed[today.getMonth()] + " " + today.getDate();
        html += TR_todaybutton + TD_todaybutton;
        html += "<button class='dpTodayButton' onClick='datepicker.refreshDatePicker();'>this month</button> ";
        if (this.isPopup)
            html += "<button class='dpTodayButton' onClick='datepicker.updateDateField();'>close</button>";
        html += xTD + xTR;

        // and finally, close the table
        html += xTABLE;

        this.picker.innerHTML = html;
        // add an "iFrame shim" to allow the datepicker to display above selection lists
        this.resizeShim();
    },


    /**
    Convenience function for writing the code for the buttons that bring us back or forward
    a month.
    */
    getButtonCode: function (dateVal, adjust, label) {
        var newMonth = (dateVal.getMonth() + adjust) % 12;
        var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
        if (newMonth < 0) {
            newMonth += 12;
            newYear += -1;
        }

        return "<button class='dpButton' onClick='datepicker.refreshDatePicker(" + newYear + ", " + newMonth + ");'>" + label + "</button>";
    },


    /**
    Convert a JavaScript Date object to a string, based on the dateFormat and dateSeparator
    variables at the beginning of this script library.
    */
    getDateString: function (dateVal) {
        var dayString = "00" + dateVal.getDate();
        var monthString = "00" + (dateVal.getMonth() + 1);
        dayString = dayString.substring(dayString.length - 2);
        monthString = monthString.substring(monthString.length - 2);

        switch (this.dateFormat) {
            case "dmy":
                return dayString + this.dateSeparator + monthString + this.dateSeparator + dateVal.getFullYear();
            case "ymd":
                return dateVal.getFullYear() + this.dateSeparator + monthString + this.dateSeparator + dayString;
            case "mdy":
            default:
                return monthString + this.dateSeparator + dayString + this.dateSeparator + dateVal.getFullYear();
        }
    },


    /**
    Convert a string to a JavaScript Date object.
    */
    getFieldDate: function (dateString) {
        var dateVal;
        var dArray;
        var d, m, y;

        try {
            dArray = this.splitDateString(dateString);
            if (dArray) {
                switch (this.dateFormat) {
                    case "dmy":
                        d = parseInt(dArray[0], 10);
                        m = parseInt(dArray[1], 10) - 1;
                        y = parseInt(dArray[2], 10);
                        break;
                    case "ymd":
                        d = parseInt(dArray[2], 10);
                        m = parseInt(dArray[1], 10) - 1;
                        y = parseInt(dArray[0], 10);
                        break;
                    case "mdy":
                    default:
                        d = parseInt(dArray[1], 10);
                        m = parseInt(dArray[0], 10) - 1;
                        y = parseInt(dArray[2], 10);
                        break;
                }
                dateVal = new Date(y, m, d);
            } else if (dateString) {
                dateVal = new Date(dateString);
            } else {
                dateVal = new Date();
            }
        } catch (e) {
            dateVal = new Date();
        }

        return dateVal;
    },
    isEnabled: function (year, month, day) {
        if (!this.enabledDays)
            return true;

        var mnth = month + 1;
        if (mnth < 10)
            mnth = "0" + mnth;
        dayNum = day;
        if (day < 10)
            dayNum = "0" + day;
        var selected = (mnth + "/" + dayNum + "/" + year)

        for (var i = 0; i < this.enabledDays.length; i++) {
            if (this.enabledDays[i] == selected) {
                return true;
            }
        }
        return false;
    },


    /**
    Try to split a date string into an array of elements, using common date separators.
    If the date is split, an array is returned; otherwise, we just return false.
    */
    splitDateString: function (dateString) {
        var dArray;
        if (dateString.indexOf("/") >= 0)
            dArray = dateString.split("/");
        else if (dateString.indexOf(".") >= 0)
            dArray = dateString.split(".");
        else if (dateString.indexOf("-") >= 0)
            dArray = dateString.split("-");
        else if (dateString.indexOf("\\") >= 0)
            dArray = dateString.split("\\");
        else
            dArray = false;

        return dArray;
    },
    updateDateField: function (dateString) {

        if (dateString) {
            this.targetDateField.value = dateString;
            this.selectedDate = this.getFieldDate(dateString);
        }
        if (this.isPopup) {
            this.picker.style.visibility = "hidden";
            this.picker.style.display = "none";
            this.resizeShim();
            this.targetDateField.focus();
        }
        else {
            var dt = this.selectedDate;
            this.refreshDatePicker(dt.getFullYear(), dt.getMonth(), dt.getDate());

        }

        //run onclose event.
        if ((dateString) && (typeof (this.onSelect) == "function"))
            this.onSelect(this.selectedDate);
    },
    resizeShim: function () {
        if (this.isPopup) {
            this.shim.style.position = "absolute";
            this.shim.style.width = this.picker.offsetWidth;
            this.shim.style.height = this.picker.offsetHeight;
            this.shim.style.top = this.picker.style.top;
            this.shim.style.left = this.picker.style.left;
            this.shim.style.zIndex = this.picker.style.zIndex - 1;
            this.shim.style.visibility = this.picker.style.visibility;
            this.shim.style.display = this.picker.style.display;
        }
    },
    loadMediaList: function (targetDiv, mediatype, listsize, selectedDate) {

        this.mediaListDiv = targetDiv;
        lara.indicateOn();
        var data = new dataObject();
        data.add("SelectedDate", this.getDateString(selectedDate));

        data.add("MediaType", mediatype);
        data.add("ListSize", listsize);
        lara.request("/_ui/media:LoadMediaList", data, function (result) { datepicker.processLoadMediaList(result); });

    },
    processLoadMediaList: function (result) {
        if (result.success) {
            $l(this.mediaListDiv).innerHTML = result.html;
        }
        else {
            alert(result.error);
        }
        lara.indicateOff();
    }
};

//there can be only one
var datepicker;
if (!datepicker)
    datepicker = new geoDatePicker();



    


