/*
Javascript lib containing the functions to be used by NewsCircle
*/


/*
	when a keyword is added	using add keyword widget

	would be called internally by keyword adding script
*/

function suggestSourcesFor(news_circle_id, tag_ids){
	// form the request
	var tag_ids_for_post = '';
	tag_ids.each(function(s,i)
		{
			tag_ids_for_post += 'tag_ids[' + i + ']='+ s + '&';
		}
		);

	var post_parameters = 'news_circle_id='+news_circle_id+'&'+tag_ids_for_post.sub('&$', '');

	var ajaxRequestOptions = {
		method: 'post',
		postBody: post_parameters,
		onSuccess: updateSuggestedSourcesList,
		// Handle 404
		on404: suggestedSources404Callback,
		// Handle other errors
		onFailure: suggestedSourcesFailureCallback
	}
	new Ajax.Request('/news-circle/get-source-suggestions', ajaxRequestOptions);

}
// updating of list of sources
function updateSuggestedSourcesList(response){
	var response_data = response.responseText.evalJSON();
	var display_data = '';
	var prv_data = $('suggested_source_holder').innerHTML;
	response_data.each(
		function(feed, i){
			// if the source has already been suggested do not add it
			if($('suggested_source-'+feed.id) == null){

				display_data += '<div id="suggested_source-'+feed.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('+feed.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="'+feed.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\'">'+feed.title.truncate(50)+'</a>'+
										'</div>';
										if(feed.description != "") {
											display_data += '<div style="margin:0px;padding:0px;font-size:11px;color:#A4A4A4;overflow:hidden;">'+feed.description.truncate(120)+'</div>';
										}
				display_data +=   	'</div>'+
									'<br clear="all">'+
								'</div>';
			}
		}
	);
	refreshSnapshots();
	if(display_data != "") {
		$('suggested_source_success_message').innerHTML = "Here are some suggested sources based on the topics you have added. Click on 'Add', to add sources to this News Network.";
		$('suggested_source_success_message').style.display = "block";
	}
	$('suggested_source_holder').innerHTML = display_data + prv_data;
	$('suggested_source_holder').style.display = 'block';

}
function suggestedSources404Callback(){
//	console.log('May be routes are not enabled');
}
function suggestedSourcesFailureCallback(){
	// works only when firebug is enabled
//	console.log('Something went terribly wrong');
}
// should be adding all the suggested sources at once
function addAllSuggestedSources(){
	// collect all the suggested sources
	//use the _addSuggestedSource for each of them

	$$('#suggested_sources div a').each(function (s){_addSuggestedSource(s.href)});
	$$('#suggested_sources div').each(function(s){s.remove()});
}

// could later on be used for adding of group of sources
function addSuggestedSources(){

}

//handle adding of single sources
function addSuggestedSource(suggested_id){
	_addSuggestedSource($$('#suggested_source-'+suggested_id+' a').first().href);
	$('suggested_source-'+suggested_id).remove();
}

// refactored functions which is free of DOM information of sources and adds the source to existing sources.
function _addSuggestedSource(rss_enabled_uri){
	$('add_feeds_field').value = rss_enabled_uri;
	// call already existing function to add new source
	addNewFeedToNewsCircle();
	$('add_feeds_field').value ="";
}
// toggling the disply of sources
// also changing the icon of maximizer/minimizer, which is done through changing of class
function toggleSources(control){
	$('suggested_sources').toggle();
	$('suggested_sources-pager').toggle();
	if(control.hasClassName('maximizer')){
		control.removeClassName('maximizer');
		control.addClassName('minimizer');
	}
	else if(control.hasClassName('minimizer')){
		control.removeClassName('minimizer');
		control.addClassName('maximizer');
	}
}
function updatePagedSources(page_number, news_circle_id){
	var post_data = 'page='+page_number+'&news_circle_id='+news_circle_id;

	var ajaxRequestOptions = {
		method: 'post',
		postBody: post_data,
		onSuccess: updatePagedSuggestedSourcesList,
		// Handle 404
		on404: suggestedSources404Callback,
		// Handle other errors
		onFailure: suggestedSourcesFailureCallback
	}
	new Ajax.Request('/news-circle/get-source-suggestions-for-news_circle', ajaxRequestOptions);

}

// repetition of code, much of it taken from above updater, refactor for good design
function updatePagedSuggestedSourcesList(response){

	var response_data = response.responseText.evalJSON();

	var display_data = '';
	if (response_data.suggested_sources)
		response_data.suggested_sources.each(

		function(feed, i){
			// if the source has already been suggested do not add it
			if( $('suggested_source-'+feed.id) == null ){
				display_data += '<div id="suggested_source-' + feed.id + '" style="width:100%;clear:both;margin-bottom:1.1em;" > 	<div style="float:left" onclick="addSuggestedSource( ' + feed.id + ')" class="action-on-item"><!-- carrying event handler for adding this source to list of sources --> Add </div><div class="source-info" style="margin-left:4em;"> <a target="new" href="' + feed.url +'" > '+ feed.title.truncate(50) + '</a><br/> <div style="font-size:0.7em"> ' + (feed.description ? feed.description.truncate(120) : '') + '</div></br> </div> </div>';
			}
		}
		);
	$('suggested_sources').innerHTML = display_data;
	//is there a previous list of suggested sources
	if(!$('suggested-sources-pager-previous')){

		$('suggested_sources-pager').insert('<div id="suggested-sources-pager-previous" class="action-on-item" style="float:left" onclick="updatePagedSources('+ (parseInt(response_data.page) - 1) +', '+ response_data.news_circle_id +')"> &laquo Previous </div>');
	}
	else{
		$('suggested-sources-pager-previous').replace('<div id="suggested-sources-pager-previous" class="action-on-item" style="float:left" onclick="updatePagedSources('+ (parseInt(response_data.page) - 1) +', '+ response_data.news_circle_id +')"> &laquo Previous </div>');
	}
	if(response_data.previous){
		// create previous element if it does not already exists
		$('suggested-sources-pager-previous').show();
	}
	else{
		$('suggested-sources-pager-previous').hide();
	}
	//is there a next list of suggested sources
	if(!$('suggested-sources-pager-next')){

			$('suggested_sources-pager').insert('<div id="suggested-sources-pager-next" class="action-on-item" style="float:right" onclick="updatePagedSources('+ (parseInt(response_data.page) + 1) +', '+ response_data.news_circle_id +')"> More &raquo; </div>');
	}
	else{
		$('suggested-sources-pager-next').replace('<div id="suggested-sources-pager-next" class="action-on-item" style="float:right" onclick="updatePagedSources('+ (parseInt(response_data.page) + 1) +', '+ response_data.news_circle_id +')"> More &raquo; </div>');
	}


	if(response_data.more){
		$('suggested-sources-pager-next').show();
	}
	else{
		$('suggested-sources-pager-next').hide()
	}

}

//Check and change news network name.
var changeNewsNetName = function ( old_name, new_name){
//	$('remove_loading').style.display = 'block';
	if(new_name.strip() == ''){
		$('news_network_change_error_box').innerHTML = "News Network can't be empty.";
	}else if(old_name.strip() == new_name.strip()){
		$('news_network_change_error_box').innerHTML = "Please click on cancel if you don't want to change News Network name.";
	}else{
		var postParameters = "old_name=" + old_name.strip() + "&new_name=" + new_name.strip();
		var ajaxRequestOptions = {
			// Use POST
			method: 'post',
			// Send this lovely data
			postBody: postParameters,
			// Handle successful response
			onSuccess: changeNewsNetNameCallback,
			// Handle 404
			on404: changeNewsNetName404Callback,
			// Handle other errors
			onFailure: changeNewsNetNameFailureCallback
		}
		//alert(old_name + new_name);
		new Ajax.Request('/change-network-name', ajaxRequestOptions);
	}
}
var changeNewsNetNameCallback = function (response){
	//eval the json object
	var response_data = response.responseText.evalJSON();
	if(response_data.ok == true)
	{
		$('news_network_name_lbl').innerHTML = response_data.nn_name;
		$('news_network_name_div').style.display='block';
		$('news_network_change_name').style.display='none';
		$('news_network_change_error_box').innerHTML = "";
	}
	else{
		$('news_network_change_error_box').innerHTML = response_data.message;
	}
}
/**
 * removeUserFavoriteSource failure callback function
 */
var changeNewsNetNameFailureCallback = function (){
		alert("Sorry its not edited.");
}
/**
 * removeUserFavoriteSource 404 callback function
 */
var changeNewsNetName404Callback = function (){
	alert("Error page is not found");
}


var ignoreInvitedNetwork = function (nn_id){
	$('join_reject_loading'+nn_id).style.display = 'block';
	var postParameters = "network_id=" + nn_id;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: ignoreInvitedNetworkCallback,
		// Handle 404
		on404: ignoreInvitedNetwork404Callback,
		// Handle other errors
		onFailure: ignoreInvitedNetworkFailureCallback
	}
	//alert(old_name + new_name);
	new Ajax.Request('/reject-invited-network', ajaxRequestOptions);
}
var ignoreInvitedNetworkCallback = function (response){
	//eval the json object
	var response_data = response.responseText.evalJSON();
	if(response_data.ok == true)
	{
		$('nn_inviters_list_div'+response_data.nn_id).style.display = 'none';
	}
	else{
		alert("Error!!");
	}
}
/**
 * removeUserFavoriteSource failure callback function
 */
