// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// setting a global variable be used for accessing the images hosted at s3
///var s3_asset_address = ((location.host == 'devpune.socialmedian.com' || location.host == 'pune.socialmedian.com') ? 'http://devpune.s3.amazonaws.com' : 'http://socialmedian.s3.amazonaws.com');
///var s3_static_asset_address = 'http://socialmedian.s3.amazonaws.com';
MORE_COMMENTS_FOR_3_OPEN = new Hash();
// set from generic_partial/story/_like_unlike_stories.rhtml
var HAVE_MOOD_DATA = new Hash();
//global array for tweet
var tweet_story_info = [];
/**
*	Global variables for user if user logged in.
*/
var showClipBoxOrNot = '';
var globalUserId = 0;
// global variable that holds user's newsmakers and followers for aotocomplete
var MY_SM_CONTACTS = [];
var NO_SM_CONTACTS = 0;
// global variable for storing news flash user infromation for displaying activities
var STORY_NEWS_FLASH_INFO = new Array();
/**
 *
 */
function get_url_parameter(name) {
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null )
		return "";
	else
		return results[1];
}

/**
 * Sort news networks
 */
function newsCircleSorting (sorting) {
	/**
	 * @author AA
	 * Modified the function, removed extra checking
	 */
	var firstTime = window.location.href.indexOf("?");
	var currentLocation = window.location.href;
	var locationWithoutParam = (firstTime != -1 ? currentLocation.slice(0,firstTime) : currentLocation);
	var siteURL = locationWithoutParam + '?s=' + sorting;
	window.location.href = siteURL;
}

/**
 * Show different version story weight
 */
function storyShorting (storyWeightVersion) {
	var firstTime = window.location.href.indexOf("?");
	var isRepeat = window.location.href.indexOf("&show=");
	var temp = window.location.href;
	if (firstTime != -1) {
		var temp1 = temp.slice(0,firstTime);
		var siteURL = temp1 + '?show=' + storyWeightVersion;
	} else {
		var siteURL = temp + '?show=' + storyWeightVersion;
	}
	window.location.href = siteURL;
}
/**
 * Show comment box for clip
 */
 var old_story_id = null; //global
function showCommentBox(sId, clipFlag, aId)  {
	// call clip/unclip function
	clipUnclipStory(sId, aId);
	// code to display comment box
	// display box only while clipping a story
	var showFlag = false;
	if(showClipBoxOrNot == 'y') {
		showFlag = true;
	} else {
		showFlag = false;
	}
	if(clipFlag == 0) {
		showFlag = true;
	} else {
		showFlag = false;
	}
/******
***   Removed call of function which open box for share a story while clip it.
***   Still nor removed related variables(showClipBoxOrNot-Global, showFlag-local, old_story_id-global,,, etc..), from code
*******/
//	if(showFlag == true && showClipBoxOrNot == 'y') {
		// populate html code
//		subShowClipBox(sId, aId);
//	}
}

/**
 * sub function to show comment box for clip
 */
function subShowClipBox(sId, aId) {
	// check for previously opened comment box, if exists close that box
	if(old_story_id != null) {
		$('clip_holder_main'+old_story_id).style.display = 'none';
	}
	var htmlHolder = "";
	htmlHolder = '<div id="clip_holder_main'+aId+'" style="position:absolute;top:5px;margin:0px;padding:7px 5px 10px 5px;width:455px;background-color:#EFEFEF;">'+
							'<div style="margin:0px;padding:0px 0px 6px 12px;font-family:arial;font-size:13px;font-weight:bold;">Here are some more ways you can share:</div>'+
							'<div style="margin:0px;padding:0px;background-color:#FFFFFF;">'+
								'<!-------------- Tabs for different functionalities --------------->'+
								'<div style="margin:0px;padding:0px;font-family:arial;font-size:13px;float:left;width:100%;background-color:#EFEFEF;">'+
									'<div id="write_a_comment'+aId+'" style="margin:0px;padding:5px 8px 5px 8px;float:left;background-color:#FFFFFF;border-top:1px solid #FFFFFF;border-left:1px solid #FFFFFF;" onclick="showWriteAComment('+sId+','+aId+');return false; if (MY_SM_CONTACTS.length == 0 && NO_SM_CONTACTS == 0){getMyContacts();}">Add Comment</div>'+
									'<div id="send_to_a_news_circle'+aId+'" style="margin:0px;padding:5px 8px 5px 8px;float:left;background-color:#EFEFEF;border-top:1px solid #FFFFFF;border-right:1px solid #FFFFFF;cursor:pointer;" onclick="getUsersNewsNetworks('+sId+','+aId+');return false;">Send to a News Network</div>'+
									'<div id="email_to_a_friend'+aId+'" style="margin:0px;padding:5px 8px 5px 8px;float:left;background-color:#EFEFEF;border-top:1px solid #FFFFFF;border-right:1px solid #FFFFFF;cursor:pointer;" onclick="showEmailToAFriend('+sId+','+aId+');return false;">Email to a friend</div>'+
									'<br clear="all">'+
								'</div>'+
								'<br clear="all">'+
								'<div id="clip_contents_holder'+aId+'" style="margin:0px;padding:0px;"></div>'+
							'</div>'+
							'<div style="padding:10px 8px 0px 7px;margin:0px;">';
	if(showClipBoxOrNot == 'y') {
		htmlHolder += '<div id="do_not_show_link_in_future'+aId+'" onclick="showClipBoxOrNotInFuture('+sId+','+aId+');return false;" style="padding:0px;margin:0px;float:left;font-family:arial;font-size:11px;font-weight:normal;text-decoration:underline;cursor:pointer;color:#8E8E8E;">Do not show me this box</div>';
	}
		htmlHolder += '<div style="padding:0px;margin:0px;float:right;font-family:arial;font-size:11px;font-weight:normal;text-decoration:underline;cursor:pointer;" onclick="$(\'clip_holder_main'+aId+'\').style.display=\'none\'">Close</div>'+
							'</div>'+
						'</div>';
	try {
		$('clip_comment_holder'+aId).innerHTML = htmlHolder;
		$('clip_comment_holder'+aId).style.display = "block";
		// activate write a comment tab
		showWriteAComment(sId, aId);
		old_story_id = aId;
	} catch(e){}
}

/**
 * Add comments while clipping a story
 */
var posted_comment = "";
var addClipComment = function (story_id, aId){
	if(($('user_comment'+aId).value).strip() == "") {
		alert("Please enter a comment");
		return false;
	}
	if ($('twit_id'+aId).value.strip() != "" && $('twit_pass'+aId).value.strip() != "") {
		var tweeterusername = $('twit_id'+aId).value.strip();
		var tweeterpassword = $('twit_pass'+aId).value.strip();
		if ($('save_or_not'+aId).checked) {
			var pass_save_or_not = "yes";
		} else {
			var pass_save_or_not = "no";
		}
		var formData = Form.serialize("clipCommentForm"+aId);
		var postParameters = formData+"&story_id="+story_id+"&act_id="+aId+"&tw_id="+tweeterusername+"&tw_pass="+tweeterpassword+"&save_my_tw_pass="+pass_save_or_not;
	} else {
		var tweeterusername = $('twitter_user_id').value;
		var tweeterpassword = $('twitter_user_password').value;
		var formData = Form.serialize("clipCommentForm"+aId);
		var postParameters = formData+"&story_id="+story_id+"&act_id="+aId+"&tw_id="+tweeterusername+"&tw_pass="+tweeterpassword;
	}
	try {
		postParameters += "&display_comment_count="+$('display_comment_count_'+aId).value;
	} catch(e){}
	// this is to show success message for comment post
	try{
		posted_comment = $('user_comment'+aId).value;
		$('user_comment'+aId).value = "";
		$('user_comment'+aId).focus();
	} catch(e) {}
	$('addCommentAcitvityIcon'+aId).style.visibility = 'visible';
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: function(response) {addClipCommentCallback(response, story_id)},
		// Handle 404
		on404: function(){addClipComment404Callback(aId);},
		// Handle other errors
		onFailure: function(){addClipCommentFailureCallback(aId);}
	}
	new Ajax.Request('/add-clip-comment', ajaxRequestOptions);
}
/**
 * Clip comments success callback function
 */
var addClipCommentCallback = function (response, story_id){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// hide the loading icon
	try{
		$('addCommentAcitvityIcon'+response_data.act_id).style.visibility = 'hidden';
	}catch(e){}
	//check if there is an error
	if (response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		response_data.comment_text = response_data.comment_text.gsub(/(?:\r\n|\n)/, "<br/>");
		// publish feed on facebook
		if(currentFbUserId > 0) {
			var s_comment = "\""+response_data.comment_text.strip()+"\"";
		 	if(tweet_story_info[story_id][0]!= 'story') {
				var actionText="Clip It!";
				var s_link = "http://"+location.host+"/story/"+story_id+"/"+tweet_story_info[story_id][3];
				var src=tweet_story_info[story_id][4];
		 		var title = "<a href='"+s_link+"'>"+unescape(tweet_story_info[story_id][2]).truncate(50)+"</a>"+" on <a href='"+s_link+"'>socialmedian</a>";
				var bundleData = {"actionText":actionText,"url":s_link,"images":[{"src":src,"href":s_link}],"title":title, "short_desc":unescape(tweet_story_info[story_id][2]).truncate(100), "long_desc":unescape(tweet_story_info[story_id][2]).truncate(200), "comment":s_comment};
			} else {//alert(tweet_story_info[story_id])
				var actionText="Clip It!";
				var s_link = "http://"+location.host+"/story/"+story_id+"/"+tweet_story_info[story_id][4];
				var src=tweet_story_info[story_id][5];
				var title = "<a href='"+s_link+"'>"+unescape(tweet_story_info[story_id][1])+"</a>";
				var bundleData = {"actionText":actionText,"url":s_link,"images":[{"src":src,"href":s_link}],"title":title, "short_desc":unescape(tweet_story_info[story_id][2]).truncate(100), "long_desc":unescape(tweet_story_info[story_id][2]).truncate(200), "comment":s_comment};
			}

			//var data = {"comment" : "\""+$('user_comment'+aId).value.strip()+"\"", "story_link" : "<a href='http://"+location.host+"/story/"+story_id+"/info'>...</a>"};
			publishFeedOnFb(commentBundleId, bundleData);
		}
		try {
			$('clipCommentRsponse'+response_data.act_id).innerHTML = response_data.message;
			//yellow fading technique
			startFadingColor = 0;
			fadeElementId = 'clipCommentRsponse'+response_data.act_id;
			changeBackgroundColorObject = setInterval(yellowFadingTechnique, 400);
			$('clipCommentRsponse'+response_data.act_id).style.display = "block";
		} catch(e) {}
		try {
			$('clipCommentRsponse_hotlist'+response_data.act_id).innerHTML = response_data.message;
			//yellow fading technique
			startFadingColor = 0;
			fadeElementId = 'clipCommentRsponse_hotlist'+response_data.act_id;
			changeBackgroundColorObject = setInterval(yellowFadingTechnique, 400);
			$('clipCommentRsponse_hotlist'+response_data.act_id).style.display = "block";
		} catch(e) {}
		// Hide the comment box
		try {
			$('clip_holder_main'+response_data.act_id).style.display = 'none';
		} catch(e) {}
		// show newly added comment
		try {
			if(response_data.fb_user_id > 0) {
				var userImage  = '<img id="addComment'+response_data.cmt_id+'-'+response_data.fb_user_id+'">';
			} else {
				var userImage  = '<img src="'+S3_DYNAMIC_ASSETS_PATH +'/user-images/'+response_data.cur_user_id+'-small.jpg">';
			}
			$('innerShareCommentBoxHolder'+response_data.act_id).innerHTML += '<div style="margin:0px;padding:10px 0px 0px 15px;">'+
																				'<div style="margin:0px;padding:0px;float:left;">'+userImage+'</div>'+
																				'<div style="margin:0px;padding:2px 0px 2px 5px;float:left;font-size:11px;width:450px;"><a href="http://'+APP_DOMAIN+'/'+response_data.cur_user_socialmedian_url+'/home" style="color:#2464AB;cursor:pointer;text-decoration:underline;">You</a>, <span style="color:#898989;">Just now</span> : '+response_data.comment_text+'</div>'+
																				'<br clear="all">'+
																			'</div>';
			// set fb user image
			if(response_data.fb_user_id > 0) {
				setUserImage([response_data.fb_user_id], 'square', ['addComment'+response_data.cmt_id]);
			}

		} catch(e) {}

		// change comment counts
		try {
			var arr = $('comment_link_'+response_data.act_id).innerHTML.split(" ");
			var val = parseInt(arr[0])+1;
			if(isNaN(val)) {
				$('comment_link_'+response_data.act_id).innerHTML = "1 Comment";
			} else {
				$('comment_link_'+response_data.act_id).innerHTML = val+" Comments";
			}
		} catch(e) {}
		// Comment count header
		try {
			var ofc = parseInt($('out_of_comment_'+response_data.act_id).innerHTML)+1;
			var tc = parseInt($('total_comment_'+response_data.act_id).innerHTML)+1;
			showLessCount[response_data.act_id] = showLessCount[response_data.act_id] + 1;
		    $('display_comment_count_'+response_data.act_id).value = response_data.display_comment_count;
			if(response_data.comment_count <= 3) {
				//$('commentCountHeader'+response_data.act_id).innerHTML ='Showing '+response_data.comment_count+' out of '+response_data.comment_count+' comments';
				$('out_of_comment_'+response_data.act_id).innerHTML = ofc;
				$('total_comment_'+response_data.act_id).innerHTML = tc;
			} else {
				$('out_of_comment_'+response_data.act_id).innerHTML = ofc;
				$('total_comment_'+response_data.act_id).innerHTML = tc;
				//$('commentCountHeader'+response_data.act_id).innerHTML ='Showing '+response_data.display_comment_count+' out of '+response_data.comment_count+' comments &nbsp;&nbsp;<a id="comment_view_all_link'+response_data.act_id+'" onclick="viewAllComments('+response_data.story_id+','+response_data.act_id+','+response_data.comment_count+','+response_data.display_comment_count+');" style="font-family:arial;font-size:12px;color:#696969;cursor:pointer;text-decoration:underline;">View All</a>';
			}
		} catch(e) {}

		// perform clip action and update total clip count
		performClipAction(response_data.story_id, response_data.act_id);
	}
}

/**
 * Clip comments failure callback function
 */
var addClipCommentFailureCallback = function (aId){
	// hide the loading icon
	$('addCommentAcitvityIcon'+aId).style.visibility = 'hidden';
	alert("Error on page");
}
/**
 * Clip comments 404 callback function
 */
var addClipComment404Callback= function (aId){
	// hide the loading icon
	$('addCommentAcitvityIcon'+aId).style.visibility = 'hidden';
	alert("Error page is not found");
}

/**
 * Clip/unclip a story
 */
var clipUnclipStory = function (story_id, aId, e) {
	// check for unclip action
	if($('clipUnclipStory_'+story_id)) {
		var ele = $('clipUnclipStory_'+story_id);
	} else if($('clipUnclipStory_hotlist_'+story_id)) {
		var ele = $('clipUnclipStory_hotlist_'+story_id);
	} else if($('clipUnclipStorySmallIcon'+story_id)) {
		var ele = $('clipUnclipStorySmallIcon'+story_id);
	}
	var control_multiple_clips = 0;
	var clipped = 1;
	if(ele && (ele.className == "clippedStoryPin" || ele.className == "clippedStoryPinSmall")) {
		clipped = 0;
		if(!confirm("This story will be removed from your home page. This action cannot be undone. Please confirm that you want to remove this story.")) {
			return false;
		}
	}
	// show loading image
	try {
		$('popularStoriesLoading'+story_id).style.display = 'block';
	} catch(err){}
	try {
		$('clipCommentRsponse'+aId).innerHTML = '<div style="padding:4px 0px 0px 0px;margin:0px;width:150px;">'+
													'<div style="float:left;padding:0px;margin:0px;"><img src="'+ S3_STATIC_ASSETS_PATH +'/images/loader.gif"></div>'+
													'<div style="float:left;padding:0px 0px 0px 5px;margin:0px;">Loading...</div>'+
													'<br clear="all">'+
												'</div>';
		$('clipCommentRsponse'+aId).style.display = 'block';
	} catch(err){}
	try {
		$('activity_'+ aId +'_done_by_div').innerHTML = '<div style="padding:4px 0px 0px 0px;margin:0px;width:150px;">'+
															'<div style="float:left;padding:0px;margin:0px;"><img src="'+ S3_STATIC_ASSETS_PATH +'/images/loader.gif"></div>'+
															'<div style="float:left;padding:0px 0px 0px 5px;margin:0px;">Loading...</div>'+
															'<br clear="all">'+
														'</div>';
		$('activity_'+ aId +'_done_by_div').style.display = 'block';
	} catch(err){}
	var postParameters = "story_id="+story_id+"&act_id="+aId+"&control_multiple_clips="+control_multiple_clips;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: clipUnclipStoryCallback,
		// Handle 404
		on404: clipUnclipStory404Callback,
		// Handle other errors
		onFailure: clipUnclipStoryFailureCallback
	}
	new Ajax.Request('/clip-unclip-story', ajaxRequestOptions);
}
/**
 * Clip/unclip a story success callback function
 */
var clipUnclipStoryCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track clip and unclip action
	tracAjaxFunctionalities('/clip-unclip-story');
	// hide loading image
	try {
		$('popularStoriesLoading'+response_data.story_id).style.display = 'none';
	} catch(e){}
	//check if there is an error
	if (response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		response_data.control_multiple_clips = 1;
		//if there is not error
		//change the clip image.
		try {
			var htmlHolder = "";
			try {
				htmlHolder = '<div style="margin:0px;padding:0px;float:left;font-weight:bold;width:45%;color:#F26B0D;">Clip it!</div>';
				//if(showClipBoxOrNot == 'n' && eval('user_clipped_story'+response_data.act_id) == 0) {
				//	htmlHolder += '<div style="margin:0px;padding:1px 6px 0px 0px;float:right;color:#818181;font-size:11px;font-family:arial;">'+
				//				'<a onclick="subShowClipBox('+response_data.story_id+','+response_data.act_id+');" style="text-decoration:underline;cursor:pointer;color:#818181;">Comment</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a onclick="subShowClipBox('+response_data.story_id+','+response_data.act_id+');getUsersNewsNetworks('+response_data.story_id+','+response_data.act_id+');" style="text-decoration:underline;cursor:pointer;color:#818181;">Share</a>'+
				//			'</div>';
				//}
				htmlHolder += '<br clear="all"><div style="margin:0px;padding:0px;float:left;font-weight:normal;font-size:12px;">'+response_data.message+'</div><br clear="all">';
				$('clipCommentRsponse'+response_data.act_id).innerHTML = htmlHolder;
				$('clipCommentRsponse'+response_data.act_id).style.display = "block";
				//yellow fading technique
				startFadingColor = 0;
				fadeElementId = 'clipCommentRsponse'+response_data.act_id;
				changeBackgroundColorObject = setInterval(yellowFadingTechnique, 400);

			} catch (err) {}
			// to be deleted

			if (response_data.action == "unclipped") {
				try {
	//				htmlHolder = '<div style="margin:0px;padding:0px;float:left;font-weight:bold;width:52%;color:#F26B0D;">Clip it!</div>';
					//if(showClipBoxOrNot == 'n' && eval('user_clipped_story'+response_data.story_id) == 0) {
						//htmlHolder += '<div style="margin:0px;padding:1px 6px 0px 0px;float:right;color:#818181;font-size:11px;font-family:arial;font-weight:normal;">'+
									//'<a onclick="subShowClipBox('+response_data.story_id+','+response_data.act_id+');" style="text-decoration:underline;cursor:pointer;color:#818181;">Comment</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a onclick="subShowClipBox('+response_data.story_id+','+response_data.act_id+');getUsersNewsNetworks('+response_data.story_id+','+response_data.act_id+');" style="text-decoration:underline;cursor:pointer;color:#818181;">Share</a>'+
								//'</div>';
					//}
	//				htmlHolder += '<br clear="all"><div style="margin:0px;padding:0px;float:left;font-weight:normal;font-size:12px;">'+response_data.message+'</div><br clear="all">';
	//				$('clipCommentRsponse_hotlist'+response_data.act_id).innerHTML = htmlHolder;

					var clipped_by_list = generateActivityByList(response_data.clipped_by, "clipped", {}, response_data.act_id, response_data.story_id, response_data.story_permalink);
					if(clipped_by_list != ''){
						$('activity_'+ response_data.act_id +'_done_by_div').innerHTML = clipped_by_list;
						//yellow fading technique
						startFadingColor = 0;
						fadeElementId = 'activity_'+ response_data.act_id +'_done_by_div';
						changeBackgroundColorObject = setInterval(yellowFadingTechnique, 400);
					}else{
						$('activity_'+ response_data.act_id +'_div').style.display = 'none';
					}
				} catch (e) {}

				//for other clips (other than hotlist)
				try{
					$('clipUnclipStory_'+response_data.act_id).className = "unclippedStoryPin";
					$('clipUnclipStory_'+response_data.act_id).title = "Add to my Clips";
				} catch (e) {}
				//for hotlist clips
				try{
					$('clipUnclipStory_hotlist_'+response_data.act_id).className = "unclippedStoryPin";
					$('clipUnclipStory_hotlist_'+response_data.act_id).title = "Add to my Clips";
				} catch (e) {
				}
				//remove story when user is on his profile page
				try {
					$('clipUnclipStoryOuterDiv_'+response_data.story_id).style.display = "none";
					$('clipUnclipStoryOuterDiv_'+response_data.story_id).innerHTML = "";
				} catch (e) {
				}
				eval('user_clipped_story'+response_data.story_id+'=0');
			} else if (response_data.action == "clipped") {
				try {
	//				htmlHolder = '<div style="margin:0px;padding:0px;float:left;font-weight:bold;width:52%;color:#F26B0D;">Clip it!</div>';
					//if(showClipBoxOrNot == 'n' && eval('user_clipped_story'+response_data.story_id) == 0) {
						//htmlHolder += '<div style="margin:0px;padding:1px 6px 0px 0px;float:right;color:#818181;font-size:11px;font-family:arial;font-weight:normal;">'+
									//'<a onclick="subShowClipBox('+response_data.story_id+','+response_data.act_id+');" style="text-decoration:underline;cursor:pointer;color:#818181;">Comment</a>&nbsp;&nbsp;|&nbsp;&nbsp;<a onclick="subShowClipBox('+response_data.story_id+','+response_data.act_id+');getUsersNewsNetworks('+response_data.story_id+','+response_data.act_id+');" style="text-decoration:underline;cursor:pointer;color:#818181;">Share</a>'+
								//'</div>';
					//}
	//				htmlHolder += '<br clear="all"><div style="margin:0px;padding:0px;float:left;font-weight:normal;font-size:12px;">'+response_data.message+'</div><br clear="all">';
	//				$('clipCommentRsponse_hotlist'+response_data.act_id).innerHTML = htmlHolder;

					var clipped_by_list = generateActivityByList(response_data.clipped_by, "clipped", response_data.current_user, response_data.act_id, response_data.story_id, response_data.story_permalink);

					$('activity_'+ response_data.act_id +'_done_by_div').innerHTML = clipped_by_list;

					// set fb user image
					if(response_data.current_user.fb_connect_status == "connected" || response_data.current_user.fb_connect_status == "merged") {
						setUserImage([response_data.current_user.fb_user_id], 'square', ['activityPic'+response_data.act_id]);
					}

					//yellow fading technique
					startFadingColor = 0;
					fadeElementId = 'activity_'+ response_data.act_id +'_done_by_div';
					changeBackgroundColorObject = setInterval(yellowFadingTechnique, 400);
				} catch (e) {}

				try {
					// If user not yet clipped any story, then rediect to home page
					if($('clips-container').innerHTML.strip() == "") {
						window.location = "/"+response_data.author+"/home";
						return;
					}
				} catch(e) {}
				//for other clips (other than hotlist)
				try {
					$('clipUnclipStory_'+response_data.act_id).className = "clippedStoryPin";
					$('clipUnclipStory_'+response_data.act_id).title = "Remove this Clip";
				} catch (e) {}
				//for hotlist clips
				try {
					$('clipUnclipStory_hotlist_'+response_data.act_id).className = "clippedStoryPin";
					$('clipUnclipStory_hotlist_'+response_data.act_id).title = "Remove this Clip";
				} catch (e) {}
				eval('user_clipped_story'+response_data.story_id+'=1');

				// publish activity on facebook
				if(currentFbUserId > 0 && tweet_story_info[response_data.story_id] != undefined) {
				 	if(tweet_story_info[response_data.story_id][0] != 'story') {
						var actionText="Clip It!";
						var s_link = "http://"+location.host+"/story/"+response_data.story_id+"/"+tweet_story_info[response_data.story_id][3];
						var src=tweet_story_info[response_data.story_id][4];
				 		var title = "<a href='"+s_link+"'>"+unescape(tweet_story_info[response_data.story_id][2]).truncate(50)+"</a>"+" on <a href='"+s_link+"'>socialmedian</a>";
						var bundleData = {"actionText":actionText,"url":s_link,"images":[{"src":src,"href":s_link}],"title":title, "short_desc":unescape(tweet_story_info[response_data.story_id][2]).truncate(100), "long_desc":unescape(tweet_story_info[response_data.story_id][2]).truncate(200)};
					} else {
						var actionText="Clip It!";
						var s_link = "http://"+location.host+"/story/"+response_data.story_id+"/"+tweet_story_info[response_data.story_id][4];
						var src=tweet_story_info[response_data.story_id][5];
						var title = "<a href='"+s_link+"'>"+unescape(tweet_story_info[response_data.story_id][1])+"</a>";
						var bundleData = {"actionText":actionText,"url":s_link,"images":[{"src":src,"href":s_link}],"title":title, "short_desc":unescape(tweet_story_info[response_data.story_id][2]).truncate(100), "long_desc":unescape(tweet_story_info[response_data.story_id][2]).truncate(200)};
					}
					publishFeedOnFb(clipBundleId, bundleData);
				}
			}
			// update clips total count
			var str = "";
			if(response_data.total_clips == 0 || response_data.total_clips > 1) {
				str = "Clips";
			} else {
				str = "Clip";
			}
			try {
				$('clipUnclipStory_'+response_data.act_id).innerHTML = '<div align="center" class="clipCountHolder">'+response_data.total_clips+'</div>'+
												  '<div align="center" class="clipText">'+str+'</div>';
			} catch(e) {}
			try {
				$('clipUnclipStory_hotlist_'+response_data.act_id).innerHTML = '<div align="center" class="clipCountHolder">'+response_data.total_clips+'</div>'+
												  '<div align="center" class="clipText">'+str+'</div>';
			} catch(e) {}
			// update images for different activities with the same story
			changeSameStoriesImage(response_data.story_id, response_data.action,response_data.total_clips);
			// update images and clips count in users page
			updateClipCountNImages(response_data.story_id, response_data.total_clips)
		} catch (e) {}
	}
}
/**
 * Clip/unclip a story failure callback function
 */
var clipUnclipStoryFailureCallback = function (){
	alert("Error on page");
}
/**
 * Clip/unclip a story 404 callback function
 */
var clipUnclipStory404Callback = function (){
	alert("Error page is not found");
}

// to update fb user info dynamically
var FbUserInfo = {};
function setUserImage(fbUserIds, picSize, idsStr) {
	var reqIds = [];
	for(i=0;i<fbUserIds.length;i++){
		if(FbUserInfo[fbUserIds[i]] == undefined){
			reqIds.push(fbUserIds[i]);
		}
	}
	if(reqIds.length > 0){
		//FB_RequireFeatures(["Api"], function(){
			//FB.Facebook.init(FB_APP_API_KEY, CHANNEL_PATH);
			var api = FB.Facebook.apiClient;
			var sql = "SELECT uid,pic_square_with_logo,pic_with_logo,pic_big from user WHERE uid IN ("+reqIds.join(",")+")";
			api.fql_query(sql, function(result){
				for(i=0;i<result.length;i++){
					var uid = result[i].uid;
					var picSquare = ((result[i].pic_square_with_logo == "" || result[i].pic_square_with_logo == null) ? "http://static.ak.connect.facebook.com/pics/q_silhouette_logo.gif" : result[i].pic_square_with_logo.replace(/\&amp;/g,'&'));
					var picNormal = ((result[i].pic_big == "" || result[i].pic_big == null) ? "http://static.ak.fbcdn.net/pics/d_silhouette.gif" : result[i].pic_big.replace(/\&amp;/g,'&'));
					var picLarge = ((result[i].pic_with_logo == "" || result[i].pic_with_logo == null) ? "http://static.ak.connect.facebook.com/pics/d_silhouette_logo.gif" : result[i].pic_with_logo.replace(/\&amp;/g,'&'));
					FbUserInfo[uid] = {"uid" : uid, "pic_square" : picSquare, "pic_large" : picLarge, "pic_normal" : picNormal};
				}
				processFbUserImage(fbUserIds, picSize, idsStr);
			});
		//});
	} else {
		processFbUserImage(fbUserIds, picSize, idsStr);
	}
}

// show facebook user profile image
var processFbUserImage = function(fbUserIds, picSize, idsStr){
	var dim = (picSize == "square" ? "20" : "100");
	for(i=0;i<fbUserIds.length;i++){
		var ele = $(idsStr[i]+"-"+fbUserIds[i]);
		ele.src = FbUserInfo[fbUserIds[i]]["pic_"+picSize];
		if(picSize != "normal") {
			ele.width = dim;
			ele.height = dim;
		}
	}
}

var generateActivityByList = function (activity_by_array, activity, current_user, act_id, story_id, story_permalink){
	var recent_or_home = 0;
	try {
		var recent_or_home = (recent_activity == 1) ? -1 : 0;
	} catch(e){}
	var activity_by_list = '';
	var total_other_users = activity_by_array.length;
	var display_users_counter = 0;
	if(activity == 'news_flash') {
		activity_by_list = activity_by_list+get_users_concatenated_by('News flash&nbsp;by&nbsp;');
	}
	if(current_user.socialmedian_url){
		populateUserInfoArray(current_user);
		activity_by_list = activity_by_list
						+'<div style="height:20px;margin:0px;padding:0px;float:left;">'
						+'	<table cellspacing="0" cellspadding="0"><tr><td valign="bottom" style="height:27px;">'
						+'		<div style="margin:0px;padding:0px;"> '
						+'			<a href="http://'+APP_DOMAIN+'/'+ current_user.socialmedian_url +'/" style="text-decoration:none;color:#2364a9;" onmouseover="Javascript: createUserShortInfoTemplate('+ current_user.id +',\'user_'+ current_user.id +'_'+ act_id +'_detail\', \''+ current_user.socialmedian_url +'\','+ recent_or_home +');" onmouseout="Javascript: $(\'user_'+ current_user.id +'_'+ act_id +'_detail\').style.display = \'none\';">';
									if(current_user.fb_connect_status == "connected" || current_user.fb_connect_status == "merged") {
										activity_by_list = activity_by_list
						+'				<img id="activityPic'+act_id+'-'+current_user.fb_user_id+'" /> <u>You</u>';
									} else {
										activity_by_list = activity_by_list
						+'				<img src="'+S3_DYNAMIC_ASSETS_PATH +'/user-images/'+ current_user.id +'-small.jpg"> <u>You</u>';
									}
						activity_by_list = activity_by_list
						+'			</a>';
		if(Prototype.Browser.IE){
			activity_by_list = activity_by_list
						+'			<div id="user_'+ current_user.id +'_'+ act_id +'_detail" class="userDetailsContainer" onmouseenter="Javascript: $(\'user_'+ current_user.id +'_'+ act_id +'_detail\').style.display = \'block\';" onmouseleave="Javascript: $(\'user_'+ current_user.id +'_'+ act_id +'_detail\').style.display = \'none\';">'
						+'			</div>';
		}else{
			activity_by_list = activity_by_list
						+'			<div id="user_'+ current_user.id +'_'+ act_id +'_detail" class="userDetailsContainer" onmouseover="Javascript: $(\'user_'+ current_user.id +'_'+ act_id +'_detail\').style.display = \'block\';" onmouseout="Javascript: $(\'user_'+ current_user.id +'_'+ act_id +'_detail\').style.display = \'none\';">'
						+'			</div>';
		}
		activity_by_list = activity_by_list
						+'		</div>'
						+'	</td></tr></table>'
						+' </div> ';
		display_users_counter++;
	}

	var total_other_users1 = (display_users_counter == 0) ? total_other_users-1 : total_other_users;
	for(var i = 0;i <= 3 && i < total_other_users; i++){
		var code_string = '';
		code_string = code_string
					+'<div style="height:20px;margin:0px;padding:0px;float:left;">'
					+'	<table cellspacing="0" cellspadding="0"><tr><td valign="bottom" style="height:27px;">'
					+'		<div style="margin:0px;padding:0px;"> '
					+'			<a href="http://'+APP_DOMAIN+'/'+ activity_by_array[i].socialmedian_url +'/" style="text-decoration:none;color:#2364a9;" onmouseover="Javascript: createUserShortInfoTemplate('+ activity_by_array[i].user_id +',\'user_'+ activity_by_array[i].user_id +'_'+ act_id +'_detail\', \''+ activity_by_array[i].socialmedian_url +'\','+ recent_or_home +');" onmouseout="Javascript: $(\'user_'+ activity_by_array[i].user_id +'_'+ act_id +'_detail\').style.display = \'none\';">'
					+'  			<img src="'+S3_DYNAMIC_ASSETS_PATH +'/user-images/'+ activity_by_array[i].user_id +'-small.jpg"> <u>' + activity_by_array[i].socialmedian_url + '</u>'
					+'			</a>';
		if(Prototype.Browser.IE){
			code_string = code_string
					+'			<div id="user_'+ activity_by_array[i].user_id +'_'+ act_id +'_detail" class="userDetailsContainer" onmouseenter="Javascript: $(\'user_'+ activity_by_array[i].user_id +'_'+ act_id +'_detail\').style.display = \'block\';" onmouseleave="Javascript: $(\'user_'+ activity_by_array[i].user_id +'_'+ act_id +'_detail\').style.display = \'none\';">'
					+'			</div>';
		}else{
			code_string = code_string
					+'			<div id="user_'+ activity_by_array[i].user_id +'_'+ act_id +'_detail" class="userDetailsContainer" onmouseover="Javascript: $(\'user_'+ activity_by_array[i].user_id +'_'+ act_id +'_detail\').style.display = \'block\';" onmouseout="Javascript: $(\'user_'+ activity_by_array[i].user_id +'_'+ act_id +'_detail\').style.display = \'none\';">'
					+'			</div>';
		}
		code_string = code_string
					+'		</div>'
					+'	</td></tr></table>'
					+' </div> ';

		if((display_users_counter < 3) && (display_users_counter == total_other_users1))
		{
			if(display_users_counter == 0)
		    {
		    	activity_by_list+=code_string;
		    }
		    else
		    {
		    	activity_by_list = activity_by_list + get_users_concatenated_by(' and ') + code_string;;
			}
		}
		else if(display_users_counter>=3 && display_users_counter <= total_other_users1)
		{
			var left_other = total_other_users1 - display_users_counter + 1;
			activity_by_list = activity_by_list
							+'<div style="margin:0px;padding:0px;float:left;">'
							+'	<table cellspacing="0" cellspadding="0"><tr><td valign="bottom" style="height:27px;">'
							+' 		and '
							+'		<a href="http://'+APP_DOMAIN+'/story/'+ story_id +'/'+ story_permalink +'" style="text-decoration:underline;">'
							+ 			left_other
							+ 			(left_other > 1 ? ' other people' : ' other person')
							+'		</a>'
							+'	</td></tr></table>'
							+'</div>';
			break;
		}
		else
		{
		    if(display_users_counter == 0)
		    {
		    	activity_by_list+=code_string;
		    }
		    else
		    {
		    	activity_by_list = activity_by_list + get_users_concatenated_by(', ') + code_string;
		    }
		}
		display_users_counter++;
	}
	if(activity_by_list != '' && activity != 'news_flash') {
		activity_by_list = activity_by_list+get_users_concatenated_by(activity +' a story');
	}
	return activity_by_list
}

/**
  * AA 09/12/08
  * return the user concatenated string on home pages for activities
  * @param innter_text
  * @return innerhtml for the concatenation.
  */
 function get_users_concatenated_by(innter_text){
 	var contentHtml = '<div style="margin:0px;padding:0px;float:left;">'
						+'	<table cellspacing="0" cellspadding="0"><tr><td valign="bottom" style="height:27px;">'
						+ 		innter_text
						+'	</td></tr></table>'
						+'</div>';
	return contentHtml;
 }

/**
 * perform clip action on comment, share story with news nwtwork and share story by email
 * @modified by alpesh/ajay
 * @date 05 oct, 2008
 * @added total_clips variable contain the story clip count
 */
function performClipAction(story_id, act_id, total_clips) {
	var proceed_further_or_not = 0;
	try {
		if($('clipUnclipStory_hotlist_'+story_id).className == "unclippedStoryPin") {
			proceed_further_or_not = 1;
		}
	} catch(e) {}
	try {
		if($('clipUnclipStory_'+act_id).className == "unclippedStoryPin") {
			proceed_further_or_not = 1;
		}
	} catch(e) {}
	if(proceed_further_or_not == 1) {
		//for hotlist clips
		try {
			$('clipUnclipStory_hotlist_'+story_id).className = "clippedStoryPin";
			$('clipUnclipStory_hotlist_'+story_id).title = "Remove this Clip";
		} catch (e) {}

		//for other clips (other than hotlist)
		try {
			$('clipUnclipStory_'+act_id).className = "clippedStoryPin";
			$('clipUnclipStory_'+act_id).title = "Remove this Clip";
		} catch (e) {}
		var str = "";
		if(total_clips == null){
			try{
				total_clips = parseInt(response_data.total_clips)+1;
			}catch(e){}
		}
		if(total_clips > 1) {
			str = "Clips";
		} else {
			str = "Clip";
		}
		try {
			$('clipUnclipStory_'+act_id).innerHTML = '<div align="center" class="clipCountHolder">'+total_clips+'</div>'+
											  '<div align="center" class="clipText">'+str+'</div>';
		} catch(e) {}
		// update images for different activities with the same story
		changeSameStoriesImage(story_id, "clipped", total_clips);
		eval('user_clipped_story'+story_id+'=1');
	}
}

/**
 * Vote for a tag
 */
var voteForTag = function (news_circle_id, news_circle_tag_id, tag_id, tag_vote){
	var postParameters = "news_circle_id="+news_circle_id+"&news_circle_tag_id="+news_circle_tag_id+"&tag_id="+tag_id+"&tag_vote="+tag_vote;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: voteForTagCallback,
		// Handle 404
		on404: voteForTag404Callback,
		// Handle other errors
		onFailure: voteForTagFailureCallback
	}
	new Ajax.Request('/vote_for_topic', ajaxRequestOptions);
}
/**
 * Vote for a tag success callback function
 */
var voteForTagCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track 'vote for topic' action
	tracAjaxFunctionalities('/vote_for_topic');
	if(response_data.error == 1) {
		alert(response_data.message);
	} else {
		if (response_data.up_image == "active") {
			$("voteForTagUp_"+response_data.tag_id).src =  S3_STATIC_ASSETS_PATH + "/images/aupmod.gif";
			$("voteForTagUp_"+response_data.tag_id).onmouseover= function(){$("voteForTagUp_"+response_data.tag_id).src= S3_STATIC_ASSETS_PATH +'/images/auproll.gif';};
			$("voteForTagUp_"+response_data.tag_id).onmouseout= function(){$("voteForTagUp_"+response_data.tag_id).src=  S3_STATIC_ASSETS_PATH + '/images/aupmod.gif';};
		} else {
			$("voteForTagUp_"+response_data.tag_id).src = S3_STATIC_ASSETS_PATH + "/images/aupgray.gif";
			$("voteForTagUp_"+response_data.tag_id).onmouseover= function(){$("voteForTagUp_"+response_data.tag_id).src= S3_STATIC_ASSETS_PATH + '/images/auproll.gif';};
			$("voteForTagUp_"+response_data.tag_id).onmouseout= function(){$("voteForTagUp_"+response_data.tag_id).src=  S3_STATIC_ASSETS_PATH + '/images/aupgray.gif';};
		}
		if (response_data.down_image == "active") {
			$("voteForTagDown_"+response_data.tag_id).src = S3_STATIC_ASSETS_PATH + "/images/adownmod.gif";
			$("voteForTagDown_"+response_data.tag_id).onmouseover= function(){$("voteForTagDown_"+response_data.tag_id).src= S3_STATIC_ASSETS_PATH + '/images/adownroll.gif';};
			$("voteForTagDown_"+response_data.tag_id).onmouseout= function(){$("voteForTagDown_"+response_data.tag_id).src= S3_STATIC_ASSETS_PATH + '/images/adownmod.gif';};
		} else {
			$("voteForTagDown_"+response_data.tag_id).src = S3_STATIC_ASSETS_PATH + "/images/adowngray.gif";
			$("voteForTagDown_"+response_data.tag_id).onmouseover= function(){$("voteForTagDown_"+response_data.tag_id).src= S3_STATIC_ASSETS_PATH + '/images/adownroll.gif';};
			$("voteForTagDown_"+response_data.tag_id).onmouseout= function(){$("voteForTagDown_"+response_data.tag_id).src= S3_STATIC_ASSETS_PATH + '/images/adowngray.gif';};
		}
		$("totalVoteForTag_"+response_data.tag_id).innerHTML = "(Score: "+response_data.total_vote+" Total Vote: "+(response_data.total_user_vote==null?"0":response_data.total_user_vote)+")";
		for (i=0; i<totalVoteForTagIDs.length; i++) {
			$("totalVoteForTag_"+totalVoteForTagIDs[i]).style.display = "block";
		}
	}
}
/**
 * Vote for a tag failure callback function
 */
var voteForTagFailureCallback = function (){
	alert("Error on page");
}
/**
 * Vote for a tag 404 callback function
 */
var voteForTag404Callback= function (){
	alert("Error page is not found");
}

/**
 * Vote for a feed
 */
var voteForFeed = function (news_circle_id, news_circle_feed_id, feed_id, feed_vote){
	var postParameters = "news_circle_id="+news_circle_id+"&news_circle_feed_id="+news_circle_feed_id+"&feed_id="+feed_id+"&feed_vote="+feed_vote;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: voteForFeedCallback,
		// Handle 404
		on404: voteForFeed404Callback,
		// Handle other errors
		onFailure: voteForFeedFailureCallback
	}
	new Ajax.Request('/vote_for_feed', ajaxRequestOptions);
}
/**
 * Vote for a feed success callback function
 */
var voteForFeedCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track 'vote for feed' action
	tracAjaxFunctionalities('/vote_for_feed');
	if(response_data.error == 1) {
		alert(response_data.message);
	} else {
		if (response_data.up_image == "active") {
			$("voteForFeedUp_"+response_data.feed_id).src = S3_STATIC_ASSETS_PATH + "/images/aupmod.gif";
			$("voteForFeedUp_"+response_data.feed_id).onmouseover= function(){$("voteForFeedUp_"+response_data.feed_id).src= S3_STATIC_ASSETS_PATH + '/images/auproll.gif';};
			$("voteForFeedUp_"+response_data.feed_id).onmouseout= function(){$("voteForFeedUp_"+response_data.feed_id).src=S3_STATIC_ASSETS_PATH + '/images/aupmod.gif';};
		} else {
			$("voteForFeedUp_"+response_data.feed_id).src = S3_STATIC_ASSETS_PATH + "/images/aupgray.gif";
			$("voteForFeedUp_"+response_data.feed_id).onmouseover= function(){$("voteForFeedUp_"+response_data.feed_id).src= S3_STATIC_ASSETS_PATH + '/images/auproll.gif';};
			$("voteForFeedUp_"+response_data.feed_id).onmouseout= function(){$("voteForFeedUp_"+response_data.feed_id).src= S3_STATIC_ASSETS_PATH + '/images/aupgray.gif';};
		}
		if (response_data.down_image == "active") {
			$("voteForFeedDown_"+response_data.feed_id).src = S3_STATIC_ASSETS_PATH + "/images/adownmod.gif";
			$("voteForFeedDown_"+response_data.feed_id).onmouseover= function(){$("voteForFeedDown_"+response_data.feed_id).src=S3_STATIC_ASSETS_PATH + '/images/adownroll.gif';};
			$("voteForFeedDown_"+response_data.feed_id).onmouseout= function(){$("voteForFeedDown_"+response_data.feed_id).src=S3_STATIC_ASSETS_PATH +'/images/adownmod.gif';};
		} else {
			$("voteForFeedDown_"+response_data.feed_id).src = S3_STATIC_ASSETS_PATH + "/images/adowngray.gif";
			$("voteForFeedDown_"+response_data.feed_id).onmouseover= function(){$("voteForFeedDown_"+response_data.feed_id).src=S3_STATIC_ASSETS_PATH + '/images/adownroll.gif';};
			$("voteForFeedDown_"+response_data.feed_id).onmouseout= function(){$("voteForFeedDown_"+response_data.feed_id).src=S3_STATIC_ASSETS_PATH + '/images/adowngray.gif';};
		}
		$("totalVoteForFeed_"+response_data.feed_id).innerHTML = "(Score: "+response_data.total_vote+" Total Vote: "+(response_data.total_user_vote==null?"0":response_data.total_user_vote)+")";
		for (i=0; i<totalVoteForFeedIDs.length; i++) {
			$("totalVoteForFeed_"+totalVoteForFeedIDs[i]).style.display = "block";
		}
	}
}

/**
 * Vote for a feed failure callback function
 */
var voteForFeedFailureCallback = function (){
	alert("Error on page");
}
/**
 * Vote for a feed 404 callback function
 */
var voteForFeed404Callback= function (){
	alert("Error page is not found");
}

/////////////////////
//Validate username of url.
/////////////////////

var checkUserNameAndSubmit = function (){
	if(off == true) { // this is used to fix form submit on enter key press (for opera and safari)
		return false;
	}
	var error_message = '';
	var userEmail = $('user_email').value.strip();
	var userPassword = $('user_password').value.strip();
	var userName = $('user_socialmedian_url').value.strip();
	if(userEmail == '') {
		error_message = "Email should not be blank";
	} else if(userPassword == '') {
		error_message = "Password should not be blank";
	} else if(userName.match(/[^a-zA-z0-9_\-]/)!=null) {
		error_message = "Username must be one word or contain '_' or '-'";
	} else if(userName.length < 2 || userName.length > 20) {
		error_message = 'Username must be 2 to 20 characters long.';
	} else if(userName=='username') {
		error_message = 'Fill a unique username for url';
	} else if(userName=='') {
		error_message = 'Fill a unique username for url';
	}
	if (error_message != '') {
		$('signup_error_div').innerHTML = error_message;
	 	return false;
	} else {
		document.signup.submit();
	}
}
//Email Portion

/********************
**Email Validation.
********************/
var emailCheck = function (str) {

		var at="@"
		var dot="."
		var lat=str.indexOf(at)
		var lstr=str.length
		var ldot=str.indexOf(dot)
		if (str.indexOf(at)==-1){
  	       return "One or more E-mail ID(s) are invalid !!";
		}

		if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		   return "One or more E-mail ID(s) are invalid !!";
		}

		if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		    return "One or more E-mail ID(s) are invalid !!";
		}

		 if (str.indexOf(at,(lat+1))!=-1){
		    return "One or more E-mail ID(s) are invalid !!";
		 }

		 if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		    return "One or more E-mail ID(s) are invalid !!";
		 }

		 if (str.indexOf(dot,(lat+2))==-1){
		    return "One or more E-mail ID(s) are invalid !!";
		 }

		 if (str.indexOf(" ")!=-1){
		    return "One or more E-mail ID(s) are invalid !!";
		 }
 	  return ''
	}

////////////////////////////
//Remove Unwanted spaces from the string, made a function of class String.
////////////////////////////
String.prototype.trim = function(){
	   var string = this;

   		//Remove leading spaces
   		while(string.charAt(0) == " ")
	      string = string.substring(1, string.length);

   		//Remove trailing spaces
	   while(string.charAt(string.length-1) == " ")
	      string = string.substring(string, string.length-1);

	   return string;
	}
/**
 * sendMail
 */
var clipMailFlag;
var sendMail = function (clipMail, aId){
	clipMailFlag = clipMail;
	var error_message = '';
	// Email must not blank blank or not
	if($('recipient_email').value=='' || $('recipient_email').value=='Type Email-id')
	{
		error_message = "Enter a valid Email-Id !!";
	}
	else if($('message').value.length >=300)
	{
		// If message is more than 300 character
		error_message = "Write message upto 300 characters only !!";
	}
	else
	{
		//Check email ids are valid or not.
		var emails = $('recipient_email').value.split(',');
		var arrlen = emails.length;
		for (var i=0; i<arrlen; i++)
		{
			error_message = emailCheck(emails[i].trim());
			if (error_message != '') break;
		}
	}
	// If error_message contains error message, means invalidate, display it.
	if(error_message != '')
	{
		//Alert By filling error div.
		$('email_error_div').innerHTML = '';
		$('email_error_div').style.color = "red";
		$('email_error_div').innerHTML = error_message;
		return false;
	}

	var postParameters = Form.serialize("mailForm");//"story_id="+story_id;
	postParameters += "&act_id="+aId;
	try{
		$('submit_comment_button').style.display ='none';
		$('activity_loading_symbol').style.display ='block';
	} catch (e) {}
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: storyMailForFeedCallback,
		// Handle 404
		on404: storyMailForFeed404Callback,
		// Handle other errors
		onFailure: storyMailForFeedFailureCallback
	}
	new Ajax.Request('/story/share-with-friend', ajaxRequestOptions);
}
/**
 * sendMail success callback function
 */
var storyMailForFeedCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track 'share story with friend' action
	tracAjaxFunctionalities('/story/share-with-friend');
	if(response_data.error == 1) {
		alert(response_data.message);
	}
	else{
		if(clipMailFlag == 1) {
			try {
				$('clipCommentRsponse'+response_data.act_id).innerHTML = response_data.message;
				//yellow fading technique
				startFadingColor = 0;
				fadeElementId = 'clipCommentRsponse'+response_data.act_id;
				changeBackgroundColorObject = setInterval(yellowFadingTechnique, 400);
				$('clipCommentRsponse'+response_data.act_id).style.display = "block";
			} catch(e) {}
			try {
				$('clipCommentRsponse_hotlist'+response_data.act_id).innerHTML = response_data.message;
				//yellow fading technique
				startFadingColor = 0;
				fadeElementId = 'clipCommentRsponse_hotlist'+response_data.act_id;
				changeBackgroundColorObject = setInterval(yellowFadingTechnique, 400);
				$('clipCommentRsponse_hotlist'+response_data.act_id).style.display = "block";
			} catch(e) {}
			// Hide the comment box
			try {
				$('clip_holder_main'+response_data.act_id).style.display = 'none';
			} catch(e) {}
			try {
				$('comment_link_'+response_data.act_id+'_div').className = "commentStoryBackgroundInactive";
				$('share_link_'+response_data.act_id+'_div').className = "shareStoryBackgroundInactive";
				$('commentShareBoxHolder'+response_data.act_id).style.display = "none";
			} catch(e) {}

			// perform clip action and update total clip count
			performClipAction(response_data.story_id, response_data.act_id);
		} else {
			$('email_error_div').style.color = "green";
			$('email_error_div').innerHTML = response_data.message;
			$('recipient_email').value='';
			$('message').value='';
			if(response_data.comment_on_email=='comment') {
				window.location = response_data.refresh_story
			}
		}
	}
}
/**
 * sendMail failure callback function
 */
var storyMailForFeedFailureCallback = function (){
	alert("Error on page");
}
/**
 * sendMail 404 callback function
 */
var storyMailForFeed404Callback= function (){
	alert("Error page is not found");
}

/**
 * Report a bug
 */
var dontCloseTheFeatureWindow = 0;
var sendBugReport = function (){
	/**
	 * KD 04/12/08
	 * Check if summary field is blank or not.
	 */
	if($('bug_Summary').value.strip()==""){
		alert("Please enter the summary.");
		$('bug_Summary').focus();
		return false;
	}
	$('loading_bug').style.display = 'block';
	var postParameters = Form.serialize("mailBugReport");
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: bugReportForFeedCallback,
		// Handle 404
		on404: bugReportForFeed404Callback,
		// Handle other errors
		onFailure: bugReportForFeedFailureCallback
	}
	new Ajax.Request('/report-bug', ajaxRequestOptions);
	//alert("Testing for Bug report -- " + postParameters);
}
/**
 * bugMail success callback function
 */
var bugReportForFeedCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	if(response_data.error == 1) {
		alert(response_data.message);
	}
	else{
		alert(response_data.message);
		if (dontCloseTheFeatureWindow!=1) {
			$('mail_bug_div').style.display='none';
		} else {
			window.close();
		}
	}
	$('loading_bug').style.display = 'none';
	$('bug_Summary').value = '';
	$('bug_message').value = '';
}
/**
 * bugMail failure callback function
 */
var bugReportForFeedFailureCallback = function (){
	alert("Error on page");
	$('loading_bug').style.display = 'none';
}
/**
 * bugMail 404 callback function
 */
var bugReportForFeed404Callback= function (){
	alert("Error page is not found");
	$('loading_bug').style.display = 'none';
}


/**
 * Open a snip dialog box
 *
 * @newsCircle => 0|1, from user page or news network page
 */
//var snipDesc = "A snip, short for snippet, is a short note. Do you Twitter? A snip is like a tweet.\n\nWe'll automatically share your snip with any relevant News Networks you belong to.";
var snipDesc = "Post a short note.";

 function addSnipDialogBox(newsCircle)
 {
 	$('news_success_message').style.display='none';

	// Hide add news dialog box
	try {
		$('news_box').style.display = "none";
	} catch(e) {}

	// Open Add a new snip dialogbox
 	document.getElementById('add_snip_holder').innerHTML = '<div id="add_snip" name="addSnip" style="position: absolute;display:block;background-color:#EFEFEF;padding:10px;margin:0px;border:1px solid #c7c7c7;font-size:14px;">'+
									'<form id="addSnipForm" name="addSnipForm" style="margin:0px;padding:0px;">'+
										'<div style="font-weight:bold;font-family:arial;font-size:15px">Add a Snip</div>'+
										'<textarea onfocus="showUserDescription(this.value,\'description\',\'snipDesc\');" id="description" name="description" style="width:250px; height:100px;">'+snipDesc+'</textarea></p>'+
							 			'<div align="right" style="margin:0px;padding:0px;">'+
							 				'<div id="loading_image" align="center" style="margin:0px;padding:0px;font-size:13px;font-family:arial;font-weight:normal;float:left;width:170px;display:none;">'+
												'<div style="padding:0px;margin:0px;width:120px;">'+
													'<div style="float:left;padding:0px;margin:0px;"><img src="'+ S3_STATIC_ASSETS_PATH + '/images/loader.gif"></div>'+
													'<div style="float:left;padding:0px 0px 0px 5px;margin:0px;">Adding a Snip...</div>'+
													'<br clear="all">'+
												'</div>'+
											'</div>'+
											'<div style="margin:0px;padding:0px 10px 0px 0px;float:right;">'+
												'<input type="button" id="add_snip_button" name="add snip" onclick="addSnip('+newsCircle+');" value="Add">'+
							 					'<a href="" onClick="$(\'add_snip\').style.display=\'none\';return false;" style="margin-left:3px">close</a>'+
											'</div>'+
											'<br clear="all">'+
										'</div>'+
									'</form>'+
								'</div>';
 }

/**
 * Add a snip
 *
 * @newsCircle => 0|1, from user page or news network page
 */
// global variable to hold information about other pages (1 => other than nn page and home page)
var snip_other_page;

// Global variable used for callback function
var newsCircleOrUserPage=0;

var addSnip = function (newsCircle,other_page){
	snip_other_page = other_page;
	var errorMessage = '';
	var sharedNetworks ='' ;
	var autoshare = $('snip_auto_sharing_yes').checked;
	var description = $('description').value.strip();
	// Check snip value blank or not
	if(description.length == 0) {
		// Display error
		$('description').value = '';
		$('description').focus();
		errorMessage = "Please enter Snip description";
	} else if(description.strip() == snipDesc) {
		errorMessage = "Please enter description";
		$('description').value = '';
	} else if(description.length >=300) {
		// If description is more than 300 character
		errorMessage = "Enter upto 300 character";
	} else if(!autoshare){
		if(networks_selected.length > 0){
				networks_selected.each(function(element, index){
				sharedNetworks += '&sn['+ index + ']=' + element;
				});
				networks_selected = [];
				$('selected_news_networks').innerHTML = '';

		}
		else
		{
			errorMessage = 'When not auto sharing you must choose one of the networks to share with';
		}
	}

	// If error_message is not blank display error
	if(errorMessage != '') {
		//show error message
		try {
			$('snip_success_message').style.color = "red";
			$('snip_success_message').innerHTML = errorMessage;
			$('snip_success_message').style.display = "block";
		} catch(e){}
		return false;
	} else {
		//$('add_snip_button').disabled=true;
	}

	// Add description to parameters and remove all leading and trailing whitespace from a string
	var postParameters = "description="+encodeURIComponent(description);
	// Fetch news network id and send
	postParameters += "&news_circle_id=" + newsCircle;
	postParameters += '&autoshare=' + autoshare;
	postParameters += autoshare ? '' : sharedNetworks;

	if(newsCircle > 0) {
		newsCircleOrUserPage = 1;
	}
	// hide success message div
	$('snip_success_message').style.display='none';
	// show loading image
	try {
		$('snip_loder_image').style.display = "block";
	} catch(e) {}
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: addSnipCallback,
		// Handle 404
		on404: addSnip404Callback,
		// Handle other errors
		onFailure: addSnipFailureCallback
	}
	// Data store model
	new Ajax.Request('/add-snip', ajaxRequestOptions);
}

/**
 * Add a snip success callback function
 */
var addSnipCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track add snip action
	tracAjaxFunctionalities('/add-snip');
	// hide loading image
	try {
		$('snip_loder_image').style.display = "none";
	} catch(e) {}
	//check if there is an error
	if (response_data.error == 1) {
		//alert the error
		//alert(response_data.message);
		try {
			$('snip_success_message').style.color = "red";
			$('snip_success_message').innerHTML = response_data.message;
			$('snip_success_message').style.display = "block";
		} catch(e){}
	} else {
		//if there is not error

		// Hide add snip dialog box
		//$('add_snip_button').disabled=false;
		//$('add_snip').style.display='none';
		// Update the MyClip list
		var storyDetail;
		//if there is not error

		// news network or User page
		// 0=>User page page
		// 1=>news network page
		if(newsCircleOrUserPage == 0) {
			try {
				if(snip_other_page != 1) {
					var clipUnclip = $('clips-container').innerHTML;
					if(clipUnclip.strip().length==0) {
						$('section-header').style.display='block';
					}

					/* storyDetail = '<div id="clipUnclipStoryOuterDiv_'+response_data.story_id+'" style="padding: 0px 0px 5px;margin:0px;">'+
						 				'<div style="padding:0px;margin:0px;float:left;width:50px;">'+
											'<div id="clipUnclipStory_'+response_data.story_id+'" class="clippedStoryPin" title="Remove this Clip" onClick="javascript: clipUnclipStory('+response_data.story_id+',); return false;">'+
												'<div class="clipCountHolder" align="center">1</div>'+
												'<div class="clipText" align="center">Clip</div>'+
											'</div>'+
										 '</div>'+
										'<div style="font-size:11px;padding:0px 0px 10px 2px;float:left;width:298px">'+
										   '<div align="left" style="font-size:12px;padding:5px 0px 0px 0px;width:100%;override:hidden">'+
										   		'"'+response_data.description.truncate(150,'')+'" <font style="color:#6F6F6F;font-size:11px;">(<a href="/story/'+response_data.story_id+'/snip-'+response_data.author+'-'+response_data.story_id+'" class="read_more_link">Read More</a>)</font>'+
										   '</div>'+
										   '<div style="margin:0px;font-size:11px;padding:3px 0px 0px 0px;width:100%;">'+
										     '<div style="float:left;font-size:11px;padding:3px 0px 0px 0px;width:202px">'+
													'Submitted by: <a href="/'+response_data.author+'" style="color:gray">'+response_data.author.capitalize()+'</a>'+
											  '</div>'+
											  '<div align="right" style="float:right;color:gray;padding:3px 0px 0px 0px;width:90px">Just now</div>'+
											  '<br clear="all">'+
										   '</div>'+
										   '<br clear="all">'+
										'</div>'+
										'<br clear="all">'+
									'</div>'; */

					storyDetail = '<div id="clipUnclipStoryOuterDiv_'+response_data.story_id+'" style="padding:3px 0px 8px 0px;margin:0px;">'+
										'<div style="padding:0px 0px 0px 10px;margin:0px;float:left;width:50px;">'+
											'<div id="clipUnclipStory_'+response_data.story_id+'" class="clippedStoryPin" title="Remove this Clip" onClick="javascript: clipUnclipStory('+response_data.story_id+','+response_data.story_id+'); return false;">'+
												'<div align="center" class="clipCountHolder">1</div>'+
												'<div align="center" class="clipText">Clip</div>'+
											'</div>'+
											'<br clear="all">'+
										'</div>'+
										'<div style="font-size:11px;padding:10px 0px 8px 5px;float:left;width:210px;">'+
											'<div style="font-size:12px;padding:5px 0px 0px 0px;width:100%;overflow:hidden;">'+
												'"'+response_data.description.truncate(150,'')+'" <font style="color:#6F6F6F;font-size:11px;">(<a href="/story/'+response_data.story_id+'/snip-'+response_data.author+'-'+response_data.story_id+'" class="read_more_link">Read More</a>)</font>'+
											'</div>'+
										'</div>'+
										'<br clear="all">'+
									'</div>';

					$('clips-container').innerHTML = storyDetail + clipUnclip;
				}
			} catch(e) {}
		}
		else
		{
			try {
				$('add_snip_main').style.display='block';
				try {
					$('news_network_stories_not_found').style.display = 'none';
				} catch (e) {}
				var clipUnclip = $('add_snip_main').innerHTML;
				eval('user_clipped_story'+response_data.story_id+' = 1');
				eval('story'+response_data.story_id+' = 0');
				storyDetail = '<div style="padding:10px 0px 10px 10px;margin:0px;width:670px;border-bottom:1px solid #CCCCCC;">'+
								'<div align="left" style="margin:0px;padding:0px;width:55px;float:left;">'+
									'<div id="clipUnclipStory_'+response_data.story_id+'" class="clippedStoryPin" onClick="javascript: showCommentBox('+response_data.story_id+',user_clipped_story'+response_data.story_id+','+response_data.story_id+'); return false;">'+
										'<div align="center" class="clipCountHolder">1</div>'+
										'<div align="center" class="clipText">Clip</div>'+
									'</div>'+
								'</div>'+
								'<div style="margin:0px;padding:0px;width:610px;float:right;">'+
									'<div align="left" style="margin:0px;padding:0px;width:605px;font-size:14px;font-family:arial;font-weight:bold;">'+
										'<div style="margin:0px;padding:0px;float:right;color:gray;font-size:11px;font-weight:normal;">'+
											'Just now'+
										'</div>'+
										'<br clear="all">'+
									'</div>'+
									'<div align="left" id="clipCommentRsponse'+response_data.story_id+'" style="padding:0px 0px 0px 2px;font-size:13px;font-weight:normal;font-family:arial;width:99%;display:none;"></div>'+
									'<div align="left" id="clip_comment_holder'+response_data.story_id+'" style="position: relative;padding:2px;width:99%;display:none;"></div>'+
									'<div align="left" style="margin:0px;padding:4px 0px 4px 0px;width:600px;font-size:12px;font-family:arial;font-weight:normal;">'+
										'Submitted by <a href="/'+response_data.author+'/home" style="color:#A2A2A2">You</a> : '+
										response_data.description.truncate(150)+' <font style="color:#6F6F6F;font-size:11px;">(<a href="/story/'+response_data.story_id+'/snip-'+response_data.author+'-'+response_data.story_id+'" class="read_more_link">Read More</a>)</font>'+
									'</div>'+
									'<div style="font-size:11px;margin:0px;padding:8px 0px 4px 0px;color:gray;">'+
										'<div style="padding:5px 0px 0px 0px;margin:0px;font-size:11px;">'+
											'<a id="comment_link_'+response_data.story_id+'" href="javascript:void(0);" class="commentStoryInactive" onclick="getStoryComments('+response_data.story_id+','+response_data.story_id+',0,'+response_data.user_id+',\''+response_data.author+'\'); if (MY_SM_CONTACTS.length == 0 && NO_SM_CONTACTS == 0){getMyContacts();}">Add Comment</a>'+
											'<a id="share_link_'+response_data.story_id+'" href="javascript:void(0);" class="shareStoryInactive" onclick="getUsersNewsNetworks('+response_data.story_id+','+response_data.story_id+',\'regular\');">Share</a>'+
											'<a onclick="voteStory(this, \'down\', '+response_data.nc_id+', '+response_data.story_id+')" id="not_relevant_inactive_'+response_data.story_id+'" class="notRelevantStoryActive" style="display:none;">Not relevant</a>'+
											'<a onclick="voteStory(this,\'down\', '+response_data.nc_id+', '+response_data.story_id+')" id="not_relevant_active_'+response_data.story_id+'" class="notRelevantStoryInactive" style="display:block;">Not relevant</a>'+
											'<br clear="all">'+
										'</div>'+
									'</div>'+
									'<div align="left" id="commentShareBoxHolder'+response_data.story_id+'" style="margin:0px;padding:3px 0px 3px 0px;"></div>'+
								'</div>'+
								'<br clear="all">'+
							'</div>';
				$('add_snip_main').innerHTML = storyDetail + clipUnclip;
			} catch(e) {}
		}
		try{
		// tweet info
		tweet_story_info[response_data.story_id] = ["snip",'',escape(response_data.description.truncate(119)),response_data.permalink];
		} catch(e) {}
		// share story with relevent news networks
		response_data.autoshare? autoShareSnipWithNewsNetwork(response_data.nc_id,response_data.story_id) : shareSnipWithNewsNetworks(response_data.share_to, response_data.story_id);
		// Display succcess message
		$('snip_success_message').style.color = "#008000";
		$('snip_success_message').innerHTML = response_data.message;
		$('snip_success_message').style.display='block';
		// empty text area
		$('description').value = "";
	}
}

/**
 * Add a snip failure callback function
 */
var addSnipFailureCallback = function (){
	alert("Error on page");
}
/**
 * Add a snip a story 404 callback function
 */
var addSnip404Callback= function (){
	alert("Error page is not found");
}


/**
 * Share snip with relevant news network.
 */
var autoShareSnipWithNewsNetwork = function(ncid,sid) {
		var postParameters = "news_circle_id="+ncid;
		    postParameters += "&story_id="+sid;
		    postParameters += "&autoshare="+ true;
		var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: shareSnipWithNewsNetworkCallback,
		// Handle 404
		on404: shareSnipWithNewsNetwork404Callback,
		// Handle other errors
		onFailure: shareSnipWithNewsNetworkFailureCallback
	}
	new Ajax.Request('/share-snip-with-news-network', ajaxRequestOptions);
}
/**
 * Share snip with relevant news network.
 */
var shareSnipWithNewsNetworks = function(ncids,sid) {
		var postParameters = "autoshare="+false;
		    postParameters += "&story_id="+sid;
		    ncids.each(function(network_id, index){
			postParameters += '&sn['+ index +']=' + network_id;
		    });
		var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: shareSnipWithNewsNetworkCallback,
		// Handle 404
		on404: shareSnipWithNewsNetwork404Callback,
		// Handle other errors
		onFailure: shareSnipWithNewsNetworkFailureCallback
	}
	new Ajax.Request('/share-snip-with-news-network', ajaxRequestOptions);
}
/**
 * Share snip with relevant news network callback function
 */
var shareSnipWithNewsNetworkCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
}

/**
 * Share snip with relevant news network failure callback function
 */
var shareSnipWithNewsNetworkFailureCallback = function (){
	alert("Error on page");
}
/**
 * Share snip with relevant news network404 callback function
 */
var shareSnipWithNewsNetwork404Callback= function (){
	alert("Error page is not found");
}



/**
 * Edit a the story
 *
 * @type => news | snip
 * @storyId => Stroy which we want to edit
 */

// Global variable used for callback function
var storyType;

var editStroy = function (storyId,type){

	var errorMessage = '';  // Used for error
	var postParameters = "story_id="+storyId; // Story id
	postParameters +="&type="+type; // Story type

	// Used for callback function
	storyType = type;

	// Check for errors
	if(type == 'snip')
	{
		var description=$('edit_description').value.strip(); // Snip description
		// Check snip value blank or not
		if(description.length==0)
		{
			$('edit_description').value = ''; // Clear the text field value
			errorMessage = "Enter snip description"; // Error message
		}
		else if(description.length==0)
		{
			// Display error
			$('edit_description').value = '';
			$('edit_description').focus();
			errorMessage = "Enter valid snip description";
		}
		else if(description.strip() == 'A snip is a short note on any topic.')
		{
			errorMessage = "Enter description"; // Error message
			$('edit_description').value = '';
		}
		else if(description.length >=300)
		{
			// If description is more than 300 character
			errorMessage = "Enter upto 300 character";
		}
		$('edit_description').focus(); // focus on field
		// Add snip fields to parames list
		postParameters += "&description="+description;

	}
	else
	{
		$('edit_news_headline').value = $('edit_news_headline').value.stripTags().gsub(/\<\>|\<|\>/, '');
		if($('edit_news_headline').value == "") {
			alert("Title should not be blank");
			return;
		}
		// Check for atleast one character or number in title
		if(!checkAtleastOneCharacterOrNumber("edit_news_headline")) {
			alert("Title should contain atleast one character or number");
			return;
		}
		// Add news fields to parames list
		postParameters += "&";
		postParameters += Form.serialize("editNewsForm");
	}


	// If error_message is not blank display error
	if(errorMessage != '')
	{
		// Popup error message
		alert(errorMessage);
		return false;
	}

	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: editStroyCallback,
		// Handle 404
		on404: editStroy404Callback,
		// Handle other errors
		onFailure: editStroyFailureCallback
	}
	// Data store model
	new Ajax.Request('/edit-story', ajaxRequestOptions);
}

/**
 * Edit a story success callback function
 */
var editStroyCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track edit story action
	tracAjaxFunctionalities('/edit-story');
	//check if there is an error
	if (response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		if(storyType=='snip')
		{
			// for snip
			window.location = window.location.href;
		}
		else
		{
			// for news
			window.location = response_data.redirect_urls;
		}
	}
}

/**
 * Edit a story failure callback function
 */
var editStroyFailureCallback = function (){
	alert("Error on page");
}
/**
 * Edit story  404 callback function
 */
var editStroy404Callback= function (){
	alert("Error page is not found");
}


/**
 * Delete a story
 *
 * @type => snip | news
 * @storyId => Story which we want to delete
 */

var deleteUserStory = function (storyId,type){
	// Confirm box before delete
	if(!confirm("Do you really want to delete this "+type.capitalize()+" ?")) {
		return false;
	}
	// Post parameters for delete story
	var postParameters = "story_id="+storyId; // Story id
	postParameters += "&type="+type; // Story type
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: deleteUserStoryCallback,
		// Handle 404
		on404: deleteUserStory404Callback,
		// Handle other errors
		onFailure: deleteUserStoryFailureCallback
	}
	// Data delete model
	new Ajax.Request('/delete-user-story', ajaxRequestOptions);
}

/**
 * Delete a story success callback function
 */
var deleteUserStoryCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track delete user story action
	tracAjaxFunctionalities('/delete-user-story');
	//check if there is an error

	if (response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		//if there is not error
		window.location = document.location.protocol+'//'+location.host+response_data.redirect_urls;
	}
}

/**
 * Delete a story failure callback function
 */
var deleteUserStoryFailureCallback = function (){
	alert("Error on page");
}
/**
 * Delete a story 404 callback function
 */
var deleteUserStory404Callback= function (){
	alert("Error page is not found");
}


/**
 * Forgot a password module call
 */

var forgotPassword = function (form_called_from){
	var postParameters = Form.serialize(form_called_from+"_frm_forgot_password");
	//alert("Testing for Bug report -- " + postParameters);
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: function(response){ forgotPasswordForFeedCallback(response,form_called_from); },
		// Handle 404
		on404: forgotPasswordForFeed404Callback,
		// Handle other errors
		onFailure: forgotPasswordForFeedFailureCallback
	}
	new Ajax.Request('/forgot_password', ajaxRequestOptions);
	//alert("Testing for Bug report -- " + postParameters);
}
/**
 *  Forgot a password success callback function
 */
var forgotPasswordForFeedCallback = function (response,form_called_from){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	if(response_data.error == 1) {
		alert(response_data.message);
	}
	else{
		alert(response_data.message);
//		$('forgot_password_notification_div').style.display='block';// = response_data.message;
		$(form_called_from+'_forgot_password_div').style.display='none';
	}
}
/**
 * Forgot a password failure callback function
 */
var forgotPasswordForFeedFailureCallback = function (){
	alert("Error on page");
}
/**
 * Forgot a password 404 callback function
 */
var forgotPasswordForFeed404Callback= function (){
	alert("Error page is not found");
}

var default_desc = "Enter your news description.";
/**
 * Show user description on onfocus()
 */
function showUserDescription(val, obj_id, default_msg) {
	if (default_msg == "snipDesc") {
	    // Opera & IE not detect new line character in value field.
	    var org_des= val;
	    if(Prototype.Browser.IE || Prototype.Browser.Opera){
		    var val1 = val.replace(/\n/g, "");
		        val1 = val1.replace(/\r/g, "\n");
		    val = val1;
		}

	    if(val == snipDesc) {
			$(obj_id).value = "";
		} else {
			$(obj_id).value = org_des;
		}
	} else {
		if(val != default_msg) {
			$(obj_id).value = val;
		} else {
			$(obj_id).value = "";
		}
	}
}

/**
 * Show default message on onBlur()
 */
function replaceDefaultText(obj_id, default_msg) {
	if($(obj_id).value == "") {
		$(obj_id).value = default_msg;
	}
}

/**
 * Populate news response in user's page
 */
function showAddedNews(sId, permalink, title, link, desc, author) {
	var previuos_data;

	previuos_data = $('clips-container').innerHTML;
	if($('clips-container').innerHTML.strip().length == 0) {
		$('section-header').style.display = 'block';
	}
	// concatenate new response with previous response
	/*var story_detail = '<div id="clipUnclipStoryOuterDiv_'+sId+'" style="padding:0px 0px 10px 0px;margin:0px;">'+
							'<div style="margin:0px;padding:0px;float:left;width:50px;">'+
										'<div id="clipUnclipStory_'+sId+'" class="clippedStoryPin" title="Remove this Clip" onClick="javascript: clipUnclipStory('+sId+'); return false;">'+
											'<div align="center" class="clipCountHolder">1</div>'+
											'<div align="center" class="clipText">Clip</div>'+
										'</div>'+
							'</div>'+
							'<div style="padding:0px 0px 10px 2px;margin:0px;float:left;width:298px;">'+
								'<div style="font-size:15px;padding:3px 0px 0px 0px;width:100%;">'+
									'<a href="/story/'+sId+'/'+permalink+'">'+title+'</a>'+
								'</div>'+
								'<div style="margin:0px;font-size:11px;padding:3px 0px 0px 0px;width:100%;">'+
									'<div style="float:left;font-size:11px;padding:3px 0px 0px 2px;width:202px;overflow:hidden;">'+
										'Submitted by: <a href="/'+author+'" style="color:gray">' + author.capitalize() + '</a>'+
									'</div>'+
									'<div align="right" style="float:right;color:gray;padding:3px 0px 0px 0px;width:90px;overflow:hidden;">'+
										'Just now'+
									'</div>'+
									'<br clear="all">'+
								'</div>'+
							'</div>'+
							'<br clear="all">'+
						'</div>'; */


	var story_detail = '<div id="clipUnclipStoryOuterDiv_'+sId+'" style="padding:3px 0px 8px 0px;margin:0px;">'+
							'<div style="padding:0px 0px 0px 10px;margin:0px;float:left;width:50px;">'+
								'<div id="clipUnclipStory_'+sId+'" class="clippedStoryPin" title="Remove this Clip" onClick="javascript: clipUnclipStory('+sId+','+sId+'); return false;">'+
									'<div align="center" class="clipCountHolder">1</div>'+
									'<div align="center" class="clipText">Clip</div>'+
								'</div>'+
								'<br clear="all">'+
							'</div>'+
							'<div style="font-size:11px;padding:10px 0px 8px 5px;float:left;width:210px;">'+
								'<div style="font-size:12px;padding:5px 0px 0px 0px;width:100%;overflow:hidden;">'+
									'<a href="/story/'+sId+'/'+permalink+'" style="text-decoration:underline;">'+title+'</a>'+
								'</div>'+
							'</div>'+
							'<br clear="all">'+
						'</div>';

	$('clips-container').innerHTML = story_detail + previuos_data;
}

/**
 * Populate news response in news network page
 */
function showAddedNewsInNewsCircle(response_data) {
	try {
		$('news_network_stories_not_found').style.display = 'none';
	} catch (e) {}
	previous_data = $('add_snip_main').innerHTML;
	eval('user_clipped_story'+response_data.story_id+' = 1');
	eval('story'+response_data.story_id+' = 0');
	var story_detail = '<div style="padding:10px 0px 10px 10px;margin:0px;width:670px;border-bottom:1px solid #CCCCCC;">'+
							'<div align="left" style="margin:0px;padding:0px;width:55px;float:left;">'+
								'<div id="clipUnclipStory_'+response_data.story_id+'" class="clippedStoryPin" onClick="javascript: showCommentBox('+response_data.story_id+',user_clipped_story'+response_data.story_id+','+response_data.story_id+'); return false;">'+
									'<div align="center" class="clipCountHolder">1</div>'+
									'<div align="center" class="clipText">Clip</div>'+
								'</div>'+
							'</div>'+
							'<div style="margin:0px;padding:0px;width:610px;float:right;">'+
								'<div align="left" style="margin:0px;padding:0px;width:605px;font-size:14px;font-family:arial;font-weight:bold;">'+
									'<div style="margin:0px;padding:0px;width:515px;float:left;">'+
										'<a href="/story/'+response_data.story_id+'/'+response_data.permalink+'" style="color:#2262A9;text-decoration:none;">'+response_data.title+'</a>'+
									'</div>'+
									'<div style="margin:0px;padding:0px;float:right;color:gray;font-size:11px;font-weight:normal;">'+
										'Just now'+
									'</div>'+
									'<br clear="all">'+
								'</div>'+
								'<div align="left" id="clipCommentRsponse'+response_data.story_id+'" style="padding:0px 0px 0px 2px;font-size:13px;font-weight:normal;font-family:arial;width:99%;display:none;"></div>'+
								'<div align="left" id="clip_comment_holder'+response_data.story_id+'" style="position: relative;padding:2px;width:99%;display:none;"></div>'+
								'<div align="left" style="margin:0px;padding:4px 0px 4px 0px;width:600px;font-size:12px;font-family:arial;font-weight:normal;">'+
									'Submitted by <a href="/'+response_data.author+'/home" style="color:#A2A2A2">You</a> : '+
									response_data.description.truncate(300)+' <font style="color:#6F6F6F;font-size:11px;">(<a href="/story/'+response_data.story_id+'/'+response_data.permalink+'" class="read_more_link">Read More</a>)</font>'+
								'</div>'+
								'<div style="font-size:11px;margin:0px;padding:8px 0px 4px 0px;color:gray;">'+
									'<div style="padding:5px 0px 0px 0px;margin:0px;font-size:11px;">'+
										'<a id="comment_link_'+response_data.story_id+'" href="javascript:void(0);" class="commentStoryInactive" onclick="getStoryComments('+response_data.story_id+','+response_data.story_id+',0,'+response_data.user_id+',\''+response_data.author+'\'); if (MY_SM_CONTACTS.length == 0 && NO_SM_CONTACTS == 0){getMyContacts();}">Add Comment</a>'+
										'<a id="share_link_'+response_data.story_id+'" href="javascript:void(0);" class="shareStoryInactive" onclick="getUsersNewsNetworks('+response_data.story_id+','+response_data.story_id+',\'regular\');">Share</a>'+
										'<a onclick="voteStory(this, \'down\', '+response_data.nc_id+', '+response_data.story_id+')" id="not_relevant_inactive_'+response_data.story_id+'" class="notRelevantStoryActive" style="display:none;">Not relevant</a>'+
										'<a onclick="voteStory(this,\'down\', '+response_data.nc_id+', '+response_data.story_id+')" id="not_relevant_active_'+response_data.story_id+'" class="notRelevantStoryInactive" style="display:block;">Not relevant</a>'+
										'<br clear="all">'+
									'</div>'+
								'</div>'+
								'<div align="left" id="commentShareBoxHolder'+response_data.story_id+'" style="margin:0px;padding:3px 0px 3px 0px;"></div>'+
							'</div>'+
							'<br clear="all">'+
						'</div>';

	$('add_snip_main').innerHTML = story_detail + previous_data;

}


function allTrim(strValue)
{
	var j=strValue.length-1;i=0;
	while(strValue.charAt(i++)==' ');
	while(strValue.charAt(j--)==' ');
	return strValue.substr(--i,++j-i+1);
}

/**
 * Show confirm box
 */
var cookieValueForComment;
function showConfirmBox() {
	// take values from cookie and do Deserialization
	var cookieValue = getCookie("duplicateNews");
	var add_comment_text = '';
	var a = cookieValue.split("&");
	for(i=0;i<a.length;i++)
	{
	   var b = a[i].split("=");
	   if(b[0]=='news_desc' && !unescape(b[1]).blank())
	   {
			add_comment_text = '<br><br>Do you want to have the following entered as a comment to this story?<br>"'+unescape(b[1])+'"<p align="center"><a href="javascript:void(0)" onclick="addUserNewsComment()">Yes</a> | <a href="javascript:void(0)" onclick="$(\'confirmBox\').style.display = \'none\'">No</a></p>';
			cookieValueForComment = "news_desc=" + b[1];
	   }
	}

	cookieValue = cookieValue.replace(/force_add=0/gi, "force_add=1");
	// show confirm box
	$('confirmBox').innerHTML = '<div align="center" style="display:block;background-color:#EFEFEF;padding:10px;margin:0px;border:1px solid #c7c7c7;font-size:14px;font-weight:bold;">'+
		'This story already exists on socialmedian. We have clipped it for you and will alert your networks that you are interested in this story.'+
		add_comment_text +
		'</div>';
	$('confirmBox').style.display='block';

	// delete cookie for further use
	deleteCookie("duplicateNews");
}

//Check for atleast one character or number in title
function checkAtleastOneCharacterOrNumber(elId) {
	var checkOK = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
	var checkStr = $(elId).value;
	var checkValid = false;
	for (i = 0;  i < checkStr.length;  i++)	{
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++) {
			if (ch == checkOK.charAt(j)) {
				checkValid = true;
				break;
			}
		}
	}
	if(checkValid == true) {
		return true;
	}
}

/**
 * Add news
 */
// global variable to hold information about other pages (1 => other than nn page and home page)
var news_other_page;
var addUserNews = function (str, other_page){
	news_other_page = other_page;
	var autoshare = $('auto_sharing_yes').checked;
	var sharedNetworks ='' ;
	var errorMessage = '';
	if(str == "0") {
		//strip all html tags from title
		$('news_headline').value = $('news_headline').value.stripTags().gsub(/\<|\>/, '');
		if($('news_headline').value == "") {
			//show error message
			try {
				$('news_success_message').style.color = "red";
				$('news_success_message').innerHTML = "Headline should not be blank";
				$('news_success_message').style.display = "block";
			} catch(e){}
			return;
		}
		if($('news_url').value != "" && $('news_url').value.lastIndexOf(HTTP_APP_DOMAIN,0) != -1 ) {
				//show error message
			try {
				$('news_success_message').style.color = "red";
				$('news_success_message').innerHTML = "News from "+HTTP_APP_DOMAIN+" cannot be added";
				$('news_success_message').style.display = "block";
			} catch(e){}
			return;
		}
		// Check for atleast one character or number in title
		if(!checkAtleastOneCharacterOrNumber("news_headline")) {
			try {
				$('news_success_message').style.color = "red";
				$('news_success_message').innerHTML = "Headline should contain atleast one character or number";
				$('news_success_message').style.display = "block";
			} catch(e){}
			return;
		}
		// check for default description
		if($('news_desc').value == default_desc) {
			$('news_desc').value = "";
		}

		if(!autoshare){
			if(networks_selected_news.length > 0){
					networks_selected_news.each(function(element, index){
					sharedNetworks += '&sn['+ index + ']=' + element;
					});
					networks_selected_news = [];
					$('selected_news_networks_news').innerHTML = '';
			}
			else
			{
				errorMessage = 'When not auto sharing you must choose one of the networks to share with';
			}
		}

		// If error_message is not blank display error
		if(errorMessage != '') {
			//show error message
			try {
				$('news_success_message').style.color = "red";
				$('news_success_message').style.display = "block";
				$('news_success_message').innerHTML = errorMessage;
			} catch(e){}
			return false;
		}
		var postParameters = Form.serialize('addNewsForm');
		// Fetch news network id and send
		postParameters += '&autoshare=' + autoshare;
		postParameters += autoshare ? '' : sharedNetworks;
		// ST on 24/12/2008 - this cookie is not used now(no redirection for duplicate news, just a message there itself)
		//setCookie("duplicateNews",postParameters,0);
	} else {
		var postParameters = unescape(str);
	}
	// hide success message
	try {
		$('news_success_message').style.display = "none";
	} catch(e){}
	// show loading image
	try {
		$('news_loder_image').style.display = "block";
	} catch(e){}
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: addUserNewsCallback,
		// Handle 404
		on404: addUserNews404Callback,
		// Handle other errors
		onFailure: addUserNewsFailureCallback
	}
	new Ajax.Request('/add-news', ajaxRequestOptions);
}
/**
 * Add news success callback function
 */
var confirmBoxFlag = 0;
var addUserNewsCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track add news action
	tracAjaxFunctionalities('/add-news');
	// hide loading image
	try {
		$('news_loder_image').style.display = "none";
	} catch(e){}
	//check if there is an error
	if (response_data.error == 1) {
		//alert the error
		alert(response_data.message);
		//this cookie is not used now
		//deleteCookie("duplicateNews");
	} else if (response_data.error == 2) {
		//alert the error
		try {
				$('news_success_message').style.color = "red";
				$('news_success_message').innerHTML = response_data.message;
				$('news_success_message').style.display = "block";
			} catch(e){}
		//this cookie is not used now
		//deleteCookie("duplicateNews");
	} else {
		// empty all text field and text area
		$('news_headline').value = "";
		$('news_url').value = "";
		$('news_desc').value = "";
		if(confirmBoxFlag == 1) {
			try {
				$('news_success_message').style.color = "#008000";
				$('news_success_message').innerHTML = "<a href='/story/"+response_data.story_id+"/"+response_data.permalink+"' styel='color:blue;text-decoration:underline;'>News</a> added successfully.";
				$('news_success_message').style.display = 'block';
			}catch(e) {}
			//shareNewsWithNewsNetwork(response_data.nc_id,response_data.force_add,response_data.story_id);
			// share story with relevent news networks
			response_data.autoshare? shareNewsWithNewsNetwork(response_data.nc_id,response_data.force_add,response_data.story_id) : autoShareNewsWithNewsNetwork(response_data.share_to, response_data.story_id);
			return;
		}
		if(response_data.action == "news_added") {
			if(response_data.force_add == 1) {
				window.location = "/story/"+response_data.story_id+"/"+response_data.permalink;
			} else {
				// show success message
				try {
					$('news_success_message').style.color = "#008000";
					$('news_success_message').innerHTML = "<a href='/story/"+response_data.story_id+"/"+response_data.permalink+"' styel='color:blue;text-decoration:underline;'>News</a> added successfully.";
					$('news_success_message').style.display = 'block';
				}catch(e) {}
				//shareNewsWithNewsNetwork(response_data.nc_id,response_data.force_add,response_data.story_id);
				// share story with relevent news networks
				response_data.autoshare? shareNewsWithNewsNetwork(response_data.nc_id,response_data.force_add,response_data.story_id) : autoShareNewsWithNewsNetwork(response_data.share_to, response_data.story_id);
				if(news_other_page != 1) {
					showAddedNews(response_data.story_id, response_data.permalink, response_data.title, response_data.link, response_data.description, response_data.author);
				}
			}
			//this cookie is not used now
			//deleteCookie("duplicateNews");
		} else if(response_data.action == "link_exists" || response_data.action == "nc_link_exists") {
			// redirect to story page
			//window.location = "/story/" + response_data.story_id+"/"+response_data.permalink;
			try {
				$('news_success_message').innerHTML = "<div style='color:maroon;font-weight:bold'>This <a href='/story/"+response_data.story_id+"/"+response_data.permalink+"'>News</a> already exists on socialmedian. </div><div style='font-size:12px;color:black;padding:4px 0px 0px 0px'>We have clipped it for you and will alert your networks that you are interested in this story.</div>";
				$('news_success_message').style.display = 'block';
			}catch(e) {}
		} else if(response_data.action == "nc_news_added") {
			if(response_data.force_add == 1) {
				window.location = "/story/"+response_data.story_id+"/"+response_data.permalink;
			} else {
				try {
					$('news_success_message').style.color = "#008000";
					$('news_success_message').innerHTML = "<a href='/story/"+response_data.story_id+"/"+response_data.permalink+"' style='color:blue;text-decoration:underline;'>News</a> added successfully.";
					$('news_success_message').style.display = 'block';
				}catch(e) {}
				//shareNewsWithNewsNetwork(response_data.nc_id,response_data.force_add,response_data.story_id);
				// share story with relevent news networks
				response_data.autoshare? shareNewsWithNewsNetwork(response_data.nc_id,response_data.force_add,response_data.story_id) : autoShareNewsWithNewsNetwork(response_data.share_to, response_data.story_id);
				showAddedNewsInNewsCircle(response_data);
			}
			//this cookie is not used now
			//deleteCookie("duplicateNews");
		}

		try{
		// tweet info
		tweet_story_info[response_data.story_id] = ["news",escape(response_data.title.truncate(119)),'',response_data.permalink];
		} catch(e) {}
	}

	// Enable submit button
	//$('news_submit_button').disabled=false;
}
/**
 * Add news failure callback function
 */
var addUserNewsFailureCallback = function (){
	alert("Error on page");
}
/**
 * Add news 404 callback function
 */
var addUserNews404Callback= function (){
	alert("Error page is not found");
}

/**
 * Share news with relevant news network.
 */
var shareNewsWithNewsNetwork = function(ncid,fadd,sid) {

		var postParameters = "news_circle_id="+ncid;
		    postParameters += "&force_add="+fadd;
		    postParameters += "&story_id="+sid;
		    postParameters += "&autoshare="+true;
		var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: shareNewsWithNewsNetworkCallback,
		// Handle 404
		on404: shareNewsWithNewsNetwork404Callback,
		// Handle other errors
		onFailure: shareNewsWithNewsNetworkFailureCallback
	}
	new Ajax.Request('/share-news-with-news-network', ajaxRequestOptions);
}


/**
 * Share news with relevant news network.
 */
var autoShareNewsWithNewsNetwork = function(ncids,sid) {
		var postParameters = "autoshare="+false;
		    postParameters += "&story_id="+sid;
		    ncids.each(function(network_id, index){
			postParameters += '&sn['+ index +']=' + network_id;
		    });
		var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: shareNewsWithNewsNetworkCallback,
		// Handle 404
		on404: shareNewsWithNewsNetwork404Callback,
		// Handle other errors
		onFailure: shareNewsWithNewsNetworkFailureCallback
	}
	new Ajax.Request('/share-news-with-news-network', ajaxRequestOptions);
}

/**
 * Share news with relevant news network callback function
 */
var shareNewsWithNewsNetworkCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
}

/**
 * Share news with relevant news network failure callback function
 */
var shareNewsWithNewsNetworkFailureCallback = function (){
	alert("Error on page");
}
/**
 * Share news with relevant news network404 callback function
 */
var shareNewsWithNewsNetwork404Callback= function (){
	alert("Error page is not found");
}


/**
 * If story is already exits
 * Add user news description as a comment
 */

var addUserNewsComment = function() {

	var postParameters = cookieValueForComment + "&story_id=" + $("story_id").value + "&permalink=" + $("story_permalink").value;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this data
		postBody: postParameters,
		// Handle successful response
		onSuccess: addUserNewsCommentCallback,
		// Handle 404
		on404: addUserNewsComment404Callback,
		// Handle other errors
		onFailure: addUserNewsCommentFailureCallback
	}
	new Ajax.Request('/add-user-news-as-comment', ajaxRequestOptions);
}

/**
 * Add news success callback function
 */
var addUserNewsCommentCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	if (response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	}
	else
	{
	    window.location = "/story/"+response_data.story_id+"/"+response_data.permalink;
	}
}

/**
 * Add news comment failure callback function
 */
var addUserNewsCommentFailureCallback = function (){
	alert("Error on page");
}
/**
 * Add news comment 404 callback function
 */
var addUserNewsComment404Callback= function (){
	alert("Error page is not found");
}

/**
 * Add new tag to news network
 * @loc_spe => location specific or not 1=>ture,0=>false
 */
var addNewTagToNewsCircle = function (topicValue){
	// Split key words by ',' and check for its length
	if(topicValue.strip().stripTags() == ''){
			$("add_keywords_message").innerHTML = "Topic can't be blank.";
			$("add_keywords_message").style.display = "block";
			/**
			 * @author jeevan
			 * @date 3/3/09
			 * display error message on news network wizard if you dont add any topics and also on news network page.
			 */
			try{
				$("nnRelatedTopicsErrorMsgBox").innerHTML = "Topic can't be blank.";
				$("nnRelatedTopicsErrorMsgBox").style.display = "block";
			} catch(e){}
			return false;
	} else if(topicValue.strip().stripTags().match(/[:|_|"|'|\\|*|~|!|@|$|%|^|&|=|(|)|\[|\]|{|}|;|?|<|>|`|\/]/)) {
			/**
			 * @author jeevan
			 * @date 3/3/09
			 * check word for special characters.if word containa special characters, display error message on news network wizard page and news network page.
			 */
			$("add_keywords_message").innerHTML = "Special characters not allowed";
			$("add_keywords_message").style.display = "block";
			try{
				$("nnRelatedTopicsErrorMsgBox").innerHTML = "Special characters not allowed ";
				$("nnRelatedTopicsErrorMsgBox").style.display = "block";
			} catch(e){}
			return false;
	} else{
		var key_arr = topicValue.strip().stripTags().split(",");
		if($('nc_locaiton_specific').value == 'Y' && key_arr.length >1 )
		{
			$("add_keywords_message").innerHTML = "Multiple locations not allowed.";
			$("add_keywords_message").style.display = "block";
			return false;
		}
		if(NETWORK_PAGE == 1){
			var postParameters = Form.serialize("frm_add_new_tag");
		}else{
			var postParameters = "tag[news_circle_id]="+NEWS_NETWORK_ID+"&tag[tags]="+encodeURIComponent(topicValue)+"&nc_locaiton_specific=0";
		}

		var ajaxRequestOptions = {
			// Use POST
			method: 'post',
			// Send this data
			postBody: postParameters,
			// Handle successful response
			onSuccess: addNewTagToNewsCircleCallback,
			// Handle 404
			on404: addNewTagToNewsCircle404Callback,
			// Handle other errors
			onFailure: addNewTagToNewsCircleFailureCallback
		}
		new Ajax.Request('/add-topics', ajaxRequestOptions);
	}

}
/**
 * Add new tag to news network success callback function
 */
var addNewTagToNewsCircleCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track add topics action
	tracAjaxFunctionalities('/add-topics');
	if(response_data.error == 1) {
		$("add_keywords_message").innerHTML = response_data.message;
		$("add_keywords_message").style.display = "block";
		try{
			$("nnRelatedTopicsErrorMsgBox").innerHTML = response_data.message;
			$("nnRelatedTopicsErrorMsgBox").style.display = "block";
		}catch(e){}
	} else {
		$("add_keywords_message").innerHTML = response_data.message;
		$("add_keywords_message").style.display = "block";
		//create other variables
		var news_circle_id = "";
		var tag_ids = "";
		var news_circle_tag_ids = "";
		//show keywords
		var show_new_keywords = "";
		for (i=0; i<response_data.info.length; i++) {
			//show keyword
		    show_new_keywords += "<div id="+response_data.info[i]['nc_id']+"-topic-"+response_data.info[i]['id']+" style='padding:0px 0px 3px 3px;margin:0px;display:block;'>"+
									"<span style='float:left;padding:0px;margin:0px;width:39px'>"+
										"<img id='voteForTagUp_"+response_data.info[i]['id']+"' src='"+ S3_STATIC_ASSETS_PATH + "/images/aupgray.gif' onmouseover='this.src=\""+ S3_STATIC_ASSETS_PATH + "/images/auproll.gif\"' onmouseout='this.src=\""+ S3_STATIC_ASSETS_PATH + "/images/aupgray.gif\"' onClick=voteForTag('"+response_data.info[i]['nc_id']+"','"+response_data.info[i]['nct_id']+"','"+response_data.info[i]['id']+"','1'); style='cursor:pointer;'>"+
								  		" <img id='voteForTagDown_"+response_data.info[i]['id']+"' src='"+ S3_STATIC_ASSETS_PATH + "/images/adowngray.gif' onmouseover='this.src=\""+ S3_STATIC_ASSETS_PATH + "/images/adownroll.gif\"' onmouseout='this.src=\""+ S3_STATIC_ASSETS_PATH + "/images/adowngray.gif\"' onClick=voteForTag('"+response_data.info[i]['nc_id']+"','"+response_data.info[i]['nct_id']+"','"+response_data.info[i]['id']+"','-1'); style='cursor:pointer;'>"+
								  	"</span>"+
								  	"<span style='float:left;padding:0px 0px 0px 3px;margin:0px'>"+
										' <div style="font-family:arial;font-weight:normal;font-size:12px;float:left;color:#2463A8;"><a href="/topic-stories/'+response_data.info[i]['id']+'/'+response_data.info[i]['tag_permalink']+'" style="color:#2463A8;text-decoration:none;" onmouseover="this.style.textDecoration=\'underline\'" onmouseout="this.style.textDecoration=\'none\'">'+response_data.info[i]['name']+'</a></div>'+
										" <div id='totalVoteForTag_"+response_data.info[i]['id']+"' style='color:gray;font-size:10px;padding:4px 0px 0px 10px;display:block;float:left;'></div>"+
										" <div id='news_circle_keyword_"+response_data.info[i]['id']+"' style='display:none;float:left;padding:2px 0px 0px 4px;margin:0px'><img src='"+ S3_STATIC_ASSETS_PATH + "/images/loader.gif'></div>"+
										'<br clear="all">'+
									"</span>"+
									"<span id=\"" + response_data.info[i]['nc_id']+'-topic_deleter-' + response_data.info[i]['id'] +"\" style=\"cursor:pointer; float:right;margin-right:10px;font-size:10px;\" onclick=\"remove_topic(this)\"> delete </span><br clear='all'/>"+
								"</div>";
			/**
			*	insert topics on left side for create news network / edit news network wizard
			*/
			if(NETWORK_PAGE == 0){
				try{
					$('add_location_message').style.display = "none";
					/**
					*	disaplayTopicsOnLeftSide function creates the html for displaying on edit/add News Network wizard left pannel.<b>
					*   Function define on nn/wizard.js file.
					*/
					var insertUserTopic = disaplayTopicsOnLeftSide(response_data.info[i]['id'], ''+response_data.info[i]['name']+'');
					// insert the topics on left hand side
					new Insertion.Bottom('nnRelatedTopicsDisplayBox', insertUserTopic.replace('[pannel]','left'));
				}catch(e){}
			}
			try{
				$("news_circle_keyword_"+response_data.info[i]['id']).style.display = "block";
			}catch(e){}
			totalVoteForTagIDs[totalVoteForTagIDs.length] = response_data.info[i]['id'];
			if (tag_ids=="") {
				tag_ids += response_data.info[i]['id'];
				news_circle_tag_ids += response_data.info[i]['nct_id'];
				news_circle_id = response_data.info[i]['nc_id'];
			} else {
				tag_ids += "-"+response_data.info[i]['id'];
				news_circle_tag_ids += "-"+response_data.info[i]['nct_id'];
			}
		}
		//crawl feed
		if (news_circle_id != "" && NETWORK_PAGE == 1) {
			crawlNewsCircleTags(news_circle_id, tag_ids, news_circle_tag_ids, $("add_tags_field").value);
			// updating the suggesting sources
			//suggestSourcesFor(news_circle_id, tag_ids.split('-'));

		}
		$("add_tags_field").value = "";
		if (show_new_keywords!="") {
			Insertion.Before("newly_added_keywords", show_new_keywords);
			$("newly_added_keywords").style.display = "block";
		}
	}
}
/**
 * Add new tag to news network failure callback function
 */
var addNewTagToNewsCircleFailureCallback = function (){
	alert("Error on page");
}
/**
 * Add new tag to news network 404 callback function
 */
var addNewTagToNewsCircle404Callback= function (){
	alert("Error page is not found");
}

/**
 * Crawl news network for location specific
 */
var crawlNewsCircleForLocation = function(news_circle_id,tags) {
	var postParameters = "news_circle_id="+news_circle_id+"&tags="+tags;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this data
		postBody: postParameters,
		// Handle successful response
		onSuccess: crawlNewsCircleForLocationCallback,
		// Handle 404
		on404: crawlNewsCircleForLocation404Callback,
		// Handle other errors
		onFailure: crawlNewsCircleForLocationFailureCallback
	}
	new Ajax.Request('/crawl_news_circle_for_location', ajaxRequestOptions);
	$('add_location_message').style.display="block";
}
/**
 * Crawl news network for location success callback function
 */
var crawlNewsCircleForLocationCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	//$("add_location_message").innerHTML = response_data.message;
	window.location = "/network/"+response_data.news_network_permlink;
}

/**
 * Crawl news network for location failure callback function
 */
var crawlNewsCircleForLocationFailureCallback = function (){
	alert("Error on page");
}
/**
 * Crawl news network for location 404 callback function
 */
var crawlNewsCircleForLocation404Callback= function (){
	alert("Error page is not found");
}


/**
 * Crawl news network tags
 */
var crawlNewsCircleTags = function (news_circle_id, tag_ids, news_circle_tag_ids, tags){
	var postParameters = "news_circle_id="+news_circle_id+"&tag_ids="+tag_ids+"&news_circle_tag_ids="+news_circle_tag_ids+"&tags="+tags;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this data
		postBody: postParameters,
		// Handle successful response
		onSuccess: crawlNewsCircleTagsCallback,
		// Handle 404
		on404: crawlNewsCircleTags404Callback,
		// Handle other errors
		onFailure: crawlNewsCircleTagsFailureCallback
	}
	new Ajax.Request('/crawl-news-circle', ajaxRequestOptions);
}
/**
 * Crawl news network tags success callback function
 */
var crawlNewsCircleTagsCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	if(response_data.error == 1) {
		$("add_keywords_message").innerHTML = response_data.message;
		$("add_keywords_message").style.display = "block";
	} else {
		$("add_keywords_message").innerHTML = response_data.message;
		$("add_keywords_message").style.display = "block";
		//split the tag ids
		tag_ids = response_data.tag_ids.split("-");
		for (i=0; i<tag_ids.length; i++) {
			//hide all loading images
			$("news_circle_keyword_"+tag_ids[i]).style.display = "none";
		}
	}
}
/**
 * Crawl news network tags failure callback function
 */
var crawlNewsCircleTagsFailureCallback = function (){
	alert("Error on page");
}
/**
 * Crawl news network tags 404 callback function
 */
var crawlNewsCircleTags404Callback= function (){
	alert("Error page is not found");
}

/**
 * Add new feed to news network
 */
var addNewFeedToNewsCircle = function (){
	if ($('add_feeds_field').value == '')
	{
		$("add_feeds_message").innerHTML = "Source URL is mandatory.";
		$("add_feeds_message").style.display = "block";
		return false;
	}
	else
	{
		$("add_feeds_message").style.display = "none";
		$("news_network_sources_loading_image").style.display = "block";
		var postParameters = Form.serialize("frm_add_new_feed");
		var ajaxRequestOptions = {
			// Use POST
			method: 'post',
			// Send this data
			postBody: postParameters,
			// Handle successful response
			onSuccess: addNewFeedToNewsCircleCallback,
			// Handle 404
			on404: addNewFeedToNewsCircle404Callback,
			// Handle other errors
			onFailure: addNewFeedToNewsCircleFailureCallback
		}
		new Ajax.Request('/add-feeds', ajaxRequestOptions);
	}
}
/**
 * Add new feed to news network success callback function
 */
var addNewFeedToNewsCircleCallback = function (response){
	$("add_feeds_message").style.display = "block";
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track add feeds action
	tracAjaxFunctionalities('/add-feeds');
	if(response_data.error == 1) {
		$("add_feeds_message").innerHTML = response_data.message;
		$("add_feeds_message").style.display = "block";
		$("news_network_sources_loading_image").style.display = "none";
	} else {
		$("add_feeds_message").innerHTML = response_data.message;
		$("add_feeds_message").style.display = "block";
		$("news_network_sources_loading_image").style.display = "none";
		$("add_feeds_field").value = "";
		//show feeds
		var show_new_feeds = "";
		for (i=0; i<response_data.info.length; i++) {
			//show feed
		   	show_new_feeds = showUserAddedSources(response_data.info[i]['nc_id'], response_data.info[i]['id'], response_data.info[i]['ncf_id'], response_data.info[i]['name'], response_data.info[i]['added_by'], response_data.info[i]['added_on']);
			//$('newly_added_feeds').innerHTML = show_new_feeds + $('newly_added_feeds').innerHTML;
			new Insertion.Before("newly_added_feeds", show_new_feeds);
			totalVoteForFeedIDs[totalVoteForFeedIDs.length] = response_data.info[i]['id'];
			crawlNewsCircleFeed(response_data.info[i]['id'], response_data.info[i]['ncf_id'], response_data.info[i]['nc_id']);
		}
		$("newly_added_feeds").style.display = "block";
	}
}
/**
 * Add new feed to news network failure callback function
 */
var addNewFeedToNewsCircleFailureCallback = function (){
	alert("Error on page");
	$("news_network_sources_loading_image").style.display = "none";
}
/**
 * Add new feed to news network 404 callback function
 */
var addNewFeedToNewsCircle404Callback= function (){
	alert("Error page is not found");
	$("news_network_sources_loading_image").style.display = "none";
}

/**
 * Crawl news network feeds
 */
var crawlNewsCircleFeed = function (feed_id, news_circle_feed_id, news_circle){
	var postParameters = "feed_id="+feed_id+"&news_circle_feed_id="+news_circle_feed_id+"&news_circle="+news_circle;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this data
		postBody: postParameters,
		// Handle successful response
		onSuccess: crawlNewsCircleFeedCallback,
		// Handle 404
		on404: crawlNewsCircleFeed404Callback,
		// Handle other errors
		onFailure: crawlNewsCircleFeedFailureCallback
	}
	new Ajax.Request('/crawl-feed', ajaxRequestOptions);

}
/**
 * Crawl news network feeds success callback function
 */
var crawlNewsCircleFeedCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	if(response_data.error == 1) {
		$("add_feeds_message").innerHTML = response_data.message;
		$("add_feeds_message").style.display = "block";
	} else {
		$("add_feeds_message").innerHTML = response_data.message;
		$("add_feeds_message").style.display = "block";
		//hide all loading images
		$("news_circle_feed_"+response_data.feed_id).innerHTML = response_data.show_data;
		$("news_circle_feed_loading_"+response_data.feed_id).style.display = "none";
	}
}
/**
 * Crawl news network feeds failure callback function
 */
var crawlNewsCircleFeedFailureCallback = function (){
	alert("Error on page");
}
/**
 * Crawl news network feeds 404 callback function
 */
var crawlNewsCircleFeed404Callback= function (){
	alert("Error page is not found");
}

/**
 * Refresh the current page
 */
var refreshCurrentPage = function () {
	var sURL = unescape(window.location.pathname);
	window.location.href = sURL;
}

/**
 * Set, Get and Delete Cookies
 */
function setCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/; domain="+COOKIE_DOMAIN+"";
}

function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function deleteCookie(name) {
	setCookie(name,"",-1);
}

/**
 * Email alert frequency setting for news networks
 */
var changeEmailAlertFrequency = function (){
	var select_obj = $('email_alert_frequency');
	var postParameters = "alert_frequency="+select_obj.options[select_obj.selectedIndex].value;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this data
		postBody: postParameters,
		// Handle successful response
		onSuccess: changeEmailAlertFrequencyCallback,
		// Handle 404
		on404: changeEmailAlertFrequency404Callback,
		// Handle other errors
		onFailure: changeEmailAlertFrequencyFailureCallback
	}
	new Ajax.Request('/change-alert-setting', ajaxRequestOptions);
}

/**
 * Crawl news network feeds success callback function
 */
var changeEmailAlertFrequencyCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	if(response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		$('email_alert_response').innerHTML = response_data.message;
		$('email_alert_response').style.display = "block";
	}
}
/**
 * Crawl news network feeds failure callback function
 */
var changeEmailAlertFrequencyFailureCallback = function (){
	alert("Error on page");
}
/**
 * Crawl news network feeds 404 callback function
 */
var changeEmailAlertFrequency404Callback= function (){
	alert("Error page is not found");
}

function test(str)
{
	alert(str);
}
/**
 * Join/Quit News Networks
 */
var joinQuitFlag;
var joinOrQuitNewsNetwork = function (nc_id, act_type, refresh_page){
	joinQuitFlag = refresh_page;
	try {
		$('browse_all_news_network_join_quit'+nc_id).innerHTML = '<img src="'+S3_STATIC_ASSETS_PATH+'/images/loader.gif">';
	} catch(e){}
	var postParameters = "id="+nc_id;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this data
		postBody: postParameters,
		// Handle successful response
		onSuccess: joinOrQuitNewsNetworkCallback,
		// Handle 404
		on404: joinOrQuitNewsNetwork404Callback,
		// Handle other errors
		onFailure: joinOrQuitNewsNetworkFailureCallback
	}
	if (act_type == "join") {
		/**
		 * ST 26/11/08
		 *
		 * Modified to 'join' in the route from 'jion'. route is modified accordingly.
		 */
		new Ajax.Request('/ajax-join-news-network', ajaxRequestOptions);
	} else {
		new Ajax.Request('/ajax-quit-news-network', ajaxRequestOptions);
	}
}

/**
 * Join/Quit News Networks success callback function
 */
// A global variable for the user if this user
var member_of_news_network = false;
// hack for displaying noise level pointer properly
POINTER_HACK = false;
var joinOrQuitNewsNetworkCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track join/quit news network action
	tracAjaxFunctionalities('/ajax-join-quit-news-network');
	if(response_data.error == 1) {
		//alert the error
		alert(response_data.message);
		if (response_data.network_type == 'xing'){
			if (response_data.action == "joined_news_network") {
				try{
					$('browse_all_news_network_join_quit'+response_data.news_circle_id).innerHTML = '<a class="join-in-button" onclick="alert(response_data.message);return false;" style="color:#6B6B6B;cursor:pointer;font-size:11px;font-weight:normal;text-decoration:underline;"></a>';
					$('browse_all_news_network_join_quit'+response_data.news_circle_id).style.display = 'block';
				} catch(e){}
			}else if (response_data.action == "quitted_news_network"){
				try{
					$('browse_all_news_network_join_quit'+response_data.news_circle_id).innerHTML = '<a onclick="alert(response_data.message);return false;" style="color:#6B6B6B;font-size:11px;font-weight:normal;cursor:pointer;text-decoration:underline;">Quit this News Network</a>';
					$('browse_all_news_network_join_quit'+response_data.news_circle_id).style.display = 'block';
				} catch(e){}
			}
		}
	} else {
		if(joinQuitFlag == 1) {
			window.location = window.location.href;
			return false;
		}
		if (response_data.action == "joined_news_network") {
			try {
				$('browse_all_news_network_join_quit'+response_data.news_circle_id).innerHTML = '<a onclick="joinOrQuitNewsNetwork('+response_data.news_circle_id+',\'quit\',0);" style="color:#6B6B6B;font-size:11px;font-weight:normal;cursor:pointer;text-decoration:underline;">Quit this News Network</a>';
			} catch(e){}
			try {
				$('join_network_symbol'+response_data.news_circle_id).innerHTML = '<span style=\'font-family:arial;font-size:12px;color:#7CB940; \'>You are now a member of this news network</span>';
				$('join_reject_loading'+response_data.news_circle_id).style.display = 'none';
				$('ignore_news_network_invitation'+response_data.news_circle_id).style.display = 'none';
			} catch(e){}
			try {
				$('join_unjoin'+response_data.news_circle_id).innerHTML = '<a onclick="joinOrQuitNewsNetwork('+response_data.news_circle_id+',\'quit\',0);" style="color:#6F6F6F;font-size:11px;font-weight:normal;cursor:pointer;">Quit</a>';
			} catch(e){}
			/**
			*	Display the Noise level controller
			*/
			$('userNoiseLevelController').style.display = 'block';
			if($('noiseLevelPointer').style.marginLeft == "23px" && !POINTER_HACK){
				$('noiseLevelPointer').style.margin = "0px 0px 0px 17px";
				POINTER_HACK = true;
			}
			// enable not relevant sources link
			member_of_news_network = true;
			$$('.not-relevant-marker-for-suggested-source').each ( function(nrs){ nrs.show();});
			// Show quit link
			try {
				$('news_network_join_quit_link_holder').innerHTML = '<a href="" onclick="javascript:joinOrQuitNewsNetwork('+response_data.news_circle_id+',\'quit\',0);return false;" style="color:#949494;cursor:pointer;text-decoration:underline;">Quit this News Network</a>';
			} catch(e){}
			try {
				$('join_quit_link_holder'+response_data.news_circle_id).innerHTML = '<div id="join_image_div'+response_data.news_circle_id+'" class="searchImageNormal"></div> '+
																					'<div style="margin:0px;padding:3px 0px 2px 5px;float:left;">'+
																						'<a id="join_unjoin'+response_data.news_circle_id+'" onclick="joinOrQuitNewsNetwork('+response_data.news_circle_id+',\'quit\',0)" style="color:#9B9B9D;cursor:pointer;text-decoration:underline;">Quit</a>'+
																					'</div>';
			} catch(e){}
			try {
				$('popular_news_network_join_quit'+response_data.news_circle_id).innerHTML = '<a onclick="joinOrQuitNewsNetwork('+response_data.news_circle_id+',\'quit\',0);" style="color:#6F6F6F;font-size:11px;font-weight:normal;cursor:pointer;">Quit</a>';
				$('popular_news_network_join_quit'+response_data.news_circle_id).style.backgroundColor = '#DFDFDF';
			} catch(e){}
			try {
				$('discover_news_network_join_quit'+response_data.news_circle_id).innerHTML = '<a onclick="joinOrQuitNewsNetwork('+response_data.news_circle_id+',\'quit\',0);" style="cursor:pointer;"><img src=\'/images/Quit.png\' /></a>';
			} catch(e){}
			try {
				$('nn_inviters_list_div'+response_data.news_circle_id).style.display = 'none';
			} catch(e){}
			try {
				// this is check for first time user joins any news network
				$('recent_news_network_join_quit'+response_data.news_circle_id).innerHTML = '<a onclick="joinOrQuitNewsNetwork('+response_data.news_circle_id+',\'quit\',0);" style="color:#6F6F6F;font-size:11px;font-weight:normal;cursor:pointer;">Quit</a>';
				$('recent_news_network_join_quit'+response_data.news_circle_id).style.backgroundColor = '#DFDFDF';
			} catch(e){}
			try {
				// 'hotlist_nn_quit_join_counter'  id is initialize in hot_list.js
				$('hotlist_join_quit_nn'+response_data.news_circle_id+'_'+hotlist_nn_quit_join_counter).innerHTML = '<a onclick="joinOrQuitNewsNetwork('+response_data.news_circle_id+',\'quit\',0);" style="color:#5F5F5F;cursor:pointer;text-decoration:underline;">Quit</a>';
				if(nnShortDetailsHash.get(response_data.news_circle_id)){
					nnShortDetailsHash.get(response_data.news_circle_id).joined_nn_or_not = 'yes';
				}
			} catch(e){}
		} else if(response_data.action == "quitted_news_network") {
			try {
				$('browse_all_news_network_join_quit'+response_data.news_circle_id).innerHTML = '<a class="join-in-button" onclick="joinOrQuitNewsNetwork('+response_data.news_circle_id+',\'join\',0);" style="color:#6B6B6B;cursor:pointer;font-size:11px;font-weight:normal;text-decoration:underline;"></a>';
			} catch(e){}
			try {
				$('join_unjoin'+response_data.news_circle_id).innerHTML = '<a onclick="joinOrQuitNewsNetwork('+response_data.news_circle_id+',\'join\',0);" style="color:#6F6F6F;font-size:11px;font-weight:normal;cursor:pointer;">Join</a>';
			} catch(e){}
			/**
			*	hide the Noise level controller
			*/
			$('userNoiseLevelController').style.display = 'none';
			// disable not relevant source link
			member_of_news_network = false;
			$$('.not-relevant-marker-for-suggested-source').each ( function(nrs){ nrs.hide();});
			// Show join link

			try {
				$('news_network_join_quit_link_holder').innerHTML = '<a href="" onclick="javascript:joinOrQuitNewsNetwork('+response_data.news_circle_id+',\'join\',0);return false;" style="color:#949494"><img src="'+S3_STATIC_ASSETS_PATH+'/images/Join-button.png"></a>';
			} catch(e){}
			//try {
				//$('join_quit_link_holder'+response_data.news_circle_id).innerHTML = '<div id="join_image_div'+response_data.news_circle_id+'" class="searchImageNormal"></div> '+
				//																	'<div style="margin:0px;padding:3px 0px 2px 5px;float:left;">'+
				//																		'<a id="join_unjoin'+response_data.news_circle_id+'" onclick="joinOrQuitNewsNetwork('+response_data.news_circle_id+',\'join\',0)" style="color:#9B9B9D;cursor:pointer;text-decoration:underline;">Join</a>'+
				//																	'</div>';
			//} catch(e){}
			try {
				$('popular_news_network_join_quit'+response_data.news_circle_id).innerHTML = '<a onclick="joinOrQuitNewsNetwork('+response_data.news_circle_id+',\'join\',0);" style="color:#2364A9;font-size:11px;font-weight:normal;cursor:pointer;">Join</a>'
				$('popular_news_network_join_quit'+response_data.news_circle_id).style.backgroundColor = '#B5D5FF';
			} catch(e){}
			try {
				$('discover_news_network_join_quit'+response_data.news_circle_id).innerHTML = '<a onclick="joinOrQuitNewsNetwork('+response_data.news_circle_id+',\'join\',0);" style="cursor:pointer;"><img src=\'/images/Join.png\' /></a>';
			} catch(e){}
			try {
				$('recent_news_network_join_quit'+response_data.news_circle_id).innerHTML = '<a onclick="joinOrQuitNewsNetwork('+response_data.news_circle_id+',\'join\',0);" style="color:#2364A9;font-size:11px;font-weight:normal;cursor:pointer;">Join</a>'
				$('recent_news_network_join_quit'+response_data.news_circle_id).style.backgroundColor = '#B5D5FF';
			} catch(e){}
			try {
				$('hotlist_join_quit_nn'+response_data.news_circle_id+'_'+hotlist_nn_quit_join_counter).innerHTML = '<a onclick="joinOrQuitNewsNetwork('+response_data.news_circle_id+',\'join\',0);" style="color:#5F5F5F;cursor:pointer;text-decoration:underline;">Join</a>'
				if(nnShortDetailsHash.get(response_data.news_circle_id)){
					nnShortDetailsHash.get(response_data.news_circle_id).joined_nn_or_not = 'no';
				}
			} catch(e){}
		}
	}
}
/**
 * Join/Quit News Networks failure callback function
 */
var joinOrQuitNewsNetworkFailureCallback = function (){
	alert("Error on page");
}
/**
 * Join/Quit News Networks 404 callback function
 */
var joinOrQuitNewsNetwork404Callback= function (){
	alert("Error page is not found");
}


/**
 * Add or Edit location specific topic
 * @ncid => news circle id
 */
var addEditLocationSpecificTopicBox = function(ncid,topic,addOrEdit,nctagid){

	if (addOrEdit ==1) // Add
	{
		$('add_loc_spe_holer').innerHTML = '<div id="add_loc_spe_tag" style="position:absolute;display:block;background-color:#EFEFEF;padding:10px;margin:0px;border:1px solid #c7c7c7;font-size:14px;width:225px;top:-10px">'+
		'<form id="frm_add_loc_spe_tag" method="POST" style="padding:0px;margin:0px">'+
			'<div style="font-weight:bold;font-family:arial;font-size:15px;width:100%;padding:0px;margin:0px">Add a location:</div>'+
			'<input id="add_loc_tags_field" name="tag[tags]" size="30" type="text" /><input type="hidden" name="tag[news_circle_id]" value="'+ncid+'" />'+
			'<div align="right" style="padding:0px;margin:0px">'+
					'<input type="button" name="button" value="Add" onclick="addEditLocationSpecificTopic(); return false;" /><input type="hidden" name="nc_locaiton_specific" id="nc_locaiton_specific" value="Y">'+
					'<a href="" onClick="$(\'add_loc_spe_tag\').style.display=\'none\';return false;" style="margin-left:3px">close</a>'+
			'</div>'+
		'</form>'+
		'</div>';
	}
	else // Edit
	{
		$('add_loc_spe_holer').innerHTML = '<div id="add_loc_spe_tag" style="position:absolute;display:block;background-color:#EFEFEF;padding:10px;margin:0px;border:1px solid #c7c7c7;font-size:14px;width:225px;top:-10px">'+
		'<form id="frm_add_loc_spe_tag" method="POST" style="padding:0px;margin:0px">'+
			'<div style="font-weight:bold;font-family:arial;font-size:15px">Edit a location:</div>'+
			'<input id="add_loc_tags_field" name="tag[tags]" size="30" type="text" value="'+topic+'" /><input type="hidden" id="previous_topic" value="'+topic+'" /><input type="hidden" name="id" value="'+nctagid+'" /><input type="hidden" name="tag[news_circle_id]" value="'+ncid+'" />'+
			'<div align="right" style="padding:0px;margin:0px">'+
					'<input type="button" name="button" value="Edit" onclick="addEditLocationSpecificTopic(); return false;" /><input type="hidden" name="nc_locaiton_specific" id="nc_locaiton_specific" value="Y">'+
					'<a href="" onClick="$(\'add_loc_spe_tag\').style.display=\'none\';return false;" style="margin-left:3px">close</a>'+
			'</div>'+
		'</form>'+
		'</div>';
	}

		//javascript: addNewTagToNewsCircle(1); return false;
}
var notLocationSpecific = function(nn_id){
	//if(!confirm("This news network will never be location specific in future, if you click ok.")){
	//	return false;
	//}
	//else{
		var postParameters = "network_id="+nn_id;
		var ajaxRequestOptions = {
			// Use POST
			method: 'post',
			// Send this data
			postBody: postParameters,
			// Handle successful response
			onSuccess: notLocationSpecificCallback,
			// Handle 404
			on404: notLocationSpecific404Callback,
			// Handle other errors
			onFailure: notLocationSpecificFailureCallback
		}
		new Ajax.Request('/no-location-option', ajaxRequestOptions);
	//}
}
/**
 * notLocationSpecific success callback function
 */
var notLocationSpecificCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	if(response_data.error == 0){
		//$('location_specific_topic_display').style.display = 'none';
		//alert(window.location.href);
		window.location = window.location.href;
	}
}
/**
 * notLocationSpecific failure callback function
 */
var notLocationSpecificFailureCallback = function (){
	alert("Error on page");
}
/**
 * notLocationSpecific 404 callback function
 */
var notLocationSpecific404Callback= function (){
	alert("Error page is not found");
}

/**
 * Add new tag to news network
 * @loc_spe => location specific or not 1=>ture,0=>false
 */
var addEditLocationSpecificTopic = function (){
	/**
	 * @author jeevan
	 * @date 16/3/09
	 * when ever a location topic is added or updated. check the topic for special characters.
	 * if yes display error message.
	 */
	if($('add_loc_tags_field').value.strip().stripTags().match(/[,|:|"|'|\\|*|~|!|@|$|%|^|&|+|=|(|)|\[|\]|{|}|;|?|<|>|`|\/]/)){
		 alert("special characters are not allowed");
		 return false;
	}
	// Split key words by ',' and check for its length
	var key_arr = $('add_loc_tags_field').value.strip().stripTags().split(",");

	valid_key = true;

	try {
		var previous_key_val = $('previous_topic').value.strip().stripTags();
		if(previous_key_val == $('add_loc_tags_field').value.strip().stripTags())
		{
			$('add_loc_spe_tag').style.display = 'none';
			return true;
		}
	}
	catch(e){}

	if($('nc_locaiton_specific').value == 'Y' && key_arr.length >1 )
	{
		alert("Multiple locations not allowed.");
		return false;
	}

	for(i=0;i<key_arr.length;i++) {
		if(key_arr[i].strip().length < 3) {
			valid_key = false;
			break;
		}
	}

	if (valid_key == false)
	{
		alert("Location must have atleast 3 characters.");
		return false;
	}
	else
	{
		var postParameters = Form.serialize("frm_add_loc_spe_tag");

		var ajaxRequestOptions = {
			// Use POST
			method: 'post',
			// Send this data
			postBody: postParameters,
			// Handle successful response
			onSuccess: addEditLocationSpecificTopicCallback,
			// Handle 404
			on404: addEditLocationSpecificTopic404Callback,
			// Handle other errors
			onFailure: addEditLocationSpecificTopicFailureCallback
		}
		new Ajax.Request('/add-edit-location-specific-topic', ajaxRequestOptions);
	}
}
/**
 * Add new tag to news network success callback function
 */
var addEditLocationSpecificTopicCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track add\edit location specific topic action
	tracAjaxFunctionalities('/add-edit-location-specific-topic');
	if(response_data.error == 1) {
		alert(response_data.message);
	} else {
		$('location_specific_topic_display').innerHTML = '<div align="left" style="padding:5px 0px 4px 10px;margin:0px;font-family:arial;background-color:#E7E7E7;"><div style="padding:0px;margin:0px;width:100%"><div style="margin:0px;padding:0px;float:left;width:180px;">This News Network is specific to '+response_data.tag_name+'.</div><div style="margin:0px;padding:0px 3px 0px 0px;float:right;">(<a href="javascript:void(0)" onClick="addEditLocationSpecificTopicBox('+response_data.ncid+',\''+response_data.tag_name+'\',0,'+response_data.nct_id+')" style="color:#757575;font-weight:bold;">Edit</a> | <a href="javascript:void(0)" onClick="removeLocation('+response_data.nct_id+','+response_data.ncid+')" style="color:#757575;font-weight:bold;">Remove</a>)</div><br clear="all"></div></div><div align="left" style="margin:0px;padding:5px 0px 0px 15px;font-family:arial;font-weight:normal;font-size:11px;color:#949494;">Enter a location, e.g. "New York" or "India" or "London" and we will only include stories which reference that location.<img src="'+ S3_STATIC_ASSETS_PATH + '/images/help_contents.gif" onmouseover="TagToTip(\'Span2\',BGCOLOR, \'#FFFFFF\',BORDERCOLOR,\'#808080\')" onmouseout="UnTip()" style="cursor: pointer;" /></div>';
		$('add_loc_spe_tag').style.display = 'none';
		// remove the topic if its already exists
		try {
			$(response_data.ncid+"-topic-"+response_data.old_tag_id).remove();
		} catch(e){}
		// add keyword to the topics list
		$('newly_added_keywords').innerHTML = "<div id="+response_data.ncid+"-topic-"+response_data.tag_id+" style='padding:0px 0px 3px 3px;margin:0px;display:block;'>"+
									"<span style='float:left;padding:0px 0px 0px 42px;margin:0px'>"+
										' <div style="font-family:arial;font-weight:normal;font-size:12px;float:left;color:#2463A8;">'+
											'<a href="/topic-stories/'+response_data.tag_id+'/'+response_data.tag_permalink+'" style="color:#2463A8;text-decoration:none;" onmouseover="this.style.textDecoration=\'underline\'" onmouseout="this.style.textDecoration=\'none\'">'+response_data.tag_name+'</a>'+
											'<span style="color:#000000;"> (location)</span> <span onmouseover="TagToTip(\'topice_location_specific\',BGCOLOR, \'#FFFFFF\',BORDERCOLOR,\'#808080\');" onmouseout="UnTip();" style="cursor: pointer;">?</span>'+
										'</div>'+
										" <div id='totalVoteForTag_"+response_data.tag_id+"' style='color:gray;font-size:10px;padding:4px 0px 0px 10px;display:block;float:left;'></div>"+
									"</span><span id=\"" + response_data.ncid+'-topic_deleter-' + response_data.tag_id+"\" style=\"cursor:pointer; float:right;margin-right:10px;font-size:10px;\" onclick=\"remove_topic(this, 'location')\"> delete </span><br clear='all'/>"+
								"</div>";
		$('newly_added_keywords').style.display = 'block';
		crawlNewsCircleForLocation(response_data.ncid,response_data.tag_name);
	}
}
/**
 * Add new tag to news network failure callback function
 */
var addEditLocationSpecificTopicFailureCallback = function (){
	alert("Error on page");
}
/**
 * Add new tag to news network 404 callback function
 */
var addEditLocationSpecificTopic404Callback= function (){
	alert("Error page is not found");
}


/**
 * Remove Locaiton specific tag
 * @params:
 * lsid => location spicific topic id ( uses for romove the topic)
 */
var removeLocation = function(lsid,ncid){

		var postParameters = "id="+lsid;
		postParameters += "&tag[news_circle_id]=" + ncid;
		var ajaxRequestOptions = {
			// Use POST
			method: 'post',
			// Send this data
			postBody: postParameters,
			// Handle successful response
			onSuccess: removeLocationCallback,
			// Handle 404
			on404: removeLocationCallback,
			// Handle other errors
			onFailure: removeLocationFailureCallback
		}
		new Ajax.Request('/remove-location-specific-topic', ajaxRequestOptions);
}

/**
 * Remove Locaiton specific tag callback function
 */
var removeLocationCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track remove location specific topic action
	tracAjaxFunctionalities('/remove-location-specific-topic');
	if(response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		if (response_data.action == "Remove") {
			// Hide the location specific div
			//$('location_specific_'+response_data.id).style.display = "none";
			$('location_specific_topic_display').innerHTML = '<div align="left" style="padding:5px 0px 4px 10px;margin:0px;font-family:arial;background-color:#E7E7E7;">Is this News Network location specific?&nbsp;&nbsp;&nbsp;<a href="javascript:void(0)" onClick="addEditLocationSpecificTopicBox('+response_data.ncid+',\'\',1,\'\')" style="color:#757575;font-weight:bold;">Yes</a>&nbsp;&nbsp;&nbsp;<a href="javascript:void(0)" onclick="notLocationSpecific('+response_data.ncid+')" style="color:#757575;font-weight:bold;">No</a></div><div align="left" style="margin:0px;padding:5px 0px 0px 15px;font-family:arial;font-weight:normal;font-size:11px;color:#949494;">Enter a location, e.g. "New York" or "India" or "London" and we will only include stories which reference that location.<img src="' + S3_STATIC_ASSETS_PATH + '/images/help_contents.gif" onmouseover="TagToTip(\'Span2\',BGCOLOR, \'#FFFFFF\',BORDERCOLOR,\'#808080\')" onmouseout="UnTip()" style="cursor: pointer;" /></div>';
			// remove topic from topics list
			try {
				$(response_data.ncid+'-topic-'+response_data.tag_id).remove();
			} catch(e){}
		}
	}
}
/**
 * Remove Locaiton specific tag failure callback function
 */
var removeLocationFailureCallback = function (){
	alert("Error on page");
}
/**
 * Remove Locaiton specific tag 404 callback function
 */
var removeLocation404Callback= function (){
	alert("Error page is not found");
}

/**
 * Activate Write a comment tab
 */
function showWriteAComment(sId, aId) {
	// make other tabs inactive
	// make Send to a News Circle Tab inactive
	var sendToNCTab = $('send_to_a_news_circle'+aId);
	sendToNCTab.style.borderRight = '1px solid #FFFFFF';
	sendToNCTab.style.cursor = 'pointer';
	sendToNCTab.style.backgroundColor = '#EFEFEF';
	// make Email to a friend Tab inactive
	var emailToFriendTab = $('email_to_a_friend'+aId);
	emailToFriendTab.style.borderRight = '1px solid #FFFFFF';
	emailToFriendTab.style.cursor = 'pointer';
	emailToFriendTab.style.backgroundColor = '#EFEFEF';
	// make current tab active
	var writeCommentTab = $('write_a_comment'+aId);
	writeCommentTab.style.cursor = 'none';
	writeCommentTab.style.backgroundColor = '#FFFFFF';
	// add html code
	$('clip_contents_holder'+aId).innerHTML = '<div id="clip_story" name="clip_story" style="padding:10px 10px 10px 15px;margin:0px;font-size:13px;">'+
											'<form id="clipCommentForm'+aId+'" onsubmit="javascript: addClipComment('+sId+',\''+aId+'\'); return false;" style="margin:0px;padding:0px;">'+
												'<div style="margin:0px;padding:0px 0px 5px 0px;">Comment:</div>'+
												//'<input type="hidden" id="display_comment_count_'+data.aId+'" value="'+display_comment_count+'">'+
												'<div style="margin:0px;padding:0px;">'+
													'<div style="margin:0px;padding:0px;float:left;width:355px;">'+
														'<textarea id="user_comment'+aId+'" name="user_comment" autocomplete="off" value="" style="width:350px; height:68px;" id="user_comment" onkeyup="auto_complete_my_contacts(event, \''+aId+'\');"></textarea>'+
														'<div id="sm_contacts_auto_complete'+aId+'" class="replize_autocompleter" style="display: none;"></div>'
													'</div>'+
													'<div style="margin:0px;padding:47px 0px 0px 10px;float:left;width:55px;">'+
														'<input type="submit" name="submit" value="Post">'+
													'</div>'+
													'<br clear="all">'+
												'</div>'+
											'</form>'+
										'</div>';
}

/**
 * Activate Send to a News Circle tab
 */
function showSendToANewsCircle(sId, aId, response_data) {
	// make other tabs inactive
	// make Write a comment Tab inactive
	var writeCommentTab = $('write_a_comment'+aId);
	writeCommentTab.style.borderRight = '1px solid #FFFFFF';
	writeCommentTab.style.cursor = 'pointer';
	writeCommentTab.style.backgroundColor = '#EFEFEF';
	// make Email to a friend Tab inactive
	var emailToFriendTab = $('email_to_a_friend'+aId);
	emailToFriendTab.style.borderRight = '1px solid #FFFFFF';
	emailToFriendTab.style.cursor = 'pointer';
	emailToFriendTab.style.backgroundColor = '#EFEFEF';
	// make current tab active
	var sendToNCTab = $('send_to_a_news_circle'+aId);
	sendToNCTab.style.cursor = 'none';
	sendToNCTab.style.backgroundColor = '#FFFFFF';
	// add html code
	var htmlHolder = "";
	htmlHolder = '<div style="padding:10px 10px 10px 15px;margin:0px;font-size:13px;">';
	if (response_data.belongs_to.length > 0) {
		htmlHolder += '<div style="margin:0px;padding:0px 0px 5px 0px;"><b>Belongs to the News Networks: </b>';
		for(j=0;j<response_data.belongs_to.length;j++) {
			if(j==0) {
				htmlHolder += '<a href="/network/'+response_data.belongs_to[j].name_permalink+'" target="_blank">'+response_data.belongs_to[j].name+'</a>';
			} else {
				htmlHolder += ', <a href="/network/'+response_data.belongs_to[j].name_permalink+'" target="_blank">'+response_data.belongs_to[j].name+'</a>';
			}
		}
		htmlHolder += '</div>';
	}

	if(response_data.network_list.length > 0) {
	htmlHolder += '<div style="margin:0px;padding:0px 0px 5px 0px;">Share this story with the News Network</div>'+
			'<form method="post" id="share_story_with_nc" name="share_story_with_nc" onSubmit="shareStoryWithNewsCircle(\''+aId+'\');return false;">'+
				'<div style="margin:0px;padding:0px 0px 5px 0px;">'+
					'<select id="news_circles" name="news_circles">';
	for(i=0;i<response_data.network_list.length;i++) {
		htmlHolder += '<option value="'+response_data.network_list[i].id+'">'+response_data.network_list[i].name+'</option>';
	}
		htmlHolder += '</select>'+
					'<input type="hidden" name="story_id" value="'+sId+'">'+
					'<input type="submit" name="share" value="Share">'+
				'</div>'+
			'</form>'+
		'</div>';
	$('clip_contents_holder'+aId).innerHTML = htmlHolder;
	}else{
	htmlHolder += '<div style="margin: 0px; padding: 0px 0px 5px;">There are no other News Networks that you have joined.</div>'; $('clip_contents_holder'+aId).innerHTML = htmlHolder;
	}

}

/**
 * Activate Email to a friend tab
 */
function showEmailToAFriend(sId, aId) {
	// make other tabs inactive
	// make Write a comment Tab inactive
	var writeCommentTab = $('write_a_comment'+aId);
	writeCommentTab.style.borderRight = '1px solid #FFFFFF';
	writeCommentTab.style.cursor = 'pointer';
	writeCommentTab.style.backgroundColor = '#EFEFEF';
	// make Send to a News Circle Tab inactive
	var sendToNCTab = $('send_to_a_news_circle'+aId);
	sendToNCTab.style.borderRight = '1px solid #FFFFFF';
	sendToNCTab.style.cursor = 'pointer';
	sendToNCTab.style.backgroundColor = '#EFEFEF';
	// make current tab active
	var emailToFriendTab = $('email_to_a_friend'+aId);
	emailToFriendTab.style.cursor = 'none';
	emailToFriendTab.style.backgroundColor = '#FFFFFF';
	// add html code
	$('clip_contents_holder'+aId).innerHTML = '<div style="padding:10px 10px 10px 15px;margin:0px;font-size:13px;">'+
				'<div style="margin:0px;padding:0px 0px 5px 0px;">Send Email:</div>'+
				'<div id="email_error_div" name="email_error_div" style="margin:0px;padding:0px;font-family:arial;color:#DF1B1B;font-size:13px;" align="center"></div>'+
				'<div style="margin:0px;padding:0px;">'+
					'<form id="mailForm" onsubmit="javascript: if($(\'message\').innerHTML==\'Write Your Own Message Here...\'){$(\'message\').innerHTML=\'\'}; sendMail(1,'+aId+'); return false;" >'+
						'<div style="margin:0px;padding:3px 0px 0px 0px;" align="left">'+
							'<div style="margin:0px;padding:3px 4px 3px 0px;float:left;">Recipient Email: </div>'+
							'<div style="margin:0px;padding:0px;float:left;"><input type="text" id="recipient_email" name="recipient_email"  style="width:234;" value="Type Email-id" onfocus="if($(\'recipient_email\').value==\'Type Email-id\'){$(\'recipient_email\').value=\'\'}"></div>'+
							'<br clear="all">'+
						'</div>'+
						'<div style="margin:0px;padding:1px 0px 0px 85px;color:#8F8F8F;font-size:11px;">(Use Commas to seperated multiple email ids, if you need.)</div>'+
						'<div style="margin:0px;padding:0px;">Message: </div>'+
						'<div style="margin:0px;padding:2px 0px 0px 0px;"><textarea name="message" style="width:350px; height:100px;" id="message" onfocus="if($(\'message\').innerHTML==\'Write Your Own Message Here...\'){$(\'message\').innerHTML=\'\';}">Write Your Own Message Here...</textarea></div>'+
						'<input type="hidden" name="story_id" value="'+sId+'">'+
						'<div style="margin:0px;padding:0px;"><input type="checkbox" name="comment" value="comment" checked> Also post this message as a public comment</div>'+
						'<div align="left" style="margin:0px;padding:5px 0px 0px 4px;font-family:arial;color:#000000;font-size:11px; width:320px;">'+
							'Don\'t worry. We won\'t share the name or email address of the person that you sent the story to.'+
						'</div>'+
						'<div style="margin:0px;padding:0px;" align="right"><input type="submit" name="submit" value="Submit"></div>'+
					'</form>'+
				'</div>'+
			'</div>';
}

/**
 * Fading Effect
 */
var fadingColor = ["9F", "B3", "AD", "A8", "A4", "A2", "A5", "A8", "AD", "B3", "BA", "C1", "C8", "CF", "D7", "FF"];
var startFadingColor = 0;
var changeBackgroundColorObject = "";
var fadeElementId = "";
function yellowFadingTechnique() {
	col_val = "#FEFF" + fadingColor[startFadingColor];
	document.getElementById(fadeElementId).style.backgroundColor = col_val;
	startFadingColor++;
	if (startFadingColor==16) {
		clearInterval(changeBackgroundColorObject);
	}
}

/**
 * Deactivate clip box functionality
 */
var showClipBoxOrNotInFuture = function(story_id, act_id){
		var postParameters = "story_id="+story_id+"&act_id="+act_id;
		var ajaxRequestOptions = {
			// Use POST
			method: 'post',
			// Send this data
			postBody: postParameters,
			// Handle successful response
			onSuccess: showClipBoxOrNotInFutureCallback,
			// Handle 404
			on404: showClipBoxOrNotInFuture404Callback,
			// Handle other errors
			onFailure: showClipBoxOrNotInFutureFailureCallback
		}
		new Ajax.Request('/show-clip-box-or-not', ajaxRequestOptions);
}

/**
 * Deactivate clip box functionality success callback function
 */
var showClipBoxOrNotInFutureCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track show clip box or not action
	tracAjaxFunctionalities('/show-clip-box-or-not');
	if(response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		showClipBoxOrNot = response_data.status;
		if(response_data.status == 'n') {
			$('clip_holder_main'+response_data.act_id).style.display = "none";
		}
	}
}
/**
 * Deactivate clip box functionality failure callback function
 */
var showClipBoxOrNotInFutureFailureCallback = function (){
	alert("Error on page");
}
/**
 * Deactivate clip box functionality 404 callback function
 */
var showClipBoxOrNotInFuture404Callback= function (){
	alert("Error page is not found");
}

/**
 * Get user's News Networks to share a story
 */
var getUsersNewsNetworks = function(story_id, aId, share){
		if($('share_link_'+aId+'_div').className != "shareStoryBackgroundActive"){
			$('share_link_'+aId+'_div').className = "shareStoryBackgroundActive";
			$('comment_link_'+aId+'_div').className = "commentStoryBackgroundInactive";
			$('news_flash_link_'+aId+'_div').className = "newsFlashStoryBackgroundInactive";
			$('commentShareBoxHolder'+aId).style.display = 'block';
			$('newsFlashBoxHolder'+aId).style.display = "none";
			$('newsFlashBroadcastBox'+aId).style.display = "none";
		}else{
			$('share_link_'+aId+'_div').className = "shareStoryBackgroundInactive";
			$('commentShareBoxHolder'+aId).style.display = 'none';
			return false;
		}
		//remove entry from hash to make fresh call to server
		try {
			shareWithNewsNetworkFlag.unset(aId);
		} catch(e){}
		// clip it box share loading image
		try {
			$('clip_contents_holder'+aId).innerHTML = '<div style="margin:0px;padding:10px 0px 0px 0px;font-size:14px;font-family:arial;" align="center"><img src="'+ S3_STATIC_ASSETS_PATH + '/images/loader.gif"> Loading...</div>';
		} catch(e) {}
		// show loading image
		try {
			$('commentShareBoxHolder'+aId).innerHTML = '<div style="padding:4px 0px 0px 0px;margin:0px;width:150px;">'+
															'<div style="float:left;padding:0px;margin:0px;"><img src="'+ S3_STATIC_ASSETS_PATH + '/images/loader.gif"></div>'+
															'<div style="float:left;padding:0px 0px 0px 5px;margin:0px;font-size:13px;">Loading...</div>'+
															'<br clear="all">'+
														'</div>';
			$('commentShareBoxHolder'+aId).style.display = "block";
		} catch(e) {}
		var postParameters = "story_id="+story_id+"&act_id="+aId+"&share="+share;
		var ajaxRequestOptions = {
			// Use POST
			method: 'post',
			// Send this data
			postBody: postParameters,
			// Handle successful response
			onSuccess: getUsersNewsNetworksCallback,
			// Handle 404
			on404: getUsersNewsNetworks404Callback,
			// Handle other errors
			onFailure: getUsersNewsNetworksFailureCallback
		}
		new Ajax.Request('/get-users-news-networks', ajaxRequestOptions);
}

/**
 * Get user's News Networks to share a story success callback function
 */
var getUsersNewsNetworksCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	if(response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		if(response_data.share == 'regular') {
			showSharingBox(response_data.story_id, response_data.act_id);
			populateShareWithNewsNetwork(response_data.story_id, response_data.act_id, response_data);
		} else {
			showSendToANewsCircle(response_data.story_id, response_data.act_id, response_data);
		}
	}
}
/**
 * Get user's News Networks to share a story failure callback function
 */
var getUsersNewsNetworksFailureCallback = function (){
	alert("Error on page");
}
/**
 * Get user's News Networks to share a story 404 callback function
 */
var getUsersNewsNetworks404Callback= function (){
	alert("Error page is not found");
}

/**
 * Share story with news circle
 */
var shareStoryWithNewsCircle = function(act_id){
		var postParameters = Form.serialize("share_story_with_nc");
		postParameters += "&act_id="+act_id;
		var ajaxRequestOptions = {
			// Use POST
			method: 'post',
			// Send this data
			postBody: postParameters,
			// Handle successful response
			onSuccess: shareStoryWithNewsCircleCallback,
			// Handle 404
			on404: shareStoryWithNewsCircle404Callback,
			// Handle other errors
			onFailure: shareStoryWithNewsCircleFailureCallback
		}
		new Ajax.Request('/story/share_with_nc', ajaxRequestOptions);
}

/**
 * Share story with news circle success callback function
 */
var shareStoryWithNewsCircleCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track share story with news network action
	tracAjaxFunctionalities('/story/share_with_nc');
	if(response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		try {
			$('clipCommentRsponse'+response_data.act_id).innerHTML = "Successfully shared with the '"+$('news_circles').options[$('news_circles').selectedIndex].text+"' News Network";
			//yellow fading technique
			startFadingColor = 0;
			fadeElementId = 'clipCommentRsponse'+response_data.act_id;
			changeBackgroundColorObject = setInterval(yellowFadingTechnique, 400);
			$('clipCommentRsponse'+response_data.act_id).style.display = "block";
		} catch(e) {}
		try {
			$('clipCommentRsponse_hotlist'+response_data.act_id).innerHTML = "Successfully shared with the '"+$('news_circles').options[$('news_circles').selectedIndex].text+"' News Network";
			//yellow fading technique
			startFadingColor = 0;
			fadeElementId = 'clipCommentRsponse_hotlist'+response_data.act_id;
			changeBackgroundColorObject = setInterval(yellowFadingTechnique, 400);
			$('clipCommentRsponse_hotlist'+response_data.act_id).style.display = "block";
		} catch(e) {}
		// Hide the comment box
		try {
			$('clip_holder_main'+response_data.act_id).style.display = 'none';
		} catch(e) {}
		try {
			$('comment_link_'+response_data.act_id+'_div').className = "commentStoryBackgroundInactive";
			$('share_link_'+response_data.act_id+'_div').className = "shareStoryBackgroundInactive";
			$('commentShareBoxHolder'+response_data.act_id).style.display = "none";
		} catch(e) {}

		// perform clip action and update total clip count
		performClipAction(response_data.story_id, response_data.act_id);
	}
}
/**
 * Share story with news circle failure callback function
 */
var shareStoryWithNewsCircleFailureCallback = function (){
	alert("Error on page");
}
/**
 * Share story with news circle 404 callback function
 */
var shareStoryWithNewsCircle404Callback= function (){
	alert("Error page is not found");
}

/**
 * Change clip/unclip image for stories in hot list
 */
function changeSameStoriesImage(sId, action, clipCount) {
    var obj = document.getElementsByTagName("div");
    var str = "";
    if(clipCount == 0 || clipCount > 1) {
            str = "Clips";
    } else {
            str = "Clip";
    }
    for(i=0;i<obj.length;i++) {
        if(obj[i].id == 'clipUnclipStory_hotlist_'+sId) {
                if(action == "clipped") {
                        obj[i].className = "clippedStoryPin";
                        obj[i].title = "Remove this Clip";
                } else if(action == "unclipped") {
                        obj[i].className = "unclippedStoryPin";
                        obj[i].title = "Add to my Clips";
                }
                // update clips total count
                obj[i].innerHTML = '<div align="center" class="clipCountHolder">'+clipCount+'</div>'+
                                                        '<div align="center" class="clipText">'+str+'</div>';
        } else if(obj[i].id == 'clipUnclipStorySmallIcon'+sId) {
            if(action == "clipped") {
                        obj[i].className = "clippedStoryPinSmall";
                        obj[i].title = "Remove this Clip";
                } else if(action == "unclipped") {
                        obj[i].className = "unclippedStoryPinSmall";
                        obj[i].title = "Add to my Clips";
                }
                // update clips total count
                obj[i].innerHTML = '<div align="center" class="clipCountHolderSmallIcon">'+clipCount+'</div>'+
                                                        '<div align="center" class="clipTextSmallIcon">'+str+'</div>';
        }
    }
}

/**
 * Change clip/unclip image for stories in users page and also update clips count
 */
function updateClipCountNImages(sId, clipCount) {
	// get all clipped and unclipped images
	var clippedImages = document.getElementsByClassName("userClippedStoryActive");
	var unclippedImages = document.getElementsByClassName("userClippedStoryInactive");
	// update clips total count
	var str = "";
	if(clipCount == 0 || clipCount > 1) {
		str = " Clips";
	} else {
		str = " Clip";
	}
	// update all clipped images to unclipped one.
	for(i=0;i<clippedImages.length;i++) {
		if(clippedImages[i].id == "clips_link_"+sId) {
			clippedImages[i].className = "userClippedStoryInactive";
			clippedImages[i].innerHTML = clipCount+str;
		}
	}
	// update all unclipped images to clipped one.
	for(i=0;i<unclippedImages.length;i++) {
		if(unclippedImages[i].id == "clips_link_"+sId) {
			unclippedImages[i].className = "userClippedStoryActive";
			unclippedImages[i].innerHTML = clipCount+str;
		}
	}
}

function showNetworkUserName(id) {
	$(id).style.display = 'block';
}

/**
 * Get News Network users
 */
var getNewsNetworkUsers = function (ncId, currentUserId){
	// show loading image
	$('news_network_user_loading_image').style.display = 'block';
	var postParameters = "news_network_id="+ncId+"&curr_user="+currentUserId;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: getNewsNetworkUsersCallback,
		// Handle 404
		on404: getNewsNetworkUsers404Callback,
		// Handle other errors
		onFailure: getNewsNetworkUsersFailureCallback
	}
	new Ajax.Request('/get-news-network-users', ajaxRequestOptions);
}

/**
 * Get News Network users success callback function
 */
var getNewsNetworkUsersCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track 'get news network users' action
	tracAjaxFunctionalities('/get-news-network-users');
	// hide loading image
	$('news_network_user_loading_image').style.display = 'none';
	if(response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		showNewsNetworkUsersAjaxCall = 1; // don't send ajax request in future
		var htmlHolder = "";
		for(i=0;i<response_data.nn_users.length;i++) {
			if(i == 21) {
				htmlHolder += '<br clear="all">'+
									'<div id="network_users" style="margin:0px;padding:0px;display:block;">';
			}
			htmlHolder += '<div style="margin:14px 8px 14px 9px;padding:0px;float:left;width:23px;height:23px;">'+
								'<table cellspacing="0" cellpadding="0" style="padding:0px;margin:0px;border:1px solid gray">'+
									'<tr>'+
										'<td style="height:20px;width:20px;padding:0px;margin:0px" valign="middle" align="center">';
											if(response_data.curr_user == response_data.nn_users[i].id) {
												htmlHolder += '<a href="/'+response_data.nn_users[i].socialmedian_url+'/home" onmouseover="$(\'network_user_name'+response_data.nn_users[i].id+'\').style.display=\'block\'" onmouseout="$(\'network_user_name'+response_data.nn_users[i].id+'\').style.display=\'none\'"><img style="vertical-align:middle;" src=\''+ S3_DYNAMIC_ASSETS_PATH +'/user-images/'+response_data.nn_users[i].id+'-small.jpg\'></a>';
											} else {
					 							htmlHolder += '<a href="/'+response_data.nn_users[i].socialmedian_url+'" onmouseover="$(\'network_user_name'+response_data.nn_users[i].id+'\').style.display=\'block\'" onmouseout="$(\'network_user_name'+response_data.nn_users[i].id+'\').style.display=\'none\'"><img style="vertical-align:middle;" src=\'' + S3_DYNAMIC_ASSETS_PATH + '/user-images/'+response_data.nn_users[i].id+'-small.jpg\'></a>';
					 						}
										htmlHolder += '</td>'+
									'</tr>'+
								'</table>'+
								'<div id="network_user_name'+response_data.nn_users[i].id+'" align="center" style="position:relative;margin:0px;padding:0px 0px 0px 0px;width:1px;font-size:11px;display:none;height:1px;">'+
									'<div align="center" style="position:absolute;top:-39px;left:-48px;margin:0px;padding:0px;width:100px;font-size:11px;z-index:10">'+
										'<div align="center" style="margin:0px;padding:0px;">'+response_data.nn_users[i].socialmedian_url+'</div>'+
									'</div>'+
								'</div>'+
							'</div>';
							if(response_data.nn_users.length > 21 && i == response_data.nn_users.length-1) {
								htmlHolder += '<br clear="all">'+
								'</div>';
							} else if(i == response_data.nn_users.length-1) {
								htmlHolder += '<br clear="all">';
							}
		}
		$('news_network_user_holder').innerHTML = htmlHolder;
	}
}

/**
 * Get News Network users failure callback function
 */
var getNewsNetworkUsersFailureCallback = function (){
	alert("Error on page");
}
/**
 * Get News Network users 404 callback function
 */
var getNewsNetworkUsers404Callback= function (){
	alert("Error page is not found");
}

/**
 * show News Network users
 */
var showNewsNetworkUsersAjaxCall = 0;
function showNetworkUsers(nnId,currUser,str) {
	if(showNewsNetworkUsersAjaxCall == 1) {
		// Don't send any request
		if(str == 'more') {
			$('network_users').style.display = 'block';
		} else if(str == 'less') {
			$('network_users').style.display = 'none';
		}
	} else {
		// Send ajax request
		getNewsNetworkUsers(nnId,currUser);
	}
}

/**
 * Get all suggested sources
 */
var getSuggestedSources = function (ncId, currentUserId){
	// show loading image
	$('news_network_suggested_sources_loading_image').style.display = 'block';
	var postParameters = "news_network_id="+ncId;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: getSuggestedSourcesCallback,
		// Handle 404
		on404: getSuggestedSources404Callback,
		// Handle other errors
		onFailure: getSuggestedSourcesFailureCallback
	}
	new Ajax.Request('/get-suggested-sources', ajaxRequestOptions);
}

/**
 * Get all suggested sources success callback function
 */
var getSuggestedSourcesCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track 'get suggested sources' action
	tracAjaxFunctionalities('/get-suggested-sources');
	// hide loading image
	$('news_network_suggested_sources_loading_image').style.display = 'none';
	if(response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		suggestedSourcesAjaxCall = 1; // don't send ajax request in future
		var htmlHolder = "";
		suggested_source_counter = 0;
		admin_suggested_sources_open_div = 0;
		for(i=0;i<response_data.admin_suggested_sources.length;i++) {
			if (response_data.admin_suggested_sources[i].nrss_first_user_id != current_user_id && response_data.admin_suggested_sources[i].nrss_sec_user_id != current_user_id) {
				if(suggested_source_counter == 5) {
					htmlHolder += '<div id="admin_suggested_sources" style="padding:0px;margin:0px;display:block;">';
					admin_suggested_sources_open_div = 1;
				}
				htmlHolder += '<div id="suggested_source-'+response_data.admin_suggested_sources[i].id+'" style="margin:0px;padding:0px 0px 12px 0px;">'+
									'<div style="margin:0px;padding:0px 0px 0px 2px;float:left;width:30px;color:#2463A8;font-family:arial;font-size:13px;cursor:pointer;" onclick="addSuggestedSource('+response_data.admin_suggested_sources[i].id+')" onmouseover="this.style.textDecoration=\'underline\'" onmouseout="this.style.textDecoration=\'none\'">Add</div>'+
									'<div style="margin:0px;padding:0px 0px 0px 5px;float:left;width:230px;">'+
										'<div style="margin:0px;padding:0px;">'+
											'<a href="'+response_data.admin_suggested_sources[i].url+'" target="_blank" style="color:#000000;text-decoration:none;cursor:pointer;font-size:13px;font-family:arial;" onmouseover="this.style.textDecoration=\'underline\'" onmouseout="this.style.textDecoration=\'none\'">'+response_data.admin_suggested_sources[i].title.truncate(50)+'</a>'+
										'</div>';
										try {
											if(response_data.admin_suggested_sources[i].description != "") {
												htmlHolder += '<div style="margin:0px;padding:0px;font-size:11px;color:#A4A4A4;overflow:hidden;">'+response_data.admin_suggested_sources[i].description.truncate(120)+'</div>';
											}
										} catch (e) {}
										source_topic_lenth = '';
										if(response_data.admin_suggested_sources_topic[response_data.admin_suggested_sources[i].id].length>1)
										{
											source_topic_lenth = 's';
										}
										htmlHolder += '<div style="margin:0px;padding:3px 0px 3px 0px;font-size:11px;color:#A4A4A4;overflow:hidden;">Topic'+source_topic_lenth+':&nbsp;'+response_data.admin_suggested_sources_topic[response_data.admin_suggested_sources[i].id].join(", ")+'</div>';

				if( (admin_suggested_source_not_relevant_point > 0) ) {
					htmlHolder += '<div class="not-relevant-marker-for-suggested-source" id="not_relevant_admin_suggested_source_link_'+response_data.admin_suggested_sources[i].id+'" style="float:left;margin:0px;padding:0px;font-size:11px;color:#A4A4A4;text-decoration:underline;cursor:pointer;display:'+ (member_of_news_network == true ? 'block' : 'none') +'" onClick="javascript:notRelevantAdminSuggestedSource('+news_circle_id+', '+response_data.admin_suggested_sources[i].id+');">Not Relevant</div>'+
				         '<div id="not_relevant_admin_suggested_source_loading_'+response_data.admin_suggested_sources[i].id+'" style="display:none;float:left;padding:0px 0px 0px 10px;margin:0px;"><img src="'+S3_STATIC_ASSETS_PATH+'/images/loader.gif"></div>'+
				         '<br clear="all">';
				}
				htmlHolder +=   	'</div>'+
									'<br clear="all">'+
								'</div>';
				suggested_source_counter++;
			}
		}
		if(admin_suggested_sources_open_div == 1) {
			htmlHolder += '</div>';
		}
		$('news_network_suggested_source_holder').innerHTML = htmlHolder;
		refreshSnapshots();
	}
}

/**
 * Get all suggested sources failure callback function
 */
var getSuggestedSourcesFailureCallback = function (){
	alert("Error on page");
}
/**
 * Get all suggested sources 404 callback function
 */
var getSuggestedSources404Callback= function (){
	alert("Error page is not found");
}

/**
 * Not relevant admin suggested sources
 */
var notRelevantAdminSuggestedSource = function (news_circle_id, sourceId){
	// show loading image
	$('not_relevant_admin_suggested_source_loading_'+sourceId).style.display = 'block';
	var postParameters = "source_id="+sourceId+"&news_circle_id="+news_circle_id+"&by="+admin_suggested_source_not_relevant_by;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: notRelevantAdminSuggestedSourceCallback,
		// Handle 404
		on404: notRelevantAdminSuggestedSource404Callback,
		// Handle other errors
		onFailure: notRelevantAdminSuggestedSourceFailureCallback
	}
	new Ajax.Request('/not-relevant-suggested-sources', ajaxRequestOptions);
}

/**
 * Not relevant admin suggested sources success callback function
 */
var notRelevantAdminSuggestedSourceCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track 'not relevant suggested sources' action
	tracAjaxFunctionalities('/not-relevant-suggested-sources');
	// hide loading image
	$('not_relevant_admin_suggested_source_loading_'+response_data.source_id).style.display = 'none';
	if(response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		//if we have to hide it....
		if (response_data.hide_div == '1') {
			$('suggested_source-'+response_data.source_id).style.display = 'none';
		} else if (response_data.hide_div == '2') {
			$('not_relevant_admin_suggested_source_link_'+response_data.source_id).style.display = 'none';
		}
	}
}

/**
 * Not relevant admin suggested sources failure callback function
 */
var notRelevantAdminSuggestedSourceFailureCallback = function (){
	alert("Error on page");
}
/**
 * Not relevant admin suggested sources 404 callback function
 */
var notRelevantAdminSuggestedSource404Callback= function (){
	alert("Error page is not found");
}

/**
 * show News Network suggested sources
 */
var suggestedSourcesAjaxCall = 0;
function showSuggestedSources(nnId,str) {
	if(suggestedSourcesAjaxCall == 1) {
		// Don't send any request
		if(str == 'more') {
			$('admin_suggested_sources').style.display = 'block';
		} else if(str == 'less') {
			$('admin_suggested_sources').style.display = 'none';
		}
	} else {
		// Send ajax request
		getSuggestedSources(nnId);
	}
}

// function to track user actions using google analytics
function tracNewsNetworkCreateAction() {
	// Google Analytics - code to track create news network action
	tracAjaxFunctionalities('/create-news-network');
}

// function to track user actions using google analytics
function tracStoryCommentAction() {
	// Google Analytics - code to track story comment action
	tracAjaxFunctionalities('/create-news-network');
}

/**
 * disable Clip-it images
 */
var disableClipItImage = function (user_id){
	var postParameters = "user_id="+user_id;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: disableClipItImageCallback,
		// Handle 404
		on404: disableClipItImage404Callback,
		// Handle other errors
		onFailure: disableClipItImageFailureCallback
	}
	new Ajax.Request('/disable-clip-it-image', ajaxRequestOptions);
}
/**
 * disable Clip-it images success callback function
 */
var disableClipItImageCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track add news action
	tracAjaxFunctionalities('/disable-clip-it-image');
	//check if there is an error
	if (response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		$('clipItMessageImage').remove();
		if($('clipitImagesInnerBorder').innerHTML.blank() == true) {
			$('clipitImagesOuterBorder').style.display = 'none';
			$('clipitImagesInnerBorder').style.display = 'none';
		}
	}
}
/**
 * disable Clip-it images failure callback function
 */
var disableClipItImageFailureCallback = function (){
	alert("Error on page");
}
/**
 * disable Clip-it images 404 callback function
 */
var disableClipItImage404Callback= function (){
	alert("Error page is not found");
}

/**
 * disable bookmarklet images
 */
var disableBookmarkletImage = function (user_id){
	if(!confirm("You have chosen to hide the socialmedian bookmarklet tool. To access the socialmedian bookmarklet tool again, please visit our FAQs.")) {
		return false;
	}
	var postParameters = "user_id="+user_id;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: disableBookmarkletImageCallback,
		// Handle 404
		on404: disableBookmarkletImage404Callback,
		// Handle other errors
		onFailure: disableBookmarkletImageFailureCallback
	}
	new Ajax.Request('/disable-bookmarklet-image', ajaxRequestOptions);
}
/**
 * disable bookmarklet images success callback function
 */
var disableBookmarkletImageCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track add news action
	tracAjaxFunctionalities('/disable-bookmarklet-image');
	//check if there is an error
	if (response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		$('bookmarkletImage').remove();
		if($('clipitImagesInnerBorder').innerHTML.blank() == true) {
			$('clipitImagesOuterBorder').style.display = 'none';
			$('clipitImagesInnerBorder').style.display = 'none';
		}
	}
}
/**
 * disable bookmarklet images failure callback function
 */
var disableBookmarkletImageFailureCallback = function (){
	alert("Error on page");
}
/**
 * disable bookmarklet images 404 callback function
 */
var disableBookmarkletImage404Callback= function (){
	alert("Error page is not found");
}

/**
 * Invite friends functionality --------- To be done later-----------
 */
function open_popup(str) {
		$(str).style.display='block';
		$('user_name').value = '';
		$('password').value = '';
	}

	function hide_popup(str) {
		$(str).style.display='none';
	}

	function set_mail_type(str) {
		$("mail_type").value=str;
	}


var AuthenticatUser = function (){
	if($('user_name').value == "" || $('password').value == "") {
		alert("User Name/Password should not be blank");
		return false;
	}
	$('invite_friends_loader_image').style.display = "block";
	var postParameters = "uname="+$('user_name').value;
	    postParameters += "&password="+$('password').value;
	    postParameters += "&mail_type="+$('mail_type').value;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: AuthenticatUserCallback,
		// Handle 404
		on404: AuthenticatUser404Callback,
		// Handle other errors
		onFailure: AuthenticatUserFailureCallback
	}
	new Ajax.Request('/fetch_webmail_contacts', ajaxRequestOptions);
}

var AuthenticatUserCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	//check if there is an error
	$('invite_friends_loader_image').style.display = "none";
	if (response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
	    if(response_data.contacts.length > 0 || response_data.register_friend.length > 0) {
			var htmlHolder = '';
			htmlHolder = '<div style="padding:0px;margin:0px;width:600px;">'+
							'<p align="right" style="font-size:10px;padding-right:5px;"><a href="javascript:void(0);" onclick="hide_popup(\'contactListDetails\');">close</a></p>'+
							'<div style="margin:0px;padding:0px;">'+
								'<div align="center" style="margin:0px;padding:10px 0px 0px 0px;font-size:14px;font-weight:bold;font-family:arial;">'+
									'Already registered users from your contacts'+
								'</div>'+
								'<div align="center" style="margin:0px;padding:15px 1px 10px 1px;font-size:12px;font-family:arial;">'+
									'<div style="margin:0px;padding:5px 0px 5px 0px;background-color:#cccccc;">'+
										'<div align="center" style="margin:0px;padding:0px;float:left;width:48%;">'+
											'<div style="margin:0px;padding:0px;font-weight:bold;">Name</div>'+
										'</div>'+
										'<div align="center" style="margin:0px;padding:0px;float:right;width:48%;">'+
											'<div style="margin:0px;padding:0px;font-weight:bold;">Email</div>'+
										'</div>'+
										'<br clear="all">'+
									'</div>'+
									'<div style="margin:0px;padding:0px;max-height:200px;overflow:auto;border:1px solid #cccccc;">';
							if(response_data.register_friend.length > 0) {
								for(i=0;i<response_data.register_friend.length;i++) {
									if(response_data.register_friend[i].id != response_data.curr_user_id) {
										htmlHolder += '<div align="center" style="margin:0px;padding:5px 0px 5px 0px;font-size:12px;font-family:arial;border-bottom:1px solid #E8E5D4;">'+
												'<div style="margin:0px;padding:0px;float:left;width:48%;">'+
													'<div style="margin:0px;padding:0px;">'+response_data.register_friend[i].socialmedian_url.capitalize()+'</div>'+
												'</div>'+
												'<div style="margin:0px;padding:0px;float:right;width:48%;">'+
													'<div style="margin:0px;padding:0px;">'+response_data.register_friend[i].email+'</div>'+
												'</div>'+
												'<br clear="all">'+
											'</div>';
									}
								}
							} else {
								htmlHolder += '<div align="center" style="margin:0px;padding:5px 0px 5px 0px;font-size:12px;font-family:arial;">No Contacts!</div>';
							}
							htmlHolder += '</div>'+
								'</div>'+
							'</div>'+
							'<div style="margin:0px;padding:10px 0px 0px 0px;">'+
								'<div align="center" style="margin:0px;padding:10px 0px 0px 0px;font-size:14px;font-weight:bold;font-family:arial;">'+
									'Invite friends to socialmedian'+
								'</div>'+
								'<div align="center" style="margin:0px;padding:15px 1px 10px 1px;font-size:12px;font-family:arial;">'+
									'<div align="right" margin:0px;padding:0px 0px 5px 0px">'+
										'<input type="button" value="Check All" onclick="checkAll(\'check_class\')">&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="Uncheck All" onclick="uncheckAll(\'check_class\')">'+
									'</div>'+
									'<div style="margin:0px;padding:5px 0px 5px 0px;background-color:#cccccc;">'+
										'<div align="center" style="margin:0px;padding:0px;float:left;width:48%;">'+
											'<div style="margin:0px;padding:0px;font-weight:bold;">Name</div>'+
										'</div>'+
										'<div align="center" style="margin:0px;padding:0px;float:right;width:48%;">'+
											'<div style="margin:0px;padding:0px;font-weight:bold;">Email</div>'+
										'</div>'+
										'<br clear="all">'+
									'</div>'+
									'<div style="margin:0px;padding:0px;max-height:300px;overflow:auto;border:1px solid #cccccc;">'+
									'<form name="invite" action="/send-invitation" style="margin:0px;padding:0px;">';
									if(response_data.contacts.length > 0) {
										for(j=0;j<response_data.contacts.length;j++) {
										  	htmlHolder += '<div style="margin:0px;padding:5px 0px 5px 0px;font-size:12px;font-family:arial;border-bottom:1px solid #E8E5D4;">'+
												'<div align="center" style="margin:0px;padding:0px;float:left;width:48%;">'+
													'<div style="margin:0px;padding:0px;">';
													 if (response_data.contacts[j].name == null || response_data.contacts[j].name == ""){
													 	htmlHolder += '--';
													 }
													 else
													 {
													 	htmlHolder += response_data.contacts[j].name;
													 }
													htmlHolder +=  '</div>'+
												'</div>'+
												'<div align="left" style="margin:0px;padding:0px;float:right;width:48%;">'+
													'<input class="check_class" type="checkbox" name="invite_friends[]" value="'+response_data.contacts[j].email+'">'+
													'<span align="center" style="margin:0px;padding:0px;">'+response_data.contacts[j].email+'</span>'+
												'</div>'+
												'<br clear="all">'+
											'</div>';
									    }
									} else {
										htmlHolder += '<div align="center" style="margin:0px;padding:5px 0px 5px 0px;font-size:12px;font-family:arial;">No Contacts!</div>';
									}
								htmlHolder += '<div align="right" style="margin:0px;padding:0px 5px 0px 0px;"><input type="submit" value="Invite" disabled></div>'+
									'</form>'+
									'</div>'+
								'</div>'+
							'</div>'+
						'</div>';
		} else {
			htmlHolder = '<div style="padding:15px 0px 0px 0px;margin:0px;width:600px;font-size:13px;font-family:arial;">No contacts!</div>';
		}
		$('contactListDetails').innerHTML = htmlHolder;
		$('contactListDetails').style.display='block';
		$('invite_friends').style.display = "none";
	}
}

var AuthenticatUserFailureCallback = function (){
	$('invite_friends_loader_image').style.display = "none";
	alert("Error on page");
}

var AuthenticatUser404Callback= function (){
	$('invite_friends_loader_image').style.display = "none";
	alert("Error page is not found");
}

function checkAll(cl) {
	var obj = document.getElementsByTagName("input");
	for(i=0;i<obj.length;i++) {
		if(obj[i].className == cl) {
			obj[i].checked = true;
		}
	}
}

function uncheckAll(cl) {
	var obj = document.getElementsByTagName("input");
	for(i=0;i<obj.length;i++) {
		if(obj[i].className == cl) {
			obj[i].checked = false;
		}
	}
}
// ------------------------- end ----------------------------

/**
 * show share box in hot list
 */
function showSharingBox(sId, aId, action) {
	// change the link properties
	//$('share_link_'+aId).className = "shareStoryActive";
	try{
		//$('comment_link_'+aId).className = "commentStoryInactive";
	}catch(e){}

	$('commentShareBoxHolder'+aId).innerHTML = '<div style="margin:0px;padding:0px;">'+
													'<div style="margin:0px;padding:33px 0px 0px 0px;">'+
														'<div style="position:relative;margin:0px;padding:0px;border-top:1px solid #868686;">'+
															'<div class="shareTabActive" id="share_network'+aId+'" onclick="populateShareWithNewsNetwork('+sId+',\''+aId+'\',\'\');" style="position:absolute;top:-23px;left:30px;margin:0px;padding:0px;font-size:12px;width:63px;height:23px;">'+
																'<div align="center" style="margin:0px;padding:5px 0px 0px 0px;">'+
																	'Network'+
																'</div>'+
															'</div>'+
															'<div class="shareTabInactive" id="share_email'+aId+'" onclick="showEmailShareBox('+sId+',\''+aId+'\');" style="position:absolute;top:-23px;left:104px;margin:0px;padding:0px;font-size:12px;width:63px;height:23px;">'+
																'<div align="center" style="margin:0px;padding:5px 0px 0px 0px;">'+
																	'Email'+
																'</div>'+
															'</div>'+
															'<div class="shareTabInactive" id="share_tweet'+aId+'" onclick="showTweetShareBox('+sId+',\''+aId+'\');" style="position:absolute;top:-23px;left:177px;margin:0px;padding:0px;font-size:12px;width:63px;height:23px;">'+
																'<div align="center" style="margin:0px;padding:5px 0px 0px 0px;">'+
																	'Tweet'+
																'</div>'+
															'</div>'+
														'</div>'+
													'</div>'+
													'<div id="innerShareCommentBoxHolder'+aId+'" style="margin:0px;padding:0px;">'+
													'</div>'+
												'</div>';

	$('commentShareBoxHolder'+aId).style.display = "block";

}

/**
 * show tweet share inner box in hot list
 */
function showTweetShareBox(sId, aId) {
	// change tab properties
	$('share_network'+aId).className = "shareTabInactive";
	$('share_network'+aId).style.top = "-24px";
	//$('share_network'+aId).style.borderBottom = "1px solid #868686";
	$('share_email'+aId).className = "shareTabInactive";
	$('share_email'+aId).style.top = "-24px";
	//$('share_email'+aId).style.borderBottom = "1px solid #FFFFFF";
	// Inactive tweet tab in share
	$('share_tweet'+aId).className = "shareTabActive";
	$('share_tweet'+aId).style.top = "-23px";

	// populate email share code
	var htmlHolder = "";
	t_id = 'twit_id'+aId;
	t_pass = 'twit_pass'+aId;
	t_message = 'message'+aId;
	t_save_or_not = 'save_or_not'+aId;
	t_id_pass_div = 'twid_pass'+aId;
	t_id_pass_auto = 'twid_pass_auto'+aId;
	twitter_id = $('twitter_user_id').value;

	if(tweet_story_info[sId][0]=='snip')
	{
		tweet_send_msg = unescape(tweet_story_info[sId][2]);
	}
	else
	{
		tweet_send_msg = unescape(tweet_story_info[sId][1]);
	}

	htmlHolder += '<div id="email_error_div" name="email_error_div" style="margin:0px;padding:5px 0px 0px 0px;font-family:arial;color:#DF1B1B;font-size:13px;" align="center"></div>'+
					'<div style="margin:0px;padding:10px 0px 0px 24px;">'+
						'<div align="right" style="border:0px solid;width:427px;margin:0px;padding:0px;font-size:13px;font-family:arial;font-weight:bold;" id="char_count_status_'+aId+'">119</div>'+
						'<div style="float:left;font-size:13px;width:70px;color:#2367A8;">Message</div>'+
						'<div style="float:left;font-size:12px;width:335px;color:#2164AA;">'+
							'<textarea onblur="return charCount(this.value,\''+aId+'\');" onfocus="return charCount(this.value,\''+aId+'\');" onkeyup="return charCount(this.value,\''+aId+'\');" name="message" style="width:355px;height:50px;border:1px solid #767676;" id="'+t_message+'"></textarea>'+
						'</div>'+
						'<input type="hidden" name="password_save_or_not" id="password_save_or_not_'+aId+'" value="">'+
						'<input type="hidden" id="chage_twitter_info_'+aId+'" value="no">'+
						'<br clear="all">'+
						'<div style="margin:0px;padding:2px 0px 0px 70px;font-size:11px;color:#8F8F8F;width:330px;">'+
							'bit.ly (short) url will be added to the message.'+
						'</div>'+
						'<div style="border:0px solid;margin:0px;padding:2px 0px 4px 70px;font-size:11px;width:330px;">'+
							'<div style="float:left;border:0px solid;margin:0px;padding:0px 0px 0px 3px;font-size:11px;"><INPUT type="radio" name="story_link_'+aId+'" id="sm_story_link_'+aId+'" onclick="tweetMessage(\''+sId+'\',\''+t_message+'\',\'socialmedian\',\''+aId+'\')" checked value="yes"></div>'+
							'<div style="float:left;border:0px solid;margin:0px;padding:2px 0px 0px 3px;font-size:11px;">Link to discuss this story on socialmedian</div><br clear="all">'+
							'<div style="float:left;border:0px solid;margin:0px;padding:0px 0px 0px 3px;font-size:11px;"><INPUT type="radio" name="story_link_'+aId+'" id="orig_story_link_'+aId+'" onclick="tweetMessage(\''+sId+'\',\''+t_message+'\',\'Reading\',\''+aId+'\')" value="yes"></div>'+
							'<div style="float:left;border:0px solid;margin:0px;padding:2px 0px 0px 3px;font-size:11px;">Link to the original story</div><br clear="all">'+
						'</div>'+
						'<div id="'+t_id_pass_div+'" style="margin:0px;padding:2px 0px 0px 70px;font-size:12px;width:330px;">'+
							'<div style="padding-top:5px;font-size:12px;font-family:arial;font-weight:normal;float:left;width:70px;">Twitter ID</div>'+
							'<div style="padding-top:5px;font-size:12px;font-family:arial;font-weight:normal;float:left;"><input type="text" style="border:1px solid #767676;" name="twit_id" id="'+t_id+'" value="'+twitter_id+'"></div><br clear="all">'+
							'<div style="padding-top:3px;font-size:12px;font-family:arial;font-weight:normal;float:left;width:70px;">Password</div>'+
							'<div style="padding-top:3px;font-size:12px;font-family:arial;font-weight:normal;float:left;"><input type="password" style="border:1px solid #767676;" name="twit_pass" id="'+t_pass+'" value=""></div><br clear="all">'+
							'<div style="padding-top:3px;font-size:12px;font-family:arial;font-weight:normal;"><input type="checkbox" checked name="save_or_not" id="'+t_save_or_not+'" value="yes"> Save my twitter password</div>'+
						'</div>'+
						'<div id="'+t_id_pass_auto+'" style="margin:0px;padding:2px 0px 0px 70px;font-size:12px;width:330px;display:none;">'+
							'<div style="padding-top:3px;font-size:12px;font-family:arial;font-weight:normal;">Tweet will be sent using '+twitter_id+'&nbsp;&nbsp;<a style="text-decoration:none;" href="javascript:void(0);" onclick="$(\'chage_twitter_info_'+aId+'\').value=\'yes\';$(\''+t_id_pass_div+'\').style.display=\'block\';$(\''+t_id_pass_auto+'\').style.display=\'none\';">(change)</a></div>'+
						'</div>'+
						'<div style="margin:0px;padding:0px;width:423px;" align="right">'+
							'<input type="button" name="send" id="send_'+aId+'" value="Send" onclick="javascript:sendTweet('+sId+',\''+aId+'\');">'+
						'</div>'+
						'<div style="padding:2px 0px 0px 70px;width:330px;display:none;font-size:12px;font-family:arial;font-weight:normal;color:green;" id="successmessage_'+aId+'"><img src="'+S3_STATIC_ASSETS_PATH+'/images/loader.gif"></div>'
					'</div>';
	$('innerShareCommentBoxHolder'+aId).innerHTML = htmlHolder;
	$('password_save_or_not_'+aId).value = 'no';
	if($('twitter_user_password').value == 'yes')
	{
		$('twid_pass'+aId).style.display = 'none';
		$('twid_pass_auto'+aId).style.display = 'block';
		$('password_save_or_not_'+aId).value = 'yes';
	}
	$('successmessage_'+aId).style.display = 'none';
	tweetMessage(sId,t_message,'socialmedian',aId)
}

/**
 * Tweet message formate
 */
 function tweetMessage(story_info,msgBox,type,aId){
 	var append_source_txt = '';
 	var message = '';
 	if(tweet_story_info[story_info][0]=='story' && !tweet_story_info[story_info][3].blank())
 	{
 		append_source_txt = "["+unescape(tweet_story_info[story_info][3]).truncate(20,'')+"]";
 		message = type + ': ' + unescape(tweet_story_info[story_info][1]).truncate(80,'...') + ' ' +append_source_txt;
 	}
 	else
 	{
 		if(tweet_story_info[story_info][0]=='snip')
 		{
 			message = type + ': ' + unescape(tweet_story_info[story_info][2]).truncate(100,'...');
 		}
 		else
 		{
 			message = type + ': ' + unescape(tweet_story_info[story_info][1]).truncate(100,'...');
 		}
 	}
 	$(msgBox).value = message;
 	charCount(message,aId)
 }


/**
 * Send tweet
 */
 var sendTweet = function(sId,aId) {
 	var postParameters = "story_id="+sId+"&act_id="+aId;
 	postParameters += "&message="+escape($('message'+aId).value);
 	try{
 		sorn = $('save_or_not'+aId).checked?'yes':'no';
 		ssl = $('sm_story_link_'+aId).checked?'yes':'no';
 		postParameters += "&tw_id="+$('twit_id'+aId).value;
 		postParameters += "&tw_pass="+$('twit_pass'+aId).value;
 		postParameters += "&save_pass="+sorn;
 		postParameters += "&pass_already_save_or_not="+$('password_save_or_not_'+aId).value;
 		postParameters += "&sm_story_link="+ssl;
 		postParameters += "&edit_twitter_info="+$('chage_twitter_info_'+aId).value;
 	} catch(e){}
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: sendTweetCallback,
		// Handle 404
		on404: sendTweet404Callback,
		// Handle other errors
		onFailure: sendTweetFailureCallback
	}
	//alert(postParameters);
	new Ajax.Request('/send-story-as-tweet', ajaxRequestOptions);
	$('successmessage_'+aId).style.display = 'block';
	$('successmessage_'+aId).innerHTML = '<img src="'+S3_STATIC_ASSETS_PATH+'/images/loader.gif">';
 }

 /**
 * Send tweet success callback
 */
var sendTweetCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track add news action
	tracAjaxFunctionalities('/send-story-as-tweet');
	//check if there is an error
	if (response_data.error == 1) {
		//alert the error
		$('successmessage_'+response_data.aId).style.display = 'block';
		$('successmessage_'+response_data.aId).style.color = 'red';
		$('successmessage_'+response_data.aId).innerHTML = response_data.message;
	} else {
		$('successmessage_'+response_data.aId).style.display = 'block';
		$('successmessage_'+response_data.aId).style.color = 'green';
		$('successmessage_'+response_data.aId).innerHTML = 'Tweet Sent!';
		if(response_data.save_pass == 'yes')
		{
			$('twitter_user_id').value = response_data.twitter_id;
			$('twitter_user_password').value = 'yes';
			$('twid_pass'+response_data.aId).style.display = 'none';
			$('twid_pass_auto'+response_data.aId).style.display = 'block';
			$('twid_pass_auto'+response_data.aId).innerHTML = '<div style="padding-top:3px;font-size:12px;font-family:arial;font-weight:normal;">Tweet will be sent using '+response_data.twitter_id+'&nbsp;&nbsp;<a style="text-decoration:none;" href="javascript:void(0);" onclick="$(\'chage_twitter_info_'+response_data.aId+'\').value=\'yes\';$(\'twid_pass'+response_data.aId+'\').style.display=\'block\';$(\'twid_pass_auto'+response_data.aId+'\').style.display=\'block\';">(Change)</a></div>';
		}

		try {
			$('clipCommentRsponse'+response_data.aId).innerHTML = response_data.message;
			//yellow fading technique
			startFadingColor = 0;
			fadeElementId = 'clipCommentRsponse'+response_data.aId;
			changeBackgroundColorObject = setInterval(yellowFadingTechnique, 400);
			$('clipCommentRsponse'+response_data.aId).style.display = "block";
		} catch(e) {}
		try {
			$('clipCommentRsponse_hotlist'+response_data.aId).innerHTML = response_data.message;
			//yellow fading technique
			startFadingColor = 0;
			fadeElementId = 'clipCommentRsponse_hotlist'+response_data.aId;
			changeBackgroundColorObject = setInterval(yellowFadingTechnique, 400);
			$('clipCommentRsponse_hotlist'+response_data.aId).style.display = "block";
		} catch(e) {}
		// Hide the comment box
		try {
			$('clip_holder_main'+response_data.aId).style.display = 'none';
		} catch(e) {}
		try {
			$('comment_link_'+response_data.aId+'_div').className = "commentStoryBackgroundInactive";
			$('share_link_'+response_data.aId+'_div').className = "shareStoryBackgroundInactive";
			$('commentShareBoxHolder'+response_data.aId).style.display = "none";
		} catch(e) {}
		// perform clip action and update total clip count
		performClipAction(response_data.sId, response_data.aId);
	}
}
/**
 * Send tweet failure callback function
 */
var sendTweetFailureCallback = function (){
	alert("Error on page");
}
/**
 * Send tweet 404 callback function
 */
var sendTweet404Callback= function (){
	alert("Error page is not found");
}


/**
 * show email share inner box in hot list
 */
function showEmailShareBox(sId, aId) {
	// change tab properties
	$('share_network'+aId).className = "shareTabInactive";
	$('share_network'+aId).style.top = "-24px";
	//$('share_network'+aId).style.borderBottom = "1px solid #868686";
	$('share_email'+aId).className = "shareTabActive";
	$('share_email'+aId).style.top = "-23px";
	//$('share_email'+aId).style.borderBottom = "1px solid #FFFFFF";
	// Inactive tweet tab in share
	$('share_tweet'+aId).className = "shareTabInactive";
	$('share_tweet'+aId).style.top = "-24px";

	// populate email share code
	var htmlHolder = "";
	htmlHolder += '<div id="email_error_div" name="email_error_div" style="margin:0px;padding:5px 0px 0px 0px;font-family:arial;color:#DF1B1B;font-size:13px;" align="center"></div>'+
					'<form id="mailForm" onsubmit="javascript: if($(\'message\').innerHTML==\'Write Your Own Message Here...\'){$(\'message\').innerHTML=\'\'}; sendMail(1,\''+aId+'\'); return false;" >'+
						'<div style="margin:0px;padding:20px 0px 0px 24px;">'+
							'<div style="float:left;font-size:13px;width:70px;color:#2367A8;">Email ID\'s</div>'+
							'<div style="float:left;font-size:12px;width:335px;color:#2164AA;">'+
								'<input type="text" id="recipient_email" name="recipient_email"  style="width:357px;border:1px solid #767676;">'+
							'</div>'+
							'<br clear="all">'+
							'<div style="margin:0px;padding:2px 0px 0px 75px;color:#8F8F8F;font-size:11px;">(multiple Email ID\'s separated by commas)</div>'+
						'</div>'+
						'<div style="margin:0px;padding:10px 0px 0px 24px;">'+
							'<div style="float:left;font-size:13px;width:70px;color:#2367A8;">Message</div>'+
							'<div style="float:left;font-size:12px;width:335px;color:#2164AA;">'+
								'<textarea name="message" style="width:355px;height:50px;border:1px solid #767676;" id="message" onfocus="if($(\'message\').innerHTML==\'Write Your Own Message Here...\'){$(\'message\').innerHTML=\'\';}">Write Your Own Message Here...</textarea>'+
							'</div>'+
							'<br clear="all">'+
							'<input type="hidden" name="story_id" value="'+sId+'">'+
							'<div style="margin:0px;padding:2px 0px 0px 65px;font-size:11px;color:#8F8F8F;width:330px;">'+
								'<input type="checkbox" name="comment" value="comment" checked> Also post this message as a public comment'+
							'</div>'+
							'<div align="left" style="margin:0px;padding:3px 0px 0px 86px;font-family:arial;font-size:10px;color:#8F8F8F;width:330px;">'+
								'Don\'t worry. We won\'t share the name or email address of the person that you sent the story to.'+
							'</div>'+
							'<div style="margin:0px;padding:0px;width:423px;">'+
								'<div id="activity_loading_symbol" style="padding:0px 0px 0px 0px;margin:0px 0px 0px 0px;display:none;float:right;">'+
									'<div style="float:left;padding:0px;margin:0px;"><img src="'+ S3_STATIC_ASSETS_PATH +'/images/loader.gif"></div>'+
									'<div style="float:left;padding:0px 0px 0px 2px;margin:0px;font-size:13px;font-family:arial;">Loading...</div>'+
									'<br clear="all">'+
								'</div>'+
								'<div id="submit_comment_button" style="margin:0px;padding:0px;display:block;"  align="right">'+
									'<input type="submit" name="submit" value="Submit">'+
								'</div>'+
							'</div>'+
						'</div>'+
						'</form>';
	$('innerShareCommentBoxHolder'+aId).innerHTML = htmlHolder;

}

/**
 * show network share inner box in hot list
 */
// request has to be send or not for share with news networks
var shareWithNewsNetworkFlag = new Hash();
function populateShareWithNewsNetwork(sId, aId, response_data) {


	// check from hash, if its already exists then dont send request to server
	var val = shareWithNewsNetworkFlag.get(aId);
	if(val != undefined) {
		showSharingBox(sId, aId);
		// change tab properties
		$('share_email'+aId).className = "shareTabInactive";
		$('share_email'+aId).style.top = "-24px";
		//$('share_email'+aId).style.borderBottom = "1px solid #868686";
		$('share_network'+aId).className = "shareTabActive";
		$('share_network'+aId).style.top = "-23px";
		//$('share_network'+aId).style.borderBottom = "1px solid #FFFFFF";
		// Inactive tweet tab in share
		$('share_tweet'+aId).className = "shareTabInactive";
		$('share_tweet'+aId).style.top = "-24px";

		$('innerShareCommentBoxHolder'+aId).innerHTML = val;
		return;
	}

	// change tab properties
	$('share_email'+aId).className = "shareTabInactive";
	$('share_email'+aId).style.top = "-24px";
	//$('share_email'+aId).style.borderBottom = "1px solid #868686";
	$('share_network'+aId).className = "shareTabActive";
	$('share_network'+aId).style.top = "-23px";
	//$('share_network'+aId).style.borderBottom = "1px solid #FFFFFF";
	// Inactive tweet tab in share
	$('share_tweet'+aId).className = "shareTabInactive";
	$('share_tweet'+aId).style.top = "-24px";

	// populate share with news network code
	var htmlHolder = "";
	htmlHolder = '<div style="margin:0px;padding:20px 0px 0px 24px;">'+
						'<div style="float:left;font-size:12px;width:175px;">Belongs to the News Networks:</div>';
	if(response_data.belongs_to.length > 0)	{
		htmlHolder += '<div id="newsNetworksBelongsTo'+aId+'" style="float:left;font-size:12px;width:300px;color:#2164AA;">';
		for(j=0;j<response_data.belongs_to.length;j++) {
			if(j==0) {
				htmlHolder += '<a href="http://'+APP_DOMAIN+'/network/'+response_data.belongs_to[j].name_permalink+'" target="_blank" style="color:#2164AA;">'+response_data.belongs_to[j].name+'</a>';
			} else {
				htmlHolder += ', <a href="http://'+APP_DOMAIN+'/network/'+response_data.belongs_to[j].name_permalink+'" target="_blank" style="color:#2164AA;">'+response_data.belongs_to[j].name+'</a>';
			}
		}
		htmlHolder += '</div>';
	}
	htmlHolder += '<br clear="all">'+
					'</div>'+
					'<div style="margin:0px;padding:10px 0px 0px 24px;">'+
						'<div style="float:left;font-size:12px;width:175px;">Share with the News Network:</div>';
	if(response_data.network_list.length > 0) {
		htmlHolder += '<div style="float:left;font-size:12px;width:300px;color:#2164AA;">'+
						'<form method="post" id="share_story_with_nc" name="share_story_with_nc" onSubmit="shareStoryWithNewsCircle(\''+aId+'\');return false;">'+
							'<div style="margin:0px;padding:0px 0px 5px 0px;width:290px;">'+
								'<select id="news_circles" name="news_circles" style="width:220px;">';
		for(i=0;i<response_data.network_list.length;i++) {
			htmlHolder += '<option value="'+response_data.network_list[i].id+'">'+response_data.network_list[i].name+'</option>';
		}
					htmlHolder += '</select>'+
								'<input type="hidden" name="story_id" value="'+sId+'">'+
								'&nbsp;&nbsp;<input type="submit" name="share" value="Share">'+
							'</div>'+
						'</form>'+
						'</div>';
	} else {
		htmlHolder += '<div style="float:left;font-size:12px;width:300px;color:#000000;">There are no other News Networks that you have joined.</div>';
	}
	htmlHolder += '<br clear="all">'+
					'</div>';

	$('innerShareCommentBoxHolder'+aId).innerHTML = htmlHolder;

	// if flag is set, not send request when tab change.
	shareWithNewsNetworkFlag.set(aId,htmlHolder);
}

function getStoryShareInfo(){
	if(share == "regular") {
		var val = shareWithNewsNetworkFlag.get(aId);
		if(val != undefined) {
			showSharingBox(story_id, aId);
			$('innerShareCommentBoxHolder'+aId).innerHTML = val;
			return;
		}
	}
}
/**
 * hide comment/share box
 */
function hideCommentShareBox(uniqId) {
	$('comment_link_'+uniqId+'_div').className = "commentStoryBackgroundInactive";
	$('share_link_'+uniqId+'_div').className = "shareStoryBackgroundInactive";
	$('commentShareBoxHolder'+uniqId).style.display = "none";
}

/**
 * show comment box in hot list
 */
var cur_user_socialmedian_url = "";
function showCommentingBox(data) {

	// change the link properties
	//$('comment_link_'+data.act_id).className = "commentStoryActive";
	//$('share_link_'+data.act_id).className = "shareStoryInactive";
    // assign current user socialmedian_url to variable
	cur_user_socialmedian_url = data.cur_user;
	var htmlHolder = "";
	var display_comment_count = 3;
	htmlHolder += '<div style="margin:0px;padding:0px;">'+
												'<div style="margin:0px;padding:3px 0px 5px 15px;background-color:#ECECEC;font-family:arial;font-size:14px;color:#2367A8;">';
		if(data.comment_count <= 3) {
		    display_comment_count = data.comment_count;
			htmlHolder += '<div id="commentCountHeader'+data.act_id+'" style="margin:0px;padding:0px;float:left;"><div style="float:left;">Showing&nbsp;</div><div id="out_of_comment_'+data.act_id+'" style="float:left;">'+data.result.length+'</div><div style="float:left;">&nbsp;out of&nbsp;</div><div id="total_comment_'+data.act_id+'" style="float:left;">'+data.comment_count+'</div><div style="float:left;">&nbsp;comments</div></div>';
		} else {
			htmlHolder += '<div id="commentCountHeader'+data.act_id+'" style="margin:0px;padding:0px;float:left;"><div style="float:left;">Showing&nbsp;</div><div id="out_of_comment_'+data.act_id+'" style="float:left;">3</div><div style="float:left;">&nbsp;recent comments out of&nbsp;</div><div id="total_comment_'+data.act_id+'" style="float:left;">'+data.comment_count+'</div><div style="float:left;">&nbsp;comments &nbsp;&nbsp;<a id="comment_view_all_link'+data.act_id+'" onclick="viewAllComments('+data.story_id+','+data.act_id+','+data.comment_count+','+display_comment_count+');" style="font-family:arial;font-size:12px;color:#696969;cursor:pointer;text-decoration:underline;">View All</a></div></div>';
		}

									htmlHolder += '<div style="margin:0px;padding:2px 8px 0px 0px;float:right;"><img onclick="hideCommentShareBox('+data.act_id+');" src="'+ S3_STATIC_ASSETS_PATH + '/images/Close-button.png" style="cursor:pointer;"></div>'+
													'<br clear="all">'+
												'</div>'+
												'<div id="innerShareCommentBoxHolder'+data.act_id+'" style="margin:0px;padding:0px;">';
		if(data.result.length > 0) {
			var allCommentCount = ((data.result.length - 3) <= 0 ? 0 : (data.result.length - 3))
			for(i=0;i<data.result.length;i++) {
				data.result[i].comment_text = data.result[i].comment_text.gsub(/(?:\r\n|\n)/, "<br/>");
				if(i==0 && allCommentCount > 0) {
					htmlHolder += '<div id="showAllComments'+data.act_id+'" style="margin:0px;padding:0px;display:none;">';
				}
									htmlHolder += '<div style="margin:0px;padding:10px 0px 0px 15px;">'+
														'<div style="margin:0px;padding:0px;float:left;"><img src="'+ S3_DYNAMIC_ASSETS_PATH +'/user-images/'+data.result[i].commented_by+'-small.jpg"></div>'+
														'<div style="margin:0px;padding:2px 0px 2px 5px;float:left;font-size:11px;width:450px;"><a href="/'+data.result[i].socialmedian_url+((data.result[i].socialmedian_url == data.cur_user)? '/home': '')+'" style="color:#2464AB;cursor:pointer;text-decoration:underline;">'+((data.result[i].socialmedian_url == data.cur_user)? 'You': data.result[i].socialmedian_url.capitalize())+'</a>, <span style="color:#898989;">'+data.result[i].commented_on+'</span> : '+data.result[i].comment_text+'</div>'+
														'<br clear="all">'+
													'</div>';
									allCommentCount--;
				if(allCommentCount == 0) {
					htmlHolder += '</div>';
				}
			}
		}
		htmlHolder += '</div>'+
					'<div style="margin:0px;padding:10px 0px 0px 15px;">'+
						'<form id="clipCommentForm'+data.act_id+'" onsubmit="javascript: addClipComment('+data.story_id+',\''+data.act_id+'\'); return false;" style="margin:0px;padding:0px;">'+
						'<input type="hidden" id="display_comment_count_'+data.act_id+'" value="'+display_comment_count+'">'+
						'<div style="margin:0px;padding:0px;float:left;"><img src="'+ S3_DYNAMIC_ASSETS_PATH +'/user-images/'+data.cur_user_id+'-small.jpg"></div>'+
						'<div style="margin:0px;padding:2px 0px 0px 5px;float:left;font-size:11px;"><a href="/'+data.cur_user+'/home" style="color:#2464AB;cursor:pointer;text-decoration:underline;">You</a></div>'+
						'<div style="margin:0px;padding:0px 0px 0px 5px;float:left;font-size:12px;width:370px;color:#2164AA;">'+
							'<textarea id="user_comment'+data.act_id+'" name="user_comment" autocomplete="off" value="" style="width:370px;height:45px;border:1px solid #C1C1C1;" onkeyup="auto_complete_my_contacts(event, \''+data.act_id+'\');"></textarea>'+
							'<div id="sm_contacts_auto_complete'+data.act_id+'" class="replize_autocompleter" style="display: none;"></div>'+
						'</div>'+
						'<div style="margin:0px;padding:26px 0px 0px 7px;float:left;"><input type="submit" name="submit" value="Add"></div>'+
						'<br clear="all">'+
						'</form>'+
					'</div>'+
				'</div>';

	$('commentShareBoxHolder'+data.act_id).innerHTML = htmlHolder;
	$('commentShareBoxHolder'+data.act_id).style.display = "block";
			try{
			showLessCount[data.act_id] = parseInt($('out_of_comment_'+data.act_id).innerHTML);
			// change comment counts

			if(data.comment_count == 1) {
				$('comment_link_'+data.act_id).innerHTML = "1 Comment";
			} else if(data.comment_count > 1) {
				$('comment_link_'+data.act_id).innerHTML = data.comment_count+" Comments";
			}

			}
			catch(e){}

}
// hash to maintain view all entry for story comments
var viewAllCommentsForStoy = new Hash();
var showLessCount = new Array();
function viewAllComments(sId, aId, total_count, display_count) {
	// make a string
	var val = viewAllCommentsForStoy.get(aId);
	if(val == undefined) {
		getStoryComments(sId, aId, 0);
	} else {
		$('commentShareBoxHolder'+aId).style.display = "block";
		try {
			if($('comment_view_all_link'+aId).innerHTML == "View All") {

				// Comment count header
				try {
				var ofc = parseInt($('out_of_comment_'+aId).innerHTML);
			    var tc = parseInt($('total_comment_'+aId).innerHTML);

				$('out_of_comment_'+aId).innerHTML = tc;
				$('total_comment_'+aId).innerHTML = tc;
				showLessCount[aId] = ofc;
					//$('commentCountHeader'+response_data.act_id).innerHTML ='Showing '+total_count+' out of '+total_count+' comments &nbsp;&nbsp;<a id="comment_view_all_link'+aId+'" onclick="viewAllComments('+sId+','+aId+','+total_count+','+display_count+');" style="font-family:arial;font-size:12px;color:#696969;cursor:pointer;text-decoration:underline;">View All</a>';
				} catch(e) {}

				$('comment_view_all_link'+aId).innerHTML = "View less";
				$('showAllComments'+aId).style.display = "block";
				$('display_comment_count_'+response_data.act_id).value = total_count;

			} else {
				// Comment count header
				try {
				var ofc = parseInt($('out_of_comment_'+aId).innerHTML);
			    var tc = parseInt($('total_comment_'+aId).innerHTML);

				$('out_of_comment_'+aId).innerHTML = showLessCount[aId];
				$('total_comment_'+aId).innerHTML = tc;
				   // $('commentCountHeader'+response_data.act_id).innerHTML ='Showing '+display_count+' out of '+total_count+' comments &nbsp;&nbsp;<a id="comment_view_all_link'+aId+'" onclick="viewAllComments('+sId+','+aId+','+total_count+','+display_count+');" style="font-family:arial;font-size:12px;color:#696969;cursor:pointer;text-decoration:underline;">View All</a>';
				} catch(e) {}
				$('comment_view_all_link'+aId).innerHTML = "View All";
				$('showAllComments'+aId).style.display = "none";
			}
		} catch(e) {}
	}
}

/**
 * get all comments for the story
 */
var getStoryComments = function (sId, aId, pPage, user_id, user_url){
	// Check for total comment. if its 0 then don't make database query
		try {
			var arr = $('comment_link_'+aId).innerHTML.split(" ");
			var val = parseInt(arr[0])+1;
			if(isNaN(val)) {
				// create hash
				var data = {"comment_count":0,"act_id":aId,"cur_user":user_url,"story_id":sId,"cur_user_id":user_id,"result":[]};
				showCommentingBox(data);
				return;
			}
		} catch(e) {}
	// show loading image
	$('commentShareBoxHolder'+aId).innerHTML = '<div style="padding:4px 0px 0px 0px;margin:0px;width:150px;">'+
													'<div style="float:left;padding:0px;margin:0px;"><img src="'+ S3_STATIC_ASSETS_PATH + '/images/loader.gif"></div>'+
													'<div style="float:left;padding:0px 0px 0px 5px;margin:0px;font-size:13px;">Loading...</div>'+
													'<br clear="all">'+
												'</div>';
	$('commentShareBoxHolder'+aId).style.display = "block";
	var postParameters = "story_id="+sId+"&act_id="+aId+"&per_page="+pPage;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: function(response){getStoryCommentsCallback(response);},
		// Handle 404
		on404: getStoryComments404Callback,
		// Handle other errors
		onFailure: getStoryCommentsFailureCallback
	}
	new Ajax.Request('/get-story-comments', ajaxRequestOptions);
}

/**
 * get all comments for the story success callback
 */
var getStoryCommentsCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track add news action
	tracAjaxFunctionalities('/get-story-comments');
	//check if there is an error
	if (response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		viewAllCommentsForStoy.set(response_data.act_id,'1');
		showCommentingBox(response_data);
	}
}
/**
 * get all comments for the story failure callback function
 */
var getStoryCommentsFailureCallback = function (){
	alert("Error on page");
}
/**
 * get all comments for the story 404 callback function
 */
var getStoryComments404Callback= function (){
	alert("Error page is not found");
}

/**
 * Refresh snapshots
 */
function refreshSnapshots() {
	try {
		if(location.host == APP_DOMAIN){
			SNAP_COM = { shot_main_js_called: false };
			//var head = $("snap");
			var head = document.getElementsByTagName("head")[0];
			var script = document.createElement("script");
			script.type = 'text/javascript';
			//script.id = 'snapShots';
			//script.src = '/javascripts/snap_shots.js';
			script.src = 'http://shots.snap.com/ss/0744c6fd1325c88c0accb3bed42a90de/snap_shots.js';
			head.appendChild(script);
		}
	} catch(e){}
}

/**
 * Settign page visited or not
 */
 var settingPageVisited = function (setting_page){
 	var postParameters = "setting_page="+setting_page
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: settingPageVisitedCallback,
		// Handle 404
		on404: settingPageVisited404Callback,
		// Handle other errors
		onFailure: settingPageVisitedFailureCallback
	}
	new Ajax.Request('/setting_page_visited', ajaxRequestOptions);
}

/**
 * settingPageVisited success callback
 */
var settingPageVisitedCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track add news action
	tracAjaxFunctionalities('/setting_page_visited');
	//check if there is an error
	if (response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		if(response_data.action == 'aboutme')
		{
			window.location = "/settings?act=aboutme";
		}
		else if(response_data.action == 'alert')
		{
			window.location = "/settings?act=alert";
		}
	}
}
/**
 * settingPageVisited failure callback function
 */
var settingPageVisitedFailureCallback = function (){
	alert("Error on page");
}
/**
 * settingPageVisited 404 callback function
 */
var settingPageVisited404Callback= function (){
	alert("Error page is not found");
}

/**
 * get current users all news networks
 */
var getAllNetworksAjaxCall = 0;
function getAllNetworks(user_id, str) {
	if(getAllNetworksAjaxCall == 1) {
		// Don't send any request
		if(str == 'more') {
			$('user_networks').style.display = 'block';
		} else if(str == 'less') {
			$('user_networks').style.display = 'none';
		}
	} else {
		// Send ajax request
		getUsersAllNewsNetworks(user_id);
	}
}

/**
 * populate current users all news networks
 */
var months = new Hash({"01":"Jan","02":"Feb","03":"Mar","04":"Apr","05":"May","06":"Jun","07":"Jul","08":"Aug","09":"Sep","10":"Oct","11":"Nov","12":"Dec"});
function populateAllUserNetworks(data) {
	var htmlHolder = "";
	var extra_div_flag = 0;
	for(i=0;i<data.network_list.length;i++) {
		if(i == 11) {
			htmlHolder += '<div id="user_networks" style="margin:0px;padding:0px;">';
			extra_div_flag = 1;
		}
		htmlHolder += '<div style="padding:0px 0px 2px 10px;font-size:14px;" align="left">'+
			'<a href="/network/'+data.network_list[i].name_permalink+'" style="text-decoration:underline;">'+data.network_list[i].name+'</a>'+
		'</div>'+
		'<div style="padding:0px 0px 8px 10px;font-size:11px;" align="left">';
			if(data.network_list[i].socialmedian_url == data.cur_user) {
				htmlHolder += 'Created by: <a href="/'+data.network_list[i].socialmedian_url+'/home" style="color:gray">'+data.network_list[i].socialmedian_url.capitalize()+'</a>';
			} else {
				htmlHolder += 'Created by: <a href="/'+data.network_list[i].socialmedian_url+'" style="color:gray">'+data.network_list[i].socialmedian_url.capitalize()+'</a>';
			}
			var date_str = data.network_list[i].added_on.split(" ");
			htmlHolder += ' on '+months.get(date_str[0].split("/")[1])+' '+date_str[0].split("/")[2]+', '+date_str[0].split("/")[0]+
		'</div>';
	}
	if(extra_div_flag == 1) {
		htmlHolder += '</div>';
	}
	$('user_networks_holder').innerHTML = htmlHolder;
	getAllNetworksAjaxCall = 1;
}

/**
 * Settign page visited or not
 */
 var getUsersAllNewsNetworks = function (user_id){
 	$('network_loader_image').style.display = 'block';
 	var postParameters = "user_id="+user_id;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: getUsersAllNewsNetworksCallback,
		// Handle 404
		on404: getUsersAllNewsNetworks404Callback,
		// Handle other errors
		onFailure: getUsersAllNewsNetworksFailureCallback
	}
	new Ajax.Request('/get-user-all-networks', ajaxRequestOptions);
}

/**
 * settingPageVisited success callback
 */
var getUsersAllNewsNetworksCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	//check if there is an error
	$('network_loader_image').style.display = 'none';
	if (response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		populateAllUserNetworks(response_data);
	}
}
/**
 * settingPageVisited failure callback function
 */
var getUsersAllNewsNetworksFailureCallback = function (){
	alert("Error on page");
}
/**
 * settingPageVisited 404 callback function
 */
var getUsersAllNewsNetworks404Callback= function (){
	alert("Error page is not found");
}

/**
 * edit clips header name in my page
 */
 var editClipsHeaderText = function (){
 	if($('clips_header_text').value.strip() == "") {
 		alert("Please enter some Heading text");
 		return false;
 	}
 	if($('clips_header_text').value.strip().length > 80) {
 		alert("Exceeding character limit");
 		return false;
 	}
 	var postParameters = "clip_heading="+$('clips_header_text').value;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: editClipsHeaderTextCallback,
		// Handle 404
		on404: editClipsHeaderText404Callback,
		// Handle other errors
		onFailure: editClipsHeaderTextFailureCallback
	}
	new Ajax.Request('/edit-clips-header-text', ajaxRequestOptions);
}

/**
 * edit clips header name in my page success callback
 */
var editClipsHeaderTextCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	//check if there is an error
	if (response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		$('mypage_clips_header_text').innerHTML = response_data.heading+' <font style="font-size:13px;">( <a onclick="$(\'mypage_clips_header_text\').style.display = \'none\';$(\'mypage_clips_header_text_edit\').style.display = \'block\';" style="font-size:13px;font-weight:normal;cursor:pointer;text-decoration:underline;">Edit</a> )</font>';
		$('mypage_clips_header_text_edit').style.display = 'none';
		$('mypage_clips_header_text').style.display = 'block';
	}
}
/**
 * edit clips header name in my page failure callback function
 */
var editClipsHeaderTextFailureCallback = function (){
	alert("Error on page");
}
/**
 * edit clips header name in my page 404 callback function
 */
var editClipsHeaderText404Callback= function (){
	alert("Error page is not found");
}

/**
 * signup from other pages
 */
 var signupFromOtherPage = function (val){
	var error_message = '';
	var userEmail = $('lightbox_signup_user_email').value.strip();
	var userPassword = $('lightbox_signup_user_password').value.strip();
	var userName = $('lightbox_signup_socialmedian_url').value.strip();

	if(userEmail == '') {
		error_message = "Email should not be blank";
	} else if(userPassword == '') {
		error_message = "Password should not be blank";
	} else if (userName.match(/[^a-zA-z0-9_\-]/)!=null) {
		error_message = "Username must be one word or contain '_' or '-'" ;
	} else if(userName.length < 2 || userName.length > 20) {
		error_message = 'Username must be 2 to 20 characters long.';
	} else if(userName=='username') {
		error_message = 'Fill a unique username for url';
	} else if(userName=='') {
		error_message = 'Fill a unique username for url';
	} else if($('agree_signup_policy').checked==false) {
		error_message = 'You need to accept the terms and conditions and the privacy policy.';
	}
 	if(error_message != "") {
 		$('nn_signup_error').style.display = "block";
 		$('nn_signup_error').innerHTML = error_message;
 		if(Prototype.Browser.IE) {
 			Recaptcha.reload();
 		}
 		return false;
 	}
 	//show loading image
 	$('signup_loading').style.display = "block";
 	var postParameters = Form.serialize("nn_signup");
 	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: function(response){signupFromOtherPageCallback(response, val)},
		// Handle 404
		on404: signupFromOtherPage404Callback,
		// Handle other errors
		onFailure: signupFromOtherPageFailureCallback
	}
	new Ajax.Request('/signup', ajaxRequestOptions);
}

/**
 * signup from other pages success callback
 */
var signupFromOtherPageCallback = function (response, val){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track add news action
	tracAjaxFunctionalities('/signup');
	//urchinTracker('/signup');
	//hide loading image
 	$('signup_loading').style.display = "none";
	//check if there is an error
	if (response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		if (response_data.status == "success") {
			if(val != 0) {
				var firstTime = window.location.href.indexOf("?");
				var temp = window.location.href;
				if (firstTime != -1) {
					var siteURL = temp + '&gsm_pnn=1';
				} else {
					var siteURL = temp + '?gsm_pnn=1';
				}
				window.location.href = siteURL;
			} else {
				//$('onfly_recaptcha').style.display = "block";
				window.location = "http://"+location.host;
			}
		} else if(response_data.status == "success_reactivation") {
			window.location = window.location.href;
		} else if(response_data.status == "failure") {
			$('nn_signup_error').style.display = "block";
 			$('nn_signup_error').innerHTML = response_data.message;
 			// refresh the captcha widget
			Recaptcha.reload();
		}
	}
}
/**
 * signup from other pages failure callback function
 */
var signupFromOtherPageFailureCallback = function (){
	//hide loading image
 	$('signup_loading').style.display = "none";
	alert("Error on page");
}
/**
 * signup from other pages 404 callback function
 */
var signupFromOtherPage404Callback= function (){
	//hide loading image
 	$('signup_loading').style.display = "none";
	alert("Error page is not found");
}

/**
 * login from other pages
 */
 var loginFromOtherPage = function (place_called_from){
 	//check for blank login fields.
 	if(place_called_from == "nn"){
		try{
			$('lb_login_error_msg').style.display = "none";
		} catch(e){}
	}
 	//hide login incorrect message
 	$(place_called_from+'_login_incorrect').style.display = "none";
 	//show loading image
 	$(place_called_from+'_login_loading').style.display = "block";
	var postParameters = Form.serialize(place_called_from+"_login_form");
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess:  function(response){ loginFromOtherPageCallback(response,place_called_from); },
		// Handle 404
		on404: loginFromOtherPage404Callback,
		// Handle other errors
		onFailure: loginFromOtherPageFailureCallback
	}
	if(($(place_called_from+'_email').value != 'Email Id or Username') && ($(place_called_from+'_password').value!= 'Password') && ($(place_called_from+'_email').value != '') && ($(place_called_from+'_password').value!= '')){
		new Ajax.Request('/login', ajaxRequestOptions);
	}else{
		$(place_called_from+'_login_loading').style.display = "none";
	}
}
/**
 * login from other pages success callback
 */
var loginFromOtherPageCallback = function (response,place_called_from){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track add news action
	tracAjaxFunctionalities('/login');
	//hide loading image
 	$(place_called_from+'_login_loading').style.display = "none";
	//check if there is an error
	if (response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		if (response_data.status == "success") {
			window.location = window.location.href;
		} else if (response_data.status == "failure" && place_called_from == "nn") {
			$('lb_login_error_msg').innerHTML = response_data.message
			$('lb_login_error_msg').style.display = "block";
		}
	}
}
/**
 * login from other pages failure callback function
 */
var loginFromOtherPageFailureCallback = function (){
	//hide loading image
 	$('login_loading').style.display = "none";
	alert("Error on page");
}
/**
 * login from other pages 404 callback function
 */
var loginFromOtherPage404Callback= function (){
 	$('login_loading').style.display = "none";
	alert("Error page is not found");
}

// Newsmaker ajax functionalities
// store user prferences for future use
var userPrefHash = new Hash();

// show preference box
function showPreference(uId,userUrl) {
	if(userPrefHash.get(uId)) {
		createPrefBox(uId, userUrl);
		$('userPreferenceImage'+uId).style.display = "block";
		$('userPreferenceImage'+uId).className = "prferenceActive";
	} else {
		startFollowingUser(uId, userUrl);
	}
}

// hide preference box
function closePreference(uId) {
	$('userPrefBox'+uId).style.display = "none";
	$('userPreferenceImage'+uId).style.display = "block";
	$('userPreferenceImage'+uId).className = "prferenceInactive";
}

// create box to show preference options
function createPrefBox(uId, userUrl) {
	var htmlHolder = '<div align="left" id="userPrefBox'+uId+'" class="userPrefBox" style="margin:0px;padding:3px;position:absolute;top:5px;left:-105px;width:195px;background:#EFEFEF;z-index:1001;border:1px solid #B8B8B8;">'+
						'<div style="margin:0px;padding:0px 0px 0px 10px;float:left;font-size:13px;">Set your preferences</div>'+
						'<div style="margin:0px;padding:0px 6px 0px 0px;float:right;font-size:13px;"><img onclick="closePreference('+uId+');" src="'+S3_STATIC_ASSETS_PATH+'/images/pref-close.png" style="cursor:pointer;"></div>'+
						'<br clear="all">'+
						'<div id="followSuccessMsg'+uId+'" style="margin:0px;padding:5px 0px 5px 10px;font-size:13px;font-weight:bold;color:#D95700;display:none;"></div>'+
						'<div style="margin:0px;padding:4px 0px 0px 10px;text-align:left;">'+
							'<div style="margin:0px;padding:0px;font-size:13px;"><input type="radio" name="user_pref" id="user_pref'+uId+'" onclick="updatePreference('+uId+',\''+userUrl+'\',this)" value="all" '+(userPrefHash.get(uId) == 'all'? 'checked': '')+'> All updates <img src="'+S3_STATIC_ASSETS_PATH+'/images/Help.png" style="cursor:pointer;"></div>'+
							'<div style="margin:0px;padding:0px;font-size:13px;"><input type="radio" name="user_pref" id="user_pref'+uId+'" onclick="updatePreference('+uId+',\''+userUrl+'\',this)" value="network" '+(userPrefHash.get(uId) == 'network'? 'checked': '')+'> Only relevent updates <img src="'+S3_STATIC_ASSETS_PATH+'/images/Help.png" style="cursor:pointer;"></div>'+
							'<div style="margin:0px;padding:0px;font-size:13px;"><input type="radio" name="user_pref" id="user_pref'+uId+'" onclick="updatePreference('+uId+',\''+userUrl+'\',this)" value="stop"> Stop Following <img src="'+S3_STATIC_ASSETS_PATH+'/images/Help.png" style="cursor:pointer;"></div>'+
						'</div>'+
					'</div>';
	try {
		$('prefBoxHolder'+uId).innerHTML = htmlHolder;
		userPrefSettings = {
			tl: { radius: 5 },
			tr: { radius: 5 },
			bl: { radius: 5 },
			br: { radius: 5 },
			antiAlias: true,
			autoPad: false,
			validTags: ["div"]
		}
		var userPrefBoxObject = new curvyCorners(userPrefSettings, $('userPrefBox'+uId));
		userPrefBoxObject.applyCornersToAll();
	} catch(e){}
}

// update activity preference
function updatePreference(uId, userUrl, obj) {
	if(obj.value == "stop") {
		stopFollowingUser(uId, userUrl);
	} else if(userPrefHash.get(uId) != obj.value) {
		updateActivityPreference(uId, obj.value);
	}
}

/**
 * update activity preference of a user
 */
 var updateActivityPreference = function (uId, prefValue){
	var postParameters = "user_id="+uId+"&pref="+prefValue;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: updateActivityPreferenceCallback,
		// Handle 404
		on404: updateActivityPreference404Callback,
		// Handle other errors
		onFailure: updateActivityPreferenceFailureCallback
	}
	new Ajax.Request('/update-activity-preference', ajaxRequestOptions);
}

/**
 * update activity preference of a user success callback
 */
var updateActivityPreferenceCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track add news action
	tracAjaxFunctionalities('/update-activity-preference');
	//check if there is an error
	if (response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		if(response_data.message == "success") {
			userPrefHash.set(response_data.user_id, response_data.pref);
			try {
				$('userPrefBox'+response_data.user_id).style.display = "none";
				$('userPreferenceImage'+response_data.user_id).className = "prferenceInactive";
			} catch(e){}
		}
	}
}
/**
 * update activity preference of a user failure callback function
 */
var updateActivityPreferenceFailureCallback = function (){
	alert("Error on page");
}
/**
 * update activity preference of a user 404 callback function
 */
var updateActivityPreference404Callback= function (){
	alert("Error page is not found");
}

/**
 * start following user
 */
 var startFollowingUser = function (uId, userUrl){
	try {
		$('userPreference'+uId).style.display = "none";
		$('userPreferenceImage'+uId).style.display = "none";
	} catch(e){}
	// show loading image
	try {
		$('preferenceLoader'+uId).style.display = 'block';
	} catch(e){}
	try {
		$('userPreferenceDiv'+uId).innerHTML = '<img src="'+ S3_STATIC_ASSETS_PATH +'/images/loader.gif">';
	} catch(e){}
	var postParameters = "user_id="+uId+"&user_url="+userUrl;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: startFollowingUserCallback,
		// Handle 404
		on404: startFollowingUser404Callback,
		// Handle other errors
		onFailure: startFollowingUserFailureCallback
	}
	new Ajax.Request('/start-following', ajaxRequestOptions);
}

/**
 * start following user success callback
 */
var startFollowingUserCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track add news action
	tracAjaxFunctionalities('/start-following');
	// hide loading image
	try {
		$('preferenceLoader'+response_data.user_id).style.display = 'none';
	} catch(e){}
	//check if there is an error
	if (response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		if(response_data.message == "success") {
			// set value in hash
			userPrefHash.set(response_data.user_id, "all");
			// show preference arrow image
			try {
				$('userPreferenceImage'+response_data.user_id).className = "prferenceInactive";
				$('userPreferenceImage'+response_data.user_id).style.display = "block";
				$('userPreference'+response_data.user_id).style.display = "block";
				$('userPreference'+response_data.user_id).innerHTML = 'Preferences';
				// show preference box with success message
				//createPrefBox(response_data.user_id);
				//$('followSuccessMsg'+response_data.user_id).style.display = "block";
				//$('followSuccessMsg'+response_data.user_id).innerHTML = response_data.user_url.capitalize()+" is now your Newsmaker";
			} catch(e){}
			// hotlist user shortinfo
			try {
				$('userPreferenceDiv'+response_data.user_id).innerHTML = response_data.user_url.capitalize()+" is now your Newsmaker";
			} catch(e){}
			try{
				$('invite_friend_follow_'+response_data.user_id).style.display = 'none';
			} catch(e){}
			// change arrow images
			try {
				var downArrow = document.getElementsByClassName("arrowDownFollow");
				for(i=0;i<downArrow.length;i++) {
					if(downArrow[i].id == "followArrow"+response_data.user_id) {
						downArrow[i].className = "arrowBothFollow";
					}
				}

				var noArrow = document.getElementsByClassName("arrowNone");
				for(i=0;i<noArrow.length;i++) {
					if(noArrow[i].id == "followArrow"+response_data.user_id) {
						noArrow[i].style.display = "block";
						noArrow[i].className = "arrowUpFollow";
					}
				}
			} catch(e){}
			try {

				$('followMsg').innerHTML = "You are following "+response_data.user_url.capitalize();
			} catch(e){}
			// update hash
			try {
				var k1 = globalUserId+"-"+response_data.user_id;
				var k2 = response_data.user_id+"-"+globalUserId;
				if((followRelation[k1] != null && followRelation[k1][globalUserId]) || (followRelation[k1] != null && followRelation[k1][response_data.user_id]) || (followRelation[k2] != null && followRelation[k2][globalUserId]) || (followRelation[k2] != null && followRelation[k2][response_data.user_id])) {
					followRelation[k2] = new Array();
					followRelation[k2][globalUserId] = "y";

					// show success msg
					$('followSuccessMsg'+SHORT_INFO_DIV_ID).innerHTML = '<div style="padding:2px 0px 0px 0px;margin:0px;width:98px;">'
											 +		'<div style="padding:0px;margin:0px;float:left;font-family:Arial;font-size:12px;font-weight:bold;color:#568BBE"><a href="/users?s=my-readers" style="color:#568BBE;cursor:pointer;text-decoration:none;">Following you</a></div>'
											 +		'<div style="padding:0px 0px 0px 4px;margin:0px;float:left;"><span class="arrowDownFollow"></span></div>'
											 +		'<br clear="all"/>'
											 +	'</div>'
											 +	'<div style="padding:5px 0px 0px 0px;margin:0px;width:100px;">'
											 +		'<div style="padding:0px;margin:0px;float:left;font-family:Arial;font-size:12px;font-weight:bold;color:#568BBE"><a href="/users?s=my-newsmakers" style="color:#568BBE;cursor:pointer;text-decoration:none;">Newsmaker</a></div>'
											 +		'<div style="padding:0px 0px 0px 4px;margin:0px;float:left;"><span class="arrowUpFollow"></span></div>'
											 +		'<br clear="all"/>'
											 +	'</div>';
				} else {
					followRelation[k2] = new Array();
					followRelation[k2][globalUserId] = "n";

					// show success msg
					$('followSuccessMsg'+SHORT_INFO_DIV_ID).innerHTML = '<div style="padding:2px 0px 0px 0px;margin:0px;width:100px;">'
											 +		'<div style="padding:0px;margin:0px;float:left;font-family:Arial;font-size:12px;font-weight:bold;color:#568BBE"><a href="/users?s=my-newsmakers" style="color:#568BBE;cursor:pointer;text-decoration:none;">Newsmaker</a></div>'
											 +		'<div style="padding:0px 0px 0px 4px;margin:0px;float:left;"><span class="arrowUpFollow"></span></div>'
											 +		'<br clear="all"/>'
											 +	'</div>';
				}
			} catch(e){}
		}
	}
}
/**
 * start following user failure callback function
 */
var startFollowingUserFailureCallback = function (){
	alert("Error on page");
}
/**
 * start following user 404 callback function
 */
var startFollowingUser404Callback= function (){
	alert("Error page is not found");
}

/**
 * stop following user
 */
 var stopFollowingUser = function (uId, userUrl){
	$('userPreference'+uId).style.display = "none";
	$('userPreferenceImage'+uId).style.display = "none";
	// show loading image
	try {
		$('preferenceLoader'+uId).style.display = 'block';
	} catch(e){}
	var postParameters = "user_id="+uId;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: function(response) {stopFollowingUserCallback(response, userUrl);},
		// Handle 404
		on404: stopFollowingUser404Callback,
		// Handle other errors
		onFailure: stopFollowingUserFailureCallback
	}
	new Ajax.Request('/stop-following', ajaxRequestOptions);
}

/**
 * stop following user success callback
 */
var stopFollowingUserCallback = function (response, userUrl){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track add news action
	tracAjaxFunctionalities('/stop-following');
	// hide loading image
	try {
		$('preferenceLoader'+response_data.user_id).style.display = 'none';
	} catch(e){}
	//check if there is an error
	if (response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		if(response_data.message == "success") {
			// unset value from hash
			userPrefHash.unset(response_data.user_id);
			// hide preference arrow image
			$('userPreferenceImage'+response_data.user_id).style.display = "none";
			// hide preference box
			$('userPrefBox'+response_data.user_id).style.display = "none";
			$('userPreference'+response_data.user_id).style.display = "block";
			$('userPreference'+response_data.user_id).innerHTML = '<img src="'+S3_STATIC_ASSETS_PATH+'/images/Followon-White.png" style="width:74px;height:19px;">';

			// change mypage userbox text
			try {
				$('followMsg').innerHTML = "Follow "+userUrl.capitalize();
			} catch(e){}

			// change arrow images
			try {
				var bothArrow = document.getElementsByClassName("arrowBothFollow");
				for(i=0;i<bothArrow.length;i++) {
					if(bothArrow[i].id == "followArrow"+response_data.user_id) {
						bothArrow[i].className = "arrowDownFollow";
					}
				}

				var upArrow = document.getElementsByClassName("arrowUpFollow");
				for(i=0;i<upArrow.length;i++) {
					if(upArrow[i].id == "followArrow"+response_data.user_id) {
						upArrow[i].className = "arrowNone";
						//upArrow[i].style.display = "none";
					}
				}
			} catch(e){}
			try {
				var k2 = response_data.user_id+"-"+globalUserId;
				if(followRelation[k2][globalUserId] == "y") {
					followRelation[k2] = new Array();
					followRelation[k2][response_data.user_id] = "n";
				} else {
					followRelation[k2][globalUserId] = null;
				}
			} catch(e){}
		}
	}
}
/**
 * stop following user failure callback function
 */
var stopFollowingUserFailureCallback = function (){
	alert("Error on page");
}
/**
 * stop following user 404 callback function
 */
var stopFollowingUser404Callback= function (){
	alert("Error page is not found");
}

/**
 * Update getting started steps
 */
var gettingStartedStepUpdate = function (str){
	var postParameters = "page="+str;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: gettingStartedStepUpdateCallback,
		// Handle 404
		on404: gettingStartedStepUpdate404Callback,
		// Handle other errors
		onFailure: gettingStartedStepUpdateFailureCallback
	}
	new Ajax.Request('/getting-started-step', ajaxRequestOptions);
}

/**
 * Update getting started steps success callback
 */
var gettingStartedStepUpdateCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');

	if(response_data.action == 'email_alert')
	{
		window.location = '/settings?act=alert';
	}
	else if(response_data.action == 'follow')
	{
		// do nothing
	}
	else if(response_data.action == 'profile')
	{
		window.location = '/settings?act=aboutme';
	}
}
/**
 * Update getting started steps failure callback function
 */
var gettingStartedStepUpdateFailureCallback = function (){
	alert("Error on page");
}
/**
 * Update getting started steps 404 callback function
 */
var gettingStartedStepUpdate404Callback= function (){
	alert("Error page is not found");
}


/**
 * Update alert frequency in getting started step
 */
var setAlertFreqInGettingStarted = function (){
	var postParameters = Form.serialize("alert_setting_in_getting_started_form");
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: setAlertFreqInGettingStartedCallback,
		// Handle 404
		on404: setAlertFreqInGettingStarted404Callback,
		// Handle other errors
		onFailure: setAlertFreqInGettingStartedFailureCallback
	}
	new Ajax.Request('/set-alert-in-getting-started-step', ajaxRequestOptions);
}

/**
 * Update alert frequency in getting started step success callback
 */
var setAlertFreqInGettingStartedCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	if(response_data.ok){
		gettingStartedStepUpdate('email_alert_without_referesh');
		$('gs_email_alert').style.display = 'none';
	}
}
/**
 * Update alert frequency in getting started step failure callback function
 */
var setAlertFreqInGettingStartedFailureCallback = function (){
	alert("Error on page");
}
/**
 * Update alert frequency in getting started step 404 callback function
 */
var setAlertFreqInGettingStarted404Callback= function (){
	alert("Error page is not found");
}



/**
 * Character counter
 */
 function charCount(str,aId) {
	len = str.length;
	obj = $('send_'+aId);
    $('char_count_status_'+aId).innerHTML = '' + (119-len);
	if (len >= 119) {
		if (obj.disabled != true) {
			obj.disabled = true;
		}
	} else {
		if (obj.disabled == true) {
			obj.disabled = false;
		}
	}
}

/**
 * Check if user name is available or not
 */
// if CHECK_AVAILABILITY_SIGNUP = true -> function call is from signup page
var CHECK_AVAILABILITY_SIGNUP = false;
var checkUsernameAvailability = function (new_user_name, original_user_name, isLightBoxSignup){
	CHECK_AVAILABILITY_SIGNUP = (original_user_name == '' ? CHECK_AVAILABILITY_SIGNUP = true : CHECK_AVAILABILITY_SIGNUP);
	try {
		$('user_available_message_div').innerHTML = "";
	} catch(e){}
	var message_str = "";
	if(new_user_name.strip() == '') {
		message_str = 'User Name can not be blank.';
	} else if(new_user_name.match(/[^a-zA-z0-9_\-]/)!=null) {
		message_str = 'Username must be one word or contain  _  or  - ';
	} else if(new_user_name.length < 2 || new_user_name.length > 20) {
		message_str = 'Username must be 2 to 20 characters long.';
	} else if(new_user_name.strip() == original_user_name.strip()) {
		message_str = 'Available'
					+	'<span style="padding:0px 0px 0px 97px;">'
					+	'	<input type="button" value="Save" onclick="Javascript: saveUserName();">'
					+	'</span>';
	}
	if(message_str != "") {
		if(isLightBoxSignup == 1) { // lightbox signup process
			$('lightbox_user_available_message_div').style.color = 'red';
			$('lightbox_user_available_message_div').innerHTML = message_str;
		} else { // normal signup process
			$('user_available_message_div').style.color = 'red';
			$('user_available_message_div').innerHTML = message_str;
		}
		return;
	}
	 // show loading image
	 if(isLightBoxSignup == 1) { // lightbox signup process
	 	$('lightbox_availability_loading').style.display = 'block';
	 } else { // normal signup process
	 	$('availability_loading').style.display = 'block';
	 }
	 var postParameters = "socialmedian_url=" + new_user_name.strip();
	 var ajaxRequestOptions = {
	  // Use POST
	  method: 'post',
	  // Send this lovely data
	  postBody: postParameters,
	  // Handle successful response (this is to pass local variablres to callback function)
	  onSuccess: function(response){checkUsernameAvailabilityCallback(response, isLightBoxSignup);},
	  // Handle 404
	  on404: checkUsernameAvailability404Callback,
	  // Handle other errors
	  onFailure: checkUsernameAvailabilityFailureCallback
	 }
	 new Ajax.Request('/check-user-name', ajaxRequestOptions);
}

// Check if user name is available or not success callback
var checkUsernameAvailabilityCallback = function (response, isLightBoxSignup){
 	//eval the json object
	var response_data = response.responseText.evalJSON();
	if(response_data.ok == true) {
	    if(CHECK_AVAILABILITY_SIGNUP == true) {
	    	if(isLightBoxSignup == 1) { // lightbox signup process
		    	$('lightbox_availability_loading').style.display = 'none';
		    	$('lightbox_user_available_message_div').style.color = 'green';
		    	$('lightbox_user_available_message_div').innerHTML = 'Available';
		    } else { // normal signup process
		    	$('availability_loading').style.display = 'none';
		    	$('user_available_message_div').style.color = 'green';
		    	$('user_available_message_div').innerHTML = 'Available';
		    }
	    } else {
	    	$('availability_loading').style.display = 'none';
	    	$('user_available_message_div').style.color = 'green';
	    	$('user_available_message_div').innerHTML = 'Available'
			 + '<span style="padding:0px 0px 0px 47px;">'
			 + ' <input type="button" value="Save" onclick="Javascript: saveUserName();">'
			 + '</span>';
	    }
	} else {
       if(isLightBoxSignup == 1) { // lightbox signup process
	       $('lightbox_availability_loading').style.display = 'none';
	       $('lightbox_user_available_message_div').style.color = 'red';
	       $('lightbox_user_available_message_div').innerHTML = "Sorry, that username is already taken";
	   } else { // normal signup process
	   		$('availability_loading').style.display = 'none';
	       $('user_available_message_div').style.color = 'red';
	       $('user_available_message_div').innerHTML = (CHECK_AVAILABILITY_SIGNUP == true ? "Sorry, that username is already taken" : "Not available");
	   }
	}
}

/**
 * Check if user name is available or not failure callback function
 */
var checkUsernameAvailabilityFailureCallback = function (){
	alert("Sorry its system problem.");
}
/**
 * Check if user name is available or not 404 callback function
 */
var checkUsernameAvailability404Callback = function (){
	alert("Error page is not found");
}

// complete socialmedin url when user start typing the username for signup
var off = true; // this is used to fix form submit on enter key press (for opera and safari)
function populateUserName(obj, responseDiv, isLightBoxSignup, e) {
	//Hack for ie7 browser.
	if(Prototype.Browser.IE){
		return false;
	}
	$('lightbox_user_available_message_div').innerHTML = '';
	if(obj.value == 'username' || obj.value == '') {
		responseDiv.innerHTML = "username";
	} else {
		responseDiv.innerHTML = obj.value;
	}
	// check if enter key is pressed or not
	if(e.keyCode == 13){
		off = true;
		if(obj.value != '' && obj.value != 'username'){
			checkUsernameAvailability(obj.value, '', isLightBoxSignup);
		}
	}
}

function checkEditedCommentWordCount(count) {
	if(($('user_comment_'+count).value).strip() == ""){
 		alert("Please enter a comment");
 		return false;
 	}
 	return true;
 }

 /**
 *	display the user added sources on the right side panel
 */
 function showUserAddedSources(ncId, feedId, ncfId, name, addedBy, addedOn){
 	var feed_id = ncId+'-feed-'+feedId;
	var deleter_id = ncId+'-feed_deleter-'+feedId;
 	var show_new_feeds = "<div align='left' style='padding:5px 0px 5px 3px;margin:0px;' id=\"" + feed_id +"\">"+
							'<div style="padding:0px;margin:0px;float:left;width:39px">'+
					"<img id='voteForFeedUp_"+feedId+"' src='"+S3_STATIC_ASSETS_PATH + "/images/aupgray.gif' onmouseover='this.src=\""+ S3_STATIC_ASSETS_PATH + "/images/auproll.gif\"' onmouseout='this.src=\""+S3_STATIC_ASSETS_PATH + "/images/aupgray.gif\"' onClick=voteForFeed('"+ncId+"','"+ncfId+"','"+feedId+"','1'); style='cursor:pointer;'> "+
			  		"<img id='voteForFeedDown_"+feedId+"' src='"+S3_STATIC_ASSETS_PATH + "/images/adowngray.gif' onmouseover='this.src=\""+ S3_STATIC_ASSETS_PATH + "/images/adownroll.gif\"' onmouseout='this.src=\"" + S3_STATIC_ASSETS_PATH + "/images/adowngray.gif\"' onClick=voteForFeed('"+ncId+"','"+ncfId+"','"+feedId+"','-1'); style='cursor:pointer;'>"+
			  	'</div>'+
			  	'<div align="left" style="padding:0px 0px 0px 2px;margin:0px;float:left;width:180px;font-size:13px;font-family:arial;overflow:hidden;">'+
					" <div style='color:#2463A8;text-decoration:none;cursor:pointer;' id='news_circle_feed_"+feedId+"' onmouseover='this.style.textDecoration=\"underline\"' onmouseout='this.style.textDecoration=\"none\"'>"+name+
						' <span id="news_circle_feed_loading_'+feedId+'><img src="'+S3_STATIC_ASSETS_PATH + '/images/loader.gif"></span>'+
					"</div>"+
				"</div>"+
				"<span id=\"" +deleter_id+ "\" style=\"cursor:pointer;float:right;margin-right:10px;font-size:10px;\" onclick=\""+(NETWORK_PAGE == 1 ? 'remove_feed(this)' : 'removeSources(this)')+"\"> delete </span>"+
				"<br clear='all'/>"+
				"<div align='left' id='totalVoteForFeed_"+feedId+"' style='color:gray;font-size:10px;margin:0px;padding:4px 0px 0px 38px;display:none'></div>"+
				"<div align='left' style='margin:0px;padding:0px 0px 3px 41px;font-size:11px;'>Added by: <a href='/"+addedBy+"' style='color:gray'>"+addedBy+"</a> on  "+addedOn+"</div>"+
			"</div>";
	return show_new_feeds;
 }


/**
 * Get story video
 */
var getStoryVideo = function(story_id, div_id){
	if (story_id == "") {
		alert("Please provide story id");
		return false;
	}
	if($('storyVideoContainer_'+div_id) != null){
		$('storyZoomedVideo_'+div_id).style.display = 'block';
		$("videoZoomed_"+div_id).innerHTML = '<a href="" class="stop-button" style="text-decoration:none;" onclick="javascript: closeStoryVideo('+story_id+', '+div_id+');return false;"></a>';
		$("videoZoomedPlayText_"+div_id).innerHTML = '<a href="" style="text-decoration:none;" onclick="javascript: closeStoryVideo('+story_id+', '+div_id+');return false;">Stop</a>';
		return false;
	}
	postParameters = "story_id="+story_id;
	// display the loading icon
	$('storyVideoLoadingIcon_'+div_id).style.display= 'block';
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: function (response) {getStoryVideoCallback(response, story_id, div_id);},
		// Handle 404
		on404: getStoryVideo404Callback,
		// Handle other errors
		onFailure: getStoryVideoFailureCallback
	}
	// Data store model
	new Ajax.Request('/story-video', ajaxRequestOptions);
}

/**
 * Get story video success callback function
 */
var getStoryVideoCallback = function (response, story_id, div_id){
	// hide the loading icon
	$('storyVideoLoadingIcon_'+div_id).style.display= 'none';
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track edit story action
	tracAjaxFunctionalities('/story-video');
	//check if there is an error
	if (response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		$('videoZoomed_'+div_id).className = 'stop-button';
		var storyVideoInfo = response_data.story_video;
		$('storyZoomedVideo_'+div_id).innerHTML = '' ;
		var indexOfStickam = storyVideoInfo['url'].indexOf('player.stickam.com');
		var autoplay = "&autoplay=1";
		if(indexOfStickam >= 0){
			autoplay = "";
		}
		var storyVideoInnerHtml = '<div id="storyVideoContainer_'+div_id+'" style="padding:10px 0px 0px 0px;margin:0px;width:350px;">'
										+'<div align="center" style="padding:0px;margin:0px;float:left;'+(autoplay != "" ? 'background:url('+S3_STATIC_ASSETS_PATH+'/images/loader.gif) no-repeat 10% 10%;' : '')+'">'
											+'<object width="300" height="245">'
												+'<param name="movie" value="'+storyVideoInfo['url']+'"></param>'
												+'<param name="allowFullScreen" value="false"></param>'
												+'<param name="wmode" value="transparent"></param>'
												+'<embed src="'+storyVideoInfo['url']+autoplay+'" type="application/x-shockwave-flash" allowfullscreen="false" wmode="transparent" style="width:300px;height:245px"></embed>'
											+'</object>'
										+'</div>'
										+'<div style="padding:230px 0px 0px 5px;margin:0px;float:left;">'
											+'<div style="cursor:pointer;text-decoration:underline;color:#2C6C92;font-family:Arial;font-size:12px;padding:0px;margin:0px;width:32px;" onclick="javascript: closeStoryVideo('+story_id+', '+div_id+');return false;">close</div>'
										+'</div>'
										+'<br clear="all"/>'
								  +'</div>';
		$('storyZoomedVideo_'+div_id).innerHTML = storyVideoInnerHtml;
		$('storyZoomedVideo_'+div_id).style.display = 'block';
		$("videoZoomed_"+div_id).innerHTML = '<a href="" class="stop-button" style="text-decoration:none;" onclick="javascript: closeStoryVideo('+story_id+', '+div_id+');return false;"></a>';
		$("videoZoomedPlayText_"+div_id).innerHTML = '<a href="" style="text-decoration:none;" onclick="javascript: closeStoryVideo('+story_id+', '+div_id+');return false;">Stop</a>';
	}
}

/**
 * Get story video failure callback function
 */
var getStoryVideoFailureCallback = function (){
	// hide the loading icon
	$('storyVideoLoadingIcon_'+div_id).style.display= 'none';
	alert("Error on page");
}
/**
 * Get story video 404 callback function
 */
var getStoryVideo404Callback= function (){
	// hide the loading icon
	$('storyVideoLoadingIcon_'+div_id).style.display= 'none';
	alert("Error page is not found");
}

/**
*	closed the story video div and change the play icon
*/
function closeStoryVideo(story_id, div_id){
	//$('videoZoomed_'+story_id).className = 'play-button';
	$('storyZoomedVideo_'+div_id).style.display = 'none';
	$("videoZoomed_"+div_id).innerHTML = '<a href="" class="play-button" style="text-decoration:none;" onclick="javascript: getStoryVideo('+story_id+', '+div_id+');return false;"></a>';
	$("videoZoomedPlayText_"+div_id).innerHTML = '<a href="" style="text-decoration:none;" onclick="javascript: getStoryVideo('+story_id+', '+div_id+');return false;">Play</a>';
}



  // Switch tab functionality to get hot stories.
  var hotStoryTypes =  new Hash();
  function getHotStories(type) {
      // show tab action
      $('hotStoriesWidgetSubMenu').style.display = "none";
      if(type == "popular-day" || type == "popular-week" || type == "popular-month"){
          var activeTab = $('hotStoriesPopularTab');
          $('hotStoriesWidgetSubMenu').descendants().each(function(ele){
             ele.className = "popularStoriesLink";
          });
          if(type == "popular-day") {
              $('hotStoriesWidgetSubMenu').descendants()[0].className = "popularStoriesLinkSelected";
          } else if(type == "popular-week") {
              $('hotStoriesWidgetSubMenu').descendants()[1].className = "popularStoriesLinkSelected";
          } else if(type == "popular-month") {
              $('hotStoriesWidgetSubMenu').descendants()[2].className = "popularStoriesLinkSelected";
          }
          $('hotStoriesWidgetSubMenu').style.display = "block";
      } else if(type == "rising-fast") {
          var activeTab = $('hotStoriesRisingFastTab');
      } else if(type == "hot-discussions") {
          var activeTab = $('hotStoriesHotDiscussionsTab');
      }

      // activate current tab
      showTabAction([$('hotStoriesPopularTab'), $('hotStoriesRisingFastTab'), $('hotStoriesHotDiscussionsTab')], activeTab);

      if(hotStoryTypes.get(type)) {
          // sow tab body
          showActiveTabBody([$('hotStoriesWidget-popular-day'),$('hotStoriesWidget-popular-week'),$('hotStoriesWidget-popular-month'),$('hotStoriesWidget-rising-fast'),$('hotStoriesWidget-hot-discussions')], $('hotStoriesWidget-'+type));
      } else {
          // send request to server and get the result
          getPopularStories(type);
      }
  }

  function showTabAction(arr, selectedTabEle) {
      arr.each(function(ele){
         ele.style.top = "-22px";
         ele = ele.descendants();
         ele[0].className = "smallTabLeftOff";
         ele[1].className = "smallTabCenterOff";
         ele[2].className = "smallTabContentsOff";
         ele[3].className = "smallTabRightOff";
      });

      selectedTabEle.style.top = "-21px";
      selectedTabEle = selectedTabEle.descendants();
      selectedTabEle[0].className = "smallTabLeftOn";
      selectedTabEle[1].className = "smallTabCenterOn";
      selectedTabEle[2].className = "smallTabContentsOn";
      selectedTabEle[3].className = "smallTabRightOn";
  }

  function showActiveTabBody(arr, activeTabBodyEle) {
      arr.each(function(ele){
         ele.style.display = "none" ;
      });
      activeTabBodyEle.style.display = "block";
  }

  /*
  * function to get Hot stories. (Popular stories from socialmedian)
  */
  var getPopularStories = function (type){
      // show loading image
      $('hotStoriesWidgetLoader').style.display = "block";
      var postParameters = "stories_of="+type;
      var ajaxRequestOptions = {
          // Use POST
          method: 'post',
          // Send this lovely data
          postBody: postParameters,
          // Handle successful response
          onSuccess: function(response){getPopularStoriesCallback(response, type)},
          // Handle 404
          on404: getPopularStoriesCallback,
          // Handle other errors
          onFailure: getPopularStoriesFailureCallback
      }
      new Ajax.Request('/get-hot-stories', ajaxRequestOptions);
  }
  /**
   * function to get Hot stories callback function
   */
  var getPopularStoriesCallback = function (response, type){
      //eval the json object
      response_data = eval('(' + response.responseText + ')');
      // hide loading image
      $('hotStoriesWidgetLoader').style.display = "none";
      if(response_data.error == 0) {
          // set it in hash for further use
          hotStoryTypes.set(type, 1);
          var result = populatePopularStories(response_data);
          $('hotStoriesWidget-'+type).innerHTML = result;
          // show tab body contents
          showActiveTabBody([$('hotStoriesWidget-popular-day'),$('hotStoriesWidget-popular-week'),$('hotStoriesWidget-popular-month'),$('hotStoriesWidget-rising-fast'),$('hotStoriesWidget-hot-discussions')], $('hotStoriesWidget-'+type));
      }
  }
  /**
   * function to get Hot stories failure callback function
   */
  var getPopularStoriesFailureCallback = function (){
      alert("Error on page");
      // hide loading image
      $('hotStoriesWidgetLoader').style.display = "none";
  }
  /**
   * function to get Hot stories 404 callback function
   */
  var getPopularStories404Callback= function (){
      alert("Error page is not found");
      // hide loading image
      $('hotStoriesWidgetLoader').style.display = "none";
  }

  function populatePopularStories(response_data) {
      var htmlHolder = "";
      if(response_data.stories.length > 0) {
          var limit = (response_data.stories.length<5 ? response_data.stories.length : 5)
          for(i=0;i<limit;i++) {
              var story = response_data.stories[i]
              if(story.story_type != 'story') {
			  if(tweet_story_info[story.id] == undefined) {
				  if(story.story_image_extension =='' || story.story_image_extension==null){
					 	var story_image = '';
					} else {
						var story_image=S3_DYNAMIC_ASSETS_PATH+'/story-images/'+story.id+'-73x73.' + story.story_image_extension;
					}
			  	  	tweet_story_info[story.id] = [story.story_type, escape((story.story_title == null) ? '' : story.story_title.stripTags().gsub(/'|"/, "&#34;")), escape((story.description == null) ? '' : story.description.stripTags().gsub(/'|"/, "&#34;").truncate(200)),story.story_permalink,story_image];
			  }
			  } else {
			  	  if(tweet_story_info[story.id] == undefined) {
			  	  	var feed_info = response_data.story_feed_info[story.feed_id];
					if(story.story_image_extension ==''||story.story_image_extension==null)
					 {
					 	var story_image = '';
					 }
					else{
					var story_image=S3_DYNAMIC_ASSETS_PATH+'/story-images/'+story.id+'-73x73.' + story.story_image_extension;
					}
			  	  	tweet_story_info[story.id] = [story.story_type, escape(story.story_title.stripTags().gsub(/'|"/, "&#34;")), escape(story.description.stripTags().gsub(/'|"/, "&#34;").truncate(200)), escape(feed_info.title.stripTags().gsub(/'|"/, "&#34;")),story.story_permalink,story_image];
			  	  }
			  }
              var clip_count = response_data.clip_comment_counts[story.id]["total_clip"];
              var comment_count = response_data.clip_comment_counts[story.id]["total_comment"];
              if(response_data.story_clip_info[story.id] != undefined) {
                  eval('user_clipped_story'+story.id+' = 1');
              } else {
                  eval('user_clipped_story'+story.id+' = 0');
              }
              htmlHolder += '<div align="left" style="margin:0px;padding:5px 0px 0px 10px;">'+
                  '<div align="left" style="margin:0px;padding:0px;width:45px;float:left;">';
                      if(globalUserId != 0) {
                          if(response_data.story_clip_info[story.id] != undefined) {
                              htmlHolder += '<div id="clipUnclipStorySmallIcon'+story.id+'" class="clippedStoryPinSmall" title="Remove this Clip" onClick="javascript: showCommentBox('+story.id+','+eval('user_clipped_story'+story.id)+','+story.id+',1); return false;">';
                          } else {
                              htmlHolder += '<div id="clipUnclipStorySmallIcon'+story.id+'" class="unclippedStoryPinSmall" title="Add to my Clips" onClick="javascript: showCommentBox('+story.id+','+eval('user_clipped_story'+story.id)+','+story.id+',1); return false;">';
                          }
                              htmlHolder += '<div align="center" class="clipCountHolderSmallIcon">'+clip_count+'</div>'+
                              '<div align="center" class="clipTextSmallIcon">'+((clip_count == 0 || clip_count > 1) ? "Clips" : "Clip")+'</div>'+
                          '</div>'+
                          '<div style="margin:0px;padding:0px;float:left;text-align:center;width:30px;height:10px;"><span id="popularStoriesLoading'+story.id+'" style="display:none;"><img src="'+S3_STATIC_ASSETS_PATH + '/images/loader.gif"/></span></div><br clear="all"/>';
                      } else {
                          htmlHolder += '<div id="clipUnclipStorySmallIcon'+story.id+'" class="unclippedStoryPinSmall">'+
                              '<div align="center" class="clipCountHolderSmallIcon">'+clip_count+'</div>'+
                              '<div align="center" class="clipTextSmallIcon">'+((clip_count == 0 || clip_count > 1) ? "Clips" : "Clip")+'</div>'+
                          '</div>';
                      }
                  var date_str = story.added_on.split(" ");
                  htmlHolder += '</div>'+
                  '<div align="left" style="margin:0px;padding:6px 0px 0px 0px;width:215px;float:left;">'+
                      '<div style="padding:0px;margin:0px;font-family:Arial;font-weight:bold;font-size:12px;color:#295EAE">'+
                          '<a href="/story/'+story.id+'/'+story.story_permalink+'" style="color:#2262A9;text-decoration:none;">'+(story.story_type == "snip" ? story.description.truncate(50) : story.title)+'</a>'+
                      '</div>'+
                      '<div style="padding:2px 0px 0px 0px;margin:0px;font-family:Arial;font-weight:normal;font-size:11px;color:#7E7C6F">';
                          if(comment_count > 1) {
                              htmlHolder += '<a class="commentStoryInactiveWithBack" href="/story/'+story.id+'/'+story.story_permalink+'">'+comment_count+' Comments</a>';
                          } else if(comment_count == 1) {
                              htmlHolder += '<a class="commentStoryInactiveWithBack" href="/story/'+story.id+'/'+story.story_permalink+'">'+comment_count+' Comment</a>';
                          } else {
                              htmlHolder += '<a class="commentStoryInactiveWithBack" href="/story/'+story.id+'/'+story.story_permalink+'">Add Comment</a>';
                          }
                          htmlHolder += '<span style="color:#747474;font-size:11px;float:right;">'+story.story_added_on+'</span>'+
                      '</div>'+
                  '</div>'+
                  '<br clear="all"/>'+
              '</div>';
          }
          if(response_data.stories.length > 5) {
              htmlHolder += '<div style="margin:0px;padding:10px 0px 5px 10px;font-size:11px;">'+
                                '<a href="/stories-list/'+response_data.stories_of+'" style="color:#767676;">Show more</a>'+
                            '</div>';
          }
      } else {
          htmlHolder = '<div style="margin:0px;padding:5px 0px 5px 0px;width:100%;text-align:center;font-size:13px;font-family:arial;">Stories not found!</div>';
      }
      return htmlHolder;
  }


 /**
 * Author - Alpesh
 * Date - 10 sept, 2008
 * getting commentsinfo for story for new design
 */
 var getStoryCommentsInfo = function (uniq_id, story_id, current_user_id, current_user_name){
	if($('comment_link_'+uniq_id+'_div').className != "commentStoryBackgroundActive"){
		$('comment_link_'+uniq_id+'_div').className = "commentStoryBackgroundActive";
		$('share_link_'+uniq_id+'_div').className = "shareStoryBackgroundInactive";
		$('news_flash_link_'+uniq_id+'_div').className = "newsFlashStoryBackgroundInactive";
		$('commentShareBoxHolder'+uniq_id).style.display = 'block';
		$('newsFlashBoxHolder'+uniq_id).style.display = "none";
		$('newsFlashBroadcastBox'+uniq_id).style.display = "none";
	}else{
		$('comment_link_'+uniq_id+'_div').className = "commentStoryBackgroundInactive";
		$('commentShareBoxHolder'+uniq_id).style.display = 'none';
		return false;
	}

	// show loading image
	$('commentShareBoxHolder'+uniq_id).innerHTML = '<div style="padding:4px 0px 0px 0px;margin:0px;width:150px;">'+
													'<div style="float:left;padding:0px;margin:0px;"><img src="'+ S3_STATIC_ASSETS_PATH + '/images/loader.gif"></div>'+
													'<div style="float:left;padding:0px 0px 0px 5px;margin:0px;font-size:13px;">Loading...</div>'+
													'<br clear="all">'+
												'</div>';
	$('commentShareBoxHolder'+uniq_id).style.display = "block";

 	var postParameters = "story_id="+story_id;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: function(response){ getStoryCommentsInfoCallback(response, uniq_id, story_id, current_user_id, current_user_name); },
		// Handle 404
		on404: getStoryCommentsInfo404Callback,
		// Handle other errors
		onFailure: getStoryCommentsInfoFailureCallback
	}
	new Ajax.Request('/get-story-comments-info', ajaxRequestOptions);
}

/**
 * getStoryCommentsInfo success callback
 */
var getStoryCommentsInfoCallback = function (response, uniq_id, story_id, current_user_id, current_user_name){
	//eval the json object
 	response_data = eval('(' + response.responseText + ')');
	displayStoryCommentsInfo(response_data, uniq_id, story_id, current_user_id, current_user_name);
}
/**
 * getStoryCommentsInfo failure callback function
 */
var getStoryCommentsInfoFailureCallback = function (){
	alert("Error on page");
}
/**
 * getStoryCommentsInfo 404 callback function
 */
var getStoryCommentsInfo404Callback= function (){
	alert("Error page is not found");
}

var displayStoryCommentsInfo = function (response_data, uniq_id, story_id, current_user_id, current_user_name){
	var first_comment = response_data.open_three_comments.shift();
	var total_comments = response_data.open_three_comments.length + response_data.show_more_comments;
	var extraContent = "";
	var fbUsers = [];
	var uniqIds = [];
	commentShareBoxHTML = '<div style="margin:0px;padding:0px;float:left;width:610px;">'
						+ '	<div id="innerShareCommentBoxHolder'+uniq_id+'" style="margin:0px;padding:0px;">';
	if(first_comment){
		commentShareBoxHTML += createCommentInfoDiv(first_comment, current_user_id, current_user_name, uniq_id, response_data.replied_or_included_comments_for_user);
		if(first_comment.fb_connect_status == "connected" || first_comment.fb_connect_status == "merged"){
			fbUsers.push(first_comment.fb_user_id);
			uniqIds.push("commentList"+first_comment.id);
		}
	}
	if(response_data.show_more_comments > 0){
		commentShareBoxHTML = commentShareBoxHTML
						+ ' 	<div id="showMoreCommentsLink'+uniq_id+'" style="margin:0px;padding:9px 0px 0px 15px;font-size:12px;">'
						+ ' 		<div class="more-comments-browse-icon" style="float:left;margin:0px;padding:0px;cursor:pointer;" onclick="Javascript: getStoryAllCommentsInfo(\''+uniq_id+'\', '+story_id+', '+current_user_id+', \''+current_user_name+'\');">'
						+ '			</div>'
						+ '			<div style="float:left;margin:0px;padding:0px 0px 0px 2px;">'
						+ ' 			<i><a href="Javascript: void(0)" style="text-decoration:none;color:#2464AB;" onclick="Javascript: getStoryAllCommentsInfo(\''+uniq_id+'\', '+story_id+', '+current_user_id+', \''+current_user_name+'\');">'+ response_data.show_more_comments +' more '+ (response_data.show_more_comments == 1 ? 'comment' : 'comments' ) +'</a></i>'
						+ '			</div>'
						+ '			<br clear="all">'
						+ '		</div>'
						+ ' 	<div id="showAllComments'+uniq_id+'" style="margin:0px;padding:0px;display:none;">'
						+ '		</div>';
	}
	if(response_data.open_three_comments.length > 0){
		for(i = 0; i < response_data.open_three_comments.length; i++){
			commentShareBoxHTML += createCommentInfoDiv(response_data.open_three_comments[i], current_user_id, current_user_name, uniq_id, response_data.replied_or_included_comments_for_user);
			if(response_data.open_three_comments[i].fb_connect_status == "connected" || response_data.open_three_comments[i].fb_connect_status == "merged"){
				fbUsers.push(response_data.open_three_comments[i].fb_user_id);
				uniqIds.push("commentList"+response_data.open_three_comments[i].id);
			}
		}
	}
	var userImg = (currentFbUserId > 0 ? '<img id="addComment'+uniq_id+'-'+currentFbUserId+'"/>' : '<img src="'+S3_DYNAMIC_ASSETS_PATH +'/user-images/'+ current_user_id +'-small.jpg" >');
	if(currentFbUserId > 0){
		fbUsers.push(currentFbUserId);
		uniqIds.push("addComment"+uniq_id);
	}
	commentShareBoxHTML = commentShareBoxHTML
						+ '	</div>'
						+ '	<div style="margin:0px;padding:10px 0px 0px 15px;">'
						+ '		<form id="clipCommentForm'+uniq_id+'" onsubmit="javascript: addClipComment('+story_id+',\''+uniq_id+'\'); if ($(\'twitter_user_id\').value != \'\') {$(\'change_twitter_user_info_message_'+uniq_id+'\').style.display=\'block\';}$(\'change_twitter_user_info_'+uniq_id+'\').style.display=\'none\';$(\'include_tweet_replize_'+uniq_id+'\').checked=false; return false;" style="margin:0px;padding:0px;">'
						+ ' 		<input type="hidden" id="display_comment_count_'+uniq_id+'" value="'+ total_comments +'">'
						+ '			<div style="margin:0px;padding:0px;float:left;">'+userImg+'</div>'
						+ '			<div id="addCommentLink'+uniq_id+'" style="margin:0px;padding:0px 0px 0px 5px;float:left;font-size:12px;">';
						if(globalUserId != 0){
							extraContent = '<a style="color:#2464AB;cursor:pointer;" onclick="javascript: $(\'addCommentBox'+uniq_id+'\').style.display = \'block\'; $(\'addCommentLink'+uniq_id+'\').style.display = \'none\';getMyContacts();">Add your comment</a>';
						}else{
							extraContent = '<a style="color:#2464AB;cursor:pointer;" onclick="javascript: return false;" class="userLinkInactive">Add your comment</a>';
						}
						commentShareBoxHTML += extraContent;
	commentShareBoxHTML +='			</div>'
						+ ' 		<div id="addCommentBox'+uniq_id+'" style="display:none;">'
						+ ' 			<div style="margin:0px;padding:2px 0px 0px 5px;float:left;font-size:11px;">'
						+ '					<a href="http://'+APP_DOMAIN+'/'+current_user_name+'/home" style="color:#2464AB;cursor:pointer;text-decoration:underline;">You</a>'
						+ '				</div>'
						+ '				<div style="margin:0px;padding:0px 0px 0px 5px;float:left;font-size:12px;color:#2164AA;">'
						+ '					<textarea id="user_comment'+uniq_id+'" name="user_comment" autocomplete="off" value="" style="width:370px;height:45px;border:1px solid #C1C1C1;" onkeyup="auto_complete_my_contacts(event, '+uniq_id+');"></textarea>'
						+ '					<div id="sm_contacts_auto_complete'+uniq_id+'" class="replize_autocompleter" style="display: none;"></div>'
						+ '				</div>'
						+ '				<div style="margin:0px;padding:0px 0px 0px 7px;float:left;">'
						+ '					<div id="addCommentAcitvityIcon'+uniq_id+'" align="center" style="padding:0px;margin:0px;visibility:hidden;">'
						+ '						<img src="'+S3_DYNAMIC_ASSETS_PATH+'/images/loader.gif" />'
						+ '					</div>'
						+ '					<div style="padding:7px 0px 0px 0px;margin:0px;"><input type="submit" name="submit" value="Add" /></div>'
						+ '				</div>'
						+ ' 			<br clear="all"/>'
						+ '				<div style="margin:0px;padding:3px 0px 0px 50px;float:left;font-size:10px;">'
						+ '					<span style="color:#d97430">New!</span>&nbsp;&nbsp;Auto-complete to include your socialmedian contacts in a comment. Just type \"@\" and the first letter of the user\'s name. (e.g. @jasongoldberg @louisgray)'
						+ '				</div>'
						+ '				<div id="tweetReplizeCheckBox'+uniq_id+'" style="margin:0px;padding:3px 0px 0px 0px;float:left;">'
						+ '					<div style="margin:0px;padding:0px 0px 0px 50px;float:left;font-size:11px;">'
						+ '						<div style="padding:2px 0px 0px 0px;margin:0px;float:left;width:17px;">'
						+ '							<img src=\''+S3_STATIC_ASSETS_PATH+'/images/twitter_icon.gif\'/>'
						+ ' 					</div>'
						+ '						<div style="padding:0px;margin:0px;float:left;width:17px;"><input type="checkbox" unchecked name="send_replize_tweet" id="include_tweet_replize_'+uniq_id+'" value="yes" onclick="Javascript: if(!$(\'twitter_user_id\').value && this.checked) {$(\'change_twitter_user_info_'+uniq_id+'\').style.display=\'block\';} "></div>'
						+ '						<div style="padding:2px 0px 0px 2px;margin:0px;float:left;">'
						+ '							<div style="float:left;padding:0px 0px 0px 5px;margin:0px;">Also tweet this comment/reply on twitter.</div>'
						try {
							if($('twitter_user_id').value != "") {
								commentShareBoxHTML += '<div style="float:left;padding:0px;margin:0px;" id="change_twitter_user_info_message_'+uniq_id+'">Tweet will be sent using <font style=\'color:#d97430;\'>'+$('twitter_user_id').value+'</font>&nbsp;&nbsp;<a style="cursor:pointer;text-decoration:none;color:#2067a7;" href="javascript:void(0);" onclick="Javascript: $(\'change_twitter_user_info_message_'+uniq_id+'\').style.display=\'none\';$(\'change_twitter_user_info_'+uniq_id+'\').style.display=\'block\';$(\'include_tweet_replize_'+uniq_id+'\').checked=true;">(change)</a></div>';
							}
						} catch(e){}
						commentShareBoxHTML += '<div style="float:left;padding:0px 0px 0px 5px;margin:0px;cursor:pointer" onclick="javascript:Effect.toggle(\'twitterCommentHelp'+uniq_id+'\', \'appear\')"><span class="questionmark-icon" ></span></div>'
						+ '				            <div align="left" style="padding:0px;margin:0px;position:relative;width:1px;height:1px;float:left">'
						+ '				               <div id="twitterCommentHelp'+uniq_id+'" class="twitterCommentHelpBox" style="border:1px solid #959595;display:none;padding:0px;margin:0px;position:absolute;top:20px;left:-130px;width:200px;background-color:#FFF">'
						+ '                               <div style="padding:3px 5px 3px 5px;margin:0px;font-size:11px;">Tweets will be sent to @twittername to all users who have linked their Twitter account.</div>'
						+ '                            </div>'
						+ '			                </div>'
						+ '							<br clear="all">'
						+ '						</div>'
						+ '					</div>'
						+ '				</div>'
						+ '			</div>'
						+ '			<br clear="all">'
						+ '		</form>'
						+ '		<div id="change_twitter_user_info_'+uniq_id+'" style="margin:0px;padding:5px 0px 0px 70px;font-size:11px;width:280px;display:none">'
						+ '			<div style="padding:7px 0px 0px 20px;font-size:11px;font-family:arial;font-weight:normal;float:left;width:70px;">Twitter ID</div>'
						+ '			<div style="padding:2px;font-size:11px;font-family:arial;font-weight:normal;float:left;"><input type="text" style="border:1px solid #767676;" name="twit_id" id="twit_id'+uniq_id+'" value=""></div><br clear="all">'
						+ '			<div style="padding:7px 0px 0px 20px;font-size:11px;font-family:arial;font-weight:normal;float:left;width:70px;">Password</div>'
						+ '			<div style="padding:2px;font-size:11px;font-family:arial;font-weight:normal;float:left;"><input type="password" style="border:1px solid #767676;" name="twit_pass" id="twit_pass'+uniq_id+'" value=""></div><br clear="all">'
						+ '			<div style="padding:5px 0px 0px 20px;font-size:11px;font-family:arial;font-weight:normal;float:left;"><input type="checkbox" checked name="save_or_not" id="save_or_not<%= uniq_id%>" value="yes"></div>'
						+ '			<div style="padding:7px;font-size:11px;font-family:arial;font-weight:normal;float:left;">Save my twitter password</div>'
						+ '			<div style="margin:0px;padding:7px;width:5px;float:right;font-size:12px;font-family:arial;color:#777777;">'
						+ '				<span class="closeEditTwitterInfoBox" onclick="Javascript: if ($(\'twitter_user_id\').value != \'\') {$(\'change_twitter_user_info_message_'+uniq_id+'\').style.display=\'block\';}$(\'change_twitter_user_info_'+uniq_id+'\').style.display=\'none\';$(\'include_tweet_replize_'+uniq_id+'\').checked=false;" style="cursor:pointer; font-size:11px;color:#2067a7;">(cancel)</span>'
						+ '			</div>'
						+ '		</div>'
						+ '	</div>'
						+ '</div>'
						+ '<br clear="all">';
	$('commentShareBoxHolder'+uniq_id).style.display = 'block';
	$('commentShareBoxHolder'+uniq_id).innerHTML = commentShareBoxHTML;
	if(fbUsers.length > 0){
		setUserImage(fbUsers, "square", uniqIds);
	}
}

 /**
 * Author - Alpesh
 * Date - 16 sept, 2008
 * getting all comments info for story for new design
 */
 var getStoryAllCommentsInfo = function (uniq_id, story_id, current_user_id, current_user_name){
	// show loading image
	$('showAllComments'+uniq_id).innerHTML = '<div style="padding:4px 0px 0px 30px;margin:0px;">'+
												'<div style="float:left;padding:0px;margin:0px;"><img src="'+ S3_STATIC_ASSETS_PATH + '/images/loader.gif"></div>'+
												'<div style="float:left;padding:0px 0px 0px 5px;margin:0px;font-size:11px;">Loading...</div>'+
												'<br clear="all">'+
											 '</div>';
	$('showAllComments'+uniq_id).style.display = "block";
 	// If get more comments link hash contains data for that story's more comments, then call directly callback function with that data as response.
 	if(MORE_COMMENTS_FOR_3_OPEN.get(uniq_id)){
 		getStoryAllCommentsInfoCallback(MORE_COMMENTS_FOR_3_OPEN.get(uniq_id), uniq_id, story_id, current_user_id, current_user_name);
 	}else{
	 	var postParameters = "story_id="+story_id;
		var ajaxRequestOptions = {
			// Use POST
			method: 'post',
			// Send this lovely data
			postBody: postParameters,
			// Handle successful response
			onSuccess: function(response){ getStoryAllCommentsInfoCallback(response, uniq_id, story_id, current_user_id, current_user_name); },
			// Handle 404
			on404: getStoryAllCommentsInfo404Callback,
			// Handle other errors
			onFailure: getStoryAllCommentsInfoFailureCallback
		}
		new Ajax.Request('/get-story-all-comments-info', ajaxRequestOptions);
	}
}

/**
 * getStoryAllCommentsInfo success callback
 */
var getStoryAllCommentsInfoCallback = function (response, uniq_id, story_id, current_user_id, current_user_name){
	//If response data is not stored in hash then store it.
	if(!MORE_COMMENTS_FOR_3_OPEN.get(uniq_id)) MORE_COMMENTS_FOR_3_OPEN.set(uniq_id, response);
	var commentAllInfoHTML = '';
	//eval the json object
 	response_data = eval('(' + response.responseText + ')');
	commentAllInfoHTML += '<div id="showLessCommentsLink'+uniq_id+'" style="margin:0px;padding:9px 0px 0px 15px;font-size:12px;">'
						+ '		<div class="more-comments-shrink-icon" style="float:left;margin:0px;padding:0px;cursor:pointer;" onclick="Javascript: $(\'showAllComments'+uniq_id+'\').style.display = \'none\'; $(\'showMoreCommentsLink'+uniq_id+'\').style.display = \'block\';">'
						+ '		</div>'
						+ '		<div style="float:left;margin:0px;padding:0px 0px 0px 2px;">'
						+ ' 		<i><a href="Javascript: void(0)" style="text-decoration:none;color:#2464AB;" onclick="Javascript: $(\'showAllComments'+uniq_id+'\').style.display = \'none\'; $(\'showMoreCommentsLink'+uniq_id+'\').style.display = \'block\';">Show less</a></i>'
						+ '		</div>'
						+ '		<br clear="all">'
						+ '</div>';
	var fbUsers = [];
	var uniqIds = [];
	for(i = 0; i < response_data.story_all_comments_info.length; i++){
			commentAllInfoHTML += createCommentInfoDiv(response_data.story_all_comments_info[i], current_user_id, current_user_name, uniq_id, response_data.replied_or_included_comments_for_user);
			if(response_data.story_all_comments_info[i].fb_connect_status == "connected" || response_data.story_all_comments_info[i].fb_connect_status == "merged"){
				fbUsers.push(response_data.story_all_comments_info[i].fb_user_id);
				uniqIds.push("commentList"+response_data.story_all_comments_info[i].id);
			}
	}
	$('showAllComments'+uniq_id).innerHTML = commentAllInfoHTML;
	$('showMoreCommentsLink'+uniq_id).style.display = 'none';
	$('showAllComments'+uniq_id).style.display = 'block';
	if(fbUsers.length > 0){
		setUserImage(fbUsers, "square", uniqIds);
	}
}
/**
 * getStoryAllCommentsInfo failure callback function
 */
var getStoryAllCommentsInfoFailureCallback = function (){
	alert("Error on page");
}
/**
 * getStoryAllCommentsInfo 404 callback function
 */
var getStoryAllCommentsInfo404Callback= function (){
	alert("Error page is not found");
}

var createCommentInfoDiv = function (comment_info, current_user_id, current_user_name, uniq_id, replied_or_included_comments_for_user){
		comment_info.comment_text = comment_info.comment_text.gsub(/(?:\r\n|\n)/, "<br/>");
		if(comment_info.fb_connect_status == "connected" || comment_info.fb_connect_status == "merged"){
			var userImg = '<img id="commentList'+comment_info.id+'-'+comment_info.fb_user_id+'"/>';
		}else{
			var userImg = '<img src="'+ S3_DYNAMIC_ASSETS_PATH +'/user-images/'+comment_info.commented_by+'-small.jpg">';
		}
		var comment_user_info_box_unique_id = 'user_'+comment_info.commented_by+'_'+uniq_id+'_'+comment_info.id+'_detail';
		commentInfoDiv =  '		<div style="margin:0px;padding:5px 0px 0px 10px; width: 580px;">'
						+ '			<div style="padding:5px;margin:0px;width: 570px;'+( replied_or_included_comments_for_user.indexOf(comment_info.id) >= 0 ? 'background:#eaffd2' : '' )+'">'
						+ '		 		<div style="margin:0px;padding:0px;float:left;">'+userImg+'</div>'
						+ ' 			<div style="margin:0px;padding:2px 0px 2px 5px;float:left;font-size:11px;width:500px;">'
						+ '					<div style="margin:0px;padding:0px;float:left;">'
						+ ' 					<div style="margin:0px;padding:0px;">'
						+ ' 						<a href="http://'+APP_DOMAIN+'/'+ comment_info.socialmedian_url + ((comment_info.socialmedian_url == current_user_name) ? '/home' : '')+'" style="color:#2464AB;cursor:pointer;text-decoration:underline;" '+( current_user_id!=0 ? 'onmouseover="Javascript: createUserShortInfoTemplate('+comment_info.commented_by+',\''+comment_user_info_box_unique_id+'\', \''+current_user_name+'\', 1);" onmouseout="Javascript: $(\''+comment_user_info_box_unique_id+'\').style.display = \'none\'" ' : '') + '>'+((comment_info.socialmedian_url == current_user_name) ? 'You' : comment_info.socialmedian_url.capitalize())+ '</a>,'
						+ ' 					</div>';
						if (Prototype.Browser.IE){
							commentInfoDiv += '<div id="'+comment_user_info_box_unique_id+'" class="userDetailsContainer" onmouseenter="Javascript: $(\''+comment_user_info_box_unique_id+'\').style.display = \'block\'" onmouseleave="Javascript: $(\''+comment_user_info_box_unique_id+'\').style.display = \'none\'"></div>';
						}else{
							commentInfoDiv += '<div id="'+comment_user_info_box_unique_id+'" class="userDetailsContainer" onmouseover="Javascript: $(\''+comment_user_info_box_unique_id+'\').style.display = \'block\'" onmouseout="Javascript: $(\''+comment_user_info_box_unique_id+'\').style.display = \'none\'"></div>';
						}
						commentInfoDiv += '</div>'
					    + ' 				<span style="color:#898989;">'
						+ 						comment_info.commented_duration
						+ '					</span>'
						+ '					: '+ comment_info.comment_text
						+ ' 			</div>'
						+ '				<div style="width:30px;padding:2px 0px 0px 0px;margin:0px;float:right;font-size:11px;">'
						+ '					<span style="cursor:pointer;font-size:10px;font-family:arial;color:#2067a7;" '+ (current_user_id != 0 ? 'onclick="replyToUser(\''+comment_info.socialmedian_url+'\', \''+uniq_id+'\'); if (MY_SM_CONTACTS.length == 0 && NO_SM_CONTACTS == 0){getMyContacts();}"' : 'class="userLinkInactive"' ) +'>'
						+ '						Reply'
						+ '					</span>'
						+ '				</div>'
						+ '				<br clear="all" />'
						+ '			</div>'
						+ '		</div>';
			return commentInfoDiv;
}

var displayNoCommentsBox = function (uniq_id, story_id, current_user_id, current_user_name){
	if($('comment_link_'+uniq_id+'_div').className != "commentStoryBackgroundActive"){
		$('comment_link_'+uniq_id+'_div').className = "commentStoryBackgroundActive";
		$('share_link_'+uniq_id+'_div').className = "shareStoryBackgroundInactive";
		$('news_flash_link_'+uniq_id+'_div').className = "newsFlashStoryBackgroundInactive";
		$('commentShareBoxHolder'+uniq_id).style.display = 'block';
		$('newsFlashBoxHolder'+uniq_id).style.display = "none";
		$('newsFlashBroadcastBox'+uniq_id).style.display = "none";
	}else{
		$('comment_link_'+uniq_id+'_div').className = "commentStoryBackgroundInactive";
		$('commentShareBoxHolder'+uniq_id).style.display = 'none';
		return false;
	}
	var userImg = (currentFbUserId > 0 ? '<img id="addComment'+uniq_id+'-'+currentFbUserId+'"/>' : '<img src="'+S3_DYNAMIC_ASSETS_PATH +'/user-images/'+ current_user_id +'-small.jpg" >');
	var commentShareBoxHTML = '';
	commentShareBoxHTML = '<div style="margin:0px;padding:0px;float:left;">'
						+ '		<div id="innerShareCommentBoxHolder'+uniq_id+'" style="margin:0px;padding:0px;">'
						+ '		</div>'
						+ '		<div id="addCommentBox'+uniq_id+'" style="margin:0px;padding:10px 0px 0px 15px;">'
						+ '			<form id="clipCommentForm'+uniq_id+'" onsubmit="javascript: addClipComment('+story_id+',\''+uniq_id+'\'); if ($(\'twitter_user_id\').value != \'\') {$(\'change_twitter_user_info_message_'+uniq_id+'\').style.display=\'block\';}$(\'change_twitter_user_info_'+uniq_id+'\').style.display=\'none\';$(\'include_tweet_replize_'+uniq_id+'\').checked=false; return false;" style="margin:0px;padding:0px;">'
						+ '				<div style="margin:0px;padding:0px;float:left;">'+userImg+'</div>'
						+ '				<div style="margin:0px;padding:2px 0px 0px 5px;float:left;font-size:11px;">'
						+ '					<a href="http://'+APP_DOMAIN+'/'+current_user_name+'/home" style="color:#2464AB;cursor:pointer;text-decoration:underline;">You</a>'
						+ '				</div>'
						+ '				<div style="margin:0px;padding:0px 0px 0px 5px;float:left;font-size:12px;color:#2164AA;">'
						+ '					<textarea id="user_comment'+uniq_id+'" name="user_comment" autocomplete="off" value="" style="width:370px;height:45px;border:1px solid #C1C1C1;" onkeyup="auto_complete_my_contacts(event, \''+uniq_id+'\');"></textarea>'
						+ '					<div id="sm_contacts_auto_complete'+uniq_id+'" class="replize_autocompleter" style="display: none;"></div>'
						+ '				</div>'
						+ '				<div style="margin:0px;padding:0px 0px 0px 7px;float:left;">'
						+ '					<div id="addCommentAcitvityIcon'+uniq_id+'" align="center" style="padding:0px;margin:0px;visibility:hidden;">'
						+ '						<img src="'+S3_DYNAMIC_ASSETS_PATH+'/images/loader.gif" />'
						+ '					</div>'
						+ '					<div style="padding: 7px 0px 0px 0px;margin:0px;"><input type="submit" name="submit" value="Add" /></div>'
						+ '				</div>'
						+ ' 			<br clear="all"/>'
						+ '				<div style="margin:0px;padding:3px 0px 0px 50px;float:left;font-size:10px;">'
						+ '					<span style="color:#d97430">New!</span>&nbsp;&nbsp;Auto-complete to include your socialmedian contacts in a comment. Just type \"@\" and the first letter of the user\'s name. (e.g. @jasongoldberg @louisgray)'
						+ '				</div>'
						+ '				<div id="tweetReplizeCheckBox'+uniq_id+'" style="margin:0px;padding:3px 0px 0px 0px;float:left;">'
						+ '					<div style="margin:0px;padding:0px 0px 0px 50px;float:left;font-size:11px;">'
						+ '						<div style="padding:2px 0px 0px 0px;margin:0px;float:left;width:17px;">'
						+ '							<img src=\''+S3_STATIC_ASSETS_PATH+'/images/twitter_icon.gif\'/>'
						+ ' 					</div>'
						+ '						<div style="padding:0px;margin:0px;float:left;width:17px;"><input type="checkbox" unchecked name="send_replize_tweet" id="include_tweet_replize_'+uniq_id+'" value="yes" onclick="Javascript: if(!$(\'twitter_user_id\').value && this.checked) {$(\'change_twitter_user_info_'+uniq_id+'\').style.display=\'block\';} "></div>'
						+ '						<div style="padding:2px 0px 0px 2px;margin:0px;float:left;">'
						+ '							<div style="float:left;padding:0px 0px 0px 5px;margin:0px;">Also tweet this comment/reply on twitter.</div>'
						try {
							if($('twitter_user_id').value != "") {
								commentShareBoxHTML += '<div style="float:left;padding:0px;margin:0px;" id="change_twitter_user_info_message_'+uniq_id+'">Tweet will be sent using <font style=\'color:#d97430;\'>'+$('twitter_user_id').value+'</font>&nbsp;&nbsp;<a style="cursor:pointer;text-decoration:none;color:#2067a7;" href="javascript:void(0);" onclick="Javascript: $(\'change_twitter_user_info_message_'+uniq_id+'\').style.display=\'none\';$(\'change_twitter_user_info_'+uniq_id+'\').style.display=\'block\';$(\'include_tweet_replize_'+uniq_id+'\').checked=true;">(change)</a></div>';
							}
						} catch(e){}
						commentShareBoxHTML += '<div style="float:left;padding:0px 0px 0px 5px;margin:0px;cursor:pointer" onclick="javascript:Effect.toggle(\'twitterCommentHelp'+uniq_id+'\', \'appear\')"><span class="questionmark-icon" ></span></div>'
						+ '				            <div align="left" style="padding:0px;margin:0px;position:relative;width:1px;height:1px;float:left">'
						+ '				               <div id="twitterCommentHelp'+uniq_id+'" class="twitterCommentHelpBox" style="border:1px solid #959595;display:none;padding:0px;margin:0px;position:absolute;top:20px;left:-130px;width:200px;background-color:#FFF">'
						+ '                               <div style="padding:3px 5px 3px 5px;margin:0px;font-size:11px;">Tweets will be sent to @twittername to all users who have linked their Twitter account.</div>'
						+ '                            </div>'
						+ '			                </div>'
						+ '							<br clear="all">'
						+ '						</div>'
						+ '					</div>'
						+ '				</div>'
						+ '			</div>'
						+ '			<br clear="all">'
						+ '		</form>'
						+ '		<div id="change_twitter_user_info_'+uniq_id+'" style="margin:0px;padding:5px 0px 0px 70px;font-size:11px;width:280px;display:none">'
						+ '			<div style="padding:7px 0px 0px 40px;font-size:11px;font-family:arial;font-weight:normal;float:left;width:70px;">Twitter ID</div>'
						+ '			<div style="padding:2px;font-size:11px;font-family:arial;font-weight:normal;float:left;"><input type="text" style="border:1px solid #767676;" name="twit_id" id="twit_id'+uniq_id+'" value=""></div><br clear="all">'
						+ '			<div style="padding:7px 0px 0px 40px;font-size:11px;font-family:arial;font-weight:normal;float:left;width:70px;">Password</div>'
						+ '			<div style="padding:2px;font-size:11px;font-family:arial;font-weight:normal;float:left;"><input type="password" style="border:1px solid #767676;" name="twit_pass" id="twit_pass'+uniq_id+'" value=""></div><br clear="all">'
						+ '			<div style="padding:5px 0px 0px 40px;font-size:11px;font-family:arial;font-weight:normal;float:left;"><input type="checkbox" checked name="save_or_not" id="save_or_not<%= uniq_id%>" value="yes"></div>'
						+ '			<div style="padding:7px;font-size:11px;font-family:arial;font-weight:normal;float:left;">Save my twitter password</div>'
						+ '			<div style="margin:0px;padding:7px;width:5px;float:right;font-size:12px;font-family:arial;color:#777777;">'
						+ '				<span class="closeEditTwitterInfoBox" onclick="Javascript: if ($(\'twitter_user_id\').value != \'\') {$(\'change_twitter_user_info_message_'+uniq_id+'\').style.display=\'block\';}$(\'change_twitter_user_info_'+uniq_id+'\').style.display=\'none\';$(\'include_tweet_replize_'+uniq_id+'\').checked=false;" style="cursor:pointer; font-size:11px;color:#2067a7;">(cancel)</span>'
						+ '			</div>'
						+ '		</div>'
						+ '	</div>'
						+ '</div>'
						+ '<br clear="all">';
	$('commentShareBoxHolder'+uniq_id).style.display = 'block';
	$('commentShareBoxHolder'+uniq_id).innerHTML = commentShareBoxHTML;
	if(currentFbUserId > 0){
		setUserImage([currentFbUserId], "square", ["addComment"+uniq_id]);
	}
}

/**
 * Get story image
 */
var getStoryImage = function(story_id, div_id){
	if (story_id == "") {
		alert("Please provide story id");
		return false;
	}
	if($('storyImageContainer_'+div_id) != null){
		$('storyZoomedImage_'+div_id).style.display = 'block';
		$("imageZoomed_"+div_id).innerHTML = '<a href="" class="image-minimize-button" style="text-decoration:none;" onclick="javascript: closeStoryImage('+story_id+', '+div_id+');return false;"></a>';
		$("imageZoomedPlayText_"+div_id).innerHTML = '<a href="" style="text-decoration:none;" onclick="javascript: closeStoryImage('+story_id+', '+div_id+');return false;">Mininmize</a>';
		return false;
	}
	postParameters = "story_id="+story_id;
	// display the loading icon
	$('storyImageLoadingIcon_'+div_id).style.display= 'block';
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: function (response) {getStoryImageCallback(response, story_id, div_id);},
		// Handle 404
		on404: getStoryImage404Callback,
		// Handle other errors
		onFailure: getStoryImageFailureCallback
	}
	// Data store model
	new Ajax.Request('/story-image', ajaxRequestOptions);
}

/**
 * Get story image success callback function
 */
var getStoryImageCallback = function (response, story_id, div_id){
	// hide the loading icon
	$('storyImageLoadingIcon_'+div_id).style.display= 'none';
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track edit story action
	tracAjaxFunctionalities('/story-image');
	//check if there is an error
	if (response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		$('imageZoomed_'+div_id).className = 'image-minimize-button';
		var storyImageInfo = response_data.story_image;
		$('storyZoomedImage_'+div_id).innerHTML = '' ;
		var storyImageInnerHtml = '<div id="storyImageContainer_'+div_id+'" class="story-image" style="padding:10px 0px 0px 0px;margin:0px;">'
										+'<table width="100%" style="padding:0px;margin:0px;" valign="top" align="center">'
											+'<tr>'
												+'<td align="center" valign="middle" style="padding:2px;margin:0px;border:1px solid #959595;background:url('+S3_STATIC_ASSETS_PATH+'/images/loader.gif) no-repeat; background-position: 48% 48%;">'
													+'<div style="padding:0px;margin:0px;"><img src="'+storyImageInfo['display_url']+'" style="padding:0px;margin:0px;" /></div>'
												+'</td>'
												+'<td align="left" valign="bottom">'
													+'<div style="cursor:pointer;text-decoration:underline;color:#2C6C92;font-family:Arial;font-size:12px;padding:0px 0px 0px 2px;margin:0px;width:32px;" onclick="javascript: closeStoryImage('+story_id+', '+div_id+');return false;">close</div>'
												+'</td>'
											+'</tr>'
										+'</table>'
								  +'</div>';
		$('storyZoomedImage_'+div_id).innerHTML = storyImageInnerHtml;
		$('storyZoomedImage_'+div_id).style.display = 'block';
		$("imageZoomed_"+div_id).innerHTML = '<a href="" class="image-minimize-button" style="text-decoration:none;" onclick="javascript: closeStoryImage('+story_id+', '+div_id+');return false;"></a>';
		$("imageZoomedPlayText_"+div_id).innerHTML = '<a href="" style="text-decoration:none;" onclick="javascript: closeStoryImage('+story_id+', '+div_id+');return false;">Mininmize</a>';
	}
}

/**
 * Get story image failure callback function
 */
var getStoryImageFailureCallback = function (){
	// hide the loading icon
	$('storyImageLoadingIcon_'+div_id).style.display= 'none';
	alert("Error on page");
}
/**
 * Get story image 404 callback function
 */
var getStoryImage404Callback= function (){
	// hide the loading icon
	$('storyImageLoadingIcon_'+div_id).style.display= 'none';
	alert("Error page is not found");
}

/**
*	closed the story image div and change the enlarge icon
*/
function closeStoryImage(story_id, div_id){
	//$('imageZoomed_'+story_id).className = 'play-button';
	$('storyZoomedImage_'+div_id).style.display = 'none';
	$("imageZoomed_"+div_id).innerHTML = '<a href="" class="image-zoom-button" style="text-decoration:none;" onclick="javascript: getStoryImage('+story_id+', '+div_id+');return false;"></a>';
	$("imageZoomedPlayText_"+div_id).innerHTML = '<a href="" style="text-decoration:none;" onclick="javascript: getStoryImage('+story_id+', '+div_id+');return false;">Enlarge</a>';
}

/**
 * append @socialmedianUrl to text area
 */
var replyToUser = function(socialmedianUrl, uniqId){
	try {
		$('addCommentLink'+uniqId).style.display = 'none';
		$('addCommentBox'+uniqId).style.display = 'block';
		if ($('user_comment'+uniqId).value != "") {
		    $('user_comment'+uniqId).value = $('user_comment'+uniqId).value+"@"+socialmedianUrl+" ";
		} else {
			$('user_comment'+uniqId).value = "@"+socialmedianUrl+" ";
		}
		$('user_comment'+uniqId).focus();
	} catch (e) {}
}

// global variable for replize comments
var REPLIZE_COMMENT_ARRAY = new Array();
// global variable for currently selected Activity
var CURRENTLY_SELECTED_ACTIVITY = 0;
// global variable for checking show / hide comment
var COMMENT_BUTTON_STATUS = new Array();
 /**
 * Author - Sharief
 * Date - 19 sept, 2008
 * getting all comments info for story for replize
 */
var getStoryAllCommentsReplize = function (uniq_id, story_id, current_user_id, current_user_name){
	// show loading image
	$('commentShareBoxHolder'+uniq_id).innerHTML = '<div style="padding:4px 0px 0px 30px;margin:0px;">'+
												'<div style="float:left;padding:0px;margin:0px;"><img src="'+ S3_STATIC_ASSETS_PATH + '/images/loader.gif"></div>'+
												'<div style="float:left;padding:0px 0px 0px 5px;margin:0px;font-size:11px;">Loading...</div>'+
												'<br clear="all">'+
											 '</div>';
	$('commentShareBoxHolder'+uniq_id).style.display = "block";
 	// If get more comments link hash contains data for that story's more comments, then call directly callback function with that data as response.
 	var postParameters = "story_id="+story_id;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: function(response){ getStoryAllCommentsReplizeCallback(response, uniq_id, story_id, current_user_id, current_user_name); },
		// Handle 404
		on404: getStoryAllCommentsReplize404Callback,
		// Handle other errors
		onFailure: getStoryAllCommentsReplizeFailureCallback
	}
	new Ajax.Request('/get-all-comments-for-replize', ajaxRequestOptions);
}

/**
 * getStoryAllCommentsReplize success callback
 */
var getStoryAllCommentsReplizeCallback = function (response, uniq_id, story_id, current_user_id, current_user_name){
	//eval the json object
	 response_data = eval('(' + response.responseText + ')');
	if(response_data.error != 0){
		alert(response_data.message);
	}else{
	try {
		var userImg = (currentFbUserId > 0 ? '<img id="addComment'+uniq_id+'-'+currentFbUserId+'"/>' : '<img src="'+S3_DYNAMIC_ASSETS_PATH +'/user-images/'+ current_user_id +'-small.jpg" >');
		commentShareBoxHTML = '<div style="margin:0px;padding:0px;float:left;">'
						+'	<div id="innerShareCommentBoxHolder'+uniq_id+'" style="margin:0px;padding:0px;">'
						+'		<div id="showMoreCommentsLink'+uniq_id+'" style="margin:0px;padding:5px 0px 0px 10px; width: 580px;">'
						+'		</div>'
						+'	</div>'
						+'	<div id="showAllComments'+uniq_id+'" style="margin:0px;padding:9px 0px 0px 0px;font-size:12px;display:none;"></div>'
						+'	<div id="showMoreForReplize'+uniq_id+'" style="padding:9px 0px 0px 15px;margin:0px;display:block;font-size:12px;">'
						+'		<div class="more-comments-browse-icon" style="float:left;margin:0px;padding:0px;cursor:pointer;" onclick="javascript: getStoryAllCommentsReplize('+uniq_id+', '+story_id+', '+current_user_id+', \''+current_user_name+'\');"></div>'
						+'		<div style="float:left;margin:0px;padding:0px 0px 0px 2px;">'
						+'			<i><a class="userLinkInactive" href="Javascript: void(0)" style="text-decoration:none;color:#2464AB;" onclick="javascript: getStoryAllCommentsReplize('+uniq_id+', '+story_id+', '+current_user_id+', \''+current_user_name+'\');"></a></i>'
						+'		</div>'
						+'		<br clear="all">'
						+'	</div>'
						+ '	<div style="margin:0px;padding:10px 0px 0px 15px;">'
						+ '		<form id="clipCommentForm'+uniq_id+'" onsubmit="javascript: addClipComment('+story_id+',\''+uniq_id+'\'); if ($(\'twitter_user_id\').value != \'\') {$(\'change_twitter_user_info_message_'+uniq_id+'\').style.display=\'block\';}$(\'change_twitter_user_info_'+uniq_id+'\').style.display=\'none\';$(\'include_tweet_replize_'+uniq_id+'\').checked=false; return false;" style="margin:0px;padding:0px;">'
						+ '			<div style="margin:0px;padding:0px;float:left;">'+userImg+'</div>'
						+ '			<div id="addCommentLink'+uniq_id+'" style="margin:0px;padding:0px 0px 0px 5px;float:left;font-size:12px;">'
						+ ' 			<a style="color:#2464AB;cursor:pointer;" onclick="Javascript: $(\'addCommentBox'+uniq_id+'\').style.display = \'block\'; $(\'addCommentLink'+uniq_id+'\').style.display = \'none\'; if (MY_SM_CONTACTS.length == 0 && NO_SM_CONTACTS == 0){getMyContacts();}">Add your comment</a>'
						+ '			</div>'
						+ ' 		<div id="addCommentBox'+uniq_id+'" style="display:none;">'
						+ ' 			<div style="margin:0px;padding:2px 0px 0px 5px;float:left;font-size:11px;">'
						+ '					<a href="http://'+APP_DOMAIN+'/'+current_user_name+'/home" style="color:#2464AB;cursor:pointer;text-decoration:underline;">You</a>'
						+ '				</div>'
						+ '				<div style="margin:0px;padding:0px 0px 0px 5px;float:left;font-size:12px;color:#2164AA;">'
						+ '					<textarea id="user_comment'+uniq_id+'" name="user_comment" autocomplete="off" value="" style="width:370px;height:45px;border:1px solid #C1C1C1;" onkeyup="auto_complete_my_contacts(event, \''+uniq_id+'\');"></textarea>'
						+ '					<div id="sm_contacts_auto_complete'+uniq_id+'" class="replize_autocompleter" style="display: none;"></div>'
						+ '				</div>'
						+ '				<div style="margin:0px;padding:0px 0px 0px 7px;float:left;">'
						+ '					<div id="addCommentAcitvityIcon'+uniq_id+'" align="center" style="padding:0px;margin:0px;visibility:hidden;">'
						+ '						<img src="'+S3_DYNAMIC_ASSETS_PATH+'/images/loader.gif" />'
						+ '					</div>'
						+ '					<div style="padding: 7px 0px 0px 0px;margin:0px;"><input type="submit" name="submit" value="Add" /></div>'
						+ '				</div>'
						+ ' 			<br clear="all"/>'
						+ '				<div style="margin:0px;padding:3px 0px 0px 50px;float:left;font-size:10px;">'
						+ '					<span style="color:#d97430">New!</span>&nbsp;&nbsp;Auto-complete to include your socialmedian contacts in a comment. Just type \"@\" and the first letter of the user\'s name. (e.g. @jasongoldberg @louisgray)'
						+ '				</div>'
						+ '				<div id="tweetReplizeCheckBox'+uniq_id+'" style="margin:0px;padding:3px 0px 0px 0px;float:left;">'
						+ '					<div style="margin:0px;padding:0px 0px 0px 50px;float:left;font-size:11px;">'
						+ '						<div style="padding:2px 0px 0px 0px;margin:0px;float:left;width:17px;">'
						+ '							<img src=\''+S3_STATIC_ASSETS_PATH+'/images/twitter_icon.gif\'/>'
						+ ' 					</div>'
						+ '						<div style="padding:0px;margin:0px;float:left;width:17px;"><input type="checkbox" unchecked name="send_replize_tweet" id="include_tweet_replize_'+uniq_id+'" value="yes" onclick="Javascript: if(!$(\'twitter_user_id\').value && this.checked) {$(\'change_twitter_user_info_'+uniq_id+'\').style.display=\'block\';} "></div>'
						+ '						<div style="padding:2px 0px 0px 2px;margin:0px;float:left;">'
						+ '							<div style="float:left;padding:0px 0px 0px 5px;margin:0px;">Also tweet this comment/reply on twitter.</div>'
						try {
							if($('twitter_user_id').value != "") {
								commentShareBoxHTML += '<div style="float:left;padding:0px;margin:0px;" id="change_twitter_user_info_message_'+uniq_id+'">Tweet will be sent using <font style=\'color:#d97430;\'>'+$('twitter_user_id').value+'</font>&nbsp;&nbsp;<a style="cursor:pointer;text-decoration:none;color:#2067a7;" href="javascript:void(0);" onclick="Javascript: $(\'change_twitter_user_info_message_'+uniq_id+'\').style.display=\'none\';$(\'change_twitter_user_info_'+uniq_id+'\').style.display=\'block\';$(\'include_tweet_replize_'+uniq_id+'\').checked=true;">(change)</a></div>';
							}
						} catch(e){}
						commentShareBoxHTML += '<div style="float:left;padding:0px 0px 0px 5px;margin:0px;cursor:pointer" onclick="javascript:Effect.toggle(\'twitterCommentHelp'+uniq_id+'\', \'appear\')"><span class="questionmark-icon" ></span></div>'
						+ '				            <div align="left" style="padding:0px;margin:0px;position:relative;width:1px;height:1px;float:left">'
						+ '				               <div id="twitterCommentHelp" class="twitterCommentHelpBox'+uniq_id+'" style="border:1px solid #959595;display:none;padding:0px;margin:0px;position:absolute;top:20px;left:-130px;width:200px;background-color:#FFF">'
						+ '                               <div style="padding:3px 5px 3px 5px;margin:0px;font-size:11px;">Tweets will be sent to @twittername to all users who have linked their Twitter account.</div>'
						+ '                            </div>'
						+ '			                </div>'
						+ '							<br clear="all">'
						+ '						</div>'
						+ '					</div>'
						+ '				</div>'
						+ '			</div>'
						+ '			<br clear="all">'
						+ '		</form>'
						+ '		<div id="change_twitter_user_info_'+uniq_id+'" style="margin:0px;padding:5px 0px 0px 70px;font-size:11px;width:280px;display:none">'
						+ '			<div style="padding:7px 0px 0px 20px;font-size:11px;font-family:arial;font-weight:normal;float:left;width:70px;">Twitter ID</div>'
						+ '			<div style="padding:2px;font-size:11px;font-family:arial;font-weight:normal;float:left;"><input type="text" style="border:1px solid #767676;" name="twit_id" id="twit_id'+uniq_id+'" value=""></div><br clear="all">'
						+ '			<div style="padding:7px 0px 0px 20px;font-size:11px;font-family:arial;font-weight:normal;float:left;width:70px;">Password</div>'
						+ '			<div style="padding:2px;font-size:11px;font-family:arial;font-weight:normal;float:left;"><input type="password" style="border:1px solid #767676;" name="twit_pass" id="twit_pass'+uniq_id+'" value=""></div><br clear="all">'
						+ '			<div style="padding:5px 0px 0px 20px;font-size:11px;font-family:arial;font-weight:normal;float:left;"><input type="checkbox" checked name="save_or_not" id="save_or_not<%= uniq_id%>" value="yes"></div>'
						+ '			<div style="padding:7px;font-size:11px;font-family:arial;font-weight:normal;float:left;">Save my twitter password</div>'
						+ '			<div style="margin:0px;padding:7px;width:5px;float:right;font-size:12px;font-family:arial;color:#777777;">'
						+ '				<span class="closeEditTwitterInfoBox" onclick="Javascript: if ($(\'twitter_user_id\').value != \'\') {$(\'change_twitter_user_info_message_'+uniq_id+'\').style.display=\'block\';}$(\'change_twitter_user_info_'+uniq_id+'\').style.display=\'none\';$(\'include_tweet_replize_'+uniq_id+'\').checked=false;" style="cursor:pointer; font-size:11px;color:#2067a7;">(cancel)</span>'
						+ '			</div>'
						+ '		</div>'
						+ '	</div>'
						+' </div>';
		} catch (e) {}
		$('commentShareBoxHolder'+uniq_id).innerHTML = commentShareBoxHTML;
		if(currentFbUserId > 0){
			setUserImage([currentFbUserId], "square", ["addComment"+uniq_id]);
		}
		//If response data is not stored in hash then store it.
		var commentAllInfoHTML = '';
		/*commentAllInfoHTML += '<div id="showLessReplizeLink'+uniq_id+'" style="margin:0px;padding:0px 0px 0px 15px;font-size:12px;">'
							+ '		<div class="more-comments-shrink-icon" style="float:left;margin:0px;padding:0px;cursor:pointer;" onclick="javascript: $(\'showAllComments'+uniq_id+'\').style.display = \'none\'; $(\'showMoreCommentsLink'+uniq_id+'\').style.display = \'block\'; $(\'showMoreForReplize'+uniq_id+'\').style.display = \'block\';">'
							+ '		</div>'
							+ '		<div style="float:left;margin:0px;padding:0px 0px 0px 2px;">'
							+ ' 		<i><a href="Javascript: void(0)" style="text-decoration:none;color:#2464AB;" onclick="javascript: $(\'showAllComments'+uniq_id+'\').style.display = \'none\'; $(\'showMoreCommentsLink'+uniq_id+'\').style.display = \'block\'; $(\'showMoreForReplize'+uniq_id+'\').style.display = \'block\';">Show less</a></i>'
							+ '		</div>'
							+ '		<br clear="all">'
							+ '</div>';*/
		var fbUsers = [];
		var uniqIds = [];
		for(i = 0; i < response_data.story_all_comments_info.length; i++){
			commentAllInfoHTML += createCommentInfoDiv(response_data.story_all_comments_info[i], current_user_id, current_user_name, uniq_id, response_data.replied_or_included_comments_for_user);
			if(response_data.story_all_comments_info[i].fb_connect_status == "connected" || response_data.story_all_comments_info[i].fb_connect_status == "merged"){
				fbUsers.push(response_data.story_all_comments_info[i].fb_user_id);
				uniqIds.push("commentList"+response_data.story_all_comments_info[i].id);
			}
		}
		$('showMoreForReplize'+uniq_id).style.display = 'none';
		$('showAllComments'+uniq_id).innerHTML = commentAllInfoHTML;
		$('showMoreCommentsLink'+uniq_id).style.display = 'none';
		$('showAllComments'+uniq_id).style.display = 'block';
		if(fbUsers.length > 0){
			setUserImage(fbUsers, "square", uniqIds);
		}
	}
}

/**
 * getStoryAllCommentsReplize failure callback function
 */
var getStoryAllCommentsReplizeFailureCallback = function (){
	alert("Error on page");
}
/**
 * getStoryAllCommentsReplize 404 callback function
 */
var getStoryAllCommentsReplize404Callback= function (){
	alert("Error page is not found");
}
/**
 * Show hide story comments from replize tab on home page
 */
function showHideReplizeComments(uniq_id, story_id, current_user_id, current_user_name){
	if($('comment_link_'+uniq_id+'_div').className != "commentStoryBackgroundActive"){
		$('comment_link_'+uniq_id+'_div').className = "commentStoryBackgroundActive";
		$('share_link_'+uniq_id+'_div').className = "shareStoryBackgroundInactive";
		$('commentShareBoxHolder'+uniq_id).style.display = 'block';
	}else{
		$('comment_link_'+uniq_id+'_div').className = "commentStoryBackgroundInactive";
		$('commentShareBoxHolder'+uniq_id).style.display = 'none';
		return false;
	}
	getStoryAllCommentsReplize(uniq_id, story_id, current_user_id, current_user_name);
}


/**
 * Set, Get and Delete Cookies
 */
function setCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+escape(value)+expires+"; path=/; domain="+COOKIE_DOMAIN+"";
}

function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function deleteCookie(name) {
	setCookie(name,"",-1);
}
/**
 * To hide connect to facebook messages
 */
var connectToFbMsgClose = function(num){
	postParameters = "num="+num;
	// display the loading icon
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: function (response) {connectToFbMsgCloseCallback(response);},
		// Handle 404
		on404: connectToFbMsgClose404Callback,
		// Handle other errors
		onFailure: connectToFbMsgCloseFailureCallback
	}
	// Data store model
	new Ajax.Request('/close-fb-connect-msg', ajaxRequestOptions);
}

/**
 * To hide connect to facebook messages success callback function
 */
var connectToFbMsgCloseCallback = function (response){
	// hide the loading icon
	$('storyImageLoadingIcon_'+div_id).style.display= 'none';
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track edit story action
	tracAjaxFunctionalities('/close-fb-connect-msg');
	//check if there is an error
	if (response_data.ok == true) {
		//alert the error
		//$(div_id).style.display = 'none';
	}
}

/**
 * To hide connect to facebook messages failure callback function
 */
var connectToFbMsgCloseFailureCallback = function (){
	// hide the loading icon
	alert("Error on page");
}
/**
 * To hide connect to facebook messages 404 callback function
 */
var connectToFbMsgClose404Callback= function (){
	// hide the loading icon
	alert("Error page is not found");
}
/**
 * Author - Ajay Agrawal
 * Date - 03 Oct, 2008
 * Update the like / dislike vote for the story
 */
var updateUserLikeUnlikeVote = function (story_id, uniq_id, vote, title, permalink){
 	if(globalUserId == 0){
		return false;
	}
	try {
		if($('activity_'+ uniq_id +'_done_by_div') != null){
			$('activity_'+ uniq_id +'_done_by_div').innerHTML = '<div style="padding:4px 0px 0px 0px;margin:0px;width:150px;">'
															  +	'	<div style="float:left;padding:0px;margin:0px;"><img src="'+ S3_STATIC_ASSETS_PATH +'/images/loader.gif"></div>'
															  +	'	<div style="float:left;padding:0px 0px 0px 5px;margin:0px;">Loading...</div>'
															  +	'	<br clear="all">'
															  +	'</div>';
			$('activity_'+ uniq_id +'_done_by_div').style.display = 'block';
		}
	} catch(err){}
 	var postParameters = "story_id="+story_id+"&user_vote="+vote+"&story_title="+escape(title)+"&st_permalink="+escape(permalink);
	// Show loading icon
 	$('unlikeLikeAcitvityIcon_'+uniq_id+'_'+story_id).style.display = 'block';
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: function(response){ updateUserLikeUnlikeVoteCallback(response, story_id, uniq_id, vote, permalink); },
		// Handle 404
		on404: function (){updateUserLikeUnlikeVote404Callback(uniq_id, story_id);},
		// Handle other errors
		onFailure: function (){updateUserLikeUnlikeVoteFailureCallback(uniq_id, story_id)}
	}
	new Ajax.Request('/update-unlike-like-vote', ajaxRequestOptions);
}

/**
 * updateUserLikeUnlikeVote success callback
 */
var updateUserLikeUnlikeVoteCallback = function (response, story_id, uniq_id, vote, permalink){
	// Hide loading icon
 	$('unlikeLikeAcitvityIcon_'+uniq_id+'_'+story_id).style.display = 'none';
	//eval the json object
	 response_data = eval('(' + response.responseText + ')');
	if(response_data.error != 0){
		alert(response_data.message);
	}else{
		var userVoteCountInformation = response_data.vote_counts;
		var totalVotes = (userVoteCountInformation.total_likes + userVoteCountInformation.total_dislikes);
		if(totalVotes > 0){
			var likePersentage = Math.round(userVoteCountInformation.total_likes*100/(totalVotes));
			var displayLikePersentage = (likePersentage == 0 ? 10 : (likePersentage == 100 ? 90 : likePersentage));
			var unlikePersentage = 100 - parseInt(likePersentage);
			var displayUnlikePersentage = 99 - parseInt(displayLikePersentage);
			var activateDiv = (vote == -1 ? 'unlike' : 'like');
			var inactivateDiv = (vote == -1 ? 'like' : 'unlike');
			$(activateDiv+'FaceImage_'+uniq_id+'_'+story_id).style.display = 'none';
			$(activateDiv+'FaceImageActive_'+uniq_id+'_'+story_id).style.display = 'block';
			$(inactivateDiv+'FaceImage_'+uniq_id+'_'+story_id).style.display = 'block';
			$(inactivateDiv+'FaceImageActive_'+uniq_id+'_'+story_id).style.display = 'none';
			$("likeVotePercentageBox_"+uniq_id+'_'+story_id).innerHTML = likePersentage+"%";
			$("unlikeVotePercentageBox_"+uniq_id+'_'+story_id).innerHTML = unlikePersentage+"%";
			$('likeVotePercentage_'+uniq_id+'_'+story_id).style.width = displayLikePersentage+"%";
			$('unlikeVotePercentage_'+uniq_id+'_'+story_id).style.width = displayUnlikePersentage+"%";
			$('likeVotePercentage_'+uniq_id+'_'+story_id).className = 'opacity_100';
			$('unlikeVotePercentage_'+uniq_id+'_'+story_id).className = 'opacity_100';
			/* Update the user vote on story stats widget */
			try{
				$("userStatsLikesPercentage_"+uniq_id).innerHTML = likePersentage+'%';
				$("userStatsUnlikesPercentage_"+uniq_id).innerHTML = unlikePersentage+'%';
			}catch(e){}
			// update the clip icon status
			try {
				if($('clipUnclipStory_hotlist_'+story_id)) {
					var clipCount = $('clipUnclipStory_hotlist_'+story_id).childNodes[1].innerHTML;
					if(isNaN(parseInt(clipCount))){
						clipCount = $('clipUnclipStory_hotlist_'+story_id).childNodes[0].innerHTML;
					}
				}
			} catch(e) {}
			try {
				if($('clipUnclipStory_'+uniq_id)) {
					var clipCount = $('clipUnclipStory_'+uniq_id).childNodes[1].innerHTML;
					if(isNaN(parseInt(clipCount))){
						clipCount = $('clipUnclipStory_'+uniq_id).childNodes[0].innerHTML;
					}
				}
			} catch(e) {}
			var total_clips = parseInt(clipCount) + 1;
			performClipAction(story_id, uniq_id, total_clips);

			voted_users_list = [];
			try{
				if($('activity_'+ uniq_id +'_done_by_div') != null){
					for(i=0; i < response_data.user_vote_info.length; i++){
						// If current user info comes into array list, then check and remove it.
						if( (response_data.user_vote_info[i].vote == vote) && (response_data.user_vote_info[i].socialmedian_url != response_data.current_user.socialmedian_url)){
					        voted_users_list.push(response_data.user_vote_info[i]);
					    }
				    }
					likeUnlikeUserList = generateActivityByList(voted_users_list, (vote == 1 ? 'liked' : 'disliked'), response_data.current_user, uniq_id, story_id, permalink)
					$('activity_'+ uniq_id +'_done_by_div').innerHTML = likeUnlikeUserList;
					// set fb user image
					if(response_data.current_user.fb_connect_status == "connected" || response_data.current_user.fb_connect_status == "merged") {
						setUserImage([response_data.current_user.fb_user_id], 'square', ['activityPic'+uniq_id]);
					}
					//yellow fading technique
					startFadingColor = 0;
					fadeElementId = 'activity_'+ uniq_id +'_done_by_div';
					changeBackgroundColorObject = setInterval(yellowFadingTechnique, 400);
				}
			}catch(e){}

			// publish activity on facebook
		 	if(currentFbUserId > 0) {
			 	var bundleId = (vote == "1" ? likeBundleId : dislikeBundleId);
			 	if(tweet_story_info[story_id][0] != 'story') {
					var actionText="Clip It!";
					var s_link = "http://"+location.host+"/story/"+story_id+"/"+tweet_story_info[story_id][3];
					var src=tweet_story_info[story_id][4];
			 		var title = "<a href='"+s_link+"'>"+unescape(tweet_story_info[story_id][2]).truncate(50)+"</a>"+" on <a href='"+s_link+"'>socialmedian</a>";
					var bundleData = {"actionText":actionText,"url":s_link,"images":[{"src":src,"href":s_link}],"title":title, "short_desc":unescape(tweet_story_info[story_id][2]).truncate(100), "long_desc":unescape(tweet_story_info[story_id][2]).truncate(200)};
				} else {
					var actionText="Clip It!";
					var s_link = "http://"+location.host+"/story/"+story_id+"/"+tweet_story_info[story_id][4];
					var src=tweet_story_info[story_id][5];
					var title = "<a href='"+s_link+"'>"+unescape(tweet_story_info[story_id][1])+"</a>";
					var bundleData = {"actionText":actionText,"url":s_link,"images":[{"src":src,"href":s_link}],"title":title, "short_desc":unescape(tweet_story_info[story_id][2]).truncate(100), "long_desc":unescape(tweet_story_info[story_id][2]).truncate(200)};
				}
			 	publishFeedOnFb(bundleId, bundleData);
			 }

			try{
				if(HAVE_MOOD_DATA.get(uniq_id) == 1 && $('userStoryLikeUnlikeStatsOuterBox_'+uniq_id+'_'+story_id).style.display == 'block'){
					HAVE_MOOD_DATA.set(uniq_id, 0);
					/** call mood modification function **/
					getUsersStoryLikeUnlikeStats(story_id, uniq_id);
				}else if(HAVE_MOOD_DATA.get(uniq_id) == 1 && $('userStoryLikeUnlikeStatsOuterBox_'+uniq_id+'_'+story_id).style.display == 'none'){
					HAVE_MOOD_DATA.set(uniq_id, 0);
				}
			}catch(e){
				// call to modify the story stand alone page stats widget
				getUsersStoryLikeUnlikeStats(story_id, uniq_id);
			}
		}
	}
}
/**
 * updateUserLikeUnlikeVote failure callback function
 */
var updateUserLikeUnlikeVoteFailureCallback = function (uniq_id, story_id){
	// Hide loading icon
 	$('unlikeLikeAcitvityIcon_'+uniq_id+'_'+story_id).style.display = 'none';
	alert("Error on page");
}
/**
 * updateUserLikeUnlikeVote 404 callback function
 */
var updateUserLikeUnlikeVote404Callback= function (uniq_id, story_id){
	// Hide loading icon
 	$('unlikeLikeAcitvityIcon_'+uniq_id+'_'+story_id).style.display = 'none';
	alert("Error page is not found");
}

/**
 * Author - Alpesh
 * Date - 03 Oct, 2008
 * show more users who like story.
 */
var getMoreUsersLikeStory = function (story_id, uniq_id, percentage_likes){
	$('like_loader_div_'+uniq_id).style.display = 'block';
 	var postParameters = "story_id="+story_id;
	// Show loading icon
 	//$('unlikeLikeAcitvityIcon'+unique_id).style.visibility = 'visible';
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: function(response){ getMoreUsersLikeStoryCallback(response, uniq_id, percentage_likes); },
		// Handle 404
		on404: function (){getMoreUsersLikeStory404Callback(uniq_id);},
		// Handle other errors
		onFailure: function (){getMoreUsersLikeStoryFailureCallback(uniq_id)}
	}
	new Ajax.Request('/more-users-likes-story', ajaxRequestOptions);
}

/**
 *  show more users who like story. success callback
 */
var getMoreUsersLikeStoryCallback = function (response, uniq_id, percentage_likes){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	var moreUsersHtml = '<b>'+percentage_likes+'</b> Like:';
	moreUsersHtml += '';
	for(var i=0; i < response_data.users_likes_story.length; i++){
		moreUsersHtml += ' <a style="text-decoration:none;" href="/'+response_data.users_likes_story[i].socialmedian_url+'">'+response_data.users_likes_story[i].socialmedian_url+'</a>';
		moreUsersHtml += (i != response_data.users_likes_story.length-1) ? ',' : ' ';
	}
	moreUsersHtml += '(<a class="read_more_link" style="cursor:pointer;" onclick="javascript:$(\'more_users_like_story_span_'+uniq_id+'\').style.display = \'none\';	$(\'users_like_story_span_'+uniq_id+'\').style.display = \'block\';">show less</a>)';
	$('like_loader_div_'+uniq_id).style.display = 'none';
	$('users_like_story_span_'+uniq_id).style.display = 'none';
	$('more_users_like_story_span_'+uniq_id).style.display = 'block';
	$('more_users_like_story_span_'+uniq_id).innerHTML = moreUsersHtml;
}
/**
 *  show more users who like story. failure callback function
 */
var getMoreUsersLikeStoryFailureCallback = function (uniq_id){
	// Hide loading icon
 	//$('unlikeLikeAcitvityIcon'+uniq_id).style.visibility = 'hidden';
	alert("Error on page");
}
/**
 *  show more users who like story. 404 callback function
 */
var getMoreUsersLikeStory404Callback= function (uniq_id){
	// Hide loading icon
 	//$('unlikeLikeAcitvityIcon'+uniq_id).style.visibility = 'hidden';
	alert("Error page is not found");
}

/**
 * Author - Alpesh
 * Date - 03 Oct, 2008
 * show more users who unlike story.
 */
var getMoreUsersUnlikeStory = function (story_id, uniq_id, percentage_unlikes){
	$('unlike_loader_div_'+uniq_id).style.display = 'block';
 	var postParameters = "story_id="+story_id;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: function(response){ getMoreUsersUnlikeStoryCallback(response, uniq_id, percentage_unlikes); },
		// Handle 404
		on404: function (){getMoreUsersUnlikeStory404Callback(uniq_id);},
		// Handle other errors
		onFailure: function (){getMoreUsersUnlikeStoryFailureCallback(uniq_id)}
	}
	new Ajax.Request('/more-users-unlikes-story', ajaxRequestOptions);
}

/**
 *  show more users who unlike story. success callback
 */
var getMoreUsersUnlikeStoryCallback = function (response, uniq_id, percentage_unlikes){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	var moreUsersHtml = '<b>'+percentage_unlikes+'</b> Dislike:';
	moreUsersHtml += '';
	for(var i=0; i < response_data.users_unlikes_story.length; i++){
		moreUsersHtml += ' <a style="text-decoration:none;" href="/'+response_data.users_unlikes_story[i].socialmedian_url+'">'+response_data.users_unlikes_story[i].socialmedian_url+'</a>';
		moreUsersHtml += (i != response_data.users_unlikes_story.length-1) ? ',' : ' ';
	}
	moreUsersHtml += '(<a class="read_more_link" style="cursor:pointer;" onclick="javascript:$(\'more_users_unlike_story_span_'+uniq_id+'\').style.display = \'none\';	$(\'users_unlike_story_span_'+uniq_id+'\').style.display = \'block\';">show less</a>)';
	$('unlike_loader_div_'+uniq_id).style.display = 'none';
	$('users_unlike_story_span_'+uniq_id).style.display = 'none';
	$('more_users_unlike_story_span_'+uniq_id).style.display = 'block';
	$('more_users_unlike_story_span_'+uniq_id).innerHTML = moreUsersHtml;
}
/**
 *  show more users who unlike story. failure callback function
 */
var getMoreUsersUnlikeStoryFailureCallback = function (uniq_id){
	// Hide loading icon
 	//$('unlikeLikeAcitvityIcon'+uniq_id).style.visibility = 'hidden';
	alert("Error on page");
}
/**
 *  show more users who unlike story. 404 callback function
 */
var getMoreUsersUnlikeStory404Callback= function (uniq_id){
	// Hide loading icon
 	//$('unlikeLikeAcitvityIcon'+uniq_id).style.visibility = 'hidden';
	alert("Error page is not found");
}



/**
 * Author - Alpesh
 * Date - 03 Oct, 2008
 * show users stats of like/unlike story.
 */
var getUsersStoryLikeUnlikeStats = function (story_id, uniq_id){
	var callFromStory = 0;
	// try catch for story stats widget
	try{
		if($('userStoryLikeUnlikeStatsBox_'+uniq_id+'_'+story_id).innerHTML == ''){
			/**
			*	Rounded corner for stats box
			*/
			userStoryLikeUnlikeStatsSettings = {
			    tl: { radius: 5 },
			    tr: { radius: 5 },
			    bl: { radius: 5 },
			    br: { radius: 5 },
			    antiAlias: true,
			    autoPad: false,
			    validTags: ["div"]
			}
			var userStoryLikeUnlikeStatsObject = new curvyCorners(userStoryLikeUnlikeStatsSettings, $('userStoryLikeUnlikeStatsOuterBox_'+uniq_id+'_'+story_id));
			userStoryLikeUnlikeStatsObject.applyCornersToAll();
		}else{
			if(HAVE_MOOD_DATA.get(uniq_id) == 1){
				$('userStoryLikeUnlikeStatsOuterBox_'+uniq_id+'_'+story_id).style.display = 'block';
				try{
					$('userStoryLikeUnlikeStatsPaddingDiv_'+uniq_id+'_'+story_id).style.display = 'block';
				}catch(e){}
				return false;
			}
		}
	}catch(e){ callFromStory = 1; }
	$('unlikeLikeAcitvityIcon_'+uniq_id+'_'+story_id).style.display = 'block';
 	var postParameters = "story_id="+story_id;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: function(response){ getUsersStoryLikeUnlikeStatsCallback(response, story_id, uniq_id, callFromStory); },
		// Handle 404
		on404: function (){getUsersStoryLikeUnlikeStats404Callback(uniq_id, story_id);},
		// Handle other errors
		onFailure: function (){getUsersStoryLikeUnlikeStatsFailureCallback(uniq_id, story_id)}
	}
	new Ajax.Request('/users-likes-unlikes-story-stats', ajaxRequestOptions);
}

/**
 *  show more users who unlike story. success callback
 */
var getUsersStoryLikeUnlikeStatsCallback = function (response, story_id, uniq_id, callFromStory){
	// hide loading icon
	$('unlikeLikeAcitvityIcon_'+uniq_id+'_'+story_id).style.display = 'none';
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	if(!response_data.ok){
		alert(response_data.message);
	}else{
		HAVE_MOOD_DATA.set(uniq_id,1);
		var userLikesStoryStats = response_data.users_likes_story;
		var userUnlikesStoryStats = response_data.users_unlikes_story;
		var percentageLikes = response_data.percentage_likes;
		var percentageUnlikes = response_data.percentage_unlikes;
		var maxLikesData = Math.min(4, userLikesStoryStats.length);
		var maxUnlikesData = Math.min(4, userUnlikesStoryStats.length);
		var divWidth = (callFromStory == 1 ? '240px' : '500px');
		var displayUserStoryStatsInnerHtml =  '<div style="padding:0px;margin:0px;font-family:Arial;font-weight:normal;">'
										   	+ '	<div style="padding:0px 6px 0px 0px;margin:0px;float:left;">'
										   	+ '		<span class="like-active-background-icon"></span>'
										   	+ '	</div>'
											+ ' <div id="users_like_story_div_'+uniq_id+'" style="padding:0px 3px 0px 0px;margin:0px;float:left;width:'+divWidth+'">'
											+ '		<span id="users_like_story_span_'+uniq_id+'">'
											+ '			<b id="userStatsLikesPercentage_'+uniq_id+'">'+percentageLikes+'%</b> Like'+(percentageLikes != 0 ? ":" : "");
		for(i=0;i<maxLikesData;i++){
			displayUserStoryStatsInnerHtml  +=			(i==0 ? "" : ",")+' <a href="/'+userLikesStoryStats[i][1]+'">'+userLikesStoryStats[i][1]+'</a>';
		}
		if(userLikesStoryStats.length > 4){
			displayUserStoryStatsInnerHtml  +='			(<a class="read_more_link" style="cursor:pointer;" onclick="javascript:getMoreUsersLikeStory(\''+story_id+'\', \''+uniq_id+'\', \''+percentageLikes+'\');">show more</a>)'
		}
			displayUserStoryStatsInnerHtml  +='		</span>'
											+ '		<span id="more_users_like_story_span_'+uniq_id+'" style="display:none;"></span>'
											+ '	</div>'
											+ '	<div id="like_loader_div_'+uniq_id+'" style="padding:0px 0px 0px 25px;margin:0px;display:none;float:left;">'
											+ '		<img src="'+S3_STATIC_ASSETS_PATH+'/images/loader.gif" />'
											+ '	</div>'
											+ '	<br clear="all">'
											+ '</div>'
											+ '<div style="padding:10px 0px 3px 0px;">'
											+ '	<div style="padding:0px 6px 0px 0px;margin:0px;float:left;">'
											+ '		<span class="unlike-active-background-icon"></span>'
											+ '	</div>'
											+ '	<div id="users_unlike_story_div_'+uniq_id+'" style="padding:0px 3px 0px 0px;margin:0px;float:left;width:'+divWidth+'">'
											+ '		<span id="users_unlike_story_span_'+uniq_id+'">'
											+ '			<b id="userStatsUnlikesPercentage_'+uniq_id+'">'+percentageUnlikes+'%</b> Dislike'+(percentageUnlikes != 0 ? ":" : "");
		for(i=0;i<maxUnlikesData;i++){
			displayUserStoryStatsInnerHtml  +=			(i==0 ? "" : ",")+' <a href="/'+userUnlikesStoryStats[i][1]+'">'+userUnlikesStoryStats[i][1]+'</a>';
		}
		if(userUnlikesStoryStats.length > 4){
			displayUserStoryStatsInnerHtml  += '		(<a class="read_more_link" href="javascript:void(0);" onclick="javascript:getMoreUsersUnlikeStory(\''+story_id+'\', \''+uniq_id+'\', '+percentageUnlikes+');">show more</a>)';
		}
		displayUserStoryStatsInnerHtml  	+='		</span>'
											+ '		<span id="more_users_unlike_story_span_'+uniq_id+'" style="display:none"></span>'
											+ '	</div>'
											+ '	<div id="unlike_loader_div_'+uniq_id+'" style="padding:0px 0px 0px 25px;margin:0px;display:none;float:left;">'
											+ '		<img src="'+S3_STATIC_ASSETS_PATH+'/images/loader.gif" />'
											+ '	</div>'
											+ '	<br clear="all">'
											+ '</div>';
		try{
			$('userStoryLikeUnlikeStatsBox_'+uniq_id+'_'+story_id).innerHTML = displayUserStoryStatsInnerHtml;
		}catch(e){}
		try{
			$('like_unlike_status_info_'+story_id).innerHTML = displayUserStoryStatsInnerHtml;
		}catch(e){}
		try{
			$('userStoryLikeUnlikeStatsPaddingDiv_'+uniq_id+'_'+story_id).style.display = 'block';
		}catch(e){}
		$('userStoryLikeUnlikeStatsOuterBox_'+uniq_id+'_'+story_id).style.display = 'block';
	}
}
/**
 *  show more users who unlike story. failure callback function
 */
var getUsersStoryLikeUnlikeStatsFailureCallback = function (uniq_id, story_id){
	// Hide loading icon
 	$('unlikeLikeAcitvityIcon_'+uniq_id+'_'+story_id).style.display = 'none';
	alert("Error on page");
}
/**
 *  show more users who unlike story. 404 callback function
 */
var getUsersStoryLikeUnlikeStats404Callback= function (uniq_id, story_id){
	// Hide loading icon
 	$('unlikeLikeAcitvityIcon_'+uniq_id+'_'+story_id).style.display = 'none';
	alert("Error page is not found");
}
/**
 * Author - Sumanth
 * Date - 25 Oct, 2008
 * Logout method on election campaign header.
 */
var logoutFromCampaignPage = function(url){
	var postParameters = '';
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: function(response){ logoutFromCampaignPageCallback(response, url); },
		// Handle 404
		on404: logoutFromCampaignPage404Callback,
		// Handle other errors
		onFailure: logoutFromCampaignPageFailureCallback
	}
	new Ajax.Request('/logout', ajaxRequestOptions);
}
var logoutFromCampaignPageCallback = function (response, url){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	if (response_data.logout==true){
		window.location = window.location.href;
	}
}
/**
 * Related topics failure callback function
 */
var logoutFromCampaignPageFailureCallback = function (){
	alert("Error on page");
}
/**
 * Related topics 404 callback function
 */
var logoutFromCampaignPage404Callback= function (){
	alert("Error page is not found");
}
/**
*	Closed the mood stat box.
*/
function closeMoodStatsBox(story_id, uniq_id){
	$('moodIconClass_'+uniq_id+'_'+story_id).className = "mood-inactive-icon";
	$('userStoryLikeUnlikeStatsOuterBox_'+uniq_id+'_'+story_id).style.display="none";
	try{
		$('userStoryLikeUnlikeStatsPaddingDiv_'+uniq_id+'_'+story_id).style.display="none";
	}catch(e){}
}


/*
* promote news network widget code maker function
*/
function promoteNetworkWidgetCodeMaker(){
	if ($('selected_width').value <= 159 || $('selected_width').value >= 501){
		$("display_width_message").style.display = 'block';
		return false;
	}else{
		$("display_width_message").style.display = 'none';
		var widgetCode = '<div id="smPromoteWidget"></div>';
		var sScript="<script ";
		sScript += ' type="text/javascript" language="javascript"&gt;var nos='+$('story_number').value+';var widget_width='+$('selected_width').value+';var tab = "'+$('default_tab_name').value+'"; var REF=""; SM_OPEN_NEW_WINDOW = '+$('default_window_type').value+';';
		sScript += "</script" + ">";
		sScript += '<script ';
		sScript += ' src="http://socialmedian.s3.amazonaws.com/javascripts/promote-campaign-2008.js" type="text/javascript" language="javascript">';
		sScript += "</script" + ">";
		widgetCode += sScript;
		$("widget_code_get").innerHTML = widgetCode.replace(/\</g,'&#60;').replace(/\>/g,'&#62;');
	}
}


/*
* Generate election campaign widget preview
*/
function previewWidget(){
	if ($('selected_width').value <= 159 || $('selected_width').value >= 501){
		$("display_width_message").style.display = 'block';
		return false;
	}else{
		$("display_width_message").style.display = 'none';
		nos = $('story_number').value;
		widget_width = $('selected_width').value;
		tab = $('default_tab_name').value;
		REF = '';
		SM_OPEN_NEW_WINDOW = $('default_window_type').value;
		var location = "election-widget?nos="+nos+"&widget_width="+widget_width+"&tab="+tab+"&onw="+SM_OPEN_NEW_WINDOW;
		window.location.href = location;
	}

}

/*
* MMF network widget code maker function
*/
function MMFWidgetCodeMaker(){
	if ($('selected_width').value <= 159 || $('selected_width').value >= 501){
		$("display_width_message").style.display = 'block';
		return false;
	}else{
		$("display_width_message").style.display = 'none';
		var widgetCode = '<div id="smPromoteMMFWidget"></div>';
		var sScript="<script ";
		sScript += ' type="text/javascript" language="javascript"&gt;var SM_NOS_MMF ='+$('story_number').value+';var SM_WIDGET_WIDTH_MMF='+$('selected_width').value+';var SM_TAB_MMF = "'+$('default_tab_name').value+'"; var SM_REF_MMF=""; var SM_OPEN_NEW_WINDOW_MMF = '+$('default_window_type').value+';';
		sScript += "</script" + ">";
		sScript += '<script ';
		sScript += ' src="http://socialmedian.s3.amazonaws.com/javascripts/promote-forum-updates.js" type="text/javascript" language="javascript">';
		sScript += "</script" + ">";
		widgetCode += sScript;
		$("widget_code_get").innerHTML = widgetCode.replace(/\</g,'&#60;').replace(/\>/g,'&#62;');
	}
}

/*
* Generate MMF widget preview
*/
function previewMMFWidget(){
	if ($('selected_width').value <= 159 || $('selected_width').value >= 501){
		$("display_width_message").style.display = 'block';
		return false;
	}else{
		$("display_width_message").style.display = 'none';
		SM_NOS_MMF  = $('story_number').value;
		SM_WIDGET_WIDTH_MMF = $('selected_width').value;
		SM_TAB_MMF = $('default_tab_name').value;
		SM_REF_MMF = '';
		SM_OPEN_NEW_WINDOW_MMF = $('default_window_type').value;
		var location = "mmf-widget?nos="+SM_NOS_MMF +"&widget_width="+SM_WIDGET_WIDTH_MMF+"&tab="+SM_TAB_MMF+"&onw="+SM_OPEN_NEW_WINDOW_MMF;
		window.location.href = location;
	}

}

/*
* SS 18/11/08
* promote news network widget code maker function for obama white house network
*/
function OWTNetworkWidgetCodeMaker(){
	if ($('selected_width').value <= 159 || $('selected_width').value >= 501){
		$("display_width_message").style.display = 'block';
		return false;
	}else{
		$("display_width_message").style.display = 'none';
		var widgetCode = '<div id="smPromoteOWHTWidget"></div>';
		var sScript="<script ";
		sScript += ' type="text/javascript" language="javascript"&gt;var SM_NOS_OWHT ='+$('story_number').value+';var SM_WIDGET_WIDTH_OWHT='+$('selected_width').value+';var SM_TAB_OWHT = "'+$('default_tab_name').value+'"; var SM_REF_OWHT=""; var SM_OPEN_NEW_WINDOW_OWHT = '+$('default_window_type').value+';';
		sScript += "</script" + ">";
		sScript += '<script ';
		sScript += ' src="http://socialmedian.s3.amazonaws.com/javascripts/promote-obama-white-house-transition.js" type="text/javascript" language="javascript">';
		sScript += "</script" + ">";
		widgetCode += sScript;
		$("widget_code_get").innerHTML = widgetCode.replace(/\</g,'&#60;').replace(/\>/g,'&#62;');
	}
}


/*
* SS 18/11/08
* Generate obama white house transition network widget preview
*/
function previewOWTWidget(){
	if ($('selected_width').value <= 159 || $('selected_width').value >= 501){
		$("display_width_message").style.display = 'block';
		return false;
	}else{
		$("display_width_message").style.display = 'none';
		SM_NOS_OWHT  = $('story_number').value;
		SM_WIDGET_WIDTH_OWHT = $('selected_width').value;
		SM_TAB_OWHT = $('default_tab_name').value;
		SM_REF_OWHT = '';
		SM_OPEN_NEW_WINDOW_OWHT = $('default_window_type').value;
		var location = "obama-white-house-transition-widget?nos="+SM_NOS_OWHT +"&widget_width="+SM_WIDGET_WIDTH_OWHT+"&tab="+SM_TAB_OWHT+"&onw="+SM_OPEN_NEW_WINDOW_OWHT;
		window.location.href = location;
	}

}

/**
 * SK 27/11/08
 * display stories for a particular source in a widget
 */
var getFeedStoriesWidget = function(id, eleId) {
	postParameters = "id="+id;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: function(response){ getFeedStoriesWidgetCallback(response, eleId) },
		// Handle 404
		on404: function (){getFeedStoriesWidget404Callback();},
		// Handle other errors
		onFailure: function (){getFeedStoriesWidgetFailureCallback()}
	}
	new Ajax.Request('/get-feed-stories-widget', ajaxRequestOptions);
}
var getFeedStoriesWidgetCallback = function (response, eleId){
	$(eleId).innerHTML = response.responseText;
}
var getFeedStoriesWidget404Callback = function (){}
var ggetFeedStoriesWidgetFailureCallback = function(){}

/**
 * Author - sharief
 * Date - 20 Oct, 2008
 * get user newsmakers and followers
 */
var getMyContacts = function(){
	if (MY_SM_CONTACTS.length == 0 && NO_SM_CONTACTS == 0){
		var ajaxRequestOptions = {
			// Handle successful response
			onSuccess: function(response){ getMyContactsCallback(response) },
			// Handle 404
			on404: function (){getMyContacts404Callback();},
			// Handle other errors
			onFailure: function (){getMyContactsFailureCallback()}
		}
		new Ajax.Request('/get-my-newsmakers-and-followers', ajaxRequestOptions);
	}else{
		return false;
	}
}

var getMyContactsCallback = function (response){
	//eval the json object
	response_data = response.responseText.evalJSON();
	MY_SM_CONTACTS = response_data.socialmedian_users;
	if (MY_SM_CONTACTS.length == 0) {
		NO_SM_CONTACTS = 1;
	}
}

var getMyContacts404Callback = function (uniqId){
	alert("Error page is not found");
}

var getMyContactsFailureCallback = function (uniqId){
	alert("Error on page");
}
/**
 * Author - sharief
 * Date - 20 Oct, 2008
 * autocomplete my newsmaker and follower socialmedian urls
 */
var autoCompleteActivatedFor = new Array();
var auto_complete_my_contacts = function(event, uniqId, otherTextAreaId){
	var element_id = (otherTextAreaId == undefined ? 'user_comment'+uniqId : otherTextAreaId);
	if (event.keyCode == 50 && autoCompleteActivatedFor[element_id] == undefined) {
		new Autocompleter.Local(element_id, 'sm_contacts_auto_complete'+uniqId, MY_SM_CONTACTS, {tokens:'@'});
		autoCompleteActivatedFor[element_id] = 1;
	}
}

/*
 * Trac ajax functionalities on google analytics
*/
function tracAjaxFunctionalities(custom_url) {
	if(location.hostname == "www.socialmedian.com") {
		urchinTracker(custom_url);
	}
}

/**
 * AA 26/11/08:
 *
 * Check the news flash count and display the broadcast box
 * @param story_id contain the story id of the story
 * @param uniq_id contain the unique id for creating divs
 * @param flashCount contain the total number of news flash
 * @param reload is 1 if forcefully reloaded the content
 */
 function getStoryNewsFlash(story_id, uniq_id, flashCount, reload){
	if(reload == null){
		var reload = 0;
	}
	/**
 	 *	Change the class for button
 	 */
 	if($('news_flash_link_'+uniq_id+'_div').className != "newsFlashStoryBackgroundActive"){
		$('share_link_'+uniq_id+'_div').className = "shareStoryBackgroundInactive";
		$('comment_link_'+uniq_id+'_div').className = "commentStoryBackgroundInactive";
		$('news_flash_link_'+uniq_id+'_div').className = "newsFlashStoryBackgroundActive";
		$('commentShareBoxHolder'+uniq_id).style.display = "none";
		$('newsFlashBoxHolder'+uniq_id).style.display = "block";
		$('newsFlashBroadcastBox'+uniq_id).style.display = "block";
	}else if(reload != 1){
		$('news_flash_link_'+uniq_id+'_div').className = "newsFlashStoryBackgroundInactive";
		$('newsFlashBoxHolder'+uniq_id).style.display = "none";
		$('newsFlashBroadcastBox'+uniq_id).style.display = "none";
		return false;
	}
	// check whether a News Flash exists fro the story or not
	if ($('newsFlashInfo' + uniq_id).innerHTML != "" && reload == 0) {
		$('newsFlashInfo' + uniq_id).style.display = "block";
		$('news_flash_link_'+uniq_id+'_div').className = "newsFlashStoryBackgroundActive";
		$('commentShareBoxHolder'+uniq_id).style.display = "none";
		$('newsFlashBoxHolder'+uniq_id).style.display = "block";
		return false;
	}
	if(flashCount == 0){
		displayNewsFlashBroadcastBox(story_id, uniq_id);
		return false;
	}
	var postParameters = "story_id="+story_id;
	$('newsFlashLoadingIcon'+uniq_id).style.display = "block";
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: function(response){getStoryNewsFlashCallback(response, story_id, uniq_id)},
		// Handle 404
		on404: function(){getStoryNewsFlash404Callback(uniq_id)},
		// Handle other errors
		onFailure: function(){getStoryNewsFlashFailureCallback(uniq_id)}
	}
	new Ajax.Request('/stories-news-flashes', ajaxRequestOptions);
 }

/**
 * AA 01/12/08:
 *
 * Callback function when status code 200 returns
 * @param response contain the response text from server
 * @param uniq_id contains the unique id for creating div
 */
var getStoryNewsFlashCallback = function (response, story_id, uniq_id){
	// hide the loading icon
	$('newsFlashLoadingIcon'+uniq_id).style.display = "none";
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	var error = response_data.error;
	var message = response_data.message;
	var newsFlashInfo = response_data.news_flash_info;
	displayNewsFlashInfo(newsFlashInfo, uniq_id, story_id);
	$('news_flash_link_'+uniq_id+'_div').className = "newsFlashStoryBackgroundActive";
	$('commentShareBoxHolder'+uniq_id).style.display = "none";
	$('newsFlashBoxHolder'+uniq_id).style.display = "block";
	if(error == 1){
		$('newsFlashBroadcastMessage'+uniq_id).innerHTML = message;
		$('newsFlashBroadcastMessage'+uniq_id).style.display = "block";
	}
}
/**
 * AA 01/12/08:
 *
 * Failure Callback function if server not reponded correctly
 * @param uniq_id contains the unique id for creating div
 */
var getStoryNewsFlashFailureCallback = function (uniq_id){
	// hide the loading icon
	$('newsFlashLoadingIcon'+uniq_id).style.display = "none";
	$('newsFlashBroadcastMessage'+uniq_id).innerHTML = "Something went wrong please report bug";
	$('newsFlashBroadcastMessage'+uniq_id).style.display = "block";
}
/**
 * AA 01/12/08:
 *
 * 404 Callback
 * @param uniq_id contains the unique id for creating div
 */
var getStoryNewsFlash404Callback= function (uniq_id){
	// hide the loading icon
	$('newsFlashLoadingIcon'+uniq_id).style.display = "none";
	$('newsFlashBroadcastMessage'+uniq_id).innerHTML = "Something went wrong please report bug";
	$('newsFlashBroadcastMessage'+uniq_id).style.display = "block";
}



/**
 * AA 27/11/08:
 *
 * Open text box or message when ckicked on yes/no of news flash
 * @param openInputBox contain whether to open the input box or display the message
 * @param uniq_id contains the unique id for creating div
 */
function openOptionForChangeTitle(openInputBox, uniq_id){
	if(openInputBox){
		$('newsFlashInputBoxButton'+uniq_id).className = "linkHoverActive";
		$('newsFlashInputBoxMessage'+uniq_id).className = "newsFlashLinkHover";
		$('newsFlashInputBox'+uniq_id).style.display = "block";
		$('newsFlashMessageBox'+uniq_id).style.display = "none";
		if($('newsFlashTitle'+uniq_id).value == ""){
			$('newsFlashHelpText'+uniq_id).style.display = "block";
			$('newsFlashTitle'+uniq_id).style.display = "none";
		}
	}else{
		$('newsFlashInputBoxMessage'+uniq_id).className = "linkHoverActive";
		$('newsFlashInputBoxButton'+uniq_id).className = "newsFlashLinkHover";
		$('newsFlashInputBox'+uniq_id).style.display = "none";
		$('newsFlashMessageBox'+uniq_id).style.display = "block";
		$('newsFlashcharCountStatus'+uniq_id).style.display = "none";
	}
	// open the twitt box
	$('twittNewsFlashBox'+uniq_id).style.display = "block";
	$('newsFlashBroadcast'+uniq_id).style.display = "block";
	$('newsFlashTwitterCommentHelp'+uniq_id).style.display='none';
}

/**
 * AA 27/11/08:
 *
 * Open text box or message when ckicked on yes/no of news flash
 * @param story_id story id of fro which we have to add news flash
 * @param uniq_id contains the unique id for creating div
 */
var addNewsFlashToStory = function (story_id, uniq_id){
	if($('newsFlashTitle'+uniq_id).value == "" && $('newsFlashMessageBox'+uniq_id).style.display == 'none'){
		$('newsFlashBroadcastMessage'+uniq_id).innerHTML = "Please enter a News Flash title for this story.";
		$('newsFlashBroadcastMessage'+uniq_id).style.color = "#C40A0A";
		$('newsFlashBroadcastMessage'+uniq_id).style.display = "block";
		return false;
	}else{
		if($('activity_'+ uniq_id +'_done_by_div') != null){
			$('activity_'+ uniq_id +'_done_by_div').innerHTML = '<div style="padding:4px 0px 0px 0px;margin:0px;width:150px;">'
															  +	'	<div style="float:left;padding:0px;margin:0px;"><img src="'+ S3_STATIC_ASSETS_PATH +'/images/loader.gif"></div>'
															  +	'	<div style="float:left;padding:0px 0px 0px 5px;margin:0px;">Loading...</div>'
															  +	'	<br clear="all">'
															  +	'</div>';
			$('activity_'+ uniq_id +'_done_by_div').style.display = 'block';
		}
		var newsFlashTitle = $('newsFlashTitle'+uniq_id).value;
		var postParameters = "story_id="+story_id+"&title="+encodeURIComponent(newsFlashTitle);
		if($('include_tweet_news_flash_'+uniq_id).checked == true){
			var tweeterusername = $('news_flash_twit_id'+uniq_id).value.strip();
			var tweeterpassword = $('news_flash_twit_pass'+uniq_id).value.strip();
			var savePassword = "no";
			if($('news_flash_save_or_not'+uniq_id).checked == true){
				savePassword = "yes";
			}
			postParameters += "&twitt=1"+"&tweet_id="+tweeterusername+"&tweet_pw="+tweeterpassword+"&save_or_not="+savePassword;
		}
	}
	$('newsFlashBroadcastMessage'+uniq_id).innerHTML = "<img src='"+S3_STATIC_ASSETS_PATH+"/images/loader.gif' alt='Loading'/>";
	$('newsFlashBroadcastMessage'+uniq_id).style.display = "block";
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: function(response){addNewsFlashToStoryCallback(response, uniq_id, story_id, newsFlashTitle)},
		// Handle 404
		on404: function(){addNewsFlashToStory404Callback(uniq_id)},
		// Handle other errors
		onFailure: function(){addNewsFlashToStoryFailureCallback(uniq_id)}
	}
	new Ajax.Request('/add-news-flash', ajaxRequestOptions);
}
/**
 * AA 27/11/08:
 *
 * Callback function when status code 200 returns
 * @param response contain the response text from server
 * @param uniq_id contains the unique id for creating div
 */
var addNewsFlashToStoryCallback = function (response, uniq_id, story_id, newsFlashTitle){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	var error = response_data.error;
	var message = response_data.message;
	var storyInformation = response_data.story_info;
	var storyNewsFlashInfo = response_data.story_news_flash_info;
	if(error == 1){
		$('newsFlashBroadcastMessage'+uniq_id).innerHTML = message;
		$('newsFlashBroadcastMessage'+uniq_id).style.color = "#C40A0A";
		return false;
	}else{
		$('newsFlashBroadcastMessage'+uniq_id).innerHTML = message;
		$('newsFlashBroadcastMessage'+uniq_id).style.color = "#6F6F6F";
		// update the clip icon status
		try {
			if($('clipUnclipStory_hotlist_'+story_id)) {
				var clipCount = $('clipUnclipStory_hotlist_'+story_id).childNodes[1].innerHTML;
				if(isNaN(parseInt(clipCount))){
					clipCount = $('clipUnclipStory_hotlist_'+story_id).childNodes[0].innerHTML;
				}
			}
		} catch(e) {}
		try {
			if($('clipUnclipStory_'+uniq_id)) {
				var clipCount = $('clipUnclipStory_'+uniq_id).childNodes[1].innerHTML;
				if(isNaN(parseInt(clipCount))){
					clipCount = $('clipUnclipStory_'+uniq_id).childNodes[0].innerHTML;
				}
			}
		} catch(e) {}
		var total_clips = parseInt(clipCount) + 1;
		performClipAction(story_id, uniq_id, total_clips);
		// publish activity on facebook
		if(currentFbUserId > 0) {
			if(storyNewsFlashInfo[0].news_flash_title != ""){
				var news_flash = "\""+storyNewsFlashInfo[0].news_flash_title.strip()+"\"";
			}else{
				var news_flash = unescape(tweet_story_info[story_id][1]);
			}
		 	if(tweet_story_info[story_id][0]!= 'story') {
				var actionText="Clip It!";
				var s_link = "http://"+location.host+"/story/"+story_id+"/"+tweet_story_info[story_id][3];
				var src=tweet_story_info[story_id][4];
		 		var title = "<a href='"+s_link+"'>"+unescape(tweet_story_info[story_id][2]).truncate(50)+"</a>"+" on <a href='"+s_link+"'>socialmedian</a>";
				var bundleData = {"actionText":actionText,"url":s_link,"images":[{"src":src,"href":s_link}],"title":title, "short_desc":unescape(tweet_story_info[story_id][2]).truncate(100), "long_desc":unescape(tweet_story_info[story_id][2]).truncate(200), "newsFlash":news_flash};
			} else {//alert(tweet_story_info[story_id])
				var actionText="Clip It!";
				var s_link = "http://"+location.host+"/story/"+story_id+"/"+tweet_story_info[story_id][4];
				var src=tweet_story_info[story_id][5];
				var title = "<a href='"+s_link+"'>"+unescape(tweet_story_info[story_id][1])+"</a>";
				var bundleData = {"actionText":actionText,"url":s_link,"images":[{"src":src,"href":s_link}],"title":title, "short_desc":unescape(tweet_story_info[story_id][2]).truncate(100), "long_desc":unescape(tweet_story_info[story_id][2]).truncate(200), "newsFlash":news_flash};
			}
			//var data = {"comment" : "\""+$('user_comment'+aId).value.strip()+"\"", "story_link" : "<a href='http://"+location.host+"/story/"+story_id+"/info'>...</a>"};
			publishFeedOnFb(newsFlashBundleId, bundleData);
		}
		flashed_users_list = [];
		try{
			if($('activity_'+ uniq_id +'_done_by_div') != null){
				for(i=0; i < storyNewsFlashInfo.length; i++){
					// If current user info comes into array list, then check and remove it.
					if(storyNewsFlashInfo[i].user_id != globalUserId){
				        flashed_users_list.push(storyNewsFlashInfo[i]);
				    }
			    }
				storyFlashUserList = generateActivityByList(flashed_users_list, 'news_flash', response_data.current_user, uniq_id, story_id, storyInformation.story_permalink)
				$('activity_'+ uniq_id +'_done_by_div').innerHTML = storyFlashUserList;
				//yellow fading technique
				startFadingColor = 0;
				fadeElementId = 'activity_'+ uniq_id +'_done_by_div';
				changeBackgroundColorObject = setInterval(yellowFadingTechnique, 400);
			}
		}catch(e){}
		// update flash count
		try{
			var flashValue = $('news_flash_link_'+uniq_id).innerHTML.gsub('News Flash', '').strip();
			var newsFlashCount = parseInt(flashValue != '' ? flashValue : 0) + 1;
			$('news_flash_link_'+uniq_id).innerHTML = (newsFlashCount > 1 ? newsFlashCount+" News Flashes" : newsFlashCount+" News Flash");
		}catch(e){}
		$('newsFlashBroadcastMessage'+uniq_id).style.display = "block";
		displayNewsFlashInfo(storyNewsFlashInfo, uniq_id, story_id);
		try{
			if (storyInformation['total_news_flash'] == 1){ displayFirstNewsFlash(storyInformation, uniq_id, storyNewsFlashInfo[0]);}
		}catch(e){}
		$('newsFlashBoxHolder'+uniq_id).style.display = "none";
		$('news_flash_link_'+uniq_id+'_div').className = "newsFlashStoryBackgroundInactive";
		try {
			$('clipCommentRsponse_hotlist'+uniq_id).innerHTML = message;
			//yellow fading technique
			startFadingColor = 0;
			fadeElementId = 'clipCommentRsponse_hotlist'+uniq_id;
			changeBackgroundColorObject = setInterval(yellowFadingTechnique, 400);
			$('clipCommentRsponse_hotlist'+uniq_id).style.display = "block";
		} catch(e) {}
		try {
			$('clipCommentRsponse'+uniq_id).innerHTML = message;
			//yellow fading technique
			startFadingColor = 0;
			fadeElementId = 'clipCommentRsponse'+uniq_id;
			changeBackgroundColorObject = setInterval(yellowFadingTechnique, 400);
			$('clipCommentRsponse'+uniq_id).style.display = "block";
		} catch(e) {}
	}
}
/**
 * AA 27/11/08:
 *
 * Failure Callback function if server not reponded correctly
 * @param uniq_id contains the unique id for creating div
 */
var addNewsFlashToStoryFailureCallback = function (uniq_id){
	$('newsFlashBroadcastMessage'+uniq_id).innerHTML = "Something went wrong please report bug";
	$('newsFlashBroadcastMessage'+uniq_id).style.color = "#C40A0A";
	$('newsFlashBroadcastMessage'+uniq_id).style.display = "block";
}
/**
 * AA 27/11/08:
 *
 * 404 Callback
 * @param uniq_id contains the unique id for creating div
 */
var addNewsFlashToStory404Callback= function (uniq_id){
	$('newsFlashBroadcastMessage'+uniq_id).innerHTML = "Something went wrong please report bug";
	$('newsFlashBroadcastMessage'+uniq_id).style.color = "#C40A0A";
	$('newsFlashBroadcastMessage'+uniq_id).style.display = "block";
}

/**
 * AA 28/11/08
 * Character counter
 * @param userString string whose length to be checked
 * @param maxChar maximum number of allowed character
 * @param customMessage user custom message
 * @param divId div id of the box to display count
 * @param errorMsgDivId div id of the box to display error msg
 */
 function newsFlashCharCount(userString, maxChar, divId, errorMsgDivId, customMessage) {
	len = userString.length;
    customMessage = (customMessage != "" ? customMessage : "You have reached maximum character limit.");
    // display the counter
    $(divId).innerHTML = '' + (maxChar-len);
	// display the error message
	if (len >= maxChar && errorMsgDivId != null) {
		$(errorMsgDivId).innerHTML = customMessage;
		$(errorMsgDivId).style.color = "#c40a0a";
		$(errorMsgDivId).style.display = "block";
	}else{$(errorMsgDivId).style.display = "none";}
}

/**
 * AA 01/12/08
 * Display the broadcast box content
 * @param story_id story id for news flash
 * @param uniq_id unique id for identifying divs
 */
 function displayNewsFlashBroadcastBox(story_id, uniq_id){
	var twitt_id = $('twitter_user_id').value;
	var twitt_pw = $('twitter_user_password').value;
	var activInactiveBroadcast = (globalUserId == 0 ? 'class="userLinkInactive"' : 'onclick="javascript: openOptionForChangeTitle([nfTitle], \''+uniq_id+'\');return false;"');
	var boradcastBoxContent = '<div style="float:left;font-size:14px;color:#333;font-weight:bold;">Broadcast a News Flash to your followers</div>'
								+'<div style="float:left;padding:0px 0px 0px 10px;"><a href="" onclick="javascript: Effect.toggle(\'newsFlashTipBox'+uniq_id+'\');return false;" class="help-small-button"></a></div>'
								+'<div id="newsFlashTipBox'+uniq_id+'" style="position:absolute;background-color:#FFF;z-index:1000;left:40%;width:260px;font-family:Arial;font-size:11px;color:#000;border:1px solid #333;display:none;"><div style="padding:0px 5px 0px 5px;">Create your own headline for this story and alert your followers to check it out!</div></div>'
								+'<br clear="all"/>'
								+'<div style="font-size:12px;float:left;color:#333;font-weight:bold;padding:10px 0px 0px 0px">Do you want to edit the headline?</div>'
								+'<div id="newsFlashInputBoxButton'+uniq_id+'" style="font-size:12px;float:left;color:#2063AD;font-weight:bold;padding:10px 0px 0px 25px" class="newsFlashLinkHover">'
									+'<a href="#" '+ activInactiveBroadcast.replace("[nfTitle]", true) +' style="text-decoration:none;">Yes</a>'
								+'</div>'
								+'<div id="newsFlashInputBoxMessage'+uniq_id+'" style="font-size:12px;float:left;color:#2063AD;font-weight:bold;padding:10px 0px 0px 10px" class="newsFlashLinkHover">'
									+'<a href="#" '+ activInactiveBroadcast.replace("[nfTitle]", false) +' style="text-decoration:none;">No</a>'
								+'</div>'
								+'<br clear="all"/>'
								+'<div id="newsFlashInputBox'+uniq_id+'" style="display:none;padding:0px 0px 0px 0px;margin:0px;">'
									+'<div id="newsFlashHelpText'+uniq_id+'" class="newsFlashHelpText" style="padding:10px 0px 0px 5px;margin:10px 0px 0px 0px;" onclick="javascript: $(\'newsFlashcharCountStatus'+uniq_id+'\').style.display = \'block\'; $(\'newsFlashHelpText'+uniq_id+'\').style.display = \'none\';$(\'newsFlashTitle'+uniq_id+'\').style.display = \'block\'; $(\'newsFlashTitle'+uniq_id+'\').focus(); return false;">'
										+'<div style="padding:0px;margin:0px;float:left;font-weight:bold">Type your News Flash headline here. </div>'
										+'<div style="padding:0px;margin:0px;float:left;color:#D1D1D1;font-weight:bold"> &nbsp;Max 70 characters</div>'
										+'<br clear="all"/>'
									+'</div>'
									+'<div align="right" id="newsFlashcharCountStatus'+uniq_id+'" style="border:0px solid;margin: 0px; padding:0px;width:615px;font-size:13px;font-family:arial;font-weight:bold; color:#c40a0a"></div>'
									+'<input type="text" maxlength="70" id="newsFlashTitle'+uniq_id+'" name="newsFlashTitle" style="display:none;padding:10px 0px 0px 5px;margin:0px;height:30px;width:615px;font-family:arial;font-weight:normal;font-size:18px;color:#000;border:1px solid #888888;" onkeyup="javascript: return newsFlashCharCount(this.value, 70, \'newsFlashcharCountStatus'+uniq_id+'\', \'newsFlashBroadcastMessage'+uniq_id+'\', \'\');" onfocus="javascript: return newsFlashCharCount(this.value, 70, \'newsFlashcharCountStatus'+uniq_id+'\', \'newsFlashBroadcastMessage'+uniq_id+'\', \'\');" onblur="javascript: return newsFlashCharCount(this.value, 70, \'newsFlashcharCountStatus'+uniq_id+'\', \'newsFlashBroadcastMessage'+uniq_id+'\', \'\');"/>'
								+'</div>'
								+'<div id="newsFlashMessageBox'+uniq_id+'" style="padding:13px 0px 0px 0px;margin:0px;display:none;color:#D3731D;font-weight:bold;font-size:14px">The original headline of the story will be submitted as your News Flash</div>'
								+'<div style="padding:0px;margin:0px;display:none;" id="twittNewsFlashBox'+uniq_id+'">'
									+'<div style="padding:5px 0px 0px 0px;margin:0px;float:left;width:17px;">'
										+'<input type="checkbox" name="send_news_flash_tweet" id="include_tweet_news_flash_'+uniq_id+'" value="yes" onclick="javascript: if(!$(\'twitter_user_id\').value && this.checked) {$(\'news_flash_change_twitter_user_info_'+uniq_id+'\').style.display=\'block\';} ">'
									+'</div>'
									+'<div style="padding:5px 0px 0px 2px;margin:0px;float:left;font-size:11px;">'
										+'<div style="float:left;padding:0px 0px 0px 3px;margin:0px;">Tweet this News Flash on <img src="'+S3_STATIC_ASSETS_PATH+'/images/twitter_icon.gif" alt="twitter"/> twitter.</div>';
										if (twitt_id != ""){
											boradcastBoxContent += '<div style="float:left;padding:5px 0px 0px 0px;margin:0px;" id="news_flash_change_twitter_user_info_message_'+uniq_id+'">'
																		+'&nbsp;Tweet will be sent using - <font style="color:#d97430;">'+twitt_id+'</font>&nbsp;<a style="cursor:pointer;text-decoration:none;color:#2067a7;" href="javascript:void(0);" onclick="javascript: $(\'news_flash_change_twitter_user_info_message_'+uniq_id+'\').style.display=\'none\';$(\'news_flash_change_twitter_user_info_'+uniq_id+'\').style.display=\'block\';$(\'include_tweet_news_flash_'+uniq_id+'\').checked=true;">(change)</a>'
																	+'</div>';
										}
				    boradcastBoxContent += '<div align="left" style="padding:0px;margin:0px;position:relative;width:1px;height:1px;float:left">'
											+'<div id="newsFlashTwitterCommentHelp'+uniq_id+'" class="twitterCommentHelpBox" style="border:1px solid #959595;display:none;padding:0px;margin:0px;position:absolute;top:20px;left:-130px;width:200px;background-color:#FFF">'
								                +'<div style="padding:3px 5px 3px 5px;margin:0px;font-size:11px;">Tweets will be sent to @twittername to all users who have linked their Twitter account.</div>'
								            +'</div>'
										+'</div>'
										+'<br clear="all"/>'
									+'</div>'
									+'<br clear="all"/>'
									+'<div id="news_flash_change_twitter_user_info_'+uniq_id+'" style="margin:0px;padding:5px 0px 0px 70px;font-size:11px;width:280px;display:none">'
										+'<div style="padding:7px 0px 0px 20px;font-size:11px;font-family:arial;font-weight:normal;float:left;width:70px;">Twitter ID</div>'
										+'<div style="padding:2px;font-size:11px;font-family:arial;font-weight:normal;float:left;"><input type="text" style="border:1px solid #767676;" name="twit_id" id="news_flash_twit_id'+uniq_id+'" value=""></div>'
										+'<br clear="all"/>'
										+'<div style="padding:7px 0px 0px 20px;font-size:11px;font-family:arial;font-weight:normal;float:left;width:70px;">Password</div>'
										+'<div style="padding:2px;font-size:11px;font-family:arial;font-weight:normal;float:left;"><input type="password" style="border:1px solid #767676;" name="twit_pass" id="news_flash_twit_pass'+uniq_id+'" value=""></div>'
										+'<br clear="all"/>'
										+'<div style="padding:5px 0px 0px 20px;font-size:11px;font-family:arial;font-weight:normal;float:left;"><input type="checkbox" checked name="save_or_not" id="news_flash_save_or_not'+uniq_id+'" value="yes"></div>'
										+'<div style="padding:7px;font-size:11px;font-family:arial;font-weight:normal;float:left;">Save my twitter password</div>'
										+'<div style="margin:0px;padding:7px;width:5px;float:right;font-size:12px;font-family:arial;color:#777777;">'
											+'<span class="closeEditTwitterInfoBox" '+(globalUserId != '' ? 'onclick="javascript: if ($(\'twitter_user_id\').value != \'\') {$(\'news_flash_change_twitter_user_info_message_'+uniq_id+'\').style.display=\'block\';}$(\'news_flash_change_twitter_user_info_'+uniq_id+'\').style.display=\'none\';$(\'include_tweet_news_flash_'+uniq_id+'\').checked=false;"' : '') +' style="cursor:pointer; font-size:11px;color:#2067a7;">(cancel)</span>'
										+'</div>'
									+'</div>'
								+'</div>'
								+'<div id="newsFlashBroadcast'+uniq_id+'" style="padding:0px;margin:0px;display:none;">'
									+'<div id="newsFlashBroadcastButton'+uniq_id+'" style="float:left;padding:10px 0px 0px 0px;margin:0px;"><a href="" onclick="javascript: addNewsFlashToStory('+story_id+', \''+uniq_id+'\');return false;" class="broadcast-button"></a></div>'
									+'<div id="newsFlashBroadcastMessage'+uniq_id+'" style="float:left;padding:13px 0px 0px 30px;margin:0px;font-family:arial;font-weight:bold;font-size:13px;color:#6F6F6F;display:none;"></div>'
									+'<br clear="all"/>'
								+'</div>';
	$("newsFlashBroadcastBox"+uniq_id).innerHTML = boradcastBoxContent;
	newsFlashTipBoxSettings = {
	        tl: { radius: 5 },
	        tr: { radius: 5 },
	        bl: { radius: 5 },
	        br: { radius: 5 },
	        antiAlias: true,
	        autoPad: false,
	        validTags: ["div"]
	    }
	    var newsFlashTipBoxObject = new curvyCorners(newsFlashTipBoxSettings, $('newsFlashTipBox'+uniq_id));
	    newsFlashTipBoxObject.applyCornersToAll();
	$("newsFlashBroadcastBox"+uniq_id).style.display = 'block';

 }

  /**
   * AA 01/12/08
   * Display the first news flash added by current user
   * @param storyInfo contains the objects of story information
   * @param uniq_id contains unique id
   * @partam newsFlashTitle contain the changed story title else blank
   */
function displayFirstNewsFlash(storyInfo, uniq_id, newsFlashInfo){
	try{
		$('newsFlashInfo' +uniq_id).style.display = "block";
		$('news_flash_link_'+uniq_id+'_div').className = "newsFlashStoryBackgroundActive";
	}catch(e){}
	$('commentShareBoxHolder'+uniq_id).style.display = "none";
	$('newsFlashBoxHolder'+uniq_id).style.display = "block";
	if (storyInfo['total_news_flash'] > 0){
		if (newsFlashInfo['title_changed'] == "y"){
				var innerHtmlContent =/*'	<div style="padding:4px 4px 0px 0px;margin:0px;float:left;">'
									 +'		<span class="news-flash-icon"></span>'
									 +'	</div>'
									 +*/'	<div style="float:left;padding:3px 0px 0px 0px" class="'+(storyInfo['total_news_flash'] < 5 ? 'bold_16' : 'bold_18')+'">'
									 +'		<a href="/story/'+uniq_id+'/'+storyInfo['story_permalink']+'" style="text-decoration:none;color:#c30606;">'+newsFlashInfo['news_flash_title']+'</a>'
									 +'		<font class="normal_12"> - <a href="/'+newsFlashInfo['socialmedian_url']+'" style="text-decoration:none;">You</a></font>'
									 +'	</div>'
									 +' <br clear="all"/>';
		}else{
				var innerHtmlContent =/*'	<div style="float:left;padding:8px 4px 0px 0px;margin:0px;width:3%;">'
									 +'		<span class="news-flash-icon"></span>'
									 +'	</div>'
									 +*/'	<div style="float:left;padding:6px 0px 0px 0px;width:96%;" class="'+(storyInfo['total_news_flash'] < 5 ? 'bold_16' : 'bold_18')+'">'
									 +'		<a href="/story/'+uniq_id+'/'+storyInfo['story_permalink']+'" style="text-decoration:none;color:#c30606;">'+storyInfo['title']+'</a>'
									 +' 	<font class="normal_12"> - <a href="/'+newsFlashInfo['socialmedian_url']+'" style="text-decoration:none;">You</a></font>'
									 +'	</div>'
									 +'	<br clear="all"/>';
	  }
	} else {
			var innerHtmlContent ='	<div style="float:left;color:#4282B9;padding:6px 0px 0px 0px" class="flash_story_title">'
								 +'		<a href="/story/'+uniq_id+'/'+storyInfo['story_permalink']+'" style="text-decoration:none;color:#2364a9;">'+storyInfo['title']+'</a><font class="normal_12"> - <a href="/'+newsFlashInfo['socialmedian_url']+'" style="text-decoration:none;">You</a></font>'
							     +'	</div>'
							     +'	<br clear="all"/>';
	}

	$('storyTitle'+uniq_id).innerHTML = innerHtmlContent;
}
/**
 * AA 23/12/08
 * Display all the news flashes at the bottom of the story descrioption
 * @param newsFlashInfo contain the news flash for that story
 * @param uniq_id contain unique id
 */
function displayNewsFlashInfo(newsFlashInfo, uniq_id, story_id){
	var newsFlashInfoContent = "";
	var userWithOldNewsFlashTitle = "";
	var originalTitle = "";
	var userName = "";
	var displayDeleteBox = false;
	var followingStatusClass = "";
	for(i=0;i<newsFlashInfo.length;i++){
		userName = newsFlashInfo[i]['socialmedian_url'].currentUser(newsFlashInfo[i]['user_id']);
		if(globalUserId == newsFlashInfo[i]['user_id']){
			displayDeleteBox = true;
		}
		if(newsFlashInfo[i]['title_changed'] == "y"){
			newsFlashInfoContent += '<div style="padding:4px 0px 0px 0px;margin:0px;font-weight:normal;font-family:arial;font-size:11px;width:100%;">'
		  							 	+'<div style="padding:0px 2px 0px 0px;margin:0px;float:left;">'
									 		+'<span class="news-flash-icon"></span>'
									 	+'</div>'
									 	+'<div style="padding:0px 5px 0px 0px;margin:0px;float:left;color:#6F6F6F;">'
											+newsFlashInfo[i]['news_flash_title'] +' - '+'<a href="/'+(newsFlashInfo[i]['user_id'] != globalUserId ? userName : newsFlashInfo[i]['socialmedian_url']+"/home")+'" style="text-decoration:none;">'+userName+'</a>'
									 	+'</div>'
										+'<div style="float:left;" class="'+newsFlashInfo[i]['following_status_class']+'"></div>'
									 	+'<div style="padding:0px 5px 0px 0px;margin:0px;float:right;">'+newsFlashInfo[i]['added_time']+'</div>'
									 	+'<br clear="all"/>'
		  							 +'</div>';
		} else {
			originalTitle = newsFlashInfo[i]['original_title'];
			userWithOldNewsFlashTitle += '<div style="float:left;">'+(userWithOldNewsFlashTitle != "" ? ', ' : ' ')+'</div>'
										+'<div style="float:left;padding:0px;margin:0px 2px 0px 2px;">'
											+'<a href="/'+(newsFlashInfo[i]['user_id'] != globalUserId ? userName : newsFlashInfo[i]['socialmedian_url']+"/home")+'" style="text-decoration:none;">'+userName+'</a>'
										+'</div>'
										+'<div style="float:left;" class="'+newsFlashInfo[i]['following_status_class']+'" ></div>';
		}
		/**
		* Ketan 29/12/08
		* Display the news flash when it is added from story page.
		*/
		if(newsFlashInfo[i]['title_changed'] == "y"){
			var newsFlashTitleAfterAdd = newsFlashInfo[i]['news_flash_title'];
		}else{
			var newsFlashTitleAfterAdd = newsFlashInfo[i]['original_title'];
		}
	}
	if (userWithOldNewsFlashTitle != "") {
		newsFlashInfoContent +='<div style="padding:4px 0px 0px 0px;margin:0px;font-weight:normal;font-family:arial;font-size:11px;width:100%;">'
  							 	+'<div style="padding:0px 2px 0px 0px;margin:0px;float:left;">'
							 		+'<span class="news-flash-icon"></span>'
							 	+'</div>'
							 	+'<div style="padding:0px;margin:0px;float:left;color:#6F6F6F;">'
									+originalTitle +' - '
							 	+'</div>'
								+'<div style="float:left;">'+userWithOldNewsFlashTitle+'<br clear="all"/></div>'
							 	+'<br clear="all"/>'
  							 +'</div>';
	}
	displayDeleteBox == true ? displayNewsFlashDeleteBox(story_id, uniq_id) : displayNewsFlashBroadcastBox(story_id, uniq_id);
	try{
		$('newsFlashInfo'+uniq_id).innerHTML = newsFlashInfoContent;
		$('newsFlashInfo'+uniq_id).style.display = (newsFlashInfo.length > 0) ? "block" : "none";
	}catch(e){}
	/**
	* Ketan 29/12/08
	* Display the news flash when it is added from story page.
	*/
	try{
		$('addNewsFlashButtonContainer'+uniq_id).innerHTML = '<div style="padding:5px 0px 0px 0px;margin:0px;" class="newsFlashLinkHover" onclick="javascript: toggleTheNewsFlashBox('+story_id+', \''+uniq_id+'\',\'1\');">'
																+'<span style="cursor:pointer;float:left;" class="news-flash-background-icon"></span>'
																+'<a><font style="padding:0px 0px 0px 3px;margin:0px;text-decoration:none;cursor:pointer;float:left;font-size:12px;font-family:arial;font-weight:bold;">Edit News Flash</font></a>'
															+'</div>'
															+'<br clear="all"/>';
		$('newsFlashShowAfterAddTitleBox'+uniq_id).innerHTML = newsFlashTitleAfterAdd;
		$('newsFlashShowAfterAddOuterBox'+uniq_id).style.display = "block";
	}catch(e){}
}

/**
 * AA 23/12/08
 * Return "You" if currently traverse string is currently loggedin user
 * @param user_id contain the currently traverse user id
 */
String.prototype.currentUser = function(user_id) {
    return (user_id == globalUserId ? "You" : this);
}

/**
 * AA 01/12/08
 * Display the news flash delete box content
 * @param story_id story id for news flash
 * @param uniq_id unique id for identifying divs
 */
 function displayNewsFlashDeleteBox(story_id, uniq_id){
	var deleteBoxContent = '<div style="font-size:14px;color:#333;font-weight:bold;">You can only broadcast one News Flash per story. </div>'
							+'<div style="font-size:12px;float:left;color:#333;font-weight:bold;padding:10px 0px 0px 0px">Do you want to delete your previous News Flash?</div>'
							+'<div id="newsFlashInputBoxButton'+uniq_id+'" style="font-size:12px;float:left;color:#2063AD;font-weight:bold;padding:10px 0px 0px 25px" class="newsFlashLinkHover"><a href="/delete-news-flash?story_id='+story_id+'" style="text-decoration:none;">Yes</a></div>'
							+'<br clear="all"/>'
							+'<div style="float:left;padding:5px 0px 0px 0px;margin:0px;"><span  class="nn-note-small-button"></span></div>'
							+'<div style="float:left;padding:8px 0px 0px 3px;margin:0px;font-family:arial;font-weight:normal;font-size:11px;color:#000;">Delete your previous News Flash to submit a new one on the same story.</div>'
							+'<br clear="all"/>';
	$("newsFlashBroadcastBox"+uniq_id).innerHTML = deleteBoxContent;
	$("newsFlashBroadcastBox"+uniq_id).style.display = "block";
 }

 /**
  * AA 23/12/08
  * Delete the news flash added by user on particular story
  * @param story_id story id for News Flash
  * @param uniq_id unique id to identify the the div
  */
 function deleteStoryNewsFlash(story_id, uniq_id){
	if(confirm("Are you sure you want to delete the News Flash?")){
		postParameters = "story_id="+story_id;
		var ajaxRequestOptions = {
			// Use POST
			method: 'post',
			// Send this lovely data
			postBody: postParameters,
			// Handle successful response
			onSuccess: function(response){deleteStoryNewsFlashCallback(response, story_id, uniq_id)},
			// Handle 404
			on404: function(){deleteStoryNewsFlashFailureCallback(uniq_id)},
			// Handle other errors
			onFailure: function(){deleteStoryNewsFlash404Callback(uniq_id)}
		}
		new Ajax.Request('/delete-news-flash', ajaxRequestOptions);
	}
 }
 /**
 * AA 27/11/08:
 *
 * Callback function when status code 200 returns
 * @param response contain the response text from server
 * @param uniq_id contains the unique id for creating div
 */
var deleteStoryNewsFlashCallback = function (response, story_id, uniq_id){
	getStoryNewsFlash(story_id, uniq_id, 2, 1);
}
 /**
 * AA 27/11/08:
 *
 * Failure Callback function if server not reponded correctly
 * @param uniq_id contains the unique id for creating div
 */
var deleteStoryNewsFlashFailureCallback = function (uniq_id){
	$('newsFlashBroadcastMessage'+uniq_id).innerHTML = "Please report bug";
	$('newsFlashBroadcastMessage'+uniq_id).style.color = "#C40A0A";
	$('newsFlashBroadcastMessage'+uniq_id).style.display = "block";
}
/**
 * AA 27/11/08:
 *
 * 404 Callback
 * @param uniq_id contains the unique id for creating div
 */
var deleteStoryNewsFlash404Callback= function (uniq_id){
	$('newsFlashBroadcastMessage'+uniq_id).innerHTML = "Please report bug";
	$('newsFlashBroadcastMessage'+uniq_id).style.color = "#C40A0A";
	$('newsFlashBroadcastMessage'+uniq_id).style.display = "block";
}
/**
 * Ketan 29/12/08:
 * Function to toggle the broadcast/delete news flash box on story page.
 * @param uniq_id contains the unique id for creating div
 */
function toggleTheNewsFlashBox(story_id, uniq_id, current_user_added_flash){
	//show the broadcast/delete news flash box according to its display status.
	if($('newsFlashBoxHolder'+uniq_id).style.display=="block"){
		$('newsFlashBoxHolder'+uniq_id).style.display="none";
	}else{
		$('newsFlashBoxHolder'+uniq_id).style.display="block";
	}
	//call the appropriate function to show the broadcast/delete news flash box.
	if(current_user_added_flash==0){
		displayNewsFlashBroadcastBox(story_id, uniq_id);
	}else{
		displayNewsFlashDeleteBox(story_id, uniq_id);
	}
}

/**
 * Bala 16/01/09:
 * Function to change query order.
 * @param filterStoryOrder query parameter
 * @param valueOfParameter value of query parameter
 */
var changeFilterStoryOrderParam = function (filterStoryOrder, valueOfParameter){
	if(valueOfParameter == 'recent'){
		filterStoryOrder = ['recent'];
	}else if(valueOfParameter == 'today' && filterStoryOrder.indexOf('today') < 0){ // In this case remove if previous selection was 'recent', and push 'today'
		filterStoryOrder = ['today'];
	}else if(valueOfParameter == 'week' && filterStoryOrder.indexOf('week') < 0){
		filterStoryOrder = ['week'];
	}
	if(filterStoryOrder.length == 0){ // if this was empty fill it with default.
		filterStoryOrder = ['recent'];
	}
	return filterStoryOrder;
}

/**
 * Bala 20/02/09:
 * Authenticate user based on facebook credentials
 */
var authenticateFbUser = function(is_button_clicked) {
 	var postParameters = "fb_clicked="+is_button_clicked;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess:  authenticateFbUserCallback,
		// Handle 404
		on404: authenticateFbUser404Callback,
		// Handle other errors
		onFailure: authenticateFbUserFailureCallback
	}
	new Ajax.Request('/authenticate-facebook-user', ajaxRequestOptions);
}
/**
 * Authenticate user based on facebook credentials success callback
 */
var authenticateFbUserCallback = function(response) {
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track add news action
	//tracAjaxFunctionalities('/authenticate-facebook-user');
	if(response_data.error == 0) {
		window.location = (response_data.auth ? redirectFbUser(true) : "http://"+location.host+"/connect-to-facebook?user_name="+response_data.userName);
	}else{
		if(location.href == ("http://"+location.host+"/fb-connect-status")) {
			window.location = redirectFbUser(false)
		}
	}
}
/**
 * Authenticate user based on facebook credentials failure callback function
 */
var authenticateFbUserFailureCallback = function () {
	alert("Error on page");
}
/**
 * Authenticate user based on facebook credentials 404 callback function
 */
var authenticateFbUser404Callback= function () {
 	alert("Error page is not found");
}