/**************************
          Tabs
**************************/
var TABS_SET_CLASS_NAME = 'form-builder-tabs';
var TABS_TITLE_CLASS_NAME = 'form-builder-tab';
var TABS_CONTENT_CLASS_NAME = 'form-builder-tab';

function startTabs()
{
    var DLs = document.getElementsByTagName('DL');
    for (var i = 0; i < DLs.length; i ++) {
        if (DLs[i].className && DLs[i].className == TABS_SET_CLASS_NAME) {
            setTabs(DLs[i]);
        }
    }
}

function setTabs(tabset)
{
    var max_height = 0;
    var contents = new Array;
    var titles = new Array;
    for (var i = 0; i < tabset.childNodes.length; i ++) {
        if (tabset.childNodes[i].tagName == 'DD' && tabset.childNodes[i].className.match(new RegExp('^' + TABS_CONTENT_CLASS_NAME))) {
            if (max_height < tabset.childNodes[i].offsetHeight) {
                max_height = tabset.childNodes[i].offsetHeight;
            }
            contents[contents.length] = tabset.childNodes[i];
        } else if (tabset.childNodes[i].tagName == 'DT' && tabset.childNodes[i].className.match(new RegExp('^' + TABS_TITLE_CLASS_NAME))) {
            tabset.childNodes[i].onclick = function() {
                showTab(this.parentNode, this);
            }
            titles[titles.length] = tabset.childNodes[i];
        }
    }
    tabset.style.height = (max_height + titles[0].offsetHeight) + 'px';
    for (var i = 0; i < contents.length; i ++) {
        contents[i].style.height = max_height + 'px';
    }
    
    if (!is_browser_ie()) {
        var content = document.getElementById('content');
        var container = document.getElementById('container');
        var middle = document.getElementById('middle');

        //var content_pad = max_height - content.offsetHeight;
        var content_pad = 200;
        if (is_browser_opera()) {
            content_pad += 20;
        }
        var container_pad = content_pad + container.offsetHeight - content.offsetHeight;
        var middle_pad = container_pad + middle.offsetHeight - container.offsetHeight;
        
        /*content.style.height = (max_height + content_pad) + 'px';*/
        container.style.height = (max_height + container_pad) + 'px';
        middle.style.height = (max_height + middle_pad) + 'px';
    }
    
    hideTabs(tabset);
    showTab(tabset, titles[0]);
}

function showTab(tabset, tab)
{
    hideTabs(tabset);
    var number = 0;
    for (var i = 0; i < tabset.childNodes.length; i ++) {
        if (tabset.childNodes[i].tagName == 'DT'
         && tabset.childNodes[i].className.match(new RegExp('^' + TABS_TITLE_CLASS_NAME))) {
             number ++;
        }
        if (tabset.childNodes[i] === tab) {
            tabset.childNodes[i].className = tabset.childNodes[i].className.replace(new RegExp('-active|-hidden$'), '-visible');
            //tabset.childNodes[i].className += '-visible';
            break;
        }
    }

    for (var i = 0; i < tabset.childNodes.length; i ++) {
        if (tabset.childNodes[i].tagName == 'DD'
         && tabset.childNodes[i].className.match(new RegExp('^' + TABS_CONTENT_CLASS_NAME))) {
            number --;
        }
        if (!number) {
            break;
        }
    }
    
    if (!number) {
        tabset.childNodes[i].className = tabset.childNodes[i].className.replace(new RegExp('-hidden$'), '-visible');
    }
}

function hideTabs(tabset)
{
    for (var i = 0; i < tabset.childNodes.length; i ++) {
        if (tabset.childNodes[i].tagName == 'DD' && tabset.childNodes[i].className.match(new RegExp('^' + TABS_CONTENT_CLASS_NAME))) {
            tabset.childNodes[i].className = tabset.childNodes[i].className.replace(new RegExp('-visible|-hidden$'), '');
            tabset.childNodes[i].className += '-hidden';
        } else if (tabset.childNodes[i].tagName == 'DT' && tabset.childNodes[i].className.match(new RegExp('^' + TABS_TITLE_CLASS_NAME))) {
            tabset.childNodes[i].className = tabset.childNodes[i].className.replace(new RegExp('-visible|-hidden$'), '');
            tabset.childNodes[i].className += '-hidden';
        }
    }
}

