﻿
SAT = function () {

    /* Private */

    /* Properties */

    var cmp = {};





    /* Methods */

    var init = function () {

        /* Constructor */
        TVI.debug = false;

        TVI.Forms.handlerURL = '/handlers/';

        TVI.Data.defaultURL = '/handlers/data.aspx/query';

        initSearch();
        initLogin();
        initButtons();
        initPopup();
        initCurrency();
        initAutocomplete();
    };




    var initAutocomplete = function () {
        // $('#autoComplete').fadeTo(0, 0.95);
        var timeoutID = 0;
        var suggestionHighlighted = false;
        $('#searchForm-keywords-control').keyup(function (e) {

            // Is it an up or down arrow key?
            if (e.keyCode == 38 || e.keyCode == 40) {


                if (!$('#autoComplete').is(':visible')) {
                    $('#autoComplete').slideDown('fast');
                    return;
                }


                if ($('#autoComplete .selected').length = 0) {
                    // If we don't already have one selected, select the first or last
                    if (e.keyCode == 40) {
                        // Down
                        $('#autoComplete span:first').addClass('selected');
                    }
                    else {
                        // Up
                        $('#autoComplete span:last').addClass('selected');
                    }
                    return;
                }
                var currentlySelectedItem = $('#autoComplete .selected');
                var currentlySelectedIndex = $('#autoComplete span').index(currentlySelectedItem);
                if (e.keyCode == 40) {
                    // Down
                    currentlySelectedIndex = currentlySelectedIndex + 1;
                }
                else {
                    // Up
                    currentlySelectedIndex = currentlySelectedIndex - 1;
                }

                if (currentlySelectedIndex > $('#autoComplete span').length - 1) {
                    // If at the bottom, go to the top
                    currentlySelectedIndex = 0;
                }
                if (currentlySelectedIndex < 0) {
                    // If at the top, close the auto complete box
                    $('#autoComplete span').removeClass('selected');
                    $('#autoComplete').slideUp('fast');
                    suggestionHighlighted = false;
                    return;
                }

                // Actually select the item!
                $('#autoComplete span').removeClass('selected');
                $('#autoComplete span:eq(' + currentlySelectedIndex + ')').addClass('selected');
                suggestionHighlighted = true;
                return;

            }
            else if (e.keyCode == 13) {

                if (suggestionHighlighted) {
                    $('#searchForm-keywords-control').val($('#autoComplete .selected a').text());
                    keywordSearch();
                }
                else {
                    keywordSearch();
                }

            }
            else if ($('#searchForm-keywords-control').val().length > 1) {

                if (timeoutID != 0) {
                    clearTimeout(timeoutID)
                }
                timeoutID = setTimeout(function () {
                    TVI.ajax({
                        url: '/Handlers/SAT.aspx/getAutoComplete',
                        data: {
                            value: sanitised($('#searchForm-keywords-control').val()),
                            type: $('#searchForm-choose-control').val()
                        },
                        success: function (d) {

                            if (!$('#autoComplete').is(':visible')) {
                                $('#autoComplete').slideDown('fast');
                            } else {
                                // check that they haven't already selected one, don't want it replacing the selected one!
                                if ($('#autoComplete .selected').length < 1) {
                                    $('#autoComplete').empty();


                                    for (var i = 0; i < d.rows.length; i++) {
                                        $('#autoComplete').append('<span><a href="#">' + d.rows[i].Title + '</a></span>');
                                    }
                                }
                            }



                        }
                    });
                }, 100);
                $('#searchForm-keywords-control').blur(function () {
                    if (!suggestionHighlighted) {
                        $('#autoComplete').slideUp('fast');
                    }
                });

                $('#autoComplete a').live('click', function () {
                    $('#searchForm-keywords-control').val($(this).text());
                    keywordSearch();
                    return false;
                });
            }

        })
    }




    var initCurrency = function () {

        // Get current currency
        TVI.ajax({
            url: '/Handlers/SAT.aspx/getCurrency',
            success: function (data) {
                SAT.currency = data.currency;
                $('.currency li a').removeClass('selected');
                $('.currency .' + SAT.currency + ' a').addClass('selected');
                $('.currencyLabel').html(data.currency + 's');
                // Once we have the selected currenct run currency conversion
                SAT.setPrices();
            }
        });

        //Setup currency coversion buttons function
        $('.currency a').live('click', function () {
            $('.currency li a').removeClass('selected');
            $(this).addClass('selected');
            //Work out which button was pressed
            SAT.currency = $(this).parent().attr('class');
            $('.currencyLabel').html(SAT.currency + 's');

            $.ajax({
                type: "POST",
                url: '/Handlers/SAT.aspx/setCurrency',
                data: '{"currency":"' + SAT.currency + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) { }
            });
            //Run the actual conversion
            SAT.setPrices();
            return false;
        });

    };

    var initButtons = function () {

        $('#chooseFormatBox .chooseFormatInner a').click(function () {

            switch ($(this).parent().attr('class')) {

                case "button22 buttonMp3g":
                    TVI.ajax({

                        url: '/handlers/SAT.aspx/setDefaultFormat',
                        data: {
                            'format': 'mp3+g'
                        },
                        success: function (d) {
                            $('.trackOptions option').attr('selected', '');
                            $('.trackOptions option[value="mp3+g"]').attr('selected', 'selected');
                        }
                    });
                    break;

                case "button22 buttonMp4":
                    TVI.ajax({

                        url: '/handlers/SAT.aspx/setDefaultFormat',
                        data: {
                            'format': 'mp4'
                        },
                        success: function (d) {
                            $('.trackOptions option').attr('selected', '');
                            $('.trackOptions option[value="mp4"]').attr('selected', 'selected');
                        }
                    });
                    break;

                case "button22 buttonCdg":
                    TVI.ajax({

                        url: '/handlers/SAT.aspx/setDefaultFormat',
                        data: {
                            'format': 'cdg'
                        },
                        success: function (d) {
                            $('.trackOptions option').attr('selected', '');
                            $('.trackOptions option[value="cdg"]').attr('selected', 'selected');
                        }
                    });
                    $('#popup select option').attr('selected', '');
                    $('#popup select option[value="cdg"]').attr('selected', 'selected');
                    //SAT.showPopup();
                    $('#popupWrapper').show();
                    break;

                case "button22 buttonDvd":
                    TVI.ajax({

                        url: '/handlers/SAT.aspx/setDefaultFormat',
                        data: {
                            'format': 'dvd'
                        },
                        success: function (d) {
                            $('.trackOptions option').attr('selected', '');
                            $('.trackOptions option[value="dvd"]').attr('selected', 'selected');
                        }
                    });
                    $('#popup select option').attr('selected', '');
                    $('#popup select option[value="dvd"]').attr('selected', 'selected');
                    //SAT.showPopup();
                    $('#popupWrapper').show();

                    break;
            }
            return false;
        });

        TVI.event('.buttonCheckout', 'click', function () {
            TVI.ajax({

                url: '/handlers/SAT.aspx/basketValid',
                data: {

                },
                success: function (d) {
                    window.location = '/checkoutlogin.aspx';
                },
                failure: function (d) {
                    $('#basketErrors').html(d.errors[0].message + "<br />");
                }

            });
        });

    }

    var initPopup = function () {

        $('#chooseFormatForm input').keypress(function (event) {
            if (event.keyCode == '13') {
                $('#chooseFormatForm .buttonContinue a').click();
            }
        });


        $('#chooseFormatForm .buttonContinue a').click(function () {
            if ($('#chooseFormatForm #chooseFormatForm-discName-control').val() == "") {
                $('#chooseFormatForm .error').html('Please enter a disc name');
                return false;
            }
            if ($('#chooseFormatForm #chooseFormatForm-discName-control').val().length > 30) {
                $('#chooseFormatForm .error').html('Disc names are limited to 30 characters');
                return false;
            }
            if ($('#popupExistingDisc').val() == '') {
                // This is a create disc request
                TVI.ajax({

                    url: '/handlers/SAT.aspx/addDiscToBasket',
                    data: {
                        'format': $('#chooseFormatForm #chooseFormatForm-format-control').val(),
                        'name': $('#chooseFormatForm #chooseFormatForm-discName-control').val()
                    },
                    success: function (d) {

                        // If this was a request through a track dropdown, add the track to the disc
                        if ($('#popupAddTrack').val() != '') {
                            TVI.ajax({

                                url: '/handlers/SAT.aspx/addToBasket',
                                data: {
                                    'format': 'disc' + d.discID,
                                    'id': $('#popupAddTrack').val()
                                },
                                success: function (e) {
                                    $('#popupAddTrack').val('')
                                    TVI.fireEvent('basketUpdated', d);
                                    TVI.fireEvent('basketUpdated', e);
                                }

                            });

                        }
                        else {
                            TVI.fireEvent('basketUpdated', d);
                        }
                        SAT.hidePopup();
                    }
                });
            } else {
                // We have an existing disc to update
                TVI.ajax({

                    url: '/handlers/SAT.aspx/updateDiscInBasket',
                    data: {
                        'format': $('#chooseFormatForm #chooseFormatForm-format-control').val(),
                        'name': $('#chooseFormatForm #chooseFormatForm-discName-control').val(),
                        'disc': $('#popupExistingDisc').val()
                    },
                    success: function (d) {
                        SAT.hidePopup();
                        TVI.fireEvent('basketUpdated', d);
                    }
                });
            }
            return false;
        });

        $('#popup .close a').click(function () {
            SAT.hidePopup();
            return false;
        });

    }

    var initSearch = function () {

        cmp.keywordSearchForm = new TVI.Form({

            ID: 'searchForm',
            local: true

        });

        $('#letters a').click(function () {
            if ($('#azForm-azChoose-control').val() != "") {
                // Work out which letter was clicked
                var letter = $(this).parent().attr('ID').substring(7);
                window.location = '/search.aspx?display=track&mode=track&lettermode=' + $('#azForm-azChoose-control').val() + '&letter=' + letter;
            }
            else {
                $('#azForm .error').html("Please choose a search option");
            }
            return false;
        });

        $('#browseForm-choose a').click(function () {
            window.location = '/search.aspx?display=track&mode=track&genre=' + $('#browseForm-choose-control').val();
            return false;
        });

        // Set Dropdowns & Check Boxes

        if (TVI.Request.QueryString['artist'] != undefined) {
            $('option[value="artist"]').attr('selected', 'selected');
        }
        if (TVI.Request.QueryString['title'] != undefined) {
            if (TVI.Request.QueryString['mode'] == 'album') {
                $('option[value="album"]').attr('selected', 'selected');
            }
            else {
                $('option[value="track"]').attr('selected', 'selected');
                $('option[value="title"]').attr('selected', 'selected');
            }
        }

        if (TVI.Request.QueryString['duet'] == 'true') {
            $('#searchForm-filters-duet').attr('checked', 'checked');
        }

        if (TVI.Request.QueryString['fadedEnding'] == 'true') {
            $('#searchForm-filters-fadedEnding').attr('checked', 'checked');
        }



        // Set sort dropdown
        $('#sort').change(function () {
            if (window.location.toString().indexOf('?') < 1) {
                // Rewritten url
                // if ($('#hid_sort').val() != '' && window.location.toString().indexOf($('#hid_sort').val()) > 0) {
                //     window.location = window.location.toString().replace($('#hid_sort').val(), $(this).val());
                // }
                // else 
                if (window.location.toString().match(/.*.com\/[^\/]\/[^\/]\/[^\/]\/[^\/]/)) {
                    window.location = window.location.toString().replace(/(.*.com[\/].*[\/].*[\/]).*([\/].*)/gi, '$1' + $(this).val() + '$2');
                }
                else if (window.location.toString().indexOf('trackartist') > 0) {
                    window.location = window.location.toString().replace(/(.*com\/[^\/]+\/[^\/]+\/[^\/]+)(?:\/[^\/]+\/?(all|\d+)|(.*))?/gi, '$1/' + $(this).val() + '$2');
                } else {
                    var matches = window.location.toString().match(/(.*com\/[^\/]+\/[^\/]+)(?:\/[^\/]+\/?(all|\d+)|(.*))?/gi);
                    window.location = window.location.toString().replace(/(.*com\/[^\/]+\/[^\/]+)(?:\/[^\/]+\/?(all|\d+)|(.*))?/gi, '$1/' + $(this).val() + '$2');

                }
            }
            else if (window.location.toString().indexOf('sort') > 0) {
                window.location = window.location.toString().replace(/sort=[a-zA-Z]*/g, "sort=" + $(this).val());
            }
            else {
                window.location = window.location + "&sort=" + $(this).val();
            }

        });


        if (TVI.Request.QueryString['sort'] != undefined) {
            $('#sort').val(TVI.Request.QueryString['sort']);
        }
        if ($('#hid_sort').val() != undefined) {
            $('#sort').val($('#hid_sort').val());
        }

        $('#searchForm-keywords .TVI-formSubmit').click(function () {
            keywordSearch();
        });

    }

    var keywordSearch = function () {

        var displaymode = "";
        var mode = "";
        var searchfor = "";
        var duet = "";
        var fadedEnding = "";

        if (cmp.keywordSearchForm.field('choose').val() == 'title' || cmp.keywordSearchForm.field('choose').val() == 'artist') {
            displaymode = "track";
            mode = "track";
            searchfor = cmp.keywordSearchForm.field('choose').val();
        }
        else {
            displaymode = "album";
            mode = "album";
            searchfor = "title";
        }

        if ($('#searchForm-filters-duet:checked').length > 0) {
            duet = '&duet=true';
        }

        if ($('#searchForm-filters-fadedEnding:checked').length > 0) {
            fadedEnding = '&fadedEnding=true';
        }

        window.location = '/search.aspx?display=' + displaymode + '&mode=' + mode + '&' + searchfor + '=' + searchsanitised(cmp.keywordSearchForm.field('keywords').val()) + duet + fadedEnding;

    }

    var sanitised = function (input) {
        return input.replace(/-/g, "_").replace(/ /g, "-").replace(/&/g, "[AND]").replace(/[?]/g, "[QUES]");
    }

    var searchsanitised = function (input) {
        return input.replace(/-/g, "_").replace(/ /g, "-").replace(/&/g, "[AND]").replace(/[?]/g, "[QUES]").replace(/\'/g, "");
    }

    var initLogin = function () {


        SAT.setFocusBlur($('#loginForm INPUT'));


        // Submit login form
        var submitLogin = function () {
            if (cmp.loginForm.field('email').val() === '' || cmp.loginForm.field('email').val() === 'Email Address') {
                return;
            }

            cmp.loginForm.submit({

                url: '/handlers/SAT.aspx/login',
                data: {
                    'remember': $('#chk_remember').is(':checked')
                },
                success: function (d) {

                    $('#mainColumns').removeClass('loggedOut').addClass('loggedIn');
                    $('#welcomeBack').text(d.name);
                    $('#accountCredit .price').data('originalPrice', d.credit)
                    $('#accountCredit .price').html('£' + d.credit);
                    $('#loginError').hide();
                    TVI.fireEvent('basketUpdated', d);
                },
                failure: function (d) {

                    $('#loginError').show();
                }

            });

        };


        cmp.loginForm = new TVI.Form({

            ID: 'loginForm',
            buttons: [{

                selector: '#loginButton',
                enter: true,
                handler: submitLogin

            }]

        });

        TVI.event('.logout', 'click', function () {
            TVI.ajax({
                url: '/handlers/SAT.aspx/logout',
                data: {},
                success: function (d) {
                    window.location = "/";
                }
            });
        });


    };



    /* Public */

    TVI.apply(cmp, {

        /* Properties */
        showPopup: function () {
            if ($.browser.msie && $.browser.version == "6.0") {
                $('select').hide();
                $('#popupWrapper select').show();
            }
            $('#overlay').fadeTo(0, 0);
            $('#overlay').show();
            $('#popupWrapper').fadeTo(0, 0);
            $('#popupWrapper').show();

            $('#overlay').fadeTo('slow', 0.8);
            $('#popupWrapper').fadeTo('slow', 1);
            $('#popupWrapper input').keypress(function (event) {
                if (event.keyCode == '13') {
                    $('#popupWrapper .buttonContinue a').click();
                }
            });
        },
        hidePopup: function () {
            if ($.browser.msie && $.browser.version == "6.0") {
                $('select').show();
            }
            $('#overlay').fadeOut();
            $('#popupWrapper').fadeOut();

            $('#popup #popupAddTrack').val('');
            $('#popup #popupExistingDisc').val('');
            $('#popup #chooseFormatForm-discName-control').val('');
        },

        // current currency
        currency: 'GBP',
        // currency rates
        dollar: '0',
        sterling: '1',
        euro: '0',

        getRates: function () {
            //Get the exchange rates
            $.ajax({
                type: "POST",
                url: '/Handlers/SAT.aspx/getRates',
                async: false,
                data: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    result = JSON.parse(data.d);
                    var rates = result.rates;
                    SAT.dollar = rates.dollar;
                    SAT.euro = rates.euro;
                }
            });
        },

        // Function to do currency conversion for all prices on page. Takes string of row to limit replace to certain area on page
        setPrices: function () {
            var Symbol;
            if (SAT.euro == 0) {
                SAT.getRates();
            }
            //Some vars to store prices temporarily
            var OriginalPrice;
            var NewPrice;
            var Rate

            switch (SAT.currency) {
                case "dollar":
                    Rate = SAT.dollar;
                    Symbol = "$";
                    break;
                case "pound":
                    Rate = 1;
                    Symbol = "£";
                    break;
                case "euro":
                    Rate = SAT.euro;
                    Symbol = "€";
                    break;
            }

            //Go through each element with a class of price
            $('.price').each(function () {

                if ($(this).data('originalPrice') == undefined) {
                    $(this).data('originalPrice', $(this).html().substring(1));
                }

                OriginalPrice = parseFloat($(this).data('originalPrice'));

                NewPrice = OriginalPrice * Rate;

                if ($(this).hasClass('nodecimal')) {
                    $(this).html(Symbol + String(NewPrice.toFixed(0)));
                }
                else {
                    $(this).html(Symbol + String(NewPrice.toFixed(2)));
                }
            });
        },

        setFocusBlur: function (inputs) {

            // Function to set focus-blur on textboxes
            inputs.each(function () {

                // For password boxes remove the background on focus and restore it on blur if its empty
                //            if ($(this).attr('type') === 'password') {

                //                                            $(this).focus(function() {
                //                                                if ($(this).val() === '') {
                //                                                    $(this).parent().data('background', $(this).parent().css('background-image'));
                //                                                    $(this).parent().css('background-image', $(this).parent().data('background').replace("-password",""));
                //                                                }
                //                                            });
                //                                            $(this).blur(function() {
                //                                                if ($(this).val() === '') {
                //                                                    $(this).parent().css('background-image', $(this).parent().data('background'));
                //                                                }
                //                                            });
                //            }
                //            else {
                // For normal
                $(this).data('original', $(this).val());

                $(this).focus(function () {
                    if ($(this).val() === $(this).data('original')) {
                        $(this).val('');
                    }
                });

                $(this).blur(function () {
                    if ($(this).val() === '') {
                        $(this).val($(this).data('original'));
                    }
                });
                //            }
            });

        }

    });


    TVI.ready(init);


    return cmp;


} ();

