/*****************************************************

 * Extenal JS function

 * 

 * @author      Saidur Rahman <thinker.bijon@gmail.com>

 * @version     1.0

 * @date        2007/11/18

 * @copyright   Right Brain Solution <www.rbs.com>

 *****************************************************/

/**

 * OnKeyPress function for Flickr Search

 *

 * @param   none

 * @return  list of image from Flickr

 */

 

/**

* Contains the delay time 

 * @var string 

*/



var t = null;

/**

* Contains the search keyword 

 * @var string 

*/

var liveSearchLast  = "";





var liveSearchReq   = false;

var tubeSearchReq   = false;

var flickrSearchReq = false;

/**

   *Contain the ajax call of Flickr Search Status

   *

   *@var boolean

*/



var ajaxFlickrStatus = false;





/**

   *Contain the ajax call of Video Search Status

   *

   *@var boolean

*/



var ajaxVideoStatus = false;



/**

   *Contain the ajax call of Quatation Search Status

   *

   *@var boolean

*/



var ajaxQuoteStatus = false;



var ajaxTags = false;

var ajaxTerms =false ;

 

/**

 *

 *Containg the current page of Quation 

 *

 *

*/

var cuurentPageQuatation = -4;                           



 /**

 *

 *Containg the current page of Photo

 *

 *

*/

var cuurentPagePhoto = 1;

 /**

 *

 *Containg the current page ofvideo

 *

 *

*/

var cuurentPageVideo = 1;



 

/** jquery on load fucntion 

 *  initially loader image will be hide

*/



/**

 *contain yahoo terms 

*/

var yahooTerms = null ;



/**

 * 

*/

var quoteTabOn = 0;

var photoTabOn = 1;

var videoTabOn = 0;





/** 

 *  Contain the quation result

*/

var quoteCount =  0;

var flickrCount = 0;

var videoCount = 0;



var feelText = 'Type in how you feel...';



//tagview var

var new_id   = 0;

var tagArray = new Array();

var cur_arr = new Array();







$(function(){

		     

/**

 //initaly interface

  //

  //

 */

 initialInterface(); 

 

 /**

   *  when click 

  *  remove the 'Type it here..'

 */

 $('#feeling').click( function () {

  

   if ($('#feeling').val()==feelText) 

     $('#feeling').val('');

});



 /**

    * If empty 

   * set the 'Type it here..'

  */

 $('#feeling').blur( function () {

    if ($('#feeling').val()=='')

	//$('#feeling').val('Type it here...');

    $('#feeling').val(feelText);

    });





 $('#quotes').click( function () {

    

    $("#tabQuote").attr('class', 'current');

    $("#tabPhoto").attr('class', '');

    $("#tabVideo").attr('class', '');

     

     if ($('#feeling').val()==feelText)

	  {

            $(".add-quote").hide();

	  }

     else 

	{

	   quoteTab();

	   quotetionTabInterface ();

	   quotePaging ();

	   

	}

 });

 

 

  $('#videos').click( function () {

     

     $("#tabQuote").attr('class', '');

     $("#tabPhoto").attr('class', '');

     $("#tabVideo").attr('class', 'current');



     //if ($('#feeling').val()=='Type it here...')

     if ($('#feeling').val()==feelText) 

			  {

			    $(".add-videos").hide();

			  }

			else 

			 {

			   videoTab();

			   videoTabInterface ();

			   videoPaging ();

			  }

});





$('#photos').click( function () {

    

     $("#tabQuote").attr('class', '');

     $("#tabPhoto").attr('class', 'current');

     $("#tabVideo").attr('class', '');

    

     if ($('#feeling').val()==feelText)

	{

	  $(".add-photos").hide();

 	}

     else 

	{

          photoTab();     

	     photoTabInterface();	 

	    if (flickrCount!=0)

          {

          photoPaging();

          }

          

	}

});	



/**

 * Call pagination for quatation

 

*/



/**

* click for quote next function 

* 

*/										   

$('#quote-paging-next').click( function () {   

      

      cuurentPageQuatation = cuurentPageQuatation+4;

      //load ajax loader into photos div and initially hide the div

      $('.add-quote').html($("#loader-media").clone());

      ajaxQuote (yahooTerms);

     

    });

$('#quote-paging-prev').click( function () {

      cuurentPageQuatation = cuurentPageQuatation-4;

      //load ajax loader into photos div and initially hide the div

      $('.add-quote').html($("#loader-media").clone());

      ajaxQuote (yahooTerms);

    

    });





/**

* click for image next function 

* 

*/										   

$('#photo-paging-next').click( function () {   

      cuurentPagePhoto = cuurentPagePhoto+1;

      //load ajax loader into photos div and initially hide the div

      photoHide();

      $('.add-photos').html($("#loader-media").clone());

      ajaxFlickr (yahooTerms);

    

    });

$('#photo-paging-prev').click( function () {

      cuurentPagePhoto = cuurentPagePhoto-1;

      photoHide();

      //load ajax loader into photos div and initially hide the div

      $('.add-photos').html($("#loader-media").clone());

      ajaxFlickr (yahooTerms);

    

    });

    

    

 /**

* click for video next function 

* 

*/										   





$('#video-paging-prev').click( function () {

   

   //alert (cuurentPageVideo);

   if (cuurentPageVideo>1)

      {

        cuurentPageVideo = cuurentPageVideo-20;

        videoHide();

	$('.add-videos').html($("#loader-media").clone());

        ajaxVideo (yahooTerms);

      }

     // $("#photo-paging").hide();

    

    });



$('#video-paging-next').click( function () {   

    

     cuurentPageVideo = cuurentPageVideo+20;

     videoHide();

     //load ajax loader into photos div and initially hide the div

     $('.add-videos').html($("#loader-media").clone());

     

     ajaxVideo (yahooTerms);

     

    });

   







    

    

    }); //end of load function 	  





