var ns4=document.layers;
var ns6=document.getElementById && !document.all;
var ie4=document.all;
var opr=navigator.userAgent.indexOf("Opera");

/**** Error reporting ****/

window.onerror = function(errorMessage, url, line) {
	var loggerUrl = SITE_ROOT+"/?script=frmw.script.error_report";
	var parameters = "&description=" + escape(errorMessage)
		+ "&url=" + escape(url)
		+ "&line=" + escape(line)
		+ "&parent_url=" + escape(document.location.href)
		+ "&user_agent=" + escape(navigator.userAgent);
  
	/** Send error to server */
	new Image().src = loggerUrl + parameters;
  
	//alert('En feil har oppstått. Feilen er innrapportert og vi vil se på saken. Vi anbefaler at du laster siden på nytt.');
};

/**** Admin ****/

function submitbutton(task, admin_id) {
	$('.adminform input[name=task]').val(task);
	if(admin_id>0) {
		$('.adminform input[name=admin_id]').val(admin_id);
	}
	$('.adminform').submit();
}

function switchAllCheckboxes(num, is_checked) {
	for (var j = 0; j < num; j++) {
		box = eval("document.admin_form.checkbox_"+j);
		box.checked = is_checked;
		if(!is_checked)
			document.admin_form.boxchecked.value = 0;
		else
			document.admin_form.boxchecked.value = num;
   }
}

function toggleCheck(checkbox) {
	checkelement = document.getElementById(checkbox);
	if(checkelement.checked) {
		checkelement.checked = false;
		document.admin_form.boxchecked.value--;
	}
	else {
		checkelement.checked = true;
		document.admin_form.boxchecked.value++;
	}
}

function toggleImage(myImage, image1, image2) {
	if(myImage.src==image1)
		myImage.src=image2;
	else
		myImage.src=image1;

}

function rowHoverState(element) {
	element.className = 'admin_list_tr_hover';
}

function rowDefaultState(element, num) {
	if(num==1) {
		element.className = 'admin_list_tr_row_1';
	}
	else {
		element.className = 'admin_list_tr_row_2';
	}
}

function isChecked(ischecked) {
	if (ischecked == true){
		document.admin_form.boxchecked.value++;
	}
	else {
		document.admin_form.boxchecked.value--;
	}
}

function setCheckboxesRange(do_check, numItems) {
	var i = 1;
	var countRows = 0;
	while(countRows < numItems) {
		if(document.admin_form.elements[i].name.substring(0,8)=='checkbox') {
			document.admin_form.elements[i].checked = do_check;
			countRows++;
		}
		i++;
	}
	if (do_check) {
		document.admin_form.boxchecked.value = numItems;
	}
	else {
		document.admin_form.boxchecked.value = 0;
	}
	return true;
}

function setDateValue(field_name, type, value) {
	field_element = document.getElementById(field_name);
	switch(type) {
		case 'day':
			field_element.value = field_element.value.substring(0,6)+value+field_element.value.substring(8);
		break;    
		case 'month':
			field_element.value = field_element.value.substring(0,4)+value+field_element.value.substring(6);
		break;
		case 'year':
			field_element.value = value+field_element.value.substring(4);
		break;
		case 'hour':
			field_element.value = field_element.value.substring(0,8)+value+field_element.value.substring(10);
		break;
		case 'minute':
			field_element.value = field_element.value.substring(0,10)+value;
		break;
		default:

	}
}

var liveSearchTime = null;
var liveSearchLast = null;

function liveSearchStart(admin_id, item_id, domain) {
	if (liveSearchTime) {
		window.clearTimeout(liveSearchTime);
	}
	$('#filter_loader').css('display', 'block');
	liveSearchTime = window.setTimeout("liveSearchDoReq('"+admin_id+"','"+item_id+"','"+domain+"')",800);
}

