// Ajax loading handler
var loadingHandler = {
	onCreate:   function() { if($("ajax_loading_div")!=null) { $("ajax_loading_div").style.display = "block"; } },
	onComplete: function() { if($("ajax_loading_div")!=null && Ajax.activeRequestCount==0) { $("ajax_loading_div").style.display = "none"; } }
};

// Handler registration
Ajax.Responders.register(loadingHandler);

// Throw the ajax request to find tags which start with the user query
function loadQueryResults()
{
	// Get the real query
	var query = trim($("query").value);
	// If there exists a query
	if(query.length > 2)
	{
		// Params to post
		var params = 'query='+query;
		// Ajax request
		new Ajax.Request('./ajax/queryResult.php',{method:'post',parameters:params,onComplete:showQueryResults});
	}
	else
	{
		$("queryResults").update();
		$("queryResults").style.display = 'none';
	}
}

// Show the tags which start with the user query
function showQueryResults(xml)
{
	// Set te result id to 0
	queryResultId = 0;
	// Clear the div content
	$("queryResults").update();
	$("queryResults").style.display = 'none';
	// Get the root node
	var results = xml.responseXML.getElementsByTagName("results")[0].childNodes;
	if(!results)
	{
		alert("Erreur de recuperation des données...");
		return;
	}
	// Init the result counter
	queryResultCount = 0;
	// For each result
	for(var i=0;i<results.length;i++)
	{
		// Get the current child node
		var node = results.item(i);
		// If this is a result node
		if(node.nodeName=="result")
		{
			// Create a new div
			var newDiv = document.createElement("div");
			newDiv.id = "result_"+(++queryResultCount);
			newDiv.textContent = node.textContent;
			newDiv.className = "queryResult";
			newDiv.setAttribute("onClick","javascript:sendSearchForm('"+node.textContent+"');");
			newDiv.setAttribute("onMouseOver","javascript:setActiveResult('"+queryResultCount+"');");
			newDiv.setAttribute("onMouseOut","javascript:setInactiveResults();");
			// Add the new div
			$("queryResults").appendChild(newDiv);
		}
		else if(node.nodeName=="count")
		{
			var resultCount = node.textContent;
		}		
	}
	// If there exists results
	if(queryResultCount)
	{
		// Set the div visible
		$("queryResults").style.display = '';
		// Print the result count
		if(queryResultCount<resultCount)
		{
			var newDiv = document.createElement("div");
			newDiv.textContent = "... ("+queryResultCount+" de "+resultCount+")";
			newDiv.className = "queryResult";
			// Add the new div
			$("queryResults").appendChild(newDiv);
		}
	}
}

// Launch an ajax request for the workspace
function launchAjaxWorkspace(params, fct, notClear)
{	
	// Clear the post content
	if(notClear==null && $("workspace_form_content")!=null)
	{
		$("workspace_form_content").update();
		$("workspace_form_content").style.visibility = "hidden";
	}
	// Ajax request
	new Ajax.Request('./ajax/workspace.php',{method:'post',parameters:params,onComplete:fct});
}

// Load the workspace list
function workspaceLoadList(type)
{
	// Set the params
	var params = "action=workspace_load_list&type=" + type;
	// Launch the ajax request
	launchAjaxWorkspace(params,workspaceLoadContent);
}

// Reload the workspace list
function workspaceReloadList(type)
{
	// Set the params
	var params = "action=workspace_reload_list&type=" + type;
	// Launch the ajax request
	launchAjaxWorkspace(params,workspaceLoadContent,true);
}

// Gets the form to add an item
function workspaceAddUrl(type)
{
	// Set the params
	var params = "action=workspace_add_url&type=" + type;
	// Launch the ajax request
	launchAjaxWorkspace(params,workspaceFormLoadContent);
}

// Add an URL to a workspace list (submited)
function workspaceAddUrlSubmited(type)
{
	// Set the params
	var params = "action=workspace_add_url_submited&type=" + type + 
	"&url=" + urlencode($("ajax_field_url").value) +
	"&title=" + ($("ajax_field_title").value).replace("&", " ") +
	"&description=" + ($("ajax_field_desc").value).replace("&", " ");
	
	if(type=="seed")
	{
		params += "&category=" + ($("ajax_field_cat")[$("ajax_field_cat").selectedIndex].value).replace("&", " ");
	}
	
	// Launch the ajax request
	launchAjaxWorkspace(params,workspaceFormLoadContent);
}

