/*global window, deconcept, jQuery, SWFObject, alert*/
"use strict";

/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;

var audioTagSupport = false;
var selectedEngine = false;
var messages = {
    "timeout": {
        "cz": "Aplikace neobdržela od serveru zvuková data v určeném časovém limitu. Můžete to zkusit znovu později.",
        "en": "Timeout occured, audio data was not received. Please, try again later. "
    },    
    "notext": {
        "cz": "Nebyl zadán žádný text.",
        "en": "You need to type some text."
    },
    "progress": {
        "cz": "Probíhá syntéza ...",
        "en": "Synthesizing ..."
    },
    "synthesize": {
        "cz": "Syntetizovat",
        "en": "Synthesize"
    },
    "toolong": {
        "cz": "Váš text je příliš dlouhý. Text musíte zkrátit na % znaků.",
        "en": "Your text is too long. Text must have maximum of % characters."
    }
};

String.prototype.trim = function() {
    return this.replace(/(^\s*)|(\s*$)/g, "")
};

function loadjscssfile(filename, filetype){
 var fileref=null;
 if (filetype=="js"){ //if filename is a external JavaScript file
  fileref=document.createElement('script');
  fileref.setAttribute("type","text/javascript");
  fileref.setAttribute("src", filename);
 }
 else if (filetype=="css"){ //if filename is an external CSS file
  fileref=document.createElement("link");
  fileref.setAttribute("rel", "stylesheet");
  fileref.setAttribute("type", "text/css");
  fileref.setAttribute("href", filename);
 }
 if (typeof fileref!="undefined") {
  document.getElementsByTagName("head")[0].appendChild(fileref);
 }
}


 
function flashplayer(mp3url, tagid)  {    
    var so = new SWFObject('/demo/mediaplayer.swf','mpl','370','20','8');
    so.addParam('allowscriptaccess','always');
    so.addParam('allowfullscreen','true');
    so.addVariable('height','20');
    so.addVariable('width','370');
    so.addVariable('type', 'mp3');
    so.addVariable('file', mp3url);    
    so.addVariable('showstop','true');
    so.addVariable('usefullscreen','false');    
    so.addVariable('autostart','true');
    so.useExpressInstall('/demo/expressinstall.swf');
    so.write(tagid);    
}

function playurl(mp3url) {
    if (audioTagSupport) {
        jQuery("#audioplayer>audio").attr("src", mp3url);        
    }else {
        flashplayer(mp3url, "audioplayer");        
    }
}

function loadtext(url) {    
    jQuery('#ttstext').attr('disabled', true);
    jQuery.get(url, function(data){
        if (data.length>150) {
            data = data.substring(0,150);
        }
        jQuery('#ttstext').attr('disabled', false).value(data);        
    });
    return false;
}

function loadengine(eng, lang) {
    jQuery.ajax({  
        type: "GET",  
        url: "/demo/start.php",  
        data: "q=loadvoice&langcode="+lang+"&id="+eng.substr(1),  
        success: function(msg){  
            jQuery("#voicepar").html(msg);
            document.location.hash = eng;
            selectedEngine = eng.split('#')[1];
        }  
    });     
    return false;
}

function loadtext2(text) {  
    var MAXLEN = 350;
    text = text.substring(0,MAXLEN);
    jQuery('#ttstext').val(text);    
    return false;
}

function progress_class(delta, maxtime) {    
    var handle = 0;        
    var index = 0;
    var fncfinalize=this.finalize;
    
    this.finalize = function() {
        if (handle) {
            window.clearInterval(handle);
            handle = 0;
        }
    }    
    
    function to_full() {        
        index = index + (delta*100.0/maxtime);        
        jQuery("#progressbar").progressbar("option", "value", index);
        if (index>100) { fncfinalize(); }
    };
        
    this.start = function() {        
        handle = window.setInterval(to_full, delta);        
    }    
}
                                                    

function create_playback() {
    /*global $, audioTagSupport:true */    
    audioTagSupport = false;
    if (!jQuery.browser.msie) {
        audioTagSupport = !!(document.createElement('audio').canPlayType);
    }
     audioTagSupport = false;
    if (audioTagSupport) {        
        document.write("<audio autoplay autobuffer controls></audio>");                
    }    
}


function bad_alert(message, timeout) {
    timeout = (timeout == undefined) ? 0 : timeout;
    
    if (bad_alert.timeout_id != undefined) {
        clearTimeout(bad_alert.timeout_id)
        bad_alert.timeout_id = undefined;
    }
    jQuery("#errormessage").html(message);
    jQuery("#badalert").slideDown();
    if (timeout > 0) {
        bad_alert.timeout_id = setTimeout(function() {
            jQuery("#badalert").slideUp();
        }, timeout*1000 );
    }
}


function setup_demo() {
    var $ = jQuery;    
    $('#mp3player').hide(); 
    $('#rsstexts').hide();    
    $("#progressbar").progressbar({ value: 0 });
    
    $('#ttsdemo').submit(function() {
        var e = $("#ttstext")[0];
        var mytext = e.value.trim();
        var MAXLEN = 350;
        if (mytext.length == 0) {
            // bad_alert("Nebyl zadán žádný text.", 10);
            bad_alert(messages["notext"][window.LANGCODE], 10);            
            e.focus();
            return false;
        }
        if (mytext.length>MAXLEN) {
            // bad_alert("Váš text je příliš dlouhý. Text musíte zkrátit na "+MAXLEN+" znaků.", 10);
            bad_alert(messages["toolong"][window.LANGCODE].replace("%", MAXLEN), 10);
            
            e.selectionStart = MAXLEN-1;
            e.selectionEnd = mytext.length;
            e.focus();
            return false;
        }
        var format = $("#HDDNFORMAT").html();
        var data  = {text: mytext, eid: selectedEngine, f0: "1.0", diak: "0", speed: "1.0", format: format};        
        $("#audioplayer").show();
        $("#badalert").slideUp();
        $("#progressbar").progressbar("option", "value", "0");
        $("#progressbar").slideDown();                
        
        var progress = new progress_class(500, 15000);        
        $("#commitbtn").attr("disabled", true).attr("value", messages["progress"][window.LANGCODE]).end();
        progress.start();
        $.post("/demo/start.php?langcode="+window.LANGCODE+"&q=tts", data, function (data) {
            // progress_finalize();
            progress.finalize();
            $("#progressbar").slideUp();
            $("#commitbtn").attr("disabled", false).attr("value", messages["synthesize"][window.LANGCODE]).end();
            if ((data != "")&&(data.indexOf(".mp3")>-1)) {
                playurl(data);
                $("#audioplayer").slideDown();                
            }else {
                bad_alert(messages["timeout"][window.LANGCODE], 0);
            }
        }); // , "json"
        
        return false; 
    }); 
}