function quoteTab ()

{

    quoteTabOn = 1;

    photoTabOn = 0;

    videoTabOn = 0;



}



function photoTab ()

{

    quoteTabOn = 0;

    photoTabOn = 1;

    videoTabOn = 0;



}



function videoTab ()

{

    quoteTabOn = 0;

    photoTabOn = 0;

    videoTabOn = 1;



}

    

function photoHide ()

{

   

   $("#photo-paging").hide();

   $("#photo-paging-next").hide();

   $("#photo-paging-prev").hide();

}



function videoHide ()

{

   $("#video-paging").hide();

   $("#video-paging-next").hide();

   $("#video-paging-prev").hide();

   

} 



function quoteHide ()

{

   $("#quote-paging").hide();

   $("#quote-paging-next").hide();

   $("#quote-paging-prev").hide();

} 



    

    

    

    /**

*  initial hide the all divs 

* initally load the image 

*/



function initialInterface()

{

   $('.videoImage a').lightBox({type:'video', inLineVideoAll:'true'});

   $("#loader").hide();

   $("#loader-flickr").hide();

   $("#loader-video").hide();

   $("#quote-paging").hide();

   $("#photo-paging").hide();

   $("#video-paging").hide();



}



function quotetionTabInterface()

{

   $(".add-photos").hide();

   $(".add-videos").hide();

   $("#photo-paging").hide();

   $("#photo-paging-next").hide();

   $("#video-paging-next").hide();   

   (quoteCount==0)? $("#quote-paging").hide():$("#quote-paging").show();

   (cuurentPageQuatation == 0)? $("#quote-paging").hide():$("#quote-paging").show();

   $(".add-quote").show("slow");

   $("#video-paging").hide();



}









function videoTabInterface ()

{

   $(".add-quote").hide("slow");

   $(".add-photos").hide("slow");

   $("#quote-paging").hide();

   $("#quote-paging-next").hide();

   $("#quote-paging-prev").hide();

   $("#photo-paging-next").hide();

   $("#photo-paging-prev").hide();

   $("#photo-paging").hide();

   $("#photo-paging-next").hide();

   $("#photo-paging-prev").hide();

   $(".add-videos").show("slow");

   (videoCount==0)? $("#video-paging").hide():$("#video-paging").show('slow');

   (videoCount==0)?  $("#video-paging-next").hide():$("#video-paging-next").show('slow');

   if (videoCount!=0 && videoCount<20)

    {

       $("#video-paging-next").hide();

    } else

    {

       $("#video-paging-next").show('slow');     

    }

}   



function photoTabInterface()

{

    //$("#loader-flickr").show("slow");

    $(".add-quote").hide("slow");

    $(".add-videos").hide("slow");

    $("#quote-paging").hide();

    $("#video-paging").hide();

    $("#video-paging-next").hide();  

    $(".add-photos").show("slow");

    $("#photo-paging").show();

    (flickrCount==0)? $("#photo-paging").hide():$("#photo-paging").show('slow');

    (flickrCount==0)?  $("#photo-paging-next").hide():$("#photo-paging-next").show('slow');

    if (flickrCount!=0 && flickrCount<20)

    {

       $("#photo-paging-next").hide();

    } else

    {

       $("#photo-paging-next").show('slow');     

    }

    

    

    

} 

    

    

/**

 * Clickl pagination onphotos

 

*/

 

		   

		   

/**

  * TimeOut Hold 200 ms and Start LiveSearch

  *

  *

*/



function liveSearchStart()

{
	len = tagArray.length;
	//empty the tag array for a new search.
	for( i = 0; i< len; i++ )
	{
		tagArray.pop();
	}
	  

	if (t) {

		    window.clearTimeout(t);

	       }

		   

    t = window.setTimeout("liveSearchDoSearch()",200);

}

/**

* this function check the ajax Request 

*and if the ajaxRequest is not successful

* then it will stop the ajax Request

*/





function abortAjaxRequest()

{

     

       cuurentPagePhoto = 1;

       cuurentPageQuatation = 0;

       cuurentPageVideo=1;

       if (ajaxTerms.readyState<4)

       { 

             ajaxTerms.abort();

             ajaxTerms =false;

       }

       

       if (ajaxVideoStatus.readyState < 4)

	   {

	      //$('.add-videos').html('');

	      ajaxVideoStatus.abort();

	      ajaxVideoStatus = false;

	      

	   }

	

	   if (ajaxFlickrStatus.readyState<4)

	   { 

		     ajaxFlickrStatus.abort();

		     ajaxFlickrStatus =false;

	   }

	     

	   if (ajaxQuoteStatus.readyState<4)

	   {

		     ajaxQuoteStatus.abort();

		     ajaxQuoteStatus =false;

	   }

}



/**

 * Start Search 

 *

 * @return    Search Result

 */





function liveSearchDoSearch() 