// Modify an URL into a workspace list
function workspaceModifyUrl(type, id)
{
	// Set the params
	var params = "action=workspace_modify_url&type=" + type + "&id=" + id;
	// Launch the ajax request
	launchAjaxWorkspace(params,workspaceFormLoadContent);
}

// Modify an URL into a workspace list (submited)
function workspaceModifyUrlSubmited(type, id)
{
	// Set the params
	var params = "action=workspace_modify_url_submited&type=" + type + 
	"&id=" + id +
	"&url=" + urlencode($("ajax_field_url").value) +
	"&title=" + ($("ajax_field_title").value).replace("&", " ") +
	"&description=" + ($("ajax_field_desc").value).replace("&", " ");
	
	if(type=="seed")
	{
		params += "&category=" + ($("ajax_field_cat")[$("ajax_field_cat").selectedIndex].value).replace("&", " ");
	}
	
	// Launch the ajax request
	launchAjaxWorkspace(params,workspaceFormLoadContent);
}

// Delete an URL into a workspace list
function workspaceDeleteUrl(type,id)
{
	// Set the params
	var params = "action=workspace_delete_url&type=" + type + "&id=" + id;
	// Launch the ajax request
	launchAjaxWorkspace(params,workspaceFormLoadContent);
}

// Update an URL status into a workspace list
function workspaceUpdateUrlStatus(type,id)
{
	// Get the status
	var actived = ($("ajax_field_flow_" + id).checked) ? "true" : "false";
	// Set the params
	var params = "action=workspace_update_url_status&type=" + type + "&id=" + id + "&actived=" + actived;
	// Launch the ajax request
	launchAjaxWorkspace(params,workspaceFormLoadContent);
}

// Change the parsing frequency
function workspaceUpdateRssParsingFrequence()
{
	// Get the frequency
	var frequency = $("ajax_field_frequency")[$("ajax_field_frequency").selectedIndex].value;
	// Set the params
	var params = "action=workspace_update_rss_parsing_frequence&frequency=" + frequency;
	// Launch the ajax request
	launchAjaxWorkspace(params,workspaceFormLoadContent);
}

// Change the list max post
function workspaceUpdateRssMaxPost()
{
	// Get the value
	var max_post = $("ajax_field_max_post")[$("ajax_field_max_post").selectedIndex].value;
	// Set the params
	var params = "action=workspace_update_rss_max_post&max_post=" + max_post;
	// Launch the ajax request
	launchAjaxWorkspace(params,workspaceFormLoadContent);
}

// Load the workspace content
function workspaceLoadContent(xml)
{
	// Vars
	var page = null;
	var clear = null;
	// Get the child nodes
	var childs = xml.responseXML.getElementsByTagName("ajax_xml")[0].childNodes;
	// For each child node
	for(var i=0;i<childs.length;i++)
	{
		// Get the current child node
		var node = childs.item(i);
		// If this is the page node
		if(node.nodeName=="page")
		{
			// Get the HTML flow
			page = getNodeContent(node);
		}
		// If this is the clear node
		if(node.nodeName=="clearForm")
		{
			// Get the clear status
			clear = getNodeContent(node);
		}
	}
	// If there is a page content
	if(page!=null)
	{
		// Load the content
		$("workspace_content").update(page);
	}
	// If the form have to been cleared
	if(clear=="true")
	{
		// Clear the form div
		$("workspace_form_content").update();
	}
}

// Load the workspace form content
function workspaceFormLoadContent(xml)
{
	// Vars
	var page = null;
	var reload = null;
	var type = null;
	// Get the child nodes
	var childs = xml.responseXML.getElementsByTagName("ajax_xml")[0].childNodes;
	// For each child node
	for(var i=0;i<childs.length;i++)
	{
		// Get the current child node
		var node = childs.item(i);
		// If this is the page node
		if(node.nodeName=="page")
		{
			// Get the HTML flow
			page =  getNodeContent(node);
		}
		// If this is the reload node
		if(node.nodeName=="reloadList")
		{
			// Get the reload status and the content type
			reload =  getNodeContent(node);
			type = node.getAttribute("type");
		}
	}
	// If there is a page content
	if(page!=null)
	{
		// Load the content
		$("workspace_form_content").update(page);
		$("workspace_form_content").style.visibility = "visible";
		// Add an effect
		new Effect.BlindDown("workspace_form_content");
	}
	// If the workspace have to be reloaded
	if(reload=="true" && type!=null)
	{
		workspaceReloadList(type);
	}
}