function liveSearchDoReq(admin_id,item_id,domain) {
	var post_url = URL_PREFIX+"://"+domain+"?script=admin.script.searchlist&admin_id="+admin_id+"&item_id="+item_id+'&'+$('#searchblock input.search_input').serialize();
	var field_changed = false;
	
	if(liveSearchLast!=post_url) {
		field_changed = true;
		liveSearchLast=post_url;
	}
	
	if(field_changed) {
		$.ajax({
			url: post_url,
			cache: false,
			success: function(response){
				$("#admin_list_container").html(response);
				$('#filter_loader').css('display', 'none');
			}
		});
	}
	else {
  		$('#filter_loader').css('display', 'none');
	}
}

function str_pad(input,pad_length,pad_string) {
	var o = input.toString();
	if (!pad_string) { pad_string = '0'; }
	while (o.length < pad_length) {
		o = pad_string + o;
	}
	return o;
};

/**** Change state of an textarea ****/

function custom_clear_textarea(id, classname) {
	if(!$('#'+id).hasClass(classname)) {
		$('#'+id).val('');
		$('#'+id).addClass(classname);
	}
}

/**** Restrict input in textarea ****/
function restrictinput(maxlength,e,placeholder) {
	if (window.event && event.srcElement.value.length>=maxlength) {
		return false;
	}
	else if (e.target&&e.target==eval(placeholder)&&e.target.value.length>=maxlength){
		var pressedkey=/[a-zA-Z0-9\.\,\/]/; //detect alphanumeric keys
		if (pressedkey.test(String.fromCharCode(e.which))) {
			e.stopPropagation();
		}
	}
}

function countlimit(maxlength,e,placeholder) {
	alert('ok');
	var theform=eval(placeholder)
	var lengthleft=maxlength-theform.value.length
	var placeholderobj=document.all? document.all[placeholder] : document.getElementById(placeholder)
	if (window.event||e.target&&e.target==eval(placeholder)) {
		if (lengthleft<0)
			theform.value=theform.value.substring(0,maxlength)
		placeholderobj.innerHTML=lengthleft
	}
}

function insertAtCursor(myField, myValue) { //insert text into textarea
	if (document.selection) { //IE support
		myField.focus();
		sel = document.selection.createRange();
		sel.text = myValue;
	}
	else if (myField.selectionStart || myField.selectionStart == '0') { //Mozilla/Firefox/Netscape 7+ support
	
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring(0, startPos)+ myValue+ myField.value.substring(endPos, myField.value.length);
	} else {
		myField.value += myValue;
	}
}

function displaylimit(thename, theid, thelimit) {
	var theform=theid!=""? document.getElementById(theid) : thename
	var limit_text='<span class="limit_textarea_num" id="'+theform.toString()+'">'+thelimit+'</span>'
	var ns6=document.getElementById&&!document.all
	if (document.all||ns6)
		document.write(limit_text)
	if (document.all) {
		eval(theform).onkeypress=function(){ return restrictinput(thelimit,event,theform)}
		eval(theform).onkeyup=function(){ countlimit(thelimit,event,theform)}
	}
	else if (ns6) {
		document.body.addEventListener('keypress', function(event) { restrictinput(thelimit,event,theform) }, true);
		document.body.addEventListener('keyup', function(event) { countlimit(thelimit,event,theform) }, true);
	}
}

function insertImageToRTE(path, style) {
	tinyMCE.execCommand('mceInsertContent',false,'<img style="'+style+'" src="'+path+'" />');
}

/**** Insert in TyinMCE in admin ****/

function getGeneratedImage(picture_id, picture_subtext, picture_alttext, picture_creator, domain_root, run_version, maxwidth) {
	var width = $('#'+picture_id+'_size').val();
	var post_url = URL_PREFIX+"://"+domain_root+"/?script=admin.script.generate_picture&picture_id="+picture_id+"&width="+width;
	
	$.ajax({
		type: "GET",
		url: post_url,
		success: function(msg){
			insertGeneratedImage(picture_id, width, maxwidth, msg, picture_subtext, picture_alttext, picture_creator);
	   }
	});
	
	//$("#"+picture_id+'_button').attr('disabled', 'disabled');
}

