﻿/********** SETUP **********/
var _editable = false;
var _animSpeed = 'fast';
//$('tbody tr:odd').addClass('a');

$.ajaxSetup({
    type: 'POST',
    data: '{}',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    async: true,
    cache: false,
    error: function (xhr, ajaxOptions, thrownError) {
        _busy(false);
        alert('Hmm... something wrong\n\n' + xhr.statusText + '\n\n' + thrownError);
    }
});

$('#tr-c').html($('#main table tbody tr').length);

_refreshLinks();

/********** EVENT BINDINGS **********/
$('#tr #n a').live('click', function (e) {
    e.preventDefault();
    _busy(true);
    if ($('#tr .win').length && $('#tr .win').data('o') && $('#tr .win').data('o').url == $(this).attr('href')) {
        $('#tr .win').hide(_animSpeed, function () {
            $('#tr .win').remove();
        });
    }
    else {
        $('#tr .win').remove();
        if ($(e.target).data('o').type == 1) {
            $.ajax({
                data: '{"filename":"' + $(this).attr('href').substr(1) + '"}',
                url: 'service.asmx/GetHtml',
                success: function (r) {
                    $(r.d)
                        .data('o', $(e.target).data('o'))
                        .appendTo('#tr')
                        .show(_animSpeed);
                    if ($('#login-win #username').length > 0) {
                        $('#login-win #username').focus();
                    }
                    else if ($('#add-win #artist').length > 0) {
                        $('#add-win #artist').focus();
                    }
                    _busy(false);
                }
            });
        }
        else {
            $.ajax({
                url: 'service.asmx/' + $(this).attr('href').substr(1),
                success: function (r) {
                    if ($(e.target).data('o') && $(e.target).data('o').cb && $(e.target).data('o').cb.length) {
                        eval($(e.target).data('o').cb)(r.d);
                    }
                    _refreshLinks();
                    _busy(false);
                }
            });
        }
    }
});
$('.win #cancel,.win #cancel-2').live('click', function (e) {
    e.preventDefault();
    $(e.target).parents('.win').hide(_animSpeed, function () {
        $(e.target).parents('.win').remove();
    });
});
$('#login-win #submit').live('click', function (e) {
    e.preventDefault();
    _busy(true);
    $.ajax({
        url: 'service.asmx/Login',
        data: '{ "username":"' + $('#username').val() + '","password":"' + $('#password').val() + '"}',
        success: function (r) {
            $('#tr .win').remove();
            if (!r.d) {
                alert('Unauthorized');
            }
            _editable = r.d;
            _refreshLinks();
            _busy(false);
        }
    });
});
$('#add-win #submit').live('click', function (e) {
    e.preventDefault();
    _busy(true);
    $.ajax({
        url: 'service.asmx/AddItem',
        data: '{ "artist":"' + $('#artist').val() + '","album":"' + $('#album').val() + '","typeid":"' + $('#type').val() + '","year":"' + $('#year').val() + '","labelid":"' + $('#label').val() + '","comments":"' + $('#comment').val() + '"}',
        success: function (r) {
            if (r.d) {
                $('#tr .win').remove();
                _refreshLinks();
                _refreshItemList();
            }
            _busy(false);
        }
    });
});
$('#addlabel').live('click', function (e) {
    e.preventDefault();
    _busy(true);
    $.ajax({
        data: '{"filename":"' + $(this).attr('href').substr(1) + '"}',
        url: 'service.asmx/GetHtml',
        success: function (r) {
            $(r.d)
                .appendTo('#tr')
                .css(
                    {
                        'left': ($(e.target).offset().left+200)+'px',
                        'top': $(e.target).offset().top+'px'
                    }
                    )
                .show(_animSpeed);
            if ($('#labelname').length > 0) {
                $('#labelname').focus();
            }
            _busy(false);
        }
    });
});
$('#add-label-win #submit-2').live('click', function (e) {
    e.preventDefault();
    _busy(true);
    var _val = $('#labelname').val();
    $.ajax({
        url: 'service.asmx/AddLabel',
        data: '{ "labelName":"' + _val + '"}',
        success: function (r) {
            $('#tr #add-label-win #cancel-2').click();
            if (!r.d) {
                _refreshLinks();
            }
            else {
                $.ajax({
                    url: 'service.asmx/GetLabels',
                    success: function (r) {
                        $('#label').html('');
                        $(r.d).each(function (i, o) {
                            $('<option>')
                                .attr('value', o.id)
                                .html(o.name + '&nbsp;(' + o.count + ')')
                                .appendTo('#label');
                        });
                        $('#label option:contains(' + _val.toString() + ')').attr('selected', 'selected');
                        _val = null;
                    }
                });
            }

            _busy(false);
        }
    });    
});
$('#top #album-info #edit').live('click', function (e) {
    e.preventDefault();
    _busy(true);
    $('.win #cancel,.win #cancel-2').click();
    $.ajax({
        data: '{"filename":"' + $(this).attr('href').substr(1) + '"}',
        url: 'service.asmx/GetHtml',
        success: function (r) {
            $(r.d)
                .appendTo('#tr')
                .show(_animSpeed);

            var _selectedObject = $('#top #album-info').data('o');
            $('#edit-win #itemid').val(_selectedObject.id);
            $('#edit-win #artist').val(_selectedObject.artist);
            $('#edit-win #album').val(_selectedObject.album);
            $('#edit-win #type option:contains(' + _selectedObject.type + ')').attr('selected', 'selected');
            $('#edit-win #year').val(_selectedObject.year);
            $('#edit-win #label option:contains(' + _selectedObject.label + ')').attr('selected', 'selected');
            $('#edit-win #comment').val(_selectedObject.comment);
            if ($('#edit-win #artist').length > 0) {
                $('#edit-win #artist').focus();
            }

            _busy(false);
        }
    });
});
$('#edit-win #submit').live('click', function (e) {
    e.preventDefault();
    _busy(true);
    $.ajax({
        url: 'service.asmx/UpdateItem',
        data: '{ "itemid":"' + $('#itemid').val() + '","artist":"' + $('#artist').val() + '","album":"' + $('#album').val() + '","typeid":"' + $('#type').val() + '","year":"' + $('#year').val() + '","labelid":"' + $('#label').val() + '","comments":"' + $('#comment').val() + '"}',
        success: function (r) {
            if (r.d) {
                $('#edit-win #cancel').click();
                _refreshLinks();
                _refreshItemList();
            }
            _busy(false);
        }
    });
});
$('.win input,.win select').live('keypress', function (e) {
    if (e.keyCode == 13) {
        $('#submit,#submit-2', $(e.target).parents('.win')).click();
    }
});
$('#main table tbody tr').live('click', function (e) {
    _busy(true);
    $('.win #cancel,.win #cancel-2').click();
    if ($('#top #album-info').length < 1) {
        $('<div>')
            .attr('id', 'album-info')
            .appendTo($('#top'));
    }
    else {
        $('#top #album-info')
            .hide();
    }
    var _objectByRow = _getObjectByRow($(this));
    $('#top #album-info').data('o', _objectByRow);
    $.ajax({
        url: 'service.asmx/GetAlbumInfo',
        data: '{"artist":"' + _objectByRow.artist + '","album":"' + _objectByRow.album + '"}',
        success: function (r) {
            $('#top #album-info')
                .html('');
            $('<img>')
                .attr('src', 'ca_l.gif')
                .data('o', r.d)
                .appendTo('#top #album-info');
            if (r.d.imageurl_large && r.d.imageurl_large.length > 0) {
                $('#top #album-info img').click(function (e) {
                    $('<img>')
                        .attr('src', $(this).data('o').imageurl_large)
                        .addClass('xlarge')
                        .css(
                            {
                                'top': ($(this).position().top - 126) + 'px',
                                'left': ($(this).position().left - 126) + 'px'
                            }
                            )
                        .click(function () {
                            $('#top #album-info img.xlarge')
                                .hide()
                                .remove();
                        })
                        .appendTo('#top #album-info');
                });
            }
            $('#top #album-info img').attr('src', r.d.imageurl && r.d.imageurl.length > 0 ? r.d.imageurl : 'ca_n.gif');
            $('<div>')
                .appendTo('#top #album-info');
            $('<h2>')
                .html(r.d.artist)
                .appendTo('#top #album-info div');
            $('<h3>')
                .html(r.d.album)
                .appendTo('#top #album-info div');
            $('<p>')
                .html('released:&nbsp;' + (r.d.releasedate && r.d.releasedate.length > 0 ? r.d.releasedate : 'n/a'))
                .appendTo('#top #album-info div');
            $('<p>')
                .html('more info:&nbsp;')
                .appendTo('#top #album-info div');
            if (r.d.url && r.d.url.length) {
                $('<a>')
                    .text(r.d.url)
                    .attr('href', r.d.url)
                    .click(function (e) {
                        e.preventDefault();
                        window.open($(this).attr('href'));
                    })
                    .appendTo('#top #album-info div p:last');
            }
            else {
                $('#top #album-info div p:last').html($('#top #album-info div p:last').html() + 'n/a');
            }
            if (r.d.tracks.length > 0) {
                $('<ol>')
                    .appendTo('#top #album-info div');
                $.each(r.d.tracks, function (i, o) {
                    $('<li>')
                        .html(o)
                        .appendTo('#top #album-info div ol');
                });
            }
            $('<p>')
                .html((_editable ? '<a href="/edit-item" id="edit">edit</a>' : '') + '<a href="#">close</a>')
                .attr('id', 'close')
                .click(function (e) {
                    e.preventDefault();
                    $('#top #album-info').hide();
                })
                .appendTo('#top #album-info');
            $('#top #album-info').show();
            _objectByRow = null;
            _busy(false);
        }
    });
});