var ignoreInvitedNetworkFailureCallback = function (){
		alert("Error!!");
}
/**
 * removeUserFavoriteSource 404 callback function
 */
var ignoreInvitedNetwork404Callback = function (){
	alert("Error!!");
}





/* function to remove topics from a news circle */

function remove_topic(topic, str){
	// Check for location specific topic
	var proceed = 1;
	if(str == 'location') {
		if(!confirm("This News Network is location specific. If you remove this topic, then this News Network will no longer be location specific News Network.")) {
			proceed = 0;
		}
	}
	if(proceed == 1) {
	    // extract news circle identifier and topic identifier and form the post query data
	    // the format of id for deleter controls are news_circle_id-topic_deleter-tag_id
	    var id_components = topic.id.split('-');
	    var post_data = 'news_network_id='+ id_components.first() +'&topic_id='+id_components.last();
	    var ajaxRequestOptions = {
		method: 'post',
		postBody: post_data,
		onSuccess: update_topic_list,
		// Handle 404
		on404: suggestedSourcesFailureCallback,
		// Handle other errors
		onFailure: suggestedSourcesFailureCallback
	    }
	    new Ajax.Request('/remove-topic-from-news-network', ajaxRequestOptions);
	}
}

function update_topic_list(response){
    var data =  response.responseText.evalJSON();
    if(data.error == 1){
    	alert(data.message);
    }
    // Google Analytics - code to track remove topic from news network action
	tracAjaxFunctionalities('/remove-topic-from-news-network');
    var parent = $(data.news_network_id+'-topic-'+data.topic_id).remove();

	/**
	 * @author jeevan
	 * @date 16/3/09
	 * While creating a new news network, If I delete the topic from right panel, the topic is not getting deleted from left panel
	 */    
	try {
    	var divId = data.news_network_id+"-topic-left-"+data.topic_id;
		// deleted the topic from left side
		var relatedTopicMainDiv = document.getElementById('nnRelatedTopicsDisplayBox');
		var relatedTopics = document.getElementById(divId);
		relatedTopicMainDiv.removeChild(relatedTopics);
	} catch (e) {}
    // remove location specic topic from the top
    try {
    	$('location_specific_topic_display').innerHTML = '<div align="left" style="padding:5px 0px 5px 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('+data.news_network_id+',\'\',1,\'\')" style="color:#757575;font-weight:bold;">Yes</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="javascript:void(0)" onclick="notLocationSpecific('+data.news_network_id+')" 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>';
    } catch(e){}
}
function remove_feed(feed){
    // extract news circle identifier and topic identifier and form the post query data
    // the format of id for deleter controls are news_circle_id-topic_deleter-tag_id
    var id_components = feed.id.split('-');
    var post_data = 'news_network_id='+ id_components.first() +'&feed_id='+id_components.last();
    var ajaxRequestOptions = {
	method: 'post',
	postBody: post_data,
	onSuccess: update_feed_list,
	// Handle 404
	on404: suggestedSourcesFailureCallback,
	// Handle other errors
	onFailure: suggestedSourcesFailureCallback
    }
    new Ajax.Request('/remove-source-from-news-network', ajaxRequestOptions);

}

