// LOADED VIDEO
var _LOADED_VIDEO_ID = null;

var _SELECTED_FOR_USER = false;

var task = null;
var locked = false;

var LAPSE_TIME_LIMIT = 10;


function utf8_encode ( argString ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: sowberry
    // +    tweaked by: Jack
    // +   bugfixed by: Onno Marsman
    // +   improved by: Yves Sucaet
    // +   bugfixed by: Onno Marsman
    // *     example 1: utf8_encode('Kevin van Zonneveld');
    // *     returns 1: 'Kevin van Zonneveld'

    var string = (argString+'').replace(/\r\n/g, "\n").replace(/\r/g, "\n");

    var utftext = "";
    var start, end;
    var stringl = 0;

    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;

        if (c1 < 128) {
            end++;
        } else if((c1 > 127) && (c1 < 2048)) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc !== null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }

    if (end > start) {
        utftext += string.substring(start, string.length);
    }

    return utftext;
}


function runVideo(fVideo, vName, id) {
    locked = true;

    var embed = '' +
                '<object classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" id="video" width="320" height="310">' +
                '    <param name="url" value="' + fVideo + '" />' +
                '    <param name="src" value="' + fVideo + '" />' +
                '    <param name="showcontrols" value="true" />' +
                '    <param name="autostart" value="true" />' +
                '    ' +
                '    <!--[if !IE]>-->' +
                '    <object id="video" type="video/x-ms-wmv" data="' + fVideo + '" width="320" height="310">' +
                '        <param name="src" value="' + fVideo + '" />' +
                '        ' +
                '        <param name="controller" value="true" />' +
                '        <param name="autostart" value="true" />' +
                '    </object>' +
                '    <!--<![endif]-->' +
                '</object>' +
                '';
    try {
        Ext.getDom('video').FileName = '';
        Ext.getDom('video').url = '';
        Ext.getDom('video').src = '';

        Ext.getDom('show-video').innerHTML = '';
    }
    catch(e) {
        locked = false;
        return false;
    }

    _LOADED_VIDEO_ID = id;


    Ext.getDom('you-see').innerHTML = vName;
    Ext.getDom('show-video').innerHTML = embed;

    var marketURLVideo = PTJS_APPLICATION_SYSTEM_SITE_WS +  "index?showVideo=" + fVideo + "&nameVideo=" + utf8_encode(vName) + "&idVideo=" + id;
    Ext.getDom('url-location-text').value = marketURLVideo;

    var count = 1;
    var taskLapse = {
        run: function() {
            if(count==LAPSE_TIME_LIMIT) {
                Ext.TaskMgr.stop(taskLapse);

                locked = false;
            }

            count++;
        },

        interval: 1000
    };

    Ext.TaskMgr.start(taskLapse);
}

function viewRunTimeVideo() {
    if(locked==true) {
        return false;
    }

    var storeRunTime = new Ext.data.JsonStore({
        id: 'storeRunTime',
        autoLoad: true,
        url: 'index/runtime',
        root: 'results',
        fields: [
            'id',
            'videos_channels_id',
            'videos_id',
            'title',
            'view_date',
            'starter_hour',
            'finisher_hour',
            'daily',
            'weekly',
            'monthly',
            'week_day',
            'month_day',
            'description',
            'date_time_added',
            'active',
            'videos_name',
            'videos_video',
            'channels_title'
        ],

        listeners: {
            load: function () {
                var tmpStore = Ext.StoreMgr.lookup('storeRunTime');

                if(tmpStore && tmpStore.getTotalCount() > 0) {
                    var record = tmpStore.getAt(0);

                    //if(_LOADED_VIDEO_ID != record.data.videos_id) {
                          var fVideo = PTJS_APPLICATION_SYSTEM_PUBLIC_WS + 'files/videos/' + record.data.videos_video;
                          runVideo(fVideo, record.data.videos_name, record.data.videos_id);
                    //}
                }
            }
        }
    });
}