var _searchTimeout;
$('#srch').keyup(function (e) {
    if (_serchKeyCheck(e.keyCode)) {
        if (_searchTimeout) {
            clearTimeout(_searchTimeout);
        }
        _searchTimeout = setTimeout(function () {
            _busy(true);
            // THE FOLLOWING STRANGE APPROACH IS NEEDED, TO MAKE THE BUSY-THINGY APPEAR
            setTimeout(function () {
                _searchEval();
            }, 50);
        }, e.keyCode == 13 ? 150 : 1500);
    }
});

function _serchKeyCheck(k) {
    return (k == 8 || k == 13 || k == 32 || (k >= 48 && k <= 57) || (k >= 65 && k <= 90) || (k >= 96 && k <= 105) || (k >= 186 && k <= 192) || (k >= 219 && k <= 222) || k == 226);
}

function _searchEval() {    
    var _regex = new RegExp('(' + $('#srch').val() + ')', 'gi');
    var _visible = false;

    $('#main table tbody tr').each(function (tri, tro) {
        _visible = false;
        $('td', $(tro)).each(function (tdi, tdo) {
            $(tdo).text($(tdo).text().replace(/<\/?i>/gi, ''));
            if (_regex.test($(tdo).text())) {
                $(tdo).html($(tdo).text().replace(_regex, '<i>$1</i>'));
                _visible = true;
            }
        });
        if (_visible) {
            $(tro).show();
        }
        else {
            $(tro).hide();
        }
    });
    $('#main table tbody tr:visible:even').removeClass('a');
    $('#main table tbody tr:visible:odd').addClass('a');
    _regex = _visible = null;

    var _visibleCount = $('#main table tbody tr:visible').length;
    var _totalCount = $('#main table tbody tr').length;
    $('#tr-c').html(_visibleCount == _totalCount ? (_totalCount) : (_visibleCount + '/' + _totalCount));
    _visibleCount = _totalCount = null;
    _busy(false);
}

