/*  
 * Project: QShout - Shoutbox Widget for jQuery
 * Version: v1.0 (03/01/‎2010, ‏‎12:02:23 PM)
 * URL    : http://qshout.borisding.com
 * License: MIT  (http://www.opensource.org/licenses/mit-license.php)
 *          Copyright (c) 2010, Boris Ding P H
 */

(function($){
      //public QShout
      $.QShout = function( uSettings ){                   
      //default settings
       settings = {
        //misc.
        qsId        : "qsId",
        serverPage  : "_src/qshout.php",
        loader      : "<table width='100%' height='100%'><tr><td valign='center' align='center'><img src='img/loading.gif'></td></tr></table>",
        timer       : 60000,
        maxRow      : 30,
        //shoutbox's body
        bwidth      : "270px",
        bheight     : "500px",
        bBorderWidth: "0px",
        bBorderStyle: "solid",
        bBorderColor: "#000000",
        bFontSize   : "11px",
        bFontFamily : "Verdana, Calibri, Arial",
		blinkColor  : "#00FF00",
        //shoutbox's content
        evenRowColor: "#f5f5f5",
        oddRowColor : "#ffffff",
        rowPadding  : "4px",
        ipCursor    : "help",
        dUrlColor   : "#888888",
        //shoutbox's footer
        fFieldHight : "auto",
        fFieldSize  : 20,
        fFontSize   : "11px",
        fBorderWidth: "0px",
        fBorderStyle: "solid",
        fBorderColor: "#000000",
        fBgColor    : "#f7f7f7"
       };
      //merge/overwrite with user's settings
       settings = ( uSettings )? $.extend( settings, uSettings )
                               : settings;

      if( settings.qsId ){
      //init shoutbox
        $.QShout.init();
      }     
   };

   $.QShout = $.extend( $.QShout, {
      //load html content
      init: function(){
      //qShout's html
      var qShoutHtml = 	"<div style='align: left;'>"			+
						"<div id='qShout'> </div>" 	+
						"<div id='qFooter'>"      	+
						"<div id='sbxpostfrm' style='border-top: 1px dashed #a0ffa0';>" 	+
						"<div class='sbel1'><span class='menutext2'>Message:</span></div>" +
						"<div class='sbel2'><input type='text' id='qMessage' value='' border='0' maxlength='250' class='sbxinput'></div>" +
						"<div class='sbel3'><input type='button' value='Shout' class='btn' onClick='$.QShout.validatePost();' id='qPostBtn'> <a href='javascript:void(0);' onClick='$.QShout.init();'><img src='img/Refresh.png' border='0' title='Refresh chat'></a></div>" +
						"</div>" +
						"</div>" +
						"</div>" ;

      $("#" + settings.qsId ).html( qShoutHtml )                       
                              .each(function(){

          $(this).find("#qShout").html( settings.loader )
                                 .each(function(){
               $(this).css({
               'border-style': settings.bBorderStyle,
               'border-width': settings.bBorderWidth,
               'border-color': settings.bBorderColor,
               'height'      : settings.bheight,
               'width'       : settings.bwidth,
               'overflow'    : 'auto'
               });
          });
       });

       //style footer's form
       this.styleFooterEle();

       //get content of shout box
        setTimeout( function(){
         $.QShout.loadContent();
        }, 300 );
      },
     
      styleFooterEle: function(){
       var inputs = $("#qFooter: input");

      //iterate to check each element type
        inputs.each(function() {
          var currentEleType = this.type;
          switch(currentEleType){
           case "text":
            $(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":
             $(this).css({
              'font-size': settings.fFontSize,
              'height'   : settings.fFieldHeight
             });
              break;
          }//end switch
        });
      },

      loadContent: function( action ){
       var act = {load: "load"};
       if( action ) { act = $.extend( act, action ) };

       var maxRow = ( settings.maxRow < 0 ) ? 30 
	                                    : settings.maxRow;
											
       var param = "maxRow="+ maxRow +"&action=get";
       var url   = settings.serverPage + "?" + param;
       $.getJSON(url,
        function( data ){
         var arrayMessage = data.chat.message;         
         var content = "<ul style='margin:0; padding:0px; list-style: none;'>";
          $.each( arrayMessage, function(i){
           content += 
						"<li>"+
						"<div class='sbxname'>"+
						arrayMessage[i].user +
						"</div>"+
						"<div class='sbxdate'>" +
						arrayMessage[i].time +
						"</div>"+
						"<div class='sbxmsg'>"+
						arrayMessage[i].text +
						"</div>"+
						"</li>";
          });
           content += "</ul>";
           
           //manipulate content's css
              $("#qShout").html(content)
                          .each(function(){
                $(this).scrollTop( settings.bheight );

                $(this).find("ul").css({                                           
                  'font-size'  : settings.bFontSize,
                  'font-family': settings.bFontFamily
                });

                $(this).find("ul>li:even").css({
                  'background' : 'url(img/b33.png)',
				  'border-bottom' : '1px dashed #aaa',
                  'padding'          : settings.rowPadding
                });

                $(this).find("ul>li:odd").css({
                  'background' : 'url(img/b22.png)',
				  'border-bottom' : '1px dashed #aaa',
                  'padding'          : settings.rowPadding
                });

              //apply animation for newly added
               if( act.load === "inserted" ){
                 var oriColor = $(this).find("ul>li:first").css('background-color');
                 $(this).find("ul>li:first").css('background-color', settings.blinkColor);
                    $(this).find("ul>li:first").animate({
                      opacity: 0.4
                      },'slow',function(){
                       $(this).css({
                         'background-color': oriColor,
                         'opacity': 1
                     });
                    });
                   }
              });

          //reload the content after interval time
          setTimeout( function(){
			settings.timer = ( settings.timer < 0 )? 60000
			                                       : settings.timer;
              $.QShout.loadContent();
          }, settings.timer );
        });
      },
      //inputs validation
      validatePost: function(){
       var message = $("#qMessage").val();
       if( message == "" || message == null ){
         alert("Message is emtpy!");
         $("#qMessage").focus();
         return false;
       }
       this.postShout();
      },
     //post inputs
     postShout: function(){
       var user    = this.encURI( $("#qName").val() );
       var url     = this.encURI( $("#qUrl").val() );
       var message = this.encURI( $("#qMessage").val() );
       //disable post button
       $("#qPostBtn").attr("disabled", true);

      var inputs = "user=" + uid + "&url=" + url + "&message=" + message + "&action=send";
      $.post(settings.serverPage, inputs, function( result ){
        if( result === "done" ){
            clearInterval( settings.timer );
			//load inserted
            $.QShout.loadContent({
              load: "inserted"
            });
            //clear all textfield value
            $("#qFooter: input").each(function(){
             if( this.type === "text" ){
               this.value = "";
             }else if( this.type === "button" || this.type === "submit" ){
               $(this).attr("disabled", false);
             }
          });
        }
      });
     },

    encURI: function( string ){
      return encodeURIComponent(string);
     }
    });

})(jQuery);


