Event.observe(window,'load',pre,false);
var more = true;
var jsonData="";
var jsonOffices="";
var propertynames="";
var companyId = -1;
var officedetailsarray = new Array();
var indexpage = true;
var submitted = false; // This is used to detect if the page is submitted (e.g. if there are inputparameter from standard input)
var param = "myPAR";
var url = "myURL";
var page = 1;
var pagesize = 10;
var total = 0;
var sort = 1; // The default sort method
var pnid = new Array();
var pninit = new Array();
var pninitialized = false;
var countryinit = new Array();
var countryinitialized = false;
var firstRun = true;

function pre()
{
	var urlparts = location.pathname.split('/');
	var htmlfilename = urlparts[urlparts.length-1];

	more = true;   // The checkboxes should be created on the Guided finder

	// Add observers to the find buttons
	Event.observe('quickfind', 'mouseover',  function(){$('quickfind').style.backgroundImage="url(graphics/find1_green_button_hover.png)";}, false);
	Event.observe('quickfind', 'mouseout', 	 function(){$('quickfind').style.backgroundImage="url(graphics/find1_green_button.png)";}, false);
	Event.observe('quickfind', 'click', 	 function(){$('quickfind').style.backgroundImage="url(graphics/find1_green_button_OnClick.png)";}, false);
	Event.observe('guidedfind', 'mouseover', function(){$('guidedfind').style.backgroundImage="url(graphics/find1_blue_button_hover.png)";}, false);
	Event.observe('guidedfind', 'mouseout',  function(){$('guidedfind').style.backgroundImage="url(graphics/find1_blue_button.png)";}, false);
	Event.observe('guidedfind', 'click',	 function(){$('guidedfind').style.backgroundImage="url(graphics/find1_blue_button_OnClick.png)";}, false);


	Element.hide( 'goflink' );
	Element.hide( 'subheader' );

	Event.observe('printlink', 'click', function(){window.print();}, false);	// put a listener on the more/less link
	Event.observe('printicon', 'click', function(){window.print();}, false);	// put a listener on the more/less link

	// Add action observers to the find buttons

	Event.observe('tips', 'click', showTips, false);
	Event.observe('closetips', 'click', hideTips, false);

	$('top').appendChild($('subheader'));
	$('loading').appendChild($('loadinggif'));
	$$('.weblink')[0].appendChild($('goflink'));
	
	Event.observe(window,'resize',resizeDimm,false);

	Event.observe('query', 'keypress', getkey, false);
	
	Event.observe('unlocode', 'click', openunlocodeOpenWindow, false);
	
	properties();
	init();
}

function resizeDimm(){
	if((getPageSize()[0])<1024)
		$('dimm').style.width = "1025px";
	else
		$('dimm').style.width = "100%";
		
	$('dimm').style.height = pageHeightWithTable()+"px";	
}

function pageHeightWithTable()
{
	var h = 208;
	if(more)
		h=360;

	if(defined($$('table')[0]))
		h+= Element.getHeight( $$('table')[0]);
		
	if(more)
		h+=160;

	var h2 = getPageSize()[1];	// The height of the window

//	if(h<620)	
//		h=1200;	// The minimum height for the dimmed background

	return (h>h2?h:h2);
}


function changeToResultLayout(){
	var i = 0;
	indexpage = false;
	$('top').id="topresult";
	$('moreoptions').update('<b>› <span id="more">More options;</span></b> Type of office, services and business functions');

	Element.hide( 'propertynames' );
	more=false;		// Should more options be shown on the result page.
	properties();
//	if(param!="")
//		toggled();
	Element.show( 'moreoptions' );
	Element.hide( 'strapline' );
	Element.show( 'result' );
	Element.hide( 'help' );
	Element.show( 'accumulatedinfo' );
	Element.show( 'goflink' );

	Event.observe('goflink', 'click', changeToIndexLayout, false);

	$('quickfind').style.backgroundImage="url(graphics/find2_green_button.png)";
	$('guidedfind').style.backgroundImage="url(graphics/find2_blue_button.png)";

	Event.stopObserving('quickfind','mouseover');
	Event.stopObserving('quickfind','mouseout');
	Event.stopObserving('quickfind','click');
	Event.stopObserving('guidedfind','mouseover');
	Event.stopObserving('guidedfind','mouseout');
	Event.stopObserving('guidedfind','click');

	Event.observe('quickfind', 'mouseover',  function(){$('quickfind').style.backgroundImage="url(graphics/find2_green_button_hover.png)";}, false);
	Event.observe('quickfind', 'mouseout', 	 function(){$('quickfind').style.backgroundImage="url(graphics/find2_green_button.png)";}, false);
	Event.observe('quickfind', 'click',		 function(){$('quickfind').style.backgroundImage="url(graphics/find2_green_button_OnClick.png)";}, false);
	Event.observe('guidedfind', 'mouseover', function(){$('guidedfind').style.backgroundImage="url(graphics/find2_blue_button_hover.png)";}, false);
	Event.observe('guidedfind', 'mouseout',  function(){$('guidedfind').style.backgroundImage="url(graphics/find2_blue_button.png)";}, false);
	Event.observe('guidedfind', 'click', 	 function(){$('guidedfind').style.backgroundImage="url(graphics/find2_blue_button_OnClick.png)";}, false);

	Event.observe('moreoptions', 'click', toggled, false);	// put a listener on the more/less link

	Event.observe('closeofficedetails', 'click', hideOfficeDetails, false);
	Event.observe('guidedfind', 'click', submit, false);
	Event.observe('quickfind', 'click', submit, false);

	var b = document.createElement('b');
	b.appendChild(document.createTextNode('› '));
	$('tip').appendChild(b);
	$('tip').appendChild($('tips'));


}

