var primaryTopicExample = 'e.g. iphone or Australian Olympic Team\n or Britney Spears';
var locationExample = ' e.g. New York';
var alsoKnownAsExample = ' e.g. NYC, NY, New York City';
var relatedSourcesExample = 'Enter a source name(like "BBC") \n or an RSS feed url';
var newsNetworkDescription = 'Enter a brief description for \n your News Network';
var newsNetworkWelcome = 'Welcome to the [name] News Network.\nWe can use this website to track, share,\nand discuss news from many sources.\n\nHave you tried clipping a story yet?';
var NN_PRIMARY_TOPIC = "";
var relatedTopicsExample = 'Add keywords';
var USER_RELATED_TOPICS = [];
var SUGGESTED_TOPICS_MAX_LENGTH = 8;
var SUGGESTED_TOPIC_PAGE = 0;
var SUGGESTED_TOPICS = [];
var FIRST_REQUEST_FOR_SUGGESTED_TOPICS = 0;
var NEWS_NETWORK_ID = '';
var USER_RELATED_SOURCES = [];
var OLD_RELATED_TOPICS_ARRAY = [];
var POPULAR_SOURCES_ARRAY = new Array();
var POPULAR_SOURCES_MAX_LENGTH = 8;
var POPULAR_SOURCE_PAGE = 0;
var CURRENT_PAGE = 'getStarted';
var RECOMMENDED_SOURCES_ARRAY = new Array();
var RECOMMENDED_SOURCES_MAX_LENGTH = 8;
var RECOMMENDED_SOURCE_PAGE = 0;
var NEWS_NETWORK_EXISTS = 0;
var NETWORK_TOPICS = [];
// check whether the page is load for crate news network or edit news network
var NETWORK_PAGE = '0';
// global variable for displaying and hideing location
var isOpen = 0;
// set when user editing the news network information
var NETWORK_EDIT = 0;
// JSON array for edit news network wizard
var NEWS_NETWORK_TAGS_AND_FEEDS = new Array();
var NEWS_NETWORK_HEADING = new Array();
//
var ADD_NEWS_NETWORK_WIZARD_HEADING = eval({"getStarted":"Let's create your News Network!","primaryTopics":"Alright, let's setup your public news network", "relatedTopics":"Ok, now we're getting somewhere! ", "relatedSources":"Almost done ... now we just need to choose some sources", "nnSetting":"And now for the finishing touches..."});
var EDIT_NEWS_NETWORK_WIZARD_HEADING = eval({"getStarted":"","primaryTopics":"Edit Primary Topic", "relatedTopics":"Edit Topics", "relatedSources":"Edit Sources", "nnSetting":"Finishing Touches"});
/**
 * Show user example on focus
 */
function showUserExample(val, obj_id, default_msg) {
    // 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 == eval(''+default_msg+';')) {
		$(obj_id).value = "";
	} else {
		$(obj_id).value = org_des;
	}
}

/**
*	@author Ajay Agrawal
*	@date 25 July, 2008
*	Function opens the right side menu according to page
*/

function showHideRightSideWidget(){
	switch(CURRENT_PAGE){
		case "getStarted":
				minMaxRightSideBoxes('topic', 'min');
				minMaxRightSideBoxes('source', 'min');
				break;
		case "primaryTopics":
				minMaxRightSideBoxes('topic', 'min');
				minMaxRightSideBoxes('source', 'min');
				break;
		case "relatedTopics":
				// maximize the primaryTopics box
				minMaxRightSideBoxes('topic','max');
				minMaxRightSideBoxes('source','min');
				break;
		case "relatedSources":
				// maximize the relatedSources box
				minMaxRightSideBoxes('source','max');
				break;
		case "nnSetting":
				break;
	}
}


/**
* @author Ajay Agraswal
* @Date July 17, 2008
* Create the news network
* Validate the primary topics and added it in global variable and database
* Added location on database
*/

