


//Function for building av querystring out of a searchstring
function buildQuery(searchFieldId, fields, split, convertDate) 
{
	var search = new String(document.getElementById(searchFieldId).value);
	
	if (convertDate)
		search = queryToDate(search);
	
	var stringParts = null;
	
	if (split)
	stringParts = search.split(" "); else
	stringParts = new Array(search);
	
	var query = new String();
	for (var n = 0; n < fields.length; n++)
	for (var m = 0; m < stringParts.length; m++) {
		if (query != '')
		query += ' or ';
		query += fields[n] + " CONTAINS '" + stringParts[m] + "'";
	}
	return query;
}


function buildPublicationQuery(searchModeFieldId, textFieldId, textSearchFields, dropdowns)
{
	var query = buildQuery(textFieldId, textSearchFields);	
	var searchMode = $("#" + searchModeFieldId).val();
	
	if (searchMode != 'advanced')
	{
		if (query == '')
			return "title CONTAINS 'a' or title CONTAINS 'e' or title CONTAINS ' '";
		return query;
	}
		
	if (query != '')
		query = '(' + query + ')';
	
	for (var n=0; n<dropdowns.length; n++)
	{
		var select = document.getElementById(dropdowns[n][0]);

		if (select.value != '')
		{
			if (query != "")
				query += " AND ";

			query += dropdowns[n][1] + " LIKE '" + select.value + "'";
		}
	}

	if (query == '')
			return "title CONTAINS 'a' or title CONTAINS 'e' or title CONTAINS ' '";

	return query;	
}


function queryToDate(query) 
{
	var q = new String(query);
	
	if (q.length == 8) {
		var day = parseInt(q.substr(0, 2));
		var month = parseInt(q.substr(2, 2));
		var year = parseInt(q.substr(4, 4));
		
		if (day > 0 && day < 32 && month > 0 && month < 13 && year > 1980 && year < 2100)
		q = "" + year + "-" + month + "-" + day;
	} else if (q.length == 4) {
		var day = parseInt(q.substr(0, 2));
		var month = parseInt(q.substr(2, 2));
		var year = new Date().getFullYear();
		
		var now = new Date();
		var newDate = new Date();
		
		newDate.setFullYear(year, month - 1, day);
		if (newDate.getTime() > now.getTime())
		year -= 1;
		
		if (day > 0 && day < 32 && month > 0 && month < 13 && year > 1980 && year < 2100)
		q = "" + year + "-" + month + "-" + day;
	}
	
	return q;
}



//Function to open a link in a new window
var newWin = null;
function popUp(strURL, strType, strHeight, strWidth) {
	if (newWin != null && ! newWin.closed)
	newWin.close();
	var strOptions = "";
	if (strType == "popup")
	strOptions = "location=0,menubar=0,resizable=1,scrollbars=0,status=0,titlebar=0,toolbar=0,height=" + strHeight + ",width=" + strWidth;
	newWin = window.open(strURL, 'newWin', strOptions);
	newWin.focus();
}
//Function for expanding or collapsing a chosen tag in the XSL template
function expand(thistag) {
	if (document.getElementById(thistag)) {
		styleObj = document.getElementById(thistag).style;
		if (styleObj.display == 'none') {
			styleObj.display = '';
		} else {
			styleObj.display = 'none';
		}
	}
}
function MM_jumpMenu(targ, selObj, restore) {
	//v3.0
	eval(targ + ".location='" + selObj.options[selObj.selectedIndex].value + "'");
	if (restore) selObj.selectedIndex = 0;
}
function externalLinks() {
	if (! document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i = 0; i < anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external") {
			anchor.target = "_blank";
		}
	}
}
/*
Method: pollValidate

Validation for a poll.

Parameters:

formId - String, form/@id.
*/
function pollValidate(formId) {
	var form = document.getElementById(formId)
	var el = form.elements;
	var checked = false;
	for (var i = 0; i < el.length; i++) {
		if (el[i].checked == true)
		checked = true;
	}
	if (! checked) {
		if (formHasType(form, 'checkbox'))
		alert('You have to select at least one alternative first!'); else
		alert('You have to select an alternative first!');
	} else {
		form.submit();
	}
}

