/**
 * purpose
 *
 * @param
 * @return
 * http://code.google.com/apis/youtube/developers_guide_protocol.html
 */

 var feelText = 'Type in how you feel...';

jQuery.fn.youtube = function(o) 
{   
    	 
    var script = null;
	var s = { 
                cleanReturn : 1,          //do you want a full youtube return, or just an image list
	        api_url     : null,
        	inlineVideo : 1,        //do you want to redirect to youtube, or play inlinevideo
		timer       : null,
		results     : null,
		callback    : null,
        	type        : null,    // allowed values: 'user', 'search'
        	user_id     : null,
        	tags        : null,    // comma separated list
		blockUI     : false,   // boolean, if true requires jquery.litebox.js
                keyword     : null,
                tag         : null,
		start       : null,    //The 1-based index of the first result to be retrieved (for paging).
		div         : this
				
            };
    if(o) 
	{
	    $.extend(s, o);
	}
   			
    return this.each(function(){
        		   
	  $('#youtube').remove();
	  $(this).append('<ul id="youtube">');
	  var url = $.youtube.format(s);
	  $.youtube.request(url);
    	});
}

/**
 * purpose
 *
 * @param
 * @return
 */
$.youtube = {
	        s: {}, 
                 /* start of format function */
		 format: function(s)
                 {
		          
		  this.s = s;
	          if (s.url) 
        	        {
        	          return s.url;
        	        }
        	        
        	        if (!s.callback) 
        	        {
        	            s.callback = 'dummy';
        	        }
                  
                  /*split the Yahoo tearms*/
                  tagStr = s.tags;
                  tagArr = tagStr.split('^^^');
                  s.keyword = tagArr[0];
                  s.tag     = tagArr[1];
                  
                  
                  if( s.tag == '' )
                  {
                    var url ='http://gdata.youtube.com/feeds/videos/-/'+s.keyword+'?start-index='+s.start+'&max-results='+s.results+'&alt=json-in-script&callback='+s.callback;
                  }
                  else
                  {
                    var url ='http://gdata.youtube.com/feeds/videos/-/'+s.tag+'?start-index='+s.start+'&max-results='+s.results+'&orderby=updated&alt=json-in-script&callback='+s.callback;
                  }
		  // alert (url);
		   return url;
		},  
		          /* end of format function */
              
              /* Start of request function */  
              request: function(url)
              {
		
		
		
		 var oldScriptTag = document.getElementById('jsonScript');

                 //alert(oldScriptTag);

		 if (oldScriptTag) 
		 {

                    //alert (oldScriptTag.id);

                    //alert ('delete');

		    oldScriptTag.parentNode.removeChild(oldScriptTag);
                  }
		 
                 //myurl = "http://gdata.youtube.com/feeds/videos/-/cool";		
		 script = document.createElement('script');
    		 	
		 script.setAttribute('id', 'jsonScript');
                 script.setAttribute('type', 'text/javascript');
		 script.setAttribute('src', url);
                 // InsertBefore for IE.
                // IE crashes on using appendChild before the head tag has been closed.
               // var head = document.getElementsByTagName('head').item(0);
                //head.insertBefore(script, head.firstChild);
		 //$('head',document).append( script );
		 // $('head').append(script);
		document.documentElement.firstChild.appendChild(script);
		//document.getElementsByTagName('head')[0].appendChild(script);
		
	// myurl ="http://gdata.youtube.com/feeds/videos?vq=sad&start-index=13&max-results=12&alt=json&callback=?";
	      // myurl ="http://gdata.youtube.com/feeds/videos?vq=sad&start-index=13&max-results=12&alt=json";
              
		//http://gdata.youtube.com/feeds/standardfeeds/most_viewed?alt=json-in-script&callback=handleData
		//$.getJSON("http://gdata.youtube.com/feeds/videos?vq=sad&start-index=13&max-results=12&alt=json&callback=?",jQuery.youtube.response); 
		//alert ('hello');
		//$.getJSON("http://gdata.youtube.com/feeds/videos?vq=sad&start-index=13&max-results=12&alt=json-in-script",
        //function(data){
          //    alert ('here');
        //});
		//$.getJSON(myurl,function(data){alert ('here');});
		 //jQuery('head', document).append(script);
	       },  
        /* end of request function */
	          
	/* Start of response function */
	response: function(r)
	{
	   //alert ('json response');
	   //alert (r);
	   // id = $.youtube.getId(r.feed.title.$t);
	   $.youtube.listVideos(r);  
        },
	/* end of response function */
       /* Start of getId function */
      getId: function(string)
	    {
		  var match = string.lastIndexOf("'s Videos");
		  if (match != -1) 
	          {
			  id = string.substring(0,match);
			  return id.toLowerCase();
		  }
			  
		 var match = string.lastIndexOf("query");
		if (match != -1) 
		  {
			  id = string.substring(match+7);
			  return id.toLowerCase();
		  }
	    },
	    /* End of getId function */
	    
	    /* start of listVideos function */
	    listVideos: function(json)
	    {
		  var returnHTML  = '';
		  returnHTML     += '<p>';
		
		if(json.feed.entry)
		{
		     for (var i = 0; i < json.feed.entry.length; i++) 
		     {
		         //alert (i);
			 videoCount =i; 
                         var entry = json.feed.entry[i];
			 for (var k = 0; k < entry.link.length; k++) 
			  {
					
					if (entry.link[k].rel == 'alternate') 
					{
					    url = entry.link[k].href;
					   
					   break;
					}
			   }
		  
		  
		var thumb = entry['media$group']['media$thumbnail'][3].url;
					 
		  
		  if(this.s.cleanReturn == 1)
		  {
			      
			 var videoId  = $.youtube.getVideoId(url);
			
			  if( this.s.inlineVideo == 1 )
			      {
			    
								returnHTML += '<a href="'+ videoId +'" title = "' + entry.title.$t + '"  tag="' +this.s.tag +'"  thumb = "'+ thumb + '" url = "'+ url + '" keyword = "'+ this.s.keyword + '" >';
								returnHTML += '<img src="' + thumb + '" width="75" height="75" id="youtubethumb" alt="' + entry.title.$t + '" >';
								returnHTML += '</a>';
							   
						      }
			      else
			      {
				    //view the video thumbail with video link
				returnHTML += '<a href="javascript:void(0);" onclick="insertVideo(\'' + thumb + '\',\'' + entry.title.$t + '\',\'' +this.s.tag+ '\',\'' + url + '\',\'' + s.keyword + '\');"><img src="' +thumb + '" width="75" height="75" id="youtubethumb" alt="' + entry.title.$t + '" ></a>';	
				    //returnHTML += '<a href="' + url + '"><img src="' + thumb + '" width="75" height="75" id="youtubethumb" alt="' + entry.title.$t + '" ></a>';	
			      }
		  }
		  else
		  {
				returnHTML += entry.content.$t;
		  }
			  
		       }
	  }
	  else
	  {
             videoCount = 0;
             returnHTML += '<blockquote>Sorry, no results from YouTube! Try less words. </blockquote>';
	  }
	  
	  returnHTML +='</p>';
	      
			  ajaxVideoStatus = 'finish'; 		  
			  $('.add-videos').html(returnHTML);
			  $('.add-videos a').lightBox({txtImage:'Video',type:'video'});
			  if (videoTabOn ==1)
                                                                                  {
				      $("#video-paging").show();
			              (videoCount>=11)?$("#video-paging-next").show():''; 
				    } 	
			  
			  
			   
	    },
			/* End of listVideos function */
        /** 
                         * @param url 
                          * @return video id   
                    */	
	getVideoId: function (url)
	{

	   var arrayURL= url.split("=");
	   if (arrayURL)
	    {
		   return arrayURL[1];
		}
	},
	/** 
	 * Play the video in bolockUI  
	 *
	 *@param id videoid
	 */
    playVideo : function (id,videoSource, videoTitle, searchTag, videoURL,inlinePlay)
     {
	    var html  = '';
	    html     += '<div id="youtubecontent" >';
	    if (this.s.blockUI)
	     {
	       //'<img src="' +  rootPath  + 'images/add.png' + '" alt ="add">';		  
          
		  if (inlinePlay == 'true')
		   {
		      html += '<a href="javascript:$.youtube.stopVideo()"  id="close"><img src="' +  rootPath  + 'images/dialog-titlebar-close.png' + '" alt ="add">Close</a>';
		   }else 
		   {
	                  html += '<a href="javscript:void(0);" onclick="javascript:insertVideo(\'' + videoSource+ '\',\'' + videoTitle+ '\', \'' +searchTag +'\',\'' + videoURL+'\' )"  id="add"><img src="' +  rootPath  + 'images/add.png' + '" alt ="add">Use</a>';	   
			 html += '<a href="javscript:void(0);" onclick="javascript:$.youtube.stopVideo()"  id="close"><img  src="' +  rootPath  + 'images/dialog-titlebar-close.png' + '" alt ="add">Close</a>';
		   }
		   
		  
	     }
	   
	   html += '<object>';
	   html += '<param name="movie" value="http://www.youtube.com/v/'+id+'"></param>';
	   html += '<param name="autoplay" value="1">';
	   html += '<param name="wmode" value="transparent"></param>';
	   html += '<embed src="http://www.youtube.com/v/'+id+'&rel=1" type="application/x-shockwave-flash" wmode="transparent" width="410" height="410" ></embed>';
	   html += '</object>';
	   html += '</div>';
	   
	   
	   if (this.s.blockUI)
	   {
	      $.blockUI(html,{ width: '410px', height: '410px' ,top : '15%' });
		//  $('#play').lightBox();
	    }
	},
	  /** 
                *unblock the UI
              */
    stopVideo : function ()
    {
	   
	   if (this.s.blockUI)
	   {
	       $.unblockUI();
	   }
	  // insertVideo(videoSource, videoTitle, searchTag, videoURL); 		
	},	
	            
 	 /* start of abort function */
 	  abort: function(string)
	   {
	     return false;
	   }
     /* End of abort function */
};//end of