function addPrimaryTopics(){
	$('primaryTopicErrorMsgBox').style.display = "none";
	/**
	* KD 17/11/08
	* Added the check for primary topic can be max 64 chars long.
	*/
	if($('primaryTopic').value.strip().length > 64){
		$("primaryTopicErrorMsgBox").innerHTML = "Primary topic can be max 64 characters long.";
		$("primaryTopicErrorMsgBox").style.display = "block";
		CURRENT_PAGE = 'primaryTopics';
		return false;
	}
	/**
	* @author jeevan
	* @date 3/3/09
	* check location and alsoknownas for special characters. if yes display error message
	*/
	if($('nnLocation').value.match(/[,|:|"|'|\\|*|~|!|@|$|%|^|&|+|=|(|)|\[|\]|{|}|;|?|<|>|`|\/]/)){
		$("primaryTopicErrorMsgBox").innerHTML = "Special characters not allowed";
		$("primaryTopicErrorMsgBox").style.display = "block";
		CURRENT_PAGE = 'primaryTopics';
		return false;
	}
	if($('nnKnownAs').value.match(/[:|"|'|\\|*|~|!|@|$|%|^|&|+|=|(|)|\[|\]|{|}|;|?|<|>|`|\/]/)){
		$("primaryTopicErrorMsgBox").innerHTML = "Special characters not allowed";
		$("primaryTopicErrorMsgBox").style.display = "block";
		CURRENT_PAGE = 'primaryTopics';
		return false;
	}
	if($('primaryTopic').value == primaryTopicExample || $('primaryTopic').value.strip() ==  ''){
		$('primaryTopicErrorMsgBox').innerHTML = 'Please enter the primary topic';
		$('primaryTopicErrorMsgBox').style.display = "block";
		CURRENT_PAGE = 'primaryTopics';
		return false;
	}else if($('primaryTopic').value.match(/[,|:|"|'|\\|*|~|!|@|$|%|^|&|+|=|(|)|\[|\]|{|}|;|?|<|>|`|\/]/)){
		/**
		 * @author jeevan
		 * @date 3/3/09
		 * check primary topic for special characters. if yes display error message
		 */
		$('primaryTopicErrorMsgBox').innerHTML = 'Special characters not allowed.';
		$('primaryTopicErrorMsgBox').style.display = "block";
		CURRENT_PAGE = 'primaryTopics';
		return false;
	}else{
		CURRENT_PAGE = 'relatedTopics';
		showPrimaryTopic();
		// set all other global variables
		SUGGESTED_TOPIC_PAGE=0;
		FIRST_REQUEST_FOR_SUGGESTED_TOPICS = 1;
		searchRelatedTopics();
	}
	var location = "";
	var knownAs = "";
	if($('nnLocation').value != locationExample){
		location = $('nnLocation').value;
	}
	if($('nnKnownAs').value != alsoKnownAsExample){
		knownAs = $('nnKnownAs').value;
	}
	var postParameters = "primaryTopic="+encodeURIComponent(NN_PRIMARY_TOPIC)+"&location="+encodeURIComponent(location)+"&known_as="+encodeURIComponent(knownAs)+"&nn_id="+NEWS_NETWORK_ID+"&network_edit="+NETWORK_EDIT+"&serach_reco_source=1";
	recommendedSourcesRequestSent = 0;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: addPrimaryTopicsCallback,
		// Handle 404
		on404: addPrimaryTopics404Callback,
		// Handle other errors
		onFailure: addPrimaryTopicsFailureCallback
	}
	new Ajax.Request('/create-nn/', ajaxRequestOptions);
}

/**
 * relateds topics success callback function
 */
var addPrimaryTopicsCallback = 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
		$('primaryTopicErrorMsgBox').innerHTML = response_data.message;
		$('primaryTopicErrorMsgBox').style.display = "block";
		return false;
	} else {
		if(response_data.nn_id != null){
			NEWS_NETWORK_ID = response_data.nn_id;
			NEWS_NETWORK_EXISTS = response_data.nn_exists;
		}
	}
}

/**
 * Related topics failure callback function
 */
var addPrimaryTopicsFailureCallback = function (){
	alert("Error on page");
}
/**
 * Related topics 404 callback function
 */
var addPrimaryTopics404Callback= function (){
	alert("Error page is not found");
}
/**
* @author Ajay Agraswal
* @Date July 17, 2008
* Validate the primary topics and added it in global variable
*/
function showHelpBox(showBox){
	if(showBox == 'relatedTopics'){
		Effect.toggle('nnRelatedTopicsHelpBox');
		//$('nnRelatedTopicsHelpBox').style.display = 'block';
	}else if(showBox == 'relatedSources'){
		Effect.toggle('nnRelatedSourcesHelpBox');
	}else if(showBox == 'socialmedianSearch'){
		Effect.toggle('nnSocialmedianChooseNewsHelpBox');
	}else if(showBox == 'errorHelpBox'){
		Effect.toggle('nnSettingErrorHelpBox');
	}
}

/**
* @author Ajay Agraswal
* @Date July 18, 2008
* Validate the related topics and added it in global array
*/
function addedUserRelatedTopics(topicValue){
	$('nnRelatedTopicsErrorMsgBox').style.display = 'none';
	//function defined in application.js file
	addNewTagToNewsCircle(topicValue);
	/**
	 * @author jeevan
	 * @date 4-03-09
	 * check for special characters in the entered topic.
	 * if the entered topic does not contain any of the special characters mentioned
	 * below. then only search for related topics.
	 *
	 */
	if(!(topicValue.match(/[:|_|"|'|\\|*|~|!|@|$|%|^|&|+|=|(|)|\[|\]|{|}|;|?|<|>|`|\/]/))){
		if(topicValue.indexOf(',', 0) == -1){
			USER_RELATED_TOPICS.push(topicValue);
		}else{
			var userAddedTopics = topicValue.split(',');
			for(i=0;i<userAddedTopics.length;i++){
				USER_RELATED_TOPICS.push(userAddedTopics[i]);
			}
		}
		$('nnRelatedTopics').value='';
		FIRST_REQUEST_FOR_SUGGESTED_TOPICS = 0;
		searchRelatedTopics();
	}
}

/**
* @author Ajay Agraswal
* @Date July 18, 2008
* Remove the user added topics
*/
function deleteUserAddedRelatedTopics(obj){
	remove_topic(obj);
	var id_components = obj.id.split('-');
	var divId = id_components.first() + "-topic-left-" + id_components.last();
	// deleted the topic from left side
	var relatedTopicMainDiv = document.getElementById('nnRelatedTopicsDisplayBox');
	var relatedTopics = document.getElementById(divId);
	relatedTopicMainDiv.removeChild(relatedTopics);
}

/**
* @author Ajay Agraswal
* @Date July 18, 2008
* Display and hide the select location box
*/
function showHideLocation(){
	if(isOpen == 0){
		isOpen=1;$('nnLocationIcon').style.visibility='visible';
		$('nnLocationText').style.visibility='visible';
		$('nnLocationInputBox').style.display='block';
	}else{
		$('nnLocationIcon').style.visibility='hidden';
		$('nnLocationText').style.visibility='hidden';
		$('nnLocationInputBox').style.display='none';
		isOpen=0;
	}
}

/**
* @author Ajay Agraswal
* @Date July 18, 2008
* validate the location and show/hide the box
*/
function ValidateLocation(){
	var val = $('nnLocation').value;
	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 != locationExample && val != ''){
		isOpen=1;
		$('nnLocationIcon').style.visibility='visible';
		$('nnLocationText').style.visibility='visible';
		$('nnLocationInputBox').style.display='block';
	}else{
		$('nnLocationIcon').style.visibility='hidden';
		$('nnLocationText').style.visibility='hidden';
		$('nnLocationInputBox').style.display='none';
		isOpen=0;
	}
}


/**
* @author Ajay Agraswal
* @Date July 18, 2008
* Fetch the related topics and display it on Related Topic Widget
*/
var searchRelatedTopics = function (){
	var postParameters = "topics='"
	var topics = NN_PRIMARY_TOPIC+"'";
	// added the related topic added by users
	try{
		if(USER_RELATED_TOPICS.length > 0 && USER_RELATED_TOPICS.length != undefined){
			if(USER_RELATED_TOPICS.length == 1){
				topics += ",'"+USER_RELATED_TOPICS[0]+"'";
			}else{
				topics += ",'"+USER_RELATED_TOPICS.join("','")+"'";
			}
		}
	}catch(e){}
	postParameters += encodeURIComponent(topics);
	// show the loading icon
	$('suggestedSourceLoadingDiv').style.display = 'block';
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: searchRelatedTopicsCallback,
		// Handle 404
		on404: searchRelatedTopics404Callback,
		// Handle other errors
		onFailure: searchRelatedTopicsFailureCallback
	}
	new Ajax.Request('/search-related-topics/', ajaxRequestOptions);
}
/**
 * relateds topics success callback function
 */
var searchRelatedTopicsCallback = function (response){
	// hide the loading icon
	$('suggestedSourceLoadingDiv').style.display = 'none';
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	//check if there is an error
	if (response_data.error == 1) {
		//alert the error
		$('searchedRelatedTopicsBody').innerHTML = response_data.message;
	} else {
		if(response_data.nn_id != null){
			NEWS_NETWORK_ID = response_data.nn_id;
		}
		var suggestedTopics = response_data.message;
		SUGGESTED_TOPICS = [];
		if(suggestedTopics.length < 1){ return false; }
		for(i=0;i<suggestedTopics.length;i++){
			SUGGESTED_TOPICS.push(suggestedTopics[i]['name']);
		}
		if($('searchedRelatedTopicsBody').innerHTML.search("We haven't been") != -1 || SUGGESTED_TOPICS.length < SUGGESTED_TOPICS_MAX_LENGTH || FIRST_REQUEST_FOR_SUGGESTED_TOPICS == 1){
			// clear the previously added topics
			$('searchedRelatedTopicsBody').innerHTML = "";
			showSuggestedTopics();
		}else{
			$('showNewSuggestedTopics').style.visibility = 'visible';
		}
	}
}

/**
 * Related topics failure callback function
 */
var searchRelatedTopicsFailureCallback = function (){
	// hide the loading icon
	$('suggestedSourceLoadingDiv').style.display = 'none';
	alert("Error on page");
}
/**
 * Related topics 404 callback function
 */
var searchRelatedTopics404Callback= function (){
	// hide the loading icon
	$('suggestedSourceLoadingDiv').style.display = 'none';
	alert("Error page is not found");
}


function showSuggestedTopics(){
	var suggestedStoryInnerhtml = "<div style='padding:8px 0px 0px 17px;margin:0px;font-family:Arial;font-weight:normal;font-size:13px;color:#223A66'>";
	var startPage = SUGGESTED_TOPICS_MAX_LENGTH * SUGGESTED_TOPIC_PAGE;
	var end = Math.min(startPage+SUGGESTED_TOPICS_MAX_LENGTH,SUGGESTED_TOPICS.length);
	for(i=startPage;i<end;i++){
		suggestedStoryInnerhtml += "<div style='width:15px;float:left;padding:0px;margin:0px;font-family:Arial;font-weight:normal;cursor:pointer'>"+
										"<span class='nn-add-small-button' onclick='javascript: addedUserRelatedTopics(\""+SUGGESTED_TOPICS[i]+"\"); removeFromArray(\""+SUGGESTED_TOPICS[i]+"\"); return false;'></span>"+
									"</div>"+
									"<div style='width:175px;float:left;padding:0px 0px 0px 12px;margin:0px;font-family:Arial;font-weight:normal;'>"+SUGGESTED_TOPICS[i]+"</div>"+
									"<br clear='all'/>";
	}
	suggestedStoryInnerhtml += "</div>";
	$('searchedRelatedTopicsBody').innerHTML = suggestedStoryInnerhtml;
	if(SUGGESTED_TOPICS.length > SUGGESTED_TOPICS_MAX_LENGTH){
		var paginationInnerhtml = "<div align='right' style='padding:0px 0px 0px 170px;margin:0px;'>";
		if(SUGGESTED_TOPIC_PAGE == 0){
			paginationInnerhtml += "<div style='float:left;padding:0px 0px 0px 12px;margin:0px;' onclick='javascript: return false;'><span class='nn-navigation-left-disabled-small-button'></span></div>";
		}else{
			paginationInnerhtml += "<div style='float:left;padding:0px 0px 0px 12px;margin:0px;cursor:pointer' onclick='javascript: SUGGESTED_TOPIC_PAGE--;showSuggestedTopics();return false;'><span class='nn-navigation-left-small-button'></span></div>";
		}
		if(end < SUGGESTED_TOPICS.length){
			paginationInnerhtml += "<div style='float:left;padding:0px 0px 0px 12px;margin:0px;cursor:pointer' onclick='javascript: SUGGESTED_TOPIC_PAGE++;showSuggestedTopics();return false;'><span class='nn-navigation-right-small-button'></span></div>";
		}else{
			paginationInnerhtml += "<div style='float:left;padding:0px 0px 0px 12px;margin:0px;' onclick='javascript: return false;'><span class='nn-navigation-right-disabled-small-button'></span></div>";
		}
		paginationInnerhtml += "<br clear='all'/>"+
                                     "</div>";
         new Insertion.Bottom('searchedRelatedTopicsBody',paginationInnerhtml);
	}
}

/**
* @author Ajay Agraswal
* @Date July 18, 2008
* Added the related topics on the news network
*/
var addRelatedTopicsOnNewsNetwork = function (){
	/**
	*	Update the primry related topic message box
	*/
	var primaryRelatedTopicMsgBox = "<span class='big-blue-font'>"+NN_PRIMARY_TOPIC;
	var relatedTopics = '';
	for(i=0;i<USER_RELATED_TOPICS.length;i++){
		if(i == 0){
			relatedTopics = "</span><span class='big-grey-font'> with related topics </span>"+USER_RELATED_TOPICS[i];
		}else if((i+1) == USER_RELATED_TOPICS.length){
			relatedTopics += "<span class='big-grey-font'>, and </span>"+USER_RELATED_TOPICS[i]
		}else{
			relatedTopics += ", "+USER_RELATED_TOPICS[i]
		}
	}
	primaryRelatedTopicMsgBox += "<span class='big-blue-font'>"+relatedTopics+"</span>";
	$('primaryRelatedMsgBox').innerHTML = primaryRelatedTopicMsgBox;
	/**
	*	create the post parameter for AJAX request
	*/
	if(USER_RELATED_TOPICS.length > 0){
		var postParameters = "related_topics="+USER_RELATED_TOPICS.join(',')+"&nn_id="+NEWS_NETWORK_ID;
	}else{
		//alert("Please add some topics");
		return false;
	}
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this lovely data
		postBody: postParameters,
		// Handle successful response
		onSuccess: addRelatedTopicsOnNewsNetworkCallback,
		// Handle 404
		on404: addRelatedTopicsOnNewsNetwork404Callback,
		// Handle other errors
		onFailure: addRelatedTopicsOnNewsNetworkFailureCallback
	}
	new Ajax.Request('/add-related-topics/', ajaxRequestOptions);
}
/**
 * Add topics to news netword success callback function
 */
var addRelatedTopicsOnNewsNetworkCallback = 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
		$('searchedRelatedSourcesBody').innerHTML = response_data.message;
	} else {
		for(i=0;i<USER_RELATED_TOPICS.length;i++){
			OLD_RELATED_TOPICS_ARRAY[i] = USER_RELATED_TOPICS[i];
		}
	}
}

/**
 * Add topics to news netword failure callback function
 */
var addRelatedTopicsOnNewsNetwork404Callback = function (){
	alert("Error on page");
}
/**
 * Add topics to news netword 404 callback function
 */
var addRelatedTopicsOnNewsNetworkFailureCallback= function (){
	alert("Error page is not found");
}



/**
* @author Ajay Agraswal
* @Date July 18, 2008
* Validate the related topics and added it in global array
*/
function addedUserRelatedSources(sourceValue){
	try{
		$('nnRelatedSourcesErrorMsgBox').style.visiblity = 'hidden';
	}catch(e){}
	var sourceName = sourceValue.strip().stripTags();
	if(sourceName == ""){
		$('nnRelatedSourcesErrorMsgBox').innerHTML = "Please enter a source.";
		$('nnRelatedSourcesErrorMsgBox').style.visiblity = 'visible';
		return false;
	}
	if(NETWORK_PAGE == 0){
		addNewFeed(sourceName);
	}else{
		//$('add_feeds_field').value = sourceName;
		_addSuggestedSource(sourceName);
	}
}

function searchRelatedSources(){
return false;
}

/**
*	Function remove the element form the suggested topic box
*/
function removeFromArray(topicName){
	var sourceIndex = SUGGESTED_TOPICS.indexOf(topicName);
	SUGGESTED_TOPICS.splice(sourceIndex, 1);
	showSuggestedTopics();
}

/**
 * Add new feed to news network
 */
var addNewFeed = function (rssFeed){
	$('nnRelatedSourcesErrorMsgBox').style.display = "none";
	if (rssFeed == '' || rssFeed == relatedSourcesExample){
		return false;
	}else{
		// set the post variables
		var postParameters = "rssfeed[news_circle_id]="+NEWS_NETWORK_ID+"&rssfeed[rss]="+rssFeed;
		try{
			$('addSourcesLoadingIcon').style.display = "block";
		}catch(e){}
		var ajaxRequestOptions = {
			// Use POST
			method: 'post',
			// Send this data
			postBody: postParameters,
			// Handle successful response
			onSuccess: addNewFeedCallback,
			// Handle 404
			on404: addNewFeed404Callback,
			// Handle other errors
			onFailure: addNewFeedFailureCallback
		}
		new Ajax.Request('/add-feeds', ajaxRequestOptions);
	}
}
/**
 * Add new feed to news network success callback function
 */
var addNewFeedCallback = function (response){
	$('addSourcesLoadingIcon').style.display = "none";
	$('nnRelatedSources').value = '';
	$('add_feeds_field').value = '';
	//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) {
		$('nnRelatedSourcesErrorMsgBox').innerHTML = response_data.message;
		$('nnRelatedSourcesErrorMsgBox').style.visiblity = 'visible';
	} else {
		var feedReponse = response_data.info[0];
		var insertUserSource = disaplaySourcesOnLeftSide(feedReponse.id, feedReponse.name);
		try{
			// insert the sources on left hand side
			new Insertion.Bottom('nnRelatedSourcesDisplayBox', insertUserSource.replace('[pannel]','left'));
		}catch(e){}
		// insert the sources on right hans side
		//new Insertion.Bottom('newly_added_feeds', insertUserSource.replace('[pannel]','right'));
		show_new_feeds = showUserAddedSources(feedReponse['nc_id'], feedReponse['id'], feedReponse['ncf_id'], feedReponse['name'], feedReponse['added_by'], feedReponse['added_on']);
		new Insertion.Before("newly_added_feeds", show_new_feeds);
		$('newly_added_feeds').style.display = 'block';
	}
}
/**
 * Add new feed to news network failure callback function
 */