function changeToIndexLayout()
{
	indexpage = true;
	more = true;
	page = 1;
	sort = 1;
	Element.show( 'propertynames' );
	Element.show( 'strapline' );
	Element.show( 'help' );
	Element.hide( 'accumulatedinfo' );
//	Element.hide( 'moreoptions' );
	Element.hide( 'result' );
	Element.hide( 'goflink' );
	Element.hide( 'subheader' );



	$('topresult').id="top";
	$('quickfind').style.backgroundImage="url(graphics/find1_green_button.png)";
	$('guidedfind').style.backgroundImage="url(graphics/find1_blue_button.png)";

	Event.stopObserving('quickfind','mouseover');
	Event.stopObserving('quickfind','mouseout');
	Event.stopObserving('quickfind','click');
	Event.stopObserving('guidedfind','mouseover');
	Event.stopObserving('guidedfind','mouseout');
	Event.stopObserving('guidedfind','click');


	Event.observe('quickfind', 'mouseover',  function(){$('quickfind').style.backgroundImage="url(graphics/find1_green_button_hover.png)";}, false);
	Event.observe('quickfind', 'mouseout', 	 function(){$('quickfind').style.backgroundImage="url(graphics/find1_green_button.png)";}, false);
	Event.observe('quickfind', 'click', 	 function(){$('quickfind').style.backgroundImage="url(graphics/find1_green_button_OnClick.png)";}, false);

	Event.observe('guidedfind', 'mouseover', function(){$('guidedfind').style.backgroundImage="url(graphics/find1_blue_button_hover.png)";}, false);
	Event.observe('guidedfind', 'mouseout',  function(){$('guidedfind').style.backgroundImage="url(graphics/find1_blue_button.png)";}, false);
	Event.observe('guidedfind', 'click', 	 function(){$('guidedfind').style.backgroundImage="url(graphics/find1_blue_button_OnClick.png)";}, false);


	Event.observe('tips', 'click', showTips, false);
	Event.observe('closetips', 'click', hideTips, false);
//	addObservers();	// Find and select observers

	Event.observe('guidedfind', 'click', submit, false);
	Event.observe('quickfind', 'click', submit, false);
	Event.observe('quickfind', 'click', submit, false);

}

function hideTips()
{
	$('hidden').appendChild($('space'));		// Move space to the hidden area
	$('hidden').appendChild($('info'));		// Move details to the hidden area
	$('hidden').appendChild($('modal'));	// Move modal to the hidden area
	$('hidden').appendChild($('dimm'));		// Move dimm to the hidden area
	showSelectBoxes();
}

function showTips(){
	$('dimm').style.overflowX="hidden";
	hideSelectBoxes();
	var dimmheight = pageHeightWithTable();
	if(dimmheight<800)
		dimmheight=800;
	$('dimm').style.height = (dimmheight + 'px');		// Set the height of the dimm to pageheight
	if((getPageSize()[0])<1024)
		$('dimm').style.width = "1025px";
	document.body.appendChild($('dimm'));				// Move the dimm to the page
	document.body.appendChild($('modal'));				// Move modal to the dom
	
	$('modal').appendChild($('info')); 					// Move details to the dom
	$('modal').appendChild($('space'));
	
}

function openunlocodeOpenWindow(evt){
	Event.stop(evt);
	window.open('http://www.unece.org/cefact/locode/service/location.htm');
}

function hideOfficeDetails()
{
	removeChildren('officedetails');
	$('hidden').appendChild($('details'));	// Move details to the hidden area
	$('hidden').appendChild($('trans'));	// Move trans to the hidden area
	$('hidden').appendChild($('modal'));	// Move modal to the hidden area
	$('hidden').appendChild($('dimm'));		// Move dimm to the hidden area
	$('dimm').style.height = "100%";		// Reset the height to 100%
	showSelectBoxes();
}

function showOfficeDetails(evt){
	var elem = Event.element(evt);

	if( elem.parentNode.tagName=="tr" || elem.parentNode.tagName=="TR")
		var id = elem.parentNode.id;
	else if( elem.parentNode.tagName=="td" || elem.parentNode.tagName=="TD")
		var id = elem.parentNode.parentNode.id;

	if(id>0)
	{
		// Now the popup is created, get the data

		odurl = '/gof/office_details.json';
		if(location.protocol!="http:")
			odurl = 'json/office_details.json';

		var pars = 'id=' + id;


		for (i=0;i<jsonOffices.length;i++)
			if(jsonOffices[i].i==id)
				officedetailsarray = jsonOffices[i];
				
				

		companyId = id; // set the global var
		new Ajax.Request(odurl,
			{
			  method:'get',
			  parameters: pars,
			  onCreate: showLoad,
			  onComplete: hideLoad,
			  onFailure: showFailureMessage,
			  onSuccess: updateOfficeDetails
			}
		);
	}
}




function updateOfficeDetails(req)
{
	extraInfo = req.responseText.evalJSON()

	var dimmheight = pageHeightWithTable();//(h>h2?h:h2);

	hideSelectBoxes();									// This is needed for IE6
	$('dimm').style.height = (dimmheight + 'px');		// Set the height of the dimm to pageheight
	if((getPageSize()[0])<1024)
		$('dimm').style.width = "2000px";
	document.body.appendChild($('dimm'));				// Move dimm to the dom
	document.body.appendChild($('modal'));				// Move modal to the dom
	$('modal').appendChild($('trans')); 				// Move trans to the dom
	$('trans').style.height = ((getPageScroll()[1]) + 'px');
	$('modal').appendChild($('details')); 				// Move details to the dom
	
	// fullinfo contails all info about the office
	var fullinfo = new Array();
	for (var key in officedetailsarray)
		if(defined(officedetailsarray[key]) && officedetailsarray[key]!="")
			fullinfo[key] = officedetailsarray[key];

	// Add the extra info about the office
	for (var key in extraInfo.officedetails)
		fullinfo[key] = extraInfo.officedetails[key];
	
	var div2 = document.createElement('div');

	var div = makeOneOfficeDetailDiv(fullinfo);
	div2.appendChild(div);
	$('officedetails').update(div2);	

	
}




