/*
Author : Pavan

Library to handle the javascript needs for the story
*/
/**
*	For browser checking
*/
if(navigator.userAgent.toLowerCase().indexOf("msie") > -1){
	var BROWSER = "IE";
}else{
	var BROWSER = "other";
}
function voteStory(widget, vote, nc_id, story_id){
	var story_id = story_id;
	var circle_id = nc_id;
	var protocol_version = get_url_parameter('show');
	if (protocol_version == null){
		protocol_version = 'popular';
	}
	var post_parameters = "story_id="+story_id+"&news_circle_id="+circle_id+"&vote="+vote + '&show='+ protocol_version;
	var ajaxRequestOptions = {
		method: 'post',
		postBody: post_parameters,
		onSuccess: voteStoryCallback,
		// Handle 404
		on404: voteStory404Callback,
		// Handle other errors
		onFailure: voteStoryFailureCallback
	}
	new Ajax.Request('/news-circle/vote-a-story', ajaxRequestOptions);
}

// changing the document contents in response to the vote request
var voteStoryCallback = function(response){
	// Google Analytics - code to track 'vote a story' action
	tracAjaxFunctionalities('/news-network/vote-a-story');
	var json = response.responseText.evalJSON();
	if (json.vote == 0) {
		$('not_relevant_active_'+json.story_id).style.display = "block";
		$('not_relevant_inactive_'+json.story_id).style.display = "none";
	} else {
		$('not_relevant_active_'+json.story_id).style.display = "none";
		$('not_relevant_inactive_'+json.story_id).style.display = "block";
	}
	// if there are more than one story in the document, update all those stories not relevant status.
	var inactiveImages = document.getElementsByClassName('notRelevantStoryInactive');
	for(i=0;i<inactiveImages.length;i++) {
		if (inactiveImages[i].id == "not_relevant_active_" + json.story_id) {
			if (json.vote == 0) {
				inactiveImages[i].style.display = "block";
			} else {
				inactiveImages[i].style.display = "none";
			}
		}
	}
	var activeImages = document.getElementsByClassName('notRelevantStoryActive');
	for(i=0;i<activeImages.length;i++) {
		if (activeImages[i].id == "not_relevant_inactive_" + json.story_id) {
			if (json.vote == 0) {
				activeImages[i].style.display = "none";
			} else {
				activeImages[i].style.display = "block";
			}
		}
	}
};

/**
 * vote callback function
 */
var voteStoryFailureCallback = function (response){
	alert("Error on page");
};
/**
 * story voter error handler
 */
var voteStory404Callback= function (){
	alert("Error page is not found");
};

///////////////////////////////////
//Delete story comment.
///////////////////////////////////

var deleteStoryComment = function(story_id, comment_id){

	var post_parameters = "comment_id="+comment_id+"&story_id="+story_id;
	var ajaxRequestOptions = {
		method: 'post',
		postBody: post_parameters,
		onSuccess: deleteStoryCommentCallback,
		// Handle 404
		on404: deleteStoryComment404Callback,
		// Handle other errors
		onFailure: deleteStoryCommentFailureCallback
	}
	new Ajax.Request('/delete_comment', ajaxRequestOptions);
}

// successfully deleted.
var deleteStoryCommentCallback = function(response){
	var json = response.responseText.evalJSON();
	if (json.ok == 1) {
		window.location = window.location.href;
	} else {
		alert("Deleted comment failed.");
	}
};

/**
 * deleteStoryComment callback function
 */
var deleteStoryCommentFailureCallback = function (response){
	alert("Error on page");
};
/**
 * deleteStoryComment error handler
 */
var deleteStoryComment404Callback= function (){
	alert("Error page is not found");
};

var showMoreToggle = function (){
	if($('show_more_clipper_div').innerHTML == 'Show all'){
		$('contain_clipper_div').style.overflow = 'visible';
		$('show_more_clipper_div').innerHTML = 'Show less';
	}else {
		$('contain_clipper_div').style.overflow = 'hidden';
		$('show_more_clipper_div').innerHTML = 'Show all';
	}
};