var addNewFeedFailureCallback = function (){
	alert("Error on page");
	$("addSourcesLoadingIcon").style.display = "none";
}
/**
 * Add new feed to news network 404 callback function
 */
var addNewFeed404Callback= function (){
	alert("Error page is not found");
	$("addSourcesLoadingIcon").style.display = "none";
}

/**
*	@author Ajay Agrawal
*	@Date 24 July, 2008
*	searches the popular sources on the basis of topic added.
*/
var getPopularSources = function (){
	try{
		/**
		*	Update the primry related topic message box
		*	Added By ajay
		*	Nov 06, 2008
		*/
		/**
		 *	@author jeevan
		 *	@date 16/3/2009
		 *	The topic having special characters are coming in percent encoded format.
		 *  so we are unescaping them to convert into proper format.
		 *
		 */
		var primaryRelatedTopicMsgBox = "<span class='big-blue-font'>"+unescape(NN_PRIMARY_TOPIC);
		var relatedTopics = '';
		for(i=0;i<USER_RELATED_TOPICS.length;i++){
			if(i == 0){
				relatedTopics = "</span><span class='big-grey-font'> with related topics </span>"+unescape(USER_RELATED_TOPICS[i]);
			}else if((i+1) == USER_RELATED_TOPICS.length){
				relatedTopics += "<span class='big-grey-font'>, and </span>"+unescape(USER_RELATED_TOPICS[i])
			}else{
				relatedTopics += ", "+unescape(USER_RELATED_TOPICS[i])
			}
		}
		primaryRelatedTopicMsgBox += "<span class='big-blue-font'>"+relatedTopics+"</span>";
		$('primaryRelatedMsgBox').innerHTML = primaryRelatedTopicMsgBox;
	}catch(e){}
	$('nnPopularSources').style.color = "#000";
	$('nnRecommendedSources').style.color = "#626262";
	if(POPULAR_SOURCES_ARRAY.length > 0){
		showPopularSources();
		return false;
	}
	j = 0;
	if(NETWORK_TOPICS.length > 0){
		USER_RELATED_TOPICS = NETWORK_TOPICS;
	}
	var userTopics = "'";
	if(NN_PRIMARY_TOPIC != ''){
		userTopics += NN_PRIMARY_TOPIC;
	}
	var maxTopic = Math.min(10, (USER_RELATED_TOPICS.length+SUGGESTED_TOPICS.length));
	for(i=0;i<maxTopic;i++){
		if(USER_RELATED_TOPICS.length > i){
			userTopics += "','"+escape(USER_RELATED_TOPICS[i]);
		}else{
			if(SUGGESTED_TOPICS[j] != undefined){
				userTopics += "','"+escape(SUGGESTED_TOPICS[j]);
				j++;
			}
		}
	}
	// set the post variables
	var postParameters = "nn_id="+NEWS_NETWORK_ID+"&user_topics="+userTopics+"'&network_page="+(NETWORK_EDIT == 1 ? NETWORK_EDIT : NETWORK_PAGE);
	try{
		$('addSourcesLoadingIcon').style.display = "block";
	}catch(e){}
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this data
		postBody: postParameters,
		// Handle successful response
		onSuccess: getPopularSourcesCallback,
		// Handle 404
		on404: getPopularSources404Callback,
		// Handle other errors
		onFailure: getPopularSourcesFailureCallback
	}
	new Ajax.Request('/popular-sources', ajaxRequestOptions);
}

