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

/**** Admin ****/

function submitbutton(task, admin_id) {
	document.admin_form.task.value=task;
	if((admin_id)>0) { document.admin_form.admin_id.value=admin_id; }
	
	try { document.admin_form.onsubmit(); }
	catch(e) {}
	document.admin_form.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');
	}
}

/**** 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) {
	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 accordion and facebox instantiation **/
jQuery(document).ready(function(){
    jQuery('div.accordion').accordion({
    	header: "div.toggle, a.toggle",
    	autoHeight: false,
    	alwaysOpen: false,
    	active: false
    });
    
    $(".fancybox").fancybox(); 
});

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 post_tip_a_friend(elem, url) {
	var form = $("#"+elem.id).parent();
	var data = form.serialize();
	
	$("#tip_a_friend_response").remove();
	$(".rightcol_share input.field_highlight_error").removeClass('field_highlight_error');
	$(".sendemailerror").text("");
	
	$.ajax({
		type: "GET",
		url: url+"?script=mod.0001.script.tip_a_friend",
		data: form.serialize(),
		success: function(msg){
			switch(msg) {
				case "1":
					form.parent().prepend('<div id="tip_a_friend_response" class="form_message_success">Ditt tips har blitt sendt!</div>');
					form.remove();
					$(".sendemailerror").text("Ditt tips har blitt sendt!");
				break;
				case "2":
					$("#tip_a_friend_sendermail").addClass('field_highlight_error');
					form.parent().prepend('<div id="tip_a_friend_response" class="form_message_error">Vennligst rett felter merket med rødt.</div>');
					$(".sendemailerror").text("Vennligst rett felter merket med rødt ('Din epost').");
				break;
				case "3":
					$("#tip_a_friend_receivermail").addClass('field_highlight_error');
					form.parent().prepend('<div id="tip_a_friend_response" class="form_message_error">Vennligst rett felter merket med rødt.</div>');
					$(".sendemailerror").text("Vennligst rett felter merket med rødt ('Mottakers epost').");
				break;
				case "4":
					$("#tip_a_friend_sendermail").addClass('field_highlight_error');
					$("#tip_a_friend_receivermail").addClass('field_highlight_error');
					form.parent().prepend('<div id="tip_a_friend_response" class="form_message_error">Vennligst rett felter merket med rødt.</div>');
					$(".sendemailerror").text("Vennligst rett felter merket med rødt ('Din epost' og 'Mottakers epost').");
				break;
			}
	   }
	});
}

//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 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);
		});
	}
	
	bounds.extend(myLatLng);
}