/*
 * Get the data for the dropdowns and the checkboxe
 */
function init()
{
	url = '/gof/init.json';

	if(location.protocol!="http:")
		url = 'json/init.json';

	new Ajax.Request(url,
		{
		  method:'get',
		  onCreate: showLoad,
		  onComplete: hideLoad,
		  onFailure: showFailureMessage,
		  onSuccess: updatePage
		}
	);
}


/*
 * Add the dropdowns and checkboxes to the page
 */
function updatePage(req)
{
	if(defined(req) && req.responseText!="")
		jsonData = req.responseText.evalJSON(true);
 	//var jsonData = eval('('+req.responseText+')');

	if(defined(jsonData.pagesize))
	{
		pagesize=jsonData.pagesize;
	}
	if(defined(jsonData.regions))
	{
		if(jsonData.regions.length>0)
		{
			updateDropdown('region','select continent',jsonData.regions);
		}
		else
		{
			removeChildren('region');
			appendOption('region',"",'no continent available');
		}
//		new Effect.Highlight('region');
	}
	if(defined(jsonData.countries))
	{
//		Element.show('countryloading');
		var sel = $('country').childNodes[0];

		var len = jsonData.countries.length;
		if(len>0)
		{
			if(!countryinitialized)
			{
				countryinitialized=true;
				countryinit = jsonData.countries
			}
			updateDropdown('country','select country',jsonData.countries);
		}
		else
		{
//			removeChildren(sel);
			updateDropdown('country','select country',countryinit);
		}
		// perform speciel actions if dropdown contains 1 or 2 elements
		if (len == 0)
		{
			Form.Element.disable(sel);
		}
		else if (len == 1)
		{

			var map = jsonData.countries[0];
			var id = -1;
			for (var key in map)
				id = key;

			var sel = $('country').childNodes[0];
			sel.childNodes[1].selected = true;
			Form.Element.disable(sel);


			// The only country is selected automatically, so update the city list
			url = '/gof/cities_for_country.json?id='+id;
			if(location.protocol!="http:")
				url = 'json/citiesforcountry.json'+id;

			new Ajax.Request(url,
				{
				  method:'get',
				  onCreate: showLoad,
				  onComplete: hideLoad,
				  onFailure: showFailureMessage,
				  onSuccess: updatePage
				}
			);


		}
		var sel = $('country').childNodes[0];
//		new Effect.Highlight(sel);
//		Element.hide('countryloading');

	}

	if(defined(jsonData.cities))
	{
		var len = jsonData.cities.length;

		var sel = $('city').childNodes[0];
		if(len>0)
			updateDropdown('city','select city',jsonData.cities);
		else
		{
			removeChildren(sel);
			appendOption(sel,"",'no cities available');
		}

		// perform speciel actions if dropdown contains 1 or 2 elements
		if (len == 0)
		{
			Form.Element.disable(sel);
		}
		else if (len == 1)
		{

			var map = jsonData.cities[0];
			var id = -1;
			for (var key in map)
				id = key;

			var sel = $('city').childNodes[0];
			sel.childNodes[1].selected = true;
			Form.Element.disable(sel);
		}

//		new Effect.Highlight(sel);
//		Element.hide('cityloading');
	}

// Reset the country list if details are not given en the json
// This should only be done if at the same time the country or region is updated

	// This is the checkboxes

		var pTypesDiv = document.createElement('div');

		setClass(pTypesDiv,'propertytypes');


		if(defined(jsonData.propertynames))
		{
			var i=0;
			// resolve the map to get the key and values
			var map = jsonData.propertynames;

			// Loop through the propertytypes
			var output = '';
			for (var propertytype in map)
			{
				var pTypeDiv = document.createElement('div');
				setClass(pTypeDiv,'propertytype');
				pTypesDiv.appendChild(pTypeDiv);

				// Add heading to the different types
				var p = document.createElement('p');
				p.appendChild(document.createTextNode(propertytype));
				pTypeDiv.appendChild(p);

				// Create the list and add it to the dom
				var ul = document.createElement('ul');
				pTypeDiv.appendChild(ul);


				var property = map[propertytype];
				if(defined(property))
				{
					for (var name in property)
					{
						var li = document.createElement('li');
						ul.appendChild(li);


						var label = document.createElement('label');
						label.htmlFor = name;

						label.appendChild(document.createTextNode(property[name]));

						var checkbox = document.createElement('input');
						checkbox.type = "checkbox";
//						if(indexpage)
//							checkbox.name = "prop"+name;
//						else

						checkbox.name = name;

/*						if(gup('prop'+name)=='on')
						{
							checkbox.checked = true;
							more = true;
							submitted=true;
						}
*/
//						if(list[i].v==1)
//							checkbox.disabled = "true";

						checkbox.id = "check"+name;

						li.appendChild(checkbox);
						li.appendChild(label);
						pnid[i++]=name;

						Event.observe(label, 'click', toggle_checkbox, false);
					}
				}
			}

			$('propertynames').update(pTypesDiv);
			properties();


	}
	if(defined(jsonData.offices))
	{
		updateDropdown('country','select country',jsonData.countries);
//		new Effect.Highlight('country');
	}
	if(defined(jsonData.pn))
	{
		if(jsonData.pn.length>0)
			for(var i=0; i<pnid.length; i++)	// Run through all properties
			{
				var elm = $('check'+pnid[i])
				if(existIn(pnid[i],jsonData.pn))
				{
					Form.Element.enable(elm);
					elm.parentNode.childNodes[1].style.color="#002664";
				}
				else
				{
					elm.checked=false;
					Form.Element.disable(elm);
					elm.parentNode.childNodes[1].style.color="#999";
				}
			}





		if(!pninitialized)
		{
			pninit=jsonData.pn;
			pninitialized=true;
		}

	}
	addObservers();
	if(firstRun)
		checkInputPars();
	firstRun = false;
	if(submitted)
		submit(null);

}