function _refreshLinks() {
    $('#tr #n a').remove();
    $.ajax({
        url: 'service.asmx/GetLinks',
        success: function (r) {            
            _editable = false;
            $(r.d).each(function (i, o) {
                $('<a />')
                    .data('o', o)
                    .attr('href', o.url)
                    .html(o.text)
                    .appendTo($('#n'));
                if (o.status == 1) {
                    _editable = true;
                }
            });
        }
    });
}

function _getObjectByRow(o) {
    var _tdCollection = $('td', o);
    var _newObject =
        {
            id: o.attr('id').substr(1),
            artist: $(_tdCollection[0]).text(),
            album: $(_tdCollection[1]).text(),
            label: $(_tdCollection[2]).text(),
            type: $(_tdCollection[3]).text(),
            year: $(_tdCollection[4]).text(),
            comment: $(_tdCollection[5]).text()
        };
    return _newObject;
}

function _refreshItemList() {
    $.ajax({
        url: 'service.asmx/GetCompleteList',
        success: function (r) {
            $('#main table tbody').html(r.d);
            $('#tr-c').html($('#main table tbody tr').length);
        }
    });
}

function _createWindow(id, head, fill) {
    $('.win #cancel,.win #cancel-2').click();
    $('<div>')
        .addClass('win')
        .attr('id', id)
        .appendTo('#tr');
    $('<h1>')
        .text(head)
        .appendTo('.win');

    var _contentContainer = $('<div>').appendTo('.win');
    if (fill) {
        fill.apply(this,new Array(_contentContainer));
    }    

    $('<div>')
        .appendTo('.win');
    $('<a>')
        .attr('href', '/cancel')
        .attr('id', 'cancel')
        .text('close')
        .appendTo('.win div:last');

    if (($('.win').height() + ($(window).height() / 4)) > ($(window).height() - 50)) {
        $(_contentContainer)
            .css(
                {
                    'max-height': ($(window).height() - ($(window).height() / 4) - 100) + 'px',
                    'overflow-y': 'scroll',
                    'margin-right': '-4px',
                    'padding-right': '4px'
                }
            );
    }
    $('.win').show(_animSpeed);
}