/**
 * get the popular sources success callback function
 */
var getPopularSourcesCallback = function (response){
	try{
		$('addSourcesLoadingIcon').style.display = "none";
	}catch(e){}
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	if(response_data.error == 1) {
		//error message
	} else {
		var popularSources = response_data.message;
		for(i=0;i<popularSources.length;i++){
			POPULAR_SOURCES_ARRAY[i] = popularSources[i];
		}
		showPopularSources();
	}
}
/**
 * get the popular sources failure callback function
 */
var getPopularSourcesFailureCallback = function (){
	alert("Error on page");
	$("addSourcesLoadingIcon").style.display = "none";
}
/**
 * get the popular sources 404 callback function
 */
var getPopularSources404Callback= function (){
	alert("Error page is not found");
	$("addSourcesLoadingIcon").style.display = "none";
}

/**
*	@author Ajay Agrawal
*	@Date 24 July, 2008
*	searches the popular sources on the basis of topic added.
*/
var recommendedSourcesRequestSent = 0;
var recommendedSourcesRequestMaxAttempts = 5;
var getRecommendedSources = function (){
	$('nnPopularSources').style.borderRight = "1px solid #D0D0D0";
	$('nnPopularSources').style.borderBottom = "1px solid #D0D0D0";
	$('nnRecommendedSources').style.borderLeft = "";
	$('nnRecommendedSources').style.borderBottom = "";
	$('nnPopularSources').style.color = "#626262";
	$('nnRecommendedSources').style.color = "#000";
	$('searchedRelatedSourcesBody').style.display = "none";
	if(RECOMMENDED_SOURCES_ARRAY.length > 0 && recommendedSourcesRequestSent == 1){
		showRecommendedSources();
		return false;
	}
	// set the post variables
	var postParameters = "news_network_id="+NEWS_NETWORK_ID+"&deleted_nn=1";
	$('recommendsourceLoadinIcon').style.display = "block";
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this data
		postBody: postParameters,
		// Handle successful response
		onSuccess: getRecommendedSourcesCallback,
		// Handle 404
		on404: getRecommendedSources404Callback,
		// Handle other errors
		onFailure: getRecommendedSourcesFailureCallback
	}
	new Ajax.Request('/get-suggested-sources', ajaxRequestOptions);
}

/**
 * get the popular sources success callback function
 */
