﻿function getDateMonth(stringToMatch) {

    for (i = 0; i < 12; i++) {
        if (stringToMatch == months[i])
            return i;
    }

    return 0;
}
function positionInfo(object) {

    var p_elm = object;

    this.getElementLeft = getElementLeft;
    function getElementLeft() {
        var x = 0;
        var elm;
        if (typeof (p_elm) == "object") {
            elm = p_elm;
        } else {
            elm = document.getElementById(p_elm);
        }

        while (elm != null) {
            if (elm.style.position == "fixed" || elm.style.position == "absolute") {

                elm = null;
            }
            else {
                x += elm.offsetLeft;
                elm = elm.offsetParent;
            }
        }
        return parseInt(x);
    }

    this.getElementWidth = getElementWidth;
    function getElementWidth() {
        var elm;
        if (typeof (p_elm) == "object") {
            elm = p_elm;
        } else {
            elm = document.getElementById(p_elm);
        }
        return parseInt(elm.offsetWidth);
    }

    this.getElementRight = getElementRight;
    function getElementRight() {
        return getElementLeft(p_elm) + getElementWidth(p_elm);
    }

    this.getElementTop = getElementTop;
    function getElementTop() {
        var y = 0;
        var elm;
        if (typeof (p_elm) == "object") {
            elm = p_elm;
        } else {
            elm = document.getElementById(p_elm);
        }
        while (elm != null) {
            if (elm.style.position == "fixed" || elm.style.position == "absolute") {
                elm = null;
            }
            else {
                y += elm.offsetTop;
                elm = elm.offsetParent;
            }
        }
        return parseInt(y);
    }

    this.getElementHeight = getElementHeight;
    function getElementHeight() {
        var elm;
        if (typeof (p_elm) == "object") {
            elm = p_elm;
        } else {
            elm = document.getElementById(p_elm);
        }
        return parseInt(elm.offsetHeight);
    }

    this.getElementBottom = getElementBottom;
    function getElementBottom() {
        return getElementTop(p_elm) + getElementHeight(p_elm);
    }
}