function checkInputPars(){
	page = 1; // The default page
	sort = 1; // The default sort method
	url = "";
	param = "";

	var id_country = gup('countryid');
	if (id_country>0)
	{
		var sel = $('country').childNodes[0].childNodes;
		
		// Select the right country in the dropdown
		for(var i=0;i<sel.length;i++)
			if(sel[i].value==id_country)
				sel[i].selected = true;


		// Update the city dropdown
		url = '/gof/cities_for_country.json?id='+id_country;
		if(location.protocol!="http:")
			url = 'json/citiesforcountry.json'+id_country;

		new Ajax.Request(url,
			{
			  method:'get',
			  onCreate: showLoad,
			  onComplete: hideLoad,
			  onFailure: showFailureMessage,
			  onSuccess: updatePage
			}
		);



		url = '/gof/offices_for_country.json?id='+id_country;
		if(location.protocol!="http:")
			url = 'json/offices_for_country.json';

		new Ajax.Request(url,
			{
			  method:'get',
			  onCreate: showLoad,
			  onComplete: hideLoad,
//			  onFailure: function(req) {},
//			  onException: function(t,e) {},
			  onSuccess: updateResult
			}
		);

	}
}

function disableCities(){
		var sel = $('city').childNodes[0];
		removeChildren(sel);
		appendOption(sel,"",'select city');
		Form.Element.disable(sel);
//		new Effect.Highlight(sel);

}

function toggle_checkbox(evt){
	var elem = Event.element(evt);
	var box = elem.parentNode.childNodes[0];
	if(!box.disabled)	// Only toggle if checkbox is not disabled
		box.checked = !box.checked;
}


function updateDropdown(id,first_option,list){

//	removeChildren(id);

	if(typeof(list)=="undefined")
		return;

	var select = document.createElement('select');

	appendOption(select,"",first_option);
	var i=0
	if(id=="city")
	{
		for(i; i<list.length;i++)
			appendOption(select,list[i],list[i]);

	}
	else
	{
		for(i; i<list.length;i++)
		{
			var map = list[i];
			for (var key in map)
				appendOption(select,key,map[key]);
		}
	}
	$(id).update(select);
}

function appendOption(id,key,value)
{
	var x = $(id);

	var option = document.createElement('option');

	option.value = key;
//	option.text = value;

	option.appendChild(document.createTextNode(value));
	var value = document.createAttribute("value","123");
//	option.appendChild(value);

	x.appendChild(option);
}

function updateCheckboxes(domElement,propertytype,list){
	if(typeof(list)=="undefined")
	{
		return;
	}
	var ul = document.createElement('ul');
	for(var i=0; i<list.length;i++)
	{
		var li = document.createElement('li');

		ul.appendChild(li);

		var label = document.createElement('label');
		label.htmlFor = list[i].k;

		label.appendChild(document.createTextNode(list[i].k));

		var checkbox = document.createElement('input');
		checkbox.type = "checkbox";
		checkbox.name = list[i].i;

//		if(list[i].v==1)
			checkbox.disabled = "true";


		Form.Element.disable(checkbox);

		li.appendChild(checkbox);
		li.appendChild(label);

		var h3 = document.createElement('h3');
		h3.appendChild(document.createTextNode(propertytype));
	}

	var li = document.createElement('li');
	li.appendChild(h3);
	li.appendChild(ul);

	domElement.appendChild(li);


}

function getText(el){
	var text = '';
	if (el != null) {
		if (el.childNodes){
			for(var i=o; i<el.childNodes.length;i++){
				var childNode = el.childNodes[i];
				if(childNode.nodeValue != null)
					text = text + childNode.nodeValue;
			}
		}
	}
}

function mysorter(evt){
	var child = Event.element(evt);

	child=child.parentNode.parentNode;

	if(child.id==1)	// Sort on Office Type
	{
		if(sort==1)
			sort=-sort; // reverse the order, if the sort column was selected for the second time
		else
			sort=1;
	}
	else if(child.id==3)	// Sort on City
	{
		if(sort==3)
			sort=-sort;	// reverse the order, if the sort column was selected for the second time
		else
			sort=3;
	}
	else if(child.id==5)	// Sort on Country
	{
		if(sort==2)
			sort=-sort;	// reverse the order, if the sort column was selected for the second time
		else
			sort=2;
	}
	

	if(param!="")
		var temp_param = param+"&page="+page+"&sort="+sort;
	else
		var temp_param = "page="+page+"&sort="+sort;

	// Set up an ajax request with the right sorting
	var elm = Event.element(evt);
	setCookie("sort",sort,2);
	new Ajax.Request(url,
		{
		  method:'get',
		  parameters: temp_param,
		  onCreate: showLoad,
		  onComplete: hideLoad,
		  onFailure: showFailureMessage,
		  onSuccess: updateResult
		}
	);
}