var getRecommendedSourcesCallback = function (response){

	recommendedSourcesRequestSent =1;
	try{
	$('addSourcesLoadingIcon').style.display = "none";
	}catch(e){}
	//eval the json object
	response_data = eval('(' + response.responseText + ')');
	if(response_data.error == 1) {
		// error message
	} else {
		var recommendedSources = response_data.message;
		RECOMMENDED_SOURCES_ARRAY = new Array();
		for(i=0;i<recommendedSources.length;i++){
			RECOMMENDED_SOURCES_ARRAY[i] = recommendedSources[i];
		}
		if (RECOMMENDED_SOURCES_ARRAY.length <= 0) {
			recommendedSourcesRequestMaxAttempts -= 1;
			if (recommendedSourcesRequestMaxAttempts > 0) {
				setTimeout("getRecommendedSources()", 10000);
			} else {
				showRecommendedSources();
				recommendedSourcesRequestMaxAttempts = 5;
			}
		} else {
			showRecommendedSources();
			recommendedSourcesRequestMaxAttempts = 5;
		}
	}

}
/**
 * get the popular sources failure callback function
 */
var getRecommendedSourcesFailureCallback = function (){
	alert("Error on page");
	$("addSourcesLoadingIcon").style.display = "none";
}
/**
 * get the popular sources 404 callback function
 */
var getRecommendedSources404Callback= function (){
	alert("Error page is not found");
	$("addSourcesLoadingIcon").style.display = "none";
}



/**
*	Function checks whether the new related topic is added or not
*/
/*function validateRelatedTopics(){

	if(OLD_RELATED_TOPICS_ARRAY != USER_RELATED_TOPICS){
		addRelatedTopicsOnNewsNetwork();
	}
}*/

/**
*	Display the popular sources
*/
function showPopularSources(){
	$('nnRecommendedSources').style.borderLeft = "1px solid #D0D0D0";
	$('nnRecommendedSources').style.borderBottom = "1px solid #D0D0D0";
	$('nnPopularSources').style.borderRight = "";
	$('nnPopularSources').style.borderBottom = "";
	$('searchedRelatedSourcesBody').style.display = "block";
	var nnPopularSources = "<div style='padding:10px 0px 10px 0px;margin:0px;font-family:Arial;font-weight;normal;font-size:12px;'>";
	var startPage = POPULAR_SOURCES_MAX_LENGTH * POPULAR_SOURCE_PAGE;
	var end = Math.min(startPage+POPULAR_SOURCES_MAX_LENGTH,POPULAR_SOURCES_ARRAY.length);
	for(i=startPage;i<end;i++){
			nnPopularSources += "<div style='padding:5px 0px 0px 4px;margin:0px;'>"+
									"<div style='width:12px;height:12px;padding:2px 0px 0px 0px;margin:0px;float:left;border:1px solid #DFDFDF'>"+
										"<img src='"+S3_DYNAMIC_ASSETS_PATH+"/feed-favicon/"+(POPULAR_SOURCES_ARRAY[i]['favicon']=='n'?"feed_icon":POPULAR_SOURCES_ARRAY[i]['id'])+".jpg' style='border:0px solid;height:12px;width:12px;'/>"+
									"</div>"+
							   		"<div style='width:80%;padding:0px 0px 0px 5%;margin:0px;float:left;'>"+
							   			"<div align='left' style='padding:0px 0px 0px 5px;margin:0px;'>"+
							   				"<a target='_blank' onmouseover=\"javascript: $('sourceDescription_"+i+"').style.display='block';return false;\" onmouseout=\"javascript: $('sourceDescription_"+i+"').style.display='none';return false;\" href='"+POPULAR_SOURCES_ARRAY[i]['link']+"' style='text-decoration:none'>"+POPULAR_SOURCES_ARRAY[i]['title']+"</a>"+
							   			"</div>"+
							   			"<div align='left' id='sourceDescription_"+i+"' style='color:#646464;padding:0px 0px 0px 5px;margin:0px;display:none;'>"+(POPULAR_SOURCES_ARRAY[i]['description']!=null?POPULAR_SOURCES_ARRAY[i]['description']:'')+"</div>"+
							   		"</div>"+
							   		"<div align='left' style='padding:0px 0px 0px 5px;margin:0px;float:left;cursor:pointer' onclick=\"javascript: addedUserRelatedSources('"+POPULAR_SOURCES_ARRAY[i]['rss']+"');removeFromPopularArray("+i+"); return false;\">"+
							   			"<span class='nn-add-small-button'></span>"+
							   		"</div>"+
							   		"<br clear='all'/>"+
							   	"</div>";
	}
	nnPopularSources += "</div>";
	$('searchedRelatedSourcesBody').innerHTML = nnPopularSources;
	if(POPULAR_SOURCES_ARRAY.length > POPULAR_SOURCES_MAX_LENGTH){
		var paginationInnerhtml = "<div style='padding:0px 15px 0px 0px;margin:0px;float:right'>";
		if(POPULAR_SOURCE_PAGE == 0){
			paginationInnerhtml += "<div style='float:left;padding:0px 0px 0px 12px;margin:0px;' onclick='javascript: return false;'><span class='nn-navigation-left-disabled-small-button'></span></div>";
		}else{
			paginationInnerhtml += "<div style='float:left;padding:0px 0px 0px 12px;margin:0px;cursor:pointer' onclick='javascript: POPULAR_SOURCE_PAGE--;showPopularSources();return false;'><span class='nn-navigation-left-small-button'></span></div>";
		}
		if(end < POPULAR_SOURCES_ARRAY.length){
			paginationInnerhtml += "<div style='float:left;padding:0px 0px 0px 12px;margin:0px;cursor:pointer' onclick='javascript: POPULAR_SOURCE_PAGE++;showPopularSources();return false;'><span class='nn-navigation-right-small-button'></span></div>";
		}else{
			paginationInnerhtml += "<div style='float:left;padding:0px 0px 0px 12px;margin:0px;' onclick='javascript: return false;'><span class='nn-navigation-right-disabled-small-button'></span></div>";
		}
		paginationInnerhtml += "<br clear='all'/>"+
                                     "</div><br clear='all'/>";
         new Insertion.Bottom('searchedRelatedSourcesBody',paginationInnerhtml);
         refreshSnapshots();
	}
}


var removeSources = function (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 idComponents = feed.id.split('-');
    var post_data = 'news_network_id='+ idComponents.first() +'&feed_id='+idComponents.last();
    var ajaxRequestOptions = {
	method: 'post',
	postBody: post_data,
	onSuccess: removeSourcesCallback,
	// Handle 404
	on404: removeSources404Callback,
	// Handle other errors
	onFailure: removeSourcesFailureCallback
    }
    new Ajax.Request('/remove-source-from-news-network', ajaxRequestOptions);

}

// removes the feed container
var removeSourcesCallback = function (response){
    var data =  response.responseText.evalJSON();
    if(response_data.error == 1) {
		//error message
	} else {
	    // Google Analytics - code to track remove source from news network action
		tracAjaxFunctionalities('/remove-source-from-news-network');
	    $(data.news_network_id+'-feed_left-'+data.feed_id).remove();
	    $(data.news_network_id+'-feed-'+data.feed_id).remove();
	}
}

/**
 * delete sources failure callback function
 */
var removeSourcesFailureCallback = function (){
	alert("Error on page");
	$("addSourcesLoadingIcon").style.display = "none";
}
/**
 * delete sources sources 404 callback function
 */
var removeSources404Callback = function (){
	alert("Error page is not found");
	$("addSourcesLoadingIcon").style.display = "none";
}