/**************************
         Calendar
**************************/
var CALENDAR_INPUT_CLASS_NAME = 'form-builder-calendar-input';
var CALENDAR_CONTAINER_CLASS_NAME = 'form-builder-calendar-container';
var CALENDAR_CELL_HOLIDAY_CLASS_NAME = 'form-builder-calendar-holiday';
var CALENDAR_CELL_REGDAY_CLASS_NAME = 'form-builder-calendar-regday';
var CALENDAR_CELL_CLASS_NAME = 'form-builder-calendar-grid';
var CALENDAR_GRID_CLASS_NAME = 'form-builder-calendar-grid';
var CALENDAR_DATE_CONTAINER_CLASS_NAME = 'form-builder-calendar-date-container';
var CALENDAR_GRID_CONTAINER_CLASS_NAME = 'form-builder-calendar-grid-container';
var CALENDAR_SHEET_CLASS_NAME = 'form-builder-calendar-sheet';

var CALENDAR_YEAR_FROM = '1996';
var CALENDAR_YEAR_TO = '2016';
var CALENDAR_MONTHS = new Array('Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь');
var CALENDAR_DAYS = [
    {'long_name': 'Понедельник', 'short_name': 'Пн', 'holiday': false},
    {'long_name': 'Вторник',     'short_name': 'Вт', 'holiday': false},
    {'long_name': 'Среда',       'short_name': 'Ср', 'holiday': false},
    {'long_name': 'Четверг',     'short_name': 'Чт', 'holiday': false},
    {'long_name': 'Пятница',     'short_name': 'Пт', 'holiday': false},
    {'long_name': 'Суббота',     'short_name': 'Сб', 'holiday': true},
    {'long_name': 'Воскресенье', 'short_name': 'Вс', 'holiday': true}
];

var days_in_months = {1: 30, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, 7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31};

var hide_calendar = true;

function startCalendarSheets()
{
    var inputs = document.getElementsByTagName('INPUT');
    for (var i = 0; i < inputs.length; i ++) {
        if (inputs[i].className && inputs[i].className == CALENDAR_SHEET_CLASS_NAME) {
            setCalendarSheet(inputs[i]);
        }
    }
}

function setCalendarSheet(input)
{
    var container = document.createElement('DIV');
    //input.parentNode.appendChild(container);
    input.parentNode.insertBefore(container, input.nextSibling ? input.nextSibling : input);
    input.style.display = 'none';
    container.className = CALENDAR_CONTAINER_CLASS_NAME;
    container.id = 'calendar_' + input.id;
    container.style.visibility = 'visible';
    container.style.display = 'block';
    container.style.cssFloat = 'left';
    container.style.clear = 'none';
    container.style.position = 'static';
    
    var input_pos = getElementPosition(input);
    container.style.left = input_pos.x + 'px';
    container.style.top = (input_pos.y + input.offsetHeight) + 'px';
    //container.style.width = input.offsetWidth + 'px';

    var date_container = document.createElement('DIV');
    container.appendChild(date_container);
    date_container.className = CALENDAR_DATE_CONTAINER_CLASS_NAME;
    
    var grid_container = document.createElement('DIV');
    container.appendChild(grid_container);
    grid_container.className = CALENDAR_GRID_CONTAINER_CLASS_NAME;
    
    //date picker
    var select_month = document.createElement('SELECT');
    date_container.appendChild(select_month);

    var input_year = document.createElement('INPUT');
    date_container.appendChild(input_year);

    select_month.onchange = function() {
        var date_regexp = new RegExp('([0-9]{1,2})[\.\/-]([0-9]{1,2})[\.\/-]([0-9]{4}|\d{2})');
        if (date = date_regexp.exec(input.value)) {
            var day   = parseInt(date[1]);
            var month = parseInt(date[2]);
            var year  = parseInt(date[3]);
            year = (year.toString().length == 2) ? (year < 50 ? '20' : '19').toString() + year : year;
        } else {
            var today = new Date;
            var day   = today.getDate();
            var month = today.getMonth() + 1;
            var year  = today.getFullYear();
        }
        setSheetGrid(container, day, this.value, input_year.value);
    }

    input_year.onkeyup = function() {
        var date_regexp = new RegExp('([0-9]{1,2})[\.\/-]([0-9]{1,2})[\.\/-]([0-9]{4}|\d{2})');
        if (date = date_regexp.exec(input.value)) {
            var day   = parseInt(date[1]);
            var month = parseInt(date[2]);
            var year  = parseInt(date[3]);
            year = (year.toString().length == 2) ? (year < 50 ? '20' : '19').toString() + year : year;
        } else {
            var today = new Date;
            var day   = today.getDate();
            var month = today.getMonth() + 1;
            var year  = today.getFullYear();
        }
        setSheetGrid(container, day, select_month.value, this.value);
    }
    //select_month.cssFloat = 'none';
    
    for (var i in CALENDAR_MONTHS) {
        var option = document.createElement('OPTION');
        option.value = parseInt(i) + 1;
        option.innerHTML = CALENDAR_MONTHS[i];
        select_month.appendChild(option);
    }

    
    //create calendar
    /*var select_year = document.createElement('SELECT');
    for (var i = CALENDAR_YEAR_FROM; i <= CALENDAR_YEAR_TO; i ++) {
        var option = document.createElement('OPTION');
        option.value = i;
        option.innerHTML = i;
        select_year.appendChild(option);
    }*/
    
    input_year.type = 'text';
    input_year.size = 4;
    input_year.maxLenth = 4;
    //input_year.style.cssFloat = 'none';

    var grid = document.createElement('TABLE');
    grid_container.appendChild(grid);

    grid.className = CALENDAR_GRID_CLASS_NAME;
    
    //calendar head
    var grid_head = grid.createTHead();
    
    var grid_head_row = document.createElement('TR');
    grid_head.appendChild(grid_head_row);
    
    for (var i in CALENDAR_DAYS) {
        var grid_cell = document.createElement('TH');
        grid_head_row.appendChild(grid_cell);
        grid_cell.innerHTML = CALENDAR_DAYS[i].short_name;
        grid_cell.className = (CALENDAR_DAYS[i].holiday) ? CALENDAR_CELL_HOLIDAY_CLASS_NAME : CALENDAR_CELL_REGDAY_CLASS_NAME;
    }
    
    var grid_body = document.createElement('TBODY');
    grid.appendChild(grid_body);
    
    var today = new Date;
    var day   = today.getDate();
    var month = today.getMonth() + 1;
    var year  = today.getFullYear();
    setSheetGrid(container, day, month, year);
}

