//
// element which will be injected with dynamicaly created HTML
//
var htmlElementWithVacancies = "jobslistingDiv";


// kick off as soon as page is fully loaded
window.onload = connectToServer;

function connectToServer()
{
	bswAjax({
		type:"GET",
		url:'/xml_data.php',		
		timeout:50000,
		onSuccess:parseXmlResponse,
		onError:showError,
		data:"xml"
		});
}

function parseXmlResponse(xmlDom)
{
	// this function parses xml-response and creates html-snippet
	// NOTE: this function strictly follows the xml-format described in the pdf file
	// If format changes this function will bail-out and produce an error!
	var root = xmlDom.getElementsByTagName('root');
	if (root.length != 1)
	{
		root = null;
		return showError();
	}
	
	// now, each child of <root> is called <row>
	// just collect them all in one array
	var rowarray = xmlDom.getElementsByTagName('row');
	if (rowarray.length == 0)
	{
		rowarray = null;
		return showError();
	}
	
	var htmlresponse = "";
	
	for (var i=0; i<rowarray.length; i++)
	{
		var row = rowarray[i];
		var attrs = row.attributes;

		htmlresponse += "<ul class=\"joblisting\">";
		for (var a=0; a<attrs.length; a++)
		{
			// additional request:
			// make items with "job_title" class links, pointing to "/vacancy.htm"
			// i.e. 
			// <li class="job_title"><a 
			//   href="/vacancy.htm" alt="Show full list of vacancies"> attr.value </a></li>

			htmlresponse += "<li class=\""+ attrs[a].name + "\">";
			if (attrs[a].name == "job_title") {
				htmlresponse += "<a href=\"/vacancies.htm\" target=\"_top\" alt=\"Show list of vacancies\">"
					+ attrs[a].value + "</a>"; 
			}
			else
				htmlresponse += attrs[a].value;
			
			htmlresponse += "</li>";
		}
		htmlresponse += "</ul>";		
	}

	// all done - inject HTML
	injectHtml(htmlElementWithVacancies, htmlresponse);
}

function showError()
{
	// if server doesn't reply or returns an error make an error-html snippet here
	injectHtml(htmlElementWithVacancies,
		"<ul class=\"joblisting\"><li class=\"error\">There was an error while trying to retrieve vacancies list. Please try later</li></ul>");
}

function injectHtml(htmlElementId, htmlSnippet)
{
	// parsed xml/error converted to html is injected into page here
	var HtmlEl = document.getElementById(htmlElementId);
	if (HtmlEl != null)
	{
		HtmlEl.innerHTML = htmlSnippet;
	}
}
