var t = function() {
    // Window title
    var title = 'Translate Your Website Easy';
    // New line char
    var newLine = '\n';
    // Po file line index
    var lineIndex = 0;
    // Array of lines from po file
    var lines = null;
    // Message ID token
    var msgid = 'msgid "';
    // Message string token
    var msgstr = 'msgstr "';
    // Default language
    var defaultLang = 'en';
    // Language to translate on
    var targetLang = 'en';
    // Overwrite existing translations
    var overwrite = false;

    return {
        /**
        * initialize GUI controls.
        */
        initGui : function() {
            $.get(
                'https://www.googleapis.com/language/translate/v2/languages',
                {
                    key: 'AIzaSyCLdFMTFrVIiMX0e2Dl_qYg2OiQ1TQBfSs',
                    target: 'en',
                    pp: 1
                },
                function(data) {
                    console.log(data);
                },
                'json'
            );
            // Generate language select
//            var select = $('<select>').attr('id', 'lang');
//            jQuery.each(google.language.Languages, function(langId, lang) {
//                if (defaultLang == lang) {
//                    select.append('<option selected="selected" value=' + lang + '>' + langId.capitalize() + '</option>');
//                } else if('' == lang) {
//                // Skip unknown
//                } else {
//                    select.append('<option value=' + lang + '>' + langId.capitalize() + '</option>');
//                }
//            });
//            select.prependTo('#controls');
//            $('<label>').attr('for', 'lang').html('Language: ').prependTo('#controls');
        },

        /**
        * Process po file.
        */
        process : function() {
            // Get lines and language
            lines = jQuery.trim($('#text').val()).split(newLine);
            targetLang = $('#lang').val();
            overwrite = $('#overwrite').attr('checked');

            // Init progress
            t.updateProgress(0);

            // Flag if there are strings for translation
            var containStrings = false;

            // Translate each string
            for (lineIndex = 0; lineIndex < lines.length; lineIndex++) {
                lines[lineIndex] = jQuery.trim(lines[lineIndex]);
                if (-1 != lines[lineIndex].search(msgstr)) {
                    containStrings = true;
                    lastLineIndex = lineIndex;
                    var translate = lines[lineIndex - 1].replace(msgid, '').replace('"', '').substring(0, lines[lineIndex - 1].length - 1);
                    t.translate(lineIndex, translate);
                }
            }

            // No strings - finish
            if (!containStrings) {
                t.updateProgress(100);
            }
        },

        /**
        * Translate one string.
        *
        * @param	int		index
        * @param	string	s
        */
        translate : function(index, s) {
            google.language.translate(s, '', targetLang,
                function(result) {
                    if (overwrite) {
                        var token = msgstr;
                    } else {
                        var token = msgstr + '"';
                    }

                    // Add translation
                    if (-1 != lines[index].search(token)) {
                        lines[index] = msgstr + result.translation + '"';
                    }

                    // Update status
                    t.updateProgress(Math.round(index/lines.length*100));

                    // If end, export result
                    if (index == lines.length - 1) {
                        t.exportResult();
                        t.updateProgress(100);
                    }
                });
        },

        /**
        * Update progress information.
        *
        * @param	int	percents
        */
        updateProgress : function(percents) {
            switch (percents) {
                case 0:
                    document.title = window.status = 'Initializing...';
                    $('#text').attr('disabled', true);
                    break;
                case 100:
                    window.status = 'Done';
                    document.title = title;
                    $('#text').attr('disabled', false);
                    break;
                default:
                    document.title = window.status = 'Translating...' + percents + '%';
                    break;
            }
        },

        /**
        * Export po file content.
        */
        exportResult : function() {
            $('#text').val('');
            $('#text').val(lines.join(newLine));
        }
    };
}();

// Prototype methods
String.prototype.capitalize = function(){
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};

document.onload = t.initGui();