function insertGeneratedImage(picture_id, width, maxwidth, txt, picture_subtext, picture_alttext, picture_creator) {
	padding = "";
	if(width>0 && width<=(maxwidth-20))
		padding = "padding: 10px;";
	else
		padding = "padding: 10px 0;";
	
	tinyMCE.execCommand('mceInsertContent',false,'<div style="width:'+width+'px; '+padding+'" class="inline_image_wrapper"><img src="'+txt+'" alt="'+picture_alttext+'"/><div class="picture_float_subtext">'+picture_subtext+' Foto: '+picture_creator+'</div><div class="spacer1"></div></div>');
	$(picture_id+'_button').disabled=false;
}

function insertForm(form_name, form_id) {
	tinyMCE.execCommand('mceInsertContent',false,'<div class="shema_holder" id="schema'+form_id+'">Skjema: '+form_name+'<!--FORMID'+form_id+'--></div>');
}

function insertFile(file_name, url) {
	tinyMCE.execCommand('mceInsertContent',false,'<a href="'+url+'">'+file_name+'</a>');
}

function insertPagebreak(caption) {
	tinyMCE.execCommand('mceInsertContent',false,'<div class="rte_insertbox">PAGEBREAK</div>');
}

/**** Keep alive ****/
function initiateKeepAlive(user_id, domain_root, run_version) {
	DoUpdate = function(message){
		unique = $time() + $random(0, 100);
		keepAlive(user_id, domain_root, unique, run_version);
	}
	setInterval(DoUpdate, 5000);
}

function keepAlive(user_id, domain_root, unique_id, run_version) {
	post_url = URL_PREFIX+"://"+domain_root+"/rsc/public_code_v"+run_version+"/php/standalone.php?action=frmw.script.keep_alive&user_id="+user_id+"&unique_id="+unique_id;
	request = new Request.JSON({
				url: encodeURI(post_url),
				onComplete: function(jsonObj) { updateData(jsonObj.information); }
			}).send();
	/*var req = new new Request.JSON({
								url:post_url, 
								onComplete: function(jsonObj){ updateData(jsonObj.information); },
								onFailure: function() {	alert('user_id : '+user_id+', unique_id: '+unique_id); } 
	}).send();*/
}

function updateData(jsonObj) {
	jsonObj.each(function(element) {
		if((element.element_id == 'unread_gb_msg') || (element.element_id == 'unread_pm_msg')) {
			if($(element.element_id)!=null)
				$(element.element_id).set('html', element.val);
		}
		
		//if(element.element_id == 'signed_in' && element.val == 0)
		//	alert('ikke logget inn');
	});
}

function destroyDialogBox() {
	jQuery("#dialog, .ui-dialog").remove();
	jQuery("body").append('<div id="dialog"></div>');
}

function dialogBox(message, type, title, task_id, admin_id) {
	destroyDialogBox();
	
	elem = jQuery("#dialog");

	
	if(elem.length==1) {
		if(type=="confirm") {
			elem.attr('title', (title===undefined ? 'Bekreft handling' : title));
			elem.html('<span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>'+message);
					
			jQuery(function() {
				elem.dialog({
					bgiframe: true,
					resizable: false,
					modal: true,
					overlay: {
						backgroundColor: '#000',
						opacity: 0.5
					},
					buttons: {
						'Ja!': function() {
							jQuery(this).dialog('close');
							if(admin_id===undefined || task_id===undefined) {
								//do nothing
							} else {
								submitbutton(task_id, admin_id);
							}
						},
						'Avbryt': function() {
							jQuery(this).dialog('close');
						}
					}
				});
			});
		} else {
			elem.attr('title', (title===undefined ? 'Informasjon' : title));
			elem.html('<span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>'+message);
			
			jQuery(function() {
				elem.dialog({
					bgiframe: true,
					resizable: false,
					modal: true,
					overlay: {
						backgroundColor: '#000',
						opacity: 0.5
					},
					closeOnEscape: false,
					buttons: {
						Ok: function() {
							jQuery(this).dialog('close');
						}
					}
				});
			});
		}
	}
}

