var timeid = null;
var hhid = null;
var ssid = null;

$(function() {
    $('#endtype').bind("change", function() {
        switchEndType();
    });
    $('#periodicitytype').bind("change", function() {
        switchRepeatType();
    });
    $("#repeattime").timeSelect();
    $('#calendartable div').bind("click", function() {
        $('#periodicityerror').remove();
        if ($(this).hasClass('checked')) {
            $(this).removeClass('checked');
        }
        else {
            $(this).addClass('checked');
        }
    }).attr('unselectable', 'on').select(function() { return false; }).css({
        '-moz-user-select': '-moz-none',
        '-o-user-select': 'none',
        '-khtml-user-select': 'none',
        '-webkit-user-select': 'none',
        'user-select': 'none'
    });
    
    $('#weekdaystable div').bind("click", function() {
        $('#periodicityerror').remove();
        if ($(this).hasClass('checked')) {
            $(this).removeClass('checked');
        }
        else {
            $(this).addClass('checked');
        }
    }).attr('unselectable', 'on').select(function() { return false; }).css({
        '-moz-user-select': '-moz-none',
        '-o-user-select': 'none',
        '-khtml-user-select': 'none',
        '-webkit-user-select': 'none',
        'user-select': 'none'
    });
});

$(document).ready(switchEndType).ready(switchRepeatType);

function formAfterSubmit(form) {
    if (customValidate())
        form.submit();
}

function customValidate() {
    var serialize = "";
    var mode = $('#periodicitytype').val();
    var selector;
    if (mode == "2") {
        selector = "#weekdaystable div.checked";
    }
    else if (mode == "3") {
        selector = "#calendartable div.checked";
    }
    else if (mode == "4") {
        selector = "#annuallydays ul li";
    }
    if (selector) {
        $(selector).each(function(i, e) {
        if (serialize.length > 0)
            serialize += ',';
        serialize += $(e).attr('id').replace('_','.');
        });
        $('#periodicityvalue').val(serialize);
    }
    if (selector && !serialize) {
        $('#periodicitydiv').append('<label id="periodicityerror" class="error">' + TaskRepeatResources.PeriodRequired + '</label>');
        $('#periodicityerror:first').focus();
        return false;
    }
    var endtypeselect = $('#endtype').val();
    switch (endtypeselect) {
        case "1":
            {
                $('#enddate').val("");
                $('#maxrepeats').val("");
                break;
            }
        case "2":
            {
                $('#maxrepeats').val("");
                break;
            }
        case "3":
            {
                $('#enddate').val("");
                break;
            }
    }
    $('.save,.saveandreturn').attr('disabled', true);
    return true;
}

function switchEndType() {
    var type = $('#endtype').val();
    switch (type) {
        //never
        case "1":
            {
                $('#enddate').addClass('ignore').hide();
                $('#maxrepeats').addClass('ignore').hide();
                break;
            }
        //by date
        case "2":
            {
                $('#maxrepeats').addClass('ignore').hide();
                $('#enddate').removeClass('ignore').show();
                break;
            }
        //by max repeats
        case "3":
            {
                $('#enddate').addClass('ignore').hide();
                $('#maxrepeats').removeClass('ignore').show();
                break;
            }
        default:
            {
                $('#enddate').addClass('ignore').hide();
                $('#maxrepeats').addClass('ignore').hide();
            }
    }
}

function switchRepeatType() {
    $('#periodicityerror').remove();
    var type = $('#periodicitytype').val();
    switch (type) {
        //daily 
        case "1":
            {
                $('#annuallydays').addClass('ignore').hide();
                $('#monthdays').addClass('ignore').hide();
                $('#weekdays').addClass('ignore').hide();
                break;
            }
        //weekly
        case "2":
            {
                $('#monthdays').addClass('ignore').hide();
                $('#annuallydays').addClass('ignore').hide();
                $('#weekdays').removeClass('ignore').show();
                break;
            }
        //monthly
        case "3":
            {
                $('#weekdays').addClass('ignore').hide();
                $('#annuallydays').addClass('ignore').hide();
                $('#monthdays').removeClass('ignore').show();
                break;
            }
        //annually
        case "4":
            {
                $('#weekdays').addClass('ignore').hide();
                $('#monthdays').addClass('ignore').hide();
                $('#annuallydays').removeClass('ignore').show();
                break;
            }
        default:
            {
                $('#annuallydays').addClass('ignore').hide();
                $('#monthdays').addClass('ignore').hide();
                $('#weekdays').addClass('ignore').hide();
            }
    }
}

function generateTasks() {
    var count = $('#taskscount').val();
    var ruleid = $('#id').val();
    $.getJSON(base + 'taskrepeat.ivp/generatetasks/', { count: count, ruleid: ruleid, date: new Date().toString() }, function(result) {
        reloadMaxRepeats();
        if (result.hasOwnProperty('IsOK') && !result.IsOK) {
            alert(result.Description);
        }
        else {
            alert(result);
        }
        $('#actionholder').hide();
    });
    return false;
}

function customCloseForm(url) {
    if (formchanged == true && !confirm(FormResources.FormChanged)) return;
if (url == 'close') {
self.close();
return;
}
if (url) {
document.location.href = url;
return;
}
if ($('#ref').size()) {
    document.location.href = (base + 'task.ivp/view/' + $('#ref').val());
    return;
}
var f = $('form:first');
var action = f.attr('action');
var controller = action.substr(0, action.indexOf('/'));
var href = base + controller + '/list';
document.location.href = (href);
return;
}

function reloadMaxRepeats() {
    var type = $('#endtype').val();
    if (type != "3") return;
    var url = base + "taskrepeat.ivp/reloadmaxrepeats";
    $.getJSON(url, { ruleid: $('#id').val(), date: new Date().toString() }, function(result) {
        $('#maxrepeats').val(result);
    });
}

function addDate() {
    var day = $('#periodicityday').val();
    var month = $('#periodicitymonth').val();
    var date = day + '.' + month;
    if (parseInt(day, 10) <= 31 && parseInt(day, 10) > 0 && parseInt(month, 10) <= 12 && parseInt(month, 10) > 0 && $('li#annually' + date.replace('.', '_')).size() == 0) {
        $('#annuallydays ul').append('<li id=\"' + date.replace('.', '_') + '\">' + date + '<span class=\"hover\"><a onclick=\"removeDate($(this)); return false;\"><img src=\"img/trash.gif\"><a/></span></li>');
        $('#periodicityerror').remove();
    }
}

function removeDate(obj) {
    var li = obj.closest('li');
    li.remove();
}