// jQuery related calls, either direct jquery library or third party plugins based on the same
	$(document).ready(
		function()
		{
			/**
			 * Function for hiding popup msg window
			 */
			function startTimer()
			{
				$.timer(6000, function (timer) {
				   	//alert("hello");
					$('#SuccessMessage').slideUp();
					$('#ErrorMsg').slideUp();
				   	timer.stop();
				   });
			}
			
			
			
			
			/*
			 * Method for authenticating user . 
			 * Accoridng to result show timeline and error
			 */
			function authenticate(encodedAuthorization,password)
			{
				$.ajaxSetup({
			        beforeSend: function(xhr) 
			        			{
        							xhr.setRequestHeader("Accept", "text/javascript");
        							xhr.setRequestHeader("Authorization", "Basic "+encodedAuthorization);
        							xhr.setRequestHeader("twiteract-api-access-token", Base64.encode("umundo"));
        						}
				});
                   
				$.getJSON(apiHost+'/api/authenticate.json',
				        function(data)
				        {
				        	if(!data.error)
				        	{
				        		var encodedTwiterAuthorization = Base64.encode(data.result.screenName+":"+password);
				        		
				          		$.cookie('twitterAuthorization', encodedTwiterAuthorization,{path:"/"});
				          		$.cookie('Username', data.result.screenName,{path:"/"});
				          		$.cookie('ProfileImage', data.result.profileImageUrl,{path:"/"});
				          		//$.cookie('Status', data.result.status.text);
								$('#authroization').val($.cookie('twitterAuthorization'));
								$('#user').val(data.result.screenName);
								$.cookie('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:"/"});
								
								window.location.href=userUrl+""+userPage;
								//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();
				
			}
			
			
			$('#ProductLogo').click(
					function(event)
					{
						//goToHomePage();
						$.cookie('CurrentState',null,{path:"/"});
						window.location.href = host;
					}
				);
			
			
			function goToHomePage()
			{
				var username = $.cookie('Username');
				
				$.cookie('CurrentState',null,{path:"/"});
				
				//$.cookie('CurrentState',from,{path:"/"});
				
				window.location.href = host;
				
				/*if(username == null)
				{
					gotoHome("public");
					
				}
				else
				{
					gotoHome("friends");
				}*/
			}
			
			 /****************************************code for fetching popular tweets********************************************/
			   
			
			 /**
			 * 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();
				}
			}
			
			/**
			 * 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;
				}
		    
		    
			var currentPopularTimeline = "";
			var owner = "";
			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>";
					
					
					
				   memberHtml = memberHtml+'<a alt="'+ memDetails +'" class="PopularMember" href="'+user+'"><img src="'+result[i].profileImageUrl+'" /></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:"/"});
					
				}
				
				var twitterAuthorization = $.cookie('twitterAuthorization');
				
				getTrendingTopics();
				//getUserInfo();
				
				if(twitterAuthorization)
				{
					
					showWelcomePane();
					
				} 
				else
				{
						    
					$('#Header_login').show();
					
					$('#Header_user').hide();
					
					getUserDataFromTwitter();
					//readyToFetchTimeline();
				}
			}
			
			
			function getUserDataFromTwitter()
			{
				
				/*$.timer(10000, function (timer) {
				    window.location.href="http://twitter.com/"+userPage;
				   	
				   });*/
				
				$.twitter.users.show(userPage,function(data)
						{
							
					       getUserInfoTwitter(data); 
						   readyToFetchTimeline();
						},
						function(error)
						{
						
							$("#MainLoading").html("");
							$("#MainLoading").html("Sorry, this user does not exist!");
							$("#MainLoading").show();
							
						},"json");
				
				
				
				
			}
			
					 
				
			/**
			 * 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);
			}
			
			
			/**
			 * Method for getting public timeline of twiteract
			 */
			function getPublicTimeline()
			{
				
				// Show the wait message
				$('#TimeLine').html("Public");
				$('#Tweets').html('');
				$('#Tweets').html('<center><br /><img src="'+staticHost+'/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',
				        function(data)
				        {
				        	if (!data.error) 
							{
								showTweetTimeline(data.result);
							}
							else
							{
								//alert(data.error.errorMessage);
								$('#SuccessMessage').slideUp();
								$('#ErrorMsg').html(data.error.errorMessage);
								$('#ErrorMsg').slideDown();
								window.scrollTo(0,50);
								startTimer();
							}
				        }
		        );
			}
			
			
			/**
			 * Assign events on all thumbnails to view
			 */
			$('#FollowUser').click(
					function(e)
					{
						var id = e.target.id;
						followMe();
					}
			);
			
			/**
			 * Method to get user own timeline from twiteract
			 */
			function getUserTimeline()
			{
				if(fromMore == false)
				{
					$("#MainLoading").show();
					currentTimeline = new Array()
				}
				
				$.cookie('CurrentState',"my",{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/user_timeline.json?profile=web&page='+CurrentTweet.page,
				        function(data)
				        {
				        	if (!data.error) 
							{
				        		showMyTweetTimeline(data.result);
				        		var title = '<span id="TimeLine">Your</span> Tweets';
			    				// Show the wait message
			    				$('#TimelineName').html(title);
			        			
							}
							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
				                	{
				                		//alert(data.error.errorMessage);
										$('#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 getFriendsTimeline()
			{
				// Show the wait message
				$('#TimeLine').html("Friends");
				$('#Tweets').html('');
				$('#Tweets').html('<center><br /><img src="'+staticHost+'/images/wait30trans.gif" /><h1> fetching your friends tweets </h1></center>');

				$.ajaxSetup({
		        	beforeSend: function(xhr) 
	        			{
							xhr.setRequestHeader("Accept", "text/javascript");
							xhr.setRequestHeader("Authorization",  $.cookie('twitterAuthorization'));
							xhr.setRequestHeader("twiteract-api-access-token", Base64.encode("umundo"));
						}
				});
				
				$.getJSON(
						apiHost+'/api/statuses/friends_timeline.json?profile=web',
				        function(data)
				        {
							
				        	if (!data.error) 
							{
								showTweetTimeline(data.result);
							}
							else
							{
								//alert(data.error.errorMessage);
								 $('#SuccessMessage').slideUp();
									$('#ErrorMsg').html(data.error.errorMessage);
									$('#ErrorMsg').slideDown();
									window.scrollTo(0,50);
									startTimer();
							}
				        }
		        );
			}
			
			var currentTimeline = new Array();
			var fromMore = false;
			
			/**
			 * Method to get friends time of logged in user from twiteract
			 */
			function getCurrentUserTimeline()
			{
				
				
				if(fromMore == false)
				{
					$("#MainLoading").show();
					currentTimeline = new Array()
				}
				
				$.cookie('CurrentState',"friends",{path:"/"});
				
				var currentUser = userPage;
				
				
				var userid = $("#userid").val();
				var isProtected = $("#protected").val();
				/*$('#Tweets').html('');
				$('#Tweets').html('<center><br /><img src="'+host+'/images/wait30trans.gif" /><h1> fetching tweets </h1></center>');
				 */
				
				
				$.ajaxSetup({
		        	beforeSend: function(xhr) 
	        			{
							xhr.setRequestHeader("Accept", "text/javascript");
							xhr.setRequestHeader("Authorization",  $.cookie('twitterAuthorization'));
							xhr.setRequestHeader("twiteract-api-access-token", Base64.encode("umundo"));
						}
				});
				
				$.getJSON(
						apiHost+'/api/statuses/user_timeline/'+userid+'.json?consumptionProfile=web&protected='+isProtected+'&screenName='+userPage+'&page='+CurrentTweet.page,
				        function(data)
				        {
							
				        	if (!data.error) 
							{
				        		if($.cookie('Username') != userPage)
				        		{	
				        			var title = '<span id="TimeLine">Tweets</span> from '+currentUser;
				    				// Show the wait message
				    				$('#TimelineName').html(title);
				    				
				        			showTweetTimeline(data.result.statuses);
				        		}
				        		else
				        		{
				        			
				        			
				        			var title = '<span id="TimeLine">Your</span> Tweets';
				    				// Show the wait message
				    				$('#TimelineName').html(title);
				        			showMyTweetTimeline(data.result.statuses);
				        		}
				        		
							}
							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
				                	{
				                		//alert(data.error.errorMessage);
				                		$("#MainLoading").html("");
										$("#MainLoading").html(data.error.errorMessage);
										
				                	}
				                }
								else
								{
									//alert(data.error.errorMessage);
									$("#MainLoading").html("");
									$("#MainLoading").html(data.error.errorMessage);
								}
								
								
							}
				        }
		        );
			}
			
			
			
			
			
			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:"/"});
							window.location.href=host+"/u/r/"+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 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");
			}
			
			/**
			 * method for getting user info
			 */
			function getUserInfo(data)
			{
				
				            var bgimage = data.profileBackgroundImageUrl;
							//var tweetcount = data.statuses_count;
							var profileImage = data.profileImageUrl;
							var profileName = data.name;
							var bgcolor = data.profileBackgroundColor;
					        var screenName = data.screenName;
					        var repeat = data.profileBackgroundTile;
					        var location = data.location;
					        
					        $("#userid").val(data.id);
					        $("#UserImage").attr("src",data.profileImageUrl);
					        $("#twitterLink").attr("href","http://twitter.com/"+data.screenName);
					        
					        if(data.location != null && data.location != "")
					        $("#CurrentUserLocation").html("<b>Location</b>&nbsp;:&nbsp;"+data.location);
					       
					        
					        
					        
					        if(data.description != null && data.description != "")
					        $("#CurrentUserBio").html("<b>Bio</b> : "+data.description);
					        
					        if(data.name != null && data.name != null)
					        {
					        $("#CurrentUserName").html(profileName+"&nbsp;&nbsp;<span style='color:black;font-size:20px;'>("+data.screenName+")");
					        document.title = data.name+" ("+data.screenName+") on Tvider";
					        }
					        else
					        {
					        $("#CurrentUserName").html(data.screenName);
					        document.title = data.screenName+" on Tvider";
					        }
					        
					        if(data.totalTweets != null && data.totalTweets != "")
					        $("#CurrentUserTweetCount").html("<b>Tweets</b>&nbsp;:&nbsp;"+data.totalTweets);
					        
					        if(data.friendsCount != null && data.friendsCount != "")
					        $("#CurrentUserFollowing").html("<b>Following</b>&nbsp;:&nbsp;"+data.friendsCount);
					        
					        if(data.followersCount != null && data.followersCount != "")
					        $("#CurrentUserFollowers").html("<b>Followers</b>&nbsp;:&nbsp;"+data.followersCount);
					        
					        
					        if(data.isFollowing == false && $.cookie('Username') != data.screenName)
					        	$("#FollowUser").show();
					        else
					        	$("#FollowUser").hide();
					        
					        
					        if(repeat == "true")
							{
							 
								$("body").css("background", "url('" + bgimage + "') #"+bgcolor+" repeat fixed left top");
							}
							else
							{
								$("body").css("background", "url('" + bgimage + "') #"+bgcolor+" no-repeat fixed left top");
							}
							
					        
					        
						
			}
			
			
			/**
			 * method for getting user info
			 */
			function getUserInfoTwitter(data)
			{
				
				            var bgimage = data.profile_background_image_url;
							//var tweetcount = data.statuses_count;
							var profileImage = data.profile_image_url;
							var profileName = data.name;
							var bgcolor = data.profile_background_color;
					        var screenName = data.screen_name;
					        var repeat = data.profile_background_tile;
					        var location = data.location;
					        
					        $("#userid").val(data.id);
					        $("#protected").val(data.protected);
					        $("#UserImage").attr("src",data.profile_image_url);
					        $("#twitterLink").attr("href","http://twitter.com/"+data.screen_name);
					        
					        if(data.location)
					        $("#CurrentUserLocation").html("Located in "+data.location);
					       
					        
					        
					        
					        if(data.description)
					        $("#CurrentUserBio").html(data.description);
					        
					        if(data.name)
					        {
					        $("#CurrentUserName").html(profileName+"&nbsp;&nbsp;<span style='color:black;font-size:20px;'>("+data.screen_name+")");
					        document.title = data.name+" ("+data.screen_name+") on Tvider";
					        }
					        else
					        {
					        $("#CurrentUserName").html(data.screen_name);
					        document.title = data.screen_name+" on Tvider";
					        }
					        
					        var tweetLink = "<a href='http://twitter.com/"+data.screen_name+"' target='_blank'>Tweets</a>";
					        if(data.statuses_count)
					        $("#CurrentUserTweetCount").html(data.statuses_count+"<br />"+tweetLink);
					        else
					        $("#CurrentUserTweetCount").html("0<br />Tweets");
					        
					        
					        var followingLink = "<a href='http://twitter.com/"+data.screen_name+"/following' target='_blank'>Following</a>";
					        if(data.friends_count)
					        $("#CurrentUserFollowing").html(data.friends_count+"<br />"+followingLink);
					        else
					        $("#CurrentUserFollowing").html("0<br />Following");
					        
					        
					        var followersLink = "<a href='http://twitter.com/"+data.screen_name+"/followers' target='_blank'>Followers</a>";
					        if(data.followers_count)
					        $("#CurrentUserFollowers").html(data.followers_count+"<br />"+followersLink);
					        else
					        $("#CurrentUserFollowers").html("0<br />Followers");
					      
					        if($.cookie('Username') != data.screen_name)
					        {
					        	
					        	$("#FollowUser").show();
					        }
					        else
					        {
					        	
					        	$("#FollowUser").hide();
					        }
					        
					        
					        if(repeat)
							{
							 
								$("body").css("background", "url('" + bgimage + "') #"+bgcolor+" repeat fixed left top");
							}
							else
							{
								$("body").css("background", "url('" + bgimage + "') #"+bgcolor+" no-repeat fixed left top");
							}
							
					        
					        
						
			}
			
			/**
			 * 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($.cookie('Username') == userPage)
					getUserTimeline();
		        else
		        	getCurrentUserTimeline();
				
				
				//getCurrentUserTimeline();
				
				/*if(current == "friends")
					getFriendsTimeline();
				else if(current == "public")
				   getPublicTimeline();*/
			}
			
			
			/**
			 * function for making app ready to get timeline
			 */
			function readyToFetchTimeline()
			{
				  
				
				   CurrentTweet.page = 1;
				   
				   $("#Tweets").html("");
				   $("#Tweets").html('<ul id="Demo"></ul>');
				   
				   $("#ShowMore").hide();
				   
					currentTimeline = new Array();
					
					
					$("#MainLoading").html('<center><br /><img src="'+staticHost+'/images/wait30trans.gif" /><h1> fetching tweets </h1></center>');
					$("#MainLoading").show();
				
					
					
					
					
					if($.cookie('Username') == userPage)
						getUserTimeline();
			        else
			        	getCurrentUserTimeline();
					
					
					
					
			}
			
			/**
		     * 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)
			{
				
				//$("#FollowUser").show();
				
				$("#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 = relativeTime(date);//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;
						
						
						finalTweetMsg = toText(tweetMsg);
						var finalTweet = activateInTweetLinks(finalTweetMsg);
						
						html += '<li id="Demo'+j+'" class="DemoLi">';
						//check weather tweet had 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 = 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 paramLink = rmtUrl+""+data[i].id;
							var user = userUrl+""+data[i].fromUser;
							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();
					
					
					
					
					/**
					 * 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 }
								);
						}
						});
					
					
					$('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();
							}
						);
					
					
					
					$('#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 event for increasing view count while zoom image
					 */
					$("a.Zoom").click(
						   function(e)
						   {
							   var zoomId = e.target.id;
							   
							   increaseView(zoomId.split("Zoom")[1]);
							   
							   e.stopImmediatePropagation();
						   }
					);
					
					
					/**
					 * Assign events on all thumbnails to view
					 */
					$('a.Favorite').click(
							function(event)
							{
								var divId = event.target.id;
								doFavorite(divId);
							}
					);
					
					
					/**
					 * Assign events on all thumbnails to view
					 */
					$('a.Abuse').click(
							function(event)
							{
								var divId = event.target.id;
								doReportAbuse(divId);
								event.stopImmediatePropagation();
							}
					);
					
					
					
					
					
					
	
				}
				else
				{
					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 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
					                	{
					                		// 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();
											
					                	}
					                }
									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"
						  );
					
				}
			}
			
			
			/**
			 * 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();
											
					                	}
					                }
									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"
						  );
					
				}
			}
			
			
			/**
			 * Method for deleting user own tweet.
			 */
			function deleteMyTweet(id)
			{
				
				var tweetId = id.split("DeleteImg")[1];
				
				
				var richMediaId = currentTimeline[tweetId].id;
				
				var return_value = confirm("Sure you want to delete this tweet? There is NO undo!");
                 
				if(return_value == true)
				{
					//True value script
					//$('#DeleteSpan'+tweetId).html("");
					  var loading = staticHost+'/images/loading.gif';
						$('#DeleteImg'+tweetId).attr("src",loading);

					
							$.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)
							    	    {
								    	    
								    	   
								    	    $('#ErrorMsg').slideUp();
											$('#SuccessMessage').html("Tweet deleted successfully.");
											$('#SuccessMessage').slideDown();
											window.scrollTo(0,50);
											startTimer();
											
											readyToFetchTimeline();
											
											//getUserTimeline();
								    	    
								    	  
								    	    
							    	    }
							    	    else
							    	    {
							    	    	if(response.error.errorCode == 1121)
							                {
							                	//alert("Authentication failed. Your Twitter Username\/Password are incorrect.");
							                	var yesOrNo = confirm(response.error.errorMessage+" Please re-login with valid Username and Password.");
							                	if(yesOrNo)
							                	{
							                		logout();
							                	}
							                	else
							                	{
							                		var deleteUrl = staticHost+"/images/delete.png";
									    	    	$('#DeleteSpan'+tweetId).html("");
													$('#DeleteSpan'+tweetId).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();
													
							                	}
							                }
											else
											{
		// else show error msg
												
												var deleteUrl = staticHost+"/images/delete.png";
								    	    	$('#DeleteSpan'+tweetId).html("");
												$('#DeleteSpan'+tweetId).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)
			{
				$("#MainLoading").hide();
				
				var html ="";
				
				var length = data.length;
		 		
				
		 		var upto = start + length;
		 		
				var html = '';
				
		     
				
				
				//currentTimeline = data.statuses;
				
				//getUserInfo(data.user);
				
				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 = relativeTime(date);//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;
						
						
						finalTweetMsg = toText(tweetMsg);
						var finalTweet = activateInTweetLinks(finalTweetMsg);
						
						
						html += '<li id="Demo'+j+'" class="DemoLi"><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 profileImage = staticHost+'/images/defaultImage.png';
						
						if(data[i].profileImageUrl)
							profileImage = data[i].profileImageUrl;
						
						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 deleteUrl = staticHost+"/images/delete.png";
						
						var paramLink = rmtUrl+""+data[i].id;
						var user = userUrl+""+data[i].fromUser;
						
						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" && (data[i].mediaStatus == "HOSTED" || data[i].mediaStatus == 'CORRUPT'))
							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="'+profileImage+'" /></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="ViewAndFav" style="width:90px;border-right:1px solid lightgrey;"><span class="data" id="view'+j+'">'+data[i].views+' views</span><br /><span class="data" id="Fav'+j+'">'+data[i].favourite+' <img src="'+fav+'" /></span></div><div class="ViewAndFav" style="width:190px;"><span class="data">'+data[i].mediaStatus+'</span><span id="Option'+j+'" class="Option1" style="display:none"><a class="Favorite" title="Favorite this tweet"><img id="Favorite'+j+'" src="' + favbig + '" /></a> <img src="' + pipe + '" /><a class="Delete" id="Delete'+j+'" title="Delete this tweet"><img id="DeleteImg'+ j +'" src="' + deleteUrl + '" /></a></span></div></td></tr></table></td>';
							else if(data[i].sourceMediaType == "VIDEO" && (data[i].mediaStatus != "HOSTED" || data[i].mediaStatus != 'CORRUPT'))
							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="'+profileImage+'" /></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="ViewAndFav" style="width:90px;border-right:1px solid lightgrey;"><span class="data" id="view'+j+'">'+data[i].views+' views</span><br /><span class="data" id="Fav'+j+'" >'+data[i].favourite+' <img src="'+fav+'" /></span></div><div class="ViewAndFav" style="width:190px;"><span class="data">'+data[i].mediaStatus+'</span></div></td></tr></table></td>';	
							else if(data[i].sourceMediaType == "AUDIO" && (data[i].mediaStatus == "HOSTED" || data[i].mediaStatus == 'CORRUPT'))
							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="'+profileImage+'" /></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="ViewAndFav" style="width:90px;border-right:1px solid lightgrey;"><span class="data" id="view'+j+'">'+data[i].views+' views</span><br /><span class="data" id="Fav'+j+'">'+data[i].favourite+' <img src="'+fav+'" /></span></div><div class="ViewAndFav" style="width:190px;"><span class="data">'+data[i].mediaStatus+'</span><span id="Option'+j+'" class="Option1" style="display:none"><a class="Favorite" title="Favorite this tweet"><img id="Favorite'+j+'" src="' + favbig + '" /></a> <img src="' + pipe + '" /><a class="Delete" id="Delete'+j+'" title="Delete this tweet"><img id="DeleteImg'+ j +'" src="' + deleteUrl + '" /></a></span></div></td></tr></table></td>';
							else if(data[i].sourceMediaType == "AUDIO" && (data[i].mediaStatus != "HOSTED" || data[i].mediaStatus != 'CORRUPT'))
							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="'+profileImage+'" /></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="ViewAndFav" style="width:90px;border-right:1px solid lightgrey;"><span class="data" id="view'+j+'">'+data[i].views+' views</span><br /><span class="data" id="Fav'+j+'">'+data[i].favourite+' <img src="'+fav+'" /></span></div><div class="ViewAndFav" style="width:190px;"><span class="data">'+data[i].mediaStatus+'</span></div></td></tr></table></td>';
							else if(data[i].sourceMediaType == "IMAGE" && 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="'+profileImage+'" /></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="ViewAndFav" style="width:90px;border-right:1px solid lightgrey;"><span class="data" id="view'+j+'">'+data[i].views+' views</span><br /><span class="data"  id="Fav'+j+'">'+data[i].favourite+' <img src="'+fav+'" /></span></div><div class="ViewAndFav" style="width:190px;"><span class="data" >'+data[i].mediaStatus+'</span><span id="Option'+j+'" class="Option1" style="display:none"><a title="Favorite this tweet" class="Favorite"><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="Delete" id="Delete'+j+'" title="Delete this tweet"><img id="DeleteImg'+ j +'" src="' + deleteUrl + '" /></a></span></div></td></tr></table></td>';
							else if(data[i].sourceMediaType == "IMAGE" && (data[i].mediaStatus != "HOSTED" || data[i].mediaStatus != 'CORRUPT'))
							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="'+profileImage+'" /></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="ViewAndFav" style="width:90px;border-right:1px solid lightgrey;"><span class="data" id="view'+j+'">'+data[i].views+' views</span><br /><span class="data"  id="Fav'+j+'">'+data[i].favourite+' <img src="'+fav+'" /></span></div><div class="ViewAndFav" style="width:190px;"><span class="data" >'+data[i].mediaStatus+'</span></div></td></tr></table></td>';
							else if(data[i].mediaStatus == 'CORRUPT')
							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="'+profileImage+'" /></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="ViewAndFav" style="width:90px;border-right:1px solid lightgrey;"><span class="data" id="view'+j+'">'+data[i].views+' views</span><br /><span class="data" id="Fav'+j+'">'+data[i].favourite+' <img src="'+fav+'" /></span></div><div class="ViewAndFav" style="width:190px;"><span class="data" >'+data[i].mediaStatus+'</span><span id="Option'+j+'" class="Option1" style="display:none"><a class="Delete" id="Delete'+j+'" title="Delete this tweet"><img id="DeleteImg'+ j +'" src="' + deleteUrl + '" /></a><span></div></td></tr></table></td>';	
							else if((data[i].sourceMediaType == "VIDEO" || data[i].sourceMediaType == "AUDIO")  && (data[i].mediaStatus == "HOSTED" && data[i].mediaStatus != 'CORRUPT'))
							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="'+profileImage+'" /></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="ViewAndFav" style="width:90px;border-right:1px solid lightgrey;"><span class="data" id="view'+j+'">'+data[i].views+' views</span><br /><span class="data" id="Fav'+j+'" >'+data[i].favourite+' <img src="'+fav+'" /></span></div><div class="ViewAndFav" style="width:190px;"><span class="data" >'+data[i].mediaStatus+'</span><span id="Option'+j+'" class="Option1" style="display:none"><a class="Favorite" title="Favorite this tweet"><img id="Favorite'+j+'" src="' + favbig + '" /></a> <img src="' + pipe + '" /> <a class="Delete" id="Delete'+i+'" title="Delete this tweet"><img id="DeleteImg'+ i +'" src="' + deleteUrl + '" /></a></span></div></td></tr></table></td>';
							
							
							
						html += '</tr></table></li>';
						
						
						
						
						
					}
			
			html += '</ul>';	
			
			$('#Demo').append(html);
			// show more button visible
			if(currentTimeline.length >=20)
			$('#ShowMore').show();
			
			
			$('#MoreLoading').hide();
			$('#More').show();
			
			
			/**
			 * 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 }
						);
				}
				});
			
			
			$('a.More').click(
					function(event)
					{
						getMoreTimeline();
						event.stopImmediatePropagation();
					}
				);
					
			
										
					/**
					 * Assign events on all thumbnails to view
					 */
					$('a.Favorite').click(
							function(event)
							{
								var divId = event.target.id;
								doFavorite(divId);
							}
					);
					
					
					
					
					
					$('#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 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();
						   }
					);
					
					
		
					
							
							/**
							 * Assign Events on all Delete Buttons
							 */
							$('a.Delete').click(
									function(event)
									{
										var DeleteId=event.target.id;
										deleteMyTweet(DeleteId);
									}
									
							);
				}
				else
				{
					if(currentTimeline.length <=0)
					{	
					$('#Tweets').html('');
					$('#Tweets').html('<center><br /><h1> No tweets available.</h1></center>');
					}
					else
					{
						$('#ShowMore').hide();
						$('#MoreLoading').hide();
						$('#More').show();
					}
					
				}
			}
			
			
			
			/**
			 * Assign onclick event on login button 
			 */
			$('#Login').click(
				function()
				{
					
					login('#Login');
				}
			);
			
			
			
			/**
			 * 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+"/user/"+userPage,{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;
			}
			
			/**
			 * method for opening user page
			 */
			function gotoUserPage(){
				
				var username = $.cookie('Username');
				
				window.location.href=userUrl+""+username;
			}
			
			/**
			 * Method to follow current user
			 */
			function followMe(){
				var userid = $("#userid").val();
				
				if($.cookie('Username') != "" && $.cookie('Username') != null)
				{	
				$.ajaxSetup({
		        	beforeSend: function(xhr) 
	        			{
							xhr.setRequestHeader("Accept", "text/javascript");
							xhr.setRequestHeader("Authorization",  $.cookie('twitterAuthorization'));
							xhr.setRequestHeader("twiteract-api-access-token", Base64.encode("umundo"));
						}
				});
				
				$("#FollowUser").hide();	
	           $("#FollowWaiting").show();
	           
	    	 $.post(apiHost+'/api/friendships/create/'+userPage+".json", 
	    			 function(data){
	    		 
	    		 			var response = JSON.parse(data);
				    	    if(response.result != null)
				    	    {
					    	    
					    	   
				    	    	$("#CurrentUserFollowers").html(response.result.followersCount+"<br />Followers");
						        
				    	    	 $("#FollowWaiting").hide();
				    	    	 
						        if(response.result.isFollowing == false)
						        	$("#FollowUser").show();
						        else
						        	$("#FollowUser").hide();
						        
					    	   					    	  
					    	    
				    	    }
				    	    else
				    	    {
				    	    	if(response.error.errorCode == 1121)
				                {
				                	//alert("Authentication failed. Your Twitter Username\/Password are incorrect.");
				                	var yesOrNo = confirm(response.error.errorMessage+" Please re-login with valid Username and Password.");
				                	if(yesOrNo)
				                	{
				                		logout();
				                	}
				                	else
				                	{
				                		$('#SuccessMessage').slideUp();
										$('#ErrorMsg').html(response.error.errorMessage);
										$('#ErrorMsg').slideDown();
										$("#FollowUser").hide();
										 $("#FollowWaiting").hide();
										window.scrollTo(0,50);
										startTimer();
										
				                	}
				                }
								else
								{
// else show error msg
									
									$('#SuccessMessage').slideUp();
									$('#ErrorMsg').html(response.error.errorMessage);
									$('#ErrorMsg').slideDown();
									$("#FollowUser").hide();
									 $("#FollowWaiting").hide();
									window.scrollTo(0,50);
									startTimer();
								}
								
				    	    }
	    	 		},"json" );	 
				}
				else
				{
					alert("Please login to follow me!");
				}
			}
			
			
			
			/**
			 * 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 = '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);
				
				
				/*if(repeat == "true")
				{
				 
					$("body").css("background", "url('" + bgimage + "') #"+bgcolor+" repeat fixed left top");
				}
				else
				{
					$("body").css("background", "url('" + bgimage + "') #"+bgcolor+" no-repeat fixed left top");
				}*/
				
				
				
				$('#Header_login').hide();
				
				$('#Header_user').show();
				
				$('#authorization').val($.cookie('twitterAuthorization'));
				
				$('#Home').bind("click",function(){gotoHome("friends");});
				$('#MyTweet').bind("click", function(){gotoUserPage();});
				$('#PublicTweet').bind("click", function(){gotoHome("public");});
				$('#logout').bind("click", function(){logout('#Login');});
				
				
				
								
				var currentState = $.cookie('CurrentState');
				
				if($.cookie('Username')== userPage)
				{
					readyToFetchTimeline();
						
					$.twitter.users.show(userPage,function(data)
							{
							   getUserInfoTwitter(data); 
							   
							},
							function(error)
							{
								$("#MainLoading").html("");
								$("#MainLoading").html("Sorry, this user does not exist!");
								$("#MainLoading").show();
							},"json");
				
				}
				else
				{
					
					
					$.twitter.users.show(userPage,function(data)
							{
							   getUserInfoTwitter(data); 
							   readyToFetchTimeline();
							},
							function(error)
							{
								$("#MainLoading").html("");
								$("#MainLoading").html("Sorry, this user does not exist!");
								$("#MainLoading").show();
							},"json");
				}
				
				
				
				
				var successMsg = $.cookie('SuccessMsg');
				
				
				
			
			}		
			
			/**
			 * 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");
		    }
		    
		   
		}
	);