var postalSearchTime = null;
function initiatePostalSearch(postalcode, url, divId) {
	$('zip_loader').style.display = 'inline';
	if(postalSearchTime) {
			window.clearTimeout(postalSearchTime);
	}
	postalSearchTime = window.setTimeout("doPostalNumberSearch('"+postalcode+"','"+url+"&postal="+postalcode+"','"+divId+"')",800);
}

function toggleElement(id) {
	$('#'+id).toggle('blind');
}

function hideElement(id) {
	$('#'+id+':visible').hide('blind');
}

function showElement(id) {
	$('#'+id+':hidden').show('blind');
}

function doPostalNumberSearch(postalcode, url, divId) {
	jQuery.getJSON(
		url,
		function(data){
	    	elem = jQuery("#"+divId);
			if(elem.length)
				elem.html(data.information[0].place);
		}
	);
	$('zip_loader').style.display = 'none';
}

/** Genereal instantiation **/
$().ready(function(){
	$('div.accordion').accordion({
		header: "div.toggle, a.toggle",
		autoHeight: false,
		alwaysOpen: false,
		active: false
	});
	
	$('div.accordion.defaultOpen').accordion( "activate" , 0);
	
	$("form.stop_submit").bind('submit', function() { return false; });
	
	$("form.ajax").ajaxify();
	$('textarea[maxlength]').setMaxLength();
	$('textarea.autofocus, input.autofocus').setAutofocus();
});

$.fn.setMaxLength = function() {
	$(this).bind('keyup', function() {
		var max = $(this).attr('maxlength');
		if($(this).val().length > max)
			$(this).val($(this).val().substr(0, $(this).attr('maxlength')));
		$(this).parent().parent().find('.chars_remaining').html((max - $(this).val().length));
	});
}

$.fn.setAutofocus = function() {
	$(this).after($('<input>').attr('type', 'hidden').attr('name', 'autofocus_textcache').val($(this).val()));
	$(this).bind('focus', function () {
		$(this).addClass('focus');
		if($(this).val() == $(this).next('input[name=autofocus_textcache]').val())
			$(this).val('');
		$(this).parent().parent().find('.autofocus_focus').show();
	});
	
	$(this).bind('blur', function() {
		if($(this).val() == '' || $(this).val() == $(this).next('input[name=autofocus_textcache]').val()) {
			$(this).removeClass('focus');
			$(this).val($(this).next('input[name=autofocus_textcache]').val());
			$(this).parent().parent().find('.autofocus_focus').hide();
		}
	});
}

$.fn.ajaxify = function() {
	$(this).bind('submit', function() {
		theForm = $(this);
		submitLabel = theForm.find('input:submit').val();
		theForm.find('input:submit').replaceWith($('<div>').addClass('loader').addClass('uiLoader'));
		if(typeof(tinyMCE)!="undefined")
			tinyMCE.triggerSave();
		if(theForm.attr('action').length > 0) {
			$.ajax({
				url: theForm.attr('action'),
				type: "POST",
				dataType: "json",
				cache: false,
				async: false,
				data: input2json(theForm),
				success: function(json) {
					theForm.find('.loader').replaceWith($('<input>').attr('type', 'submit').addClass('default_button uiButton').val(submitLabel));
					
					if(json.callback!=undefined && json.callback.length > 0) {
						eval('theForm.'+json.callback+'(json)');
					}
					
					
					if(json.status!=undefined) {
						if(theForm.find('.form_response div').is(':visible')) {
							theForm.find('.form_response div:visible').fadeOut('fast', function () {
								theForm.find('.form_response .message_'+json.status).fadeIn('fast');
								theForm.find('.controllers .controller').removeClass('err');
								theForm.find('.controllers .outline_'+json.status).addClass('err');
							});
						}
						else {
							theForm.find('.form_response .message_'+json.status).fadeIn('fast', function () {
								theForm.find('.controllers .controller').removeClass('err');
								theForm.find('.controllers .outline_'+json.status).addClass('err');
							});
						}
					}
				}
			});
		} else {
			alert('ERROR: URL for ajax call not specified (in action attribute on form).');
		}
		return false;
	});
}