// removes the feed container
function update_feed_list(response){
    var data =  response.responseText.evalJSON();
    if(data.error == 1){
    	alert(data.message);
    }
    // Google Analytics - code to track remove source from news network action
	tracAjaxFunctionalities('/remove-source-from-news-network');
    var parent = $(data.news_network_id+'-feed-'+data.feed_id).remove();
}



var offsetxpoint=-60; //Customize x offset of tooltip
var offsetypoint=20; //Customize y offset of tooltip
var ie=document.all;
var ns6=document.getElementById && !document.all;
var enabletip=false;
var tipobj = '';
function definetipobj(){
if (ie||ns6){
	tipobj = document.all ? document.all["scoretooltip"] : document.getElementById	? document.getElementById("scoretooltip") : "";
}
}
function ietruebody(){
return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
}

function ddrivetip(thetext, thecolor, thewidth){
if (ns6||ie){
if (typeof thewidth!="undefined") tipobj.style.width=thewidth+"px";
if (typeof thecolor!="undefined" && thecolor!="") tipobj.style.backgroundColor=thecolor;
tipobj.innerHTML=thetext;
enabletip=true;
return false;
}
}

function positiontip(e){
if (enabletip){
var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
//Find out how close the mouse is to the corner of the window
var rightedge=ie&&!window.opera? ietruebody().clientWidth-event.clientX-offsetxpoint : window.innerWidth-e.clientX-offsetxpoint-20
var bottomedge=ie&&!window.opera? ietruebody().clientHeight-event.clientY-offsetypoint : window.innerHeight-e.clientY-offsetypoint-20

var leftedge=(offsetxpoint<0)? offsetxpoint*(-1) : -1000

//if the horizontal distance isn't enough to accomodate the width of the context menu
if (rightedge<tipobj.offsetWidth)
//move the horizontal position of the menu to the left by it's width
tipobj.style.left=ie? ietruebody().scrollLeft+event.clientX-tipobj.offsetWidth+"px" : window.pageXOffset+e.clientX-tipobj.offsetWidth+"px"
else if (curX<leftedge)
tipobj.style.left="5px"
else
//position the horizontal position of the menu where the mouse is positioned
tipobj.style.left=curX+offsetxpoint+"px"

//same concept with the vertical position
if (bottomedge<tipobj.offsetHeight)
tipobj.style.top=ie? ietruebody().scrollTop+event.clientY-tipobj.offsetHeight-offsetypoint+"px" : window.pageYOffset+e.clientY-tipobj.offsetHeight-offsetypoint+"px"
else
tipobj.style.top=curY+offsetypoint+"px"
tipobj.style.visibility="visible"
}
}