function setSheetGrid(calendar, day, month, year)
{
    var grid = calendar.getElementsByTagName('TABLE')[0];
    
    var day_of_week = weekday(1, month, year);
    var days_in_month = (month == 2) ? (leap_year(year) ? 29 : 28) : days_in_months[month];
    
    if (!day_of_week) {
        //for sunday
        day_of_week = 7;
    } else {
        day_of_week ++;
    }
    
    var select_month = calendar.getElementsByTagName('SELECT')[0];
    select_month.value = month;
    
    var input_year = calendar.getElementsByTagName('INPUT')[0];
    input_year.value = year;
    
    //calendar body
    var grid_body = grid.tBodies[0].cloneNode(false);
    grid.replaceChild(grid_body, grid.tBodies[0]);
    
    var grid_body_row = grid_body.insertRow(0)
    
    for (var i = 1; i < day_of_week - 1; i ++) {
        var grid_body_cell = grid_body_row.insertCell(grid_body_row.cells.length);
        grid_body_cell.innerHTML = '&nbsp;';
        grid_body_cell.className = CALENDAR_CELL_CLASS_NAME;
    }
    
    var today = new Date;
    var t_day   = today.getDate();
    var t_month = today.getMonth() + 1;
    var t_year  = today.getFullYear();

    for (var i = 1; i <= days_in_month; i ++) {
        if ((i + day_of_week - 2) % 7 == 1) {
            delete(grid_body_row);
            var grid_body_row = grid_body.insertRow(grid.rows.length - 1);
        }
        
        var grid_body_cell = grid_body_row.insertCell(grid_body_row.cells.length);
        grid_body_cell.innerHTML = i;

        if (day == i) {
            grid_body_cell.className = CALENDAR_CELL_CLASS_NAME + '-current';
        } else {
            grid_body_cell.className = CALENDAR_CELL_CLASS_NAME;
            grid_body_cell.onmouseover = function () {this.className = CALENDAR_CELL_CLASS_NAME + '-hover';};
            grid_body_cell.onmouseout = function () {this.className = CALENDAR_CELL_CLASS_NAME;};
        }
        if (t_year == year && t_month == month && t_day == i) {
            grid_body_cell.style.borderColor = 'red';
            grid_body_cell.style.borderWidth = '2px';
            grid_body_cell.style.borderStyle = 'solid';
        }
        grid_body_cell.onclick = function () {
            var input = document.getElementById(calendar.id.replace('calendar_', ''));
            input.value = format_date(this.innerHTML, select_month.value, input_year.value);
            setSheetGrid(calendar, this.innerHTML, select_month.value, input_year.value);
        };
    }

    i = (days_in_month + day_of_week - 1) % 7;
    if (!i) {
        i = 7;
    }

    if (i > 1) {
        for (; i < 7; i ++) {
            var grid_body_cell = grid_body_row.insertCell(grid_body_row.cells.length);
            grid_body_cell.innerHTML = '&nbsp;';
            grid_body_cell.className = CALENDAR_CELL_CLASS_NAME;
        }
    }
    document.getElementById(calendar.id.replace('calendar_', '')).onclick();
}

