/** Texyla
 *  Licence GPL
 *  Autoři: Jan Marek, Petr Vaněk
 *  Version: 0.6
 */

jQuery.fn.extend({
   texyla:function(options){
      this.filter("textarea").each(function(){
         new Texyla(this,options)
      })
   }
});
jQuery.extend({
   texyla:function(options){
      jQuery("textarea").texyla(options)
   }
});
function Texyla(textarea,options){
   this.options=jQuery.extend({},this.defaultOptions,options||{});
   this.textarea=jQuery(textarea);
   if(this.textarea.data("texyla"))return false;
   this.textarea.data("texyla",true);
   var lng=this.options.language;
   if(!this.languages[lng]){
      this.error("Language '"+lng+"' is not loaded.");
      return false
   }
   this.lng=this.languages[lng];
   this.baseDir=this.options.baseDir||this.baseDir;
   this.options.iconPath=this.expand(this.options.iconPath);
   this.options.previewPath=this.expand(this.options.previewPath);
   this.texy=new Texy(this);
   this.wrap();
   for(var i=0;    i<this.initPlugins.length;    i++){
      this.initPlugins[i].apply(this)
   }
   this.cStart = 125;
};

Texyla.prototype.expand=function(text,variable){
   text=text.replace("%texyla_base%",this.baseDir);
   if(variable){
      text=text.replace("%var%",variable)
   }
   return text
};

Texyla.prototype.initPlugins=[];
jQuery.texyla.setDefaults=function(defaults){
   jQuery.extend(Texyla.prototype.defaultOptions,defaults)
};

jQuery.texyla.initPlugin=function(pluginInit){
   Texyla.prototype.initPlugins.push(pluginInit)
};

jQuery.texyla.addButton=function(name,func){
   Texyla.prototype.buttons[name]=func
};

jQuery.texyla.extend=function(extendingObject){
   jQuery.extend(Texyla.prototype,extendingObject)
};

jQuery.texyla.addStrings=function(lng,strings){
   if(!Texyla.prototype.languages[lng]){
      Texyla.prototype.languages[lng]={}
   }
   jQuery.extend(Texyla.prototype.languages[lng],strings)
};

jQuery.texyla.setErrorHandler=function(handler){
   Texyla.prototype.error=handler
};

Texyla.prototype.submit=function(){
   var f=this.textarea.get(0).form;
   function submitnout(){
      if(f.submit.tagName==undefined){
         f.submit()
      }else{
         f.submit.click()
      }
   }
   if(typeof f.onsubmit=='function'){
      if(f.onsubmit()){
         submitnout()
      }
   }else{
      submitnout()
   }
};

Texyla.prototype.error=function(message){
   alert("Error: "+message)
};

Texyla.prototype.baseDir=jQuery("head script:last").attr("src").replace(/(\/js)?\/?[\w-]+\.js$/,'');
Texyla.prototype.languages={};

Texyla.prototype.defaultOptions={
   textarea:"textarea",
   width:null,
   padding:5,
   texyCfg:"",
   toolbar:['bold','italic',null,'ul','ol',null,'link',null,'emoticon','symbol',"img","table",null,['web']],
   bottomLeftToolbar:['edit','preview'],
   bottomRightEditToolbar:['syntax'],
   bottomRightPreviewToolbar:['submit'],
   buttonType:"span",
   tabs:false,
   defaultView:"edit",
   iconWidth:16,
   iconHeight:16,
   baseDir:null,
   iconPath:"%texyla_base%/icons/%var%.png",
   previewPath:"%texyla_base%/../php/preview.php",
   language:"cs"
};

function Selection(ta){
   this.textarea=ta
};

Selection.prototype={
   lineFeedFormat:null,
   lineFeedKnown:false,
   isIe:function(){
      if(this.textarea.selectionStart||this.textarea.selectionStart===0){
         return false
      }else if(document.selection){
         return true
      }
      return null
   },
   tag:function(firstText,secondText){
      this.update();
      this.changeSelection(firstText+this.text()+secondText);
      if(this.isCursor()){
         this.select(this.start+firstText.length,0)
      }else{
         this.select(this.start,firstText.length+this.length()+secondText.length)
      }
      this.cStart = -1;this.cEnd = -1;
      
   },
   replace:function(replacement){
      if(replacement===null)return;
      this.update();
      this.changeSelection(replacement);
      this.select(this.start,replacement.length)
      this.cStart = -1;this.cEnd = -1;
      
   },
   trimSelect:function(){
      this.update();
      if(this.text().substring(this.length(),this.length()-1)==" "){
         this.select(this.start,this.length()-1)
      }
      
      return this.update()
   },
   phrase:function(firstText,secondText){
      this.trimSelect().tag(firstText,secondText?secondText:firstText)
      
   },
   changeSelection:function(replacement){
      var scrolled=this.textarea.scrollTop;
      var val=this.textarea.value;
      this.textarea.value=val.substring(0,this.start)+replacement+val.substring(this.end);
      this.textarea.scrollTop=scrolled
      
   },
   lf:function(){
      if(this.lineFeedKnown)return this.lineFeedFormat;
      var unix=this.textarea.value.indexOf('\n');
      var mac=this.textarea.value.indexOf('\r');
      var win=this.textarea.value.indexOf('\r\n');
      var lineFeed=null;
      if(unix>=0)lineFeed='\n';
      if(mac>=0)lineFeed='\r';
      if(win>=0)lineFeed='\r\n';
      if(lineFeed){
         this.lineFeedFormat=lineFeed;
         this.lineFeedKnown=true;
         return lineFeed
      }

      return document.selection?'\r\n':'\n'
   },
   update:function(){
      this.textarea.focus();
      if(this.cStart!=-1) {
         this.start = this.cStart;
         this.end = this.cEnd;
         
      }else{
      if(this.isIe()){
         var range=document.selection.createRange();
         var bookmark=range.getBookmark();
         var contents=this.textarea.value;
         var originalContents=contents;
         var marker="[~M~A~R~K~E~R~]";
         while(contents.indexOf(marker)!=-1){
            marker=marker+Math.random()
         }
         range.text=marker+range.text+marker;
         contents=this.textarea.value;
         this.start=contents.indexOf(marker);
         contents=contents.replace(marker,"");
         this.end=contents.indexOf(marker);
         this.textarea.value=originalContents;
         range.moveToBookmark(bookmark);
         range.select()
      }else{
         this.start=this.textarea.selectionStart;
         this.end=this.textarea.selectionEnd
      }
      }
      return this
   },
   cUpdate:function(){
      this.textarea.focus();
      if(this.isIe()){
         var range=document.selection.createRange();
         var bookmark=range.getBookmark();
         var contents=this.textarea.value;
         var originalContents=contents;
         var marker="[~M~A~R~K~E~R~]";
         while(contents.indexOf(marker)!=-1){
            marker=marker+Math.random()
         }
         range.text=marker+range.text+marker;
         contents=this.textarea.value;
         this.cStart=contents.indexOf(marker);
         contents=contents.replace(marker,"");
         this.cEnd=contents.indexOf(marker);
         this.textarea.value=originalContents;
         range.moveToBookmark(bookmark);
         range.select()
      }else{
         this.cStart=this.textarea.selectionStart;
         this.cEnd=this.textarea.selectionEnd
      }
      return this
   },
   length:function(){
      return this.end-this.start
   },
   text:function(){
      return this.textarea.value.substring(this.start,this.end)
   },
   isCursor:function(){
      return this.start==this.end
   },
   select:function(from,length){

      if(this.isIe()){
         var lfCount=this.textarea.value.substring(0,from).split("\r\n").length-1;
         from-=lfCount;
         this.textarea.focus();
         this.textarea.select();
         var ieSelected=document.selection.createRange();
         ieSelected.collapse(true);
         ieSelected.moveStart("character",from);
         ieSelected.moveEnd("character",length);
         ieSelected.select()
      }else{
         this.textarea.selectionStart=from;
         this.textarea.selectionEnd=from+length
      }
      this.textarea.focus()
   },
   selectBlock:function(){
      this.update();
      var lf=this.lf();
      var ta=this.textarea;
      var workFrom=ta.value.substring(0,this.start).lastIndexOf(lf);
      if(workFrom!==-1)workFrom+=lf.length;
      var from=Math.max(0,workFrom);
      var len=ta.value.substring(from,this.start).length+this.length();
      var fromSelectionEnd=ta.value.substring(this.end,ta.value.length);
      var lineFeedPos=fromSelectionEnd.indexOf(lf);
      len+=lineFeedPos==-1?fromSelectionEnd.length:lineFeedPos;
      this.select(from,len);
      return this.update()
   }
};