function hideddrivetip(){
if (ns6||ie){
enabletip=false
tipobj.style.visibility="hidden"
tipobj.style.left="-1000px"
tipobj.style.backgroundColor=''
tipobj.style.width=''
}
}

document.onmousemove=positiontip


/**
* Added by: Ajay Agrawal
*	Function update the primary/ location topics
*/
/**
 * KD 14/11/08:
 *
 * Used to edit the primary/location topics
 */
var updateTopics = function (topicName, topicType, nnId, tag_id){
	/**
	* Added the check for primary topic. Primary topic can be max 64 chars long.
	*/
	if(topicType=="primary"){
		if(topicName.strip().length > 64){
			$("edit_primarytopic_message").innerHTML = "Primary topic can be max 64 characters long.";
			$("edit_primarytopic_message").style.display = "block";
			return false;
		}
	}
	if(topicName.strip().stripTags() == ''){
		$("edit_primarytopic_message").innerHTML = "Primary topic can't be blank.";
		$("edit_primarytopic_message").style.display = "block";
		return false;
	}else if(topicName.strip().stripTags().match(/[,|:|"|'|\\|*|~|!|@|$|%|^|&|+|=|(|)|\[|\]|{|}|;|?|<|>|`|\/]/)){
		/**
		 * @author jeevan
		 * @date 3/3/09
		 * when ever is topic is updated. check the updated topic for special characters.
		 * if yes display error message.
		 */
		$("edit_primarytopic_message").innerHTML = "Special characters not allowed.";
		$("edit_primarytopic_message").style.display = "block";
		return false;
	}else{
		var postParameters = "nn_id="+nnId+"&tag_type="+topicType+"&tag_name="+topicName;
	}

	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this data
		postBody: postParameters,
		// Handle successful response
		onSuccess: function(response) {try{updateTopicsCallback(response, tag_id, topicType);}catch(e){alert(e)}},
		// Handle 404
		on404: updateTopics404Callback,
		// Handle other errors
		onFailure: updateTopicsFailureCallback
	}
	new Ajax.Request('/edit-topics', ajaxRequestOptions);
}
/**
 * displays the stories on the news network wizard success callback function
 */
function updateTopicsCallback(response, tag_id, tag_type){
	var response_data = response.responseText.evalJSON();
	if(response_data == "") {
		alert("No story found");
	} else {
		tagId = response_data.tag_id;
		paramLink = response_data.tag_paramlink;
		tagName = response_data.tag_name;
			try{
			$("edit_primarytopic_message").innerHTML = tag_type.capitalize()+" topic updated successfully.";
			$("edit_primarytopic_message").style.display = "block";
			$("nn"+tag_type.capitalize()+"Topic").style.display="block";
			$("nn"+tag_type.capitalize()+"TopicEditBox").style.display="block";
			$("edit"+tag_type.capitalize()+"Topic").style.display="none";
			$(tag_type+"_"+tag_id).innerHTML = '<a href="/topic-stories/'+tagId+'/'+paramLink+'" style="color:#2463A8;text-decoration:none;" onmouseover="this.style.textDecoration=\"underline\"" onmouseout="this.style.textDecoration=\"none\"">'+$('newsNetwork'+tag_type.capitalize()+'Topic').value+'</a>';
			$(tag_type+"_"+tag_id).style.display="block";
			}catch(e){alert(e);}
	}
}
/**
 * displays the stories on the news network wizard failure callback function
 */
var updateTopicsFailureCallback = function (){
	alert("Error on page");
}
/**
 * displays the stories on the news network wizard 404 callback function
 */
var updateTopics404Callback= function (){
	alert("Error page is not found");
}