/**
*	Display the popular sources
*/
function showRecommendedSources(){
	//$('nnPopularSources').style.borderRight = "1px solid #D0D0D0";
	//$('nnPopularSources').style.borderBottom = "1px solid #D0D0D0";
	//$('nnRecommendedSources').style.borderLeft = "";
	//$('nnRecommendedSources').style.borderBottom = "";
	$('recommendsourceLoadinIcon').style.display = "none";
	$('searchedRelatedSourcesBody').style.display = "block";
	var nnRecommendedSources = "<div style='padding:10px 0px 10px 0px;margin:0px;font-family:Arial;font-weight;normal;font-size:12px;'>";
	var startPage = RECOMMENDED_SOURCES_MAX_LENGTH * RECOMMENDED_SOURCE_PAGE;
	var end = Math.min(startPage+RECOMMENDED_SOURCES_MAX_LENGTH,RECOMMENDED_SOURCES_ARRAY.length);
	for(i=startPage;i<end;i++){
			var displayTitle = RECOMMENDED_SOURCES_ARRAY[i]['title'];
			nnRecommendedSources += "<div style='padding:5px 0px 0px 0px;margin:0px;'>"+
							   		"<div style='width:80%;padding:0px 0px 0px 5%;margin:0px;float:left;'>"+
							   			"<div align='left' style='padding:0px 0px 0px 5px;margin:0px;'>"+
							   				"<a target='_blank' title='"+RECOMMENDED_SOURCES_ARRAY[i]['title']+"' href='"+RECOMMENDED_SOURCES_ARRAY[i]['url']+"' style='text-decoration:none'>"+(RECOMMENDED_SOURCES_ARRAY[i]['title'].length > 30 ? RECOMMENDED_SOURCES_ARRAY[i]['title'].substr(0,30).concat('..') : RECOMMENDED_SOURCES_ARRAY[i]['title'])+"</a>"+
							   			"</div>"+
							   		"</div>"+
							   		"<div align='left' style='padding:0px 14px 0px 5px;margin:0px;float:right;cursor:pointer' onclick=\"javascript: addedUserRelatedSources('"+RECOMMENDED_SOURCES_ARRAY[i]['rss_url']+"');removeFromSuggestedArray("+i+"); return false;\">"+
							   			"<span class='nn-add-small-button'></span>"+
							   		"</div>"+
							   		"<br clear='all'/>"+
							   	"</div>";
	}
	nnRecommendedSources += "</div>";
	$('searchedRelatedSourcesBody').innerHTML = nnRecommendedSources;
	if(RECOMMENDED_SOURCES_ARRAY.length > RECOMMENDED_SOURCES_MAX_LENGTH){
		var paginationInnerhtml = "<div style='padding:0px 15px 0px 0px;margin:0px;float:right'>";
		if(RECOMMENDED_SOURCE_PAGE == 0){
			paginationInnerhtml += "<div style='float:left;padding:0px 0px 0px 12px;margin:0px;' onclick='javascript: return false;'><span class='nn-navigation-left-disabled-small-button'></span></div>";
		}else{
			paginationInnerhtml += "<div style='float:left;padding:0px 0px 0px 12px;margin:0px;cursor:pointer' onclick='javascript: RECOMMENDED_SOURCE_PAGE--;showRecommendedSources();return false;'><span class='nn-navigation-left-small-button'></span></div>";
		}
		if(end < RECOMMENDED_SOURCES_ARRAY.length){
			paginationInnerhtml += "<div style='float:left;padding:0px 0px 0px 12px;margin:0px;cursor:pointer' onclick='javascript: RECOMMENDED_SOURCE_PAGE++;showRecommendedSources();return false;'><span class='nn-navigation-right-small-button'></span></div>";
		}else{
			paginationInnerhtml += "<div style='float:left;padding:0px 0px 0px 12px;margin:0px;' onclick='javascript: return false;'><span class='nn-navigation-right-disabled-small-button'></span></div>";
		}
		paginationInnerhtml += "<br clear='all'/>"+
                                     "</div><br clear='all'/>";
         new Insertion.Bottom('searchedRelatedSourcesBody',paginationInnerhtml);
	}
    if(end == 0){
		$('searchedRelatedSourcesBody').innerHTML = '<div style="padding:10px 5px 5px 10px;margin:0px;" >Sorry, we were not able to find recommended sources at this time. Please try your search again later.</div>';
	}
	refreshSnapshots();
}


/**
*	set the default setting for rounded corners
*/
 roundedCornerSettings = {
     tl: { radius: 5 },
     tr: { radius: 5 },
     bl: { radius: 5 },
     br: { radius: 5 },
     antiAlias: true,
     autoPad: false,
     validTags: ["div"]
 }
// Creates the rounded corner for the div "objectName"
var createRoundedCorner = function (){
	var objectName = ['newsNetworkPhoto','newsNetworkDescription','newsNetworkWelcomeMsg','newsNetworkNameContentDiv','newsNetworkNoise'];
	for(i=0;i<objectName.length;i++){
		var roundedCornerBoxObject = new curvyCorners(roundedCornerSettings, $(objectName[i]));
		roundedCornerBoxObject.applyCornersToAll();
	}
}

// contain the status (show/hiode) of div
var CURRENT_DIV_STATUS = new Array();
/**
*	Function show / hide the content/heading div on news network setting page.
*/
function showHideContent(divName){
	if(CURRENT_DIV_STATUS[divName] == null || CURRENT_DIV_STATUS[divName] == 0){
		$('newsNetwork'+divName+'ContentDiv').style.display = 'block';
		$('newsNetwork'+divName+'HeadingDiv').style.display = 'none';
		CURRENT_DIV_STATUS[divName] = 1;
	}else{
		$('newsNetwork'+divName+'ContentDiv').style.display = 'none';
		$('newsNetwork'+divName+'HeadingDiv').style.display = 'block';
		CURRENT_DIV_STATUS[divName] = 0;
	}
}


/**
*	Function remove the element form the popular sources box
*/
function removeFromPopularArray(sourceIndex){
	POPULAR_SOURCES_ARRAY.splice(sourceIndex, 1);
	showPopularSources();
}
/**
*	Function remove the element form the suggested sources box
*/
function removeFromSuggestedArray(sourceIndex){
	RECOMMENDED_SOURCES_ARRAY.splice(sourceIndex, 1);
	showRecommendedSources();
}

