/* $Id: calendar2.js,v 1.3.2.2 2009/09/18 14:12:56 alik Exp $ */


/**
 * Modify from controls when the "NULL" checkbox is selected
 *
 * @param   string   the MySQL field type
 * @param   string   the urlencoded field name
 * @param   string   the md5 hashed field name
 *
 * @return  boolean  always true
 */
function nullify(theType, urlField, md5Field, multi_edit)
{
    var rowForm = document.forms['insertForm'];

    if (typeof(rowForm.elements['funcs' + multi_edit + '[' + urlField + ']']) != 'undefined') {
        rowForm.elements['funcs' + multi_edit + '[' + urlField + ']'].selectedIndex = -1;
    }

    // "SET" field , "ENUM" field with more than 20 characters
    // or foreign key field
    if (theType == 1 || theType == 3 || theType == 4) {
        rowForm.elements['field_' + md5Field + multi_edit + '[]'].selectedIndex = -1;
    }
    // Other "ENUM" field
    else if (theType == 2) {
        var elts     = rowForm.elements['field_' + md5Field + multi_edit + '[]'];
        // when there is just one option in ENUM:
        if (elts.checked) {
            elts.checked = false;
        } else {
            var elts_cnt = elts.length;
            for (var i = 0; i < elts_cnt; i++ ) {
                elts[i].checked = false;
            } // end for

        } // end if
    }
    // Other field types
    else /*if (theType == 5)*/ {
        rowForm.elements['fields' + multi_edit + '[' + urlField + ']'].value = '';
    } // end if... else if... else

    return true;
} // end of the 'nullify()' function


/**
 * Unchecks the "NULL" control when a function has been selected or a value
 * entered
 *
 * @param   string   the urlencoded field name
 *
 * @return  boolean  always true
 */
function unNullify(urlField, multi_edit)
{
    var rowForm = document.forms['insertForm'];

    if (typeof(rowForm.elements['fields_null[multi_edit][' + multi_edit + '][' + urlField + ']']) != 'undefined') {
        rowForm.elements['fields_null[multi_edit][' + multi_edit + '][' + urlField + ']'].checked = false
    } // end if

    if (typeof(rowForm.elements['insert_ignore_' + multi_edit]) != 'undefined') {
        rowForm.elements['insert_ignore_' + multi_edit].checked = false
    } // end if

    return true;
} // end of the 'unNullify()' function

var day;
var month;
var year;
var hour;
var minute;
var second;
var clock_set = 0;
var start_date;

/**
 * Opens calendar window.
 *
 * @param   string      calendar2.php parameters
 * @param   string      form name
 * @param   string      field name
 * @param   string      edit type - date/timestamp
 */
function openCalendar(form, field, type, start_date) {
    var obj_calwindow = window.open("/calendar2.php?form="+form+"&field="+field+"&type="+type+"&start_date="+start_date, "calendar", "width=250,height=280,status=yes");
    obj_calwindow.opener = window;
	obj_calwindow.focus();
}

/**
 * Formats number to two digits.
 *
 * @param   int number to format.
 */
function formatNum2(i, valtype) {
    f = (i < 10 ? '0' : '') + i;
    if (valtype && valtype != '') {
        switch(valtype) {
            case 'month':
                f = (f > 12 ? 12 : f);
                break;

            case 'day':
                f = (f > 31 ? 31 : f);
                break;

            case 'hour':
                f = (f > 24 ? 00 : f);
                break;

            default:
            case 'second':
            case 'minute':
                f = (f > 59 ? 59 : f);
                break;
        }
    }

    return f;
}

/**
 * Formats number to four digits.
 *
 * @param   int number to format.
 */
function formatNum4(i) {
    return (i < 1000 ? i < 100 ? i < 10 ? '000' : '00' : '0' : '') + i;
}

/**
 * Initializes calendar window.
 */
