$(document).ready(function() {
    function getChannel() {
        $("div#loading").text("Yükleniyor...");
        $('#channel').empty();
        $.ajax({
            url: 'ajax/channel',
            data: "country=" + $('#country').val() + "&category=" + $('#category').val(),
            type: 'post',
            dataType: 'json',
            success: function (j) {
                var options = [], i = 0, o = null;
                for (i = 0; i < j.length; i++) {
                    if(i == 0) {
                        o = document.createElement("OPTION");
                        o.value = 0;
                        o.text = 'Kanal Seçiniz';
                        $('#channel').get(0).options[i] = o;
                    }
                    o = document.createElement("OPTION");
                    o.value = typeof j[i] == 'object' ? j[i]['id'] : j[i];
                    o.text = typeof j[i] == 'object' ? j[i]['label'] : j[i];
                    $('#channel').get(0).options[i + 1] = o;
                }
                setTimeout(function () {
                    $('#channel')
                        .find('option:first')
                        .attr('selected', 'selected')
                        .parent('select')
                        .trigger('change');
                }, 0);
                $("div#loading").text("");
            },
            error: function (xhr, desc, er) {
                // add whatever debug you want here.
                alert("an error occurred");
            }
        });
    }
    $('#category').change(function(){
        getChannel();
    });

    $('#country').change(function(){
        getChannel();
    });

    $('#channel').change(function(){
        if($('#channel').val() != 0) {
            window.location.href = 'tv/izle/' + $('#channel').val();
        }
    });
});
