/*  
 * Project: QShout - Shoutbox Widget for jQuery
 * Version: v1.1.8 (28/09/‎2010, ‏‎10:53 AM)
 * URL    : http://qshout.borisding.com
 * License: MIT  (http://www.opensource.org/licenses/mit-license.php)
 *          Copyright (c) 2010, Boris Ding P H
 */

(function(jQuery){
      //public QShout
      jQuery.QShout = function( uSettings ){                   
      //default settings    
       settings = {

        //misc.
        qsId        : "qsId",
        serverPage  : "index.php?ind=urlobox&op=save_msgblo",
        loader      : "Cargando...",
        timer       : 300000,
        maxRow      : 30,

        //shoutbox's body
        bFontSize   : "10px",
        bFontFamily : "Courier, Courier New, Verdana, Arial",
        blinkColor  : "#ffccff",

        //shoutbox's content
        bwidth      : "144px",
        bheight     : "300px",
        evenRowColor: "#f5f5f5",
        oddRowColor : "#ffffff",
        rowPadding  : "1px",
        ipCursor    : "help",
        dUrlColor   : "#888888",
        dbackColor   : "#FAFCFE",
        doverflowx   : "hidden",
        doverflowy   : "scroll",
        bBorderWidth: "1px",
        bBorderStyle: "dotted",
        bBorderColor: "#465584",
        dscf01   : "#8CB6E7",
        dscf02   : "#345487",
        dscf03   : "#345487",
        dscf04   : "#345487",
        dscf05   : "#345487",
        dscf06   : "white",
        dscf07   : "#DFE6EF",
        dscf08   : "pre",
        dscf09   : "-moz-pre-wrap",
        dscf10   : "-hp-pre-wrap",
        dscf11   : "-o-pre-wrap",
        dscf12   : "-pre-wrap",
        dscf13   : "pre-wrap",
        dscf14   : "pre-line",
        dscf15   : "break-word",

        //shoutbox's footer
        fFieldHight : "auto",
        fFieldSize  : 18,
        fFontSize   : "10px",
        fBorderWidth: "1px",
        fBorderStyle: "solid",
        fBorderColor: "#000000",
        fBgColor    : "#f7f7f7"

       };
      //merge/overwrite with user's settings
       settings = ( uSettings )? jQuery.extend( settings, uSettings )
                               : settings;

      if( settings.qsId ){
      //init shoutbox
        jQuery.QShout.init();
      //bind 'Enter' key, code 13 to submit
        jQuery('#qName, #qUrl, #qMessage').keypress(function(e){
          code = e.keyCode ? e.keyCode : e.which;
          if( code.toString() == 13 ){
            jQuery.QShout.validatePost();
          }
        });
      }     
   };

   jQuery.QShout = jQuery.extend( jQuery.QShout, {
      //load html content
      init: function(){
      //qShout's html      
      var qShoutHtml = "<table cellpadding='0' id='qWrapper' width='144px'>" +
                       "<tr><td align='center' class='tdblock'>"           +
                       "<u>&Uacute;LTIMOS 10 MENSAJES</u>"+
                       "</td></tr>" +
                       "<tr><td align='center' class='tdglobal'>"           +
                       "<a href='./index.php?ind=urlobox'>Avanzado</a>"+
                       "</td></tr>" +
                       "<tr><td>"                +
                       //shoutbox's content
                       "<div id='qShout'></div>" +
                       "</td></tr>"              +
                       //shoutbox's footer
                       "<tr><td>"                +
                       "<div id='qFooter'>"      +
                       "<tr><td align='center' class='tdblock'>"                +
                       "Mensaje<br />"+
                       "<form action='' name='mkpshaj' onsubmit='return false;' method='post'>"+
                       "<input type='text' id='qMessage' name='qMessage' maxlength='"+maxlengajchat+"'>" +
                       "</form>"+
                       "<input type='hidden' id='qUrl' value=''>" +
                       "<input type='hidden' id='qName' value='" + usernmejchat + "'>" +
                       "</td></tr>"              +
                       "<tr><td align='center' class='tdblock'>"           +
                       "<input type='button' value='Enviar' onClick='jQuery.QShout.validatePost();' id='qPostBtn'> "+
                       "<a href='javascript:void(0);' id='qPostBtn3' onClick='emo_popac();'><img src='./mkportal/templates/Menudo/images/buttons/ed_smiley.gif' border='0'/></a>"+
                       "</td></tr>" +
                       "<tr><td align='center' class='tdblock'>"           +
                       "<a href='javascript:void(0);' id='qPostBtn2' onClick='jQuery.QShout.init();'>Actualizar</a>"+
                       "</td></tr>" +
                       "</div>"     +
                       "</div>"     +
                       "</td></tr>" +
                       "</table>";

      jQuery("#" + settings.qsId ).html( qShoutHtml )                       
                             .each(function(){
     
             jQuery(this).find("#qFooter table").css({
               'border-style'    : settings.fBorderStyle,
               'border-width'    : settings.fBorderWidth,
               'border-color'    : settings.fBorderColor,
               'width'           : '100%',
               'background-color': settings.fBgColor,
               'font-size'       : settings.fFontSize
              });

          jQuery(this).find("#qShout").html( settings.loader )
                                 .each(function(){
               jQuery(this).css({
               'background': settings.dbackColor,
               'overflow-x': settings.doverflowx,
               'overflow-y': settings.doverflowy,
               'scrollbar-face-color': settings.dscf01,
               'scrollbar-highlight-color': settings.dscf02,
               'scrollbar-3dlight-color': settings.dscf03,
               'scrollbar-shadow-color': settings.dscf04,
               'scrollbar-darkshadow-color': settings.dscf05,
               'scrollbar-arrow-color': settings.dscf06,
               'scrollbar-track-color': settings.dscf07,
               'white-space': settings.dscf08,
               'white-space': settings.dscf09,
               'white-space': settings.dscf10,
               'white-space': settings.dscf11,
               'white-space': settings.dscf12,
               'white-space': settings.dscf13,
               'white-space': settings.dscf14,
               'word-wrap': settings.dscf15,
               'border-width': settings.bBorderWidth,
               'border-style': settings.bBorderStyle,
               'border-color': settings.bBorderColor,
               'height'      : settings.bheight,
               'width'       : settings.bwidth
               });
          });
       });

       //style footer's form
       this.styleFooterEle();

       //get content of shout box
        setTimeout( function(){
         jQuery.QShout.loadContent();
        }, 300 );
      },
     
      styleFooterEle: function(){
       var inputs = jQuery("#qFooter :input");

      //iterate to check each element type
        inputs.each(function() {
          var currentEleType = this.type;
          switch(currentEleType){
           case "text":
            jQuery(this).css({
             'border-width' : settings.fBorderWidth,
             'border-style' : settings.fBorderStyle,
             'border-color' : settings.fBorderColor,
             'font-size'    : settings.fFontSize,
             'height'       : settings.fFieldHeight
            });
            //set the size of textfield
            this.size = settings.fFieldSize;
            break;
            case "button":
             jQuery(this).css({
              'font-size': settings.fFontSize,
              'height'   : settings.fFieldHeight
             });
              break;
          }//end switch
        });
      },

      loadContent: function( action ){
       
       var act = {load: "load"};
       if( action ) { act = jQuery.extend( act, action ) };

       var maxRow = ( settings.maxRow < 0 ) ? 30 
	                                    : settings.maxRow;
	 var noCache = Date();										
       var param = "maxRow="+ maxRow +"&action=get";
       var url   = settings.serverPage + "&" + param + "&ts8=" + noCache;
       jQuery.getJSON(url,
        function( data ){
         var arrayMessage = data.chat.message;         
         var content = "<ul style='margin:0; padding:0px; list-style: none;'>";
          jQuery.each( arrayMessage, function(i){
           arrayMessage[i].user = "<a href='"+ userurljchat + arrayMessage[i].idu +"'>"+ arrayMessage[i].user + "</a>";
           var message = arrayMessage[i].text;
               message = message.replace(/%22/gi,'"');
           content += "<li>"+
                      "<div class='tdblock' align='left' alt='"+arrayMessage[i].time+"' title='"+arrayMessage[i].time+"'>por: "+
                      arrayMessage[i].user +
                      "</div>"+
                      "<div class='tdglobal' align='left'>"+
                      message+
                      "</div></li>";
          });
           content += "</ul>";

           //manipulate content's css
              jQuery("#qShout").html(content)
                          .each(function(){
                jQuery(this).scrollTop( settings.bheight );

                jQuery(this).find("ul").css({                                           
                  'font-size'  : settings.bFontSize,
                  'font-family': settings.bFontFamily
                });

                jQuery(this).find("ul>li:even").css({
                  'background-color' : settings.evenRowColor,
                  'padding'          : settings.rowPadding
                });

                jQuery(this).find("ul>li:odd").css({
                  'background-color' : settings.oddRowColor,
                  'padding'          : settings.rowPadding
                });

              //apply animation for newly added
               if( act.load === "inserted" ){
                 var oriColor = jQuery(this).find("ul>li:first").css('background-color');
                 jQuery(this).find("ul>li:first").css('background-color', settings.blinkColor);
                    jQuery(this).find("ul>li:first").animate({
                      opacity: 0.4
                      },'slow',function(){
                       jQuery(this).css({
                         'background-color': oriColor,
                         'opacity': 1
                     });
                    });
                   }
              });

          //reload the content after interval time
          setTimeout( function(){
			settings.timer = ( settings.timer < 0 )? 60000
			                                       : settings.timer;
              jQuery.QShout.loadContent();
              jQuery("#qPostBtn").attr("disabled", false);
              jQuery("#qMessage").attr("disabled", false);
              jQuery("#qPostBtn2").show();

          }, settings.timer );
        });
      },
      //inputs validation
      validatePost: function(){
       var name    = jQuery.trim(jQuery("#qName").val());
       var url     = jQuery.trim(jQuery("#qUrl").val());
       var message = jQuery.trim(jQuery("#qMessage").val());

       if( name == "" || name == null ){
         alert("Nombre no encontrado!");
         jQuery("#qName").focus();
         return false;
       }
       
       if( name.length > 500 ){
         alert("Nombre demasiado largo (500 max)!");
         jQuery("#qName").focus();
         return false;
       }
       
       if( message == "" || message == null ){
         alert("Debes escribir un mensaje.");
         jQuery("#qMessage").focus();
         return false;
       }
       if( url != "" ){
         var checkURL = new RegExp();
         checkURL.compile("^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+jQuery");
         if( !checkURL.test(url) ){
           alert("URL Invalida!");
           jQuery("#qUrl").focus();
           return false;
         }
       }
       this.postShout();
      },
     //post inputs
     postShout: function(){
       var user    = this.encURI( jQuery("#qName").val() );
       var url     = this.encURI( jQuery("#qUrl").val() );
       var message = this.encURI( jQuery("#qMessage").val() );
       
            jQuery("#qPostBtn").attr("disabled", true);
            jQuery("#qMessage").attr("disabled", true);
            jQuery("#qPostBtn2").hide();

      var inputs = "user=" + user + "&url=" + url + "&message=" + message + "&action=send";
      jQuery.post(settings.serverPage, inputs, function( result ){
        result = jQuery.trim(result);        
        if( result === "done" ){
            clearInterval( settings.timer );
	    //load inserted
            jQuery.QShout.loadContent({
              load: "inserted"
            });
            //clear all textfield value
            jQuery("#qFooter :input").each(function(){
             if( this.type === "text" ){
               this.value = "";
             }else if( this.type === "button" || this.type === "submit" ){
               jQuery(this).attr("disabled", false);
             }
          });
        }
      });
     },
    //encode
    encURI: function( string ){
      return encodeURIComponent(string);
     }
    });

})(jQuery);
