$(loadLists);

function loadLists() {
    if (typeof cache == 'undefined') {
        cache = new Cache();
    }
    if (typeof requests == 'undefined') {
        requests = new RequestsController();
    }
    // global: query, video, user
    var $elementSelectList = $('#elementSelectList');
    var $elementSelectAction = $('#elementSelectAction');
    var $selectList = $('#selectList');
    var $selectAction = $('#selectAction');
    $selectList.html('');
    $selectAction.html('');
    // if (typeof video != 'undefined' || typeof query != 'undefined') {
        requests.add('/list/get', {}, function(data) {
            // alert(data.toSource());
            // alert(find.toSource());
            var lists = parseLists(data.lists);
            var featuredLists = lists.featuredLists;
            var myLists = lists.myLists;
            var selected = '';
            var disabled = '';
            if (!user.logged_in) {
                 disabled = ' disabled="disabled"';
            }
            var edit = 'View';
            var item = 'This Video';
            if (typeof video == 'undefined') {
                var item = 'All Results';
            }
            $selectList.append('<option value="">All Videos</option>');
            $selectList.append('<option disabled="disabled"></option>');
            $selectList.append('<option disabled="disabled">Featured Lists:</option>');
            for (var i in featuredLists) {
                if (typeof query != 'undefined' && query.l == featuredLists[i].listId) {
                    $elementSelectList.html('List: ' + featuredLists[i].title);
                    selected = ' selected';
                } else {
                    selected = '';
                }
                $selectList.append('<option value="' + featuredLists[i].listId + '"' + selected + '>&nbsp;&nbsp;' + featuredLists[i].title + '</option>');
            }
            $selectList.append('<option disabled="disabled"></option>');
            $selectList.append('<option disabled="disabled">My Lists:</option>');
            for (var i in myLists) {
                if (typeof query != 'undefined' && query.l == myLists[i].listId) {
                    $elementSelectList.html('List: ' + myLists[i].title);
                    selected = ' selected';
                } else {
                    selected = '';
                }
                $selectList.append('<option value="' + myLists[i].listId + '"' + selected + '>&nbsp;&nbsp;' + myLists[i].title + '</option>');
            }
            $selectAction.append('<option value="actions">List Actions...</option>');
            $selectAction.append('<option disabled="disabled"></option>');
            if ($selectList.val()) {
                $selectAction.append('<option disabled="disabled">List: ' + getListTitleById(data.lists, $selectList.val()) + '</option>');
                var listData = getListDataById(data.lists, $selectList.val());
                //alert (listData.toSource());
                if (listData.published == 0 || user.admin) {
                    edit = 'View/Edit';
                }
                $selectAction.append('<option value="edit">' + edit + ' List Info...</option>');
                if (user.admin) {
                    if (getListTitleById(myLists, $selectList.val())) {
                        // make sure no list is featured that has the same name as an already featured list
                        if (!listTitleExists(featuredLists, getListTitleById(myLists, $selectList.val()))) {
                            $selectAction.append('<option value="publish">Add List to Featured Lists</option>');
                        }
                    } else {
                        $selectAction.append('<option value="republish">Put List on Top of Featured Lists</option>');
                        $selectAction.append('<option value="unpublish">Remove List from Featured Lists</option>');
                    }
                }
                $selectAction.append('<option disabled="disabled"></option>');
            }
            if (typeof query != 'undefined' || typeof video != 'undefined') {
                $selectAction.append('<option value="add"' + disabled + '>Add ' + item + ' to List...</option>');
                $selectAction.append('<option value="remove"' + disabled + '>Remove ' + item + ' from List...</option>');
                $selectAction.append('<option disabled="disabled"></option>');
            }
            $selectAction.append('<option value="create"' + disabled + '>Create New List...</option>');
            if (myLists.length == 0) {
                disabled = ' disabled="disabled"';
            }
            if (myLists.length > 0) {
                $selectAction.append('<option value="delete"' + disabled + '>Delete List...</option>');
            }
        });
    /*
    } else {
        $elementSelectList.addClass('disabled').html('List...');
        $elementSelectAction.addClass('disabled').html('List Actions...');
        $selectList.hide();
        $selectAction.hide();
    }
    */
}
function selectList() {
    document.location.href = '/find?l=' + $('#selectList').val();
}
function selectAction() {
    var list = $('#selectList').val();
    var action = $('#selectAction').val();
    var actionText = $("option[value='" + action + "']").html();
    $('#elementSelectAction').html(actionText);
    // uncomment this and crash safari
    // $('#dialogContent').html('');
    if (action == 'edit') {
        requests.add('/list/get', {}, function(data) {
            var listData = getListDataById(data.lists, list);
            // alert(listData.toSource());
            requests.add('/list/videos', {listId: query.l}, function(data) {
                if (actionText.substr(0, 9) == 'View/Edit') {
                    var disabled = '';
                } else {
                    var disabled = ' disabled="disabled"';
                }
                var html = '<div style="float: left; width: 128px; height: 24px; text-align: right">';
                if (!disabled) {
                    html += 'Name';
                }
                html += '</div>';
                html += '<div style="float: left; width: 400px; height: 24px; margin-left: 8px">';
                html += '<input id="title" style="width: 396px" value="' + listData.title + '"' + disabled + ' />';
                html += '</div>';
                if (!disabled) {
                    html += '<div style="float: left; width: 128px; height: 24px">';
                    html += '<div id="elementSelectImage" class="enabled element elementSelect">Select Image...</div>';
                    html += '<select id="selectImage" class="enabled transparent" style="position: relative; top: -16px" onChange="selectImage()">';
                    if (data.videos.length) {
                        for (var i in data.videos) {
                            if (data.videos[i].id == listData.iconId) {
                                var selected = ' selected="selected"';                        
                            } else {
                                var selected = '';
                            }
                            html += '<option value="' + data.videos[i].id + '"' + selected + '>' + data.videos[i].title + '</option>';
                        }
                    } else {
                        html += '<option disabled="disabled">No Videos in List</option>';                    
                    }
                    html += '</select>';
                    html += '</div>';
                    html += '<div style="float: left; width: 400px; height: 24px; margin-left: 8px">';
                    html += 'Description';
                    html += '</div>';
                }
                if (!listData.iconId) {
                    html += '<div id="image" style="float: left; width: 128px; height: 128px">';
                } else {
                    html += '<div id="image" style="float: left; width: 128px; height: 128px; background: url(/' + listData.iconId + '/poster.128.jpg)">';
                }
                // html += '<img src="/static/images/corners128.png" />';
                html += '</div>';
                html += '<div id="descriptionBox" style="float: left; width: 400px; height: 128px; margin-left: 8px">';
                html += '<textarea id="description" style="width: 396px; height: 124px"' + disabled + '>';
                html += listData.description;
                html += '</textarea>';
                html += '</div>';
                /*
                html += '<div style="float: left; width: 128px; height: 24px; background: red">';
                html += '<div id="elementSelectView" class="enabled element elementSelect">View as Icons</div>';
                html += '<select id="selectView" class="enabled transparent" style="position: relative; top: -16px" onChange="selectView()">';
                html += '<option value="icon">View as Icons</option>';
                html += '<option value="map">View as Map</option>';
                html += '</select>';
                html += '</div>';
                */
                if (!disabled) {
                    var buttons = [
                        ['Save', function() {
                            $('.dialogButton').removeClass('enabled');
                            $('.dialogButton').addClass('disabled');
                            var parameters = {
                                listId: $('#selectList').val(),
                                title: $('#title').val(),
                                description: $('#description').val()
                            }
                            if ($('#selectImage').val()) {
                                parameters.iconId = $('#selectImage').val()
                            }
                            //alert(parameters.toSource())
                            requests.add('/list/get', {}, function(data) {
                                var lists = parseLists(data.lists);
                                var myLists = lists.myLists;
                                if (!parameters.title) {
                                    var html = $('#dialogContent').html();
                                    $('#dialogContent').html('Please enter a list name.');
                                    setTimeout(function() {
                                        $('#dialogContent').html(html);
                                        $('.dialogButton').removeClass('disabled');
                                        $('.dialogButton').addClass('enabled');
                                    }, 1000);
                                } else if (parameters.title != listData.title && listTitleExists(myLists, parameters.title)) {
                                    var html = $('#dialogContent').html();
                                    $('#dialogContent').html('List name already exists.');
                                    setTimeout(function() {
                                        $('#dialogContent').html(html);
                                        $('.dialogButton').removeClass('disabled');
                                        $('.dialogButton').addClass('enabled');
                                    }, 1000);
                                } else {
                                    requests.add('/list/edit', parameters, function() {
                                        loadLists();
                                        $('#dialogContent').html('Your changes have been saved.');
                                        setTimeout(function() {
                                            dialog.close();
                                        }, 1000);
                                    });
                                }
                            });
                        }],
                        /*
                        ['Preview', function() {
                            var html = $('#descriptionBox').html();
                            var preview = '<div id="textCell" class="cell">';
                            preview += '<div class="border cell400">';
                            preview += '<div class="corner topLeft"/>';
                            preview += '<div class="center" style="width: 384px" />';
                            preview += '<div class="corner topRight"/>';
                            preview += '</div>';
                            preview += '<div class="content" style="text-align: left; height: 96px">';
                            preview += '<div><span style="font-weight: bold">' + $('#title').val() + '</span></div>';
                            preview += '<div style="margin-top: 8px">' + $('#description').val() + '</div>';
                            preview += '</div>';
                            preview += '<div class="border cell400">';
                            preview += '<div class="corner bottomLeft"/>';
                            preview += '<div class="center" style="width: 384px"/>';
                            preview += '<div class="corner bottomRight"/>';
                            preview += '</div>';
                            preview += '</div>';
                            $('#descriptionBox').html(preview);
                            setTimeout(function() {
                                $('#descriptionBox').html(html);
                            }, 3000);
                        }],
                        */
                        ['Cancel', function() { dialog.close() }]
                    ];
                } else {
                    var buttons = [
                        ['Close', function() { dialog.close() }]
                    ];
                }
                var dialog = new Dialog(actionText, html, buttons, 552, 276);
                dialog.load();
            });
        });
    } else if (action == 'publish') {
        requests.add('/list/publish', {listId: list}, function() {
            loadLists();
        });
    } else if (action == 'republish') {
        requests.add('/list/unpublish', {listId: list}, function() {
            requests.add('/list/publish', {listId: list}, function() {
                loadLists();
            });
        });
    } else if (action == 'unpublish') {
        requests.add('/list/unpublish', {listId: list}, function() {
            loadLists();
        });
    } else if (action == 'add') {
        createDialog('add');
    } else if (action == 'remove') {
        createDialog('remove');
    } else if (action == 'create') {
        var dialog = new Dialog('Create New List', $('<input/>').attr({
            id: 'dialogInput'
        }).css({
            width: '260px'
        }), [
            ['Create', function() {
                $('.dialogButton').removeClass('enabled');
                $('.dialogButton').addClass('disabled');
                var title = $('#dialogInput').val();
                requests.add('/list/get', {}, function(data) {
                    var lists = parseLists(data.lists);
                    var myLists = lists.myLists;
                    if (!title) {
                        var html = $('#dialogContent').html();
                        $('#dialogContent').html('Please enter a list name.');
                        setTimeout(function() {
                            $('#dialogContent').html(html);
                            $('.dialogButton').removeClass('disabled');
                            $('.dialogButton').addClass('enabled');
                        }, 1000);
                    } else if (listTitleExists(myLists, title)) {
                        var html = $('#dialogContent').html();
                        $('#dialogContent').html('List name already exists.');
                        setTimeout(function() {
                            $('#dialogContent').html(html);
                            $('.dialogButton').removeClass('disabled');
                            $('.dialogButton').addClass('enabled');
                        }, 1000);
                    } else {
                        requests.add('/list/add', {title: title}, function() {
                            loadLists();
                            $('#dialogContent').html('New list created.');
                            setTimeout(function() {
                                dialog.close();
                            }, 1000);
                        });
                    }
                });
            }],
            ['Cancel', function() { dialog.close() }]
        ], 280, 100);
        dialog.load(function() {
            $('#dialogInput').focus();
        });
    } else if (action == 'delete') {
        createDialog('delete');
    }
    $('#elementSelectAction').html('List Actions...');
    $('#selectAction').val('actions');
}
function selectDialogList() {
    $('#elementSelectDialogList').html($("option[value='" + $('#selectDialogList').val() + "']").html());
}
function selectImage() {
    $('#image').css({
        background: 'url(/' + $('#selectImage').val() + '/poster.128.jpg)'
    })
}
function createDialog(name) {
    var strings = {
        add: {
            button: 'Add',
            url: '/list/add',
            success: 'Video(s) Added to List'
        },
        remove: {
            button: 'Remove',
            url: '/list/remove',
            success: 'Video(s) Removed from List'
        },
        'delete': {
            button: 'Delete',
            url: '/list/remove',
            success: 'List Deleted'
        }
    }
    var list = $('#selectList').val();
    var action = $('#selectAction').val();
    var actionText = $("option[value='" + action + "']").html().replace('...', '');
    var html = '<div id="elementSelectDialogList" class="enabled element264 elementSelect264">Select List...</div>';
    html += '<select id="selectDialogList" class="enabled transparent" onChange="selectDialogList()"></select>';
    requests.add('/list/get', {}, function(data) {
        var lists = parseLists(data.lists);
        var featuredLists = lists.featuredLists;
        var myLists = lists.myLists;
        var parameters = {};
        if (name != 'delete') {
            if (typeof video != 'undefined') {
                parameters.videoId = video.id;
            } else {
                parameters.f = query.f;
                parameters.q = query.q;
                parameters.l = query.l;
            }
        }
        var dialog = new Dialog(actionText, html, [
            [strings[name].button, function() {
                if ($('#selectDialogList').val() != 'select') {
                    $('.dialogButton').removeClass('enabled');
                    $('.dialogButton').addClass('disabled');
                    parameters.listId = $('#selectDialogList').val();
                    requests.add(strings[name].url, parameters, function() {
                        loadLists();
                        $('#dialogContent').html(strings[name].success);
                        setTimeout(function() {
                            dialog.close();
                        }, 1000);
                    });
                }
            }],
            ['Cancel', function() { dialog.close() }]
        ], 280, 100);
        dialog.load(function() {
            var $selectList = $('#selectDialogList');
            $selectList.append('<option selected="selected" value="select">Select List...</option>');
            $selectList.append('<option disabled="disabled"></option>');
            $selectList.append('<option disabled="disabled">Featured Lists:</option>');
            for (var i in featuredLists) {
                if (user.admin) {
                    $selectList.append('<option value="' + featuredLists[i].listId + '">&nbsp;&nbsp;' + featuredLists[i].title + '</option>');
                }
            }
            $selectList.append('<option disabled="disabled"></option>');
            $selectList.append('<option disabled="disabled">My Lists:</option>');
            for (var i in myLists) {
                $selectList.append('<option value="' + myLists[i].listId + '">&nbsp;&nbsp;' + myLists[i].title + '</option>');
            }
        });
    });
}
function parseLists(lists) {
    var featuredLists = [];
    var myLists = [];
    for (var i in lists) {
        var list = lists[i];
        if (list.published) {
            featuredLists.push(list);
        } else {
            myLists.push(list);
        }
    }
    featuredLists.sort(sortLists);
    myLists.sort(sortLists);
    return {
        featuredLists: featuredLists,
        myLists: myLists
    };
}
function sortLists(x, y) {
    return x.title.toLowerCase() > y.title.toLowerCase();
}
function getListDataById(lists, id) {
    for (var i in lists) {
        if (lists[i].listId == id) {
            return lists[i];
        }
    }
    return false;    
}
function getListTitleById(lists, id) {
    for (var i in lists) {
        if (lists[i].listId == id) {
            return lists[i].title;
        }
    }
    return false;    
}
function listTitleExists(lists, title) {
    for (var i in lists) {
        if (lists[i].title == title) {
            return true;
        }
    }
    return false;    

}