{

  // check the match previous one and the current keyword 

  if (liveSearchLast != $('#feeling').val())

  {  

       abortAjaxRequest();

       //$("#video-paging-next").hide(); 

       photoTab ();

       ////load ajax loader into photos div and initially hide the div

       //$('.add-photos').html($("#loader-media").clone());

       //$(".add-photos").show();

       ////load ajax loader into videos div and initially hide the div

       //$('.add-videos').html($("#loader-media").clone());

       //$('.add-videos').hide();

       ////load ajax loader into quote div

       //$('.add-quote').html($("#loader-media").clone());

       //$('.add-quote').hide();

       //// check  where the tag length is greater than 2

      if( $('#feeling').val().length > 2 )  

          {

                   liveSearchLast = $('#feeling').val();

                   

                   isFlickr  = liveSearchLast.search('/www.flickr.com/');

                   isYoutube = liveSearchLast.search('/www.youtube.com/');



                   if( isFlickr > 0 )

                   {

                        alert( 'Flickr' + isFlickr );

                        return;

                   }

                   else if( isYoutube > 0 )

                   {

                        abortAjaxRequest();

                        //load ajax loader into videos div and initially hide the div

                        $('.add-videos').html($("#loader-media").clone());

                        $('.add-videos').show();

                        

                        $('.add-photos').html($("#loader-media").clone());

                        $(".add-photos").hide();

                        

                        $('.add-quote').html($("#loader-media").clone());

                        $('.add-quote').hide();

                        

                        ajaxVideoByUrl( liveSearchLast );

                   }

                   else

                   {

                        abortAjaxRequest();

                        //load ajax loader into photos div and initially hide the div

                        $('.add-photos').html($("#loader-media").clone());

                        $(".add-photos").show();

                        //load ajax loader into videos div and initially hide the div

                        $('.add-videos').html($("#loader-media").clone());

                        $('.add-videos').hide();

                        //load ajax loader into quote div

                        $('.add-quote').html($("#loader-media").clone());

                        $('.add-quote').hide();

                        getYahooTerms(liveSearchLast);

                   }

          }

          else 

          {

	           $(".add-quote").html('Please type more than 2 Character');

          }		

		  

    }// End of match  if 

         

} // End of function 



function getYahooTerms( context )

{

   ajaxTerms= $.ajax({

                     type: "POST",

                     url : rootPath + 'member/getYahooTerms',

                     data: "context=" + context,

                     success: function(data)

                     {

                        yahooTerms = data;

                        

                         //tag view

                         strTag = ajaxTagTab( data );



                         $(".photoTag").html( strTag );  

                         //eng tag view.

                            

		                    callAjaxRequest(data);

                    }

       });        

}

/**

* Call Ajax Request for tag

*



*/



function callAjaxRequest (tag)

{

    

    if( tagArray.length > 0 )

    {

        tag = $('#feeling').val() + '^^^' + tagArray.join( " " );

        //tag = tagArray.join( " " ) + '^^^' ;

        abortAjaxRequest();

        //load ajax loader into photos div and initially hide the div

        $('.add-photos').html($("#loader-media").clone());

        $(".add-photos").show();

        //load ajax loader into videos div and initially hide the div

        $('.add-videos').html($("#loader-media").clone());

        $('.add-videos').hide();

        //load ajax loader into quote div

        $('.add-quote').html($("#loader-media").clone());

        $('.add-quote').hide();

    }

    

    //alert( tag );

    

    // Call Ajax Flickr

    ajaxFlickr(tag);

          

    // Call Ajax Quotation 

    ajaxQuote(tag);

    

    //Call Ajax Video

    ajaxVideo(tag);



}



function quotePaging ()

{

  (quoteCount==0)? $("#quote-paging").hide():$("#quote-paging").show('slow');

  (quoteCount<4)? $("#quote-paging-next").hide():$("#quote-paging-next").show('slow');

  (cuurentPageQuatation==0)? $("#quote-paging-prev").hide() :$("#quote-paging-prev").show('slow');  

}



function videoPaging ()

{

   $("#video-paging").show();

   //(videoCount>=11)?$("#video-paging-next").show():''; 

   (cuurentPageVideo==1)? $("#video-paging-prev").hide():$("#video-paging-prev").show('slow'); 			 

   (videoCount<20)? $("#video-paging-next").hide():$("#video-paging-next").show('slow');

}

function photoPaging ()

{

  $("#photo-paging").show();

  (cuurentPagePhoto==1)? $("#photo-paging-prev").hide():$("#photo-paging-prev").show('slow');

  (flickrCount<20)? $("#photo-paging-next").hide():$("#photo-paging-next").show('slow');

}



/**

 * Send Ajax Request for Quatation text

 *

 * @return    Quation with Div Format

 */

function ajaxQuote(tag)

{

  

  ajaxQuoteStatus = $.ajax({

       	  	 	                type:    "POST",

             		              url :    rootPath +'member/searchMediaQuotes/'+cuurentPageQuatation,

             		              data:    "keyword="+tag,

			                        success: function(data)

				                               {

				                                   htmldata = data.split("++");

					                                 $("#loader").hide("slow");

				                                   quoteCount = htmldata[0];

					                                 

					                                 $(".add-quote").html(htmldata[1]);

					                                 

					                                 if (quoteTabOn==1)

					                                 {

					                                    quotePaging();

					                                 }

					

					

				                               }

       	                    });		





}









/**

 * Send Ajax Request after succes quotation ajax request 

 *

 * @return    flickr Image in Div add-photos  

 */

function ajaxFlickr(tag)

{

      ajaxFlickrStatus = $.ajax({

                                    type: "POST",

    	                              url : rootPath +'member/searchMediaFlickr/'+cuurentPagePhoto,

    	                              data: "keyword="+tag,

    	                              success: function(data)

    	                                       {

                                                 htmldata = data.split("++");

                                                 

                                        			   $(".add-photos").html(htmldata[1]);

                                                 $('.add-photos a').lightBox({txtImage:'Image'});

                                                 

				                                         flickrCount = htmldata[0];

                                                

                                                 if (flickrCount!=0)

                                                 {

                                				            if (photoTabOn ==1)

                                                    {

                                                        photoPaging ();

                                				            }

                                                 }                    

				                                         $("#video-paging").hide();

				                                    }



	                              });		 



}