function initCalendar() {
    if (!year && !month && !day) {
        /* Called for first time */
        //if (window.opener.dateField.value) {

        value = dateField.value;
        if ((value=="")&&(start_date!=""))
        	value = start_date;

        if (value&&value!="undefined") {
            //if (window.opener.dateType == 'datetime' || window.opener.dateType == 'date') {
            if (dateType == 'datetime' || dateType == 'date') {
                //if (window.opener.dateType == 'datetime') {
                if (dateType == 'datetime') {
                    parts   = value.split(' ');
                    value   = parts[0];

                    if (parts[1]) {
                        time    = parts[1].split(':');
                        hour    = parseInt(time[0],10);
                        minute  = parseInt(time[1],10);
                        second  = parseInt(time[2],10);
                    }
                }
                //date        = value.split("-");
                if (value.search('-')>0) {
    	            date        = value.split("-");
	            } else if (value.search('/')>0){
	                date        = value.split("/");
	            }

                day         = parseInt(date[1],10);
                month       = parseInt(date[0],10) - 1;
                year        = parseInt(date[2],10);
            } else {
                year        = parseInt(value.substr(4,4),10);
                month       = parseInt(value.substr(0,2),10) - 1;
                day         = parseInt(value.substr(2,2),10);

              //  year        = parseInt(value.substr(0,4),10);
              //  month       = parseInt(value.substr(4,2),10) - 1;
              //  day         = parseInt(value.substr(6,2),10);
                hour        = parseInt(value.substr(8,2),10);
                minute      = parseInt(value.substr(10,2),10);
                second      = parseInt(value.substr(12,2),10);
            }
        }

        if (isNaN(year) || isNaN(month) || isNaN(day) || day == 0) {
            dt      = new Date();
            year    = dt.getFullYear();
            month   = dt.getMonth();
            day     = dt.getDate();
        }
        if (isNaN(hour) || isNaN(minute)) {
            dt      = new Date();
            hour    = dt.getHours();
            minute  = dt.getMinutes();
            second  = dt.getSeconds();
        }
    } else {
        /* Moving in calendar */
        if (month > 11) {
            month = 0;
            year++;
        }
        if (month < 0) {
            month = 11;
            year--;
        }
    }

    if (document.getElementById) {
        cnt = document.getElementById("calendar_data");
    } else if (document.all) {
        cnt = document.all["calendar_data"];
    }

    cnt.innerHTML = "";

    str = ""

    //heading table
    str += '<table style="margin-top:0px;" width="100%" style="background-color:#ffffff;" align="center" cellpadding="0" cellspacing="2"><tr><td class="caption" width="50%" align="right">';
    str += '<form method="NONE" onsubmit="return 0">';
	str += '<input type="hidden" id="datetime" name="datetime" value="'+formatNum2(month+1, 'month')+"/"+formatNum2(day,'day')+"/"+formatNum4(year,'year')+'">'
	str += '<input type="hidden" id="selected_td" name="selected_td" value="">'
    str += '<nobr><a href="javascript:month--; initCalendar();">&laquo;</a> ';
    str += '<select id="select_month" name="monthsel" onchange="month = parseInt(document.getElementById(\'select_month\').value); initCalendar();">';
    for (i =0; i < 12; i++) {
        if (i == month) selected = ' selected="selected"';
        else selected = '';
        str += '<option value="' + i + '" ' + selected + '>' + month_names[i] + '</option>';
    }
    str += '</select>';
    str += ' <a href="javascript:month++; initCalendar();">&raquo;</a></nobr>';
    str += '</form>';
    str += '</td><td class="caption" width="50%" align="left">';
    str += '<form method="NONE" onsubmit="return 0">';
    str += '<nobr><a href="javascript:year--; initCalendar();">&laquo;</a> ';
    str += '<select id="select_year" name="yearsel" onchange="year = parseInt(document.getElementById(\'select_year\').value); initCalendar();">';
    for (i = year - 50; i <= year+5; i++) {
        if (i == year) selected = ' selected="selected"';
        else selected = '';
        str += '<option value="' + i + '" ' + selected + '>' + i + '</option>';
    }
    str += '</select>';
    str += ' <a href="javascript:year++; initCalendar();">&raquo;</a></nobr>';
    str += '</form>';
    str += '</td></tr></table>';

    str += '<table width="100%" style="background-color:#ffffff;" align="center" cellpadding="0" cellspacing="2" border="0"><tr>';
    for (i = 0; i < 7; i++) {
        str += "<th style='width:14%' class=\"wd1\">" + day_names[i] + "</th>";
    }
	 str += "</tr>";

    var firstDay = new Date(year, month, 1).getDay();
    var lastDay = new Date(year, month + 1, 0).getDate();

    str += "<tr style='height:20px;'>";

    dayInWeek = 0;
    for (i = 0; i < firstDay; i++) {
        str += '<td align="center" class=\"wd1\"></td>';
        dayInWeek++;
    }

    var selected_i = 0;

    for (i = 1; i <= lastDay; i++) {
        if (dayInWeek == 7) {
            str += "</tr><tr style='height:20px;'>";
            dayInWeek = 0;
        }

        dispmonth = 1 + month;

        //if (window.opener.dateType == 'datetime' || window.opener.dateType == 'date') {
        if (dateType == 'datetime' || dateType == 'date') {
            actVal = formatNum2(dispmonth, 'month') + "/" + formatNum2(i, 'day')+ "/"+ formatNum4(year);
        } else {
            actVal = "" + formatNum2(dispmonth, 'month') + formatNum2(i, 'day')+ formatNum4(year);
        }
        if (i == day) {
            style = ' class="so1"';
            selected_i=i;
        } else {
            style = ' class="wd1"';
        }
        str += "<td id="+i+" " + style + "><a href=\"javascript:returnDate2('" + actVal +"','"+i+"');\">" + i + "</a></td>"
        dayInWeek++;
    }
    for (i = dayInWeek; i < 7; i++) {
        str += "<td class=\"wd1\"></td>";
    }
    str += "</tr></table>";

    cnt.innerHTML = str;

    document.getElementById('selected_td').value=selected_i;

    // Should we handle time also?
    //if (window.opener.dateType != 'date' && !clock_set) {
    if (dateType != 'date' && !clock_set) {
        if (document.getElementById) {
            cnt = document.getElementById("clock_data");
        } else if (document.all) {
            cnt = document.all["clock_data"];
        }

        str = '';
        str = '<div align=center style="padding-top:3px">';
        str += '<form class="clock" align="center" style="margin-top:0">';
        str += '<input id="hour"    type="text" size="2" maxlength="2" onblur="this.value=formatNum2(this.value, \'hour\')" value="' + formatNum2(hour, 'hour') + '" />:';
        str += '<input id="minute"  type="text" size="2" maxlength="2" onblur="this.value=formatNum2(this.value, \'minute\')" value="' + formatNum2(minute, 'minute') + '" /><br><br>';
        str += "<input  style='width:40px;' type=button name='bth' value='Ok' onclick='returnDate3();'>&nbsp;&nbsp;&nbsp;&nbsp;"
        str += "<input  style='width:40px;' type=button name='bth' value='Cancel' onclick='window.close();'>"
        str += '</form></div>';
        cnt.innerHTML = str;
        clock_set = 1;
    }
    if (dateType == 'date') {
        if (document.getElementById) {
            cnt = document.getElementById("clock_data");
        } else if (document.all) {
            cnt = document.all["clock_data"];
        }
        str = '<div align=center>';
        str += '<form class="clock" align="center">';
        str += "<input width='100px;' type=button name='bth' value='Ok' onclick='returnDate3();'>&nbsp;&nbsp;&nbsp;&nbsp;"
        str += "<input width='100px;' type=button name='bth1' value='Cancel' onclick='window.close();'>"
        str += '</form></div>';
        cnt.innerHTML = str;
        clock_set = 1;
    }

}