/**
*	Function check the news network name in database and retun sucess or error message
*/
function validateNewsNetworkName(){
    if($('newsNetworkName').value == ''){
		$('newsNetworkSettingErrorDiv').innerHTML = 'Please enter the news network name';
		$('newsNetworkSettingErrorDiv').style.visiblity = "visible";
		return false;
	}
    var post_data = 'name='+ $('newsNetworkName').value+"&nid="+NEWS_NETWORK_ID;
    var ajaxRequestOptions = {
		method: 'post',
		postBody: post_data,
		onSuccess: validateNewsNetworkNameCallback,
		// Handle 404
		on404: validateNewsNetworkName404Callback,
		// Handle other errors
		onFailure: validateNewsNetworkNameFailureCallback
    }
    new Ajax.Request('/validate-news-network-name', ajaxRequestOptions);
}
//  validate news network name callback
var validateNewsNetworkNameCallback = function (response){
    //eval the json object
	response_data = eval('(' + response.responseText + ')');
    if(response_data.error == 1) {
		//error message
		$('newsNetworkSettingErrorDiv').innerHTML = response_data.message;
		$('newsNetworkSettingErrorDiv').style.visiblity = "visible";
		deleteCookie("duplicateNews");
	} else {
		if(response_data.news_network_name_exists == 1){
			$('nn_id').value = NEWS_NETWORK_ID;
			if($('nnDescription').value == newsNetworkDescription){
				 $('nnDescription').value = '';
			}
			//newsNetworkWelcome = newsNetworkWelcome.replace("[name]", $('newsNetworkName').value);
			if($('nnWelcome').value == newsNetworkWelcome){
				$('nnWelcome').value = '';
			}
			document.newsNetworkSettingForm.submit();
		}else{
			scroll(0,0);
			$('newsNetworkSettingErrorDiv').innerHTML = 'Sorry but a News Network already exists with that name. Please choose another name.';
			$('newsNetworkSettingErrorDiv').style.visiblity = 'visible';
			$('newsNetworkSettingErrorHelpBox').style.visiblity = 'visible';
			return false;
		}
	}
}
/**
 * validate news network name failure callback function
 */
var validateNewsNetworkName404Callback = function (){
	alert("Error on page");
}

/**
 * validate news network name 404 callback function
 */
var validateNewsNetworkNameFailureCallback = function (){
	alert("Error on page");
}


/**
*	Function send crawl request to the server
*/
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+"&deleted=y";
	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);
}
var STORIES_TIME_INTERVAL = "";
/**
 * Crawl news network feeds success callback function
 */
var crawlNewsCircleFeedCallback = function (response){
}
/**
 * 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");
}

/**
*	Function fetches the story count for the news circle
*/
var getStoriesCount = function(){
var postParameters = "nn_id="+NEWS_NETWORK_ID;
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this data
		postBody: postParameters,
		// Handle successful response
		onSuccess: getStoriesCountCallback,
		// Handle 404
		on404: getStoriesCount404Callback,
		// Handle other errors
		onFailure: getStoriesCountFailureCallback
	}
	new Ajax.Request('/get-story-count', ajaxRequestOptions);
}
var NEWS_NETWORK_STORIES_COUNT = 0;
var PREVIOUSLY_SEARCHED_STORIES_COUNT = 0;
/**
 * displays the stories on the news network wizard success callback function
 */
var getStoriesCountCallback = function (response){
	var data =  response.responseText.evalJSON();
    if(data.error == 1) {
		//error message
	} else {
		NEWS_NETWORK_STORIES_COUNT = data.total_story;
		if(NEWS_NETWORK_STORIES_COUNT > 0 && NEWS_NETWORK_STORIES_COUNT > PREVIOUSLY_SEARCHED_STORIES_COUNT){
			PREVIOUSLY_SEARCHED_STORIES_COUNT = NEWS_NETWORK_STORIES_COUNT;
			if(NEWS_NETWORK_STORIES_COUNT >= 16){
				$('storiesLoadingIcon').style.display = 'none';
				$("storiesLoadingMessage").style.display = "none";
				$("refreshStoriesMessage").style.display = "block";
				clearInterval(STORIES_TIME_INTERVAL);
			}else{
				//var page = parseInt(NEWS_NETWORK_STORIES_COUNT/15);
				getNewsNetworkStories();
			}
		}
	}
}
/**
 * displays the stories on the news network wizard failure callback function
 */
var getStoriesCountFailureCallback = function (){
	alert("Error on page");
}
/**
 * displays the stories on the news network wizard 404 callback function
 */
var getStoriesCount404Callback= function (){
	alert("Error page is not found");
}
/**
*	Function displays the stories on the news network wizard
*/

var getNewsNetworkStories = function (noiseLevel){
	$("refreshStoriesMessage").style.display = "none";
	var postParameters = "nn_id="+NEWS_NETWORK_ID;
	try{
		if(noiseLevel != null){
			postParameters += "&noise_level="+noiseLevel
		}
	}catch(e){}
	var ajaxRequestOptions = {
		// Use POST
		method: 'post',
		// Send this data
		postBody: postParameters,
		// Handle successful response
		onSuccess: getNewsNetworkStoriesCallback,
		// Handle 404
		on404: getNewsNetworkStories404Callback,
		// Handle other errors
		onFailure: getNewsNetworkStoriesFailureCallback
	}
	new Ajax.Request('/get-stories', ajaxRequestOptions);
}
/**
 * displays the stories on the news network wizard success callback function
 */
var getNewsNetworkStoriesCallback = function (response){
	response_data = response.responseText;
	if(response_data == "") {
		alert("No story found");
	} else {
		$('nnWizardStories').innerHTML = response_data;
		$('nnWizardStories').style.display = "block";
		var searchAllHref = document.getElementById('nnWizardStories').getElementsByTagName("a");
		for(i=0;i<searchAllHref.length;i++){
			searchAllHref[i].href = '#';
			searchAllHref[i].onclick = 'javascript:void(0);';
		}
		//$('newsNetworkStoryMessageDiv').style.display = "none";
		//clearInterval(STORIES_TIME_INTERVAL);
	}
}
/**
 * displays the stories on the news network wizard failure callback function
 */
var getNewsNetworkStoriesFailureCallback = function (){
	alert("Error on page");
}
/**
 * displays the stories on the news network wizard 404 callback function
 */
var getNewsNetworkStories404Callback= function (){
	alert("Error page is not found");
}

/**
*	Function validate the user added sources
*/
function validateNewsNetworkSources(){
	if(USER_RELATED_SOURCES.length <= 0){
		$('nnRelatedSourcesErrorMsgBox').innerHTML = "Please add atleast one source";
		return false;
	}else{
		CURRENT_PAGE = 'nnSetting';
		if(NEWS_NETWORK_EXISTS == 1){
			$('newsNetworkName').value = NN_PRIMARY_TOPIC;
		}
	}
}

/**
*	minimize/maximize right side box
* @params boxName: Name of the box.
* @params event: Event type, whether to minimize box or maximize
*/
function minMaxRightSideBoxes(boxName, event){
	if(NETWORK_EDIT == 1){
		event = 'max';
	}
	if(event == 'min'){
		$('network_'+boxName+'_box_max').style.display = 'none';
		$('network_'+boxName+'_box_min').style.display = 'block';
		$('news_network_'+boxName+'_body').style.display = 'none';
		$('newsNetwork'+boxName.capitalize()+'sText').style.borderBottom = '1px solid #F7F7F7';
	}else{
		$('network_'+boxName+'_box_min').style.display = 'none';
		$('network_'+boxName+'_box_max').style.display = 'block';
		$('news_network_'+boxName+'_body').style.display = 'block';
		$('newsNetwork'+boxName.capitalize()+'sText').style.borderBottom = '1px solid #9D9D9D';
	}
}