function updateResult(req){
	if(indexpage)
		changeToResultLayout();

	var table = document.createElement('table');
	table.id = "tblSort";
	var thead = document.createElement('thead');
	var tbody = document.createElement('tbody');
	var tfoot = document.createElement('tfoot');

	table.appendChild(thead);
	table.appendChild(tbody);
	table.appendChild(tfoot);


	var jsontext = req.responseText.replace(/char(10)/g, " ");



	var jsonData = jsontext.evalJSON();

	accumulatedinfo(jsonData.acc);	// Add acc. info to the page


	var result = jsonData.offices;
	jsonOffices = result;

	var row = 0;
	// Loop over the results



	var rest = total%pagesize;
	var pages = (total-rest)/pagesize;
	if(rest>0)
		pages++;					// the extra page includes the rest

	var start = 0;					// The result number
	if (page == pages && page > 1)  // we are on the last page
		start = pagesize-rest;



	if(total>0)
	{
		// Create the thead
		var fields = ['Company Name','Type of Office','Service','City','Postal/Zipcode','Country'];
		var tr = document.createElement('tr');
		for(var i=0; i<fields.length;i++)
		{
			var th = document.createElement('th');

			th.id = i;
			if(i==0)
				setClass(th,'padding21');

			var div = document.createElement('div');
			div.style.height="18px";
			div.style.paddingBottom="7px";
			div.style.float="left";

			var span = document.createElement('span');
			span.style.position="relative";
			span.style.top="0px";
			var tn = document.createTextNode(fields[i]);
			span.appendChild(tn);
			div.appendChild(span);

			th.appendChild(div);
			var img = document.createElement('img');
			img.src = "graphics/sort_i.png";
			img.style.position="relative";
			img.style.top="5px";
			img.style.padding="0px";
			img.style.margin="0px";

			if(i==1 || i==3 || i==5)  // Office type, Country, City
			{

				Event.observe(th, 'click', mysorter, false);
				setClass(th,'sort ');

				if(i==1){
					img.style.top="5px";
					div.style.width="120px";
					if(sort==1)
						img.src = "graphics/sort_a.png";
					else if(sort==-1)
						img.src = "graphics/sort_b.png";
				}
				if(i==3){
					div.style.width="70px";
					if(sort==3)
						img.src = "graphics/sort_a.png";
					else if(sort==-3)
						img.src = "graphics/sort_b.png";
				}
				if(i==5){
					div.style.width="80px";
					if(sort==2)
						img.src = "graphics/sort_a.png";
					else if(sort==-2)
						img.src = "graphics/sort_b.png";
				}
				div.appendChild(img);
			}
			else
			{
				div.style.paddingTop="7px";
				div.style.height="10px";
			}
			tr.appendChild(th);
		}
		thead.appendChild(tr);
		// end of creating table head



		// Create the table data
		for(var i=start; i<result.length;i++)
		{
			row = i%2+1;
			clName="diff"+row;
			var tr = document.createElement('tr');
			// Loop over the attributes
				tr.id = result[i].i;
				var td = document.createElement('td');

				setClass(td,'pad22');	// add some padding to the first column

				var b = document.createElement('b');
				b.appendChild(document.createTextNode(result[i].n));
				td.appendChild(b);
				td.appendChild(document.createElement('br'));
				td.appendChild(document.createTextNode(result[i].p));

				setClass(td,clName+ " padding21" );
				tr.appendChild(td);

				var td = document.createElement('td');
				td.appendChild(document.createTextNode(result[i].o));
				setClass(td,clName);
				tr.appendChild(td);

				var td = document.createElement('td');
				td.innerHTML=result[i].s.replace(/,/g, "<br/>");
				setClass(td,clName);
				tr.appendChild(td);

				var td = document.createElement('td');
				td.appendChild(document.createTextNode(result[i].c));
				setClass(td,clName);
				tr.appendChild(td);

				var td = document.createElement('td');
				td.appendChild(document.createTextNode(result[i].z));
				setClass(td,clName);
				tr.appendChild(td);

				var td = document.createElement('td');
				td.appendChild(document.createTextNode(result[i].cn));
				setClass(td,clName);
				tr.appendChild(td);

			tbody.appendChild(tr);
			Event.observe(tr, "click", showOfficeDetails, false);
		}
	}
	else
	{


		var tr = document.createElement('tr');
		var td = document.createElement('td');
		var b = document.createElement('b');
		b.appendChild(document.createTextNode("Sorry, we did not find what you were looking for, please try again."));
		td.appendChild(b);
		td.style.backgroundColor="#8fcf5f";
		td.style.padding="22px";
		td.style.colspan=6;
		tr.appendChild(td);
		tbody.appendChild(tr);


		var tr = document.createElement('tr');
		var td = document.createElement('td');
		tr.appendChild(td);
		td.innerHTML="<h1>Quick Finder</h1><p>In the freetext input field you are able to search for a variety of data. For a complete list of search options, click 'Guide on how to find'.</p><br/><b>Search text</b><ol><li>Check that the spelling is correct</li></ol><b>Double quotes</b><ol><li>Specify the exact search criteria</li><li>Make sure that spacing between the search text and the double quotes is removed</li></ol><b>Spacing</b><ol><li>Please note that spacing is necessary when using more than one search criteria</li><li>The solutions does not support ',' and '+'</li></ol><h1>Guided Finder</h1><p>The 'Guided Finder' lists all our options in advance, your result will therefore be narrowed down and 0 results is limited.</p><br/><b>Location search</b><ol><li>Chose the region, country and city in the dropdown boxes</li><li>Click 'Find'</li></ol><b>Search by office type, service and/or business function</b><ol><li>Tick of an office type, service and/or business function</li><li>Click 'Find'</li></ol><p>Note: You don't have to take action on all options; you can click on 'Find' at any time.</p><p>If you have run out of alternatives contact DSV Group Marketing on e-mail: <a href=\"mailto:marketing@dsv.com\">marketing@dsv.com</a></p><br/><br/><br/>";
		tr.appendChild(td);
		td.id = "noresult";
		tbody.appendChild(tr);

	}

	var br = document.createElement('br');
	var div = document.createElement('div');

	if(total>pagesize)
		div.appendChild(pagination(""));	// The parameter is for the classname
	div.appendChild(table);

	if(total>pagesize)
		div.appendChild(pagination("2"));	// The parameter is for the classname

	$('result').update(div); 
	addHighlightListeners();
}