/**
 * show those users, who clipped a perticular story
 */
var userClippedStoryAjaxCall = 0;
function showStoryClippedUsers(sId,currUser,str) {
	if(userClippedStoryAjaxCall == 1) {
		// Don't send any request
		if(str == 'more') {
			$('clipped_users').style.display = 'block';
		} else if(str == 'less') {
			$('clipped_users').style.display = 'none';
		}
	} else {
		// Send ajax request
		getStoryClippedUsers(sId,currUser);
	}
}

/**
 * Get story page users
 */
var getStoryClippedUsers = function (sId, currentUserId){
	// show loading image
	$('clipped_story_user_loading_image').style.display = 'block';
	var postParameters = "story_id="+sId+"&curr_user="+currentUserId;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: getStoryClippedUsersCallback,
		// Handle 404
		on404: getStoryClippedUsers404Callback,
		// Handle other errors
		onFailure: getStoryClippedUsersFailureCallback
	}
	new Ajax.Request('/get-story-clipped-users', ajaxRequestOptions);
}

/**
 * Get News Network users success callback function
 */
var getStoryClippedUsersCallback = function (response){
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	// Google Analytics - code to track 'get news network users' action
	tracAjaxFunctionalities('/get-story-clipped-users');
	// hide loading image
	$('clipped_story_user_loading_image').style.display = 'none';
	if(response_data.error == 1) {
		//alert the error
		alert(response_data.message);
	} else {
		userClippedStoryAjaxCall = 1; // don't send ajax request in future
		var htmlHolder = "";
		for(i=0;i<response_data.story_users.length;i++) {
			if(i == 21) {
				htmlHolder += '<br clear="all">'+
									'<div id="clipped_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.story_users[i].id) {
												htmlHolder += '<a href="/'+response_data.story_users[i].socialmedian_url+'/home" onmouseover="$(\'clipped_story_user_name'+response_data.story_users[i].id+'\').style.display=\'block\'" onmouseout="$(\'clipped_story_user_name'+response_data.story_users[i].id+'\').style.display=\'none\'"><img style="vertical-align:middle;" src=\''+ S3_DYNAMIC_ASSETS_PATH +'/user-images/'+response_data.story_users[i].id+'-small.jpg\'></a>';
											} else {
					 							htmlHolder += '<a href="/'+response_data.story_users[i].socialmedian_url+'" onmouseover="$(\'clipped_story_user_name'+response_data.story_users[i].id+'\').style.display=\'block\'" onmouseout="$(\'clipped_story_user_name'+response_data.story_users[i].id+'\').style.display=\'none\'"><img style="vertical-align:middle;" src=\'' + S3_DYNAMIC_ASSETS_PATH + '/user-images/'+response_data.story_users[i].id+'-small.jpg\'></a>';
					 						}
										htmlHolder += '</td>'+
									'</tr>'+
								'</table>'+
								'<div id="clipped_story_user_name'+response_data.story_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.story_users[i].socialmedian_url+'</div>'+
									'</div>'+
								'</div>'+
							'</div>';
							if(response_data.story_users.length > 21 && i == response_data.story_users.length-1) {
								htmlHolder += '<br clear="all">'+
								'</div>';
							} else if(i == response_data.story_users.length-1) {
								htmlHolder += '<br clear="all">';
							}
		}
		$('clipped_story_user_holder').innerHTML = htmlHolder;
	}
}

/**
 * Get News Network users failure callback function
 */
var getStoryClippedUsersFailureCallback = function (){
	alert("Error on page");
}
/**
 * Get News Network users 404 callback function
 */
var getStoryClippedUsers404Callback= function (){
	alert("Error page is not found");
}

/**
 * Share story tab active/inactive
 */