/*
Function: pollIsMultiple

Checks if the form has an element with the given type.

Parameters:

form - Object, HTMLFormElement.
typeName - String, type name.

Returns:

true || false
*/
function formHasType(form, typeName) {
	var hasType = false;
	for (var i = 0; i < form.elements.length; i++) {
		if (form.elements[i].type == typeName) {
			hasType = true;
			break;
		}
	}
	return hasType;
}


/*
function changeFontSize(site, size) {
	
	var root = (site == 'bistandsaktuelt') ? '' : '/site/0';
	
	switch (size)
	{
	
		case 'normal':
			document.getElementById('fontsize').href = root + '/_public/' + site + '/css/fontsize_normal.css';
			break;

		case 'large':
			document.getElementById('fontsize').href = root + '/_public/' + site + '/css/fontsize_large.css';
			break;
		
		case 'largest':
			document.getElementById('fontsize').href = root + '/_public/' + site + '/css/fontsize_largest.css';
			break;
				
		default:
			var activeFontSize = getActiveFontsize();
			switch (activeFontSize) {
				
				case 'normal':
					document.getElementById('fontsize').href = root + '/_public/' + site + '/css/fontsize_large.css';
					if (site != "bistandsaktuelt")
						alert("set large");
					document.cookie="noradFontsize=large";
					break;
				
				case 'large':
					document.getElementById('fontsize').href = root + '/_public/' + site + '/css/fontsize_largest.css';
					if (site != "bistandsaktuelt")
						alert("set largest");
					document.cookie="noradFontsize=largest";
					break;
				
				default:
					document.getElementById('fontsize').href = root + '/_public/' + site + '/css/fontsize_normal.css';
					if (site != "bistandsaktuelt")
						alert("set normal");
					document.cookie="noradFontsize=normal";
			}
	}
	
	if (site == "bistandsaktuelt")
	{
		setTimeout ("positionMenuElements()", 1000);
	}
	
		
}







function getActiveFontsize() {

	var fontsize = document.getElementById('fontsize').href;
	
	if (fontsize.indexOf('largest') != - 1) 
		return 'largest';
	else if (fontsize.indexOf('large') != - 1) 
		return 'large'; 
	
	return 'normal';
}


*/




/**
loading popup
**/
function loadPopup(aForm){ 
     var dialog = $("#" + aForm); 
     dialog.fadeIn("slow");  
          return false;
}

/**
closing popup
**/
function disablePopup(aForm){ 
     var dialog = $("#" + aForm); 
     dialog.fadeOut("slow");  
     return false;
}


function toggle(aForm) {
     $("#" + aForm).toggle("fast");
     var icon = new String($("#" + aForm + "_img").attr("src"));
     
     if (icon.indexOf("expand.png") > 0)
     	icon = icon.replace("expand", "collapse");
     else
     	icon = icon.replace("collapse", "expand");
     
     $("#" + aForm + "_img").attr("src", icon);
     
     return false;
};


$(document).ready( function() {
    
    $('a[rel="external"]').click( function() {
        window.open( $(this).attr('href') );
        return false;
    });
    
});

function checkForm (aForm) {

//var var_name = $('#cfrom_toSender').attr('checked')?1:0;
//alert( var_name);

//alert( $("input#cfrom_toSender") ); 


    if( $("input[@name='from_toSender']:checked").val() == "on")   // get the value from a checked checkbox
    { $("input[@name='cc']").val($("input#cfrom_email").val());
    //alert( $("input[@name='cc']").val() );
    }
    
}

function positionMenuElements()
{
	
	for (var id = 1;id <= 9; id++)
	{
		
		var tab = $("#menuTop_" + id);
		var menu = $("#menuSub_" + id);
		var container = $("#topmenu");
		
		var tabPosition =  tab.position();
		var containerPosition = container.position();

		var tabPosition = tabPosition.left; // - containerPosition.left;
		var menuPosition = tabPosition + Math.ceil((tab.width() - menu.width()) / 2);

		if (menuPosition < 0)
			menuPosition = 0;
		else if (tabPosition + menu.width() > 990)
			menuPosition = 990 - menu.width();
		
		menu.css("left", menuPosition);
	}
	//
};