function ajaxTagTab( tagList )

{

     tagArr = tagList.split('^^^');

                                                 

     strTag = '<p class="standard">We searched with these tags:</p><div class="tag_view_search">';

     

     if( tagArr[1] == '' )

     {

         viewTag  = tagArr[0];

         

         wordList = "not,whose,whom,who,me,you,i,am,aren't,are,aren't,ain't,be,been,can,cannot,can't,could,couldn't,did,didn't,do,don't,does,doesn't,had,hadn't,has,hasn't,have,haven't,is,isn't,may,might,mightn't,must,mustn't,ought,shall,shan't,should,shouldn't,was,wasn't,were,weren't,will,won't,would,wouldn't";

         

         arr      = viewTag.split(' ');

         

         if( arr.length < 0 )            

         {

             strTag  += '<div id="tagDiv_0" class="ajaxTagTab">' +

                            viewTag + '&nbsp;&nbsp;<b><label style="display:inline;" onclick="closeTagDiv(\'tagDiv_0\',\''+ trim(viewTag) +'\')">x</label></b>&nbsp;&nbsp;'+

                        '</div>';

                        

             tagArray.push( viewTag );

         }

         else

         {

             for( i = 0; i < arr.length; i++ )

             {

                 //alert( wordList.search( arr[i] ) + 'arr' + arr[i] );

                 

                 if( wordList.search( arr[i] ) < 0 )

                 {

                     strTag   += '<div id="tagDiv_'+ i +'" class="ajaxTagTab">' +

                                     arr[i] + '&nbsp;&nbsp;<b><label style="display:inline;" onclick="closeTagDiv(\'tagDiv_'+ i +'\',\''+ trim(arr[i]) +'\')">x</label></b>&nbsp;&nbsp;'+

                                 '</div>';

                                 

                     tagArray.push( arr[i] );

                 }

             }

         }    

     }

     else

     {

         yahooTag  = tagArr[1].split(' ');

         

         for(i = 0; i < yahooTag.length; i++ )

         {

             strTag   += '<div id="tagDiv_'+ i +'" class="ajaxTagTab">' +

                            yahooTag[i] + '&nbsp;&nbsp;<b><label style="display:inline;"onclick="closeTagDiv(\'tagDiv_'+ i +'\',\''+ trim(yahooTag[i]) +'\')">x</label></b>&nbsp;&nbsp;'+

                         '</div>';

                         

             tagArray.push( yahooTag[i] );

         }

     }

    

     strTag += '</div>';

     

     strTag +=  '<div class="searchAjaxTag">'+

                '<div class="add_new_tag" id="addNewTag"><label onclick="showTagInput()"> Add new </label> </div> &nbsp;&nbsp;' +

                '<button style="display:inline;" onclick="callAjaxRequest(\'' + tagArray.join(" ") + '\')">' +

                    '<img src="'+rootPath+'images/tick.gif"/>'+ 

                    'Search again'+

               '</button></div>';

     

     return strTag;

}



function showTagInput()

{

    inlineInput = '<input style="width:184px; height:19px" id="new_tag" type="text" name="new_tag" id="new_tag" onblur="hideInline()">';

    

    $(".add_new_tag").html( inlineInput );

    $("#new_tag").focus();

}







function hideInline()

{

    newTag   = '<div id="tagDiv_new_'+ new_id +'" class="ajaxTagTab">' +

                     $("#new_tag").val() + '&nbsp;&nbsp;<b><label style="display:inline;" onclick="closeTagDiv(\'tagDiv_new_'+ new_id +'\',\''+ trim( $("#new_tag").val() ) +'\')" >x</label></b>&nbsp;&nbsp;'+

               '</div>';

    

    addTag   = '<label onclick="showTagInput()"> Add New </label> ';

    

    if( trim( $("#new_tag").val(), ' ' ) != '' )

    {

        $(".tag_view_search").prepend( newTag );   

        tagArray.push( $("#new_tag").val() ); 

        

        new_id = new_id + 1;

    }

    

    $(".add_new_tag").html( addTag );

}





function closeTagDiv( tagDivId, divContent )

{

    temp     = removeFromArr( tagArray, divContent );

    tagArray = temp;

    

    document.getElementById(tagDivId).style.display = 'none';

}



/**

 * Send Ajax Request after succes quotation ajax request 

 *

 * @return    Video in Div add-photos  

 */



function ajaxVideo(tag)

{ 

	ajaxVideoStatus = $.ajax({

                                type: "POST",

    	                          url : rootPath +'member/searchMediaTube/'+cuurentPageVideo,

    	                          data: "keyword="+tag,

    	                          success: function(data)

    	                          {

                                     htmldata = data.split("++");

  			                             videoHide();

                                     

                                     $(".add-videos").html(htmldata[1]);

				                             

                                     $('.add-videos a').lightBox({txtImage:'Video',type:'video'});

				                             

				                             videoCount = htmldata[0];

				                             

                        		         if (videoTabOn ==1)

                                     {

                        		            videoPaging ();

                        		         } 				   

				                        } 

	                         });		 



}



function ajaxVideoByUrl( videoUrl )