$.fn.setAjaxCheat = function() {
	$(this).bind('submit', function() {
		theForm = $(this);
		cheatFunction = theForm.find('input:hidden[name=cheat]').val();
		cleanupFunction = theForm.find('input:hidden[name=cleanup]').val();

		if(cheatFunction != undefined && cheatFunction.length > 0)
			eval('theForm.'+cheatFunction+'()');
		
		if(typeof(tinyMCE)!="undefined")
			tinyMCE.triggerSave();
		if(theForm.attr('action').length > 0) {
			$.ajax({
				url: theForm.attr('action'),
				type: "POST",
				dataType: "json",
				cache: false,
				async: true,
				data: input2json(theForm),
				success: function(json) {
					if(cleanupFunction!=undefined && cleanupFunction.length > 0)
						eval('theForm.'+cleanupFunction+'(json)');
					
					if(json.status!=undefined) {
						if(theForm.find('.form_response div').is(':visible')) {
							theForm.find('.form_response div:visible').fadeOut('fast', function () {
								theForm.find('.form_response .message_'+json.status).fadeIn('fast');
								theForm.find('.controllers .controller').removeClass('err');
								theForm.find('.controllers .outline_'+json.status).addClass('err');
							});
						}
						else {
							theForm.find('.form_response .message_'+json.status).fadeIn('fast', function () {
								theForm.find('.controllers .controller').removeClass('err');
								theForm.find('.controllers .outline_'+json.status).addClass('err');
							});
						}
					}
				}
			});
		} else {
			alert('ERROR: URL for ajax call not specified (in action attribute on form).');
		}
		return false;
	});
}

var personSearchTime = null;
var personSearchLast = '';
function personSearchStart(url, elem, qryField) {
	if (personSearchTime) {
		window.clearTimeout(personSearchTime);
	}
	jQuery('#filter_loader').css('display', 'block');
	personSearchTime = window.setTimeout("personSearchDoReq('"+url+"','"+elem+"','"+qryField+"')",800);
}

function personSearchDoReq(url, elem, qryField) {
	var query = jQuery(qryField).attr('value');
	var post_url = url+'&query='+query;
	var field_changed = false;
	
	if(query != personSearchLast)
		field_changed = true;
	
	if(field_changed) {
		var req = new Request({url:post_url, 
			onSuccess: function(txt){ 
				jQuery(elem).html(txt);
				jQuery('#filter_loader').css('display', 'none');
				
				personSearchLast = query;
			},
			onFailure: function(xhr){}
		}).send();
	}
	else {
  		jQuery('#filter_loader').css('display', 'none');
	}
}

//EMPTY A FORM FIELD IF CURRENT VALUE IS THE DEFAULT VAL
function emptyifdefault(elem, defaultVal) {
	if($("#"+elem.id).val()==defaultVal) {
		$("#"+elem.id).val('');
	}
}


//function that disables the enter key submission from a field
function disableEnter(event) {
	var e = (event ? event : window.event); 
	return (e.keyCode ? e.keyCode : e.charCode ? e.charCode : e.which) != 13;
}

function serialize_form(selector) {
	str = encodeURIComponent($(selector).serialize()).split('%').join("-.-.-").split("-.-.-3D").join("=").split("-.-.-26").join("&");
	return str;
}

function collectScriptData(uploader, selector) {
	/*var str;

	// collecting input (name, value) pair
	str = $(selector).map(function () {
		return encodeURIComponent(this.name.replace('&', '_')) + '=' + encodeURIComponent(this.value.replace('&', '_')).split('%').join("-.-.-");
	})
	.get()
	.join('&')
	.replace(/%20/g, "+");
	
	alert("&"+str);*/
	//str = encodeURIComponent($(selector).serialize()).split('%').join("-.-.-").split("-.-.-3D").join("=").split("-.-.-26").join("&");
	
	$(uploader).fileUploadSettings('scriptData', "&"+serialize_form(selector));
}

