var TTSAudioPlugin = {
    close: function(obj) {   
        var audioChoice = $(obj).closest('.ivr-Menu');
        var audioChoiceEditor   = audioChoice.children('.ivr-Menu-editor');
        var audioChoiceSelector = audioChoice.children('.ivr-Menu-selector');
        var subDiv  = audioChoiceEditor.children('.ivr-Menu-editor-padding');

        audioChoiceSelector.show();
        audioChoiceEditor.hide();
        subDiv.children('.ivr-audio-upload').hide();    
        subDiv.children('.ivr-Menu-read-text').hide();
        subDiv.children('.ivr-mp3-url').hide();
        subDiv.children('.ivr-record-audio').hide();
        subDiv.children('.removePMWrapper').show();
    },

    openEditor: function(obj) {
        var audioChoice = $(obj).closest('.ivr-Menu-selector'); 
        audioChoice.hide();
        audioChoice.parent().children('.ivr-Menu-editor').show();
        var subDiv = audioChoice.parent().children('.ivr-Menu-editor').children('.ivr-Menu-editor-padding');

        subDiv.children('.removePMWrapper').hide();

        if (obj.id  == 'txt') 
        {       
            subDiv.children('.ivr-Menu-read-text').show();   
            $('[name="uploadfile"]').css('z-index','-1');
        }
        else if (obj.id  == 'upload_mp3') {
            $('[name="uploadfile"]').css('z-index','2147483583');
            
            subDiv.children('.ivr-audio-upload').show();    
            SubObj = subDiv.children('.ivr-audio-upload').find('#uploadFileButton');        
            this.UploadFile(SubObj); 
        }
        else if (obj.id  == 'mp3_url') {
            subDiv.children('.ivr-mp3-url').show();
        }
        else if (obj.id  == 'record_audio') {
            subDiv.children('.ivr-record-audio').show();
        }
    },

    testVoice: function(obj) {
        var voice =  $(obj).parents('div.ivr-Menu-editor').find('#voice').val();
        var language = $(obj).parents('div.ivr-Menu-editor').find('#language').val();
        var text = $(obj).parents('div.ivr-Menu-editor').find('#text').val();
        if ($("#test_voice_iframe_wrapper").length == 0) {
            var exploded = document.location.href.split('/ivr');
            var action = (exploded.length > 1) ? '../test_voice.php' : 'test_voice.php';
            $("body").append('<div id="test_voice_iframe_wrapper" style="display: none;">' +
                                '<form id="test_voice_form" action="' + action + '" method="post" target="test_voice_iframe">' +
                                    '<input type="hidden" name="voice" id="voice" />' +
                                    '<input type="hidden" name="language" id="language" />' +
                                    '<input type="hidden" name="text" id="text" />' +
                                    '<input type="submit" name="submit" id="submit" value="Submit" />' +
                                '</form>' +
                                '<iframe id="test_voice_iframe" name="test_voice_iframe"></iframe>' +
                            '</form>'
            );
        }

        $("#test_voice_iframe_wrapper #voice").val(voice);
        $("#test_voice_iframe_wrapper #language").val(language);
        $("#test_voice_iframe_wrapper #text").val(text);
        $('#test_voice_iframe_wrapper #submit').click()
    },

    selectVoice: function(obj) {
        var language = $(obj).parents('.ivr2-input-container').find('#language');
        language.find('option').hide().prop('disabled', true);
        language.find('option[data-voice=' + obj.value + ']').show().prop('disabled', false);
        if (language.find('option:selected').attr('data-voice') != obj.value) {
            language.find('option').removeAttr('selected', 'selected');
            language.find('option:visible').first().attr('selected', 'selected'); 
        }
    },

    closeBtnHtml: '<a href="javascript: void(0);" class="ttsMwCloseBtn" onclick="TTSAP.removeSelectedOption(this);" style="display: block; position: absolute; right: 7px; top: 6px; color: red; z-index: 9; font-weight: bold; cursor: pointer;"><img src="images/delete.gif" style="border: 0px;"></a>',

    saveContent: function(obj, content_type) {
        var thisBlock = $(obj).closest('.ivr-Menu');

        switch (content_type) {
            case "TEXT":
                var voice_text = $(thisBlock).find('#text').val();
                var voice = $(thisBlock).find('#voice').val();
                var language = $(thisBlock).find('#language').val();
                $(thisBlock).find('#txt').addClass('ivr-Menu-Selected');
                $(thisBlock).find('#upload_mp3').removeClass('ivr-Menu-Selected');
                $(thisBlock).find('#mp3_url').removeClass('ivr-Menu-Selected');
                $(thisBlock).find('#record_audio').removeClass('ivr-Menu-Selected');
                $(thisBlock).find('.ivr-Menu-close-button').click();

                $(thisBlock).find('.content').val(voice_text);
                $(thisBlock).find('.type').val("Text");
                $(thisBlock).find('.voice').val(voice);
                $(thisBlock).find('.language').val(language);

                $(thisBlock).find(".ttsMwCloseBtn").remove();
                $(thisBlock).find('#txt').parents('div.ivr-Menu-selector-item-wrapper').append(TTSAP.closeBtnHtml);
            break;

            case "MP3_URL":
                var mp3_url = $(thisBlock).find('#mp3_url_text').val();
                $(thisBlock).find('#txt').removeClass('ivr-Menu-Selected');
                $(thisBlock).find('#upload_mp3').removeClass('ivr-Menu-Selected');
                $(thisBlock).find('#mp3_url').addClass('ivr-Menu-Selected');
                $(thisBlock).find('#record_audio').removeClass('ivr-Menu-Selected');
                $(thisBlock).find('.ivr-Menu-close-button').click();

                $(thisBlock).find('.content').val(mp3_url);
                $(thisBlock).find('.type').val("MP3_URL");

                $(thisBlock).find(".ttsMwCloseBtn").remove();
                $(thisBlock).find('#mp3_url').parents('div.ivr-Menu-selector-item-wrapper').append(TTSAP.closeBtnHtml);
            break;
        }
    },

    removeSelectedOption: function(obj) {
        parent.promptMsg('Are you sure ?', function() {
            var thisBlock = $(obj).closest('.ivr-Menu');
            $(thisBlock).find(".ttsMwCloseBtn").remove();

            $(thisBlock).find('#txt').removeClass('ivr-Menu-Selected');
            $(thisBlock).find('#upload_mp3').removeClass('ivr-Menu-Selected');
            $(thisBlock).find('#mp3_url').removeClass('ivr-Menu-Selected');
            $(thisBlock).find('#record_audio').removeClass('ivr-Menu-Selected');

            $(thisBlock).find('.content').val('');
            $(thisBlock).find('.type').val('');
            $(thisBlock).find('.voice').val('');
            $(thisBlock).find('.language').val('');

            $("#save_call_flow_btn", window.parent.document).fadeTo(0, 1);
            $("#save_call_flow_btn", window.parent.document).prop('disabled', false);
        });
    },

    UploadFile: function(obj)
    {
        var status = $(obj).closest('.explanation').find('#statusUpload');
        var fileNameStatus = $(obj).closest('.explanation').find('#voicefilename');
        var thisBlock = $(obj).closest('.ivr-Menu');
        var location = $(thisBlock).find('.location').val();
        
        var blockId = $(obj).closest('.block').prop('id');
        wId= blockId.replace(/blockObj-/g, '');  

        var action_url = '';
        switch (location) {
            case 'call_flow':
                action_url = 'process_ivr.php?act=uploadFile&wId=' + wId + '&companyId=' + companyId;
            break;
        }

        status.text('');

        new AjaxUpload(obj, {
            action: action_url,
            name: 'uploadfile',
            onSubmit: function(file, ext){
                 if (! (ext && /^(mp3|wma)$/.test(ext))){ 
                    status.text('Only MP3 files are allowed');
                    return false;
                }
                $(thisBlock).find("#uploadFileButton").val("Uploading...").prop('disabled', true);
                
            },
            onComplete: function(file, response){
                $("#save_call_flow_btn", window.parent.document).fadeTo(0, 1);
                $("#save_call_flow_btn", window.parent.document).prop('disabled', false);
                $(fileNameStatus).show();
                $(fileNameStatus).find('.uploaded_file_name').html(response);
                
                $(thisBlock).find('#txt').removeClass('ivr-Menu-Selected');
                $(thisBlock).find('#upload_mp3').addClass('ivr-Menu-Selected');
                $(thisBlock).find('#mp3_url').removeClass('ivr-Menu-Selected');
                $(thisBlock).find('#record_audio').removeClass('ivr-Menu-Selected');

                $(thisBlock).find('.content').val(response);
                $(thisBlock).find('.type').val("Audio");
                $(thisBlock).find('.ivr-Menu-close-button').click();

                $(thisBlock).find("#uploadFileButton").val("Upload").prop('disabled', false);

                $(thisBlock).find(".ttsMwCloseBtn").remove();
                $(thisBlock).find('#upload_mp3').parents('div.ivr-Menu-selector-item-wrapper').append(TTSAP.closeBtnHtml);
            }
        });
    },

    recordingId: 0,

    recordAudio: function(obj) {
        if ($(obj).val() == "Call Me") {
            this.recordingId = this.createUUID();
            var record_from = $(obj).parents('fieldset.ivr-Menu').find('#record_from').val();
            var record_to = $(obj).parents('fieldset.ivr-Menu').find('#record_to').val();

            if (record_from == "") {
                parent.errMsgDialog("Please select Caller ID.");
                return false;
            }

            if (record_to == "") {
                parent.errMsgDialog("Please enter your phone number.")
                return false;
            }

            $(obj).val('Stop');

            if ($("#record_audio_iframe_wrapper").length == 0) {
                var exploded = document.location.href.split('/ivr');
                var action = (exploded.length > 1) ? '../record_audio.php' : 'record_audio.php';

                $("body").append('<div id="record_audio_iframe_wrapper" style="display: none;">' +
                                    '<form id="record_audio_form" action="' + action + '" method="post" target="record_audio_iframe">' +
                                        '<input type="hidden" name="recordingId" id="recordingId" />' +
                                        '<input type="hidden" name="record_from" id="record_from" />' +
                                        '<input type="hidden" name="record_to" id="record_to" />' +
                                        '<input type="submit" name="submit" id="submit" value="Submit" />' +
                                    '</form>' +
                                    '<iframe id="record_audio_iframe" name="record_audio_iframe"></iframe>' +
                                '</form>'
                );
            }

            $("#record_audio_iframe_wrapper #recordingId").val(this.recordingId);
            $("#record_audio_iframe_wrapper #record_from").val(record_from);
            $("#record_audio_iframe_wrapper #record_to").val(record_to);
            $('#record_audio_iframe_wrapper #submit').click()
        }
        else {
            var recId = this.recordingId;
            $(obj).val('Please wait...');
            setTimeout(function() {
                var exploded = document.location.href.split('/ivr');
                var action = (exploded.length > 1) ? '../admin_ajax_handle.php' : 'admin_ajax_handle.php';
                $.post(action, { func: "GET_RECORDING", recordingId: recId },  function(response) {
                    var thisBlock = $(obj).closest('.ivr-Menu');

                    $(thisBlock).find('#recordedAudioSaved').css('display' ,'block');
                    if (response) {
                        $(thisBlock).find('#recordedAudioSavedWrapper').html(response.playable);
                        
                        $(thisBlock).find('#txt').removeClass('ivr-Menu-Selected');
                        $(thisBlock).find('#upload_mp3').removeClass('ivr-Menu-Selected');
                        $(thisBlock).find('#mp3_url').removeClass('ivr-Menu-Selected');
                        $(thisBlock).find('#record_audio').addClass('ivr-Menu-Selected');

                        $(thisBlock).find('.content').val(response.url);
                        $(thisBlock).find('.type').val("RECORD_AUDIO");
                        $(thisBlock).find('.ivr-Menu-close-button').click();

                        $(thisBlock).find(".ttsMwCloseBtn").remove();
                        $(thisBlock).find('#record_audio').parents('div.ivr-Menu-selector-item-wrapper').append(TTSAP.closeBtnHtml);
                    }
                    else {
                        errMsgDialog('Audio was not recorded, please try again.');
                        $(thisBlock).find('#recordedAudioSavedWrapper').html('');
                    }
                    $(obj).val('Call Me');
                }, "json");
            }, 2000);
        }
    },

    createUUID: function() {
        // http://www.ietf.org/rfc/rfc4122.txt
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4";  // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);  // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";

        var uuid = s.join("");
        return uuid;
    }
};

var TTSAP = TTSAudioPlugin;

$(document).ready(function() {
    $("select#voice").each(function() {
        TTSAP.selectVoice(this);
    });
});