function CC() {
    var calendarId = 'CC';
    var currentYear = 0;
    var currentMonth = 0;
    var currentDay = 0;

    var selectedYear = 0;
    var selectedMonth = 0;
    var selectedDay = 0;

    var dateField = null;

    var pudCtrl = null;
    var dodCtrl = null;
    var outCtrl = null;
    var pudHrCtrl = null;
    var pudMnCtrl = null;
    var dodHrCtrl = null;
    var dodMnCtrl = null;

    function getProperty(p_property) {
        var p_elm = calendarId;
        var elm = null;

        if (typeof (p_elm) == "object") {
            elm = p_elm;
        } else {
            elm = document.getElementById(p_elm);
        }
        if (elm != null) {
            if (elm.style) {
                elm = elm.style;
                if (elm[p_property]) {
                    return elm[p_property];
                } else {
                    return null;
                }
            } else {
                return null;
            }
        }
    }

    function setElementProperty(p_property, p_value, p_elmId) {
        var p_elm = p_elmId;
        var elm = null;

        if (typeof (p_elm) == "object") {
            elm = p_elm;
        } else {
            elm = document.getElementById(p_elm);
        }
        if ((elm != null) && (elm.style != null)) {
            elm = elm.style;
            elm[p_property] = p_value;
        }
    }

    function setProperty(p_property, p_value) {
        setElementProperty(p_property, p_value, calendarId);
    }

    function showTimeDropDowns() {
        dodHrCtrl.style.visibility = "visible";
        dodMnCtrl.style.visibility = "visible";
    }

    function hideTimeDropDowns() {
        dodHrCtrl.style.visibility = "hidden";
        dodMnCtrl.style.visibility = "hidden";
    }

    function getDaysInMonth(year, month) {
        return [31, ((!(year % 4) && ((year % 100) || !(year % 400))) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
    }

    function getDayOfWeek(year, month, day) {
        var date = new Date(year, month - 1, day)
        return date.getDay();
    }

    this.clearDate = clearDate;
    function clearDate() {
        dateField.value = '';
        hide();
    }

    this.setDate = setDate;
    function setDate(year, month, day) {
        if (dateField) {
            if (month < 10) { month = "0" + month; }

            //get date seperator
            var seperator = ' '; //dateField.value.charAt(2);



            var dateString = day + seperator + months[month - 1] + seperator + year
            dateField.value = dateString;
            hide();
            showDuration(pudCtrl, dodCtrl, outCtrl, pudHrCtrl, pudMnCtrl, dodHrCtrl, dodMnCtrl);
        }
        return;
    }

    function padDayPart(dayPart) {
        if (dayPart.split("/")[0].length == 1) {
            return 0 + dayPart;
        }
        return dayPart;
    }

    this.showDuration = showDuration;
    function showDuration(pudCtrl, dodCtrl, outCtrl, pudHrCtrl, pudMnCtrl, dodHrCtrl, dodMnCtrl) {
        if (pudCtrl != null && dodCtrl != null && outCtrl != null) {

            var pudString = new String(pudCtrl.value);
            var dodString = new String(dodCtrl.value);


            // in memory replace anything which is not a digit with a forward slash
            // to signify a date seperator

            var pattern = /\D/g;
            var pudMonthToMatch = pudString.match(pattern).toString().replace(/\,/g, "").replace(/^\s*|\s*$/g, "");
            var pudMonth = getDateMonth(pudMonthToMatch);
            pudString = pudString.replace(" " + pudMonthToMatch + " ", "/");

            var dodMonthToMatch = dodString.match(pattern).toString().replace(/\,/g, "").replace(/^\s*|\s*$/g, "");
            var dodMonth = getDateMonth(dodMonthToMatch);
            dodString = dodString.replace(" " + dodMonthToMatch + " ", "/");

            pudString = padDayPart(pudString);

            dodString = padDayPart(dodString);


            if (pudString.length == 7 && dodString.length == 7) {
                var pudParts = pudString.split("/");
                var pudDay = parseInt(pudParts[0], 10);

                var pudYear = parseInt(pudParts[1], 10);
                var pud = new Date();
                pud.setFullYear(pudYear, pudMonth, pudDay);
                pud.setHours(parseInt(pudHrCtrl.value, 10), parseInt(pudMnCtrl.value, 10), 0, 0);

                var dodParts = dodString.split("/");
                var dodDay = parseInt(dodParts[0], 10);
                var dodYear = parseInt(dodParts[1], 10);
                var dod = new Date();
                dod.setFullYear(dodYear, dodMonth, dodDay);
                dod.setHours(parseInt(dodHrCtrl.value, 10), parseInt(dodMnCtrl.value, 10), 0, 0);

                //Set 1 day in milliseconds
                var one_day = 1000 * 60 * 60 * 24;

                // calculate time zone offset difference in milliseconds
                var offsetDiff = (dod.getTimezoneOffset() - pud.getTimezoneOffset()) * 60 * 1000;

                // now calculate difference corrected with offset considering DST
                var diff = dod.getTime() - pud.getTime() - offsetDiff;

                // calculate in days
                var duration = diff / one_day;

                // calculate minutes, hours, days to avoid rounding errors
                diff = diff / 1000 / 60;
                var minutes = Math.floor(diff % 60);
                diff = diff / 60;
                var hours = Math.floor(diff % 24);
                diff = diff / 24;
                var days = Math.floor(diff);

                // finally round up the value as we do not have hourly rental
                // considering the 59 minutes grace period as well
                var durationDays;
                if (hours >= 1) {
                    durationDays = Math.ceil(duration);
                }
                else {
                    durationDays = Math.floor(duration);
                }

                outCtrl.innerHTML = /* duration +"<br/>"+ */durationDays;  //+ "<br/>" + pud.toString() + " .. <br/>" + dod.toString() + "";

                if (durationDays < 0) {
                    var defaultRentalLength = 2;
                    dod = new Date(pud.getFullYear(), pud.getMonth(), pud.getDate() + defaultRentalLength);

                    var dodDayString = (dod.getDate()).toString();
                    var dodYearString = (dod.getFullYear()).toString();

                    //if (dodDayString < 10) dodDayString = "0" + dodDayString;               

                    var seperator = " ";
                    dodCtrl.value = dodDayString + seperator + months[dod.getMonth()] + seperator + dodYearString;
                    outCtrl.innerHTML = defaultRentalLength;

                }
            }
        }
    }

    this.changeMonth = changeMonth;
    function changeMonth(change) {

        currentMonth += change;
        currentDay = 0;
        if (currentMonth > 12) {
            currentMonth = 1;
            currentYear++;
        } else if (currentMonth < 1) {
            currentMonth = 12;
            currentYear--;
        }

        calendar = document.getElementById(calendarId);
        calendar.innerHTML = calendarDrawTable();
    }

    this.changeYear = changeYear;
    function changeYear(change) {
        currentYear += change;
        currentDay = 0;
        calendar = document.getElementById(calendarId);
        calendar.innerHTML = calendarDrawTable();
    }

    function getCurrentYear() {
        var year = new Date().getYear();
        if (year < 1900) year += 1900;
        return year;
    }

    function getCurrentMonth() {
        return new Date().getMonth() + 1;
    }

    function getCurrentDay() {
        return new Date().getDate();
    }

    function calendarDrawTable() {
        var nextMonth = currentMonth;
        var nextMonthYear = currentYear;
        if (currentMonth == 12) {
            nextMonth = 1;
            nextMonthYear++;
        }
        else {
            nextMonth++;
        }

        var tables = "<table cellspacing='0' cellpadding='0' border='0'>";
        tables = tables + "<tr>";
        tables = tables + "<td class='calMonth'>";
        tables = tables + calMonthAsHtml(currentYear, currentMonth, 1, true, false);
        tables = tables + "</td><td class='calMonth'>";
        tables = tables + calMonthAsHtml(nextMonthYear, nextMonth, 1, false, true);
        tables = tables + "</td>";
        tables = tables + "</tr>";
        //tables = tables + "<tr class='header'><th colspan='2' style='padding: 3px;'><a href='javascript:clearCC();'>Clear</a> | <a href='javascript:hideCC();'>Close</a></th></tr>";
        tables = tables + "<tr class='calFoot'><td colspan='2'><a class='calendarClose' href='javascript:hideCC();'>" + linkCloseText + "</a>&nbsp;<a href='javascript:hideCC();'><img src='/assets/build/core/calClose.jpg' alt='" + linkCloseText + "' /></a></td></tr>";
        tables = tables + "</table>";

        return tables;
    }

    function calMonthAsHtml(year, month, day, showLeft, showRight) {
        var validDay = 0;
        var startDayOfWeek = getDayOfWeek(year, month, day);
        var daysInMonth = getDaysInMonth(year, month);
        var css_class = null;

        var table = "<table cellspacing='0' cellpadding='0' border='0'>";
        table = table + "<tr class='header'>";
        var colspan = 7;
        var dateNow = new Date();
        var disableLeft = false;

        if (showLeft && (dateNow.getFullYear() == year) && (dateNow.getMonth() == month - 1)) {
            disableLeft = true;
        }

        if (showLeft) {
            colspan--;
            if (!disableLeft) {
                table = table + "<td colspan='1' class='previous title'><a href='javascript:changeCCMonth(-1);'><img src='/assets/build/core/calPrevActive.jpg' alt='" + linkPrevMonthText + "' /></a></td>";
            }
            else {
                table = table + "<td colspan='1' class='previous title'><img src='/assets/build/core/calPrevDisabled.jpg' alt='" + linkPrevMonthText + "' /></td>";
            }
        }
        if (showRight) {
            colspan--;
        }
        table = table + "<td colspan='" + colspan + "' class='title'>" + months[month - 1] + "&nbsp;" + year + "</td>";
        if (showRight) {
            table = table + "<td colspan='1' class='next title'><a href='javascript:changeCCMonth(1);'><img src='/assets/build/core/calNextActive.jpg' alt='" + linkNextMonthText + "' /></a></td>";
        }
        table = table + "</tr>";
        table = table + "<tr>";
        for (var dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++) {
            table = table + "<th>" + dayNames[dayOfWeek] + "</th>";
        };
        table = table + "</tr>";

        for (var week = 0; week < 6; week++) {
            table = table + "<tr>";
            for (var dayOfWeek = 0; dayOfWeek < 7; dayOfWeek++) {
                if (week == 0 && startDayOfWeek == dayOfWeek) {
                    validDay = 1;
                } else if (validDay == 1 && day > daysInMonth) {
                    validDay = 0;
                }

                if (validDay) {
                    if (day == selectedDay && year == selectedYear && month == selectedMonth) {
                        css_class = 'current';
                    } else if (dayOfWeek == 0 || dayOfWeek == 6) {
                        css_class = 'weekend';
                    } else {
                        css_class = 'weekday';
                    }

                    table = table + "<td><a class='" + css_class + "' href=\"javascript:setCCDate(" + year + "," + month + "," + day + ")\">" + day + "</a></td>";

                    day++;
                } else {
                    table = table + "<td class='empty'>&nbsp;</td>";
                }
            }
            table = table + "</tr>";
        }

        table = table + "</table>";

        return table;
    }

    this.show = show;
    function show(field, pickupCtrlId, dropoffCtrlId, outputCtrlId, pudHrId, pudMnId, dodHrId, dodMnId) {
        can_hide = 0;

        if (dateField == field) {
            return;
        } else {
            dateField = field;
        }

        pudCtrl = document.getElementById(pickupCtrlId);
        dodCtrl = document.getElementById(dropoffCtrlId);
        outCtrl = document.getElementById(outputCtrlId);

        pudHrCtrl = document.getElementById(pudHrId);
        pudMnCtrl = document.getElementById(pudMnId);
        dodHrCtrl = document.getElementById(dodHrId);
        dodMnCtrl = document.getElementById(dodMnId);
        

        if (field.id.indexOf('_txtPud') > 0) {
            hideTimeDropDowns();
        }
        
        if (dateField) {
            try {
                var dateString = new String(dateField.value);

                var pattern = /\D/g;
                var monthToMatch = dateString.match(pattern).toString().replace(/\,/g, "").replace(/^\s*|\s*$/g, "");
                selectedMonth = getDateMonth(monthToMatch) + 1;
                dateString = dateString.replace(" " + monthToMatch + " ", "/");

                var dateParts = dateString.split("/");

                selectedDay = parseInt(dateParts[0], 10);
                selectedYear = parseInt(dateParts[1], 10);
            } catch (e) { }
        }
        
        if (!(selectedYear && selectedMonth && selectedDay)) {
            selectedMonth = getCurrentMonth();
            selectedDay = getCurrentDay();
            selectedYear = getCurrentYear();
        }
        
        currentMonth = selectedMonth;
        currentDay = selectedDay;
        currentYear = selectedYear;
        
        if (document.getElementById) {

            calendar = document.getElementById(calendarId);
            calendar.innerHTML = calendarDrawTable();

            setProperty('display', 'block');

            var fieldPos = new positionInfo(dateField);
            var calendarPos = new positionInfo(calendarId);

            var x = fieldPos.getElementLeft();
            var y = fieldPos.getElementBottom();

            setProperty('left', x + "px");
            setProperty('top', y + "px");

            if (document.all) {
                setElementProperty('display', 'block', 'CCIFrame');
                setElementProperty('left', x + "px", 'CCIFrame');
                setElementProperty('top', y + "px", 'CCIFrame');
                setElementProperty('width', calendarPos.getElementWidth() + "px", 'CCIFrame');
                setElementProperty('height', calendarPos.getElementHeight() + "px", 'CCIFrame');
            }

            //         calendar.focus();
            //         calendar.onblur = hideCCOnLostFocus;
        }
    }

    this.hide = hide;
    function hide() {
        showTimeDropDowns();
        if (dateField) {
            setProperty('display', 'none');
            setElementProperty('display', 'none', 'CCIFrame');
            dateField = null;
        }
    }

    this.visible = visible;
    function visible() {
        return dateField
    }

    this.can_hide = can_hide;
    var can_hide = 0;
}

var CC = new CC();

function showCC(textField, pickupCtrlId, dropoffCtrlId, outputCtrlId, pudHrId, pudMnId, dodHrId, dodMnId) {
    CC.show(textField, pickupCtrlId, dropoffCtrlId, outputCtrlId, pudHrId, pudMnId, dodHrId, dodMnId);
}

function showCcDuration(pickupCtrlId, dropoffCtrlId, outputCtrlId, pudHrId, pudMnId, dodHrId, dodMnId) {
    CC.showDuration(document.getElementById(pickupCtrlId), document.getElementById(dropoffCtrlId), document.getElementById(outputCtrlId),
   document.getElementById(pudHrId), document.getElementById(pudMnId),
   document.getElementById(dodHrId), document.getElementById(dodMnId));
}

function validateDate(textField) {
    if (textField != null) {
        var isValid = false;
        var textValue = textField.value;
        textValue = textValue.replace(/\D/gi, "");
        if (textValue.length == 8) {
            try {
                var dtDay = parseInt(textValue.substr(0, 2), 10);
                var dtMonth = parseInt(textValue.substr(2, 2), 10);
                var dtYear = parseInt(textValue.substr(4, 4), 10);
                var dt = new Date();
                dt.setFullYear(dtYear, dtMonth + 1, dtDay);
                isValid = true;
                if (dtDay < 10) dtDay = "0" + dtDay;
                if (dtMonth < 10) dtMonth = "0" + dtMonth;
                textValue = dtDay + "/" + dtMonth + "/" + dtYear;
            }
            catch (e) { }
        }
        if (!isValid) {
            textField.value = "";
        }
        else {
            textField.value = textValue;
        }
    }
}

function clearCC() {
    CC.clearDate();
}

function hideCC() {
    if (CC.visible()) {

        CC.hide();
    }
}

// This snippet is to close the calendar when the user is clicking somewhere else
// but this is not working yet
// TODO: find a way to recognise which element has the focus. [instead of ...gotFocus]
//function hideCCOnLostFocus()
//{
//   var calendar = document.getElementById("CC");
//   var isFocusInsideCalendar = false;
//   
//   isFocusInsideCalendar = iterateThroughNodes(calendar);   
//   
//   if(!isFocusInsideCalendar)
//   {
//      hideCC();
//   }
//}


//function iterateThroughNodes(node)
//{
//   var foundFocus = false;
//  
//   if(node && node.childNodes.length > 0)
//   {
//      for(var i=0;i<node.childNodes.length;i++)
//      {
//         try
//         {
//            if ( node.childNodes[i].gotFocus )
//            {
//               foundFocus = true;
//               break;
//            }
//            else
//            {
//               iterateThroughNodes(node.childNodes[i]);
//            }
//         }
//         catch (ex)
//         {
//            // catch exception for when the element doesn't support the gotFocus attribute.
//         }
//      }
//   }
//   
//   return foundFocus;
//}


function setCCDate(year, month, day) {
    CC.setDate(year, month, day);
}

function changeCCYear(change) {
    CC.changeYear(change);
}

function changeCCMonth(change) {
    CC.changeMonth(change);
}


//document.write("<iframe id='CCIFrame' src='javascript:false;' frameBorder='0' scrolling='no' style='display:none;'></iframe>");
document.write("<div id='CC'></div>");