function shareStoryTabActive(type){

	// change tab properties
	$('emailShareBoxHolderTab').className = "shareTabInactive";
	$('emailShareBoxHolderTab').style.top = "-24px";

	$('networkShareBoxHolderTab').className = "shareTabInactive";
	$('networkShareBoxHolderTab').style.top = "-24px";

	$('tweetShareBoxHolderTab').className = "shareTabInactive";
	$('tweetShareBoxHolderTab').style.top = "-24px";

	// Active tab
	$(type+'Tab').className = "shareTabActive";
	$(type+'Tab').style.top = "-23px";

	// Disable all continer
	$('emailShareBoxHolder').style.display = 'none';
	$('networkShareBoxHolder').style.display = 'none';
	$('tweetShareBoxHolder').style.display = 'none';

	// Active container
	$(type).style.display = 'block';

}

/**
 * Append socialmedian_url to text area
 */
var AddUserToReply = function(socialmedianUrl, sId){
	if ($('user_comment'+sId).value != "") {
	    $('user_comment'+sId).value = $('user_comment'+sId).value+"@"+socialmedianUrl+" ";
	} else {
		$('user_comment'+sId).value = "@"+socialmedianUrl+" ";
	}
	$('user_comment'+sId).focus();
}
/**
 *	SM 12/11/08:
 *	Function to update temp Vote For NC story
 *	@param vote: to update the total votes with either an increment or decrement 'temp'orarily,
 *	@param clear_after: when to clear the vote after the altest votign time
 *	@param story_id: voted story,
 *	@param nc_id: news circle to which the story belongs to, voted.
 *	@param from: place caled from. 0, indicates the panel and 1, indicates the news network page and event pages.
 */
var storyTempVote = function (vote, clear_after, story_id, nc_id, from){

	if(from==0){
		$('indi_'+nc_id+'_'+story_id).innerHTML = "<img src='"+S3_STATIC_ASSETS_PATH+"/images/active_scaffold/default/indicator.gif'>";
	}else{
		// This loading symbol for only temp vote on news network and evnet pages, while the votes are updated
		$('loading_icon_for_temp_vote_'+story_id).style.display='block';
	}
	var postParameters = "admin_story_vote="+vote+"&clear_after="+clear_after+"&story_id="+story_id+"&nc_id="+nc_id+"&from="+from;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: function(response){storyTempVoteCallback(response, story_id, from);},
		// Handle 404
		on404: storyTempVote404Callback,
		// Handle other errors
		onFailure: storyTempVoteFailureCallback
	}
	new Ajax.Request('/update-data-for-temp-vote', ajaxRequestOptions);
}
/*** storyTempVote callback function ***/
var storyTempVoteCallback = function (response, story_id, from){
	//eval the json object
	var response_data = response.responseText.evalJSON();
	//	Loading symbol is hidden once the temp votes are updated on news network and story pages.
	if(response_data.message == "success"){
		if(from==0){
			getNewsCircleStoriesDataForAdminVote(story_id);
		}else{
			$('loading_icon_for_temp_vote_'+story_id).style.display='none';
			alert('Temp vote updated successfully with '+response_data.total_votes[0]["admin_story_vote"]+' total votes, will be cleared after '+response_data.total_votes[0]["admin_vote_clear_after"]+' hours');
		}
	}else{
		alert("Sorry, there must be some problem with system.");
	}
}
/*** storyTempVote 404 callback function ***/
var storyTempVote404Callback = function (){
	alert("Sorry, its system problem.");
}
/*** storyTempVote failure callback function ***/
var storyTempVoteFailureCallback = function (){
	alert("Error, page is not found");
}

/**
 *	Narciss Singh 09/01/09:
 *	Function to update temp Vote For NC story
 *	@param vote: to update the total votes with either an increment or decrement 'temp'orarily,
 *	@param story_id: voted story,
 *	@param nc_id: news circle to which the story belongs to, voted.
 *	@param nc_created_by:news network created by user.
 */