function input2json(formselector) {
	var tmpjson = {};
	var tmpelem = null;
	var tmpval = 0;
	var checkedradio = null;
	
	$(':input', formselector).each(function() {
		if(this.name!='' && tmpjson[this.name]==undefined) {
			tmpelem = $("input[name='"+this.name+"']");
			
			if(tmpelem.is(':radio')) {
				checkedradio = $("input[name='"+this.name+"']:checked");

				if(checkedradio!=null)
					tmpval = checkedradio.val();
				else
					tmpval = 0;
			} else if(tmpelem.is(':checkbox')) {
				if(tmpelem.is(':checked'))
					tmpval = 'on';
				else
					tmpval = '';
			} else {
				tmpval = this.value;
			}
			
			tmpjson[this.name] = tmpval;
		}
	});
	return tmpjson;
}

function add_facet_selection(target_id, selection_id, form_id) {
	$(target_id).val($(target_id).val()+','+$(selection_id).text());
	$(form_id+' .searchbutton').trigger('click');
}

function remove_facet_selection(target_id, selection_id, form_id) {
	$(target_id).val($(target_id).val().split(','+$(selection_id).text()).join(''));
	$(form_id+' .searchbutton').trigger('click');
}

function add_node(map, bounds, lat, lon, title, url) {
	var myLatLng = new google.maps.LatLng(lat, lon);
	var marker = new google.maps.Marker({
		position: myLatLng,
		map: map,
		title: title
	});
	
	if(url!="") {
		google.maps.event.addListener(marker, 'click', function() {
			window.location.replace(url);
		});
	}
	
	if(bounds)
		bounds.extend(myLatLng);
}

function disable_widget(selector, fade) {
	if(fade!=null && fade==true) {
		$(selector).fadeTo(150, 0.6, function (){
			$(selector+' :input').attr('disabled', true);
		});
	}
	else {
		$(selector).css('opacity', '0.6');
		$(selector+' :input').attr('disabled', true);
	}
}

function enable_widget(selector, fade) {
	if(fade!=null && fade==true) {
		$(selector).fadeTo(150, 1, function (){
			$(selector+' :input').attr('disabled', false);
		});
	}
	else {
		$(selector).css('opacity', '1');
		$(selector+' :input').attr('disabled', false);
	}
}

/**
 * Method for setting a cookie
 *
 * @param name string cookie name
 * @param value string cookie value
 * @param expires int how many days to live before expiring
 * 
 **/
function setCookie(name, value, expires, path, domain, secure) {
	// set time, it's in milliseconds
	var today = new Date();
	today.setTime(today.getTime());

	/*
	if the expires variable is set, make the correct
	expires time, the current script below will set
	it for x number of days, to make it for hours,
	delete * 24, for minutes, delete * 60 * 24
	*/
	if(expires) {
		expires = expires*1000*60*60*24;
	}
	
	var expires_date = new Date(today.getTime()+(expires));

	document.cookie = name + "=" +escape( value ) +
	(expires ? ";expires=" + expires_date.toGMTString() : "" ) +
	(path ? ";path=" + path : "" ) +
	(domain ? ";domain=" + domain : "" ) +
	(secure ? ";secure" : "" );
}

function getCookie(check_name) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for(i=0; i<a_all_cookies.length; i++) {
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split('=');

		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if(cookie_name==check_name) {
			b_cookie_found = true;
			
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if(a_temp_cookie.length>1) {
				cookie_value = unescape(a_temp_cookie[1].replace(/^\s+|\s+$/g, ''));
			}
			
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
			break;
		}
		
		a_temp_cookie = null;
		cookie_name = '';
	}
	
	if(!b_cookie_found) {
		return null;
	}
}