// -- ORIGINAL SOFTWARE SOURCE ---------------------------------------------------------------------------------
//
// Title:   Tigra Calendar
// URL:     http://www.softcomplex.com/products/tigra_calendar/
// Version: 3.2 (American date format)
// Date:    10/14/2002

// -- MODIFICATIONS MADE BY BYRGIUS TECHNOLOGIES ---------------------------------------------------------------
//
// Developer:   Byrgius Technologies
// Files:       cal.js, cal.html
// URL:         http://www.byrgius.com/
// Version:     1.00 (iFrame Version)
// Last Mod:    07/02/2004
//
// ModDate__ModUser_______ModDescription________________________________________________________________________
// 06/24/04 David Hunt  : Allow for modification of "SELECT" input types
// 06/28/04 David Hunt  : Returns "Day of Week" value with date (to mimick OUTLOOK scheduling date format)
// 07/01/04 David Hunt  : Recompiled as "iframe_cal.js" to support inline "IFRAME" usage
// 07/01/04 David Hunt  : Recompiled as "iframe_cal.html" to support inline "IFRAME" usage
// 07/01/04 David Hunt  : Added Cascading Style Sheet (CSS) functionality
// 07/01/04 David Hunt  : Added dynamic iFrame window size functionality
// 07/01/04 David Hunt  : Added winStat function to iframe_cal.html for Advanced Rollovers
// 07/02/04 David Hunt  : Added check_field_val function for checking field value (TEXT FIELDS ONLY)
// 07/02/04 David Hunt  : Added instructions
// 07/02/04 David Hunt  : Integrated Calendar1, Calendar2, & iFrame functions into one package named "cal"
//

// -- USAGE INSTRUCTIONS ---------------------------------------------------------------------------------------
//
// Things you should know
//   - You can have an unlimited number of calendars on the page
//   - There are TWO ways to use the popup calendar
//      - Inline Frames (IFRAME)
//      - Popup Window (Loads a New Window)
//   - Each calendar must have a unique NAME/ID
//   - Each calendar on the page must be initialized when the web page loads
//   - You CAN specifiy the absolute window position on the screen if desired
//
// Insert the following script call into your Web Page (UPDATE THE PATH)
//      <script language="JavaScript" src="{YOUR_PATH_TO_CALENDAR}cal.js"></script>
//
// Setup for the Calendar Initialization
//   - You can use a TEXT or SELECT field on your form for the date.
//     The advantage of using a SELECT field is that the user can't type/affect the value
//
//   - For TEXT fields, you will use the following code
//      <script language="JavaScript">
//      <!--
//           var cal1 = new calendar(document.forms['PAGEFORM'].elements['date_01']);
//           cal1.year_scroll = true; cal1.time_comp = false; cal1.is_Select = false;
//      //-->
//      </script>
//
//   - For SELECT fields, you will use the following code
//      <script language="JavaScript">
//      <!--
//           var cal1 = new calendar(document.forms['PAGEFORM'].elements['date_01'].options[0]);
//           cal1.year_scroll = true; cal1.time_comp = false; cal1.is_Select = true;
//      //-->
//      </script>
//
// Setup for INLINE FRAMES
//   - Insert the following tag where you want the calendar to load
//      <iframe style="display:none;position:absolute;z-index=100" name="CalFrame1" id="CalFrame1" width="1" height="1" marginheight=0 marginwidth=0 frameborder=0 scrolling=no src="spacer.gif" noresize></iframe>
//
// Setting up the tags to call the calendar
//   - Use the LoadCal() function to call the calendar
//      From a Link:    <a href="javascript:cal1.LoadCal('','CalFrame1');">
//      From an Event:  <TAG onFocus="cal1.LoadCal('','CalFrame1');">
//
//   - Use the CheckVal() function to call check a TEXT field value
//      From an Event:  <TAG onChange="this.value=cal1.CheckVal(this.value);">
//

// -- Configurable Environment Variables -----------------------------------------------------------------------

// server path to calendar
var popCalPath          = '/HUMESMCCOYAVIATION.COM/www/TEMPLATES/popCal/';
var popCalPath          = '/TEMPLATES/popCal/';
var popCalHtmlFile      = 'cal.html';

// is time input control required by default
var USE_TIMECOMPONENT   = false;

// are year scrolling buttons required by default
var USE_YEARSCROLL      = true;

// is the form field a SELECT
var INPUT_SELECT        = false;

// default date format
//  0 = mm/dd/yyyy
//  1 = dow mm/dd/yyyy
var DATE_FORMAT         = 1;