function accumulatedinfo(acc){
	var div = document.createElement('div');
	var h1 = document.createElement('h1');
	var ul = document.createElement('ul');
	h1.appendChild(document.createTextNode("Result list"));
	h1.style.color="#002664";
	var li = document.createElement('li');
	li.appendChild(h1);
	ul.appendChild(li);
	for (var key in acc)
	{
		var li = document.createElement('li');
		var txtNode = document.createTextNode(key + ": " + acc[key]);
		if(key=="Total Results")
		{
			total = acc[key];
			var b = document.createElement('b');
			b.appendChild(txtNode);
			b.style.color="#002664";
			li.appendChild(b);
		}
		else
			li.appendChild(txtNode);
		setClass(li,'borderleft');
		ul.appendChild(li);
	}
	setClass(li,'borderleftright'); // Change the last element to have borden on both sides
	div.appendChild(ul);

	// PRINTALL icon	
	var img = document.createElement('img');
	img.src = "graphics/print-icon_white.png";


	var print_li = document.createElement('li');
	print_li.id="printitem";

	print_li.appendChild(img);
	print_li.appendChild(document.createTextNode(' Print All'));
	
	ul.appendChild(print_li);


	$('accumulatedinfo').update(div);
	Event.observe('printitem', 'click',printall,false);
}

function printall(){	
/*	 window.open('printall.html?no='+total,'printall','location=1,status=1,toolbar=1,menubar=1,scrollbars=1,resizable=1,width=715,height=540'); */
	 window.open('printall.html?no='+total,'printall','scrollbars=1,width=732,height=553');
}

function pagination(c){
	var rest = total%pagesize;
	var pages = (total-rest)/pagesize;

	if(rest>0)
		pages++;	// the extra page includes the rest

	var p = document.createElement('p');
	for(var i=1;i<=pages;i++)
	{
		if((i<21 && i%20==0) || (i>=21 && (i-20)%15==0))
			p.appendChild(document.createElement('br'));

		var from = (i*pagesize)-pagesize+1;
		var to = i*pagesize;
		if(i==pages)
			to = total;
		// links to first and previous page


		if(i==1)
		{
			if(page==i)
			{
				var elm = document.createElement('span');
				setClass(elm,'page');
				elm.appendChild(document.createTextNode("«"));
				p.appendChild(elm);

				var elm = document.createElement('span');
				setClass(elm,'page');
				elm.appendChild(document.createTextNode("‹"));
				p.appendChild(elm);
			}
			else
			{
				var elm = document.createElement('span');
				setClass(elm,'pagelink');
				elm.id = 1;
				elm.appendChild(document.createTextNode("«"));
				Event.observe(elm,'click',changeToPage,false);
				p.appendChild(elm);

				var elm = document.createElement('span');
				setClass(elm,'pagelink');
				elm.id = (page-1);
				elm.appendChild(document.createTextNode("‹"));
				Event.observe(elm,'click',changeToPage,false);
				p.appendChild(elm);
			}
		}
		// Links with resultnumbers
		if (page==i)
		{
			var elm = document.createElement('span');
			setClass(elm,'page');
			elm.appendChild(document.createTextNode(from+"-"+to));
			p.appendChild(elm);
		}
		else
		{
			var elm = document.createElement('span');
			setClass(elm,'pagelink');
			elm.id = i;
			elm.appendChild(document.createTextNode(from+"-"+to));
			Event.observe(elm,'click',changeToPage,false);
			p.appendChild(elm);
		}
		// add links to next and last page
		if(i==pages)
		{
			if(page==i)
			{
				var elm = document.createElement('span');
				setClass(elm,'page');
				elm.appendChild(document.createTextNode("›"));
				p.appendChild(elm);

				var elm = document.createElement('span');
				setClass(elm,'page');
				elm.appendChild(document.createTextNode("»"));
				p.appendChild(elm);
			}
			else
			{
				var elm = document.createElement('span');
				setClass(elm,'pagelink');
//				elm.id = (page+1); // doesn't work :-s
				elm.id = (page-1+2);
				elm.appendChild(document.createTextNode("›"));
				Event.observe(elm,'click',changeToPage,false);
				p.appendChild(elm);

				var elm = document.createElement('span');
				setClass(elm,'pagelink');
				elm.id = pages;
				elm.appendChild(document.createTextNode("»"));
				Event.observe(elm,'click',changeToPage,false);
				p.appendChild(elm);
			}
		}
	}

	var paginationDiv = document.createElement('div');
	setClass(paginationDiv,'pagination'+c);	// The c is to the a different class for the bottom pagination
	paginationDiv.appendChild(p);
	return paginationDiv;
}

function changeToPage(evt){
	var elm = Event.element(evt);
	page = elm.id;

	new Ajax.Request(url,
		{
		  method:'get',
		  parameters: param+"&page="+page+"&sort="+sort,
		  onCreate: showLoad,
		  onComplete: hideLoad,
		  onFailure: showFailureMessage,
		  onSuccess: updateResult
		}
	);
}


function properties()
{
	if(more)
	{
		// Do nothing if we are on the index page
		if(!indexpage)
		{
//			$('more').update('less');
			$('moreoptions').update('<b>› <span id="more">Less options</span></b>');
			Element.setStyle('topresult', {height:'268px'} );
			Element.show( 'propertynames' );
			Element.show( 'subheader' );

		}
	}
	else
	{
//		$('more').update('more');
		$('moreoptions').update('<b>› <span id="more">More options;</span></b> Type of office, services and business functions');
		Element.setStyle('topresult', {height:'116px'} );
		Element.hide( 'propertynames' );
		Element.hide( 'subheader' );
	}
}



function toggled(){
	more = !more;
	properties();
}