function trim(str) {
	str = str.replace(/^\s+/, '');
	for (var i = str.length - 1; i >= 0; i--) {
		if (/\S/.test(str.charAt(i))) {
			str = str.substring(0, i + 1);
			break;
		}
	}
	return str;
}


function mp3PlayertogglePopout(key, position, image)
{
	var height = (image == "true") ? 470 : 220;
	
	var url = new String(window.location);
	
	if (url.lastIndexOf("Avspiller%20Mp3?key") > 0)
	{
		window.close();
		return;
	}		
	else if (url.lastIndexOf("bistandsaktuelt") > 0)
		url = "http://bistandsaktuelt.no/Multimedia/Avspiller%20Mp3?key=" + key;
	else
		url = "http://norad.no/Avspiller%20Mp3?key=" + key;
		
	popUp(url, "popup", height, 490)
}

function multimedia_facebook(key, title)
{

	var url = new String(window.location);
	var u = "";
	var t = "";
	
	if (url.lastIndexOf("bistandsaktuelt") > 0)
	{
		u="http://bistandsaktuelt.no/Multimedia/Multimediearkiv/" + key + ".cms";
		t=title;
	}
	
	else if (url.lastIndexOf("Avspiller%20Mp3?key") > 0)
	{
		u=window.opener.document.location;
		t=window.opener.document.title;
	}
	
	else
	{
		t = document.title;
		u = url;
	}

	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=630,height=440');
	return false;
}

function countCharOccurences(string, chr)
{
	var str = new String(string);
	var count = 0;
	for (var n=0; n<str.length; n++) {
		if (str.charAt(n) == chr)
			count++;
	}
	return count;
}

function findNextChar(string, chr, start)
{
	var str = new String(string);
	for (var n=start; n<str.length; n++) {
		if (str.charAt(n) == chr) {
			return n;
		}
	}
	
	return -1;
}

function findPrevChar(string, chr, start)
{
	var str = new String(string);
	for (var n=start; n>=0; n--) {
		if (str.charAt(n) == chr) {
			return n;
		}
	}
	
	return -1;
}

function replaceCharsInSubstring(string, chrIn, chrOut, start, end)
{
	var str = new String(string);
	var before = str.substring(0, start);
	var after = str.substring(end+1);
	var between = str.substring(start, end+1);
	between = replaceAll(between, chrIn, chrOut);
	
	var result = new String("" + before + between + after);
	return result;
}

function replaceAll(string, search, replace)
{
	var result = new String("");
	for (var n=0; n<string.length; n++) {
		if (string.charAt(n) == search) {
			result = result + replace;
		}
		else {
			result = result + string.charAt(n);
		}
	}
	
	return result;
}

function combineTerms(string, start)
{
	var pos1 = findNextChar(string, "\"", start);
	var pos2 = findNextChar(string, "\"", pos1 + 1);
	
	if (pos1 > -1 && pos2 > pos1)
	{
		string = replaceCharsInSubstring(string, " ", "_", pos1, pos2);
		string = combineTerms(string, pos2 + 1);
	}
	
	return string;
}

function unconbineTerms(str, start)
{
	var pos1stUnderscore = findNextChar(str, "_", start);
	
	if (pos1stUnderscore == -1)
		return str;
	
	var pos1stSpace = findPrevChar(str, " ", pos1stUnderscore);
	
	if (pos1stSpace == -1)
		pos1stSpace == 0;
		
	var pos2ndSpace = findNextChar(str, " ", pos1stUnderscore);
	if (pos2ndSpace == -1)
		pos2ndSpace = str.length;
	
	var before = str.substring(0, pos1stSpace +1);
	var after = str.substring(pos2ndSpace + 1);
	var between = replaceAll(str.substring(pos1stSpace +1, pos2ndSpace), "_", " ");
	
	var result = new String(before + "\"" + between + "\" " + after);
	
	if (pos2ndSpace < str.length)
		return unconbineTerms(result, pos2ndSpace);
		
	return result;

}

function prepareSearch(query) 
{
	var str = new String(query);
	var quotes = countCharOccurences(str, "\"");
	str = combineTerms(str, 0);
	return replaceAll(str, "\"", "");
}

function unprepareSearch(query)
{
	var str = new String(query);
	if (countCharOccurences(str, "_") <= 0) {
		return query;
	}
	
	return unconbineTerms(str, 0);	
}














