﻿
SAT.Tracks = function () {

    /* Private */

    /* Properties */

    var cmp = {};





    /* Methods */

    var init = function () {

        /* Constructor */
        initTracks();
    };


    var initTracks = function () {

        $('.viewTracks').click(function () {

            var tracks = $(this).parents('tr').next();

            if ($(this).hasClass('closed')) {
                tracks.show();
                $(this).removeClass('closed').addClass('open');
            }
            else {
                tracks.hide();
                $(this).removeClass('open').addClass('closed');
            }
            return false;
        });

        TVI.event('.buttonPlus', 'click', function () {
            var that = $(this);
            TVI.ajax({

                url: '/handlers/SAT.aspx/addToBasket',
                data: {
                    'format': $(this).parents('tr').find('select').val(),
                    'id': $(this).parents('tr').attr('id')
                },
                success: function (d) {
                    // If it succeSATully adds we get the basket back from the server
                    that.closest('tr').find('.error').remove();
                    TVI.fireEvent('basketUpdated', d);
                },
                failure: function (d) {
                    that.closest('td').prev().append('<div class="error">' + d.errors[0].message + "</div>");
                    // If the track was already added we will only get an error back so we have to go fetch the basket separately
                    if (d.errors[0].code == "exist") {
                        TVI.ajax({

                            url: '/handlers/SAT.aspx/getBasket',
                            success: function (d) {
                                TVI.fireEvent('basketUpdated', d);
                            }
                        });
                    }
                }

            });

        });

        TVI.event('.addCredit', 'click', function () {
            var that = $(this);
            TVI.ajax({

                url: '/handlers/SAT.aspx/addCredit',
                data: {
                    'id': $(this).parents('.inner').attr('id').substring(6)
                },
                success: function (d) {
                    // If it succeSATully adds we get the basket back from the server
                    that.closest('.inner').find('.error').remove();
                    TVI.fireEvent('basketUpdated', d);
                },
                failure: function (d) {
                    that.closest('.inner').append('<div class="error">' + d.errors[0].message + "</div>");
                }

            });

        });

        TVI.event('.addVoucher', 'click', function () {
            var that = $(this);
            TVI.ajax({

                url: '/handlers/SAT.aspx/addVoucher',
                data: {
                    'amount': $(this).parents('.voucher').find('.voucherImage').data('originalPrice')
                },
                success: function (d) {
                    // If it succeSATully adds we get the basket back from the server
                    that.closest('.inner').find('.error').remove();
                    TVI.fireEvent('basketUpdated', d);
                },
                failure: function (d) {
                    that.closest('.inner').append('<div class="error">' + d.errors[0].message + "</div>");
                }

            });

        });


        TVI.event('.delete', 'click', function () {

            var item;
            if ($(this).parents('.discTrack').length > 0) {
                item = $(this).parents('.discTrack').attr('id') + '-' + $(this).parents('.disc').attr('id');
            }
            else if ($(this).attr('id').indexOf('disc') == 0) {
                item = $(this).attr('id');
            }
            else {
                item = $(this).parents('.item').attr('id');
            }

            TVI.ajax({

                url: '/handlers/SAT.aspx/removeFromBasket',
                data: {
                    'item': item
                },
                success: function (d) {
                    TVI.fireEvent('basketUpdated', d);
                },
                failure: function (d) {

                }

            });

        });

        TVI.event('#yourBasketBox .edit', 'click', function () {
            var item = $(this).closest('.item');
            $('#popup select option').attr('selected', '');
            $('#popup select option[value="' + item.find('.format').html() + '"]').attr('selected', 'selected');
            $('#popup #popupExistingDisc').val(item.attr('id').substring(4));
            $('#popup #chooseFormatForm-discName-control').val(item.find('.name').html());
            SAT.showPopup();
        });

        $('.trackOptions').change(function () {
            if ($(this).val() == 'new') {
                $('#popupWrapper').show();
            }
        });



        TVI.event('.up,.down', 'click', function () {

            TVI.ajax({

                url: '/handlers/SAT.aspx/moveTrack',
                data: {
                    'disc': $(this).parents('.disc').attr('id').substring(4),
                    'direction': $(this).attr('class'),
                    'track': $(this).parents('.discTrack').attr('id').substring(9)
                },
                success: function (d) {
                    TVI.fireEvent('basketUpdated', d);
                },
                failure: function (d) {

                }

            });

        });


        // Functions for changing track format in basket
        TVI.event('#yourBasketBox .format', 'click', function () {

            // Keep track of the clicked item index and type
            $('#formatChooseBasketItemIndex').val($(this).attr('data-item-index'));
            $('#formatChooseBasketItemType').val($(this).attr('data-item-type'));
            $('#formatChooseBasketForm-format-control').empty();

            switch ($(this).attr('data-item-type')) {

                case 'album':
                    $('#formatChooseBasketForm-format-control').append('<option value="mp3+g">MP3+G</option>');
                    $('#formatChooseBasketForm-format-control').append('<option value="mp4">MP4</option>');
                    $('#formatChooseBasketForm-format-control').append('<option value="cdg">CD+G</option>');
                    $('#formatChooseBasketForm-format-control').append('<option value="dvd">DVD</option>');
                    break;
                case 'disc':
                    $('#formatChooseBasketForm-format-control').append('<option value="cdg">CD+G</option>');
                    $('#formatChooseBasketForm-format-control').append('<option value="dvd">DVD</option>');
                    break;
                case 'download':
                    $('#formatChooseBasketForm-format-control').append('<option value="mp3+g">MP3+G</option>');
                    $('#formatChooseBasketForm-format-control').append('<option value="mp4">MP4</option>');
                    break;
            }
            $('#formatChooseBasketForm-format-control').val($(this).text());

            // Show popup

            $('#formatChooseBasketOverlay').fadeTo(0, 0);
            $('#formatChooseBasketOverlay').show();
            $('#formatChooseBasketPopup').fadeTo(0, 0);
            $('#formatChooseBasketPopup').show();

            $('#formatChooseBasketOverlay').fadeTo('slow', 0.8);
            $('#formatChooseBasketPopup').fadeTo('slow', 1);

        });

        TVI.event('#formatChooseBasketPopup .close a', 'click', function () {

            $('#formatChooseBasketOverlay').fadeOut();
            $('#formatChooseBasketPopup').fadeOut();
        });

        TVI.event('#formatChooseBasketPopup .buttonContinue a', 'click', function () {
            TVI.ajax({

                url: '/handlers/SAT.aspx/changeFormat',
                data: {
                    'index': $('#formatChooseBasketItemIndex').val(),
                    'type': $('#formatChooseBasketItemType').val(),
                    'format': $('#formatChooseBasketForm-format-control').val()
                },
                success: function (d) {
                    $('#formatChooseBasketOverlay').hide();
                    $('#formatChooseBasketPopup').hide();

                    TVI.fireEvent('basketUpdated', d);
                },
                failure: function (d) {

                }

            });
        });



        // Show/hide video player
        TVI.event('.videoPlayer .close a', 'click', function () {
            $('.player').html('');
            $(this).closest('tr').remove();
        });

        TVI.event('.buttonPlay a', 'click', function () {
            if ($(this).closest('tr').next().find('.videoPlayer').length > 0) {
                return;
            }
            $('.player').html('');
            $('.videoPlayer').closest('tr').remove();
            var thisTrack = $(this).closest('tr');
            var fadedEnding = thisTrack.attr('data-fadedending').replace('True', 'Yes').replace('False', 'No');
            var duration = thisTrack.attr('data-duration');
            var key = thisTrack.attr('data-key');
            var manufacturer = thisTrack.attr('data-manufacturer');
            var code = thisTrack.attr('data-code');
            thisTrack.after('<tr><td class="firstCell lastCell videoPlayer" style="text-align: center" colspan="5"><img src="/i/loading.gif" /></td></tr>');
            thisTrack.next().find('.videoPlayer').load('/player.aspx?code=' + code + '&key=' + key + '&duration=' + duration + '&faded=' + fadedEnding + '&manufacturer=' + manufacturer);

        });

        $('.trackOptions').change(function () {
            if ($(this).val() == 'new') {
                $('#popupWrapper').show();
                // Tell the popup to add a track to the disc when complete
                $('#popupAddTrack').val($(this).parents('tr').attr('id'));
            }
        });


    }


    TVI.addListener('basketUpdated', function (d) {

        if (location.href.indexOf('checkout') > 0) {
            TVI.ajax({

                url: '/handlers/SAT.aspx/basketValid',
                data: {},
                success: function (d) {
                    location.reload(true);
                },
                failure: function (d) {
                    window.location = '/';
                }

            });
        }
        $('#basketContainer').html(d.basket);
        if (d.newDisc != undefined) {
            $('.trackOptions').append('<option selected="selected" value="disc' + d.discID + '">Add To ' + d.newDisc + '</option>');
        }
        $('.currency li a').removeClass('selected');
        $('.currency .' + SAT.currency + ' a').addClass('selected');
        SAT.setPrices();


    }, this);


    TVI.ready(init);


    return cmp;


} ();