/**
 * Returns date from calendar.
 *
 * @param   string     date text
 */

function returnDate2(date, i)
{
	pred_date =document.getElementById('datetime');

	pred_date.value=date;

	pred_td_num =document.getElementById('selected_td').value;

	pred_selected_td =document.getElementById(pred_td_num);

	pred_selected_td.className='wd';

	selected_td = document.getElementById(i);

	selected_td.className='so';

	document.getElementById('selected_td').value = i;
}

function returnDate3()
{
    txt =document.getElementById('datetime').value;
	if (dateType != 'date') {
        h = parseInt(document.getElementById('hour').value,10);
        m = parseInt(document.getElementById('minute').value,10);
        if (dateType == 'datetime') {
            txt += ' ' + formatNum2(h, 'hour') + ':' + formatNum2(m, 'minute');
        } else {
            // timestamp
            txt += formatNum2(h, 'hour') + formatNum2(m, 'minute');
        }
    }
    dateField.value = txt;

     /** ADDED BY ITCRAFT **/
    if (window.opener.document.getElementById('profile-birthdate-edit')) {
    	window.opener.saveProfileData('birthdate', txt, 'profile-birthdate');
    }

    window.close();
}
function returnDate(d)
{
    txt = d;
	//if (window.opener.dateType != 'date') {
	if (dateType != 'date') {
        // need to get time
        h = parseInt(document.getElementById('hour').value,10);
        m = parseInt(document.getElementById('minute').value,10);
        //if (window.opener.dateType == 'datetime') {
        if (dateType == 'datetime') {
            txt += ' ' + formatNum2(h, 'hour') + ':' + formatNum2(m, 'minute');
        } else {
            // timestamp
            txt += formatNum2(h, 'hour') + formatNum2(m, 'minute');
        }
    }

    //window.opener.dateField.value = txt;
    dateField.value = txt;

    /** ADDED BY ITCRAFT **/
    if (window.opener.document.getElementById('profile-birthdate-edit')) {
    	window.opener.saveProfileData('birthdate', txt, 'profile-birthdate');
    }

    window.close();
}

function prepareCalendar(form, field, type, selected_date) {
	start_date = selected_date;
	dateField = eval(window.opener.document.forms[form].elements[field]);
	dateType = type;
	initCalendar();
}

