﻿
SSF = 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();
    };

    var initCurrency = function () {

        // Get current currency
        TVI.ajax({
            url: '/Handlers/SSF.aspx/getCurrency',
            success: function (data) {
                SSF.currency = data.currency;
                $('.currency li a').removeClass('selected');
                $('.currency .' + SSF.currency + ' a').addClass('selected');
                // Once we have the selected currenct run currency conversion
                SSF.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
            SSF.currency = $(this).parent().attr('class');
            $.ajax({
                type: "POST",
                url: '/Handlers/SSF.aspx/setCurrency',
                data: '{"currency":"' + SSF.currency + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) { }
            });
            //Run the actual conversion
            SSF.setPrices();
            return false;
        });

    };

    var initButtons = function () {

        $('#chooseFormatBox .chooseFormatInner a').click(function () {

            switch ($(this).parent().attr('class')) {

                case "button22 buttonMp3g":
                    TVI.ajax({

                        url: '/handlers/SSF.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/SSF.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/SSF.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');
                    SSF.showPopup();

                    break;

                case "button22 buttonDvd":
                    TVI.ajax({

                        url: '/handlers/SSF.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');
                    SSF.showPopup();
                    break;
            }
            return false;
        });

        TVI.event('.buttonCheckout', 'click', function () {
            TVI.ajax({

                url: '/handlers/SSF.aspx/basketValid',
                data: {

            },
            success: function (d) {
                window.location = '/checkoutlogin.aspx';
            },
            failure: function (d) {
                $('#basketErrors').html(d.errors[0].message + "<br />");
            }

        });
    });

}

var initPopup = function () {

    $('#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/SSF.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/SSF.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);
                    }
                    SSF.hidePopup();
                }
            });
        } else {
            // We have an existing disc to update
            TVI.ajax({

                url: '/handlers/SSF.aspx/updateDiscInBasket',
                data: {
                    'format': $('#chooseFormatForm #chooseFormatForm-format-control').val(),
                    'name': $('#chooseFormatForm #chooseFormatForm-discName-control').val(),
                    'disc': $('#popupExistingDisc').val()
                },
                success: function (d) {
                    SSF.hidePopup();
                    TVI.fireEvent('basketUpdated', d);
                }
            });
        }
        return false;
    });

    $('#popup .close a').click(function () {
        SSF.hidePopup();
        return false;
    });

}

var initSearch = function () {

    cmp.keywordSearchForm = new TVI.Form({

        ID: 'searchForm',
        handler: keywordSearch

    });

    $('#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-control').change(function () {
        window.location = '/search.aspx?display=track&mode=track&genre=' + $(this).val();
    });

    // Set Dropdowns

    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');
        }
    }


}

var keywordSearch = function () {

    var displaymode = "";
    var mode = "";
    var searchfor = "";
    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";
    }
    window.location = 'search.aspx?display=' + displaymode + '&mode=' + mode + '&' + searchfor + '=' + cmp.keywordSearchForm.field('keywords').val().replace("'","");

}


var initLogin = function () {


    SSF.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/SSF.aspx/login',

            success: function (d) {

                $('#mainColumns').removeClass('loggedOut').addClass('loggedIn');
                $('#welcomeBack').text(d.name);
                $('#accountCredit .price').html('£' + d.credit);
                $('#loginError').hide();

            },
            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/SSF.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();
        }
        $('#popupWrapper').fadeIn();
    },
    hidePopup: function () {
        if ($.browser.msie && $.browser.version == "6.0") {
            $('select').show();
        }
        $('#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/SSF.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;
                SSF.dollar = rates.dollar;
                SSF.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 (SSF.euro == 0) {
            SSF.getRates();
        }
        //Some vars to store prices temporarily
        var OriginalPrice;
        var NewPrice;
        var Rate

        switch (SSF.currency) {
            case "dollar":
                Rate = SSF.dollar;
                Symbol = "$";
                break;
            case "pound":
                Rate = 1;
                Symbol = "£";
                break;
            case "euro":
                Rate = SSF.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;
	}
 
}