{

    ajaxVideoByUrlStatus = $.ajax( 

                                    {

                                        type    : "POST",

                                        url     : rootPath + 'member/searchMediaTubeByUrl/' + cuurentPageVideo,

                                        data    : "keyword="+videoUrl,

                                        success : function( data )

                                                  {

                                                       htmldata = data.split("++");

                    				                           videoHide();

                                                  

                                                       $(".add-videos").html(htmldata[1]);

                                                       $('.add-videos a').lightBox({txtImage:'Video',type:'video'});

                    				                           videoCount = htmldata[0];

                                                  }

                                    }

                                 )

}

	



/**

 * Insert Image to the database

 * and reload the site contents

 *

 * @param    photoId    -- Image Id from Flickr

 *                  imgPath    -- Flickr Path to show the thumbal image

 *                  profileID  -- User name who add the image

 *                  photoTitle -- Title of the image from Flickr

 *                  tag        -- search tag for the image

 *

 * @return   Content Page with new inserted image.

 */



function insertPhoto( photoId, imgPath, profileId, photoTitle, tag, link, keyword, photo_owner_name, photo_owner_url )

{

   //alert( photoId +'__'+ imgPath+'__'+profileId+'__'+photoTitle+'__'+ tag+'__'+ link+'__'+ keyword+'__'+ photo_owner_name+'__'+'__'+photo_owner_url );  return;

   

	

	 $(".add-photos").hide();

	 $("#photo-paging").hide();

	 abortAjaxRequest();

	 $('div.add-photos img').css({ border: "3px solid #FFFFFF"});

	 $('#photo_' + photoId ).css({ border: "3px solid red"});



      //send a feeling

		  if( HTTP_REFER.indexOf( 'sendafeeling' ) != -1 )

		  {

				$.ajax({

					type	:	"POST",

					url		: 	rootPath + "site/sendFeelingPhoto",

					data:        "imgPath="     + imgPath    + 

        					     "&profileId="  + profileId  + 

        					     "&photoTitle=" + photoTitle +

        					     "&photoId="    + photoId    +   

        					     "&tag="        + tag        +

        					     "&link="       + link       +

        					     "&keyword="    + keyword    +

    					         "&photo_owner_name=" + photo_owner_name +

    					         "&photo_owner_url=" + photo_owner_url,          

					success	:	function( serverResponse )

								{

									//$("#feeling").val('Type it here...') ;

                  $("#feeling").val(feelText) ; 

                                    

									//$("#timeline").html( serverResponse );

									$("#timeline").prepend(serverResponse);

									// photoHide ();

                                                                         //videoHide ();

                                                                         //quoteHide ();

								}

				});

		  }//end of send a feeling

		  else

		  {

	        $.ajax({

    			type:    "POST",

    			url:     rootPath  + 'member/addPhotoToMyPage',

    			data:    "imgPath="     + imgPath    + 

    			         "&profileId="  + profileId  + 

    			         "&photoTitle=" + photoTitle +

    			         "&photoId="    + photoId    +   

    			         "&tag="        + tag        +

					         "&link="       + link       +

					         "&keyword="    + keyword    +

					         "&photo_owner_name=" + photo_owner_name +

					         "&photo_owner_url=" + photo_owner_url, 



    					          success: function(msg)

    					          {

    					            

    					                 if( msg == 'not_login' )

    					                 {

    					                    location.href = 'auth/login';

											            return;

    					                 }

    					                 

    					                 $("#feeling").val(feelText) ;

    		                             //$("#siteContents").html(msg);

    		                            $head="<h2 id='recently'>Who's been mooning recently?</h2>";

								               $("#recently").remove();

            							     $("#timeline").prepend(msg);

            							     //$("#timeline").prepend($head);

    	                  }

	         });		 

  		} // end of ajax call	

} 



/**

 * Insert Quote to the database

 * and reload the site contents

 * @param    quoteId    -- Quation Id from Quation book

 *           quote      -- Quation 

 *           profileID  -- User name who add the image

 *           tag        -- search tag for the image

 *           authorId   -- quote Autor id form Quation book 

 *           quoteURL   -- Quotation URL 

 *           authorLink -- Quotation Author Link

 *

 * @return   Content Page with new inserted Quote.

 */



function insertQuote(quoteId,quote,profileID,tag,authorId,quoteURL,authorLink, keyword)

{



	   $(".add-quote").hide();

		 

		 abortAjaxRequest();



		 //send a feeling

		  if( HTTP_REFER.indexOf( 'sendafeeling' ) != -1 )

		  {

				$.ajax({

					type	:	"POST",

					url		: 	rootPath + "site/sendFeelingQuote",

					data	:	"quoteId="     + quoteId    + 

								  "&quote="      + quote      + 

								  "&profileID="  + profileID  + 

								  "&tag="        + tag        +

								  "&authorId="   + authorId   +

								  "&quoteURL="   + quoteURL   +

								  "&authorLink=" + authorLink +

                  "&keyword="    + keyword,

					success	:	function( serverResponse)

								{

									//$("#feeling").val('Type it here...') ;

                                    $("#feeling").val(feelText) ;



									//$("#timeline").html( serverResponse );

									$("#timeline").prepend(serverResponse);

								}

				});

		  }//end of send a feeling

		  else

		  {

		 		$.ajax({

    					type:    "POST",

    					url:     rootPath  + 'member/addQuotationtoToMyPage',

    					data:    "quoteId="     + quoteId    + 

    					         "&quote="      + quote      + 

    					         "&profileID="  + profileID  + 

    					         "&tag="        + tag        +

							         "&authorId="   + authorId   +

							         "&quoteURL="   + quoteURL   +

							         "&authorLink=" + authorLink +

                                 "&keyword="    + keyword,



    					          success: function(msg)

    					          {

								        if( msg == 'not_login' )

    					                {

    					                  location.href = 'auth/login';

										          	return;

    					                }

    					                 

                              $("#feeling").val(feelText) ;

    		                                    

									            $head="<h2 id='recently'>Who's been mooning recently?</h2>";

									            

									            $("#recently").remove();

									            

									            $("#timeline").prepend(msg);

									            //$("#timeline").prepend($head);

 	                  }

	         });		 

		}

}