function addObservers(evt) {
	Event.observe($('region').childNodes[0], 'change', region_changed, false);
	Event.observe($('country').childNodes[0], 'change', country_changed, false);
	Event.observe($('city').childNodes[0], 'change', city_changed, false);
	Event.observe('guidedfind', 'click', submit, false);
	Event.observe('quickfind', 'click', submit, false);
}

function getkey(evt){
	if(evt.keyCode==13)
		submit(evt);
}
function region_changed(evt){

//	Form.Element.disable($('country').childNodes[0]);
//	Form.Element.disable($('city').childNodes[0]);
	disableCities();
	var element = Event.element(evt);

	var id = $F(element);

	if(id=="")
		id=-1;

	if(id==-1)
	{

		for(var i=0; i<pninit.length; i++)
		{
			if(pninit[i]!=14)
			{
				var elm = $('check'+pninit[i])
				elm.parentNode.childNodes[1].style.color="#002664";
				Form.Element.enable(elm);
			}
		}

	}

	url = '/gof/countries_for_region.json';
	param = 'id='+id
	if(location.protocol!="http:")
		url = 'json/countriesforregion.json';

	// Get the updated list of countries
	new Ajax.Request(url,
		{
		  method:'get',
		  parameters: param,
		  onCreate: showLoad,
		  onComplete: hideLoad,
		  onFailure: showFailureMessage,
		  onSuccess: updatePage
		}
	);
}

function existIn(x,arr){
	for (var i=0; i<arr.length; i++)
		if(arr[i]==x)
			return true;
	return false;
}

function country_changed(evt){

	// Reset the city dropdown
	var sel = $('city').childNodes[0].childNodes[0].selected = true;
	Form.Element.disable($('city').childNodes[0]);
	var element = Event.element(evt);
	var id = $F(element);
//	disableCities();

	if(id=="")
		id=-1;

	if(id==-1)
	{
			// Select country is chosen, so get the pn list på the selected region

			var id = $F($('region').childNodes[0])
			if(id=="")
			{
				for(var i=0; i<pninit.length; i++)
				{
					if(pninit[i]!=14)
					{
						var elm = $('check'+pninit[i])
						elm.parentNode.childNodes[1].style.color="#002664";
						Form.Element.enable(elm);
					}
				}			
			}
			else
			{
				url = '/gof/countries_for_region.json';
				param = 'id='+id;
				if(location.protocol!="http:")
					url = 'json/countriesforregion.json';
			
				// Get the updated list of countries
				new Ajax.Request(url,
					{
					  method:'get',
					  parameters: param,
					  onCreate: showLoad,
					  onComplete: hideLoad,
					  onFailure: showFailureMessage,
					  onSuccess: updatePage
					}
				);
			}

	}
	else
	{
		if(id=="")
			return;
		url = '/gof/cities_for_country.json';
	
		param = 'id='+id;
		
	
		if(location.protocol!="http:")
			url = 'json/citiesforcountry.json'+id;
	
		new Ajax.Request(url,
			{
			  method:'get',
			  parameters: param,
			  onCreate: showLoad,
			  onComplete: hideLoad,
			  onFailure: showFailureMessage,
			  onSuccess: updatePage
			}
		);
	}
}

function city_changed(evt){
	var element = Event.element(evt);
	var city = $F(element);

	if(city=="select city" || city=="")
		return;

	url = 'props_for_city.json';
	param = 'city='+city;

	if(location.protocol!="http:")
		url = 'json/props_for_city.json'+city;

	// Get the updated list of countries

	new Ajax.Request(url,
		{
		  method:'get',
		  parameters: param,
		  onCreate: showLoad,
		  onComplete: hideLoad,
		  onFailure: showFailureMessage,
		  onSuccess: updatePage
		}
	);
}

function submit(evt){

	page = 1; // The default page
	sort = 1; // The default sort method

	var button = Event.element(evt);
	Event.stop(evt);

	url = "";
	param = "";
	var searchType = "";

	// Quickfind
	if(button.id=="quickfind" || evt.keyCode==13)
	{
		var tmp = $('query').value.replace(/\%/g, "%25");// replace percent
		tmp = tmp.replace(/&/g, "%26");					// replace ampersand so query is not split
		tmp = tmp.replace(/\#/g, "%23");				// replace hashmark so query is not truncated
		tmp = tmp.replace(/\?/g, "%3F");				// replace questionmark so first part isn't omitted
		tmp = tmp.replace(/\+/g, "%2B");				// replace plus, because whitespace is replaced with + in the uriComponentEncode step
		param = "query="+tmp;
		url = '/gof/offices_search.json';
		
		if(location.protocol!="http:")
			url = 'json/offices_search.json';
		more=false;

	}
	// Guidedfind
	else
	{
		var id_region 	= $F($('region').childNodes[0]);
		var id_country 	= $F($('country').childNodes[0]);
		var city 		= $F($('city').childNodes[0]);


		if(city!="select city" && city!="" && city!="no cities available")
		{

			url = '/gof/offices_for_country.json';
			param = 'id='+id_country+'&city='+city;
			if(location.protocol!="http:")
				url = 'json/offices_for_country.json';
			searchType="country";			

		}
		else if(id_country!="" && id_country!="no countries available")
		{

			url = '/gof/offices_for_country.json';
			param = 'id='+id_country;
			if(location.protocol!="http:")
				url = 'json/offices_for_country.json';
			searchType="country";
		}
		else if(id_region!="")
		{

			url = '/gof/offices_for_region.json';
			param = 'id='+id_region;

			if(location.protocol!="http:")
				url = 'json/officesforregions.json';
			searchType="region";
		}
		else
		{
			url = '/gof/offices_for_region.json?id=-1';
			if(location.protocol!="http:")
				url = 'json/officesforregions.json';
			searchType="regionid=-1&";
		}

		// This is the end of the guided find branch

		var form = $('guidedfind').parentNode.parentNode;
		if(param!="")
			param+="&"+$(form).serialize();
		else
			param =$(form).serialize();

		if(param!="")
			more=true
	}
	more=false;

	// find the offices
	//	var pagesort = "&page="+page+"&sort="+sort;
	setCookie("searchUrl",searchType+param,2);
	new Ajax.Request(url,
		{
		  method:'get',
		  parameters: param,
		  onCreate: showLoad,
		  onComplete: hideLoad,
//		  onFailure: function(req) {showname(req.responseText)},
//		  onException: function(t,e) {showname(e);},
		  onSuccess: updateResult
		}
	);
}



function showFailureMessage(){

	// Do nothing
}

function gup( name )
{
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp( regexS );
  var results = regex.exec( window.location.href );
  if( results == null )
    return "";
  else
    return results[1];
}

function removeChildren(elm){
	element = $(elm);
	$A(element.childNodes).each(function(e){
		  e.parentNode.removeChild(e);
	});
}


/////////////////////
function getCookie(c_name)
{
	if (document.cookie.length>0)
	{
		c_start=document.cookie.indexOf(c_name + "=")
		if (c_start!=-1)
		{
			c_start=c_start + c_name.length+1
			c_end=document.cookie.indexOf(";",c_start)
			if (c_end==-1)
				c_end=document.cookie.length
			return unescape(document.cookie.substring(c_start,c_end))
		}
	}
	return ""
}
function setCookie(c_name,value,expiredays)
{
	var exdate=new Date()
	exdate.setDate(exdate.getDate()+expiredays)
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : "; expires="+exdate.toGMTString())
}