function Texy(texyla){
   this.textarea=texyla.textarea.get(0);
   this.texyla=texyla
   this.cStart = -1;this.cEnd = -1;
};

Texy.prototype=jQuery.extend({},Selection.prototype,{
   bold:function(){
      this.trimSelect();
      var text=this.text();
      if(text.match(/^\*\*.*\*\*$/)){
         this.replace(text.substring(2,text.length-2))
      }else{
         this.tag("**","**")
      }
   },
   italic:function(){
      this.trimSelect();
      var text=this.text();
      if(text.match(/^\*\*\*.*\*\*\*$/)||text.match(/^\*[^*]+\*$/)){
         this.replace(text.substring(1,text.length-1))
      }else{
         this.tag("*","*")
      }
   },
   block:function(what){
      this.tag('/--'+what+this.lf(),this.lf()+'\\--')
   },
   link:function(addr){
      if(addr)this.phrase('"','":'+addr)
   },
   acronym:function(title){
      this.update();
      if(title){
         if(this.text().match(/^[a-zA-ZěščřžýáíéúůĚŠČŘŽÝÁÍÉÚŮ]{2,}$/)){
            this.tag('','(('+title+'))')
         }else{
            this.phrase('"','"(('+title+'))')
         }
      }
   },
   line:function(){
      this.update();
      var lf=this.lf();
      var lineText=lf+lf+'-------------------'+lf+lf;
      if(this.isCursor())this.tag(lineText,'');else this.replace(lineText)
   },
   align:function(type){
      this.update();
      var lf=this.lf();
      var start='.'+type+lf;
      var newPar=lf+lf;
      var found=this.textarea.value.substring(0,this.start).lastIndexOf(newPar);
      var beforePar=found+newPar.length;
      if(found==-1){
         this.textarea.value=start+this.textarea.value
      }else{
         this.textarea.value=this.textarea.value.substring(0,beforePar)+start+this.textarea.value.substring(beforePar)
      }
      this.select(this.start+start.length,this.length())
   },
   _toRoman:function(num){
      num=Math.min(parseInt(num,10),5999);
      var mill=['','M','MM','MMM','MMMM','MMMMM'],cent=['','C','CC','CCC','CD','D','DC','DCC','DCCC','CM'],tens=['','X','XX','XXX','XL','L','LX','LXX','LXXX','XC'],ones=['','I','II','III','IV','V','VI','VII','VIII','IX'],m,c,t,r=function(n){
         n=(num-(num%n))/n;
         return n
      };

      m=r(1000);
      num=num%1000;
      c=r(100);
      num=num%100;
      t=r(10);
      return mill[m]+cent[c]+tens[t]+ones[num%10]
   },
   _toLetter:function(n){
      var alphabet=["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
      return alphabet[Math.max(0,Math.min(n,alphabet.length)-1)]
   },
   list:function(type){
      this.selectBlock();
      var lf=this.lf();
      var lines=this.text().split(lf);
      var lineCt=this.isCursor()?3:lines.length;
      var replacement='';
      for(var i=1;i<=lineCt;i++){
         var bullet={
            ul:'-',
            ol:i+')',
            bq:'>',
            indent:'',
            romans:this._toRoman(i)+')',
            smallRomans:this._toRoman(i).toLowerCase()+')',
            smallAlphabet:this._toLetter(i)+')',
            bigAlphabet:this._toLetter(i).toUpperCase()+')'
         };

         replacement+=bullet[type]+' '+(!this.isCursor()?lines[i-1]:'')+(i!=lineCt?lf:'');
         if(this.isCursor()&&i===1)var curPos=replacement.length-1
      }
      if(this.isCursor()){
         this.tag(replacement.substring(0,curPos),replacement.substring(curPos))
      }else{
         this.replace(replacement)
      }
   },
   indent:function(){
      this.list("indent")
   },
   unindent:function(){
      this.selectBlock();
      var lines=this.text().split(this.lf());
      var replacement=[];
      for(var i=0;i<lines.length;i++){
         var first=lines[i].substring(0,1);
         if(first==" "||first=="\t"){
            replacement.push(lines[i].substring(1,lines[i].length))
         }else{
            replacement.push(lines[i])
         }
      }
      this.replace(replacement.join(this.lf()))
   },
   moje:function(){
      this.selectBlock();
      var lines=this.text().split(this.lf());
      var replacement=[];
      for(var i=0;i<lines.length;i++){
         replacement[i]=lines[i];
         H = RegExp("(^[-#\\*=]+$)");
         if (H.test(replacement[i])){
            replacement[i]='';
         }
         var B = /[\*]{1,2}([^\*]+)[\*]{1,2}/g;
         replacement[i]=replacement[i].replace(B,'$1');

         var S1 = /"([^\[]+)\.\[[^\]]*\]"/g;
         replacement[i]=replacement[i].replace(S1,'$1');

         var S = /\.\[[^\]]*\]/g;
         replacement[i]=replacement[i].replace(S,'');

         var A = /\.\<|\.\>|\.\<\>|\=/g;
         replacement[i]=replacement[i].replace(A,'');

      }
      this.replace(replacement.join(this.lf()))
   },
   style:function(type){
      this.trimSelect();
      var text=this.text();
      var bi = /^([\*]{1,2})[^*]+([\*]{1,2})$/
      var result = text.match(bi);
      if (result) {
         this.replace(text.substring(result[1].length,text.length-result[2].length))
         this.tag(result[1],' .['+type+']'+result[2]);
      }
      else {
         this.tag('"',' .['+type+']"');
      }
        

        
        
   },
   heading:function(type){
      this.selectBlock();
      var lf=this.lf();
      function underline(len,type){
         var txt='';
         for(var i=0;i<Math.max(3,len);i++){
            txt+=type
         }
         return txt
      }
      if(this.isCursor()){
         var headingText=prompt(this.texyla.lng.texyHeadingText,'');
         if(headingText){
            this.tag(headingText+lf+underline(headingText.length,type)+lf,'')
         }
      }else{
         this.tag('',lf+underline(this.length(),type))
      }
   },
   img:function(src,alt,lightBox,align,descr){
      var imgT='';
      if(align=='<>'){
         imgT+=this.lf()+'.<>'+this.lf();
         align=false
      }
      if(lightBox){
         imgT+='[* thumb/'+src+' ';
         imgT+=alt?'.('+alt+') ':'';
         imgT+=(align?align:'*')+']';
         imgT+=':[* '+src+' *]';
         imgT+=descr?' *** '+alt:'';
      }
      else {
         imgT+='[* '+src+' ';
         imgT+=alt?'.('+alt+') ':'';
         imgT+=(align?align:'*')+']';
         imgT+=descr?' *** '+alt:'';
      }
      this.replace(imgT)
   },
   table:function(cols,rows,header){
      var lf=this.lf();
      var tabTxt=lf;
      for(var i=0;i<rows;i++){
         if(header==='n'&&i<2){
            tabTxt+='|';
            for(var j=0;j<cols;++j){
               tabTxt+='--------'
            }
            tabTxt+=lf
         }
         for(j=0;j<cols;j++){
            if(header==='l'&&j===0){
               tabTxt+="|* \t"
            }else{
               tabTxt+="| \t"
            }
            if(i===0&&j===0)var curPos=tabTxt.length-1
         }
         tabTxt+='|'+lf
      }
      tabTxt+=lf;
      this.tag(tabTxt.substring(0,curPos),tabTxt.substring(curPos))
   }
});
jQuery.fn.extend({
   ajaxUpload:function(callback){
      if(!this.is("form"))return;
      if(!arguments.callee.count){
         arguments.callee.count=0
      }
      var target="ajaxUploadFrame"+(++arguments.callee.count);
      var iframe=jQuery('<iframe src="" width="1" height="1" frameborder="0" '+'name="'+target+'"></iframe>');
      iframe.css({
         visibility:"hidden",
         position:"absolute",
         left:"-1000px",
         top:"-1000px"
      });
      iframe.appendTo("body");
      iframe.load(function(){
         jQuery.event.trigger("ajaxComplete");
         var iframeEl=iframe.get(0);
         var body;
         if(iframeEl.contentDocument){
            body=iframeEl.contentDocument.body
         }else{
            body=iframeEl.contentWindow.document.body
         }
         var content=$(body).text();
         if(!content){
            callback()
         }else{
            eval("var data = "+content+";");
            callback(data)
         }
         setTimeout(function(){
            iframe.remove()
         },1000)
      });
      this.attr({
         target:target,
         method:"post",
         enctype:"multipart/form-data"
      }).submit();
      jQuery.event.trigger("ajaxStart")
   }
});
(function($){
   $.texyla.addStrings("cs",{
      btn_h1:"Nejv\u011bt\u0161í nadpis",
      btn_h2:"Velký nadpis",
      btn_h3:"St\u0159ední nadpis",
      btn_h4:"Nejmen\u0161í nadpis",
      btn_bold:"Tu\u010dn\u011b",
      btn_italic:"Kurzíva",
      btn_del:"P\u0159e\u0161krtnuto",
      btn_center:"Zarovnání na st\u0159ed",
      btn_left:"Zarovnání vlevo",
      btn_right:"Zarovnání vpravo",
      btn_justify:"Zarovnání do bloku",
      btn_ul:"Seznam",
      btn_ol:"\u010císlovaný seznam",
      btn_olRomans:"\u0158ímské \u010díslování",
      btn_olRomansSmall:"Malé \u0159ímské \u010díslování",
      btn_olAlphabetSmall:"Malá abeceda",
      btn_olAlphabetBig:"Velká abeceda",
      btn_blockquote:"Bloková citace",
      btn_sub:"Dolní index",
      btn_sup:"Horní index",
      btn_link:"Odkaz",
      btn_acronym:"Vysv\u011btlení zkratky",
      btn_hr:"\u010cára",
      btn_code:"Kód",
      btn_codeHtml:"Kód html",
      btn_codeCss:"Kód CSS",
      btn_codeJs:"Kód javascript",
      btn_codePhp:"Kód php",
      btn_codeSql:"Kód SQL",
      btn_comment:"Komentá\u0159",
      btn_div:"Blok div",
      btn_text:"Text",
      btn_codeInline:"Inline kód",
      btn_html:"HTML",
      btn_notexy:"Inline text",
      btn_edit:"Upravit",
      btn_preview:"Náhled",
      btn_htmlPreview:"HTML",
      btn_syntax:"Nápov\u011bda",
      btn_submit:"Odeslat",
      btn_web:"Web editoru Texyla",
      btn_unformat: "Zrušit formátování",
      btn_orange: "Oranžový text",
      texyHeadingText:"Text nadpisu",
      acronymTitle:"Titulek",
      linkUrl:"Adresa odkazu",
      wait:"Prosím \u010dekejte",
      viewEmpty:"Textové pole je prázdné!",
      windowOk:"OK",
      windowClose:"Zav\u0159ít",
      windowCancel:"Storno",
      windowCloseAfterInsert:"Zav\u0159ít po vlo\u017eení",
      syntaxUrl:"http://www.kreativnigalerie.cz/stranka/napoveda-editor",
      btn_color:"Barvy",
      win_color:"Vyberte barvu",
      colorSelectModeHeading:"Obarvit:",
      colorSelectModeText:"text",
      colorSelectModeBackground:'pozadí',
      btn_emoticon:"Smajlík",
      win_emoticon:"Vlo\u017eit smajlík",
      btn_files:"Soubory",
      win_files:"Soubory",
      filesUpload:"Nahrát",
      btn_img:"Obrázek",
      win_img:"Vlo\u017eit obrázek",
      imgSrc:"Adresa obrázku",
      imgAlt:"Popis",
      imgAlign:"Zarovnání",
      imgAlignNone:"\u017eádné",
      imgAlignLeft:"vlevo",
      imgAlignRight:"vpravo",
      imgAlignCenter:"na st\u0159ed",
      imgDescription:"Zobrazit jako popisek",
      win_link:"Vlo\u017eit odkaz",
      linkText:"Text odkazu",
      btn_symbol:"Symbol",
      win_symbol:"Vlo\u017eit symbol",
      btn_table:"Tabulka",
      win_table:"Vlo\u017eit tabulku",
      tableCols:"Po\u010det sloupc\u016f",
      tableRows:"Po\u010det \u0159ádek",
      tableTh:"Hlavi\u010dka",
      tableThNone:"\u017eádná",
      tableThTop:"naho\u0159e",
      tableThLeft:"vlevo",
      btn_textTransform:"Transformovat text",
      win_textTransform:"Vyberte transformaci",
      textTransformLower:"malá písmena",
      textTransformUpper:"VELKÁ PÍSMENA",
      textTransformCapitalize:"První Velká",
      textTransformFirstUpper:"První velké",
      textTransformUrl:"tvar-webove-adresy",
      btn_youtube:"YouTube",
      win_youtube:"YouTube",
      youtubeUrl:"Vlo\u017ete adresu videa nebo jeho ID",
      youtubePreview:"Náhled videa"
   });
   Texyla.prototype.buttons={
      unformat:function(){
         this.texy.moje('')
      },
      orange:function(){
         this.texy.style('orange')
      },
      h1:function(){
         this.texy.heading('#')
      },
      h2:function(){
         this.texy.heading('*')
      },
      h3:function(){
         this.texy.heading('=')
      },
      h4:function(){
         this.texy.heading('-')
      },
      bold:function(){
         this.texy.bold()
      },
      italic:function(){
         this.texy.italic()
      },
      del:function(){
         this.texy.phrase('--')
      },
      center:function(){
         this.texy.align('<>')
      },
      left:function(){
         this.texy.align('<')
      },
      right:function(){
         this.texy.align('>')
      },
      justify:function(){
         this.texy.align('=')
      },
      ul:function(){
         this.texy.list('ul')
      },
      ol:function(){
         this.texy.list('ol')
      },
      olRomans:function(){
         this.texy.list('romans')
      },
      olRomansSmall:function(){
         this.texy.list('smallRomans')
      },
      olAlphabetSmall:function(){
         this.texy.list('smallAlphabet')
      },
      olAlphabetBig:function(){
         this.texy.list('bigAlphabet')
      },
      blockquote:function(){
         this.texy.list('bq')
      },
      indent:function(){
         this.texy.indent()
      },
      unindent:function(){
         this.texy.unindent()
      },
      sub:function(){
         this.texy.phrase('__')
      },
      sup:function(){
         this.texy.phrase('^^')
      },
      link:function(){
         this.texy.link(prompt(this.lng.linkUrl,'http://'))
      },
      acronym:function(){
         this.texy.acronym(prompt(this.lng.acronymTitle,''))
      },
      hr:function(){
         this.texy.line()
      },
      code:function(){
         this.texy.block('code')
      },
      codeHtml:function(){
         this.texy.block('code html')
      },
      codeCss:function(){
         this.texy.block('code css')
      },
      codeJs:function(){
         this.texy.block('code js')
      },
      codePhp:function(){
         this.texy.block('code php')
      },
      codeSql:function(){
         this.texy.block('code sql')
      },
      codeInline:function(){
         this.texy.phrase('`')
      },
      html:function(){
         this.texy.block('html')
      },
      notexy:function(){
         this.texy.phrase("''","''")
      },
      web:function(){
         window.open('http://texyla.janmarek.net/')
      },
      syntax:function(){
         window.open(this.lng.syntaxUrl)
      },
      div:function(){
         this.texy.block('div')
      },
      comment:function(){
         this.texy.block('comment')
      },
      text:function(){
         this.texy.block('text')
      },
      preview:function(){
         this.view("preview")
      },
      htmlPreview:function(){
         this.view("htmlPreview")
      },
      edit:function(){
         this.view("edit")
      },
      submit:function(){
         this.submit()
      }
   };

   Texyla.prototype.wrap=function(){
      this.container=this.textarea.wrap('<div class="texyla"></div>').parent();
      var containerWidth=this.options.width||this.textarea.get(0).offsetWidth||this.textarea.width();
      this.container.width(containerWidth);
      this.editDiv=this.textarea.wrap('<div class="textarea-container"></div>').parent().wrap('<div class="edit-div"></div>').parent();
      if(this.textarea.get(0).offsetWidth>0){
         this.textarea.width(containerWidth);
         var delta=this.textarea.get(0).offsetWidth-containerWidth
      }else{
         var delta=0
      }
      this.textarea.width(containerWidth-delta-2*this.options.padding);
      this.textareaHeight=this.textarea.get(0).offsetHeight;
      this.previewDiv=$('<div class="preview-div"></div>').insertAfter(this.editDiv);
      this.previewDiv.prepend('<div class="view-header" style="background-image: url(\''+this.expand(this.options.iconPath,"preview")+'\');">'+this.lng.btn_preview+'</div>');
      this.preview=$('<div class="preview"></div>').appendTo(this.previewDiv).wrap('<div class="preview-wrapper ui-widget-content"></div>');
      this.htmlPreviewDiv=$('<div class="html-preview-div"></div>').insertAfter(this.previewDiv);
      this.htmlPreviewDiv.prepend('<div class="view-header" '+'style="background-image: url(\''+this.expand(this.options.iconPath,"htmlPreview")+'\');">'+this.lng.btn_htmlPreview+'</div>');
      this.htmlPreview=$('<pre class="html-preview"></pre>').appendTo(this.htmlPreviewDiv).wrap('<div class="preview-wrapper ui-widget-content"></div>');
      this.wait=$('<div class="preview-wait">'+this.lng.wait+'</div>');
      this.createToolbar();
      this.createBottomToolbar();
      this.view(this.options.defaultView,true)
   };

   Texyla.prototype.createToolbar=function(){
      var toolbar=$('<ul class="toolbar"></ul>').prependTo(this.editDiv);
      var item,toolbar2;
      for(var i=0;i<this.options.toolbar.length;i++){
         item=this.options.toolbar[i];
         if(typeof item=="string"){
            $("<span title='"+this.lng["btn_"+item]+"'>"+"<img src='"+this.expand(this.options.iconPath,item)+"' width='"+this.options.iconWidth+"' height='"+this.options.iconHeight+"'>"+"</span>").click(this.clickButton(item)).appendTo("<li class='btn_"+item+"'></li>").parent().appendTo(toolbar)
         }else if(item===null){
            toolbar.append("<li class='separator'></li>")
         }else if($.isArray(item)){
            toolbar2=$("<ul class='ui-widget-content ui-corner-all'></ul>");
            var menuTimeout;
            toolbar2.appendTo("<li class='menu'></li>").parent().mouseover(function(){
               clearTimeout(menuTimeout);
               $(this).siblings().find("ul:visible").fadeOut("fast");
               $(this).find("ul").show()
            }).mouseout(function(){
               var _this=this;
               menuTimeout=setTimeout(function(){
                  $(_this).find("ul").fadeOut("fast")
               },300)
            }).appendTo(toolbar);
            for(var j=0;j<item.length;j++){
               $("<li class='btn_"+item[j]+" ui-corner-all'>"+"<span style='background-image: url(\""+this.expand(this.options.iconPath,item[j])+"\");'>"+this.lng["btn_"+item[j]]+"</span></li>").hover(function(){
                  $(this).addClass("ui-state-hover")
               },function(){
                  $(this).removeClass("ui-state-hover")
               }).click(this.clickButton(item[j])).appendTo(toolbar2)
            }
         }else if(typeof(item)=="object"&&item.type=="label"){
            var text=item.translatedText?this.lng[item.translatedText]:item.text;
            toolbar.append("<li class='label ui-state-disabled'>"+text+"</li>")
         }
      }
   };

   Texyla.prototype.clickButton=function(name){
      var _this=this;
      if(name in this.buttons){
         return function(e){
            _this.buttons[name].call(_this,e)
         }
      }else{
         return function(){
            _this.error('Function "'+name+'" is not supported!')
         }
      }
   };

   Texyla.prototype.createBottomToolbar=function(){
      var bottomToolbar=$("<div class='bottom-toolbar'></div>").appendTo(this.container);
      this.leftToolbar=$("<div class='left-toolbar'></div>").appendTo(bottomToolbar);
      var right=$('<div class="right-toolbar"></div>').appendTo(bottomToolbar);
      this.rightEditToolbar=$("<div class='right-edit-toolbar'></div>").appendTo(right);
      this.rightPreviewToolbar=$("<div class='right-preview-toolbar'></div>").appendTo(right);
      if(this.options.tabs){
         this.leftToolbar.addClass("tabs")
      }else if(this.options.buttonType=="span"){
         this.leftToolbar.addClass("span-tb")
      }
      if(this.options.buttonType=="span"){
         right.addClass("span-tb")
      }
      var _this=this;
      function createButton(icon,name,func,tabs){
         var iconUrl=_this.expand(_this.options.iconPath,icon);
         if(_this.options.buttonType=="span"||tabs){
            return $("<span class='btn btn_"+icon+" ui-state-default "+(tabs?"ui-corner-bottom":"ui-corner-all")+"'>"+"<span class='btn-left'></span><span class='btn-middle'>"+"<span style='background-image: url(\""+iconUrl+"\");' class='icon-span'>"+name+"</span>"+"</span><span class='btn-right'></span>"+"</span>").click(func).hover(function(){
               $(this).addClass("ui-state-hover")
            },function(){
               $(this).removeClass("ui-state-hover")
            })
         }else{
            return $("<button type='button' class='btn_"+icon+"'>"+"<img src='"+iconUrl+"' width='"+_this.options.iconWidth+"' height='"+_this.options.iconHeight+"'>"+" "+name+"</button>").click(func)
         }
      };

      function insertButtons(toolbar,buttons,tabs){
         for(var i=0;i<buttons.length;i++){
            createButton(buttons[i],_this.lng["btn_"+buttons[i]],_this.clickButton(buttons[i]),tabs).appendTo(toolbar)
         }
      };

      insertButtons(this.leftToolbar,this.options.bottomLeftToolbar,this.options.tabs);
      insertButtons(this.rightEditToolbar,this.options.bottomRightEditToolbar);
      insertButtons(this.rightPreviewToolbar,this.options.bottomRightPreviewToolbar)
   };

   Texyla.prototype.view=function(type,first){
      var taVal=this.textarea.val();
      if(type!="edit"&&taVal==""){
         if(first){
            this.view("edit");
            return
         }
         alert(this.lng.viewEmpty);
         this.textarea.focus();
         return
      }
      switch(type){
         case"preview":
            this.previewDiv.show();
            this.htmlPreviewDiv.hide();
            this.editDiv.hide();
            this.rightPreviewToolbar.show();
            this.rightEditToolbar.hide();
            break;
         case"htmlPreview":
            this.previewDiv.hide();
            this.htmlPreviewDiv.show();
            this.editDiv.hide();
            this.rightPreviewToolbar.show();
            this.rightEditToolbar.hide();
            break;
         case"edit":
            this.previewDiv.hide();
            this.htmlPreviewDiv.hide();
            this.editDiv.show();
            this.rightPreviewToolbar.hide();
            this.rightEditToolbar.show();
            break
      }
      if(type!="edit"){
         var height=this.textarea.get(0).offsetHeight||this.textareaHeight;
         if(height){
            var curPrev=this[type=="preview"?"preview":"htmlPreview"].parent();
            curPrev.height(height);
            var delta=curPrev.get(0).offsetHeight-height;
            this.container.find("div.preview-wrapper").height(height-delta)
         }else{
            this.container.find("div.preview-wrapper").height("auto")
         }
      }
      if(this.options.tabs){
         var tabs=this.leftToolbar;
         tabs.find(".ui-state-active").removeClass("ui-state-active");
         tabs.find(".btn_"+type).addClass("ui-state-active")
      }else{
         var views=["preview","htmlPreview","edit"];
         for(var i=0;i<views.length;i++){
            if(views[i]==type){
               this.container.find(".btn_"+type).hide()
            }else{
               this.container.find(".btn_"+views[i]).show()
            }
         }
      }
      if(type!="edit"&&this.lastPreviewedTexy!=taVal){
         var _this=this;
         function onLoad(data){
            _this.preview.html(data).show();
            _this.htmlPreview.text(data.replace(new RegExp("\n","g"),_this.texy.lf())).show();
            if(typeof(_this.htmlPreview.jush)=="function"){
               _this.htmlPreview.jush("htm")
            }
            _this.wait.hide()
         };

         this.lastPreviewedTexy=taVal;
         var parent=this[type=="preview"?"preview":"htmlPreview"].parent();
         parent.prepend(this.wait);
         this.wait.show().css({
            marginTop:(parent.get(0).offsetHeight-this.wait.get(0).offsetHeight)/2,
            marginLeft:(parent.get(0).offsetWidth-this.wait.get(0).offsetWidth)/2
         });
         this.preview.hide();
         this.htmlPreview.hide();
         $.post(this.options.previewPath,{
            texy:taVal,
            cfg:this.options.texyCfg
         },onLoad,"html")
      }
   };

   $.texyla.initPlugin(function(){
      if(typeof(this.textarea.resizable)!="function")return;
      var _this=this;
      this.textarea.resizable({
         handles:'s',
         minHeight:80,
         stop:function(){
            _this.textareaHeight=_this.textarea.get(0).offsetHeight
         }
      });
      this.textarea.parent().css("padding-bottom",0)
   });
   $.texyla.initPlugin(function(){
      var _this=this;
      this.textarea.bind($.browser.opera?"keypress":"keydown",function(e){
         _this.keys(e)
      })
   });
   $.texyla.extend({
      keys:function(e){
         var pressedKey=e.charCode||e.keyCode||-1;
         var action=false;
         if(e.ctrlKey&&pressedKey==66&&!e.altKey){
            this.texy.bold();
            action=true
         }
         if(e.ctrlKey&&pressedKey==73){
            this.texy.italic();
            action=true
         }
         if(pressedKey==9&&e.shiftKey){
            this.texy.unindent();
            action=true
         }
         if(pressedKey==9&&!e.shiftKey){
            if(this.texy.update().text().indexOf(this.texy.lf())==-1){
               this.texy.tag('\t','')
            }else{
               this.texy.indent()
            }
            action=true
         }
         if(e.ctrlKey&&pressedKey==83){
            this.submit();
            action=true
         }
         if(action){
            if(e.preventDefault&&e.stopPropagation){
               e.preventDefault();
               e.stopPropagation()
            }else{
               window.event.cancelBubble=true;
               window.event.returnValue=false
            }
         }
      }
   });
   $.texyla.initPlugin(function(){
      this.openedWindows={}
   });
   $.texyla.addWindow=function(name,options){
      Texyla.prototype.windowConfigs[name]=options;
      if(options.dimensions){
         var defaults={};

         defaults[name+"WindowDimensions"]=options.dimensions;
         $.texyla.setDefaults(defaults)
      }
      $.texyla.addButton(name,function(){
         this.openWindow(name)
      })
   };

   $.texyla.extend({
      windowConfigs:{},
      openWindow:function(name){
         if(typeof(jQuery.fn.dialog)!="function"){
            this.error("jQuery UI plugin Dialog is not loaded.");
            return false
         }
         if(!Texyla.prototype.windowConfigs[name]){
            this.error("Window "+name+" is not defined.");
            return false
         }
         if(this.isWindowOpened(name)){
            return this.getWindow(name).dialog("moveToTop")
         }
         var config=Texyla.prototype.windowConfigs[name];
         var el=config.createContent.call(this);
         this.openedWindows[name]=el;
         var options=config.options||{};

         options.title=config.title?config.title:this.lng["win_"+name];
         var dimensions=this.options[name+"WindowDimensions"];
         if(dimensions){
            options.width=dimensions[0];
            options.height=dimensions[1]
         }
         var _this=this;
         if(config.action){
            options.buttons={};

            options.buttons[this.lng.windowOk]=function(){
               config.action.call(_this,el);
               if(!config.stayOpened){
                  _this.closeWindow(name)
               }
            };

            options.buttons[this.lng.windowCancel]=function(){
               _this.closeWindow(name)
            }
         }
         options.close=function(){
            _this.closeWindow(name)
         };

         el.dialog(options);
         el.find("input:first").focus();
         return el
      },
      closeWindow:function(name){
         this.openedWindows[name].dialog("destroy").remove();
         this.openedWindows[name]=null
      },
      isWindowOpened:function(name){
         return this.openedWindows[name]?true:false
      },
      getWindowAction:function(name){
         return Texyla.prototype.windowConfigs[name].action
      },
      getWindow:function(name){
         return this.openedWindows[name]?this.openedWindows[name]:null
      }
   });
   $.texyla.addWindow("img",{
      createContent:function(){
         return $('<div><table><tbody><tr>'+'<th><label>'+this.lng.imgSrc+'</label></th>'+'<td><input type="text" class="src"></td>'+'</tr><tr>'+'<th><label>'+this.lng.imgAlt+'</label></th>'+'<td><input type="text" class="alt"></td>'+'</tr><tr>'+'<td></td>'+'<td><label><input type="checkbox" class="descr">'+this.lng.imgDescription+'</label></td>'+'</tr><tr>'+'<td></td>'+'<td><label><input type="checkbox" class="lightBox">'+this.lng.imgLightBox+'</label></td>'+'</tr><tr>'+'<th><label>'+this.lng.imgAlign+'</label></th>'+'<td><select class="align">'+'<option value="*">'+this.lng.imgAlignNone+'</option>'+'<option value="<">'+this.lng.imgAlignLeft+'</option>'+'<option value=">">'+this.lng.imgAlignRight+'</option>'+'<option value="<>">'+this.lng.imgAlignCenter+'</option>'+'</select></td>'+'</tr></tbody></table></div>')
      },
      action:function(el){
         this.texy.img(el.find(".src").val(),el.find(".alt").val(),el.find(".lightBox").get(0).checked,el.find(".align").val(),el.find(".descr").get(0).checked)
      },
      dimensions:[350,250]
   });
   $.texyla.setDefaults({
      emoticonPath:"%texyla_base%/emoticons/texy/%var%.gif",
      emoticons:{
         ':-)':'smile',
         ':-(':'sad',
         ';-)':'wink',
         ':-D':'biggrin',
         '8-O':'eek',
         '8-)':'cool',
         ':-?':'confused',
         ':-x':'mad',
         ':-P':'razz',
         ':-|':'neutral'
      }
   });
   $.texyla.initPlugin(function(){
      this.options.emoticonPath=this.expand(this.options.emoticonPath)
   });
   $.texyla.addWindow("emoticon",{
      createContent:function(){
         var _this=this;
         var emoticons=$('<div></div>');
         var emoticonsEl=$('<div class="emoticons"></div>').appendTo(emoticons);
         for(var i in this.options.emoticons){
            function emClk(emoticon){
               return function(){
                  _this.texy.replace(emoticon);
                  if(emoticons.find("input.close-after-insert").get(0).checked){
                     emoticons.dialog("close")
                  }
               }
            };

            $("<img src='"+this.options.emoticonPath.replace("%var%",this.options.emoticons[i])+"' title='"+i+"' alt='"+i+"' class='ui-state-default'>").hover(function(){
               $(this).addClass("ui-state-hover")
            },function(){
               $(this).removeClass("ui-state-hover")
            }).click(emClk(i)).appendTo(emoticonsEl)
         }
         emoticons.append("<br><label><input type='checkbox' checked class='close-after-insert'> "+this.lng.windowCloseAfterInsert+"</label>");
         return emoticons
      },
      dimensions:[192,170]
   });
   $.texyla.addWindow("link",{
      dimensions:[330,180],
      createContent:function(){
         this.texy.cUpdate();
         return $('<div><table><tbody><tr>'+'<th><label>'+this.lng.linkText+'</label></th>'+'<td><input type="text" class="link-text" value="'+this.texy.trimSelect().text()+'"></td>'+'</tr><tr>'+'<th><label>'+this.lng.linkUrl+'</label></th>'+'<td><input type="text" class="link-url" value="http://"></td>'+'</tr></tbody></table></div>')
      },
      action:function(el){

         var txt=el.find(".link-text").val();
         txt=txt==''?'':'"'+txt+'":';
         this.texy.replace(txt+el.find(".link-url").val())
      }
   });
   $.texyla.setDefaults({
      symbols:["&","@",["<","&lt;"],[">","&gt;"],"[","]","{","}","\\","α","β","π","µ","Ω","∑","°","∞","≠","±","×","÷","≥","≤","®","™","€","£","$","~","^","·","•"]
   });
   $.texyla.addWindow("symbol",{
      dimensions:[300,230],
      createContent:function(){
         var _this=this;
         var el=$('<div></div>');
         var symbolsEl=$('<div class="symbols"></div>').appendTo(el);
         var symbols=this.options.symbols;
         for(var i=0;i<symbols.length;i++){
            function clk(text){
               return function(){
                  _this.texy.replace(text);
                  if(el.find("input.close-after-insert").get(0).checked){
                     el.dialog("close")
                  }
               }
            };

            $("<span class='ui-state-default'></span>").hover(function(){
               $(this).addClass("ui-state-hover")
            },function(){
               $(this).removeClass("ui-state-hover")
            }).text(symbols[i]instanceof Array?symbols[i][0]:symbols[i]).click(clk(symbols[i]instanceof Array?symbols[i][1]:symbols[i])).appendTo(symbolsEl)
         }
         el.append("<br><label><input type='checkbox' checked class='close-after-insert'> "+this.lng.windowCloseAfterInsert+"</label>");
         return el
      }
   });
   $.texyla.setDefaults({
      colors:['red','blue','aqua','black','fuchsia','gray','green','lime','maroon','navy','olive','orange','purple','silver','teal','white','yellow','#AABBCC']
   });
   $.texyla.addWindow("color",{
      createContent:function(){
         var _this=this;
         var colors=$('<div></div>');
         var colorsEl=$('<div class="colors"></div>').appendTo(colors);
         function colorClk(color){
            return function(){
               _this.texy.update();
               if(_this.texy.isCursor()){
                  _this.texy.selectBlock().phrase('',' .{color: '+color+'}')
               }else{
                  _this.texy.phrase('"',' .{color: '+color+'}"')
               }
               if(colors.find("input.close-after-insert").get(0).checked){
                  colors.dialog("close")
               }
            }
         }
         for(var i=0;i<_this.options.colors.length;i++){
            var color=_this.options.colors[i];
            $('<span class="ui-state-default ui-corner-all" title="'+color+'">'+'<span style="background-color:'+color+'">&nbsp;</span>'+'</span>').hover(function(){
               $(this).addClass("ui-state-hover")
            },function(){
               $(this).removeClass("ui-state-hover")
            }).click(colorClk(color)).appendTo(colorsEl)
         }
         colors.append("<br><label><input type='checkbox' checked class='close-after-insert'> "+this.lng.windowCloseAfterInsert+"</label>");
         return colors
      },
      dimensions:[200,150]
   });
   $.texyla.addWindow("textTransform",{
      createContent:function(){
         return $("<div><form>"+"<label><input type='radio' name='changeCase' value='lower'> "+this.lng.textTransformLower+"</label><br>"+"<label><input type='radio' name='changeCase' value='upper'> "+this.lng.textTransformUpper+"</label><br>"+"<label><input type='radio' name='changeCase' value='firstUpper'> "+this.lng.textTransformFirstUpper+"</label><br>"+"<label><input type='radio' name='changeCase' value='cap'> "+this.lng.textTransformCapitalize+"</label><br>"+"<label><input type='radio' name='changeCase' value='url'> "+this.lng.textTransformUrl+"</label>"+"</form></div>")
      },
      action:function(el){
         var text=this.texy.update().text();
         var newText=null;
         var transformation=el.find("form input:checked").val();
         switch(transformation){
            case"lower":
               newText=text.toLowerCase();
               break;
            case"upper":
               newText=text.toUpperCase();
               break;
            case"cap":
               newText=text.replace(/\S+/g,function(a){
               return a.charAt(0).toUpperCase()+a.substr(1,a.length).toLowerCase()
            });
            break;
            case"firstUpper":
               newText=text.charAt(0).toUpperCase()+text.substr(1,text.length).toLowerCase();
               break;
            case"url":
               var nodiac={
               'á':'a',
               'č':'c',
               'ď':'d',
               'é':'e',
               'ě':'e',
               'í':'i',
               'ň':'n',
               'ó':'o',
               'ř':'r',
               'š':'s',
               'ť':'t',
               'ú':'u',
               'ů':'u',
               'ý':'y',
               'ž':'z'
            };

            var s=text.toLowerCase();
               var s2='';
               for(var i=0;i<s.length;i++){
               s2+=(typeof nodiac[s.charAt(i)]!='undefined'?nodiac[s.charAt(i)]:s.charAt(i))
            }
            newText=s2.replace(/[^a-z0-9_]+/g,'-').replace(/^-|-$/g,'');
               break;default:
         }
         if(newText!==null){
            this.texy.replace(newText)
         }
      },
      dimensions:[220,210]
   });
   $.texyla.setDefaults({
      filesPath:"%texyla_base%/../php/plugins/files/files.php",
      filesThumbPath:"%texyla_base%/../php/plugins/files/thumbs.php?image=%var%",
      filesIconPath:"%texyla_base%/plugins/files/icons/%var%.png",
      filesUploadPath:"%texyla_base%/../php/plugins/files/upload.php"
   });
   $.texyla.initPlugin(function(){
      this.options.filesPath=this.expand(this.options.filesPath);
      this.options.filesUploadPath=this.expand(this.options.filesUploadPath)
   });
   $.texyla.addWindow("files",{
      dimensions:[400,350],
      createContent:function(){
         this.texy.cUpdate();
         var _this=this;
         var upload=$('<form action="'+this.options.filesUploadPath+'" class="upload" method="post" enctype="multipart/form-data"><div>'+'<input type="hidden" name="folder" class="folder" value="">'+'<input type="file" name="file" class="file"> '+'<input type="button" value="Nahrát" class="btn ui-state-default ui-corner-all">'+'</div></form>');
         var gallery=$('<div class="gallery"></div>');
         var el=$('<div />').append(upload).append(gallery);
         function createInsertImageFunc(img){
            return function(){
               var winEl=_this.openWindow("img");
               winEl.find(".src").val(img.insertUrl);
               winEl.find(".alt").val(img.description).select();
               el.dialog("close")
            }
         };

         function createInsertFileFunc(img){
            return function(){
               var winEl=_this.openWindow("link");
               winEl.find(".link-url").val(img.insertUrl);
               winEl.find(".link-text").val(img.description).select();
               el.dialog("close")
            }
         };

         function createChangeDir(dir){
            return function(){
               galleryReload(dir.key)
            }
         };

         upload.find(".btn").hover(function(){
            $(this).addClass("ui-state-hover")
         },function(){
            $(this).removeClass("ui-state-hover")
         }).click(function(){
            if(!upload.find(".file").val())return;
            el.ajaxStart(function(){
               el.html('<p class="wait">'+_this.lng.wait+'</p>')
            }).ajaxComplete(function(){
               el.dialog("close")
            });
            upload.ajaxUpload(function(data){
               if(data.error){
                  _this.error(data.error)
               }else{
                  if(data.type=="image"){
                     var imgWin=_this.openWindow("img");
                     imgWin.find(".src").val(data.filename);
                     imgWin.find(".alt").focus()
                  }else{
                     var linkWin=_this.openWindow("link");
                     linkWin.find(".link-url").val(data.filename);
                     linkWin.find(".link-text").focus()
                  }
               }
            })
         });
         function galleryReload(currentDir){
            gallery.empty().append('<p class="wait">'+_this.lng.wait+'</p>');
            upload.hide().find(".folder").val(currentDir);
            $.ajax({
               type:"GET",
               dataType:"json",
               cache:false,
               url:_this.options.filesPath,
               data:{
                  folder:currentDir
               },
               success:function(data){
                  gallery.empty();
                  upload.show();
                  var list=data.list;
                  for(var i=0;i<list.length;i++){
                     var item=$('<div class="gallery-item ui-state-default ui-corner-all">'+'<table><tr>'+'<td class="image"></td><td class="label"></td>'+'</tr></table>'+'</div>').hover(function(){
                        $(this).addClass("ui-state-hover")
                     },function(){
                        $(this).removeClass("ui-state-hover")
                     }).appendTo(gallery);
                     switch(list[i].type){
                        case"up":case"folder":
                           item.click(createChangeDir(list[i]));
                           item.find(".image").append('<img src="'+_this.expand(_this.options.filesIconPath,list[i].type)+'" width="16" height="16" alt="">');
                           item.find(".label").text(list[i].name);
                           break;
                        case"image":
                           item.click(createInsertImageFunc(list[i]));
                           item.find(".image").append('<image src="'+_this.expand(_this.options.filesThumbPath,list[i].thumbnailKey)+'">');
                           item.find(".label").append(list[i].name+'<br>'+'<small>'+list[i].description+'</small>');
                           break;
                        case"file":
                           item.click(createInsertFileFunc(list[i]));
                           item.find(".image").append('<img src="'+_this.expand(_this.options.filesIconPath,"file")+'" width="16" height="16" alt="">');
                           item.find(".label").append(list[i].name+'<br>'+'<small>'+list[i].description+'</small>');
                           break
                     }
                  }
               }
            })
         }
         galleryReload("");
         return el
      }
   });
   $.texyla.addWindow("table",{
      dimensions:[320,200],
      action:function(cont){
         this.texy.table(cont.find(".cols").val(),cont.find(".rows").val(),cont.find(".header").val())
      },
      createContent:function(){
         this.texy.cUpdate();
         var _this=this;
         var cont=$("<div style='position:relative'>"+'<table class="table"><tbody>'+'<tr><th><label>'+this.lng.tableCols+'</label></th><td><input type="number" class="cols" size="3" maxlength="2" min="1" value="2"></td></tr>'+'<tr><th><label>'+this.lng.tableRows+'</label></th><td><input type="number" class="rows" size="3" maxlength="2" min="1" value="2"></td></tr>'+'<tr><th><label>'+this.lng.tableTh+'</label></th><td><select class="header">'+'<option>'+this.lng.tableThNone+'</option>'+'<option value="n">'+this.lng.tableThTop+'</option>'+'<option value="l">'+this.lng.tableThLeft+'</option>'+'</select></td></tr></tbody></table>'+'<div class="tab-background"><div class="tab-selection"></div><div class="tab-control"></div></div>'+"</div>");
         var resizing=true,posX,posY;
         cont.find(".tab-control").click(function(e){
            resizing=!resizing
         }).mousemove(function(e){
            if(resizing){
               posX=e.pageX;
               var el=this;
               while(el.offsetParent){
                  posX-=el.offsetLeft;
                  el=el.offsetParent
               }
               posY=e.pageY;
               el=this;
               while(el.offsetParent){
                  posY-=el.offsetTop;
                  el=el.offsetParent
               }
               var cols=Math.ceil(posX/8);
               var rows=Math.ceil(posY/8);
               cont.find(".tab-selection").css({
                  width:cols*8,
                  height:rows*8
               });
               cont.find(".cols").val(cols);
               cont.find(".rows").val(rows)
            }
         }).dblclick(function(){
            _this.getWindowAction("table").call(_this,cont);
            cont.dialog("close")
         });
         cont.find(".cols, .rows").bind("change click blur",function(){
            var cols=Math.min(cont.find(".cols").val(),10);
            var rows=Math.min(cont.find(".rows").val(),10);
            cont.find(".tab-selection").css({
               width:cols*8,
               height:rows*8
            })
         });
         return cont
      }
   });
   $.texyla.setDefaults({
      youtubeMakro:"[* youtube:%var% *]"
   });
   $.texyla.addWindow("youtube",{
      createContent:function(){
         var el=$("<div><form><div>"+'<label>'+this.lng.youtubeUrl+'<br>'+'<input type="text" size="35" class="key">'+"</label><br><br>"+this.lng.youtubePreview+'</div>'+'<div class="thumb"></div>'+"</form></div>");
         el.find(".key").bind("keyup change",function(){
            var val=this.value;
            var key="";
            if(val.substr(0,7)=="http://"){
               var res=val.match("[?&]v=([a-zA-Z0-9-]+)");
               if(res)key=res[1]
            }else{
               key=val
            }
            $(this).data("key",key);
            el.find(".thumb").html('<img src="http://img.youtube.com/vi/'+key+'/1.jpg" width="120" height="90">')
         });
         return el
      },
      action:function(el){
         var txt=this.expand(this.options.youtubeMakro,el.find(".key").data("key"));
         this.texy.update().replace(txt)
      },
      dimensions:[320,300]
   });
   $.texyla.addStrings("cs",{})
})(jQuery);