/**

 * send Ajax Request to banned a specifice image

 *

 * @param    $user_id -- User Identification Number

 * @return   HTML Content

 */

function changeImageStatus( user_id, reqStatus, feeling_id )

{

	//alert( user_id +'-' + reqStatus +'-' + feeling_id );

	

    

    $.ajax({

    					type:    "POST",

    					url:     rootPath  + 'member/changeStatus',

    					data:    "action="      + reqStatus  + 

    					         "&profileId="  + user_id    +

    					         "&feelingId="  + feeling_id,

    					          success: function(msg)

    					          {

    					              //alert( msg ); return;

    					          	  refAddress = msg.split('^^^'); 

    					              $("#msgHolder_" + feeling_id).html(refAddress[0]);

    					              

    					              setTimeout( location.href = refAddress[1],20000);

    	                  }

	         });		

}



/** 

 * Send Invitation

 * 

 * @param 

 */

 function sendInvitation( user_id )

 {

      var arr          = Array();

	    var email_str    = '';

      

	    var emailAddress = document.getElementById('inviteEmail').value ;

	    var filter       = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

      

	    arr = emailAddress.split(', ');

      

	    if( emailAddress == '' )

	    {

		     $("#errorInvite").html('Please enter a Email Address.');

		     return;

	    }

      

	    for( i=0; i < arr.length; i = parseInt(i) + 1)

	    {

		        if( filter.test(arr[i]) )

		        {

    		   	    if( i == 0 ) 

        		   	    	email_str = arr[i];

    		   	    else

    		       	    	email_str += '^^^' + arr[i];

		        }

		        else

		        { 

		   	        $("#errorInvite").html('NO! Please enter a valid email address');

		   	        //alert('NO! Incorrect email address');

		   	        return;

		        }	

	    }



	 $.ajax(

				  {

				  	type:    "POST",

				  	url :    rootPath + 'member/sendInvitation',

				  	data:    "userId="       + user_id      +

				  			     "&email="       + email_str ,

            success: function( serverResponse )

				  			     {

				  				     //alert(serverResponse);

				  				     $("#errorInvite").html(serverResponse);

				  			     }

				  }

		     );

 }

 

 function addFriend( user_id, friend_id  )

 {

     $.ajax(

                {

                    type:    "POST",

                    url :    rootPath + 'auth/addFriendInfo',

                    data:    "userId="       + user_id      +

                             "&friendId="    + friend_id ,

                    success: function( serverResponse )

                             {

                                 if( serverResponse == 'True')

                                 {

                                    $("#addFriend").html('Friend request Send.');

                                 }

                                 else

                                    {

                                        return;

                                    }

                             }

                }

           );

 }

 

 function acceptFriendReq( user_id, friend_id, status )

 {

     //alert( user_id + '--' + friend_id + '--'+ status ); 

     

     $.ajax(

                {

                    type:    "POST",

                    url :    rootPath + 'friend/addFriendReq',

                    data:    "userId="       + user_id     +

                             "&friendId="    + friend_id   +

                             "&status="      + status  , 

                    success: function( serverResponse )

                             {

                                 if( serverResponse == 'success')

                                 {

                                    location.href = HTTP_REFER ; 

                                 }

                                 else

                                    {

                                        return;

                                    }

                             }

                }

           );

 }

 

 function playInlineVideo(videoId,divId)

 {

	    var arrayString;

	    

      if ( $.browser.msie ) 

      {

        arrayString = videoId.split("/");

        videoId     = arrayString[4];

			}

			

     	var html  = '';

     	

	    html += '<object>';

	    html += '<param name="movie" value="http://www.youtube.com/v/'+videoId+'"></param>';

	    html += '<param name="autoplay" value="1">';

	    html += '<param name="wmode" value="transparent"></param>';

	    html += '<embed src="http://www.youtube.com/v/'+videoId+'&autoplay=1" type="application/x-shockwave-flash" wmode="transparent" width="380" height="380" ></embed>';

	    html += '</object>';

	    

	    var url = 'http://www.youtube.com/v/'+videoId;

 }

 

 function previewFeelings()

 {

    	recip_name    = $("#recp_name").val();

    	send_name     = $("#send_name").val();

    	feeling_text  = $("#feelings_body").val();

    	quote = $('#timeline').html();

    	

    	divContent    = '<div style="background-color:#98CE75; color:white; margin:0;padding:3px"> ' + rootPath + '/feeling/asdfertf32dfd</div>'

    	divContent   += '<b>' + recip_name + '</b><br/>';

    	divContent   += quote;

    	

    	$('#email-box').html( divContent );

 }

 

 /**

 * purpose      Insert the video to Page

 *

 * @param       video Link

 * @return      Ajax Response

 * @author      M.M.H.Masud <masudiiuc@gmail.com>

 */

function insertVideo( videoSource, videoTitle, searchTag, videoURL,videoKeyword,videoId ) 