function voteStoryfromNetworkPage(vote, nc_id, story_id, voted_by){
	if (vote == 'down_nn_creator' || vote == 'down_admin' ){
		if (confirm ('Do you really want to mark this story as irrelevant? This will delete the story from this News Network')){
			removeStoryfromNetworkPage(nc_id, story_id, voted_by);
		} else {
			return false;
		}
	} else {
		var post_parameters = "story_id="+story_id+"&news_circle_id="+nc_id+"&vote="+vote;
		var ajaxRequestOptions = {
			method: 'post',
			postBody: post_parameters,
			onSuccess: function(response){voteStoryfromNetworkPageCallback(response, nc_id, voted_by);},
			// Handle 404
			on404: voteStoryfromNetworkPage404Callback,
			// Handle other errors
			onFailure: voteStoryfromNetworkPageFailureCallback
		}
		new Ajax.Request('/vote-a-story-from-news-network', ajaxRequestOptions);
	}
}

// changing the document contents in response to the vote request
function voteStoryfromNetworkPageCallback(response, nc_id, voted_by){
	// Google Analytics - code to track 'vote a story' action
	tracAjaxFunctionalities('/news-network/vote_a_story_from_news_network');
	var json = response.responseText.evalJSON();
	var story_id = json.story_id;
	if (json.vote == 0) {
		if (voted_by == 'admin') {
			$('vote_up_story_admin_'+story_id).className = 'story-voteup-active-icon';
			$('vote_up_story_admin_'+story_id).title = 'Vote up';
		} else {
			$('vote_down_story_'+story_id).className= 'story-votedown-active-icon';
			$('vote_down_story_'+story_id).title= 'Mark as irrelevant';
		}
	} else if(json.vote == -1) {
		$('vote_down_story_'+story_id).className= 'story-votedown-inactive-icon';
		$('vote_down_story_'+story_id).title= 'Cancel vote';
	} else {
		$('vote_up_story_admin_'+story_id).className= 'story-voteup-inactive-icon';
		$('vote_up_story_admin_'+story_id).title= 'Cancel vote';
	}
}

/**
 * vote failure function
 */
var voteStoryfromNetworkPageFailureCallback = function (){
	check_click_before_response = 1;
	alert("Error on page");
};
/**
 * story voter error handler
 */
var voteStoryfromNetworkPage404Callback= function (){
	check_click_before_response  = 1;
	alert("Error page is not found");
};

/**
 *	Narciss Singh 12/01/09:
 *	Function to remove the story from the news network page when the news network creator or admin votes the story down
 *	@param story_id: voted story,
 *	@param nc_id: news circle to which the story belongs to, voted.
 */

function removeStoryfromNetworkPage(nc_id, story_id, voted_by){
	var post_parameters = "story_id="+story_id+"&news_circle_id="+nc_id;
		var ajaxRequestOptions = {
			method: 'post',
			postBody: post_parameters,
			onSuccess: removeStoryfromNetworkPageCallback,
			// Handle 404
			on404: removeStoryfromNetworkPage404Callback,
			// Handle other errors
			onFailure: removeStoryfromNetworkPageFailureCallback
		}
		new Ajax.Request('/remove-a-story-from-news-network', ajaxRequestOptions);
}

// changing the document contents in response to the vote request
var removeStoryfromNetworkPageCallback = function(response){
	// Google Analytics - code to track 'vote a story' action
	tracAjaxFunctionalities('/news-network/remove_a_story_from_news_network');
	var response_data = response.responseText.evalJSON();
	var story_id = response_data.story_id
	if(response_data.message == "success"){
		$('story_content_'+story_id).style.display = 'none';
	}
}

/**
 * vote callback function
 */
var removeStoryfromNetworkPageFailureCallback = function (){
	alert("Error on page");
};
/**
 * story remover error handler
 */
var removeStoryfromNetworkPage404Callback= function (){
	alert("Error page is not found");
};