Ext.onReady(function() {
    Ext.QuickTips.init();

    Ext.getDom('about').onclick = function() {
        runVideo(PTJS_APPLICATION_SYSTEM_SITE_WS + "public/videos/about.wmv", "Sobre a Daqui TV", 0);
    }

    viewRunTimeVideo();

    // task
    task = {
        run: function() {
            var obj = Ext.getDom('video');

            try {
                var duration = obj.currentMedia.durationString;
                var position = obj.controls.currentPositionString || null;

                if(position==null) {
                    if(Ext.getDom('video').playState != 6) {
                        viewRunTimeVideo();
                    }
                }
            }
            catch(e) {

            }
        },

        interval: 30000
    };
    Ext.TaskMgr.start(task);

    var searchNow = function () {
        var valueSearch = Ext.getDom('input-search').value;

        if(valueSearch!="") {
            //messageStartTransaction();

            Ext.getCmp('channels_id').setValue(PTJS_HANDLE_OBJECTS_TREECOMBOBOX_ROOT_TEXT);

            var tmpStore = Ext.StoreMgr.lookup('store_videos_id');
            if(tmpStore) {
                tmpStore.reload({
                    params: {
                        name: valueSearch
                    }
                })
            }
        }
    };

    Ext.getDom('send-search').onclick = searchNow;
    Ext.getDom('input-search').onkeypress = function (e) {
        var evt = e || window.event;
        var key = evt.which || evt.keyCode;

        if(key == 13) {
            searchNow();
        }
    }

    var form = new Ext.form.FormPanel({
        id: 'form',
        title: '',
        labelWidth: 80,
        labelAlign: 'left',
        baseCls: 'x-plain',
        bodyStyle: 'padding:0px 0px 0px 0px; position:relative;',
        width: 364,
        height: 200,
        autoScroll: true,
        fileUpload: false,
        renderTo: 'channels',

        items: [
            /*
            new Ext.letti.TreeCombobox({
                id: 'channels_id',
                dataUrl: 'index/channelsnode',
                store: new Ext.data.SimpleStore({
                    fields:['id', 'title'],
                    data:[[]]
                }),
                allowBlank: true,
                fieldLabel: 'Canais',
                msgTarget: 'side',
                displayField: 'title',
                valueField:  'id',
                hideLabel: true,
                name: 'channels_id',
                hiddenName: 'channels_id_key',
                width: 353,
                maxHeight: 164,
                value: PTJS_HANDLE_OBJECTS_TREECOMBOBOX_ROOT_TEXT,

                listeners: {
                    select: function () {
                        //messageStartTransaction();

                        Ext.getCmp('videos_id').setValue('');
                        Ext.getDom('input-search').value = '';

                        var tmpStore = Ext.StoreMgr.lookup('store_videos_id');
                        if(tmpStore) {
                            tmpStore.reload({
                                params: {
                                    channels_id: Ext.getCmp('channels_id').hiddenField.value
                                }
                            })
                        }
                    }
                }
            }),
            */

            new Ext.form.ComboBox({
                store: new Ext.data.Store({
                    storeId: 'store_channels_id',
                    autoLoad: true,

                    proxy: new Ext.data.HttpProxy({
                        url: 'index/channels'
                    }),

                    reader: new Ext.data.JsonReader({
                        root: 'results',
                        totalProperty: 'total'
                    }, [
                        {name: 'id', mapping: 'id'},
                        {name: 'title', mapping: 'title'}
                    ])
                }),

                id: 'channels_id',
                mode: 'remote',
                valueField:  'id',
                displayField: 'title',
                hideLabel: true,
                name: 'channels_id',
                hiddenName: 'channels_id_key',
                fieldLabel: 'Canais',
                editable: false,
                emptyText: 'Escolha o Tema...',
                typeAhead: true,
                forceSelection: true,
                triggerAction: 'all',
                selectOnFocus: true,
                anchor: '95%',

                listeners: {
                    select: function () {
                        //messageStartTransaction();

                        Ext.getCmp('videos_id').setValue('');
                        Ext.getDom('input-search').value = '';

                        var tmpStore = Ext.StoreMgr.lookup('store_videos_id');
                        if(tmpStore) {
                            tmpStore.reload({
                                params: {
                                    channels_id: Ext.getCmp('channels_id').hiddenField.value
                                }
                            })
                        }
                    }
                }
            }),

            {
                xtype: "multiselect",
                fieldLabel: "Videos",
                hideLabel: true,
                id: "videos_id",
                name: "videos_id",

                store: new Ext.data.Store({
                    storeId: 'store_videos_id',
                    autoLoad: true,

                    proxy: new Ext.data.HttpProxy({
                        url: 'index/videos'
                    }),

                    reader: new Ext.data.JsonReader({
                        root: 'results',
                        totalProperty: 'total'
                    }, [
                        {name: 'id', mapping: 'id'},
                        {name: 'name', mapping: 'name'},
                        {name: 'video', mapping: 'video'}
                    ]),

                    listeners: {
                        load: function () {
                            Ext.MessageBox.hide();
                        }
                    }
                }),

                valueField: "id",
                displayField: "name",
                width: 342,
                height: 150,
                allowBlank: true,
                legend: "Videos",

                listeners: {
                    change: function (field, newValue, oldValue) {
                        var tmpStore = Ext.StoreMgr.lookup('store_videos_id');
                        var fieldValue = field.getValue();

                        var index = tmpStore.find('id', fieldValue, 0, false, true);

                        if(index > -1) {
                            var record = tmpStore.getAt(index);
                            var fVideo = PTJS_APPLICATION_SYSTEM_PUBLIC_WS + 'files/videos/' + record.data.video;

                            runVideo(fVideo, record.data.name, record.data.id);
                        }
                    }
                }
            }
        ]
    })

    if(showVideo!=null && idVideo!=null) {
        runVideo(showVideo, nameVideo, idVideo);

        showVideo = null;
        nameVideo = null;
        idVideo = null;
    }
});