// Launch an ajax request for the news
function launchAjaxNews(params,fct)
{	
	// Clear the post content
	if($("rss_main")!=null)
	{
		$("rss_main").update();
		$("rss_main").style.visibility = "hidden";
	}
	// Ajax request
	new Ajax.Request('./ajax/news.php',{method:'post',parameters:params,onComplete:fct});
}

// Load a RSS list
function newsLoadRssList()
{
	// Set the params
	var params = "action=news_load_rss_list";
	// Launch the ajax request
	launchAjaxNews(params,newsLoadList);
}

// Load a RSS post
function newsLoadRss(id)
{
	// Set the params
	var params = "action=news_load_rss&id=" + id;
	// Launch the ajax request
	launchAjaxNews(params,newsLoadContent);
}

// Load a RSS list of more recent articles
function newsLoadRssListMoreRecent(index)
{
	// Set the params
	var params = "action=news_load_rss_list_more_recent&index=" + index;
	// Launch the ajax request
	launchAjaxNews(params,newsLoadList);
}

// Load a RSS list of older articles
function newsLoadRssListOlder(index)
{
	// Set the params
	var params = "action=news_load_rss_list_older&index=" + index;
	// Launch the ajax request
	launchAjaxNews(params,newsLoadList);
}

// Load the RSS post content
function newsLoadContent(xml)
{
	// Vars
	var page = null;
	// Get the child nodes
	var childs = xml.responseXML.getElementsByTagName("ajax_xml")[0].childNodes;
	// For each child node
	for(var i=0;i<childs.length;i++)
	{
		// Get the current child node
		var node = childs.item(i);
		// If this is the page node
		if(node.nodeName=="page")
		{
			// Get the HTML flow
			page = getNodeContent(node);
		}
	}
	// If there is a page content
	if(page!=null)
	{
		// Load the content
		$("rss_main").update(page);
		$("rss_main").style.visibility = 'visible';
	}
}

// Load the RSS list content
function newsLoadList(xml)
{
	// Vars
	var page = null;
	// Get the child nodes
	var childs = xml.responseXML.getElementsByTagName("ajax_xml")[0].childNodes;
	// For each child node
	for(var i=0;i<childs.length;i++)
	{
		// Get the current child node
		var node = childs.item(i);
		// If this is the page node
		if(node.nodeName=="page")
		{
			// Get the HTML flow
			page = getNodeContent(node);
		}
	}
	// If there is a page content
	if(page!=null)
	{
		// Load the content
		$("rss_list").update(page);
	}
}

// Init the checked url image
function init_checked_url_img()
{
	$("check_url_img").setAttribute("src","./img/check.png");
}

// Check an URL
function checkUrl(input_id)
{
	// Params to post
	var params = 'url=' + $(input_id).value;
	// Ajax request
	new Ajax.Request('./ajax/checkUrl.php',{method:'post',parameters:params,onComplete:checkedUrl});
}

function checkedUrl(xml)
{
	// Get the root node
	var root_node = xml.responseXML.getElementsByTagName("result")[0];
	// Error node
	var error_node = root_node.getElementsByTagName("error");
	// Status node
	var status_node = root_node.getElementsByTagName("status");
	// If an error exists
	if(error_node.length > 0)
	{
		// Alert
		alert("An error occurred during the URL checking [" + getNodeContent(error_node[0]) + "].");
	}
	else
	{
		// Get the status
		var status = getNodeContent(status_node[0]);
		// Valid URL
		if(status == "valid")
		{
			$("check_url_img").setAttribute("src","./img/valid.png");
		}
		else
		{
			$("check_url_img").setAttribute("src","./img/invalid.png");
		}
	}
}