// calendar input
function startCalendars()
{
    var inputs = document.getElementsByTagName('INPUT');
    for (var i = 0; i < inputs.length; i ++) {
        if (inputs[i].className && inputs[i].className == CALENDAR_INPUT_CLASS_NAME) {
            setCalendar(inputs[i]);
        }
    }
}

function setCalendar(input)
{
    input.onclick = function() {
        hide_calendar = true;
        showCalendar(this, document.getElementById('calendar_' + this.id));
    }
    
    input.onkeypress = function() {
        hide_calendar = true;
        showCalendar(this, document.getElementById('calendar_' + this.id));
    }
    
    input.onblur = function() {
        if (hide_calendar) {
            hideCalendar(document.getElementById('calendar_' + this.id));
        }
    }

    var container = document.createElement('DIV');
    input.parentNode.insertBefore(container, input.nextSibling ? input.nextSibling : input);
    container.className = CALENDAR_CONTAINER_CLASS_NAME;
    container.id = 'calendar_' + input.id;
    container.onmouseover = function() {
        hide_calendar = false;
    }
    
    container.onmouseout = function() {
        hide_calendar = true;
    }
    
    var input_pos = getElementPosition(input);
    container.style.left = input_pos.x + 'px';
    container.style.top = (input_pos.y + input.offsetHeight) + 'px';
    //container.style.width = input.offsetWidth + 'px';

    var date_container = document.createElement('DIV');
    container.appendChild(date_container);
    date_container.className = CALENDAR_DATE_CONTAINER_CLASS_NAME;
    
    var grid_container = document.createElement('DIV');
    container.appendChild(grid_container);
    grid_container.className = CALENDAR_GRID_CONTAINER_CLASS_NAME;
    
    //date picker
    var select_month = document.createElement('SELECT');
    date_container.appendChild(select_month);

    var input_year = document.createElement('INPUT');
    date_container.appendChild(input_year);

    select_month.onchange = function() {
        var date_regexp = new RegExp('([0-9]{1,2})[\.\/-]([0-9]{1,2})[\.\/-]([0-9]{4}|\d{2})');
        if (date = date_regexp.exec(input.value)) {
            var day   = parseInt(date[1]);
            var month = parseInt(date[2]);
            var year  = parseInt(date[3]);
            year = (year.toString().length == 2) ? (year < 50 ? '20' : '19').toString() + year : year;
        } else {
            var today = new Date;
            var day   = today.getDate();
            var month = today.getMonth() + 1;
            var year  = today.getFullYear();
        }
        setGrid(container, day, this.value, input_year.value);
    }

    input_year.onkeyup = function() {
        var date_regexp = new RegExp('([0-9]{1,2})[\.\/-]([0-9]{1,2})[\.\/-]([0-9]{4}|\d{2})');
        if (date = date_regexp.exec(input.value)) {
            var day   = parseInt(date[1]);
            var month = parseInt(date[2]);
            var year  = parseInt(date[3]);
            year = (year.toString().length == 2) ? (year < 50 ? '20' : '19').toString() + year : year;
        } else {
            var today = new Date;
            var day   = today.getDate();
            var month = today.getMonth() + 1;
            var year  = today.getFullYear();
        }
        setGrid(container, day, select_month.value, this.value);
    }
    //select_month.cssFloat = 'none';
    
    for (var i in CALENDAR_MONTHS) {
        var option = document.createElement('OPTION');
        option.value = parseInt(i) + 1;
        option.innerHTML = CALENDAR_MONTHS[i];
        select_month.appendChild(option);
    }

    
    //create calendar
    /*var select_year = document.createElement('SELECT');
    for (var i = CALENDAR_YEAR_FROM; i <= CALENDAR_YEAR_TO; i ++) {
        var option = document.createElement('OPTION');
        option.value = i;
        option.innerHTML = i;
        select_year.appendChild(option);
    }*/
    
    input_year.type = 'text';
    input_year.size = 4;
    input_year.maxLenth = 4;
    //input_year.style.cssFloat = 'none';
    
    var btn_close = document.createElement('INPUT');
    btn_close.type = 'button';
    date_container.appendChild(btn_close);
    btn_close.value = 'x';
    btn_close.onclick = function () {
        hideCalendar(container);
    }
    btn_close.className = 'close';

    var grid = document.createElement('TABLE');
    grid_container.appendChild(grid);

    grid.className = CALENDAR_GRID_CLASS_NAME;
    
    //calendar head
    var grid_head = grid.createTHead();
    
    var grid_head_row = document.createElement('TR');
    grid_head.appendChild(grid_head_row);
    
    for (var i in CALENDAR_DAYS) {
        var grid_cell = document.createElement('TH');
        grid_head_row.appendChild(grid_cell);
        grid_cell.innerHTML = CALENDAR_DAYS[i].short_name;
        grid_cell.className = (CALENDAR_DAYS[i].holiday) ? CALENDAR_CELL_HOLIDAY_CLASS_NAME : CALENDAR_CELL_REGDAY_CLASS_NAME;
    }
    
    var grid_body = document.createElement('TBODY');
    grid.appendChild(grid_body);
    
}