{

	var inLinePlay =true;

	

	videoURL ='http://www.youtube.com/v/'+videoId;

	

  if( HTTP_REFER.indexOf( 'sendafeeling' ) != -1 )

  {

        $.ajax({

                    type    :    "POST",

                    url     :    rootPath + "site/sendFeelingVideo",

                    data    :    "videoSource="      + videoSource+ 

                                 "&videoTitle="      + videoTitle+   

                                 "&videoId="         + videoId+   

                                 "&videoURL="        + videoURL+

                                 "&searchTag="       + searchTag+ 

                                 "&keyword="         + videoKeyword ,

                    success :    function( serverResponse )

                                 {

                                     $("#feeling").val(feelText) ;



                                     //$("#timeline").html( serverResponse );

                                     $("#timeline").prepend(serverResponse);

                                 }

                });

    }

    else

    {

        $.ajax({

                        type:    "POST",

                        url:     rootPath  + 'member/insertVideo',

                        data:    "videoSource="      + videoSource+ 

                                 "&videoTitle="      + videoTitle+   

                                 "&videoId="         + videoId+   

                                 "&videoURL="        + videoURL+

                                 "&searchTag="       + searchTag+ 

                                 "&keyword="         + videoKeyword ,    

                        success: function(msg)

                        {

                                 

                                 if( msg == 'not_login' )

                                 {

                                    location.href = rootPath +'auth/login';

                                    return;

                                 }

                                 

                                 $("#recently").remove();

				                         $("#feeling").val(feelText) ;

                                 head="<h2 id='recently'>Who's been mooning recently?</h2>";

                                 $("#timeline").prepend(msg);

                                 $(".add-videos").hide();

				                         videoHide();

                                 // $('#' + divId).lightBox({type:'video',inLineVideoId:'videoId'});

                                 $('.videoImage a').lightBox({type:'video',inLineVideoId:'true'});

                        }

             });

    }//end of if else

}



//build in function from http://www.webtoolkit.info/javascript-trim.html

function trim(str, chars) 

{

    return ltrim(rtrim(str, chars), chars);

}



function ltrim(str, chars) 

{

    chars = chars || "\\s";

    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");

}



function rtrim(str, chars) 

{

    chars = chars || "\\s";

    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");

}



function removeFromArr( arr, val_tag )

{

    var index;



    for( i = 0; i < arr.length; i++ )

    {

        if( arr[i] == val_tag )

        {

            index = i;

            break;

        }

    }



    arr.splice(index,1);

    

    return arr;

}



function changeFeelingText( feel_id ) 

{

    inlineInput = '<input class="inlineInput" type="text" name="new_feeling_'+ feel_id +'" id="new_feeling_'+ feel_id +'">'+

                  '&nbsp;<button style="display:inline; margin-bottom:3px;" onclick="saveNewFeelingsText(\''+ feel_id +'\')" >' +

                        '<img src="'+ rootPath +'images/tick.gif"/>' +

                        'Add' + 

                  '</button>' +

                  '&nbsp;<button style="display:inline; margin-bottom:3px;" onclick="hideInputBox(\''+ feel_id +'\')" >' +

                        '<img src="'+ rootPath +'images/tick.gif"/>' +

                        'Cancel' + 

                  '</button>';

    

    $("#inputBox_" + feel_id ).html( inlineInput );

    $("#new_feeling_" + feel_id ).focus();

}



function hideInputBox( feel_id )

{

    $("#inputBox_" + feel_id ).html('') ;

}







function saveNewFeelingsText( feel_id )

{

    feel_text = $("#new_feeling_" + feel_id).val();

    

    $("#inputBox_" + feel_id ).html('') ;

    

    if( trim(feel_text) == '' )

    {

        return;

    }

    

    $.ajax({

               type:    "POST",

               url:     rootPath  + 'moonrise/update_feelings',

               data:    "feel_id="      + feel_id+ 

                        "&feel_text="   + feel_text ,    

               success: function( msg )

                        {

                            $("#feel_text_" +feel_id ).html( msg ) ;

                        }

            });

    

}



function remove_tag( feel_id, tag_id )

{

    tag_div = 'tag_view_' + feel_id;



    $.ajax ( {

                    type:    "POST",

                    url:     rootPath + 'moonrise/remove_tag',

                    data:    "feel_id="    + feel_id +

                             "&tag_id="    + tag_id,

                    success: function( isSuccess )

                             {

                                 if( isSuccess )

                                 {

                                    document.getElementById( "tag_view_" + tag_id ).style.display = 'none';

                                 }

                             }

             }

           )

}



function addTagToFeeling( feel_id )

{

    inlineInput = '<input class="inlineInput" type="text" name="new_tag_' + feel_id + '" id="new_tag_' + feel_id  + '" >'+

                  '&nbsp;<button style="display:inline; margin-bottom:3px;" onclick="saveNewTag(\''+ feel_id +'\')" >' +

                        '<img src="'+ rootPath +'images/tick.gif"/>' +

                        'Add' + 

                  '</button>' +

                  '&nbsp;<button style="display:inline; margin-bottom:3px;" onclick="hideTagInputBox(\''+ feel_id +'\')" >' +

                        '<img src="'+ rootPath +'images/tick.gif"/>' +

                        'Cancel' + 

                  '</button>';  

    

    $("#add_input_tag_" + feel_id ).html( inlineInput );

    $("#new_tag_" + feel_id ).focus();

}



function saveNewTag(feel_id)