// default character to use as a seperator in the date (mm/dd/yyyy)
var DIV_CHAR            = '/';

// if two digit year input dates after this year considered 20 century.
var NUM_CENTYEAR        = 30;

// calendar object array
var calendars           = [];

// regex for raw date formatting
var RE_NUM              = /^\-?\d+$/;

// -- create calendar object -----------------------------------------------------------------------------------
function calendar(obj_target) {
    // assigning methods
    this.LoadCal        = cal_load_cal;
    this.CheckVal       = check_field_val;
    this.gen_date       = cal_gen_date;
    this.gen_time       = cal_gen_time;
    this.gen_tsmp       = cal_gen_tsmp;
    this.prs_date       = cal_prs_date;
    this.prs_time       = cal_prs_time;
    this.prs_tsmp       = cal_prs_tsmp;

    // validate input parameters
    if (!obj_target)
        return cal_error("Error calling the calendar: no target control specified");
    if (obj_target.value == null)
        return cal_error("Error calling the calendar: parameter specified is not valid target control");

    this.target         = obj_target;
    this.time_comp      = USE_TIMECOMPONENT;
    this.year_scroll    = USE_YEARSCROLL;
    this.date_format    = DATE_FORMAT;
    this.div_char       = DIV_CHAR;
    this.is_Select      = INPUT_SELECT;
    this.pox_x          = 0;
    this.pox_y          = 0;

    // register in global collections
    this.id             = calendars.length;
    calendars[this.id]  = this;
}

// -- load calendar iFrame layer -------------------------------------------------------------------------------
function cal_load_cal (str_datetime) {
    this.dt_current = this.prs_tsmp(str_datetime ? str_datetime : this.target.value);
    if (!this.dt_current) return;
    if (this.frame_name) {
        var obj_calFrame = document.getElementById(this.frame_name);
        obj_calFrame.src = (
            popCalPath + popCalHtmlFile + '?datetime=' + this.dt_current.valueOf() + '&id=' + this.id
            + '&fName=' + this.frame_name + '&pos_x=' + this.pos_x + '&pos_y=' + this.pos_y
        );
    } else {
        if (!this.pos_x) { this.pos_x = 200; };
        if (!this.pos_y) { this.pos_y = 200; };
        var obj_calwindow = window.open(
            popCalPath + popCalHtmlFile + '?datetime=' + this.dt_current.valueOf() + '&id=' + this.id + '&pos_x='
            + this.pos_x + '&pos_y=' + this.pos_y, 'Calendar','width=200,height=200,status=no,resizable=no,top='
            + this.pos_x + ',left=' + this.pos_y + ',dependent=yes,alwaysRaised=yes'
        );
        obj_calwindow.opener = window;
        obj_calwindow.focus();
    };
}

// -- timestamp generating -------------------------------------------------------------------------------------
function cal_gen_tsmp (dt_datetime) {
    return(this.gen_date(dt_datetime) + ' ' + this.gen_time(dt_datetime));
}

// -- get day name ---------------------------------------------------------------------------------------------
function getDayName (int_day,format) {
    var ARR_WEEKDAYS = new Array(6);
    if (format) {
        ARR_WEEKDAYS    = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
    } else {
        ARR_WEEKDAYS    = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    };
    return (ARR_WEEKDAYS[int_day]);
}

// -- date generating ------------------------------------------------------------------------------------------
function cal_gen_date (dt_datetime) {
    var rFormat;
    if (this.date_format) {
        rFormat = getDayName(dt_datetime.getDay()) + ' ';
    };
    rFormat = rFormat + (dt_datetime.getMonth() < 9 ? '0' : '') + (dt_datetime.getMonth() + 1)
                      + this.div_char + (dt_datetime.getDate() < 10 ? '0' : '')
                      + dt_datetime.getDate() + this.div_char + dt_datetime.getFullYear();
    return rFormat;
}

// -- time generating ------------------------------------------------------------------------------------------
function cal_gen_time (dt_datetime) {
    return (
        (dt_datetime.getHours() < 10 ? '0' : '') + dt_datetime.getHours() + ":"
        + (dt_datetime.getMinutes() < 10 ? '0' : '') + (dt_datetime.getMinutes()) + ":"
        + (dt_datetime.getSeconds() < 10 ? '0' : '') + (dt_datetime.getSeconds())
    );
}