function checkboxIsChanged(evt)
{
	oldType=getCookie('type');
	var type="";
	if($('adv').checked)
		type = "advanced";
	else
		type = "simple";
	setCookie('type',type,365);
}


function getParameters() {

   var params = new Array();
   var urlpar = window.location.href;
   var paramsStart = urlpar.indexOf("?");
   var hasMoreParams = true;

   if(paramsStart != -1){

     var paramString = urlpar.substr(paramsStart + 1);
     var params = paramString.split("&");
     for(var i = 0 ; i < params.length ; i++) {

       var pairArray = params[i].split("=");

       if(pairArray.length == 2){
         params[pairArray[0]] = pairArray[1];
       }

     }
     return params;
   }
   return null;
}


//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.org
//
function getPageScroll(){

	var yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}

	arrayPageScroll = new Array('',yScroll)
	return arrayPageScroll;
}

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.com
// Edit for Firefox by pHaez
//
function getPageSize(){

	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth;
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}


	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = xScroll;
	} else {
		pageWidth = windowWidth;
	}

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
	return arrayPageSize;
}
function showSelectBoxes(){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}
}

function hideSelectBoxes(){
	var selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "hidden";
	}
}

function showLoad(){
	document.body.appendChild($('modal2'));				// Move modal to the dom
	$('modal2').appendChild($('trans2')); 				// Move trans to the dom
	$('trans2').style.height = ((getPageScroll()[1] + 300) + 'px');
	$('modal2').appendChild($('loading')); 				// Move loading to the dom
}

function hideLoad(){
	$('hidden').appendChild($('loading'));	// Move loading to the hidden area
	$('hidden').appendChild($('trans2'));	// Move trans to the hidden area
	$('hidden').appendChild($('modal2'));	// Move modal to the hidden area
}
///////////////////////////////////////////////
/// Functions for coloring the result table ///
///////////////////////////////////////////////
function ascendDOM(e, target) {
  while (e.nodeName.toLowerCase() != target && 
      e.nodeName.toLowerCase() != 'html')
    e = e.parentNode;
  return (e.nodeName.toLowerCase() == 'html') ? null : e;
}

function setClass(element,clName)
{
	if (navigator.appName=="Microsoft Internet Explorer")
		element.className=clName;
	else
		element.setAttribute("class",clName);
}

function setCellColor(element,clName)
{
	var pad = false;
	if(element.className.length>12)
		pad=true;		
	// If clName is empty, chenge to normal css
	if (clName==" ") 
	{
		clName = element.className.substr(0,5);
	}
	else
		clName = element.className.substr(0,5) + clName; 
	
	if(pad)
		clName+=" padding21";
	setClass(element,clName);
}

function setRowColor(element,clName)
{
	var cells = element.getElementsByTagName('td');
		for (i=0;i<cells.length;i++)
			setCellColor(cells[i],clName);
}

function hover(e)
{
  var el;
  if (window.event && window.event.srcElement)
    el = window.event.srcElement;
  if (e && e.target)
    el = e.target;
  if (!el) return;
  var parent_row = ascendDOM(el, 'tr');
  if (parent_row == null)  return;	
  setRowColor(parent_row,'hove');
}


function normal(e)
{
 var el;
  if (window.event && window.event.srcElement)
    el = window.event.srcElement;
  if (e && e.target)
    el = e.target;
  if (!el) return;
  var parent_row = ascendDOM(el, 'tr');
  if (parent_row == null)  return;	
  setRowColor(parent_row,' ');
}

function addHighlightListeners()
{ 
  if (!document.getElementsByTagName) return;
  var rows = document.getElementsByTagName('tr');
  for (var i = 1; i < rows.length; i++) {
    Event.observe(rows[i], "mouseover", hover, false);
    Event.observe(rows[i], "mouseout", normal, false);
  } 
}

function setCookie(c_name,value,expiredays)
{
	var exdate=new Date()
	exdate.setDate(exdate.getDate()+expiredays)
	document.cookie=c_name+ "=" +escape(value)+
	((expiredays==null) ? "" : "; expires="+exdate.toGMTString())
}
