function initFMakeSubmit() {
    $.each([
        "#create",
        "#clear"
    ], function(index, value) {
        $(value).click(function (event) {
            var source = $(event.target);
            $('#fMake').attr('submitByButton', source.attr('id'))
        });
    });

    $(function () {
        $("#fMakeLoading").hide();
        $('#fMake')
                .show()
                .submit(function (a, b, c) {
            var by = $(this).attr('submitByButton');
            if (by != 'create')
                return;

            $('#create').addClass('inProgress');

            var w = $('#slider').width();
            var s = $('#hand1').position().left / w;
            var e = $('#hand2').position().left / w;
            //alert($('#fadein').attr('checked'));
            $.ajax({
                type: 'POST',
                url: '/ringtone/make',
                data: {
                    start: s,
                    end: e,
                    create: $('#create').val(),
                    volume: $('#volumeSlider').slider('value'),
                    fadein: $('#fadein').attr('checked'),
                    fadeout:$('#fadeout').attr('checked')
                },
                success: function (data, textStatus, jqXHR) {
                    $('#create').removeClass('inProgress');
                    //data = data;
                    //$('#create').removeClass('inProgress');
                    //this.process(data)
                },
                error: function (data, textStatus, jqXHR) {
                    $('#create').removeClass('inProgress');
                },
                cache: false,
                dataType: 'script'
            });
            return false;
        });
    });
}

$.fn.millisecondsToStr = function(t) {
    t = isNaN(t) ? 0 : t;
    t = Math.round(t);
    var h = Math.floor(t / (60 * 60 * 1000));
    t -= h * 60 * 60 * 1000;
    var m = Math.floor(t / (60 * 1000));
    t -= m * 60 * 1000;
    var s = Math.floor(t / 1000);
    t -= s * 1000;
    if (h < 10) h = '0' + h;
    if (m < 10) m = '0' + m;
    if (s < 10) s = '0' + s;
    return m + ":" + s + "." + t;
};

function initRingtoneSelection(start, end, recordDuration, recordUrl) {
    $(function() {
        soundManager.onready(function() {
            var updatePlayingPosition = function () {
                var w = $('#slider').width();
                var d = this.duration;
                var p = this.position;
                $('#playing').css('width', Math.round(Math.min(w, Math.max(0, w * (p / d)))));
            };
            var sound = soundManager.createSound({ id: recordUrl,
                url: recordUrl,
                autoLoad: true,
                volume: 100,
                whileloading: function (v, a, c) {
                    var w = $('#slider').width();
                    var t = this.bytesTotal;
                    var l = this.bytesLoaded;
                    $('#loaded').css('width', Math.min(w, Math.max(0, w * (1 - l / t))));
                },
                onload: function (success) {
                    if (success) {
                        $('#loaded').hide();
                    } else {
                        $().toastmessage('showToast', {
                            text     : 'Error on load audio. Can\'t play.',
                            sticky   : true,
                            position : 'middle-center',
                            type     : 'error',
                            closeText: ''/*,
                             close    : function () {
                             console.log("toast is closed ...");
                             }*/
                        });
                    }
                },
                whileplaying: updatePlayingPosition,
                onstop: updatePlayingPosition
            });

            var slider = $('#slider');
            slider.click(function (event) {
                var t = soundManager.getSoundById(recordUrl);
                if (!t) return;

                var position = Math.floor(sound.duration * event.layerX / $(this).width());

                sound.stop();
                sound.play({position: position});
            });

            $('#controls #play').click(function (event) {
                sound.play();
            });
            $('#controls #pause').click(function (event) {
                sound.togglePause();
            });
            $('#controls #stop').click(function (event) {
                sound.stop();
            });

        });

        var updateHand = function(event, ui) {
            ui = $(this);//ui.helper;
            var width = ui.parent().width();
            var pos = Math.round(recordDuration * ui.position().left / width);
            ui.find('span').html(ui.millisecondsToStr(pos));

            /*var l1 = $('#hand1').position().left;
             var l2 = $('#hand2').position().left;
             */
            var l1 = ui.position().left;
            var l2 = $(ui.attr('id') == 'hand1' ? '#hand2' : '#hand1').position().left;

            var len = Math.abs(l1 - l2);
            $('#selected')
                    .css('left', Math.min(l1, l2))
                    .css('width', len);
            var duration = recordDuration * len / width;
            $('#ringtoneDuration').html(ui.millisecondsToStr(duration));
            if (30000 < duration) {
                $('#tooLong').show();
            } else {
                $('#tooLong').hide();
            }
        };

        var options = {
            containment: "parent",
            create: updateHand,
            drag: updateHand,
            axis: 'x',
            scroll: false,
            handle: 'span'
        };

        var s = $('#slider').width() / recordDuration;

        $.each([
            ["#hand2", start],
            ["#hand1", end]
        ], function(index, value) {
            $(value[0]).css('left', s * value[1])
                    .draggable(options)
                    .click(function () {
                //click to prevent start playing
                return false;
            })
                    ;

        });
    });
}

soundManager.url = '/sm/';

// disable debug mode after development/testing..
soundManager.debugMode = false;
//soundManager.flashVersion = 9;
//soundManager.flash9Options.useWaveformData = true;

soundManager.defaultOptions = {

    /*position: 0,*/
    /*whileplaying: function() {
     setTrackPosition(soundManager.getSoundById(TRACK).position);
     }*//*,
     onfinish: function(){ setBtnImg(this.sID, 1);},
     onplay:   function(){ setBtnImg(this.sID, 0);},
     onpause:  function(){ setBtnImg(this.sID, 1);},
     onresume: function(){ setBtnImg(this.sID, 0);},
     onstop:   function(){ setBtnImg(this.sID, 1);}
     */
};


soundManager.useFastPolling = true; // increased JS callback frequency, combined with useHighPerformance = true

threeSixtyPlayer.config.scaleFont = (navigator.userAgent.match(/msie/i) ? false : true);
threeSixtyPlayer.config.showHMSTime = true;

// enable some spectrum stuffs

threeSixtyPlayer.config.useWaveformData = true;
threeSixtyPlayer.config.useEQData = true;

// enable this in SM2 as well, as needed

if (threeSixtyPlayer.config.useWaveformData) {
    soundManager.flash9Options.useWaveformData = true;
}
if (threeSixtyPlayer.config.useEQData) {
    soundManager.flash9Options.useEQData = true;
}
if (threeSixtyPlayer.config.usePeakData) {
    soundManager.flash9Options.usePeakData = true;
}

// favicon is expensive CPU-wise, but can be used.
if (window.location.href.match(/hifi/i)) {
    threeSixtyPlayer.config.useFavIcon = true;
}

if (window.location.href.match(/html5/i)) {
    // for testing IE 9, etc.
    soundManager.useHTML5Audio = true;
}

$(function(){
    initFMakeSubmit();

    $('.j__load').each(function (){
        var s = $.parseJSON($(this).html()
            .replace('<!--', '')
            .replace('-->', '')
            );
        $(this).replaceWith(s);
    });
});
