/**
 * Показывает попап с контекстной помощью.
 *
 */
/*function doc_help() {
    alert($('#help-contents').html());
}*/


$(document).ready(function() 
{
    
    /**
     * Disable/enable "state" select.
     * 
     * @var boolean state
     */
    function state_disable(state) 
    {
        // set select disable property
        $('#state').attr('disabled', state);
        
        // add div label contents
        if (state) {
            $('#state').attr('selectedIndex', 0);
            
            label = '<label for="state">State:</label>';
            label += '<br/><span class="small">optional</span>';
        } else {
            label = '<label class="bold" for="state">State:</label>';
        }
        $('#state').parent().prev().html(label);
    }
    
    function getLicensureValues() 
    {
        $.getJSON('?module=user&service=licensure&country=' 
            + $('#country option:selected').val(),
            function(response) 
            {
                var target = $('#licensure');
                target.empty();
                
                i=0;
                $.each(response, function(value, name) {
                    target.append('<option value="' + value + '">' + name + '</option>');
                    // set initial value
                    if (value == $('#licensure_init').val()) {
                        target.attr('selectedIndex', i);
                    }
                    i++;
                });
            });
    }
    
    /**
     * Control "State" and "Licensure" depending on country.
     *
     */
     $('#country').change(function() {
        state_disable('US' == $('#country option:selected').val() ? false : true);
        
        if ('physician' == $('#user_role').val()) {
            getLicensureValues();
        }
     }).change();
    
});



/**
 * Печатает документ с подтверждением.
 *
 */
function doc_print() {
    doc_confirm(function(){window.print();});
}

/**
 * Показывает PDF-версию с подтверждением.
 *
 */
function doc_pdf(element) {
    doc_confirm(function(){element.submit();});
}

/**
 * Выводит подтверждение.
 *
 */
function doc_confirm(action) {
    var text = 'HouseDoc cannot secure or guarantee the privacy of messages or documents once they are printed or saved to your computer';
    if (window.confirm(text)) {
        action.apply();
    }
}

/** Подтверждения при кликах по элементам интерфейса **/

$.extend(Confirm, {
    'patient':   'Do you really want to delete patient from your contact list?',
    'physician': 'Do you really want to delete physician your contact list?',
    'personnel': 'Do you really want to delete personnel from your office?',
    'leave':     'Confirm request to separate from Office'
});

/** Финты со списками **/

var Select = {

    AutoFill: function(selector) {
        var elements = $(selector);
        elements.change(function() {
            var index = this.selectedIndex;
            if (index > 0) {
                elements.each(function() {
                    if (this.selectedIndex <= 0) {
                        this.selectedIndex = index;
                    }
                });
            }
        }).change();
    },

    Unify: function(selector) {

        var elements = $(selector);

        function getSelected() {
            var selected = new Array;
            elements.each(function() {
                if (this.selectedIndex > 0) {
                    selected.push($(this).val());
                }
            });
            return selected;
        }

        function setOptions(element, values, selected) {
            var current = $(element).val()
                options = element.options;
            // очищаем опции списка
            options.length = 0;
            $.each(values, function() {
                if ($.inArray(this[0], selected) < 0 || current == this[0]) {
                    var option = new Option();
                    option.value = this[0];
                    option.text = this[1];
                    options.add(option);
                }
            })
            // выставляем опцию с исходным значение выбранной в списке
            $(element).val(current)
        }

        if (elements.length > 1) {
            var values = new Array;
            $.each(elements.get(0).options, function(option) {
                values.push([this.value, this.text]);
            });
            elements.change(function() {
                elements.each(function() {
                    setOptions(this, values, getSelected());
                });
            }).change();
        }
    }
}

/** Фильтр списка услуг при составлении сообщения пациентом **/
function filter_services(services, available) {

    $('#to').change(function () {
        var physician = $(this).val();
        var service = $('#service').get(0), options = service.options,
            selected = options[service.selectedIndex].value;
        options.length = 0;
        if (physician in available) {
            $.each(available[physician], function(id, price) {
                var option = new Option();
                option.value = id;
                option.text = services[id] + (0 != price && null != price ? ' ($' + price + ')' : '');
                option.selected = id == selected;
                options.add(option);
            });
        }
    }).change();
}

/** Фильтр списка услуг при составлении сообщения пациентом **/
function edit_services() {

    var physician = $('#_physician').val();

    var hide = function() {
        $('.description').hide();
    }

    $('.link-description').click(function() {
        $(this).hide();
        $(this).parent().next().show();
    });

    $('.description-cancel').click(function() {
        hide();
        $('.link-description').show();
    });

    $('.description-submit').click(function() {
        var parent = $(this).parent(),
            index = parent.find('input').val(),
            value = parent.find('textarea').val();

        $.post((location.search ? location.search + '&' : '?') + 'module=user&service=description',
        {
            index: index,
            description: value
        },
        function(response) {
            $('#action-' + index).text(response.filled ? 'Edit' : 'Add');
            $('.description').hide();
            $('.link-description').show();
        }, 'json');
    });
};