function populatePlaylist(p) {
    _createWindow(
        'playlist',
        'Last 10 albums heard',
        function (_contentContainer) {
            $(p).each(function (i, o) {
                var _div = $('<div>').appendTo(_contentContainer);
                $('<img>')
                    .data('o', o)
                    .attr('src', 'ca_l.gif')
                    .appendTo(_div);
                $('img', _div).attr('src', o.imageurl && o.imageurl.length > 0 ? o.imageurl : 'ca_n.gif');
                if (o.imageurl_large && o.imageurl_large.length) {
                    $('img', _div).click(function (e) {
                        $('.win img.xlarge')
                            .hide()
                            .remove();
                        $('<img>')
                            .attr('src', $(this).data('o').imageurl_large)
                            .addClass('xlarge')
                            .css(
                                {
                                    'top': (($(this).offset().top + 300 + 50) > $(window).height() ? $(this).position().top - (300 - 34) : $(this).position().top) + 'px',
                                    'left': ($(this).position().left) + 'px'
                                }
                                )
                            .click(function () {
                                $('.win img.xlarge')
                                    .hide()
                                    .remove();
                            })
                        .appendTo(_contentContainer);
                    });
                }
                $('<h2>')
                    .text(o.artist)
                    .appendTo(_div);
                $('<h3>')
                    .text(o.album)
                    .appendTo(_div);
                _div = null;
            });
        });
}

function populateChecklist(p) {
    _createWindow(
        'checklist',
        'Checklist',
        function (_contentContainer) {
            $(p).each(function (i, o) {
                var _div = $('<div>').appendTo(_contentContainer);
                var _h2 = $('<h2>')
                    .text(o.artist)
                    .appendTo(_div);
                if (o.albums.length) {
                    $('<a>')
                        .click(function (e) {
                            e.preventDefault();
                            $('.win div div div').hide();
                            $('div', $(this).parents('div').get(0)).show();
                        })
                        .attr('href', '/checklist/' + o.artist)
                        .text('expand')
                        .appendTo(_h2);
                    $(o.albums).each(function (ai, ao) {
                        var _parent = $('<div>').appendTo(_div);
                        $('<img>')
                            .attr('src', 'ca_l.gif')
                            .appendTo(_parent);
                        $('img', _parent).attr('src', ao.imageurl && ao.imageurl.length ? ao.imageurl : 'ca_n.gif');
                        $('<a>')
                            .html('<h3>' + ao.album + '</h3>')
                            .attr('href', ao.url)
                            .click(function (e) {
                                e.preventDefault();
                                window.open($(this).attr('href'));
                            })
                            .appendTo(_parent);
                        _parent = null;
                    });
                }
                if (_editable) {
                    $('<a>')
                        .click(function (e) {
                            e.preventDefault();
                            $.ajax({
                                data: '{"artist":"' + $(e.target).data('o').artist + '"}',
                                url: 'service.asmx/DeleteFromChecklist',
                                success: function (r) {
                                    if (r.d) {
                                        $(e.target).parents('div:first').remove();
                                    }
                                }
                            });
                        })
                        .data('o', o)
                        .attr('href', '#')
                        .text('delete')
                        .appendTo('h2', _div);
                }
                _h2 = null;
                _div = null;
            });
        });
}

function populateLatest(p) {
    _createWindow(
        'latest',
        'Latest additions',
        function (_contentContainer) {
            $(p).each(function (i, o) {
                var _div = $('<div>').appendTo(_contentContainer);
                $('<img>')
                    .data('o', o)
                    .attr('src', 'ca_l.gif')
                    .appendTo(_div);
                $('img', _div).attr('src', o.imageurl && o.imageurl.length > 0 ? o.imageurl : 'ca_n.gif');
                if (o.imageurl_large && o.imageurl_large.length) {
                    $('img', _div).click(function (e) {
                        $('.win img.xlarge')
                            .hide()
                            .remove();
                        $('<img>')
                            .attr('src', $(this).data('o').imageurl_large)
                            .addClass('xlarge')
                            .css(
                                {
                                    'top': (($(this).offset().top + 300 + 50) > $(window).height() ? $(this).position().top - (300 - 34) : $(this).position().top) + 'px',
                                    'left': ($(this).position().left) + 'px'
                                }
                                )
                            .click(function () {
                                $('.win img.xlarge')
                                    .hide()
                                    .remove();
                            })
                        .appendTo(_contentContainer);
                    });
                }
                $('<h2>')
                    .text(o.artist)
                    .appendTo(_div);
                $('<h3>')
                    .text(o.album)
                    .appendTo(_div);
                _div = null;
            });
        });
}

function _busy(b) {
    if (b) {
        if ($('#busy').length < 1) {
            $('<div>')
                .attr('id', 'busy')
                .html('<img src="l.gif" alt="" />very busy...')
                .appendTo('body');
        }
    }
    else {
        $('#busy').remove();
    }
}
