// jQuery related calls, either direct jquery library or third party plugins based on the same
	$(document).ready(
		function()
		{
					
			
			/**
			 * Function for hiding popup msg window
			 */
			function startTimer()
			{
				$.timer(6000, function (timer) {
				   	//alert("hello");
					$('#SuccessMessage').slideUp();
					$('#ErrorMsg').slideUp();
				   	timer.stop();
				   });
			}
			
			
			
			
			/*
			 * Method for authenticating user . 
			 * Accoridng to result show timeline and error
			 */
			function authenticate(encodedAuthorization,password)
			{
				$.ajaxSetup({
			        beforeSend: function(xhr) 
			        			{
        							xhr.setRequestHeader("Accept", "text/javascript");
        							xhr.setRequestHeader("Authorization", "Basic "+encodedAuthorization);
        							xhr.setRequestHeader("twiteract-api-access-token", Base64.encode("umundo"));
        						}
				});
                   
				$.getJSON(apiHost+'/api/authenticate.json',
				        function(data)
				        {
				        	if(!data.error)
				        	{
				        		var encodedTwiterAuthorization = Base64.encode(data.result.screenName+":"+password);
				        		
				        		$.cookie('twitterAuthorization', encodedTwiterAuthorization,{path:"/"});
				          		$.cookie('Username', data.result.screenName,{path:"/"});
				          		$.cookie('ProfileImage', data.result.profileImageUrl,{path:"/"});
				          		//$.cookie('Status', data.result.status.text);
								$('#authroization').val($.cookie('twitterAuthorization'));
								$('#user').val(data.result.screenName);
								$.cookie('userid',data.result.id,{path:"/"});
								$.cookie('Bgimage',data.result.profileBackgroundImageUrl,{path:"/"});
								$.cookie('Repeat',data.result.profileBackgroundTile,{path:"/"});
								$.cookie('Bgcolor',data.result.profileBackgroundColor,{path:"/"});
								$.cookie('SuccessMsg','false',{path:"/"});
								$.cookie('CurrentState','friends',{path:"/"});
								window.location.href = host;
								$.cookie('CurrentState','friends',{path:"/"});
								//if(fromTweet == false)
				          		//showWelcomePane();
								/*else
								postTweet();*/	
				        	}
				        	else
				        	{
				        		$('#LoginBtn').html('<a href="javascript:void(0);" id="Login" class="bt_login">Login</a>');
				                
				                $("#Login").bind("click", function()
				    					{
				    						login('#Login');
				    					}
				    				);
				                
				                if(data.error.errorCode == 1121)
				                {
				                	//alert("Authentication failed. Your Twitter Username\/Password are incorrect.");
				                	$('#SuccessMessage').slideUp();
									$('#ErrorMsg').html("Authentication failed. Your Twitter Username\/Password are incorrect.");
									$('#ErrorMsg').slideDown();
									window.scrollTo(0,50);
									startTimer();
				                }
				                else
				                {
					        	   // alert(data.error.errorMessage);
					        	    $('#SuccessMessage').slideUp();
									$('#ErrorMsg').html(data.error.errorMessage);
									$('#ErrorMsg').slideDown();
									window.scrollTo(0,50);
									startTimer();
				                }
				        	}
				        }
		        );
			}
			var result = {
				
					rmtresponse : ""
			};
			/**
			 * Method for load some effects while page page loading
			 * And checks Authorization.
			 */
			function loadUp()
			{
				$('#headerUsername').inputTextToggle();
				$('#headerPassword').inputTextToggle();
				//$('#twitterUsername').inputTextToggle();
				//$('#twitterPassword').inputTextToggle();
				$('#text').inputTextToggle();
				checkAuthorization();
				
				
			}
			
			
			
			
			
			loadUp();

			
			
			
			
			
			function goToHomePage()
			{
				var username = $.cookie('Username');
				
				$.cookie('CurrentState',null,{path:"/"});
				
				//$.cookie('CurrentState',from,{path:"/"});
				
				window.location.href = host;
				
				
			}
			
			
			
	

			
		
			// Define corners and opposites arrays
			var corners = [
			    'topMiddle'
			];
			var opposites = [
			   'bottomMiddle'
			];
			var i = 0;

			  $('a.Links')
			      .mouseover(function(e)
			      {
				 
			         // If counter reaches maximum, reset
			         if(i === corners.length) i = 0;
			         
			         // Destroy currrent tooltip if present
			         if($(this).data("qtip")) $(this).qtip("destroy");
			         
			         $(this).qtip({
			               content: $(this).attr("alt"), // Set the tooltip content to the current corner
			               position: {
			                  corner: {
			                     tooltip: corners[i], // Use the corner...
			                     target: opposites[i] // ...and opposite corner
			                  }
			               },
			               show: {
			                  when: false, // Don't specify a show event
			                  ready: true // Show the tooltip when ready
			               },
			               hide: false, // Don't specify a hide event
			               style: {
			                  border: {
			                     width: 3,
			                     radius: 3
			                  },
			                  padding: 10, 
			                  textAlign: 'left',
			                  tip: true, // Give it a speech bubble tip with automatic corner detection
			                  name: 'cream' // Style it according to the preset 'cream' style
			               }
			            });
			         
			         i++; // Increase the counter
			      }).mouseout(function(e){
							       // Destroy currrent tooltip if present
			         if($(this).data("qtip")) $(this).qtip("destroy");
							    });
			  
		
			  
			
			/**
			 * Method for checking authorization of user.
			 * Either user logged in or not. If user is logged in user then show friends timeline and show welcome pane
			 */
			function checkAuthorization()
			{
				
				var twitterAuthorization = $.cookie('twitterAuthorization');
				if(twitterAuthorization)
				{
					showWelcomePane();
					
				} 
				else
				{
						    
					$('#Header_login').show();
					
					$('#Header_user').hide();
					
					/*// Show the wait message
					$('#TimeLine').html("Public");
					$('#Tweets').html('');
					$('#Tweets').html('<center><br /><img src="'+host+'/images/wait30trans.gif" /><h1> fetching public tweets </h1></center>');
                    
					
					$.ajaxSetup({
				        beforeSend: function(xhr) 
				        			{
	        							xhr.setRequestHeader("twiteract-api-access-token", Base64.encode("umundo"));
	        							
	        						}
					});
	                   
					
					$.getJSON(
							host+'/api/statuses/public_timeline.json?profile=web',
					        function(data)
					        {
					        	if (!data.error) 
								{
									showTweetTimeline(data.result);
								}
								else
								{
									//alert(data.error.errorMessage);
									$('#SuccessMessage').slideUp();
									$('#ErrorMsg').html(data.error.errorMessage);
									$('#ErrorMsg').slideDown();
									window.scrollTo(0,50);
									startTimer();
								}
					        }
			        );*/
					
					
					
					
				}
			}
			
			
			/**
			 * Assign event on TweetPane heading
			 */
			$('#TweetFormPaneHeading').click(
				function()
				{
		
					
					openForm('#TweetFormPaneHeading');
				}
			);
			
			/**
			 * Assign event on TweetPane arrow
			 */
			$('#TweetArrow').click(
				function()
				{
		
					
					openForm('#TweetArrow');
				}
			);
			
			/**
			 * Assign event on TweetPane arrow
			 */
			$('#TweetDownArrow').click(
				function()
				{
		
					
					closeForm('#TweetDownArrow');
				}
			);
			
			/**
			 * function for opening twwet form
			 */
			function openForm(ele)
			{
				    
				openNewTweetForm();
           	   			
			}
			
			/**
			 * function for closing twwet form
			 */
			function closeForm(ele)
			{
				openDetailPane(ele);
			}
			
			
			$('#ProductLogo').click(
					function(event)
					{
						//goToHomePage();
						$.cookie('CurrentState',null,{path:"/"});
						window.location.href = host;
					}
				);
			
			/**
			 * Method for getting public timeline of twiteract
			 */
			function getPublicTimeline()
			{
				
				// Show the wait message
				$('#TimeLine').html("Public");
				$('#Tweets').html('');
				$('#Tweets').html('<center><br /><img src="'+host+'/images/wait30trans.gif" /><h1> fetching public tweets </h1></center>');

				$.ajaxSetup({
			        beforeSend: function(xhr) 
			        			{
        							xhr.setRequestHeader("twiteract-api-access-token", Base64.encode("umundo"));
        							
        						}
				});
				
				$.getJSON(
						host+'/api/statuses/public_timeline.json?profile=web',
				        function(data)
				        {
				        	if (!data.error) 
							{
								showTweetTimeline(data.result);
							}
							else
							{
								//alert(data.error.errorMessage);
								$('#SuccessMessage').slideUp();
								$('#ErrorMsg').html(data.error.errorMessage);
								$('#ErrorMsg').slideDown();
								window.scrollTo(0,50);
								startTimer();
							}
				        }
		        );
			}
			
			/**
			 * Method for navigating user to home page
			 */
			function gotoHome(from)
			{
				
				$.cookie('CurrentState',null,{path:"/"});
				
				$.cookie('CurrentState',from,{path:"/"});
				
				window.location.href = host;
			}
			
			/**
			 * Method to get user own timeline from twiteract
			 */
			function getUserTimeline()
			{
				// Show the wait message
				$('#TimeLine').html("Your");
				$('#Tweets').html('');
				$('#Tweets').html('<center><br /><img src="'+host+'/images/wait30trans.gif" /><h1> fetching your tweets </h1></center>');

				$.ajaxSetup({
		        	beforeSend: function(xhr) 
	        			{
							xhr.setRequestHeader("Accept", "text/javascript");
							xhr.setRequestHeader("Authorization",  $.cookie('twitterAuthorization'));
							xhr.setRequestHeader("twiteract-api-access-token", Base64.encode("umundo"));
						}
				});
				
				$.getJSON(
						host+'/api/statuses/user_timeline.json?profile=web',
				        function(data)
				        {
				        	if (!data.error) 
							{
				        		showMyTweetTimeline(data.result);
							}
							else
							{
								//alert(data.error.errorMessage);
								$('#SuccessMessage').slideUp();
								$('#ErrorMsg').html(data.error.errorMessage);
								$('#ErrorMsg').slideDown();
								window.scrollTo(0,50);
								startTimer();
							}
				        }
		        );
			}
			
			/**
			 * Method to get friends time of logged in user from twiteract
			 */
			function getFriendsTimeline()
			{
				// Show the wait message
				$('#TimeLine').html("Friends");
				$('#Tweets').html('');
				$('#Tweets').html('<center><br /><img src="'+host+'/images/wait30trans.gif" /><h1> fetching your friends tweets </h1></center>');

				$.ajaxSetup({
		        	beforeSend: function(xhr) 
	        			{
							xhr.setRequestHeader("Accept", "text/javascript");
							xhr.setRequestHeader("Authorization",  $.cookie('twitterAuthorization'));
							xhr.setRequestHeader("twiteract-api-access-token", Base64.encode("umundo"));
						}
				});
				
				$.getJSON(
						host+'/api/statuses/friends_timeline.json?profile=web',
				        function(data)
				        {
							
				        	if (!data.error) 
							{
								showTweetTimeline(data.result);
							}
							else
							{
								//alert(data.error.errorMessage);
								 $('#SuccessMessage').slideUp();
									$('#ErrorMsg').html(data.error.errorMessage);
									$('#ErrorMsg').slideDown();
									window.scrollTo(0,50);
									startTimer();
							}
				        }
		        );
			}
			
			var currentTimeline = null;
			
			function showDetails(i){
				
				window.scrollTo(0,50);
				var acutalId = i.split("ContentThumb")[1];
			
				showDetailPane(currentTimeline[acutalId],"OnClick");
				
				$('#TweetFormPaneHeading').html("tweet a video / audio / picture status");
          	    $('#StatusId').html("");
          	    $('#TextValue').html('');
          	 
          	    var html = '<textarea id="text" name="text" class="text_twit" title="Watch my tweet at #twiteract" ></textarea>';
          	  $('#TextValue').html(html);
          	 
          	  $('#text').inputTextToggle();
          	  $('#tweetPost').removeClass('updateReply');
          	  $('#tweetPost').addClass('update');

          	  $('#tweetPost').html('Update');
          	  
          	  //$('#PlayerViewContent').hide();
          	  $('#Cancel').hide();
          	  
          	  
          	 /**
   			 * Assign event on tweetPost button for posting tweet
   			 */
   			$('#text').keyup(
   					function()
   					{
   						updateCharsNum('#text',110,'#CharLimit');
   					}
   				);
				
				$('#TweetPaneForm').hide();
				$('#TweetArrow').show();
				$('#TweetDownArrow').hide();
				$('#PlayerViewContent').slideDown();
				//$('#ViewDetails').hide();
				//$('#PlayerView').slideDown();
				/**
				 * Log url 
				 */
				$.getJSON(
						host+'/rmtanalytics/logview/'+currentTimeline[acutalId].id,
				        function(data)
				        {
				        }
					  );
				
			}
			
			
			
						
			/**
			 * Method for rendering resulted timeline at frontend
			 */
			function showTweetTimeline(data)
			{
				var html = '<ul id="Demo">';
				var length = data.length;
		     
				
				
				currentTimeline = data;
				if(data.length > 0)
				{	
					if( $("#TweetDetailsMessage").html() != "FROMRMT")
					{	
						showDetailPane(data[0]);
					}
					
					for (var i = 0; i < length; i++)
					{
						
						var date = new Date(data[i].createdAt);
						var age = jQuery.timeago(date); 
						
						var tweetMsg = new String();
						tweetMsg = data[i].textTweet;
						
						var tweetMsgArr = new Array();
						tweetMsgArr = tweetMsg.split(" ");
						
						var tweetHref = new String();
						var newTweetMessage = new String();
						var arrLen = tweetMsgArr.length;
						
						for (var j = 0; j < arrLen; j++)
						{
							if(tweetMsgArr[j].indexOf('http://') != -1)
							{
								tweetHref = tweetMsgArr[j];
								
							}
							else
								newTweetMessage += tweetMsgArr[j] + ' ';
						}
						
						//var finalTweetMsg = showLines(50, newTweetMessage);
						
						var mm=newTweetMessage.substring(3,8);
						
						if(mm!="mmmmm" && mm!="wwwww" && mm!="ddddd" && mm!="MMMMM" && mm!="WWWWW" && mm!="DDDDD")
						  {
						  
							finalTweetMsg=newTweetMessage.wordWrap(30,"\n", false); 
						 }
					  else{
						  finalTweetMsg=newTweetMessage.wordWrap(20,"\n", false);  
					  }		    
						
						
						html += '<li id="Demo'+i+'"><table><tr>';
						
						var thumbUrl = host+'/images/default.gif';
						
						if( data[i].webThumbUrl != null  && data[i].mediaStatus == "HOSTED")
						{
							thumbUrl = data[i].webThumbUrl;
						}
						else if(data[i].webThumbUrl == null  && data[i].sourceMediaType == "AUDIO")
						{
							thumbUrl = host+'/images/default_thumbnail.gif';
						}
						
						var twitLink = host+"/web/webwatch/"+data[i].id;
						
						var zoomUrl = host+"/images/zoom_in.png";
						var image = host+"/images/image.png";
						var video = host+"/images/video.png";
						var audio = host+"/images/audio.png";
						
												
						html += '<td valign="top" id="Thumb">' ;
												
						html += '<a id="Thumb'+i+'" class="ContentLink"><img class="ContentThumb" id="ContentThumb'+ i +'"  src="' + thumbUrl + '" alt="Watch - '+ finalTweetMsg +'" title="'+finalTweetMsg+'"/></a>' + 
						'</td>';
						
							if(data[i].sourceMediaType == "VIDEO")
							html += '<td valign="top" align="left" id="TextTweetMsg">'+finalTweetMsg+'<div id="InlineMediaStatus"><img src="' + video + '" class="Zoom"/>&nbsp;video</div><br /><span><img id="ProfileThumb" src="'+data[i].profileImageUrl	+'" />&nbsp;by- <a href="http://twitter.com/'+data[i].fromUser+'" target="_blank">'+data[i].fromUser+'</a> / </span><span id="Age">posted '+age+'</span></td>';
							else if(data[i].sourceMediaType == "AUDIO")
							html += '<td valign="top" align="left" id="TextTweetMsg">'+finalTweetMsg+'<div id="InlineMediaStatus"><img src="' + audio + '" class="Zoom"/>&nbsp;audio</div><br /><span><img id="ProfileThumb" src="'+data[i].profileImageUrl	+'" />&nbsp;by- <a href="http://twitter.com/'+data[i].fromUser+'" target="_blank">'+data[i].fromUser+'</a> / </span><span id="Age">posted '+age+'</span></td>';
							else if(data[i].mediaStatus == "HOSTED")
							html += '<td valign="top" align="left" id="TextTweetMsg">'+finalTweetMsg+'<div id="InlineMediaStatus"><img src="' + image + '" class="Zoom"/>&nbsp;image</div><br /><span><img id="ProfileThumb" src="'+data[i].profileImageUrl	+'" />&nbsp;by- <a href="http://twitter.com/'+data[i].fromUser+'" target="_blank">'+data[i].fromUser+'</a> / </span><span id="Age">posted '+age+'</span></td><td id="OptionTD"><span id="Option'+i+'" class="Option" style="display:none"><a href="' + data[i].fileUrl + '" title="Zoom In -'+data[i].textTweet+'" class="Zoom"><img src="' + zoomUrl + '" /></a> </span></td>';
							else
							html += '<td valign="top" align="left" id="TextTweetMsg">'+finalTweetMsg+'<div id="InlineMediaStatus"><img src="' + image + '" class="Zoom"/>&nbsp;image</div><br /><span><img id="ProfileThumb" src="'+data[i].profileImageUrl	+'" />&nbsp;by- <a href="http://twitter.com/'+data[i].fromUser+'" target="_blank">'+data[i].fromUser+'</a> / </span><span id="Age">posted '+age+'</span></td>';
							
							
							
						html += '</tr></table></li>';
						
						
						
						
						
					}
					
					html += '</ul>';	
					
					$('#Tweets').html('');						
					$('#Tweets').html(html);
					
					
					/**
					 * Assign events on all thumbnails to view
					 */
					$('a.ContentLink').click(
							function(e)
							{
								var id = e.target.id;
								showDetails(id);
							}
					);
					
					
					$('#Demo li').hover(
							
							function (ev) {
								var spanId = this.id.split("Demo")[1];
								$("#Option"+spanId).show();
								//$(this).parent().find("span.Option").show("slow");
							},
							function () {
								var spanId = this.id.split("Demo")[1];
								$("#Option"+spanId).hide();
								//$(this).parent().find("span.Option").hide("slow");
							}
					);
					
					/**
					 * Assign zoom event on all ZoomIn button 
					 */
					$("a.Zoom").zoomimage({
						controlsTrigger: 'mouseover',
						className: 'custom',
						shadow: 40,
						controls: false,
						centered: true,
						opacity: 1,
						beforeZoomIn: function(boxID) {
							$('#' + boxID)
								.find('img')
								.css('opacity', 0)
								.animate(
									{'opacity':1},
									{ duration: 500, queue: false }
								);
						},
						beforeZoomOut: function(boxID) {
							$('#' + boxID)
								.find('img')
								.css('opacity', 1)
								.animate(
									{'opacity':0},
									{ duration: 500, queue: false }
								);
						}
						});
	
				}
				else
				{
					//alert("No tweets available.");
					$('#Tweets').html('');
					$('#Tweets').html('<center><br /><h1> No tweets available.</h1></center>');
				}
			}

			
			/**
			 * Method for rendering resulted timeline at frontend
			 */
			function showTimeline(data)
			{
				var html = '<ul id="Demo">';
				var length = data.length;
		     
				
				
				currentTimeline = data;
				if(data.length > 0)
				{	
										
					for (var i = 0; i < length; i++)
					{
						
						var date = new Date(data[i].created_at);
						var age = jQuery.timeago(date); 
						
						var tweetMsg = new String();
						tweetMsg = data[i].text;
						
						
						
						html += '<li id="Demo'+i+'"><table><tr>';
						
						
						
						html += '<td valign="top" align="left" id="TextTweetMsg">'+tweetMsg+'<br /><span><img id="ProfileThumb" src="'+data[i].profile_image_url	+'" />&nbsp;by- <a href="http://twitter.com/'+data[i].from_user+'" target="_blank">'+data[i].from_user+'</a> / </span><span id="Age">posted '+age+'</span></td>';
						
												
						
						
							
							
							
						html += '</tr></table></li>';
						
						
						
						
						
					}
					
					html += '</ul>';	
					
					$('#Tweets').html('');						
					$('#Tweets').html(html);
					
					
					
					
	
				}
				else
				{
					//alert("No tweets available.");
					$('#Tweets').html('');
					$('#Tweets').html('<center><br /><h1> No tweets available.</h1></center>');
				}
			}
			
			function deleteMyTweet(id)
			{
				var acutalId = id.split("Delete")[1];
				
				
				var richMediaId = currentTimeline[acutalId].id;
				
				var return_value = confirm("Sure you want to delete this tweet? There is NO undo!");
                 
				if(return_value == true)
				{
					//True value script
					$('#DeleteSpan'+acutalId).html("");
				$('#DeleteSpan'+acutalId).html('<img src="'+host+'/images/loading.gif" />');
				
							$.ajaxSetup({
					        	beforeSend: function(xhr) 
				        			{
										xhr.setRequestHeader("Accept", "text/javascript");
										xhr.setRequestHeader("Authorization",  $.cookie('twitterAuthorization'));
										xhr.setRequestHeader("twiteract-api-access-token", Base64.encode("umundo"));
									}
							});
							
				         
				    	 $.post(host+'/api/statuses/delete.json', {richMediaTweetId:richMediaId},
				    	    	 function(response){
							    	    if(response.result != null)
							    	    {
								    	    
								    	    //$("#retweeting").replaceWith('<span id="Retwit" >Re-Tweet</span>');
								    	    //alert("Tweet deleted successfully.");
								    	    $('#ErrorMsg').slideUp();
											$('#SuccessMessage').html("Tweet deleted successfully.");
											$('#SuccessMessage').slideDown();
											window.scrollTo(0,50);
											startTimer();
								    	    getUserTimeline();
								    	    
							    	    }
							    	    else
							    	    {
							    	    	var deleteUrl = host+"/images/delete.png";
							    	    	$('#DeleteSpan'+acutalId).html("");
											$('#DeleteSpan'+acutalId).html('<a class="Delete" id="Delete'+acutalId+'"><img id="Delete'+ acutalId +'" src="' + deleteUrl + '" /></a>');
								    	    
											//alert(response.error.errorMessage);
											$('#SuccessMessage').slideUp();
											$('#ErrorMsg').html(response.error.errorMessage);
											$('#ErrorMsg').slideDown();
											window.scrollTo(0,50);
											startTimer();
							    	    }
				    	 		},"json" );	 
				}
					
			}
			
			/**
			 * Method for rendering resulted timeline at frontend
			 */
			function showMyTweetTimeline(data)
			{
				var html = '<ul id="Demo">';
				var length = data.length;
		     
				
				
				currentTimeline = data;
				if(data.length > 0)
				{	
					if( $("#TweetDetailsMessage").html() != "FROMRMT")
					{	
						showDetailPane(data[0]);
					}
					
					for (var i = 0; i < length; i++)
					{
						
						var date = new Date(data[i].createdAt);
						var age = jQuery.timeago(date); 
						
						var tweetMsg = new String();
						tweetMsg = data[i].textTweet;
						
						var tweetMsgArr = new Array();
						tweetMsgArr = tweetMsg.split(" ");
						
						var tweetHref = new String();
						var newTweetMessage = new String();
						var arrLen = tweetMsgArr.length;
						
						for (var j = 0; j < arrLen; j++)
						{
							if(tweetMsgArr[j].indexOf('http://') != -1)
							{
								tweetHref = tweetMsgArr[j];
								//newTweetMessage += '<a href="'+tweetHref+'" >'+tweetHref+'</a>'+' ';
							}
							else
								newTweetMessage += tweetMsgArr[j] + ' ';
						}
						
						//var finalTweetMsg = showLines(50, newTweetMessage);
						
						var mm=newTweetMessage.substring(3,8);
						
						if(mm!="mmmmm" && mm!="wwwww" && mm!="ddddd" && mm!="MMMMM" && mm!="WWWWW" && mm!="DDDDD")
						  {
						  
							finalTweetMsg=newTweetMessage.wordWrap(30,"\n", false); 
						 }
					  else{
						  finalTweetMsg=newTweetMessage.wordWrap(20,"\n", false);  
					  }		 	    
						
						
						html += '<li id="Demo'+i+'"><table><tr>';
						
						var thumbUrl = host+'/images/default.gif';
						
						if( data[i].webThumbUrl != null  && data[i].mediaStatus == "HOSTED")
						{
							thumbUrl = data[i].webThumbUrl;
						}
						else if(data[i].webThumbUrl == null  && data[i].sourceMediaType == "AUDIO")
						{
							thumbUrl = host+'/images/default_thumbnail.gif';
						}
						
						var twitLink = host+"/web/webwatch/"+data[i].id;
						
						var zoomUrl = host+"/images/zoom_in.png";
						var image = host+"/images/image.png";
						var video = host+"/images/video.png";
						var audio = host+"/images/audio.png";
						var deleteUrl = host+"/images/delete.png";
						
													
						html += '<td valign="top" id="Thumb">' +
						'<a id="Thumb'+i+'" class="ContentLink"><img class="ContentThumb" id="ContentThumb'+ i +'"  src="' + thumbUrl + '" alt="Watch - '+ finalTweetMsg +'" title="'+finalTweetMsg+'"/></a>' + 
						'</td>';
						
							if(data[i].sourceMediaType == "VIDEO" && (data[i].mediaStatus == "HOSTED" || data[i].mediaStatus == 'CORRUPT'))
							html += '<td valign="top" align="left" id="TextTweetMsg">'+finalTweetMsg+'<div id="InlineMediaStatus"><img src="' + video + '" class="Zoom"/>&nbsp;video&nbsp;&middot;&nbsp;<span id="MediaStatusSpan">Status - '+data[i].mediaStatus+'<span></div><br /><span><img id="ProfileMyThumb" src="'+data[i].profileImageUrl	+'" />&nbsp;by- <a href="http://twitter.com/'+data[i].fromUser+'" target="_blank">'+data[i].fromUser+'</a> / </span><span id="Age">posted '+age+'</span></td><td id="OptionTD"><span id="Option'+i+'" class="Option" style="display:none"><span id="DeleteSpan'+i+'"><a class="Delete" id="Delete'+i+'" title="Delete this tweet"><img id="Delete'+ i +'" src="' + deleteUrl + '" /></a></span></span></td>';
							else if(data[i].sourceMediaType == "VIDEO" && (data[i].mediaStatus != "HOSTED" || data[i].mediaStatus != 'CORRUPT'))
							html += '<td valign="top" align="left" id="TextTweetMsg">'+finalTweetMsg+'<div id="InlineMediaStatus"><img src="' + video + '" class="Zoom"/>&nbsp;video&nbsp;&middot;&nbsp;<span id="MediaStatusSpan">Status - '+data[i].mediaStatus+'<span></div><br /><span><img id="ProfileMyThumb" src="'+data[i].profileImageUrl	+'" />&nbsp;by- <a href="http://twitter.com/'+data[i].fromUser+'" target="_blank">'+data[i].fromUser+'</a> / </span><span id="Age">posted '+age+'</span></td>';
							else if(data[i].sourceMediaType == "AUDIO" && (data[i].mediaStatus == "HOSTED" || data[i].mediaStatus == 'CORRUPT'))
							html += '<td valign="top" align="left" id="TextTweetMsg">'+finalTweetMsg+'<div id="InlineMediaStatus"><img src="' + audio + '" class="Zoom"/>&nbsp;audio&nbsp;&middot;&nbsp;<span id="MediaStatusSpan">Status - '+data[i].mediaStatus+'<span></div><br /><span><img id="ProfileMyThumb" src="'+data[i].profileImageUrl	+'" />&nbsp;by- <a href="http://twitter.com/'+data[i].fromUser+'" target="_blank">'+data[i].fromUser+'</a> / </span><span id="Age">posted '+age+'</span></td><td id="OptionTD"><span id="Option'+i+'" class="Option" style="display:none"><span id="DeleteSpan'+i+'"><a class="Delete" id="Delete'+i+'"><img id="Delete'+ i +'" src="' + deleteUrl + '" /></a></span></span></td>';
							else if(data[i].sourceMediaType == "AUDIO" && (data[i].mediaStatus != "HOSTED" || data[i].mediaStatus != 'CORRUPT'))
							html += '<td valign="top" align="left" id="TextTweetMsg">'+finalTweetMsg+'<div id="InlineMediaStatus"><img src="' + audio + '" class="Zoom"/>&nbsp;audio&nbsp;&middot;&nbsp;<span id="MediaStatusSpan">Status - '+data[i].mediaStatus+'<span></div><br /><span><img id="ProfileMyThumb" src="'+data[i].profileImageUrl	+'" />&nbsp;by- <a href="http://twitter.com/'+data[i].fromUser+'" target="_blank">'+data[i].fromUser+'</a> / </span><span id="Age">posted '+age+'</span></td>';
							else if(data[i].sourceMediaType == "IMAGE" && data[i].mediaStatus == "HOSTED")
							html += '<td valign="top" align="left" id="TextTweetMsg">'+finalTweetMsg+'<div id="InlineMediaStatus"><img src="' + image + '" class="Zoom"/>&nbsp;image&nbsp;&middot;&nbsp;<span id="MediaStatusSpan">Status - '+data[i].mediaStatus+'<span></div><br /><span><img id="ProfileMyThumb" src="'+data[i].profileImageUrl	+'" />&nbsp;by- <a href="http://twitter.com/'+data[i].fromUser+'" target="_blank">'+data[i].fromUser+'</a> / </span><span id="Age">posted '+age+'</span></td><td id="OptionTD"><div id="Option'+i+'" class="Option1" style="display:none"><a href="' + data[i].fileUrl + '" title=" Zoom - '+data[i].textTweet+'" class="Zoom"><img src="' + zoomUrl + '" /></a> <br /><span id="DeleteSpan'+i+'"><a class="Delete" id="Delete'+i+'"><img id="Delete'+ i +'" src="' + deleteUrl + '" /></a></span></div></td>';
							else if(data[i].mediaStatus == 'CORRUPT')
							html += '<td valign="top" align="left" id="TextTweetMsg">'+finalTweetMsg+'<div id="InlineMediaStatus"><img src="' + image + '" class="Zoom"/>&nbsp;image&nbsp;&middot;&nbsp;<span id="MediaStatusSpan">Status - '+data[i].mediaStatus+'<span></div><br /><span><img id="ProfileThumb" src="'+data[i].profileImageUrl	+'" />&nbsp;by- <a href="http://twitter.com/'+data[i].fromUser+'" target="_blank">'+data[i].fromUser+'</a> / </span><span id="Age">posted '+age+'</span></td><td id="OptionTD"><span id="Option'+i+'" class="Option" style="display:none"><span id="DeleteSpan'+i+'"><a class="Delete" id="Delete'+i+'"><img id="Delete'+ i +'" src="' + deleteUrl + '" /></a></span></span></td>';
							else
							html += '<td valign="top" align="left" id="TextTweetMsg">'+finalTweetMsg+'<div id="InlineMediaStatus"><img src="' + image + '" class="Zoom"/>&nbsp;image&nbsp;&middot;&nbsp;<span id="MediaStatusSpan">Status - '+data[i].mediaStatus+'<span></div><br /><span><img id="ProfileThumb" src="'+data[i].profileImageUrl	+'" />&nbsp;by- <a href="http://twitter.com/'+data[i].fromUser+'" target="_blank">'+data[i].fromUser+'</a> / </span><span id="Age">posted '+age+'</span></td>';
							    
								
							
						html += '</tr></table></li>';
						
						
						
						
						
					}
					
					html += '</ul>';	
					
					$('#Tweets').html('');						
					$('#Tweets').html(html);
					
					
					
					$('#Demo li').hover(
							
							function (ev) {
								var spanId = this.id.split("Demo")[1];
								$("#Option"+spanId).show();
								$("#Option1"+spanId).show();
								//$(this).parent().find("span.Option").show("slow");
							},
							function () {
								var spanId = this.id.split("Demo")[1];
								$("#Option"+spanId).hide();
								$("#Option1"+spanId).hide();
								//$(this).parent().find("span.Option").hide("slow");
							}
					);
					/**
					 * Assign events on all thumbnails to view
					 */
					$('a.ContentLink').click(
							function(e)
							{
								var id = e.target.id;
								showDetails(id);
							}
					);
					
					
					/**
					 * Assign Events on all Delete Buttons
					 */
					$('a.Delete').click(
							function(event)
							{
								var DeleteId=event.target.id;
								deleteMyTweet(DeleteId);
							}
							
					);
	
	
					/**
					 * Assign zoom event on all ZoomIn button 
					 */
					$("a.Zoom").zoomimage({
						controlsTrigger: 'mouseover',
						className: 'custom',
						shadow: 40,
						controls: false,
						centered: true,
						opacity: 1,
						beforeZoomIn: function(boxID) {
							$('#' + boxID)
								.find('img')
								.css('opacity', 0)
								.animate(
									{'opacity':1},
									{ duration: 500, queue: true }
								);
						},
						beforeZoomOut: function(boxID) {
							$('#' + boxID)
								.find('img')
								.css('opacity', 1)
								.animate(
									{'opacity':0},
									{ duration: 500, queue: true }
								);
						}
						});
	
				}
				else
				{
					//alert("No tweets available.");
					$('#Tweets').html('');
					$('#Tweets').html('<center><br /><h1> No tweets available.</h1></center>');

				}
			}
			
			/**
			 * Method for rendering detail pane for first tweet of current timeline
			 */
			function showDetailPane(data)
			{
				
				
				var tweetMsg = new String();
				tweetMsg = data.textTweet;
				
				var tweetMsgArr = new Array();
				tweetMsgArr = tweetMsg.split(" ");
				
				var tweetHref = new String();
				var newTweetMessage = new String();
				var arrLen = tweetMsgArr.length;
				
				for (var j = 0; j < arrLen; j++)
				{
					if(tweetMsgArr[j].indexOf('http://') != -1)
					{
						tweetHref = tweetMsgArr[j];
						//newTweetMessage += '<a href="'+tweetHref+'" >'+tweetHref+'</a>'+' ';
					}
					else
						newTweetMessage += tweetMsgArr[j] + ' ';
				}
				
				//var finalTweetMsg = showLines(50, newTweetMessage);
				
				var mm=newTweetMessage.substring(3,8);
				
				if(mm!="mmmmm" && mm!="wwwww" && mm!="ddddd" && mm!="MMMMM" && mm!="WWWWW" && mm!="DDDDD")
				  {
				  
					finalTweetMsg=newTweetMessage.wordWrap(30,"\n", false); 
				 }
			  else{
				  finalTweetMsg=newTweetMessage.wordWrap(20,"\n", false);  
			  }	
				
				var browserlink = window.location.href;
				
				//changes title of document
				document.title = finalTweetMsg+" - Twiteract.com";
				
				var playerHtml = "";
				
				if(data.sourceMediaType == 'VIDEO' && data.mediaStatus == "HOSTED")
				{
					var playerSrc = host+'/images/TwiteractPlayer.swf';
					var playerBase = host+'/images/';
					var flashvar = '&contentUrl='+data.fileUrl+'&contentLength='+data.duration+'&contentThumbnailUrl='+data.webThumbUrl+'&contentType=video';
					playerHtml = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"  id="umundoPlayer"  width="400" height="300" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab"> <param name="movie" value= "'+playerSrc+'" /><param name="quality" value="high" /> <param name="bgcolor" value="#CCCCCC" /> <param name="allowScriptAccess" value="always" /> <param name="wmode" value="transparent" /><param name = "allowFullScreen" value = "true"><param name="FlashVars" value="'+flashvar+'" /><embed id="umundoPlayer" src="'+playerSrc+'" base="'+playerBase+'" quality="high" swliveconnect="true" wmode="transparent" scale="noscale" flashvars="'+flashvar+'" bgcolor="#CCCCCC" width="400" height="300" name="umundoPlayer" align="middle" allowScriptAccess="always" allowFullScreen="true" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>'
					+'<textarea rows="1" cols="1" id="TextAreaID" name="TextAreaID" style="display: none"><embed id="twiteractPlayer" src="'+playerSrc+'" base="'+playerBase+'" quality="high" swliveconnect="true" wmode="transparent" scale="noscale" flashvars="'+flashvar+'" bgcolor="#CCCCCC" width="400" height="300" name="umundoPlayer" align="middle" allowScriptAccess="always" allowFullScreen="true" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />'
			        +'<br /><b>'+finalTweetMsg+'<br />'
					+'<a href="'+rmtUrl+''+data.id+'" target="_blank"><b>twiteract.com | send this to your friends</b></a>'
					+'</textarea>';
				}
				else if(data.sourceMediaType == 'AUDIO' && data.mediaStatus == "HOSTED")
				{
					var thumbUrl = host+'/images/default_thumbnail.gif';
					var playerSrc = host+'/images/TwiterAct.swf';
					var playerBase = host+'/images/';
					var flashvar = '&contentUrl='+data.fileUrl+'&contentLength='+data.duration+'&contentThumbnailUrl='+thumbUrl+'&contentType=audio';
					playerHtml = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"  id="umundoPlayer"  width="320" height="240" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab"> <param name="movie" value= "'+playerSrc+'" /><param name="quality" value="high" /> <param name="bgcolor" value="#CCCCCC" /> <param name="allowScriptAccess" value="always" /> <param name="wmode" value="transparent" /><param name = "allowFullScreen" value = "true"><param name="FlashVars" value="'+flashvar+'" /><embed id="umundoPlayer" src="'+playerSrc+'" base="'+playerBase+'" quality="high" swliveconnect="true" wmode="transparent" scale="noscale" flashvars="'+flashvar+'" bgcolor="#CCCCCC" width="320" height="240" name="umundoPlayer" align="middle" allowScriptAccess="always" allowFullScreen="true" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>'
					+'<textarea rows="1" cols="1" id="TextAreaID" name="TextAreaID" style="display: none"><embed id="twiteractPlayer" src="'+playerSrc+'" base="'+playerBase+'" quality="high" swliveconnect="true" wmode="transparent" scale="noscale" flashvars="'+flashvar+'" bgcolor="#CCCCCC" width="320" height="240" name="umundoPlayer" align="middle" allowScriptAccess="always" allowFullScreen="true" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />'
					 +'<br /><b>'+finalTweetMsg+'<br />'
						+'<a href="'+rmtUrl+''+data.id+'" target="_blank"><b>twiteract.com | send this to your friends</b></a>'
			         +'</textarea>';
				}
				else if(data.sourceMediaType == 'IMAGE' && data.mediaStatus == "HOSTED")
				{
					playerHtml = '<span id="ImageAndZoom"><span id="InnerBG"><img src="'+data.fileUrl+'" class="PlayerImage"/></span><a href="' + data.fileUrl + '" title=" Zoom - '+data.textTweet+'" class="ZoomMainClass">click here to zoom-in</a></span>'
					   			  +'<textarea rows="1" cols="1" id="TextAreaID" name="TextAreaID" style="display: none"><img src="'+data.fileUrl+'" width = "320" height="240"/>'
					   			 +'<br /><b>'+finalTweetMsg+'<br />'
									+'<a href="'+rmtUrl+''+data.id+'" target="_blank"><b>twiteract.com | send this to your friends</b></a>'
					   			  +'</textarea>';
				}
				else
				{
					var processingImage = host+"/images/message.png";
					playerHtml = '<img src="'+processingImage+'" class="PlayerImage"/>'
		   			  +'<textarea rows="1" cols="1" id="TextAreaID" name="TextAreaID" style="display: none"><img src="'+data.fileUrl+'" width = "320" height="240"/>'
		   			 +'<br /><b>'+finalTweetMsg+'<br />'
						+'<a href="'+rmtUrl+''+data.id+'" target="_blank"><b>twiteract.com | send this to your friends</b></a>'
		   			  +'</textarea>';	
				}
				
				$('#Player').html(playerHtml);
				
				
				/**
				 * Assign zoom event on all ZoomIn button 
				 */
				$("a.ZoomMainClass").zoomimage({
					controlsTrigger: 'mouseover',
					className: 'custom',
					shadow: 40,
					controls: false,
					centered: true,
					opacity: 1,
					beforeZoomIn: function(boxID) {
						$('#' + boxID)
							.find('img')
							.css('opacity', 0)
							.animate(
								{'opacity':1},
								{ duration: 500, queue: true }
							);
					},
					beforeZoomOut: function(boxID) {
						$('#' + boxID)
							.find('img')
							.css('opacity', 1)
							.animate(
								{'opacity':0},
								{ duration: 500, queue: true }
							);
					}
					});
				
					    
				var twitDetail = "";
				
				
				twitDetail = '<div id="ProfileImageView">'
				+'<img src="'+data.profileImageUrl+'" width="50" height="50" />'
				+'</div>'
				+'<div id="TweetDetailsView">'
		        
				+'<span id="TweetDetailsOwner">'+finalTweetMsg+'</span>'
		        +'<span id="TweetDetailsMsg">by - <a href="http://twitter.com/'+data.fromUser+'" target="_blank">'+data.fromUser+'</a></span>'
		        +'<input type="hidden" id="FromUser" name="FromUser" value="'+data.fromUser+'" />'
		        +'<span id="Embed">Embed &nbsp;&middot;&nbsp; Share &nbsp;&middot;&nbsp; Bookmark </span>'
		         +'<span id="EmbedGigya">'
		         +'</span>';
				
				if(data.mediaStatus == "HOSTED")
				{
					twitDetail= twitDetail+'<span id="Retwit" >Re-Tweet</span><span id="Reply">Reply</span><span id="NewTweet">New Tweet</span>'
					+'</div>';
				}
				else
				{
					twitDetail= twitDetail+'<span id="NewTweet">New Tweet</span>'
					+'</div>';
				}
				
								
				$('#TweetDetails').html(twitDetail);
				
				
				/*var thumb = host+"/images/default.gif";
				
				if(data.webThumbUrl != null)
				thumb = data.webThumbUrl;
				else if(data.webThumbUrl == null && data.sourceMediaType == "AUDIO")
				thumb = host+"/images/default_thumbnail.gif";
				
				
					
				var viewDetailHtml = '<span id="ViewThumb"><img src="'+thumb+'" /></span> <span id="Message">'+finalTweetMsg+' <br /><br />by - <a href="http://twitter.com/'+data.fromUser+'">'+data.fromUser+'</a> </span><span id="Arrow"><img src="'+host+'/images/left_arrow.gif" /></span>';	
				$("#ViewDetails").html(viewDetailHtml);
				*/
				
				//$("#PlayerViewContent").slideDown();
				detailPaneEvents(data,finalTweetMsg);
			
				
			}
			
			/**
			 * Method for assigning events to the retwut and reply buttons
			 */
			function detailPaneEvents(data,finalTweetMsg)
			{
				
				/**
				 * Assign event to ViewThumb image
				 
				
				$('#ViewThumb').click(
						function()
						{
				
							
							openDetailPane('#ViewThumb');
						}
					);
			
				$('#Arrow').click(
						function()
						{
				
							
							openDetailPane('#Arrow');
						}
					);*/
				/*
				* Assign onclick event on login button 
				 */
				$('#Retwit').click(
					function()
					{
			
						
						reTweetCall('#Retwit',data);
					}
				);
			
				 $('#Reply').click(
							function()
							{
								openReplyForm('#Reply',data.statusId,finalTweetMsg);
							}
					);
				 
					
				 $('#NewTweet').click(
							function()
							{
								openNewTweetForm();
							}
					);
				 
			    getShareMessage(data);
				
			     
			}
			
			/**
			 * method for oepnign detail pane
			 */
			function openDetailPane(ele)
			{
				$('#TweetPaneForm').slideUp();
				//$("#ViewDetails").hide();
				//$('#PlayerView').slideDown();
				 $('#PlayerViewContent').slideDown();
				$('#TweetArrow').show();
				$('#TweetDownArrow').hide();
				$('#TweetFormPaneHeading').html("tweet a video / audio / picture status");
          	    $('#StatusId').html("");
          	    $('#TextValue').html('');
          	 
          	    var html = '<textarea id="text" name="text" class="text_twit" title="Watch my tweet at #twiteract" ></textarea>';
          	  $('#TextValue').html(html);
          	 
          	  $('#text').inputTextToggle();
          	  $('#tweetPost').removeClass('updateReply');
          	  $('#tweetPost').addClass('update');

          	  $('#tweetPost').html('Update');
          	  
          	  //$('#PlayerViewContent').hide();
          	  $('#Cancel').hide();
          	  
          	  
          	 /**
   			 * Assign event on tweetPost button for posting tweet
   			 */
   			$('#text').keyup(
   					function()
   					{
   						updateCharsNum('#text',110,'#CharLimit');
   					}
   				);
   			
			}
			
			
			   
			   function openNewTweetForm()
			   {
				   //$("#ViewDetails").slideDown();
				   //$('#PlayerView').hide();
				   
				   $('#TweetHead').show();
				  $('#ReplyHead').hide();
				  $('#TweetFormPaneHeading').html("tweet a video / audio / picture status");
             	  $('#StatusId').html("");
             	  $('#TextValue').html('');
             	  var html = '<textarea id="text" name="text" class="text_twit" title="Watch my tweet at #twiteract" ></textarea>';
             	  $('#TextValue').html(html);
             	 
             	  $('#text').inputTextToggle();
             	  $('#tweetPost').removeClass('updateReply');
             	  $('#tweetPost').addClass('update');

             	  $('#tweetPost').html('Update');
             	  
             	  $('#PlayerViewContent').hide();
             	  $('#Cancel').hide();
             	  $('#TweetArrow').hide();
             	  $('#TweetDownArrow').show();
             	  $('#tweetPost').show();
 				  $('#tweetWebcamPosting').replaceWith('<span id="tweetWebcamPost" name="tweetWebcamPost" class="update">Update</span>');
 				  $('#tweetWebcamPost').hide()
             	  $('#WebcamArea').hide();
             	  $('#WebCamMsg').hide();
             	  $('#FileAndWebcam').slideDown();
             	  $('#TweetPaneForm').slideDown();
             	 
             	 /**
  				 * Assign event on tweetPost button for posting tweet
  				 */
  				$('#tweetPost').one("click",
  						function(event)
  						{
  							loginAndPostTweet('#tweetPost');
  							event.stopImmediatePropagation();
  						}
  					);
  				
             	 /**
      			 * Assign event on tweetPost button for posting tweet
      			 */
      			$('#text').keyup(
      					function()
      					{
      						updateCharsNum('#text',110,'#CharLimit');
      					}
      				);
      			
   				  
             }
			  
				
				function openReplyForm(ele,statusId,finalTweetMsg)
				{
					
					if($.cookie('Username') == null)
					{
						alert("Please login to Reply.");
					}
					else 
					{
						 var tweetuser = $("#FromUser").val();
			        	 
		                  if(tweetuser != $.cookie('Username'))	        	
			         		{
							   
		                	  // $("#ViewDetails").slideDown();
		  					   //$('#PlayerView').slideUp(); 
		  					  $('#TweetHead').hide();
		  					  $('#ReplyHead').show();
		                	  $('#ReplyFormPaneHeading').html("reply to "+finalTweetMsg);
		                	  var textValue = "@"+tweetuser;
		                	  var statusValue  = '<input id="in_reply_to_status_id" name="in_reply_to_status_id" type="hidden" value="'+statusId+'"/>';
		                	  $('#StatusId').html(statusValue);
		                	  $('#TextValue').html('');
		                	  var html = '<textarea id="text" name="text" class="text_twit" title="Reply to tweet" >'+textValue+'</textarea>';
		                	  $('#TextValue').html(html);
		                	 
		                	  
		                	  $('#tweetPost').removeClass('update');
		                	  $('#tweetPost').addClass('updateReply');

		                	  $('#tweetPost').html('Reply');
		                	  $('#PlayerViewContent').hide();
		                	  $('#Cancel').show();
		                	  $('#TweetArrow').hide();
		                	  $('#TweetDownArrow').show();
		                	  $('#tweetPost').show();
		     				  $('#tweetWebcamPosting').replaceWith('<span id="tweetWebcamPost" name="tweetWebcamPost" class="update">Update</span>');
		     				  $('#tweetWebcamPost').hide()
		                 	  $('#WebcamArea').hide();
		                 	  $('#WebCamMsg').hide();
		                 	  $('#FileAndWebcam').slideDown();
		                 	  $('#TweetPaneForm').slideDown();
		                 	 
		                 	 /**
		      				 * Assign event on tweetPost button for posting tweet
		      				 */
		      				$('#tweetPost').one("click",
		      						function(event)
		      						{
		      							loginAndPostTweet('#tweetPost');
		      							event.stopImmediatePropagation();
		      						}
		      					);
		      				
		      				/**
		          			 * Assign event on tweetPost button for posting tweet
		          			 */
		          			$('#text').keyup(
		          					function()
		          					{
		          						updateCharsNum('#text',110,'#CharLimit');
		          					}
		          				);
		          			
		      				
		                	  $('#TweetPaneForm').show("slow");
		      				  
		                	  $('#Cancel').click(
		          					function()
		        					{
		        			
		        						
		        						cancelReply();
		        					}
		        				);
		                	}
		                  else
		                  {
		                	  alert("This tweet belongs to you, so you can't Reply !");
		                  }
					}
				}
				
				function cancelReply()
				{
					
              	   // $('#TweetPaneForm').hide();
					
					openNewTweetForm();
              	    //$('#PlayerViewContent').show("slow");
				}
				
			var pconf={
					  widgetTitle: 'TwiterAct', 
					  useFacebookMystuff: 'false', 
					  defaultContent: 'TextAreaID', 
					  UIConfig: '<config baseTheme="v2"><display showEmail="true" showBookmark="true"></display></config>',
					  emailSubject : "$sender$ has shared this TwiterAct Tweets with you" ,
					  emailBody : ""	  
					};
					
			
				
					function getShareMessage(data)
					{
						var url = rmtUrl+""+data.id;
						
						var tweetMsg = new String();
						tweetMsg = data.textTweet;
						
						var tweetMsgArr = new Array();
						tweetMsgArr = tweetMsg.split(" ");
						
						var tweetHref = new String();
						var newTweetMessage = new String();
						var arrLen = tweetMsgArr.length;
						
						for (var j = 0; j < arrLen; j++)
						{
							if(tweetMsgArr[j].indexOf('http://') != -1)
							{
								tweetHref = tweetMsgArr[j];
								//newTweetMessage += '<a href="'+tweetHref+'" >'+tweetHref+'</a>'+' ';
							}
							else
								newTweetMessage += tweetMsgArr[j] + ' ';
						}
						
						var finalTweetMsg = showLines(80, newTweetMessage);
						
						
						var shareHtml = "Hi," +
					    				"<br /> <br />" +
					    				"$sender$ wants to share this TwiterAct Tweets with you. Watch <a href='"+url+"'>'"+finalTweetMsg+			    				
					    				"'</a>"+
					    				"<br /> <br />" +
					    				"$sender$ wanted to say - "+
					    				"<br />" +
					    				"$userMsg$" +
					    				"<br /> <br /> " +
					    				"Thanks , <br />"+
					    				"<a href='"+host+"'>Twiteract.com</a>";
						
						pconf.emailBody = shareHtml;	
						
						// Initialize the gigya Component
						Wildfire.initPost("768551", 'EmbedGigya', 400, 135, pconf);	
					}
		
					
					
			/**
		     *  Method for re tweet post
		     */
		     function reTweetCall(ele,result){
		         
		         var username = $.cookie('Username');
			         if(username != null)
			         {   
			        	 var tweetuser = $("#FromUser").val();
			        	 
							         var id = result.id;
						
							         $.ajaxSetup({
								        	beforeSend: function(xhr) 
							        			{
													xhr.setRequestHeader("Accept", "text/javascript");
													xhr.setRequestHeader("Authorization",  $.cookie('twitterAuthorization'));
													xhr.setRequestHeader("twiteract-api-access-token", Base64.encode("umundo"));
												}
										});
										
							         $(ele).replaceWith('<span id="retweeting"><img src="'+host+'/images/blue_loading.gif" />Re-Tweeting</span>');
							    	 $.post(host+'/api/statuses/retweet.json', {richMediaTweetId:id},
							    	    	 function(data){
										    	    if(data.result != null)
										    	    {
											    	    
											    	    $("#retweeting").replaceWith('<span id="Retwit" >Re-Tweet</span>');
											    	    $('#ErrorMsg').slideUp();
														$('#SuccessMessage').html("Media re-tweeted successfully.");
														$('#SuccessMessage').slideDown();
														window.scrollTo(0,50);
														startTimer();
											    	    //alert("Media re-tweeted successfully.");
											    	    getFriendsTimeline();
											    	    $("#Retwit").bind("click", function()
										    					{
											    	    			reTweetCall('#Retwit');
										    					}
										    				);
										    	    }
										    	    else
										    	    {
											    	    //alert(data.error.errorMessage);
											    	    $('#SuccessMessage').slideUp();
														$('#ErrorMsg').html(data.error.errorMessage);
														$('#ErrorMsg').slideDown();
														window.scrollTo(0,50);
														startTimer();
										    	    }
							    	 		},"json" );	      
			         		
			         	
				    }
			      else
			      {
			             alert("Please login to Re-Tweet.");
			      }
		    	} 
			/**
			 * Assign onclick event on login button 
			 */
			$('#Login').click(
				function()
				{
					
					login('#Login');
				}
			);
			
			
			/**
			 * Assign onclick event on webcam capture button 
			 */
			$('#RecordFromWebcam').click(
				function()
				{
					
					openWebcam("#RecordFromWebcam");
				}
			);
			/**
			 * Assign onclick event on cancel webcam link
			 */
			$('#WebcamCancel').click(
					function()
					{
						cancelWebcam('#WebcamCancel');
					}
				);
			
			/**
			 * Assign event on tweetPost button for posting tweet
			 */
			$('#tweetPost').one("click",
					function(event)
					{
						loginAndPostTweet('#tweetPost');
						event.stopImmediatePropagation();
					}
				);
			
			
		   /**
		    * Method fro opening webcam
		    */
			function openWebcam(ele){
				
				if($.cookie('Username') == null)
				{
					alert('Please login to use webcam.');
					
				}
				else
				{
					
				var videoPubUrlAndLogin = videoPublishUrl+$.cookie('Username');
				
				$('#FileAndWebcam').slideUp();
				var webcamHtml = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"  id="MediaCapture"  width="400" height="330" codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab"> <param name="FlashVars" value="&imagePublishUrl='+apiHost+'/api/multipartUpload&videoPublishUrl='+videoPubUrlAndLogin+'"/><param name="movie" value= "'+host+'/images/MediaCapture.swf" /><param name="quality" value="high" /> <param name="bgcolor" value="#CCCCCC" /> <param name="allowScriptAccess" value="always" /> <param name="wmode" value="window" /><param name = "allowFullScreen" value = "true"><embed id="MediaCapture" src="'+host+'/images/MediaCapture.swf" base="'+host+'/images/" quality="high" flashvars="&imagePublishUrl='+apiHost+'/api/multipartUpload&videoPublishUrl='+videoPubUrlAndLogin+'" swliveconnect="true" wmode="window" scale="noscale" bgcolor="#CCCCCC" width="400" height="330" name="umundoPlayer" align="middle" allowScriptAccess="sameDomain" allowFullScreen="true" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>';
				
				$('#WebCam').html(webcamHtml);
				$('#WebcamArea').slideDown();
				
				$('#tweetPost').hide();
				$('#tweetWebcamPost').show();
				// get default value of text
				var defaultText = $('#text').val();
				
				//get index of @ in text area
				var indexforAt = defaultText.indexOf("@");
				
				//if text contains @ in the text area it means its reply option so dnt change text to default text otherwise chage it.
				if(indexforAt != -1)
				{	
					$('#tweetWebcamPost').html("Reply")
				
				}
				/**
				 * Assign event on tweetPost button for posting tweet
				 */
				$('#tweetWebcamPost').click(
						function()
						{
							loginAndUpdateTweet('#tweetWebcamPost');
						}
					);
				}
				
			}
			
			/**
			 * Method for canceling webcam
			 */
			function cancelWebcam(ele)
			{
				//$('#FileAndWebcam').slideDown();
				//$('#WebcamArea').slideUp();
				
				restoreTwitPane();
			}
			
			function restoreTwitPane()
			{
				$('#WebcamArea').hide();
				$('#WebCamMsg').hide();
				$('#FileAndWebcam').slideDown();
				$('#WebCam').html("");
				//$('#text').val("");
				$('#tweetPost').show();
				$('#tweetWebcamPosting').replaceWith('<span id="tweetWebcamPost" name="tweetWebcamPost" class="update">Update</span>');
				$('#tweetWebcamPost').hide()
				
				// get default value of text
				var defaultText = $('#text').val();
				
				//get index of @ in text area
				var indexforAt = defaultText.indexOf("@");
				
				//if text contains @ in the text area it means its reply option so dnt change text to default text otherwise chage it.
				if(indexforAt == -1)
				{	
					$('#TextValue').html('');
	             	  
					var html = '<textarea id="text" name="text" class="text_twit" title="Watch my tweet at #twiteract" ></textarea>';
	             	$('#TextValue').html(html);
				}
				
             	$('#text').inputTextToggle();
             	  
                $("#text").removeAttr('disabled');
                
                $("#CharLimit").html("max 110 chars.");
				/**
				 * Assign event on tweetPost button for posting tweet
				 */
				$('#tweetPost').one("click",
						function(event)
						{
							loginAndPostTweet('#tweetPost');
							event.stopImmediatePropagation();
						}
					);
				
				/**
      			 * Assign event on tweetPost button for posting tweet
      			 */
      			$('#text').keyup(
      					function()
      					{
      						updateCharsNum('#text',110,'#CharLimit');
      					}
      				);
      			
				
			}
			var fromTweet = false;
			
			function loginAndUpdateTweet(ele)
			{
				if(WebcamCapture.mediaId != "")
				{	
				
					postWebcamTweet();
				}
				else
				{
					alert("Please stop your webcam to update status");
				}
				
			}
			
			var Htmltags				= ["<a","<img","<embed","<center","<html","<head","<body"];
			var angleBrackets			= "<" ;
			
			
			function postWebcamTweet(){
				
				var tweetText = $("#text").val();
				
				if(tweetText.length > 0 && tweetText !="Watch my tweet at #twiteract")
				{	
					/* Check for the html tags in the comment text ...*/
					for(var i=0; i<= Htmltags.length ; i++)
					{
						tweetText = tweetText.toLowerCase();
						var index = tweetText.indexOf(Htmltags[i]);
						/* if theres html tag */
						if(index != -1)
						{
							alert("Caught You!!Our super intelligent app has caught you red handed putting html code in the text.Remove it dude!");
							

							return false;
						}
					}
	
					var angularTagsIndex = tweetText.indexOf(angleBrackets);
					if(angularTagsIndex != -1)
					{
						alert("Please Remove the < or > Characters! The App does not like them!");
						
						return false;
					}

				}
				
				if(tweetText =="Watch my tweet at #twiteract")
				{
					tweetText = "";
				}
				
				$('#tweetWebcamPost').replaceWith('<span id="tweetWebcamPosting" name="tweetWebcamPosting" ><img src="'+host+'/images/wait16trans.gif" /><b>updating status</b></span>');
				
				$("#text").attr('disabled', 'disabled');
				
				
				$.ajaxSetup({
		        	beforeSend: function(xhr) 
	        			{
							xhr.setRequestHeader("Accept", "text/javascript");
							xhr.setRequestHeader("Authorization",  $.cookie('twitterAuthorization'));
							xhr.setRequestHeader("twiteract-api-access-token", Base64.encode("umundo"));
						}
				});
				
	        
	    	 $.post(host+'/api/statuses/update.json', {mediaId:WebcamCapture.mediaId,text:tweetText},
	    	    	 function(data){
				    	    if(data.result != null)
				    	    {
					    	    
					    	    
					    	    //alert("Media tweeted successfully.");
					    	    $('#ErrorMsg').slideUp();
								$('#SuccessMessage').html("Media tweeted successfully.");
								$('#SuccessMessage').slideDown();
								window.scrollTo(0,50);
								startTimer();
					    	    openNewTweetForm();
					    	    //restoreTwitPane();
					    	    getFriendsTimeline();
					    	    
					    	    
				    	    }
				    	    else
				    	    {
				    	    	$('#tweetWebcamPosting').replaceWith('<span id="tweetWebcamPost" name="tweetWebcamPost" class="update" style="display:block">Update</span>');
				    	    	
				    	    	/**
								 * Assign event on tweetPost button for posting tweet
								 */
								$('#tweetWebcamPost').click(
										function()
										{
											loginAndUpdateTweet('#tweetWebcamPost');
										}
									);
									
									$('#SuccessMessage').slideUp();
									$('#ErrorMsg').html(data.error.errorMessage);
									$('#ErrorMsg').slideDown();
									window.scrollTo(0,50);
									startTimer();
					    	    //alert(data.error.errorMessage);
				    	    }
	    	 		},"json" );	
	    	 
	    	 
	         
			}
			/**
			 * Method for login user from tweet form
			 */
			function loginAndPostTweet(ele)
			{
				var username = $('#headerUsername').val();
				var password = $('#headerPassword').val();
				
				
				
				if($.cookie('Username') == null)
				{
					alert('Please login to update your status.');
					
				}
				else
				{
					postTweet();
				}
			}
			
			
			/**
			 * Method for posting tweet
			 */
			function postTweet()
			{
				var fileValue = $("#file").val();
				
				var tweetText	=	$("#text").val();
				
				
				
				if(tweetText.length > 0 && tweetText !="Watch my tweet at #twiteract")
				{	
					/* Check for the html tags in the comment text ...*/
					for(var i=0; i<= Htmltags.length ; i++)
					{
						tweetText = tweetText.toLowerCase();
						var index = tweetText.indexOf(Htmltags[i]);
						/* if theres html tag */
						if(index != -1)
						{
							alert("Caught You!!Our super intelligent app has caught you red handed putting html code in the text.Remove it dude!");
							

							return false;
						}
					}
	
					var angularTagsIndex = tweetText.indexOf(angleBrackets);
					if(angularTagsIndex != -1)
					{
						alert("Please Remove the < or > Characters! The App does not like them!");
						
						return false;
					}

				}		
				
				if(fileValue != "" || fileValue.length > 0)
				{		
					
					$('#tweetPost').replaceWith('<img src="'+host+'/images/wait16trans.gif" /><b>updating status</b>');
					
					
					
					$('#TweetForm').submit();
					
					$("#text").attr('disabled', 'disabled');
					$("#file").attr('disabled', 'disabled');
					$("#RecordFromWebcam").unbind('click');
					$("#RecordFromWebcam").addClass("DisabledRecordFromWebcam");
					
					var html = '<img src="'+host+'/images/record_webcam_disabled.gif" title="Record from webcam" />  or'; 
					$("#RecordFromWebcam").html(html);
					setTimeout('queryStatus()', 10);
				}
				else
				{
					alert("Please choose media file from your computer.");
					return;
				}
			}
			
			
			function postReplyTweet()
			{
				var fileValue = $("#file").val();
				
				var tweetText	=	$("#text").val();
				
				if(tweetText.length > 0)
				{	
					/* Check for the html tags in the comment text ...*/
					for(var i=0; i<= Htmltags.length ; i++)
					{
						tweetText = tweetText.toLowerCase();
						var index = tweetText.indexOf(Htmltags[i]);
						/* if theres html tag */
						if(index != -1)
						{
							alert("Caught You!!Our super intelligent app has caught you red handed putting html code in the comments.Remove it dude!");
							return ;
						}
					}
	
					var angularTagsIndex = tweetText.indexOf(angleBrackets);
					if(angularTagsIndex != -1)
					{
						alert("Please Remove the < or > Characters! The App does not like them!");
						return ;
					}

				}		
				else if(fileValue != "" || fileValue.length > 0)
				{		
					$('#ReplyForm').submit();
					
					$('#tweetPost').replaceWith('<span id="login" name="login" ><img src="'+host+'/images/wait16trans.gif" /><b>updating status</b></span>');
					//setTimeout('queryStatus()', 10);
				}
				else
				{
					alert("Please choose media file from your computer.");
					return;
				}
				
				
				//setTimeout('queryStatus()', 10);
			}
			/**
			 * Method for handling enter key event for sign/login event 
			 */
			
			$("input[name='headerUsername']").keyup(
				function(e) {
					e = e || window.event;
					var key = e.which || e.keyCode;
					if(key == 13) {
						login('#Login');
					}
				}
			);
			
			/**
			 * Method for handling enter key event for sign/login event 
			 */
			$("input[name='headerPassword']").keyup(
					function(e) {
						e = e || window.event;
						var key = e.which || e.keyCode;
						if(key == 13) {
							login('#Login');
						}
					}
				);
			
			/**
			 * Method for login from header login form
			 */
			function login(ele)
			{
				$.cookie('callBackUrl', null,{path:"/"});
				
				$.cookie('callBackUrl', host,{path:"/"});
				
				window.location.href = apiHost+"/api/web/authorize";
				
				
				//Take params			
				/*var username = $('#headerUsername').val();
				var password = $('#headerPassword').val();
				
				if(username != "twitter username")
				{	
					var spaceChack = username.indexOf(" ");
					
					
					if(spaceChack != -1)
					{
						alert("Please Remove the space from Username!");
						return ;
					}
				}
				
				if (username == null || username == '' || username == "twitter username") {
					alert('Please provide your Twitter Username.');
				}
				else if (password == null || password == '') 
				{
					alert('Please provide your Twitter Password.');
				}
				else 
				{
					$(ele).replaceWith('<span id="login" name="login" ><img src="'+host+'/images/wait16trans.gif" /><b>authenticating</b></span>');
					var encodedAuthorization = Base64.encode(username+":"+password);
	
					authenticate(encodedAuthorization,password);				
				}*/	
			}
			
			/**
			 * method for logout
			 */
			function logout(ele)
			{						
				$.cookie('twitterAuthorization', null,{path:"/"});
				$.cookie('Username', null,{path:"/"});
		  		$.cookie('ProfileImage', null,{path:"/"});
		  		$.cookie('callBackUrl', null,{path:"/"});
		  		//$.cookie('Status', null);
				$('#authroization').val(null);
				
				$.cookie('Bgimage',null,{path:"/"});
				$.cookie('Bgcolor',null,{path:"/"});
				$.cookie('Repeat',null,{path:"/"});
				$.cookie('SuccessMsg','false');
				window.location.href = host;
				

			}
			/**
			 * method for opening user page
			 */
			function gotoUserPage(){
				
				var username = $.cookie('Username');
				
				window.location.href=userUrl+""+username;
			}
			
			/**
			 * Method for rendering all logged in forms means welcome pane for logged in user
			 */
			function showWelcomePane()
			{
				var username = $.cookie('Username');
				var profileImage = $.cookie('ProfileImage');
				//var status = $.cookie('Status');
				var wrappedStatus = showLines(90, status);
				var bgimage = $.cookie('Bgimage');
				var bgcolor = $.cookie('Bgcolor');
				var repeat = $.cookie('Repeat');
				
				/*if(repeat == "true")
				{
				 
					$("body").css("background", "url('" + bgimage + "') #"+bgcolor+" repeat fixed left top");
				}
				else
				{
					$("body").css("background", "url('" + bgimage + "') #"+bgcolor+" no-repeat fixed left top");
				}*/
				 
				 
				var userPaneHtml = '';
				
				//var my_name = '<h1>Welcome</h1> <a href="http://twitter.com/'+username+'" target="_blank">@'+username+'</a>';
				var my_name = 'Welcome <a href="http://twitter.com/'+username+'" target="_blank">@'+username+'</a>';
				var my_avatar = '<img src="'+profileImage+'" class="user_image" width="46" height="46"/>';
				
				$('.my_avatar').html(my_avatar);
				$('.my_name').html(my_name);
				
				
				
				$('#Header_login').hide();
				
				$('#Header_user').show();
				
				
				
				
				//$('#WelcomePane').slideDown();
				//$("#ProfileImage").html(my_avatar);
				//$("#ProfileName").html(my_name);
				//$('#TweetPane').slideDown();
				
				//$('#UserPane').slideUp();
				
				$('#authorization').val($.cookie('twitterAuthorization'));
				
				$('#Home').bind("click",function(){
					gotoHome("friends");}
				);
				$('#MyTweet').bind("click", function(){
					
					gotoUserPage();
					});
				$('#PublicTweet').bind("click", function(){
					
					gotoHome("public");
					});
				
				$('#logout').bind("click", function(){logout('#Login');});
				
				//window.location.href = host;
				
				
				/*$('#tweetPost').click(
						function(event)
						{
							loginAndPostTweet('#tweetPost');
							event.stopImmediatePropagation();
						}
					);
				
				$.ajaxSetup({
		        	beforeSend: function(xhr) 
	        			{
							xhr.setRequestHeader("Accept", "text/javascript");
							xhr.setRequestHeader("Authorization",  $.cookie('twitterAuthorization'));
							xhr.setRequestHeader("twiteract-api-access-token", Base64.encode("umundo"));
						}
				});
				
				// Show the wait message
				$('#TimelineName').html("<span id='TimeLine'>Friends</span> Tweets");
				
				$('#Tweets').html('');
				$('#Tweets').html('<center><br /><img src="'+host+'/images/wait30trans.gif" /> <h1>fetching your friends tweets</h1></center>');
				
				
				// Get the Friends Timeline
				$.getJSON(
						host+'/api/statuses/friends_timeline.json?profile=web',
				        function(data)
				        {
				        	if (!data.error) 
							{   
				        		
								showTweetTimeline(data.result);
								
								
							}
							else
							{
								//alert(data.error.errorMessage);
								$('#SuccessMessage').slideUp();
								$('#ErrorMsg').html(data.error.errorMessage);
								$('#ErrorMsg').slideDown();
								window.scrollTo(0,50);
								startTimer();
							}
								
				        }
		        );
				
				
				if(resultMsg.length >0 || resultMsg != "")
				{	
				  // alert(resultMsg);
					$('#ErrorMsg').slideUp();
					$('#SuccessMessage').html(resultMsg);
					$('#SuccessMessage').slideDown();
					window.scrollTo(0,50);
					startTimer();
				}
				else if(errorMsg.length > 0 || errorMsg != "")
				{
					$('#SuccessMessage').slideUp();
					$('#ErrorMsg').html(errorMsg);
					$('#ErrorMsg').slideDown();
					window.scrollTo(0,50);
					startTimer();
					//alert(errorMsg);
				}	
				*/
			
			}		
			
			/**
			 * Method for getting twiteract user authorization from cookie
			 */
			function getAuthorization()
			{
				return $.cookie('twitterAuthorization');
			}
			
			
						           
			/**
			 * Assign event on tweetPost button for posting tweet
			 */
			$('#text').keyup(
					function()
					{
						updateCharsNum('#text',110,'#CharLimit');
					}
				);
			
			/**
			 * Method for checking textarea char length
			 */
			function updateCharsNum(o, maxlen, state) {
				
				if (!maxlen) {
					maxlen = 110;
				}
				var message = $("#text").val();
				var message_len = message.length;
				//
				var left = maxlen - message_len;
				$(state).html(left + " characters left");
				var disabled = false;
				if (message_len > maxlen) {
					$(state).css({"color":"#ff0000"});
					disabled = true;
				} else {
					$(state).css({"color":"#494949"});
				}
				
				
					if (disabled) {
						$("#tweetPost").addClass("update_disabled");
						$("#tweetPost").unbind('click');

					} else {
						$("#tweetPost").removeClass("update_disabled");
						$('#tweetPost').click(
								function(event)
								{
									loginAndPostTweet('#tweetPost');
									event.stopImmediatePropagation();
								}
							);
					}
				
			}
            
						
			/**
			 * Method for wrapping content as per div width and height
			 */
		    function showLines(max, text)
			{
		        max--;
		        text = "" + text;
		        var temp = "";
		        var chcount = 0;
		        for (var i = 0; i < text.length; i++) // for each character ... 
		        {
		            var ch = text.substring(i, i + 1); // first character
		            var ch2 = text.substring(i + 1, i + 2); // next character
		            if (ch == '\n') // if character is a hard return
		            {
		                temp += ch;
		                chcount = 1;
		            }
		            else 
					{
		                if (chcount == max) // line has max chacters on this line
		                {
		                    temp += '\n' + ch; // go to next line
		                    chcount = 1; // reset chcount
		                }
		                else // Not a newline or max characters ...
		                {
		                    temp += ch;
		                    chcount++; // so add 1 to chcount
		                }
		            }
		        }
		        return (temp); // sends value of temp back
		    }
		    
		    
		    
		    
		    }	
	);