{

    tag_text = $("#new_tag_" + feel_id ).val();

    

    if( trim(tag_text) == '' )

    {

        document.getElementById( 'new_tag_' + feel_id ).style.display = 'none';

        return;

    }

    

    $.ajax( {

                type :           "POST",

                url  :           rootPath + 'moonrise/add_new_tag',

                data :           "feel_id="   + feel_id +

                                 "&tag_text=" + tag_text,

                success:         function( newTagLink )

                                 {

                                     if( newTagLink )

                                     {

                                         $("#add_input_tag_" + feel_id ).html('');

                                         $("#add_new_tag_" + feel_id).prepend( newTagLink );

                                     }

                                 }

            } 

          );

}



function hideTagInputBox( feel_id )

{

    $("#add_input_tag_" + feel_id ).html('');

}



function addCommentsToFeelings( feel_id )

{

    document.getElementById('comments_div_' + feel_id ).style.display = 'inline';

}



function closeComments( feel_id )

{

    document.getElementById('comments_box_' + feel_id ).value = "";

    document.getElementById('comments_div_' + feel_id ).style.display = 'none';

}



function postComments( feel_id )

{

    comment_text = document.getElementById('comments_box_' + feel_id ).value;

    

    $.ajax( {

                type :           "POST",

                url  :           rootPath + 'moonrise/postCommentsToFeelings',

                data :           "feel_id="        + feel_id +

                                 "&comments_text=" + comment_text,

                success:         function( totalComment )

                                 {

                                     if( totalComment != '' )

                                     {

                                         closeComments( feel_id );

                                         //$("#totalComments_" + feel_id ).html( 'Waiting for approval' );

                                         $("#totalComments_" + feel_id ).html( totalComment );

                                     }

                                 }

            } 

          );

}



function commentAprrove( comm_id, state )

{

    $.ajax ( 

                {

                    type:       "POST",

                    url :       rootPath + 'moonrise/changeCommentsStatus',

                    data:       "comment_id="    + comm_id +

                                "&status="       + state,

                    success:    function( response )

                                {

                                    $("#cmd_" + comm_id ).html( response );

                                }

                }

           );

}



function checkChoiceOption( objId )

{

    document.getElementById(objId).checked = true;

}



function deletUserComments( comm_id )

{

    $.ajax ( 

                {

                    type:       "POST",

                    url :       rootPath + 'moonrise/deleteComment',

                    data:       "comm_id="       + comm_id,

                    success:    function( response )

                                {

                               	

                                    $("#delete_msg" ).html( '<div class="blockquoteForErr">' + 

                                                                  response +

                                                                 '</div>');

                                                                 

                                    $("#main_div_" + comm_id ).fadeOut("slow");

	                                

                                }

                }

           );

}



function saveUserSettings()

{

	//alert($("#send_notification").is(":checked"));

	

	if( $("#send_notification").is(":checked") )

	{

		isChecked = 'Yes';

	}

	else

	{

		isChecked = 'No';

	}

	

	if( $("#unsubscribe_me").is(":checked") )

	{

		unsubscribe = 'Yes';

	}

	else

	{

		unsubscribe = 'No';

	}

	

	$.ajax ( 

                {

                    type:       "POST",

                    url :       rootPath + 'moonrise/saveUserSettings',

                    data:       "sendNotification="       + isChecked +

								"&unsubscribe="           + unsubscribe,

                    success:    function( response )

                                {

                                    $("#setting_msg" ).html( '<div class="blockquoteForErr">' + 

                                                                   response +

                                                                  '</div>');

                                }

                }

           );

}



function makeItFavorites( feeling_id , user_id, cmd )

{

	//alert( feeling_id + '--------' + user_id  + '----' + cmd);

	

	$.ajax(

			{

			     type:        "POST",

				 url:         rootPath + 'moonrise/makeItFavorites',

				 data:        "feeling_id="        + feeling_id +

				              "&user_id="          + user_id    +

							  "&cmd="              + cmd,

				 success:     function(response)

						      {

							    //  alert( response );

								  if( response == 'Favourites' )

								  {

									  contents = '<a href="javascript:void(0);" onclick="makeItFavorites(\'' + feeling_id + '\', \'' + user_id + '\', \'No\')">' +

									             '<img border="0" src="'+ rootPath +'images/icon_star_full_16x16.gif"></a>';

									  

									//  alert( contents );

									  $("#makefav_" + feeling_id ).html ( contents );

									  

								  }

								  else

								  if( response == 'Unfavourites' )

								  {

									  contents = '<a href="javascript:void(0);" onclick="makeItFavorites(\'' + feeling_id + '\', \'' + user_id + '\', \'Yes\')">' +

									             '<img border="0" src="'+ rootPath +'images/icon_star_empty_16x16.gif"></a>';

								      

									//  alert( contents );

									  $("#makefav_" + feeling_id ).html ( contents );

								  }

							  }

			}

	      );

}



function showDiv( show_div, hide_div )

{

	document.getElementById( hide_div ).style.display = "none";

	//$("#hide_div").fadeOut("slow");

	document.getElementById( show_div ).style.display = "inline";

	//$("#show_div").fadeIn("slow");

}



function saveAboutMeContents()

{

	//contents = $("#about_me_contents").val();

	contents = $("#frmAboutMe").serialize();

	

	$.ajax(

				{

					type: "POST",

					url : rootPath + "moonrise/saveAboutMeContents",

					//data: "contents=" + contents,

					data:  contents,

					success: function( saveMsg )

					         {

							    //alert( saveMsg );

								$("#setting_msg" ).html( '<div class="blockquoteForErr">' + 

                                                                   saveMsg +

                                                                  '</div>');

								return false;	

							 }

				}

	      );

}