// -- timestamp parsing ----------------------------------------------------------------------------------------
function cal_prs_tsmp (str_datetime) {
    // if no parameter specified return current timestamp
    if (!str_datetime)
        return (new Date());

    // if positive integer treat as milliseconds from epoch
    if (RE_NUM.exec(str_datetime))
        return new Date(str_datetime);

    // swap characters
    str_datetime = str_datetime.replace(/-|\.|\|/g,this.div_char);

    // remove day of week (if it is there)
    str_datetime = str_datetime.replace(/^\s*\D+\s+/,'');

    // else treat as date in string format
    var arr_datetime = str_datetime.split(' ');
    return this.prs_time(arr_datetime[1], this.prs_date(arr_datetime[0]));
}

// -- date parsing ---------------------------------------------------------------------------------------------
function cal_prs_date (str_date) {

    var arr_date = str_date.split('/');

    if (arr_date.length != 3)      return alert ("Invalid date format: '" + str_date + "'.\nFormat accepted is [dow dd-mm-yyyy].");
    if (!arr_date[1])              return alert ("Invalid date format: '" + str_date + "'.\nNo day of month value can be found.");
    if (!RE_NUM.exec(arr_date[1])) return alert ("Invalid day of month value: '" + arr_date[1] + "'.\nAllowed values are unsigned integers.");
    if (!arr_date[0])              return alert ("Invalid date format: '" + str_date + "'.\nNo month value can be found.");
    if (!RE_NUM.exec(arr_date[0])) return alert ("Invalid month value: '" + arr_date[0] + "'.\nAllowed values are unsigned integers.");
    if (!arr_date[2])              return alert ("Invalid date format: '" + str_date + "'.\nNo year value can be found.");
    if (!RE_NUM.exec(arr_date[2])) return alert ("Invalid year value: '" + arr_date[2] + "'.\nAllowed values are unsigned integers.");

    var dt_date = new Date();
    dt_date.setDate(1);

    if (arr_date[0] < 1 || arr_date[0] > 12) return alert ("Invalid month value: '" + arr_date[0] + "'.\nAllowed range is 01-12.");
    dt_date.setMonth(arr_date[0]-1);

    if (arr_date[2] < 100) arr_date[2] = Number(arr_date[2]) + (arr_date[2] < NUM_CENTYEAR ? 2000 : 1900);
    dt_date.setFullYear(arr_date[2]);

    var dt_numdays = new Date(arr_date[2], arr_date[0], 0);
    dt_date.setDate(arr_date[1]);
    if (dt_date.getMonth() != (arr_date[0]-1)) return alert ("Invalid day of month value: '" + arr_date[1] + "'.\nAllowed range is 01-"+dt_numdays.getDate()+".");

    return (dt_date)
}

// -- time parsing ---------------------------------------------------------------------------------------------
function cal_prs_time (str_time, dt_date) {

    if (!dt_date) return null;
    var arr_time = String(str_time ? str_time : '').split(':');

    if (!arr_time[0]) dt_date.setHours(0);
    else if (RE_NUM.exec(arr_time[0]))
        if (arr_time[0] < 24) dt_date.setHours(arr_time[0]);
        else return cal_error ("Invalid hours value: '" + arr_time[0] + "'.\nAllowed range is 00-23.");
    else return cal_error ("Invalid hours value: '" + arr_time[0] + "'.\nAllowed values are unsigned integers.");

    if (!arr_time[1]) dt_date.setMinutes(0);
    else if (RE_NUM.exec(arr_time[1]))
        if (arr_time[1] < 60) dt_date.setMinutes(arr_time[1]);
        else return cal_error ("Invalid minutes value: '" + arr_time[1] + "'.\nAllowed range is 00-59.");
    else return cal_error ("Invalid minutes value: '" + arr_time[1] + "'.\nAllowed values are unsigned integers.");

    if (!arr_time[2]) dt_date.setSeconds(0);
    else if (RE_NUM.exec(arr_time[2]))
        if (arr_time[2] < 60) dt_date.setSeconds(arr_time[2]);
        else return cal_error ("Invalid seconds value: '" + arr_time[2] + "'.\nAllowed range is 00-59.");
    else return cal_error ("Invalid seconds value: '" + arr_time[2] + "'.\nAllowed values are unsigned integers.");

    dt_date.setMilliseconds(0);
    return dt_date;
}

// -- field value check ----------------------------------------------------------------------------------------
function check_field_val (str_val) {
    var fVal = this.prs_tsmp(str_val);
    if (fVal) {
        return this.gen_date(fVal);
    } else {
        return '';
    };
}

// -- calendar error -------------------------------------------------------------------------------------------
function cal_error (str_message) {
    alert (str_message);
    return null;
}

// -- END OF APPLICATION ---------------------------------------------------------------------------------------