// 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) {
				   	
					$('#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('Bgimage',data.result.profileBackgroundImageUrl,{path:"/"});
								$.cookie('Repeat',data.result.profileBackgroundTile,{path:"/"});
								$.cookie('Bgcolor',data.result.profileBackgroundColor,{path:"/"});
								$.cookie('userid',data.result.id,{path:"/"});
								$.cookie('SuccessMsg','false',{path:"/"});
								$.cookie('CurrentState','friends',{path:"/"});
								$.cookie('user',data.result,{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');
				    					}
				    				);
				                
				                $("#headerUsername").removeAttr('disabled');
				                $("#headerPassword").removeAttr('disabled');
				                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();
				$('#comment_message').inputTextToggle();
				checkAuthorization();
				fetchPopularTweets();
				fetchPopularMembers();
				getTrendingTopics();
			}
			 /****************************************code for fetching popular tweets********************************************/
			   
			/**
			 * Method to convert html tags in to text
			 */
			function toText (myString){     
				htmlString = myString.split("<").join("&lt;");     
				htmlString = htmlString.split(">").join("&gt;");    
				htmlString = htmlString.split("\"").join("&quot;");    
				htmlString = htmlString.split("\'").join("&#39;");    
				return htmlString;
				}
			
			
			$('#ProductLogo').click(
					function(event)
					{
						//goToHomePage();
						$.cookie('CurrentState',null,{path:"/"});
						window.location.href = host;
					}
				);
			
			
			function goToHomePage()
			{
				var username = $.cookie('Username');
				
				
				
				//$.cookie('CurrentState',from,{path:"/"});
				
				
				
				/*if(username == null)
				{
					gotoHome("public");
					
				}
				else
				{
					gotoHome("friends");
				}*/
			}
			
			
		    /**
			 * Method for fetching most popular tweets
			 */
			function fetchPopularTweets()
			{
				$('#PopTweets').html('<center><br /><img src="'+staticHost+'/images/wait30trans.gif" /></center>');
				
				
				
				
				if(popularTweets.error == null)
				{
					
					showPopularTweetTimeline(popularTweets.result);
				}
				else
				{
					$('#SuccessMessage').slideUp();
					$('#ErrorMsg').html(popularTweets.error.errorMessage);
					$('#ErrorMsg').slideDown();
					window.scrollTo(0,50);
					startTimer();
				}
			}
			
			var currentPopularTimeline = "";
			var owner = "";
			var paramLinkForTweet = "";
			
			var popularTweetInfo = {
					thumbUrl : [],
					altText : [],
					paramLinkUrl : []
			};
			
			/**
			 * Method for rendering most popular tweets
			 */
			
			function showPopularTweetTimeline(data)
			{
				var length = data.length;
		    
				currentPopularTimeline = data;
		
				var popTweetHtml = "<div id='topSection'>";
				
                
				if(data.length > 0)
				{
					
					for(var i=0;i<length;i++)
					{
						var tempThumbUrl = data[i].webThumbUrl;
						
						if(!tempThumbUrl)
							tempThumbUrl = staticHost+'/images/default_thumbnail.png';
						
						
						popularTweetInfo.thumbUrl[i] = tempThumbUrl;
						
						
						
						var tempAltText = '<div class="ToolTip">"'+toText(data[i].textTweet)+'"<br />by - '+data[i].fromUser+'<br />'+data[i].views+' views</div>';
						
						popularTweetInfo.altText[i] = tempAltText;
						
						popularTweetInfo.paramLinkUrl[i] = rmtUrl+""+data[i].id;
						
					}
					
						popTweetHtml = popTweetHtml+"<div class='Medium' style='margin: 5px; float: left;'><a href='"+popularTweetInfo.paramLinkUrl[5]+"' class='PopLink' alt='"+popularTweetInfo.altText[5]+"'><img class='MediumImg' src='"+popularTweetInfo.thumbUrl[5]+"' /></a></div><div class='Medium' style='float: left; margin-top: 5px; margin-right: 5px; margin-bottom: 5px;'><a href='"+popularTweetInfo.paramLinkUrl[6]+"' class='PopLink' alt='"+popularTweetInfo.altText[6]+"'><img class='MediumImg' src='"+popularTweetInfo.thumbUrl[6]+"' /></a></div><div class='Medium' style='float: left; margin-top: 5px;'><a href='"+popularTweetInfo.paramLinkUrl[7]+"' class='PopLink' alt='"+popularTweetInfo.altText[7]+"'><img class='MediumImg' src='"+popularTweetInfo.thumbUrl[7]+"' /></a></div>";
						
						popTweetHtml = popTweetHtml+"<div class='Big' style='float: left; margin-right: 5px; margin-bottom: 5px; margin-left: 5px;'><a href='"+popularTweetInfo.paramLinkUrl[1]+"' class='PopLink' alt='"+popularTweetInfo.altText[1]+"'><img class='BigImg' src='"+popularTweetInfo.thumbUrl[1]+"' /></a></div><div class='Big' style='float: left; margin-bottom: 5px;'><a href='"+popularTweetInfo.paramLinkUrl[2]+"' class='PopLink' alt='"+popularTweetInfo.altText[2]+"'><img class='BigImg' src='"+popularTweetInfo.thumbUrl[2]+"' /></a></div>";
						
						popTweetHtml = popTweetHtml+"<div class='SmallContainer' style='float: left; margin-left: 5px; margin-right: 5px; margin-bottom: 5px;'><div class='Small' style='float: left; margin-right: 2px; margin-bottom: 2px;'><a href='"+popularTweetInfo.paramLinkUrl[11]+"' class='PopLink' alt='"+popularTweetInfo.altText[11]+"'><img class='SmallImg' src='"+popularTweetInfo.thumbUrl[11]+"' /></a></div><div class='Small' style='float: left;'><a href='"+popularTweetInfo.paramLinkUrl[12]+"' class='PopLink' alt='"+popularTweetInfo.altText[12]+"'><img class='SmallImg' src='"+popularTweetInfo.thumbUrl[12]+"' /></a></div><div class='Small' style='float: left; margin-right: 2px;'><a href='"+popularTweetInfo.paramLinkUrl[13]+"' class='PopLink' alt='"+popularTweetInfo.altText[13]+"'><img class='SmallImg' src='"+popularTweetInfo.thumbUrl[13]+"' /></a></div><div class='Small' style='float: left;'><a href='"+popularTweetInfo.paramLinkUrl[14]+"' class='PopLink' alt='"+popularTweetInfo.altText[14]+"'><img class='SmallImg' src='"+popularTweetInfo.thumbUrl[14]+"' /></a></div></div>";
						
						popTweetHtml = popTweetHtml+"<div class='Big' style='float: left; margin-bottom: 5px;'><a href='"+popularTweetInfo.paramLinkUrl[0]+"' class='PopLink' alt='"+popularTweetInfo.altText[0]+"'><img class='BigImg' src='"+popularTweetInfo.thumbUrl[0]+"' /></a></div>";
						
						popTweetHtml = popTweetHtml+"<div class='Medium' style='float: left; margin-left: 5px; margin-right: 5px; margin-bottom: 5px;'><a href='"+popularTweetInfo.paramLinkUrl[8]+"' class='PopLink' alt='"+popularTweetInfo.altText[8]+"'><img class='MediumImg' src='"+popularTweetInfo.thumbUrl[8]+"' /></a></div><div class='Medium' style='float: left; margin-right: 5px; margin-bottom: 5px;'><a href='"+popularTweetInfo.paramLinkUrl[9]+"' class='PopLink' alt='"+popularTweetInfo.altText[9]+"'><img class='MediumImg' src='"+popularTweetInfo.thumbUrl[9]+"' /></a></div><div class='Medium' style='float: left;'><a href='"+popularTweetInfo.paramLinkUrl[10]+"' class='PopLink' alt='"+popularTweetInfo.altText[10]+"'><img class='MediumImg' src='"+popularTweetInfo.thumbUrl[10]+"' /></a></div>";
						
						popTweetHtml = popTweetHtml+"<div class='Big' style='float: left; margin-left: 5px; margin-right: 5px;'><a href='"+popularTweetInfo.paramLinkUrl[3]+"' class='PopLink' alt='"+popularTweetInfo.altText[3]+"'><img class='BigImg' src='"+popularTweetInfo.thumbUrl[3]+"' /></a></div><div class='Big' style='float: left;'><a href='"+popularTweetInfo.paramLinkUrl[4]+"' class='PopLink' alt='"+popularTweetInfo.altText[4]+"'><img class='BigImg' src='"+popularTweetInfo.thumbUrl[4]+"' /></a></div>";
						
					
				}
				
				popTweetHtml = popTweetHtml+"</div>";
				
				
				
				
				$('#PopTweets').html('');						
				$('#PopTweets').html(popTweetHtml);
				
				// Define corners and opposites arrays
				var corners = [
				    'topMiddle'
				];
				var opposites = [
				   'bottomMiddle'
				];
				var i = 0;

				  $('a.PopLink')
				      .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");
								    });
			}
			
			
			
		    
		   
		    
		    /***************************************************************************************************/

             
			loadUp();
          
			/********************* Code for getting popular members ********************************************/
			
			
			
			
			
			 /**
			 * Method for fetching most popular members
			 */
			function fetchPopularMembers()
			{
				$('#PopMembers').html('<center><br /><img src="'+staticHost+'/images/wait30trans.gif" /></center>');
				
					
				if(popularMembers.error == null)
				{
					
					showPopularMembers(popularMembers.result);
				}
				else
				{
					$('#SuccessMessage').slideUp();
					$('#ErrorMsg').html(popularMembers.error.errorMessage);
					$('#ErrorMsg').slideDown();
					window.scrollTo(0,50);
					startTimer();
				}
				
			}
			
			
			function showPopularMembers(result){
				
				var memberLength = result.length;
				
				var memberHtml = "";
				for(var i=0;i<memberLength;i++)
				{
					var user = userUrl+""+result[i].screenName;
					
					
					var memDetails =  "<div style='font-family:georgia;width:100%;font-weight:normal;padding-top:3px;'>";
					
					if(result[i].name)
						memDetails = memDetails+"<span class='userInfo'><b>"+result[i].name+"</b></span><br />";
					else
						memDetails = memDetails+"<span class='userInfo'><b>"+result[i].screenName+"</b></span><br />";
					
					if(result[i].location)
						memDetails = memDetails+"<span class='userInfo'>Located in "+result[i].location+"</span><br />";
					
					if(result[i].description)
						memDetails = memDetails+"<span class='userInfo'>"+result[i].description+"</span><br />";
					
					memDetails = memDetails +"<div style='font-family:georgia;width:100%;font-weight:normal;padding-top:3px;'>";
					
					if(result[i].followersCount)
						memDetails = memDetails+"<span class='userInfoStats'>"+result[i].followersCount +"<br />Followers </span>";
					else
						memDetails = memDetails+"<span class='userInfoStats'> 0<br />Followers </span>";
					
					if(result[i].friendsCount)
						memDetails = memDetails+"<span class='userInfoStat'>"+result[i].friendsCount +" <br />Following </span>";
					else
						memDetails = memDetails+"<span class='userInfoStat'>0<br />Following </span>";
					
					
					
					var profileImage = staticHost+"/images/defaultImage.png";
					
					if(result[i].profileImageUrl)
						profileImage = result[i].profileImageUrl;
					
				   memberHtml = memberHtml+'<a alt="'+ memDetails +'" class="PopularMember" href="'+user+'"><img src="'+profileImage+'" /></a>';	
				}
				
				$("#PopMembers").html(memberHtml);
				
				
				// Define corners and opposites arrays
				var corners = [
				    'topMiddle'
				];
				var opposites = [
				   'bottomMiddle'
				];
				var i = 0;

				  $('a.PopularMember')
				      .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");
								    });
				  
				  
			}

			
		
			// Define corners and opposites arrays
			var corners = [
			    'topMiddle'
			];
			var opposites = [
			   'bottomMiddle'
			];
			var i = 0;

			  $('a.Feature')
			      .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()
			{
				
				
				if(authInfo.length > 0)
				{
					
										
					var authInfoJson = JSON.parse(authInfo);
					
					var authToken = authInfoJson.result.oauthToken;
					var oauthTokenSecret = authInfoJson.result.oauthTokenSecret;
					var oauthHeader = "Oauth token:"+authToken+",secret:"+oauthTokenSecret;
					var screenName = authInfoJson.result.screenName;
					var userId = authInfoJson.result.userId;
					var profileImage = authInfoJson.result.profileImageUrl;
					var userName = authInfoJson.result.userName;
					$.cookie('twitterAuthorization', oauthHeader,{path:"/"});
	          		$.cookie('Username', screenName,{path:"/"});
	          		$.cookie('ProfileImage', profileImage,{path:"/"});
	          		//$.cookie('Status', data.result.status.text);
					$('#authroization').val($.cookie('twitterAuthorization'));
					$('#user').val(screenName);
					$.cookie('userid',userId,{path:"/"});
					$.cookie('CurrentState','friends',{path:"/"});
					
				}
				var twitterAuthorization = $.cookie('twitterAuthorization');
				
				
				var successMsg = $.cookie('SuccessMsg');
				
				
				if((resultMsg.length >0 || resultMsg != "" ) && (successMsg == 'false'))
				{	
					$.cookie('SuccessMsg','true',{path:"/"});
				  
					$('#ErrorMsg').slideUp();
					$('#SuccessMessage').html(resultMsg);
					$('#SuccessMessage').slideDown();
					window.scrollTo(0,50);
					startTimer();
				}
				else if((errorMsg.length > 0 || errorMsg != "") && (successMsg == 'false'))
				{
					$.cookie('SuccessMsg','true',{path:"/"});
					$('#SuccessMessage').slideUp();
					$('#ErrorMsg').html(errorMsg);
					$('#ErrorMsg').slideDown();
					window.scrollTo(0,50);
					startTimer();
					
				}
				
				
				
				if(twitterAuthorization)
				{
					showWelcomePane();
					
				} 
				else
				{
						    
					$('#Header_login').show();
					
					$('#Header_user').hide();
					
					readyToFetchTimeline("public");
					
				
				}
			}
			
			
			
			 
				
			/**
			 * function for opening twwet form
			 */
			function openForm(ele)
			{
				//$("#TweetFormPaneHeading").removeClass("TweetFormPaneHeadingActive");
				//$("#TweetFormPaneHeading").addClass("TweetFormPaneHeading");
				
				
				openNewTweetForm();
           	   			
			}
			
			/**
			 * function for closing twwet form
			 */
			function closeForm(ele)
			{
				//$("#TweetFormPaneHeading").attr('cursor', 'pointer');
				//$("#TweetFormPaneHeading").removeClass("TweetFormPaneHeading");
				//$("#TweetFormPaneHeading").addClass("TweetFormPaneHeadingActive");
				
				
				openDetailPane(ele);
			}
			
			
			
			var currentTimeline = new Array();
			var fromMore = false;
			/**
			 * Method for getting public timeline of twiteract
			 */
			function getPublicTimeline()
			{
				$.cookie('CurrentState',"public",{path:"/"});
				
				
				// Show the wait message
				$('#TimeLine').html("Public");
				
				//$('#ShowMore').hide();
				
				//$('#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(
						apiHost+'/api/statuses/public_timeline.json?profile=web&page='+CurrentTweet.page,
				        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();
							}
				        }
		        );
				
				$("#RssFeed").show();
			}
			
			
			/**
			 * Method to get user own timeline from twiteract
			 */
			function getUserTimeline()
			{
				var username = $.cookie('Username');
				
				window.location.href=userUrl+""+username;
			}
			
			/**
			 * Method to get friends time of logged in user from twiteract
			 */
			function getFriendsTimeline()
			{
				$("#RssFeed").hide();
				// Show the wait message
				$('#TimeLine').html("Friends");
				
				if(fromMore == false)
				{
					$("#MainLoading").show();
					currentTimeline = new Array()
				}
				
				$.cookie('CurrentState',"friends",{path:"/"});
				
				$.ajaxSetup({
		        	beforeSend: function(xhr) 
	        			{
							xhr.setRequestHeader("Accept", "text/javascript");
							xhr.setRequestHeader("Authorization",  $.cookie('twitterAuthorization'));
							xhr.setRequestHeader("twiteract-api-access-token", Base64.encode("umundo"));
						}
				});
				
				$.getJSON(
						apiHost+'/api/statuses/friends_timeline.json?profile=web&page='+CurrentTweet.page,
				        function(data)
				        {
							
				        	if (!data.error) 
							{
								showTweetTimeline(data.result);
							}
							else
							{
								if(data.error.errorCode == 1121)
				                {
				                	//alert("Authentication failed. Your Twitter Username\/Password are incorrect.");
				                	var yesOrNo = confirm(data.error.errorMessage+" Please re-login with valid Username and Password.");
				                	if(yesOrNo)
				                	{
				                		logout();
				                	}
				                	else
				                	{
				                		 $('#SuccessMessage').slideUp();
											$('#ErrorMsg').html(data.error.errorMessage);
											$('#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();
				                }
								
								
							}
				        }
		        );
			}
			
			/**
			 * Method to get friends time of logged in user from twiteract
			 */
			function getCurrentUserTimeline()
			{
				var currentUser = $.cookie('CurrentUser');
				var title = '<span id="TimeLine">More</span> Tweets from '+currentUser;
				// Show the wait message
				$('#TimelineName').html(title);
				
				$('#Tweets').html('');
				$('#Tweets').html('<center><br /><img src="'+staticHost+'/images/wait30trans.gif" /><h1> fetching tweets </h1></center>');

				$.ajaxSetup({
		        	beforeSend: function(xhr) 
	        			{
							xhr.setRequestHeader("Accept", "text/javascript");
							//xhr.setRequestHeader("Authorization", "Basic "+$.cookie('twitterAuthorization'));
							xhr.setRequestHeader("twiteract-api-access-token", Base64.encode("umundo"));
						}
				});
				
				$.getJSON(
						apiHost+'/api/statuses/consumptionProfile/web/user_timeline/'+currentUser+'.json',
				        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 fromDetails = false;
			
			function showDetails(i,source){
				
				var currentRmtId = "";
				var currentUser = "";
				
				if(source != "fromPopular")
				{	
				var acutalId = i.split("ContentThumb")[1];
			    
				fromDetails = true;
			    
			    currentRmtId = currentTimeline[acutalId].id;
			    currentUser =  currentTimeline[acutalId].fromUser;
			    
				}
				else
				{
					var acutalId = i.split("PopContentThumb")[1];
				    
					fromDetails = true;
				    
				    currentRmtId = currentPopularTimeline[acutalId].id;
				    
				    currentUser =  currentPopularTimeline[acutalId].fromUser;
				}
				/**
				 * Log url 
				 */
				$.getJSON(
						apiHost+'/rmtanalytics/logview/'+currentRmtId,
				        function(finaldata)
				        {
							$.cookie('CurrentState',"currentUser",{path:"/"});
							$.cookie('CurrentUser',currentUser,{path:"/"});
							window.location.href=rmtUrl+""+currentRmtId;
				        }
					  );
							
			}
			
			/**
			 * Method for increase view of tweet
			 */
			function increaseView(id)
			{
				
				var rmtId = currentTimeline[id].id;
				
				/**
				 * Log url 
				 */
				$.getJSON(
						apiHost+'/rmtanalytics/logview/'+rmtId,
				        function(finaldata)
				        {
							var views = finaldata.result.views+" views";
							$("#view"+id).html(views);
				        }
					  );
			}
			
			
			
			
			/**
		     * Method to activate links in a tweet
		     * @param tweet
		     */
		    function activateInTweetLinks(tweet)
		    {
		        var str = tweet;

		        str = " " + str;
		    	str = str.replace(/(http:\/\/[^\s@]+[^\s@\.]+)/ig, '<a href="$1">$1</a>');
		     	str = str.replace(/(\s)#([^\s]*[^\s\.]+)/ig, '$1<a href="http://search.twitter.com/search?q=$2" target="_blank">#$2</a>');
		     	str = str.replace(/@(\w+)/ig, '<a href="'+userUrl+'$1">@$1</a>');
		    	return str;
		    }
		    

		   
				
			var start = 0;
			
			/**
			 * Method for rendering resulted timeline at frontend
			 */
			function showTweetTimeline(data)
			{
				//var html = '<ul id="Demo">';
				
				$("#MainLoading").hide();
				
				var html ="";
				
				var length = data.length;
		 		
				
		 		var upto = start + length;
		 		
		 		
		 		
		 		if(data.length > 0)
				{	
										
					for (var i = 0,j=start; i < length; j++,i++)
					{
						
						currentTimeline.push(data[i]);
						
						var date = new Date(data[i].createdAt);
						
						//var age = jQuery.timeago(date); 
						var age = relativeTime(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;
						
						
						finalTweetMsg = toText(tweetMsg);
						
						var finalTweet = activateInTweetLinks(finalTweetMsg);
						
						html += '<li id="Demo'+j+'" class="DemoLi">';
						//check weather tweet has 10 abusive votes then hide it and show msg
						if(data[i].abuse < 1)
						{
						
						html += '<table><tr>';
						
						
						
						var thumbUrl = staticHost+'/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 = staticHost+'/images/default_thumbnail.png';
						}
						
						var twitLink = staticHost+"/web/webwatch/"+data[i].id;
						
						var zoomUrl = staticHost+"/images/zoom_in_hover.png";
						var image = staticHost+"/images/image.png";
						var video = staticHost+"/images/video.png";
						var audio = staticHost+"/images/audio.png";
						var fav = staticHost+"/images/fav-icon_small.png";
						var favbig = staticHost+"/images/fav-icon_hover.png";	
						var pipe = staticHost+"/images/pipe.png";
						var reportAbuse = staticHost+"/images/report_abuse.png";
						
						var user = userUrl+""+data[i].fromUser;
							
						var paramLink = rmtUrl+""+data[i].id;
						
						html += '<td valign="top" id="Thumb">' ;
												
						html += '<a id="Thumb'+j+'" href="'+paramLink+'" class="ContentLink"><img class="ContentThumb" id="ContentThumb'+ j +'"  src="' + thumbUrl + '" alt="Watch - '+ finalTweetMsg +'" title="'+finalTweetMsg+'"/></a>' + 
						'</td>';
						
							if(data[i].sourceMediaType == "VIDEO")
							html += '<td style="margin: 0pt; float: left; width: 475px;"><table><tr><td valign="top" align="left" id="TextTweetMsg">'+finalTweet+'</td><td style="width:20px;float:left;"><img src="'+video+'"  style="vertical-align:middle;margin-top:3px;"/></td></tr><tr><td><div style="width:25px;float:left;" ><img id="ProfileThumb" src="'+data[i].profileImageUrl+'" /></div><div class="Age"><a href="'+user+'"  style="font-size:13px;font-family:arial;font-weight:bold;font-style:normal;">'+data[i].fromUser+'</a><br />'+age+'</div><div class="ViewsAndFavs"><span class="data" id="view'+j+'">'+data[i].views+' views</span><br /><span class="data"  id="Fav'+j+'">'+data[i].favourite+'&nbsp;<img src="'+fav+'" /></span><span id="Option'+j+'" class="Option" style="display:none"><a class="Favorite"  title="Favorite this tweet"><img id="Favorite'+j+'" src="' + favbig + '" /></a> <img src="' + pipe + '" /><a class="Abuse"  title="Report abusive"><img id="Abuse'+j+'" src="' + reportAbuse + '" /></a> </span></div></td></tr></table></td>';
							else if(data[i].sourceMediaType == "AUDIO")
							html += '<td  style="margin: 0pt; float: left; width: 475px;"><table><tr><td valign="top" align="left" id="TextTweetMsg">'+finalTweet+'</td><td style="width:20px;float:left;"><img src="'+audio+'" style="vertical-align:middle;margin-top:3px;"/></td></tr><tr><td><div style="width:25px;float:left;" ><img id="ProfileThumb" src="'+data[i].profileImageUrl+'" /></div><div class="Age"><a href="'+user+'"  style="font-size:13px;font-family:arial;font-weight:bold;font-style:normal;">'+data[i].fromUser+'</a><br />'+age+'</div><div class="ViewsAndFavs"><span class="data" id="view'+j+'">'+data[i].views+' views</span><br /><span class="data"  id="Fav'+j+'">'+data[i].favourite+'&nbsp;<img src="'+fav+'" /></span><span id="Option'+j+'" class="Option" style="display:none"><a class="Favorite"  title="Favorite this tweet"><img id="Favorite'+j+'" src="' + favbig + '" /></a> <img src="' + pipe + '" /><a class="Abuse"  title="Report abusive"><img id="Abuse'+j+'" src="' + reportAbuse + '" /></a></span></div></td></tr></table></td>';
							else if(data[i].mediaStatus == "HOSTED")
							html += '<td  style="margin: 0pt; float: left; width: 475px;"><table><tr><td valign="top" align="left" id="TextTweetMsg">'+finalTweet+'</td><td style="width:20px;float:left;"><img src="'+image+'"  style="vertical-align:middle;margin-top:3px;"/></td></tr><tr><td><div style="width:25px;float:left;" ><img id="ProfileThumb" src="'+data[i].profileImageUrl+'" /></div><div class="Age"><a href="'+user+'"  style="font-size:13px;font-family:arial;font-weight:bold;font-style:normal;">'+data[i].fromUser+'</a><br />'+age+'</div><div class="ViewsAndFavs"><span class="data" id="view'+j+'">'+data[i].views+' views</span><br /><span class="data"  id="Fav'+j+'">'+data[i].favourite+'&nbsp;<img src="'+fav+'" /></span><span id="Option'+j+'" class="Option" style="display:none"><a class="Favorite"   title="Favorite this tweet"><img id="Favorite'+j+'" src="' + favbig + '" /></a> <img src="' + pipe + '" /> <a href="' + data[i].fileUrl + '" title="Zoom In -'+finalTweetMsg+'" class="Zoom"><img id="Zoom'+j+'" src="' + zoomUrl + '"/></a> <img src="' + pipe + '" /><a class="Abuse"  title="Report abusive"><img id="Abuse'+j+'" src="' + reportAbuse + '" /></a></span></div></td></tr></table></td>';
							else
							html += '<td  style="margin: 0pt; float: left; width: 475px;"><table><tr><td valign="top" align="left" id="TextTweetMsg">'+finalTweet+'</td><td style="width:20px;float:left;"><img src="'+image+'"  style="vertical-align:middle;margin-top:3px;"/></td></tr><tr><td><div style="width:25px;float:left;" ><img id="ProfileThumb" src="'+data[i].profileImageUrl+'" /></div><div class="Age"><a href="'+user+'"  style="font-size:13px;font-family:arial;font-weight:bold;font-style:normal;">'+data[i].fromUser+'</a><br />'+age+'</div><div class="ViewsAndFavs"><span class="data" id="view'+j+'">'+data[i].views+' views</span><br /><span class="data"  id="Fav'+j+'">'+data[i].favourite+'&nbsp;<img src="'+fav+'" /></span><span id="Option'+j+'" class="Option" style="display:none"><a class="Favorite"   title="Favorite this tweet"><img id="Favorite'+j+'" src="' + favbig + '" /></a> <img src="' + pipe + '" /><a class="Abuse"  title="Report abusive"><img id="Abuse'+j+'" src="' + reportAbuse + '" /></a></span></div></td></tr></table></td>';
							
							html += '</tr></table>';
						}
						else
						{
							
							
							
							
							html = html+'<div id="AbuseDiv'+j+'" class="AbuseDiv" style="background-color:lightGrey;font-family:arial;padding:5px 5px 5px 10px;font-size:15px;display:block;">'+finalTweet+' <br />  <div style="width:100%;float:left;margin:5px 5px 5px 0px;" ><img id="ProfileThumb" src="'+data[i].profileImageUrl+'" />&nbsp;'+data[i].fromUser +'</div> <br /> Flagged as abusive tweet. click here to <a id="ShowAbuse'+j+'" class="ShowAbuse" style="cursor:pointer;">show</a> </div>';
							
							html += '<div id="AbuseContent'+j+'" style="display:none;"><table><tr>';
							
							
							
							var thumbUrl = staticHost+'/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 = staticHost+'/images/default_thumbnail.png';
							}
							
							var twitLink = host+"/web/webwatch/"+data[i].id;
							
							var zoomUrl = staticHost+"/images/zoom_in_hover.png";
							var image = staticHost+"/images/image.png";
							var video = staticHost+"/images/video.png";
							var audio = staticHost+"/images/audio.png";
							var fav = staticHost+"/images/fav-icon_small.png";
							var favbig = staticHost+"/images/fav-icon_hover.png";	
							var pipe = staticHost+"/images/pipe.png";
							var reportAbuse = staticHost+"/images/report_abuse.png";
							
							var user = userUrl+""+data[i].fromUser;
							var paramLink = rmtUrl+""+data[i].id;
							html = html+'<td valign="top" id="Thumb"><a id="Thumb'+j+'" href="'+paramLink+'" class="ContentLink"><img class="ContentThumb" id="ContentThumb'+ j +'"  src="' + thumbUrl + '" alt="Watch - '+ finalTweetMsg +'" title="'+finalTweetMsg+'"/></a></td>';
							
								if(data[i].sourceMediaType == "VIDEO")
									html = html+'<td style="margin: 0pt; float: left; width: 475px;"><table><tr><td valign="top" align="left" id="TextTweetMsg">'+finalTweet+'</td><td style="width:20px;float:left;"><img src="'+video+'"  style="vertical-align:middle;margin-top:3px;"/></td></tr><tr><td><div style="width:25px;float:left;" ><img id="ProfileThumb" src="'+data[i].profileImageUrl+'" /></div><div class="Age"><a href="'+user+'"  style="font-size:13px;font-family:arial;font-weight:bold;font-style:normal;">'+data[i].fromUser+'</a><br />'+age+'</div><div class="ViewsAndFavs"><span style="border-right:1px solid lightGrey;float:left;min-width:150px;"><span class="data" id="view'+j+'">'+data[i].views+' views</span><br /><span class="data"  id="Fav'+j+'">'+data[i].favourite+'&nbsp;<img src="'+fav+'" /></span></span><a id="HideAbuse'+j+'" class="HideAbuse" style="cursor:pointer;font-size:15px;padding-left:5px;" alt="click here to hide this abusive tweet" title="click here to hide this abusive tweet">hide</a><span id="Option'+j+'" class="Option" style="display:none"><a class="Favorite"  title="Favorite this tweet"><img id="Favorite'+j+'" src="' + favbig + '" /></a> <img src="' + pipe + '" /><a class="Abuse"  title="Report abusive"><img id="Abuse'+j+'" src="' + reportAbuse + '" /></a> </span></div></td></tr></table></td>';
								else if(data[i].sourceMediaType == "AUDIO")
									html = html+ '<td  style="margin: 0pt; float: left; width: 475px;"><table><tr><td valign="top" align="left" id="TextTweetMsg">'+finalTweet+'</td><td style="width:20px;float:left;"><img src="'+audio+'" style="vertical-align:middle;margin-top:3px;"/></td></tr><tr><td><div style="width:25px;float:left;" ><img id="ProfileThumb" src="'+data[i].profileImageUrl+'" /></div><div class="Age"><a href="'+user+'"  style="font-size:13px;font-family:arial;font-weight:bold;font-style:normal;">'+data[i].fromUser+'</a><br />'+age+'</div><div class="ViewsAndFavs"><span style="border-right:1px solid lightGrey;float:left;min-width:150px;"><span class="data" id="view'+j+'">'+data[i].views+' views</span><br /><span class="data"  id="Fav'+j+'">'+data[i].favourite+'&nbsp;<img src="'+fav+'" /></span></span><a id="HideAbuse'+j+'" class="HideAbuse" style="cursor:pointer;font-size:15px;padding-left:5px;" alt="click here to hide this abusive tweet" title="click here to hide this abusive tweet">hide</a><span id="Option'+j+'" class="Option" style="display:none"><a class="Favorite"  title="Favorite this tweet"><img id="Favorite'+j+'" src="' + favbig + '" /></a> <img src="' + pipe + '" /><a class="Abuse"  title="Report abusive"><img id="Abuse'+j+'" src="' + reportAbuse + '" /></a></span></div></td></tr></table></td>';
								else if(data[i].mediaStatus == "HOSTED")
									html = html+ '<td  style="margin: 0pt; float: left; width: 475px;"><table><tr><td valign="top" align="left" id="TextTweetMsg">'+finalTweet+'</td><td style="width:20px;float:left;"><img src="'+image+'"  style="vertical-align:middle;margin-top:3px;"/></td></tr><tr><td><div style="width:25px;float:left;" ><img id="ProfileThumb" src="'+data[i].profileImageUrl+'" /></div><div class="Age"><a href="'+user+'"  style="font-size:13px;font-family:arial;font-weight:bold;font-style:normal;">'+data[i].fromUser+'</a><br />'+age+'</div><div class="ViewsAndFavs"><span style="border-right:1px solid lightGrey;float:left;min-width:150px;"><span class="data" id="view'+j+'">'+data[i].views+' views</span><br /><span class="data"  id="Fav'+j+'">'+data[i].favourite+'&nbsp;<img src="'+fav+'" /></span></span><a id="HideAbuse'+j+'" class="HideAbuse" style="cursor:pointer;font-size:15px;padding-left:5px;" alt="click here to hide this abusive tweet" title="click here to hide this abusive tweet">hide</a><span id="Option'+j+'" class="Option" style="display:none"><a class="Favorite"   title="Favorite this tweet"><img id="Favorite'+j+'" src="' + favbig + '" /></a> <img src="' + pipe + '" /> <a href="' + data[i].fileUrl + '" title="Zoom In -'+finalTweetMsg+'" class="Zoom"><img id="Zoom'+j+'" src="' + zoomUrl + '"/></a> <img src="' + pipe + '" /><a class="Abuse"  title="Report abusive"><img id="Abuse'+j+'" src="' + reportAbuse + '" /></a></span></div></td></tr></table></td>';
								else
									html = html+ '<td  style="margin: 0pt; float: left; width: 475px;"><table><tr><td valign="top" align="left" id="TextTweetMsg">'+finalTweet+'</td><td style="width:20px;float:left;"><img src="'+image+'"  style="vertical-align:middle;margin-top:3px;"/></td></tr><tr><td><div style="width:25px;float:left;" ><img id="ProfileThumb" src="'+data[i].profileImageUrl+'" /></div><div class="Age"><a href="'+user+'"  style="font-size:13px;font-family:arial;font-weight:bold;font-style:normal;">'+data[i].fromUser+'</a><br />'+age+'</div><div class="ViewsAndFavs"><span style="border-right:1px solid lightGrey;float:left;min-width:150px;"><span class="data" id="view'+j+'">'+data[i].views+' views</span><br /><span class="data"  id="Fav'+j+'">'+data[i].favourite+'&nbsp;<img src="'+fav+'" /></span></span><a id="HideAbuse'+j+'" class="HideAbuse" style="cursor:pointer;font-size:15px;padding-left:5px;" alt="click here to hide this abusive tweet" title="click here to hide this abusive tweet">hide</a><span id="Option'+j+'" class="Option" style="display:none"><a class="Favorite"   title="Favorite this tweet"><img id="Favorite'+j+'" src="' + favbig + '" /></a> <img src="' + pipe + '" /><a class="Abuse"  title="Report abusive"><img id="Abuse'+j+'" src="' + reportAbuse + '" /></a></span></div></td></tr></table></td>';
								
						   
								html += '</tr></table></div>';
						    
						}
							
							
						html += '</li>';
						
						 
						
						
						
					}
					
					//html += '</ul>';	
					
					//$('#Tweets').html('');						
					//$('#Tweets').html(html);
					
					$('#Demo').append(html);
					
					// show more button visible
					if(currentTimeline.length >=20)
					$('#ShowMore').show();
					
					$('#MoreLoading').hide();
					$('#More').show();
					
					
					$('a.ShowAbuse').click(
							function(event)
							{
							  // showAbuseContent(event)
								var abuseId = this.id.split("ShowAbuse")[1];
								$("#AbuseDiv"+abuseId).hide();
								$("#AbuseContent"+abuseId).show();
								
							}
						);
					
					$('a.HideAbuse').click(
							function(event)
							{
							  // showAbuseContent(event)
								var abuseHideId = this.id.split("HideAbuse")[1];
								$("#AbuseContent"+abuseHideId).hide();
								$("#AbuseDiv"+abuseHideId).show();
								
								
							}
						);
					
					
					$('a.More').click(
							function(event)
							{
								getMoreTimeline();
								event.stopImmediatePropagation();
							}
						);
					/**
					 * Assign events on all thumbnails to view
					 
					$('a.ContentLink').click(
							function(e)
							{
								var id = e.target.id;
								showDetails(id);
							}
					);*/
					
					
					$('#Demo li').hover(
							
							function (ev) {
								$(this).css({"background":"rgb(246,246,246)"});
								var spanId = this.id.split("Demo")[1];
								$("#Option"+spanId).show();
								
							},
							function () {
								$(this).css({"background":"#ffffff"});
								var spanId = this.id.split("Demo")[1];
								$("#Option"+spanId).hide();
								
							}
					);
					
					
					/**
					 * Assign events on all thumbnails to view
					 */
					$('a.Favorite').click(
							function(event)
							{
								var divId = event.target.id;
								doFavorite(divId);
								event.stopImmediatePropagation();
							}
					);
					
					/**
					 * Assign events on all thumbnails to view
					 */
					$('a.Abuse').click(
							function(event)
							{
								var divId = event.target.id;
								doReportAbuse(divId);
								event.stopImmediatePropagation();
							}
					);
					
					
					/**
					 * 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 }
								);
						}
						});
					
					/**
					 * Assign event for increasing view count while zoom image
					 */
					$("a.Zoom").click(
						   function(event)
						   {
							   var zoomId = event.target.id;
							   increaseView(zoomId.split("Zoom")[1]);
							   event.stopImmediatePropagation();
						   }
					);
	
				}
				else
				{
					//alert("No tweets available.");
					if(currentTimeline.length <=0)
					{	
					$('#Tweets').html('');
					$('#Tweets').html('<center><br /><h1> No tweets available.</h1></center>');
					}
					else
					{
						$('#ShowMore').hide();
						$('#MoreLoading').hide();
						$('#More').show();
					}
				}
			}

			/**
			 * Method for getting timestamp according to time
			 */
			
			function relativeTime(pastTime)
			{
			    // Generate a JavaScript relative time for the tweets
			 
			    var origStamp = Date.parse(pastTime);
			    var curDate = new Date();
			    var currentStamp = curDate.getTime();
			    var difference = parseInt((currentStamp - origStamp)/1000);
			 
			    if(difference < 0) return "Just now";
			 
			    if(difference <= 5)          return "Just now";
			    if(difference <= 20)         return "Seconds ago";
			    if(difference <= 60)         return "A minute ago";
			    if(difference < 3600)        return parseInt(difference/60)+" minutes ago";
			    if(difference <= 1.5*3600)   return "One hour ago";
			    if(difference < 23.5*3600)   return Math.round(difference/3600)+" hours ago";
			    if(difference < 1.5*24*3600) return "One day ago";
			 
			    // If the tweet is older than a day, show an absolute date/time value;
			 
			   // Fri Nov 13 2009 17:29:52 GMT+0530 (India Standard Time)
			    var newTime = pastTime.toString();
			    var dateArr = newTime.split(' ');
			    
			    var actualTime = "";
			    var timeArr = dateArr[4].split(":");
			    
			    if(timeArr[0]>12)
			    {
			    	actualTime = timeArr[0]-12+":"+timeArr[1]+" PM ";
			    }
			    else
			    {
			    	actualTime = timeArr[0]+":"+timeArr[1]+" AM ";
			    }
			    
			       actualTime = actualTime+dateArr[1]+" "+dateArr[2];
			    
			    return actualTime;/*dateArr[4].replace(/\:\d+$/,'')+' '+dateArr[2]+' '+dateArr[1]+
			    (dateArr[3]!=curDate.getFullYear()?' '+dateArr[3]:'');*/
			}
			
			/**
			 * Method for getting more timeline
			 */
			function getMoreTimeline()
			{
				var current = $.cookie('CurrentState');
				
				fromMore = true;
				
				CurrentTweet.page = CurrentTweet.page + 1;
				
				start = start + 20;
				
				$('#MoreLoading').show();
				$('#More').hide();
				
				if(current == "friends")
					getFriendsTimeline();
				else if(current == "public")
				   getPublicTimeline();
			}
			
			
			/**
			 * Method for making current tweet as faavorite tweet
			 */
			function doFavorite(divId){
			
				// Check weather user is logged in or not
				//if not then give and alert msg for log in to make it favorite.
				if($.cookie('Username') == null)
				{
					alert('Please login to favorite this tweet!');
					
				}
				else
				{
					//extract div id from the divId
					var extractId = divId.split("Favorite")[1];
				    
					//get rich media id from curren timeline
					var richmediaId = currentTimeline[extractId].id;
				    
					//prepare ajax setup before making call
					$.ajaxSetup({
			        	beforeSend: function(xhr) 
		        			{
								xhr.setRequestHeader("Accept", "text/javascript");
								xhr.setRequestHeader("Authorization",  $.cookie('twitterAuthorization'));
								xhr.setRequestHeader("twiteract-api-access-token", Base64.encode("umundo"));
							}
					});
					
					// show loading image at current favorite image
					var loadingImg = staticHost+'/images/loading.gif';
					 $('#'+divId).attr("src",loadingImg);
					 
					/**
					 * Call to API method for making current tweet favorite
					 */
					 $.post(apiHost+'/api/favorites/create/'+richmediaId,
					        function(data)
					        {
						       
						 		var parsedData = JSON.parse(data);
						       
						       // Check weather result is null or not . if not null then update favorite count and restore previous image
								if(parsedData.result != null)
								{
									 var favImg = staticHost+"/images/fav-icon_hover.png";	
									 $('#'+divId).attr("src",favImg);
									
									 var fav = staticHost+"/images/fav-icon_small.png";
									 var newFavCount = parsedData.result.favorite+"&nbsp;<img src='"+fav+"' />";
									
									 $("#Fav"+extractId).html(newFavCount);
								}
								else
								{
									if(parsedData.error.errorCode == 1121)
					                {
					                	//alert("Authentication failed. Your Twitter Username\/Password are incorrect.");
					                	var yesOrNo = confirm(parsedData.error.errorMessage+" Please re-login with valid Username and Password.");
					                	if(yesOrNo)
					                	{
					                		logout();
					                	}
					                	else
					                	{
					                		$('#SuccessMessage').slideUp();
											$('#ErrorMsg').html(parsedData.error.errorMessage);
											$('#ErrorMsg').slideDown();
											window.scrollTo(0,50);
											
											var favImg = staticHost+"/images/fav-icon_hover.png";	
											$('#'+divId).attr("src",favImg);
											
											startTimer();
					                	}
					                	
					                }
					                else
					                {
					                	// else show error msg
										
									    $('#SuccessMessage').slideUp();
										$('#ErrorMsg').html(parsedData.error.errorMessage);
										$('#ErrorMsg').slideDown();
										window.scrollTo(0,50);
										
										var favImg = staticHost+"/images/fav-icon_hover.png";	
										$('#'+divId).attr("src",favImg);
										
										startTimer();
					                }
									
								}
					        },"json"
						  );
					
				}
			}
			
			
			/**
			 * Method for getting trending topics
			 */
			function getTrendingTopics()
			{
				var topics = "";
				$.twitter.trends(function(data)
						{
							for(var i=0;i<data.trends.length;i++)
							{
								
								var url = trendsUrl+""+escape(data.trends[i].name);
								
								
								topics = topics+"<span><a href='"+url+"'>"+data.trends[i].name+"</a></span>";
							}
							
					      $("#Topics").html(topics);
					
						},"json");
			}
			/**
			 * function for making current tweet as  report abuse tweet
			 */
			function doReportAbuse(divId)
			{
				// Check weather user is logged in or not
				//if not then give and alert msg for log in to make it favorite.
				if($.cookie('Username') == null)
				{
					alert('Please login to report this tweet as abusive!');
					
				}
				else
				{
					//extract div id from the divId
					var extractId = divId.split("Abuse")[1];
				    
					//get rich media id from curren timeline
					var richmediaId = currentTimeline[extractId].id;
				    
					//prepare ajax setup before making call
					$.ajaxSetup({
			        	beforeSend: function(xhr) 
		        			{
								xhr.setRequestHeader("Accept", "text/javascript");
								xhr.setRequestHeader("Authorization",  $.cookie('twitterAuthorization'));
								xhr.setRequestHeader("twiteract-api-access-token", Base64.encode("umundo"));
							}
					});
					
					// show loading image at current favorite image
					var loadingImg = staticHost+'/images/loading.gif';
					 $('#'+divId).attr("src",loadingImg);
					 
					/**
					 * Call to API method for making current tweet favorite
					 */
					 $.post(apiHost+'/api/abuse/create/'+richmediaId,
					        function(data)
					        {
						       
						 		var parsedData = JSON.parse(data);
						       
						       // Check weather result is null or not . if not null then update favorite count and restore previous image
								if(parsedData.result != null)
								{
									 var reportImg = staticHost+"/images/report_abuse.png";	
									 $('#'+divId).attr("src",reportImg);
									

									    $('#SuccessMessage').slideDown();
										$('#SuccessMessage').html("Thanks for your concern about the content of this tweet. It would be hidden on the timeline soon.");
										$('#ErrorMsg').slideUp();
										window.scrollTo(0,50);
										startTimer();
									 /*var fav = host+"/images/fav-icon_small.png";
									 var newFavCount = "<img src='"+fav+"' />&nbsp;"+parsedData.result.favorite;
									
									 $("#Fav"+extractId).html(newFavCount);*/
								}
								else
								{
									
									if(parsedData.error.errorCode == 1121)
					                {
					                	//alert("Authentication failed. Your Twitter Username\/Password are incorrect.");
					                	var yesOrNo = confirm(parsedData.error.errorMessage+" Please re-login with valid Username and Password.");
					                	if(yesOrNo)
					                	{
					                		logout();
					                	}
					                	
					                }
					                else
					                {
					                	// else show error msg
										
									    $('#SuccessMessage').slideUp();
										$('#ErrorMsg').html(parsedData.error.errorMessage);
										$('#ErrorMsg').slideDown();
										window.scrollTo(0,50);
										
										var reportImg = staticHost+"/images/report_abuse.png";	
										$('#'+divId).attr("src",reportImg);
										
										startTimer();
					                }
									
								}
					        },"json"
						  );
					
				}
			}
			
			/**
			 * function fro deleting my tweet
			 */
			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="'+staticHost+'/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(apiHost+'/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();
								    	    
								    	    fetchPopularTweets();
								    	    
							    	    }
							    	    else
							    	    {
							    	    	var deleteUrl = staticHost+"/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;
						
						if(tweetMsg.indexOf('&#') == -1)
						{
							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);  
						  }		 	    
						}
						else
						{
							finalTweetMsg = tweetMsg;
						}
						
						html += '<li id="Demo'+i+'"><table><tr>';
						
						var thumbUrl = staticHost+'/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 = staticHost+'/images/default_thumbnail.png';
						}
						
						var twitLink = staticHost+"/web/webwatch/"+data[i].id;
						
						var zoomUrl = staticHost+"/images/zoom_in.png";
						var image = staticHost+"/images/image.png";
						var video = staticHost+"/images/video.png";
						var audio = staticHost+"/images/audio.png";
						var deleteUrl = staticHost+"/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><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><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><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><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><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 - '+finalTweetMsg+'" 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><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><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 = data.textTweet;
				
				var tweetMsgArr = new Array();
				tweetMsgArr = tweetMsg.split(" ");
				
				var tweetHref = new String();
				var newTweetMessage = new String();
				var arrLen = tweetMsgArr.length;
				
				if(tweetMsg.indexOf("&#") == -1)
				{
					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);  
					  }	
				}
				else
				{
					finalTweetMsg = data.textTweet;
				}
				
				if(fromDetails == true)
				{	
					//changes title of document
					document.title = finalTweetMsg+" // Tvider";
				}
				
				var playerHtml = "";
				var flashvarOn = "";
				var flashvarOff = "";
				var embed = "";
				if(data.sourceMediaType == 'VIDEO' && data.mediaStatus == "HOSTED")
				{
					var playerSrc = staticHost+'/images/TwiteractPlayer.swf';
					var playerBase = staticHost+'/images/';
					flashvarOn = '&contentUrl='+data.fileUrl+'&contentLength='+data.duration+'&contentThumbnailUrl='+data.webThumbUrl+'&contentType=video&autoplay=on';
					flashvarOff = '&contentUrl='+data.fileUrl+'&contentLength='+data.duration+'&contentThumbnailUrl='+data.webThumbUrl+'&contentType=video&autoplay=off';
					playerHtml = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"  id="tviderPlayer"  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="'+flashvarOn+'" /><embed id="tviderPlayer" src="'+playerSrc+'" base="'+playerBase+'" quality="high" swliveconnect="true" wmode="transparent" scale="noscale" flashvars="'+flashvarOn+'" bgcolor="#CCCCCC" width="400" height="300" name="tviderPlayer" align="middle" allowScriptAccess="always" allowFullScreen="true" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>';
					
					
					embed = '<textarea rows="5" cols="60" readonly id="TextAreaID" name="TextAreaID" style="display: block;margin:5px 0px 0px 10px;padding: 3px; overflow: auto;" class="text_normal"><embed id="tviderPlayer" src="'+playerSrc+'" base="'+playerBase+'" quality="high" swliveconnect="true" wmode="transparent" scale="noscale" flashvars="'+flashvarOff+'" bgcolor="#CCCCCC" width="400" height="300" name="tviderPlayer" 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>tvider.com | send this to your friends</b></a>'
					+'</textarea>';
					
				}
				else if(data.sourceMediaType == 'AUDIO' && data.mediaStatus == "HOSTED")
				{
					var thumbUrl = staticHost+'/images/audio_player.png';
					var playerSrc = staticHost+'/images/TwiterAct.swf';
					var playerBase = staticHost+'/images/';
					flashvarOn = '&contentUrl='+data.fileUrl+'&contentLength='+data.duration+'&contentThumbnailUrl='+thumbUrl+'&contentType=audio&autoplay=on';
					flashvarOff = '&contentUrl='+data.fileUrl+'&contentLength='+data.duration+'&contentThumbnailUrl='+data.webThumbUrl+'&contentType=video&autoplay=off';
					playerHtml = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"  id="tviderPlayer"  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="'+flashvarOn+'" /><embed id="tviderPlayer" src="'+playerSrc+'" base="'+playerBase+'" quality="high" swliveconnect="true" wmode="transparent" scale="noscale" flashvars="'+flashvarOn+'" bgcolor="#CCCCCC" width="400" height="300" name="tviderPlayer" align="middle" allowScriptAccess="always" allowFullScreen="true" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /></object>';
					
					embed = '<textarea rows="5" cols="60" readonly id="TextAreaID" name="TextAreaID" style="display: block;margin:5px 0px 0px 10px;padding: 3px; overflow: auto;" class="text_normal"><embed id="tviderPlayer" src="'+playerSrc+'" base="'+playerBase+'" quality="high" swliveconnect="true" wmode="transparent" scale="noscale" flashvars="'+flashvarOff+'" bgcolor="#CCCCCC" width="400" height="300" name="tviderPlayer" 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>tvider.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>';
					
					embed = '<textarea rows="5" cols="60" readonly id="TextAreaID" name="TextAreaID" style="display: block;margin:5px 0px 0px 10px;padding: 3px; overflow: auto;" class="text_normal"><img src="'+data.fileUrl+'" width = "320" height="240"/>'
		   			 +'<br /><b>'+finalTweetMsg+'<br />'
						+'<a href="'+rmtUrl+''+data.id+'" target="_blank"><b>tvider.com | send this to your friends</b></a>'
		   			  +'</textarea>';
				}
				else
				{
					var processingImage = host+"/images/message.png";
					playerHtml = '<img src="'+processingImage+'" class="PlayerImage"/>';
					
					embed = '<textarea rows="5" cols="60" readonly id="TextAreaID" name="TextAreaID" style="display: block;margin:5px 0px 0px 10px;padding: 3px; overflow: auto;" class="text_normal"><img src="'+data.fileUrl+'" width = "320" height="240"/>'
		   			 +'<br /><b>'+finalTweetMsg+'<br />'
						+'<a href="'+rmtUrl+''+data.id+'" target="_blank"><b>tvider.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</span>'
		         +'<span id="EmbedGigya">'+embed+'</span>';
				
								
				if(data.mediaStatus == "HOSTED")
				{
					twitDetail= twitDetail+'<span id="Retwit" title="Re-Tweet" alt="Re-Tweet">Re-Tweet</span><span id="Reply" title="Reply" alt="Reply">Reply</span><span id="NewTweet" title="New Tweet" alt="New Tweet">New Tweet</span>'
					+'</div>';
				}
				else
				{
					twitDetail= twitDetail+'<span id="NewTweet" title="New Tweet" alt="New Tweet">New Tweet</span>'
					+'</div>';
				}
								
				$('#TweetDetails').html(twitDetail);
				
				/**
				 * Log url 
				 */
				$.getJSON(
						host+'/rmtanalytics/logview/'+data.id,
				        function(finaldata)
				        {
							var Views = finaldata.result.views;
							$('#Views').html(Views+" Views&nbsp&nbsp&nbsp|");
				        }
					  );
				
				
				var commentHead = data.commentCount+" Comments";
				$('#CommentHead').html(commentHead);
				
				//var Views = data.views+1;
				//$('#Views').html(Views+" Views");
				
				$('#comment_message').inputTextToggle();
				
				
				$('#commentRmtId').val(data.id);
				
				getComments(data.id);
				
				/**
      			 * Assign event on tweetPost button for posting tweet
      			 */
      			$('#comment_message').keyup(
      					function()
      					{
      						updateCommentCharsNum('#comment_message',1024,'#CommentCharLimit');
      					}
      				);
      			
      		    				      			
      			
				detailPaneEvents(data,finalTweetMsg);
			
				
			}
			
			function selectAndCopy(source){
				
				if (source)
			    {
			        $(source).focus();
			        $(source).select();
			        try
			        {
			            var copiedTxt = document.selection.createRange();
			            copiedTxt.execCommand("Copy");
			        }
			        catch (e)
			        {
			            // do nothing
			        }
			    }
			}
			
			/*
			* Assign onclick event on login button 
			 */
			$('#Retwit').click(
				function()
				{
		
					
					reTweetCall('#Retwit',rmtId);
				}
			);
		
			 $('#Reply').click(
						function()
						{
							openReplyForm('#Reply',data.statusId,finalTweetMsg);
						}
				);
			 
				
			 $('#NewTweet').click(
						function()
						{
							openNewTweetForm();
						}
				);
			 
			
			$('#CommentBtn').click(
					function(event)
					{ 
						addComment();
						event.stopImmediatePropagation();
					}
			);
			
			
			$('#TextAreaID').click(
					function(event)
					{
						selectAndCopy('#TextAreaID');
					}
				);
			
			
			/**
			 * Assign zoom event on all ZoomIn button 
			 */
			$("a.ZoomImage").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 }
						);
				}
				});
			
			/**
			 * Method for assigning events to the retwut and reply buttons
			 */
			function detailPaneEvents(data,finalTweetMsg)
			{
				
				
				/*
				* Assign onclick event on login button 
				 */
				$('#Retwit').click(
					function()
					{
			
						
						reTweetCall('#Retwit',data.id);
					}
				);
			
				 $('#Reply').click(
							function()
							{
								openReplyForm('#Reply',data.statusId,finalTweetMsg);
							}
					);
				 
					
				 $('#NewTweet').click(
							function()
							{
								openNewTweetForm();
							}
					);
				 
				
				$('#CommentBtn').click(
						function(event)
						{ 
							addComment();
							event.stopImmediatePropagation();
						}
				);
				
				
				$('#TextAreaID').click(
						function(event)
						{
							selectAndCopy('#TextAreaID');
						}
					);
			    //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 #tvider" ></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 #tvider" ></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: "", 
					  useFacebookMystuff: 'false', 
					  defaultContent: 'TextAreaID', 
					  UIConfig: '<config baseTheme="v2"><display showEmail="true" showBookmark="true"></display></config>',
					  emailSubject : "$sender$ has shared this Tvider 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 tvider Tweets with you. Watch <a href='"+url+"'>'"+finalTweetMsg+			    				
					    				"'</a>"+
					    				"<br /> <br />" +
					    				"$sender$ wanted to say - "+
					    				"<br />" +
					    				"$userMsg$" +
					    				"<br /> <br /> " +
					    				"Thanks , <br />"+
					    				"<a href='"+host+"'>tvider.com</a>";
						
						//Set email body of share mai
						pconf.emailBody = shareHtml;	
						
						
						//set widget title
						pconf.widgetTitle = finalTweetMsg+" // Tvider";
						
						// Initialize the gigya Component
						Wildfire.initPost("768551", 'EmbedGigya', 400, 135, pconf);	
					}
		
					
					
					/**
				     *  Method for re tweet post
				     */
				     function reTweetCall(ele,id){
				        
				         var username = $.cookie('Username');
					         if(username != null)
					         {   
					        	 var tweetuser = $("#FromUser").val();
			
					        	 $.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="'+staticHost+'/images/blue_loading.gif" />Re-Tweeting</span>');
									    	 $.post(apiHost+'/api/statuses/retweet.json', {richMediaTweetId:id},
									    	    	 function(data){
												    	    if(data.result != null)
												    	    {
													    	    
													    	    $("#retweeting").replaceWith('<span id="Retwit" title="Re-Tweet" alt="Re-Tweet"><img src="'+staticHost+'/images/retweet.png" style="vertical-align:middle"/>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',id);
												    					}
												    				);
												    	    }
												    	    else
												    	    {
													    	    //alert(data.error.errorMessage);
													    	    $('#SuccessMessage').slideUp();
																$('#ErrorMsg').html(data.error.errorMessage);
																$('#ErrorMsg').slideDown();
																window.scrollTo(0,50);
																startTimer();
																
																$("#retweeting").replaceWith('<span id="Retwit" title="Re-Tweet" alt="Re-Tweet"><img src="'+staticHost+'/images/retweet.png" style="vertical-align:middle"/>Re-Tweet</span>');

																 $("#Retwit").bind("click", function()
													    					{
														    	    			reTweetCall('#Retwit',id);
													    					}
													    				);
												    	    }
									    	 		},"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(event)
				{
					
					openWebcam("#RecordFromWebcam");
					event.stopImmediatePropagation();
				}
			);
			/**
			 * 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= "'+staticHost+'/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="'+staticHost+'/images/MediaCapture.swf" base="'+staticHost+'/images/" quality="high" flashvars="&imagePublishUrl='+apiHost+'/api/multipartUpload&videoPublishUrl='+videoPubUrlAndLogin+'" swliveconnect="true" wmode="window" scale="noscale" bgcolor="#CCCCCC" width="400" height="330" name="tviderPlayer" 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');
							event.stopImmediatePropagation();
						}
					);
				}
				
			}
			
			/**
			 * 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 #tvider" ></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 #tvider")
				{	
					/* 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 #tvider")
				{
					tweetText = "";
				}
				
				$('#tweetWebcamPost').replaceWith('<span id="tweetWebcamPosting" name="tweetWebcamPosting" ><img src="'+staticHost+'/images/wait16trans.gif" /><b>updating status</b></span>');
				
				$("#text").attr('disabled', 'disabled');
				
				
				$.ajaxSetup({
		        	beforeSend: function(xhr) 
	        			{
						xhr.setRequestHeader("Accept", "text/javascript;charset=utf-8");
						//xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
					
							xhr.setRequestHeader("Authorization",  $.cookie('twitterAuthorization'));
							xhr.setRequestHeader("twiteract-api-access-token", Base64.encode("umundo"));
						}
				});
				
	        
	    	 $.post(apiHost+'/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();
					    	    //getUserTimeline();
					    	    
					    	    
				    	    }
				    	    else
				    	    {
				    	    	
				    	    	
				    	    	if(data.error.errorCode == 1121)
				                {
				                	//alert("Authentication failed. Your Twitter Username\/Password are incorrect.");
				                	var yesOrNo = confirm(parsedData.error.errorMessage+" Please re-login with valid Username and Password.");
				                	if(yesOrNo)
				                	{
				                		logout();
				                	}
				                	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(event)
												{
													loginAndUpdateTweet('#tweetWebcamPost');
													event.stopImmediatePropagation();
												}
											);
											
											$('#SuccessMessage').slideUp();
											$('#ErrorMsg').html(data.error.errorMessage);
											$('#ErrorMsg').slideDown();
											window.scrollTo(0,50);
											startTimer();
							    	    //alert(data.error.errorMessage);
				                	}
				                	
				                }
				                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(event)
											{
												loginAndUpdateTweet('#tweetWebcamPost');
												event.stopImmediatePropagation();
											}
										);
										
										$('#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();
					
					
				}
			}
			
			function addComment()
			{
				if($.cookie('Username') == null)
				{
					alert('Please login to Tweet a Comment.');
					
				}
				else
				{
					var txt = $("#comment_message").val();
					
					txt = $.trim(txt);
					
					if(txt =="Say something about this tweet...")
					{
						txt = "";
					}
					
					if(txt.length > 0 && txt !="Say something about this tweet...")
					{	
						/* Check for the html tags in the comment text ...*/
						for(var i=0; i<= Htmltags.length ; i++)
						{
							//txt = txt.toLowerCase();
							var index = txt.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 = txt.indexOf(angleBrackets);
						if(angularTagsIndex != -1)
						{
							alert("Please Remove the < or > Characters! The App does not like them!");
							
							return false;
						}

					}	
					else if(txt.length <=0)
					{
						$('#comment_message').val("");
						
						$('#comment_message').inputTextToggle();
						
						$('#CommentCharLimit').html("max 1024 chars.");
						
						alert("Please Say something about this tweet.");
						
						
						return false;
					}
					
					
					
					 $.ajaxSetup({
				        	beforeSend: function(xhr) 
			        			{
									xhr.setRequestHeader("Accept", "text/javascript;charset=utf-8");
									xhr.setRequestHeader("Content-Type","application/form-data");
									xhr.setRequestHeader("Authorization",  $.cookie('twitterAuthorization'));
									xhr.setRequestHeader("twiteract-api-access-token", Base64.encode("umundo"));
								}
						});
						
					 


					 
					 var commentRmtId = $('#commentRmtId').val();
					 
					 $("#comment_message").val("");
					 $('#CommentBtn').hide();
					 $('#waiting').show();
					 
			        
			    	 $.post(apiHost+'/api/addComment.json', {"richMediaTweetId":commentRmtId,"text":txt},
			    	    	 function(data){
							    	    if(data.result != null)
							    	    {
							    	    	
							    	    	getComments(commentRmtId);
							    	    	window.scrollTo(0,500);
							    	    }
							    	    else
							    	    {
							    	    	$('#waiting').hide();
							    	    	$('#CommentBtn').show();
											
							    	    	$('#comment_message').val("");
											
											$('#comment_message').inputTextToggle();
											
											$('#CommentCharLimit').html("max 1024 chars.");
											
							    	    	$('#SuccessMessage').slideUp();
											$('#ErrorMsg').html(data.error.errorMessage);
											$('#ErrorMsg').slideDown();
											window.scrollTo(0,50);
											startTimer();
											
							    	    	
							    	    }	
			    	 },"json" );
				}		    	 
			}
			
			var currentComments = "";
			
			/**
			 * Method to populate comments
			 */
			function populateComment(result)
			{ 
				
				$('#CommentBtn').show();
				
				$('#waiting').hide();
				
				$('#comment_message').val("");
				
				$('#comment_message').inputTextToggle();
				
				$('#CommentCharLimit').html("max 1024 chars.");
				
				var commentHead = result.length+" Comments";
				$('#CommentHead').html(commentHead);
				
				currentComments = result;
			
				var commentHtml ="";
				for(var i=0; i<result.length; i++)
				{
				   
					var textComment = result[i].textComment;
					
					
					var mm=textComment.substring(3,8);
					
					if(textComment.indexOf("&#") == -1)
					{	
						if(mm!="mmmmm" && mm!="wwwww" && mm!="ddddd" && mm!="MMMMM" && mm!="WWWWW" && mm!="DDDDD")
						  {
						  
							textComment=textComment.wordWrap(70,"\n", false); 
						 }
					  else{
						  textComment=textComment.wordWrap(30,"\n", false);  
					  }		 
					}
					
					if($.cookie('Username') == null || $.cookie('Username') == "")
					{
						
						var date = new Date(result[i].createdAt);
						
						var age = jQuery.timeago(date); 
						
							commentHtml= commentHtml+ '<div id="CommentThumb"><div id="Age" class="age"> by - <a href="http://twitter.com/'+result[i].fromUser+'" target="_blank">'+result[i].fromUser+'</a> <br /> '+age+'</div><img src="'+result[i].profileImageUrl+'"/></div><div class="action_box curved_x">';
							
							
							
							commentHtml = commentHtml+
							              '<div style="font-size: 14px; color: black; text-align: left; float: left; width:100%; margin-left: 10px;">'+textComment+
							              '</div></div>';
					}
					else
					{

						var date = new Date(result[i].createdAt);
						var age = jQuery.timeago(date); 
						
						commentHtml= commentHtml+ '<div id="CommentThumb"><div id="Age" class="age"> by - <a href="http://twitter.com/'+result[i].fromUser+'" target="_blank">'+result[i].fromUser+'</a> <br /> '+age+'</div><img src="'+result[i].profileImageUrl+'"/></div><div class="action_box curved_x">';
						
						
						
						if(($.cookie('Username') == result[i].fromUser) || ($.cookie('Username') == $('#FromUser').val()))
						{	
						commentHtml = commentHtml+
						              '<div style="font-size: 14px; color: black; text-align: left; float: left; width: width:100%; margin-left: 10px;">'+textComment+
						              '<div id="DeleteComment" >( <a class="Remove" id="Remove'+i+'" title="Remove this comment">Remove</a> )</div></div></div>';
						}
						else
						{
							commentHtml = commentHtml+
				              '<div style="font-size: 14px; color: black; text-align: left; float: left; width: width:100%; margin-left: 10px;">'+textComment+
				              '</div></div>';
						}
						
						
					}
				
				}
				
				
				
				$('#Comments').html(commentHtml);
				
				/**
				 * Assign Events on all Delete Buttons
				 */
				$('a.Remove').click(
						function(event)
						{
							var removeId=event.target.id;
							deleteComment(removeId);
						}
						
				);
				
				
			}
			
			/**
			 * Delete comment
			 */
			function deleteComment(id)
			{
				var actualId = id.split("Remove")[1];
			
				var commentId = currentComments[actualId].id;
				
				var return_value = confirm("Sure you want to delete this comment? There is NO undo!");
				
				if(return_value == true)
				{	
						$.ajaxSetup({
				        	beforeSend: function(xhr) 
			        			{
									xhr.setRequestHeader("Accept", "text/javascript");
									xhr.setRequestHeader("Authorization",  $.cookie('twitterAuthorization'));
									xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
									xhr.setRequestHeader("twiteract-api-access-token", Base64.encode("umundo"));
								}
						});
						
					 
					 
					 var commentRmtId = $('#commentRmtId').val();
			         $('#'+id).replaceWith('<img src="'+staticHost+'/images/loading.gif" /></span>');
			    	 $.post(apiHost+'/api/deleteComment.json', {"commentId":commentId},
			    	    	 function(data){
							    	    if(data.result != null)
							    	    {
							    	    	getComments(commentRmtId);
							    	    }
							    	    else
							    	    {
							    	    	$('#SuccessMessage').slideUp();
											$('#ErrorMsg').html(data.error.errorMessage);
											$('#ErrorMsg').slideDown();
											window.scrollTo(0,50);
											startTimer();
							    	    	
							    	    }	
			    	 },"json" );
				}	    	 
			}
			
			/**
			 * Method for getting comments of current tweet
			 */
			function getComments(id)
			{
				$.ajaxSetup({
		        	beforeSend: function(xhr) 
	        			{
							xhr.setRequestHeader("Accept", "text/javascript;charset=utf-8");
							xhr.setRequestHeader("Content-Type","application/form-data");
							xhr.setRequestHeader("Authorization",  $.cookie('twitterAuthorization'));
							xhr.setRequestHeader("twiteract-api-access-token", Base64.encode("umundo"));
						}
				});
				
				$.getJSON(
						apiHost+'/api/getComments.json?richMediaTweetId='+id,
				        function(response)
				        {
				        	if (response.result != null) 
							{
				        		
				        		populateComment(response.result);
				        		
							}
							else
							{
								//alert(data.error.errorMessage);
								$('#SuccessMessage').slideUp();
								$('#ErrorMsg').html(data.error.errorMessage);
								$('#ErrorMsg').slideDown();
								window.scrollTo(0,50);
								startTimer();
							}
				        }
		        );
			}
			
			
			
			/**
			 * Method for posting tweet
			 */
			function postTweet()
			{
				var fileValue = $("#file").val();
				
				var tweetText	=	$("#text").val();
							
				if(fileValue != "" || fileValue.length > 0)
				{		
					
					
					 
					 
						 $('#tweetPost').replaceWith('<img src="'+staticHost+'/images/wait16trans.gif" /><b>updating status</b>');
							
							
						 
							$('#TweetForm').submit();
							
							$.cookie('SuccessMsg','false');
							$.cookie('CurrentState','friends',{path:"/"});
							$("#text").attr('disabled', 'disabled');
							$("#file").attr('disabled', 'disabled');
							$("#RecordFromWebcam").unbind('click');
							$("#RecordFromWebcam").addClass("DisabledRecordFromWebcam");
							
							var html = '<img src="'+staticHost+'/images/record_webcam_disabled.gif" title="Record from webcam" />  or'; 
							$("#RecordFromWebcam").html(html);
							setTimeout('queryStatus()', 10);
					
					
				}
				else
				{
					alert("Please select Media to tweet .");
					return;
				}
			}
			
			
			function postReplyTweet()
			{
				var fileValue = $("#file").val();
				
				var tweetText	=	$("#text").val();
				
				
				if(fileValue != "" || fileValue.length > 0)
				{		
					$('#ReplyForm').submit();
					
					$.cookie('SuccessMsg','false');
					$.cookie('CurrentState','friends',{path:"/"});
					$('#tweetPost').replaceWith('<span id="login" name="login" ><img src="'+staticHost+'/images/wait16trans.gif" /><b>updating status</b></span>');
					//setTimeout('queryStatus()', 10);
				}
				else
				{
					alert("Please select Media to tweet .");
					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="'+staticHost+'/images/wait16trans.gif" /><b>authenticating</b></span>');
					var encodedAuthorization = Base64.encode(username+":"+password);
					$("#headerUsername").attr('disabled', 'disabled');
					$("#headerPassword").attr('disabled', 'disabled');
					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 navigating user to home page
			 */
			function gotoHome(from)
			{
				
				$.cookie('CurrentState',null,{path:"/"});
				
				$.cookie('CurrentState',from,{path:"/"});
				
				window.location.href = host;
			}
			
			
			/**
			 * function for making app ready to get timeline
			 */
			function readyToFetchTimeline(source)
			{
				   $.cookie('CurrentState',source,{path:"/"});
				
				   CurrentTweet.page = 1;
				   
				   $("#Tweets").html("");
				   $("#Tweets").html('<ul id="Demo"></ul>');
				   
				   $("#ShowMore").hide();
				   
					currentTimeline = new Array();
					
					$("#MainLoading").show();
				
					if(source == "friends")
					{
						$("#MainLoading").html('<center><br /><img src="'+staticHost+'/images/wait30trans.gif" /><h1> fetching friends tweets </h1></center>');
						getFriendsTimeline();
						
					}
					else if(source == "my")
					{
						getUserTimeline();
					}
					else if(source == "public")
					{
						$("#MainLoading").html('<center><br /><img src="'+staticHost+'/images/wait30trans.gif" /><h1> fetching public tweets </h1></center>');
						getPublicTimeline();
					}
					
					
			}
			
			/**
			 * 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');
				
								 
				 
				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();
				
				
				$('#authorization').val($.cookie('twitterAuthorization'));
				
				$('#Home').bind("click",function(){gotoHome("friends");});
				$('#MyTweet').bind("click", function(){getUserTimeline();});
				$('#PublicTweet').bind("click", function(){readyToFetchTimeline("public");});
				$('#logout').bind("click", function(){logout('#Login');});
				
				$('#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"));
						}
				});
				
				var currentState = $.cookie('CurrentState');
				
				
				if(currentState == "friends")
				{
					readyToFetchTimeline("friends");//getFriendsTimeline();
				}
				else if(currentState == "public")
				{
					readyToFetchTimeline("public");//getPublicTimeline();
				}
				else
				{
					readyToFetchTimeline("friends");
				}
				
				
				var successMsg = $.cookie('SuccessMsg');
				
				
				if((resultMsg.length >0 || resultMsg != "" ) && (successMsg == 'false'))
				{	
					$.cookie('SuccessMsg','true',{path:"/"});
				  
					$('#ErrorMsg').slideUp();
					$('#SuccessMessage').html(resultMsg);
					$('#SuccessMessage').slideDown();
					window.scrollTo(0,50);
					startTimer();
				}
				else if((errorMsg.length > 0 || errorMsg != "") && (successMsg == 'false'))
				{
					$.cookie('SuccessMsg','true',{path:"/"});
					$('#SuccessMessage').slideUp();
					$('#ErrorMsg').html(errorMsg);
					$('#ErrorMsg').slideDown();
					window.scrollTo(0,50);
					startTimer();
					
				}	
				
			
			}		
			
			/**
			 * 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 checking textarea char length
			 */
			function updateCommentCharsNum(o, maxlen, state) {
				
				if (!maxlen) {
					maxlen = 110;
				}
				var message = $("#comment_message").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) {
						$("#CommentBtn").addClass("comment_disabled");
						$("#CommentBtn").unbind('click');

					} else {
						$("#CommentBtn").removeClass("comment_disabled");
						$('#CommentBtn').click(
								function(event)
								{ 
									addComment();
									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
		    }
		    
		    
		    String.prototype.wordWrap = function(m, b, c){
		        var i, j, s, r = this.split("\n");
		        if(m > 0) for(i in r){
		            for(s = r[i], r[i] = ""; s.length > m;
		                j = c ? m : (j = s.substr(0, m).match(/\S*$/)).input.length - j[0].length
		                || m,
		                r[i] += s.substr(0, j) + ((s = s.substr(j)).length ? b : "")
		            );
		            r[i] += s;
		        }
		        return r.join("\n");
		    }
		    
		   
		}
	);