function setGrid(calendar, day, month, year)
{
    var grid = calendar.getElementsByTagName('TABLE')[0];
    
    var day_of_week = weekday(1, month, year);
    var days_in_month = (month == 2) ? (leap_year(year) ? 29 : 28) : days_in_months[month];
    
    if (!day_of_week) {
        //for sunday
        day_of_week = 7;
    } else {
        day_of_week ++;
    }
    
    var select_month = calendar.getElementsByTagName('SELECT')[0];
    select_month.value = month;
    
    var input_year = calendar.getElementsByTagName('INPUT')[0];
    input_year.value = year;
    
    //calendar body
    var grid_body = grid.tBodies[0].cloneNode(false);
    grid.replaceChild(grid_body, grid.tBodies[0]);
    
    var grid_body_row = grid_body.insertRow(0)
    
    for (var i = 1; i < day_of_week - 1; i ++) {
        var grid_body_cell = grid_body_row.insertCell(grid_body_row.cells.length);
        grid_body_cell.innerHTML = '&nbsp;';
        grid_body_cell.className = CALENDAR_CELL_CLASS_NAME;
    }
    
    var today = new Date;
    var t_day   = today.getDate();
    var t_month = today.getMonth() + 1;
    var t_year  = today.getFullYear();

    for (var i = 1; i <= days_in_month; i ++) {
        if ((i + day_of_week - 2) % 7 == 1) {
            delete(grid_body_row);
            var grid_body_row = grid_body.insertRow(grid.rows.length - 1);
        }
        
        var grid_body_cell = grid_body_row.insertCell(grid_body_row.cells.length);
        grid_body_cell.innerHTML = i;
        grid_body_cell.className = CALENDAR_CELL_CLASS_NAME;
        grid_body_cell.onmouseover = function () {this.className = CALENDAR_CELL_CLASS_NAME + '-hover';};
        grid_body_cell.onmouseout = function () {this.className = CALENDAR_CELL_CLASS_NAME;};
        if (t_year == year && t_month == month && t_day == i) {
            grid_body_cell.style.borderColor = 'red';
            grid_body_cell.style.borderWidth = '2px';
            grid_body_cell.style.borderStyle = 'solid';
        }

        grid_body_cell.onclick = function () {
            var input = document.getElementById(calendar.id.replace('calendar_', ''));
            input.value = format_date(this.innerHTML, select_month.value, input_year.value);
            hideCalendar(calendar);
        };
    }

    i = (days_in_month + day_of_week - 1) % 7;
    if (!i) {
        i = 7;
    }

    if (i > 1) {
        for (; i < 7; i ++) {
            var grid_body_cell = grid_body_row.insertCell(grid_body_row.cells.length);
            grid_body_cell.innerHTML = '&nbsp;';
            grid_body_cell.className = CALENDAR_CELL_CLASS_NAME;
        }
    }
}

function showCalendar(input, calendar)
{
    var date_regexp = new RegExp('([0-9]{1,2})[\.\/-]([0-9]{1,2})[\.\/-]([0-9]{4}|\d{2})');
    if (date = date_regexp.exec(input.value)) {
        var day   = parseInt(date[1]);
        var month = parseInt(date[2]);
        var year  = parseInt(date[3]);
        year = (year.toString().length == 2) ? (year < 50 ? '20' : '19').toString() + year : year;
    } else {
        var today = new Date;
        var day   = today.getDate();
        var month = today.getMonth() + 1;
        var year  = today.getFullYear();
    }
    setGrid(calendar, day, month, year);
    calendar.style.visibility = 'visible';
    calendar.style.left = 10 + input.offsetWidth + getElementPosition(input).x + 'px';
    calendar.style.top = getElementPosition(input).y + 'px';
    //calendar.style.width = input.offsetWidth + 'px';
}

function hideCalendar(calendar)
{
    calendar.style.visibility = 'hidden';
}

