// global escope for variable
var pampaFormsUI;

/**
 * jquery extension for pampa forms
 * custom validation on submission
 */
 jQuery.fn.extend({pampaForm:function(){

  // alias scope
  var $this = $(this);

  // setup form masks
  if($.fn.setMask !== undefined){
    $this.find("input.decimal").setMask("decimal");
    $this.find("input").setMask();
  }

  // validate function
  this.validate({
    errorClass:'error help-inline',
    validClass:'success',
    errorElement:'span',
    highlight: function (element, errorClass, validClass) {
      $(element).parents("div.control-group").addClass('error').removeClass(validClass);
    },
    unhighlight: function (element, errorClass, validClass) {
      $(element).parents("div.control-group.error").removeClass('error').addClass(validClass);
    },
    submitHandler:function(form){
      // variable alias for scope
      var $form = $(form);

      // check if form has to conform
      if($form.hasClass("confirm")){
        if(!confirm("Are you sure?")){
          return false;
        }
      }

      // block form
      $form.block();

      // setup ajax request
      var isAjax = true;
      // check if form has a file upload
      if($form.find("input[type='file']").length > 0){
        // disable ajax submission
        isAjax = false;
      }
      if(isAjax === false){
        // create the iframe if necessary
        if($("#form_submit").length === 0){
          $('body').append('<iframe name="form_submit" id="form_submit" style="display:none" src="about:blank"></iframe>');
        }
        // setup form aditionals params
        $form.attr("enctype", "multipart/form-data");
        $form.attr("target", "form_submit");
        // submit form
        form.submit();
        return false;
      } else {
        // setup the form callback function
        var getResponse = function(rs){
          // valida o retorno
          if(rs.e){
            // set the html
            var msg_html = '<div class="alert alert-error fade in"><button type="button" class="close" data-dismiss="alert">×</button>'+ rs.m +'</div>';
            $('#layout').prepend(msg_html);

            // scroll window to top
            window.scrollTo(0,0);

            var $msgs = $('div.alert');

            if($msgs.length > 0){
              setTimeout(function(){
                $msgs.slideUp();
              },3500);
            }

            //alert(rs.m);
            $form.unblock();
          } else {
            window.location.href = $.baseURL(rs.r);
          }
        };
        // send post data with ajax
        $.post($form.attr("action"), $form.serializeArray(), getResponse, "json");
        return false;
      }
    }
  });
  return $(this);
}
});


 function PampaFormsUI(){

  // div box escope
  this.$divbox = $('div.box');

  // pampa forms selector
  this.pampaSelector = 'form.pampa_form';

  this.init = function(){
    this.setupUI();
    this.hideAllMessages();
    this.setupCombosWidth();
    this.setupBlockUI();
  };

  /**
   * perform all ui actions and adjusts
   */
   this.setupUI = function(){
    // adjust input fields widths
    $(".normal").css("width", this.getFormElementWidth()+"px");
    // check if there's more than 1 form box
    if(this.$divbox.length === 1){
      // remove box float and margin
      this.$divbox.css("float", "none").css("margin","0px auto");
    }

    // all confirm links check for confirmation
    $("a.confirm").click(function(){

      var message = 'Are you sure?';
      var meta = $(this).metadata();
      if(meta.msg){
        message = meta.msg;
      }
      return confirm(message);
    });

    // setup all fancybox links
    if($.colorbox !== undefined){
      $(".colorbox").colorbox();
    }

    // date pickers
    if($.datepicker){
      $(".datepicker").datepicker({dateFormat: "dd/mm/yy", autoclose: true});
    }

    // checkall boxes
    $("input#checkall").click(function(){
      // get current state
      var checked = $(this).attr("checked");

      // setup all others
      var $table = $("table.list");
      $table.find(":checkbox").attr("checked", checked);
    });

    // create all editor instances
    // this.createTinyMCE('textarea.tinymce');
    //this.createCKEditor('textarea.ckeditor');
// Creates a new plugin class


function arrumaAcentuacao(palavra){
    
    palavra = palavra.split('á').join('&aacute;');
    palavra = palavra.split('á').join('&aacute;');
    
    palavra = palavra.split('à').join('&agrave;');
    palavra = palavra.split('ã').join('&atilde;');
    palavra = palavra.split('â').join('&acirc;');
    palavra = palavra.split('é').join('&eacute;');
    palavra = palavra.split('é').join('&eacute;');
    palavra = palavra.split('ê').join('&ecirc;');
    palavra = palavra.split('í').join('&iacute;');
    palavra = palavra.split('í').join('&iacute;');
    palavra = palavra.split('ó').join('&oacute;');
    palavra = palavra.split('ó').join('&oacute;');
    palavra = palavra.split('õ').join('&otilde;');
    palavra = palavra.split('õ').join('&otilde;');
    palavra = palavra.split('ô').join('&ocirc;');
    palavra = palavra.split('ú').join('&uacute;');
    palavra = palavra.split('ú').join('&uacute;');
    palavra = palavra.split('ç').join('&ccedil;');
    return palavra;
}

tinymce.init({
  selector: "textarea.tinymce",
  content_css:[BASE_URL+'cms/js/tiny.css'],
    // theme: "modern",
    height: 300,   

    // paste_retain_style_properties : "text-align" ,
    // paste_auto_cleanup_on_paste : true,
    paste_postprocess: function(plugin, args) {
      // console.log(args.node);
      $no = $(args.node)
      
      $no.find('ol').each(function(){
        $ol = $(this);
        var html = $ol.html();
        html = html.split('<li').join('<p');
        html = html.split('</li').join('</p');          
        $ol.after($(html)).remove();
      });              
      var texto = $no.html();
      texto = arrumaAcentuacao(texto);
      $no.html(texto);
    },
    plugins: ["autosave",
    "advlist autolink link image lists charmap preview hr anchor pagebreak",
    "searchreplace wordcount visualblocks visualchars code fullscreen insertdatetime media nonbreaking",
    "table contextmenu directionality emoticons paste textcolor "
    ],
    

    toolbar: "itemsumario,itemsumarioback,citacao,insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image | preview media fullpage | forecolor backcolor emoticons",
    paste_data_images: true,
    setup : function(ed) {

  

      ed.addButton('citacao', {
        title : 'Configurar citação',
        image : 'img/citacao.gif',
        onclick : function() {

          ed.focus();

          var texto = ed.selection.getContent();
          ed.windowManager.open({
            title: 'Configurar citação',
            body: [
            // {type: 'textbox', name: 'texto', label: 'Texto'},
            // { type: 'container',name: 'css',html: '<style>.itemCitacao {resize: none;}#view_text {width: 400px; height:200px;border: 1px solid #c5c5c5; border-radius:4px;}.btnformat{background-color: #fff; border:1px solid #999;width:10px !important;text-align:center;border-radius: 4px;padding: 4px;}</style>'},
            // { type: 'container',name: 'code',html: '<input type="button" value="B" class="btnformat bold" />&nbsp;&nbsp;<input type="button" value="I" class="btnformat italic" /><br/><br/><iframe frameborder="0" id="view_text"></iframe>'},  
            { type: 'container',name: 'texto',html: '<textarea name="textarea" id="itemCitacao1" class="itemCitacao" style="padding: 10px; width: 400px;  border:1px solid #c5c5c5;height: 200px ;""></textarea>'}
            ],
            onsubmit: function(e) {
              /* Insert content when the window form is submitted*/  
              if (texto.indexOf('data-texto')>-1) {                

                ed.selection.setContent('<a class="nota_citacao" href="#" data-texto="'+$('#itemCitacao1').val()+'" >' +$(texto).html() + '</a>')
                // ed.selection.setContent('<a class="nota_citacao" href="#" data-texto="'+$("#view_text").contents().find("body").html()+'" >' +$(texto).html() + '</a>')
              }else{
                ed.selection.setContent('<a class="nota_citacao" href="#" data-texto="'+$('#itemCitacao1').val()+'" >' + ed.selection.getContent() + '</a>');                 
                // ed.selection.setContent('<a class="nota_citacao" href="#" data-texto="'+$("#view_text").contents().find("body").html()+'" >' + ed.selection.getContent() + '</a>');                 
              }     
            }            
          });  
          $(document).ready(function(){
            // document.getElementById('view_text').contentWindow.document.open();
            // document.getElementById('view_text').contentWindow.document.close();
            // document.getElementById('view_text').contentWindow.document.designMode="on";
            // var edit =  document.getElementById('view_text').contentWindow;
            // edit.focus();
            // $('.btnformat.bold').click(function(){
            //    var edit = document.getElementById("view_text").contentWindow;
            //    edit.focus();
            //     edit.document.execCommand("bold", false, "");
            //     edit.focus();
            // });
            // $('.btnformat.italic').click(function(){
            //    var edit = document.getElementById("view_text").contentWindow;
            //    edit.focus();
            //     edit.document.execCommand("italic", false, "");
            //     edit.focus();
            // });
            
            if (texto.indexOf('data-texto')>-1) {
              // $("#view_text").contents().find("body").html($(texto).data('texto'));
              $('#itemCitacao1').val($(texto).data('texto'));
            }       
          });     


        } 
      });

      ed.addButton('itemsumario', {
        title : 'Configurar como subitem de sumário',
        image : 'img/submenu.gif',
        onclick : function() {

          ed.focus();

          ed.selection.collapse(false);  



          var texto = ed.selection.getContent({format : 'text'});



          /* console.log(texto);*/
          var node = ed.selection.getNode();
          console.log(node.tagName);
          var rng = ed.selection.getRng();
          console.log(rng);
          ed.selection.select(node);
          if (node.tagName!='DIV' && node.tagName!='BODY' && node.tagName!='HTML') {

            if(node.classList.contains('subitem-sumario')){
              if(node.classList.contains('itemfilho')){
                console.log('ja tinha filho');
                if(node.classList.contains('nivel1')){
                  node.classList.remove('nivel1');
                  node.classList.add('nivel2');
                }else if(node.classList.contains('nivel2')){
                  node.classList.remove('nivel2');
                  node.classList.add('nivel3');
                }else if(node.classList.contains('nivel3')){
                  node.classList.remove('nivel3');
                  node.classList.add('nivel4');
                }else if(node.classList.contains('nivel4')){
                  node.classList.remove('nivel4');
                  node.classList.add('nivel5');
                }else if(node.classList.contains('nivel5')){
                  node.classList.remove('nivel5');
                  node.classList.add('nivel6');
                }else if(node.classList.contains('nivel6')){
                  node.classList.remove('nivel6');
                  node.classList.add('nivel7');
                }else if(node.classList.contains('nivel7')){
                  node.classList.remove('nivel7');
                  node.classList.add('nivel8');
                }

              }else{
                node.classList.add('itemfilho');
                node.classList.add('nivel1');
              }
            }else{
             node.classList.add('subitem-sumario');
           }
           ed.selection.setRng(rng);
         }
       }
     });
      ed.addButton('itemsumarioback', {
        title : 'Voltar nivel de subitem do sumario',
        image : 'img/submenuback.gif',
        onclick : function() {
                // Add you own code to execute something on click
                ed.focus();
                // ed.selection.select(ed.getBody(), true);
                ed.selection.collapse(false);  

                // var bm = ed.selection.getBookmark();

                var texto = ed.selection.getContent({format : 'text'});
                


                    // console.log(texto);
                    var node = ed.selection.getNode();
                    console.log(node.tagName);
                    var rng = ed.selection.getRng();
                    console.log(rng);
                    ed.selection.select(node);
                    if (node.tagName!='DIV' && node.tagName!='BODY' && node.tagName!='HTML') {

                      if(node.classList.contains('subitem-sumario')){
                        if(node.classList.contains('itemfilho')){
                          console.log('ja tinha filho');
                          if(node.classList.contains('nivel1')){
                            node.classList.remove('nivel1');                            
                          }else if(node.classList.contains('nivel2')){
                            node.classList.remove('nivel2');
                            node.classList.add('nivel1');
                          }else if(node.classList.contains('nivel3')){
                            node.classList.remove('nivel3');
                            node.classList.add('nivel2');
                          }else if(node.classList.contains('nivel4')){
                            node.classList.remove('nivel4');
                            node.classList.add('nivel3');
                          }else if(node.classList.contains('nivel5')){
                            node.classList.remove('nivel5');
                            node.classList.add('nivel4');
                          }else if(node.classList.contains('nivel6')){
                            node.classList.remove('nivel6');
                            node.classList.add('nivel5');
                          }else if(node.classList.contains('nivel7')){
                            node.classList.remove('nivel7');
                            node.classList.add('nivel6');
                          }else if(node.classList.contains('nivel8')){
                            node.classList.remove('nivel8');
                            node.classList.add('nivel7');
                          }else{
                            node.classList.remove('itemfilho');                            
                          }

                        }else{                          
                          node.classList.remove('subitem-sumario');
                        }
                      }else{
                       // node.classList.add('subitem-sumario');
                     }
                     ed.selection.setRng(rng);
                   }
                 }
               });

    }

  });


    // setup all pampa forms
    $(this.pampaSelector).pampaForm();
  };

  /**
   * creates a tinymce editor instance
   * @param selector
   */
  // this.createTinyMCE = function(selector){
  //   var $selector = $(selector);
  //   if($selector.length === 0){
  //     return;
  //   }
  //   //console.log(pampaFormsUI.getFormElementWidth());

  //   $selector.each(function(){
  //     var $textArea = $(this);
  //     $textArea.tinymce({
  //       // location of tinymce script
  //       script_url : $.baseURL('js/tiny_mce/tiny_mce.js'),
  //       valid_elements : '*[*]',
  //       // valid_elements : ""
  //       // +"@[accesskey|draggable|style|class|hidden|tabindex|contenteditable|id|title|contextmenu|lang|dir<ltr?rtl|spellcheck|"
  //       //   +"onabort|onerror|onmousewheel|onblur|onfocus|onpause|oncanplay|onformchange|onplay|oncanplaythrough|onforminput|onplaying|onchange|oninput|onprogress|onclick|oninvalid|onratechange|oncontextmenu|onkeydown|onreadystatechange|ondblclick|onkeypress|onscroll|ondrag|onkeyup|onseeked|ondragend|onload|onseeking|ondragenter|onloadeddata|onselect|ondragleave|onloadedmetadata|onshow|ondragover|onloadstart|onstalled|ondragstart|onmousedown|onsubmit|ondrop|onmousemove|onsuspend|ondurationmouseout|ontimeupdate|onemptied|onmouseover|onvolumechange|onended|onmouseup|onwaiting],"
  //       // +"a[target<_blank?_self?_top?_parent|ping|media|href|hreflang|type"
  //       //   +"|rel<alternate?archives?author?bookmark?external?feed?first?help?index?last?license?next?nofollow?noreferrer?prev?search?sidebar?tag?up"
  //       //   +"],"
  //       // +"abbr,"
  //       // +"address,"
  //       // +"area[alt|coords|shape|href|target<_blank?_self?_top?_parent|ping|media|hreflang|type|shape<circle?default?poly?rect"
  //       //   +"|rel<alternate?archives?author?bookmark?external?feed?first?help?index?last?license?next?nofollow?noreferrer?prev?search?sidebar?tag?up"
  //       //   +"],"
  //       // +"blockquote[cite],"
  //       // +"br,"
  //       // +"caption,"
  //       // +"cite,"
  //       // +"code,"
  //       // +"col[span],"
  //       // +"colgroup[span],"
  //       // +"dd,"
  //       // +"del[cite|datetime],"
  //       // +"details[open<open],"
  //       // +"dfn,"
  //       // +"dl,"
  //       // +"dt,"
  //       // +"-em/i,"
  //       // +"embed[src|type|width|height],"
  //       // +"eventsource[src],"
  //       // +"fieldset[disabled<disabled|form|name],"
  //       // +"figcaption,"
  //       // +"figure,"
  //       // +"-h1,-h2,-h3,-h4,-h5,-h6,"
  //       // +"hgroup,"
  //       // +"hr,"
  //       // +"iframe[name|src|srcdoc|seamless<seamless|width|height|sandbox],"
  //       // +"img[alt=|src|ismap|usemap|width|height],"
  //       // +"ins[cite|datetime],"
  //       // +"kbd,"
  //       // +"keygen[autofocus<autofocus|challenge|disabled<disabled|form|name],"
  //       // +"legend,"
  //       // +"li[value],"
  //       // +"mark,"
  //       // +"meter[value|min|low|high|max|optimum],"
  //       // +"object[data|type|name|usemap|form|width|height],"
  //       // +"ol[reversed|start],"
  //       // +"optgroup[disabled<disabled|label],"
  //       // +"option[disabled<disabled|label|selected<selected|value],"
  //       // +"output[for|form|name],"
  //       // +"-p,"
  //       // +"param[name,value],"
  //       // +"-pre,"
  //       // +"progress[value,max],"
  //       // +"q[cite],"
  //       // +"ruby,"
  //       // +"rp,"
  //       // +"rt,"
  //       // +"samp,"
  //       // +"section,"
  //       // +"small,"
  //       // +"source[src|type|media],"
  //       // +"-span,"
  //       // +"-strong/b,"
  //       // +"-sub,"
  //       // +"summary,"
  //       // +"-sup,"
  //       // +"table,"
  //       // +"tbody,"
  //       // +"td[colspan|rowspan|headers],"
  //       // +"tfoot,"
  //       // +"th[colspan|rowspan|headers|scope],"
  //       // +"thead,"
  //       // +"time[datetime],"
  //       // +"tr,"
  //       // +"ul,"
  //       // +"var,"
  //       // +"video[preload<none?metadata?auto|src|crossorigin|poster|autoplay<autoplay|"
  //       //   +"mediagroup|loop<loop|muted<muted|controls<controls|width|height],"
  //       // +"wbr",

  //       // General options
  //       theme : "advanced",
  //       plugins : "advimage,advlink,inlinepopups,searchreplace,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,advlist,media,table,preview,youtubeIframe",

  //       // Theme options
  //       theme_advanced_buttons1:"mylistbox | bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,link,unlink,anchor,|,formatselect,|,youtubeIframe",
  //       theme_advanced_buttons2:"preview,|,pastetext,pasteword,|,table,|,forecolor,backcolor,|,search,replace,|,outdent,indent,blockquote,cite,|,undo,redo,|,image,|,removeformat,code",
  //       theme_advanced_buttons3 : "mylistbox",
  //       theme_advanced_buttons4 : "mylistbox",
  //       theme_advanced_toolbar_location : "top",
  //       theme_advanced_toolbar_align : "left",
  //       theme_advanced_statusbar_location : "bottom",
  //       theme_advanced_resizing : false,
  //       theme_advanced_resize_horizontal:false,
  //       width:(((pampaFormsUI.getFormElementWidth())> 530)? 530 : (pampaFormsUI.getFormElementWidth())),
  //       height:($textArea.hasClass('small')) ? 200 : 500,
  //       custom_shortcuts : false,
  //       file_browser_callback:"tinyBrowser",
  //       convert_urls:false,
  //       relative_urls:false,
  //       remove_script_host:false,
  //       content_css : $.baseURL('css/editor.css'),
  //       plugin_preview_width : "750",
  //       plugin_preview_height : "500",
  //       theme_advanced_blockformats : "p,h3,h4",
  //       setup: function(ed){
  //         if($textArea.hasClass('limit'))
  //         {
  //           ed.onKeyDown.add(function(ed, e) {

  //             //define local variables
  //             var tinymax, tinylen, htmlcount;

  //             //manually setting our max character limit
  //             tinymax = $textArea.attr('data-limit');

  //             //grabbing the length of the curent editors content
  //             tinylen = ed.getContent().replace(/(<([^>]+)>)/ig,"").length;

  //             //setting up the text string that will display in the path area
  //             htmlcount = " - Character Count: " + tinylen + "/" + tinymax;

  //             // place text string in path bar
  //             if ( $('#max_char_string').size() ){
  //               $('#max_char_string').html( '&nbsp;' + htmlcount);
  //             }
  //             else {
  //               $("div#"+ed.id+"_path_row").append('<span id="max_char_string">&nbsp;'+htmlcount+'</span>')
  //             }

  //             //if the user has exceeded the max turn the path bar red.
  //             if (tinylen >= tinymax)
  //             {
  //               var code;
  //               if (!e) var e = window.event;
  //               if (e.keyCode) code = e.keyCode;
  //               else if (e.which) code = e.which;

  //               if (code == 8 || code == 46)
  //               {
  //                 // DELETE E BACKSPACE ARE OK!
  //               }
  //               else
  //               {
  //                 // prevent insertion of typed character
  //                 e.preventDefault();
  //                 e.stopPropagation();
  //                 return false;
  //               }
  //             }
  //           })

  //         }
  //       }
  //     });

  //   });
  // };

  /**
   * setup ajax errors handlers
   */
   this.setupAjaxErrors = function(){
    $.ajaxSetup({
      error:function(x,e){
        if(x.status === 0){
          alert('You are offline!!\n Please Check Your Network.');
        } else if(x.status === 404){
          alert('Requested URL not found.');
        } else if(x.status === 500){
          alert('Internel Server Error.');
        } else if(e === 'parsererror'){
          alert('Error.\nParsing JSON Request failed.');
        } else if(e === 'timeout'){
          alert('Request Time out.');
        } else {
          alert('Unknow Error.\n'+x.responseText);
        }
      }
    });
  };

  /**
   * hide all messages on screen
   */
   this.hideAllMessages = function(){
    var $msgs = $('div.alert');

    if($msgs.length > 0){
      setTimeout(function(){
        $msgs.slideUp();
      },3500);
    }
  };

  /**
   * adjust all combos to same size
   */
   this.setupCombosWidth = function(){
    // the initial combo size
    var select_size = 0;

    // combo list alias
    var $combos = $("table.table_form select");

    if($combos.length > 0){
      $combos.each(function(){
        // search for the largest combo
        if($(this).width() > select_size){
          select_size = $(this).width();
        }
      });

      // apply the width to all combos
      $combos.css("width", select_size+10+"px");
    }
  };

  /**
   * adjust blockui params such as message and css
   */
   this.setupBlockUI = function(){
    $.blockUI.defaults.message = '<img src="assets/images/upload.gif" id="ajax-loader" style="margin-right: 10px;" />Wait...';
    $.blockUI.defaults.css = {
      padding:        0,
      margin:         0,
      width:          '30%',
      top:            '40%',
      left:           '35%',
      textAlign:      'center',
      color:          '#000',
      border:         '0px',
      cursor:         'wait',
      fontSize:       '20px'
    };
    $.blockUI.defaults.overlayCSS =  {
      backgroundColor: '#FFF',
      opacity:         0.6
    };
  };

  /**
   * show a message in the form
   */
   this.showMessage = function(message, type){
    // check for empty messages
    if(message === undefined || message === ''){
      return;
    }

    // set the default type
    if(type === undefined || type === ''){
      type = 'error';
    }

    if(type == 'ok')
    {
      type = 'success';
    }

    // get for escope
    var $form = $(this.pampaSelector);

    // set the html
    var msg_html = '<div class="alert alert-'+ type +' fade in"><button type="button" class="close" data-dismiss="alert">×</button>'+ message +'</div>';
    //        "<div class='msg msg-" + type + "'><p>" + message + "</p></div>";
    $('#layout').prepend(msg_html);
    //$form.prepend(msg_html);

    // scroll window to top
    window.scrollTo(0,0);

    // call function to hide message
    this.hideAllMessages();
  };

  /**
   * return the element width based on using legend and fieldset
   */
   this.getFormElementWidth = function(){

    if(this.$divbox.find("legend")){
      return this.$divbox.width()-75;
    }
    console.log(this.$divbox.width());

    return this.$divbox.width()-40;
  };

  /**
   * block/unblock all pampa forms
   */
   this.blockForms = function(){
    $(this.pampaSelector).block();
  };
  this.unblockForms = function(){
    $(this.pampaSelector).unblock();
  };

}

// initialize the class
$(document).ready(function(){
  // initialize ui
  pampaFormsUI = new PampaFormsUI();
  pampaFormsUI.init();

  



});