var Base64 = {
 
	// private property
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 
	// public method for encoding
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = Base64._utf8_encode(input);
 
		while (i < input.length) {
 
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
 
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
 
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
 
			output = output +
			this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
			this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
 
		}
 
		return output;
	},
 
	// public method for decoding
	decode : function (input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
 
		input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
 
		while (i < input.length) {
 
			enc1 = this._keyStr.indexOf(input.charAt(i++));
			enc2 = this._keyStr.indexOf(input.charAt(i++));
			enc3 = this._keyStr.indexOf(input.charAt(i++));
			enc4 = this._keyStr.indexOf(input.charAt(i++));
 
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
 
			output = output + String.fromCharCode(chr1);
 
			if (enc3 != 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 != 64) {
				output = output + String.fromCharCode(chr3);
			}
 
		}
 
		output = Base64._utf8_decode(output);
 
		return output;
 
	},
 
	// private method for UTF-8 encoding
	_utf8_encode : function (string) {
		string = string.replace(/\r\n/g,"\n");
		var utftext = "";
 
		for (var n = 0; n < string.length; n++) {
 
			var c = string.charCodeAt(n);
 
			if (c < 128) {
				utftext += String.fromCharCode(c);
			}
			else if((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			}
			else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
 
		}
 
		return utftext;
	},
 
	// private method for UTF-8 decoding
	_utf8_decode : function (utftext) {
		var string = "";
		var i = 0;
		var c = c1 = c2 = 0;
 
		while ( i < utftext.length ) {
 
			c = utftext.charCodeAt(i);
 
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			}
			else if((c > 191) && (c < 224)) {
				c2 = utftext.charCodeAt(i+1);
				string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
				i += 2;
			}
			else {
				c2 = utftext.charCodeAt(i+1);
				c3 = utftext.charCodeAt(i+2);
				string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
				i += 3;
			}
 
		}
 
		return string;
	}
 
}