/**
*	Show/hide the page according to the current page.
*/
function displayLeftSidePage(){
	scroll(0,0);
	// hide all the left side page
	$('nnWizardGettingStarted').style.display = 'none';
	$('nnWizardPrimaryTopic').style.display = 'none';
	$('nnWizardRelatedTopic').style.display = 'none';
	$('nnWizardRelatedSource').style.display = 'none';
	$('nnWizardSetting').style.display = 'none';
	switch(CURRENT_PAGE){
		case "getStarted":
			$('nnWizardGettingStarted').style.display = 'block';
			break;
		case "primaryTopics":
			$('nnWizardPrimaryTopic').style.display = 'block';
			if(NETWORK_EDIT == 1){
				$('primaryTopicPageBack').style.visibility = 'hidden';
			}
			break;
		case "relatedTopics":
			$('nnWizardRelatedTopic').style.display = 'block';
			break;
		case "relatedSources":
			$('nnWizardRelatedSource').style.display = 'block';
			break;
		case "nnSetting":
			$('nnWizardSetting').style.display = 'block';
			// create the rounded corners
			createRoundedCorner();
			//scroll the page to top left
			scroll(0,0);
			break;
	}
}


/**
*	Create all the arrays required for editing the news network information
*/
function displayTopicsAndFeedForNetworkEdit(){
	/**
	*	Set the news network name, description, welcome message, primary topic, location
	*/
	$('nnRelatedTopics').value = relatedTopicsExample;
	$('newsNetworkName').value = (NEWS_NETWORK_TAGS_AND_FEEDS['newsCircle']['name'] != undefined ? NEWS_NETWORK_TAGS_AND_FEEDS['newsCircle']['name']: "");
	$('nnDescription').value = (NEWS_NETWORK_TAGS_AND_FEEDS['newsCircle']['description'] != undefined ? NEWS_NETWORK_TAGS_AND_FEEDS['newsCircle']['description']: "");
	$('nnWelcome').value = (NEWS_NETWORK_TAGS_AND_FEEDS['newsCircle']['welcome'] != undefined ? NEWS_NETWORK_TAGS_AND_FEEDS['newsCircle']['welcome']: "");
	$('nnKnownAs').value = (NEWS_NETWORK_TAGS_AND_FEEDS['knownAs'] != undefined ? NEWS_NETWORK_TAGS_AND_FEEDS['knownAs'] : "");
	//Display user added topics on left  side
	for(i=0;i<NEWS_NETWORK_TAGS_AND_FEEDS['tags'].length;i++){
		if(NEWS_NETWORK_TAGS_AND_FEEDS['tags'][i]['tag_type'] == 'normal'){
			var topicName = escape(NEWS_NETWORK_TAGS_AND_FEEDS['tags'][i]['name']);
			USER_RELATED_TOPICS.push(topicName);
			var insertUserTopic = disaplayTopicsOnLeftSide(NEWS_NETWORK_TAGS_AND_FEEDS['tags'][i]['id'], ''+NEWS_NETWORK_TAGS_AND_FEEDS['tags'][i]['name']+'');
			new Insertion.Bottom('nnRelatedTopicsDisplayBox', insertUserTopic.replace('[pannel]','left'));
		}else if(NEWS_NETWORK_TAGS_AND_FEEDS['tags'][i]['tag_type'] == 'primary'){
			USER_RELATED_TOPICS.push(NEWS_NETWORK_TAGS_AND_FEEDS['tags'][i]['name']);
			$('primaryTopic').value = NEWS_NETWORK_TAGS_AND_FEEDS['tags'][i]['name'];
			showPrimaryTopic();
		}else{
			$('nnLocation').value = NEWS_NETWORK_TAGS_AND_FEEDS['tags'][i]['name'];
			ValidateLocation();
			showPrimaryTopic();
		}
	}
	//Display user added sources on left  side
	for(j=0;j<NEWS_NETWORK_TAGS_AND_FEEDS['feeds'].length;j++){
		if(NEWS_NETWORK_TAGS_AND_FEEDS['feeds'][j]['id'] != 339){
			USER_RELATED_SOURCES.push(NEWS_NETWORK_TAGS_AND_FEEDS['feeds'][j]['id']);
			var insertUserSource = disaplaySourcesOnLeftSide(NEWS_NETWORK_TAGS_AND_FEEDS['feeds'][j]['id'], ''+NEWS_NETWORK_TAGS_AND_FEEDS['feeds'][j]['title']+'');
			// insert the sources on left hand side
			new Insertion.Bottom('nnRelatedSourcesDisplayBox', insertUserSource.replace('[pannel]','left'));
		}
	}
	//show user related
	searchRelatedTopics();
}

/**
*	display the primary topic and location on all the places
*/
function showPrimaryTopic(){// set the primnary topics
	try{
		NN_PRIMARY_TOPIC = 	($('primaryTopic').value != primaryTopicExample ? $('primaryTopic').value : "");
		// display the selected primary topic as heading on related topic page
		$('userSelectedPrimaryTopic').innerHTML = NN_PRIMARY_TOPIC+" ";
		$('userPrimaryTopic').innerHTML = NN_PRIMARY_TOPIC+" (Primary)";
	}catch(e){}
	if($('nnLocation').value != "" && $('nnLocation').value != locationExample){
		$('userLocation').innerHTML = $('nnLocation').value+" (Location)";
		$('userLocation').style.display = "block";
	}
	// added primary topic on right side
	$('primary_keywords').innerHTML = NN_PRIMARY_TOPIC+" (Primary)";
}

/**
*	@author: Ajay Agrawal
*	@version: 19 August 2008
*	@description: display the user added topics on Left panel on Add/Edit news network wizard page.
*/
function disaplayTopicsOnLeftSide(topicId, topicName){
	var insertUserTopic = "<div id='" + NEWS_NETWORK_ID + "-topic-[pannel]-" + topicId + "' style='padding:0px;margin:0px;width:240px;'>"+
		"<div alig='left' style='width:200px;float:left;padding:10px 0px 0px 0px;margin:0px;font-familt:Arial;color:#243968;font-size:13px;'>"+topicName+"</div>"+
		"<div id='"+ NEWS_NETWORK_ID + "-topic_deleter-" + topicId + "' style='padding:10px 0px 0px 0px;margin:0px;float:right;cursor:pointer;font-familt:Arial;color:#243968;font-size:13px;' onclick=\"javascript: deleteUserAddedRelatedTopics(this);return false;\">delete</div>"+
		"<br clear='all'/>"+
	 "</div>";
	 return insertUserTopic;
}
/**
*	@author: Ajay Agrawal
*	@version: 19 August 2008
*	@description: display the user added sources on Left panel on Add/Edit news network wizard page.
*/
function disaplaySourcesOnLeftSide(feedId, feedTitle){
	var insertUserSource = "<div align='left' id='"+NEWS_NETWORK_ID+"-feed_[pannel]-"+feedId+"' style='padding:0px;margin:0px;width:240px;'>"+
			"<div align='left' style='float:left;padding:10px 0px 0px 0px;margin:0px;font-familt:Arial;color:#243968;font-size:13px;width:190px;'>"+feedTitle+"</div>"+
			"<div id='"+NEWS_NETWORK_ID+"-feed_deleter-"+feedId+"' style='padding:10px 0px 0px 0px;margin:0px;float:right;cursor:pointer;font-familt:Arial;color:#243968;font-size:13px;' onclick=\"javascript: removeSources(this);return false;\">delete</div>"+
			"<br clear='all'/>"+
		 "</div>";
	return insertUserSource;
}

/**
*	KD 17/11/08
*	function to check the maxlength of textarea for add primary topic in nn wizard.
*/
function imposeMaxLength(Object, MaxLen){
  if (Object.value.strip().length > MaxLen){
  	Object.value = Object.value.strip().substring(0,MaxLen);
  }
}