// Must be loaded after prototype and local customizing scripts
// Event.observe(window, "load", create_form());

document.observe("dom:loaded", loadForm());

var form_oid=0;

// not used at the moment
function updateStatus(i){
	if (!defaultText('loadstatus',"some text")){
		alert("Try: "+i);
		i=i+1;
		setTimeout("updateStatus("+i+");",500);
	}
	else{
		loadForm();
	}
}

function classToArgs(classstring){
	var a=classstring.split(" ");
	var r=new Object();
	for (i=0;i<a.length;i=i+1){
		r[a[i].charAt(0)]=a[i].substring(1);
	}
	return r;
}

function loadForm(){
	var mf=$("main_form");
	if (mf) {
		cargs=classToArgs(mf.className);
		form_oid=cargs["o"];
		var url='/editr/form';

		// Try to load spreadsheet module used on budget page. Is the timeout appropriate and adequate?
		setTimeout('TrimPath.spreadsheet.initDocument()',1500);

		new Ajax.Request(url, {
			method: 'post',
			parameters: {oid: form_oid, formid: getFormID()},
			onSuccess: function(transport) {
				$("main_form").innerHTML=transport.responseText;
			},
			onFailure: function(transport) {
				$("main_form").innerHTML="En feil har oppstått. Vi beklager!";
			}
		});
	}
	else {
		setTimeout("loadForm();",500);
	}
}


function defaultText(id,text){
	var hmm=$(id);
	if (!hmm){
//     alert('hmm');
		return false;
	}
//   alert('ja');
	$(id).innerHTML=text;
	return true;
}


// changes made will not be saved
function gotopage(id){  
	var pm = new Hash();
	pm.set("goto",id);
	submitForm(pm);
}

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };

function validate(id){
	var pm = new Hash();
	pm.set("update",id);
	submitForm(pm)
}
function validateAndGotopage(id){
	var pm = new Hash();
	pm.set("update",id);
	pm.set("goto",id);
	submitForm(pm)
}
function submitForm(pm){
//   alert("calling validate3");
	var ia=$("main_form").select("input.at","select.at","textarea.at");

	var l=ia.length;
//   var i=0;
//   alert(input_array[0].value);

//   var parameterString="oid:form_oid,update:1";
//   for (var i = 0; i < l; i++) {
//     parameterString += "," + ia[i].id + ":" + encodeURI(ia[i].value);
// //     parameterString += (i > 0 ? "," : "") + ia[i].id + "=" + encodeURI(ia[i].value);
//   }  

//   alert(parameterString);
//   alert($('fform').serialize(true))

	pm.set("oid",form_oid);
	pm.set("formid",getFormID());
//   pm.set("update",1);

//   var summary="summary: ";
	var radios=new Hash();  // radio buttons needs special handling since they have many inputs with unique ids
	var checkboxen=new Hash();
	for (var i = 0; i < l; i++) {
     var summary=summary+" |"+ia[i].id+"-"+ia[i].name+"-"+ia[i].type+"| ";
//alert(summary);
//     alert(ia[i].id);
		if (ia[i].type=='radio'){  // handle radio
			var b=ia[i].id.split("_");    // the first part, before "_" is the id of the attribute
			radios.set(b[0],ia[i].name);  // name is unique per radio
		}
		else if (ia[i].type=='checkbox'){  // handle checkbox
			var b=ia[i].id.split("_");
			if (b[1]) {  // multiple checkbox with single id
				if (!checkboxen.get(b[0])) checkboxen.set(b[0],"");
				if (ia[i].checked) {
					if (checkboxen.get(b[0])=="") checkboxen.set(b[0],b[1]);
					else checkboxen.set(b[0],checkboxen.get(b[0])+'-'+b[1]);
				}
			}
			else { // single id checkbox
				if (ia[i].checked) pm.set(ia[i].id,"1");
				else pm.set(ia[i].id,"0");
			}
		}
		else if (ia[i].name=='sc'){  // handle spreadsheet hack
			// Gets the spreadsheet table based on surrounding div id.
			// Then the HTML code of the table is put into a hidden text field.
			// Ugly, but no time to do better.

			 ia[i].value=$(ia[i].id+'-sc').innerHTML;

			 pm.set(ia[i].id,encodeURIComponent(ia[i].value));  // As below.
		}
		else pm.set(ia[i].id,encodeURIComponent(ia[i].value));  // handle the rest of the input methods
	}  

	checkboxen.each(function(pair) {
		pm.set(pair.key,pair.value);
	});
//   alert(summary);
	radios.each(function(pair) {  // for each radio button
//     alert(pair.key+"="+pair.value);
		var rb=Form.getInputs('fform','radio',pair.value).find(function(radio) { return radio.checked; });  // get a button object
		if (rb) pm.set(pair.key,rb.value);   // only if object has a value will it exists. If it does, add the id and value
		else pm.set(pair.key,"");  // or set value to empty string to indicate invalid value
	});

	// Try to load spreadsheet module used on budget page. Is the timeout appropriate and adequate?
	setTimeout('TrimPath.spreadsheet.initDocument()',1500);

	// IE6 seems to have trouble with the Ajax request down below at line 220 in conjunction with this.
	new Ajax.Updater('main_form', '/editr/form', { method: 'post', parameters: pm.toObject() });


//   for (key in input_array) alert(key.value);
//   document.write("Element value is " + myArray[key]);
}
// parameters: {company: 'example', limit: 12}


// stores changes
function publish(){
	var publishbutton=document.getElementById('publiser');
	var publishwait=document.getElementById('publiser-wait');
	publishbutton.style.display='none';
	publishwait.style.display='block';

	publish_execute();
	return;
	var p1=$('password1');
	var p2=$('password2');
	if (p1&&p2) {
		var p1t=encodeURI(p1.value.trim());
		var p2t=encodeURI(p2.value.trim());
		if (p1t==p2t) {
			if (p1t=="") inlineError("pass_error","Passord mangler");
			else {
				publish_execute();
			}
		}
		else {
			inlineError("pass_error","Du må skrive samme passord to ganger");

		}
	}
}


function publish_execute(){
	var ia=$('main_form').select('input.at');
	var l=ia.length;
	var pm = new Hash();
	pm.set('oid',form_oid);
	pm.set('formid',getFormID());
	pm.set('publish',1);
	var appsum=document.getElementById('applicationsummary');
	for (var i = 0; i < l; i++) {
		pm.set(ia[i].id,encodeURI(ia[i].value));
	}
//               inlineError("pass_error","Passord ok");  return;
	new Ajax.Request('/editr/form', {
		method: 'post',
		parameters: pm.toObject(),
			onSuccess: function(transport) {
				var resp=transport.responseText.trim();
				//if (resp=="done") window.location = "/editr/received";
				//else $("main_form").innerHTML=transport.responseText;

				if (resp=="done") {
					var pm2=new Hash();
					pm2.set('applicationsummary',appsum.value);
					pm2.set('foid',form_oid);
					new Ajax.Updater('main_form', '/editr/received', {
						method: 'post',
						parameters: pm2.toObject(),
						onSuccess: function(transport) {
							//return true;
						}
					});
				}
				else $("main_form").innerHTML=transport.responseText;
			}
	});
}


function inlineError(id,msg){
	err=$(id);
	if (err) {
		err.innerHTML=msg;
		err.className="inlineerror";
	}
	else alert(msg);
}

function removeAttachments(attid){
	var els=$("main_form").select("input.cb");
	var l=els.length;
	var nc=0;
	var pm = new Hash();
	pm.set('formid',getFormID());

	for (var i = 0; i < l; i++) {
		if (els[i].checked){
			nc++;
			pm.set("da"+i,els[i].value);
		}
	}
	
	if (nc>0) {
		pm.set("delatt","1");
		pm.set("oid",form_oid);  // always needed
		pm.set("attid",attid);  // always needed
		if (document.getElementById('pageid')) pm.set("goto",document.getElementById('pageid').value);

		new Ajax.Updater('main_form', '/editr/form', { method: 'post', parameters: pm.toObject() });

		/*
		$(id).value=1;
		$(fid).setAttribute('action', '/content/edit/'+oid+'/'+ov);
		$(fid).setAttribute('enctype','multipart/form-data');
		$(fid).setAttribute('method','post');
		$(fid).submit();
		*/
	}
	else {
		inlineError("att_error","Du må velge minst ett vedlegg")
	}
}

// Checkbox hide/display fieldset
// m=attribute id s=fieldset id
function cf(m,s){
	var mid='at'+m;
	var sid='fs'+s;
	if ($(mid).checked) $(sid).style.display='block';
	else $(sid).style.display='none';
}

// Checkbox hide/display generic
function cd(m,s){
	if ($(m).checked) $(s).style.display='block';
	else $(s).style.display='none';
}

// Radio butotn hide/display generic
function rd(m,s,h){
	if ($(m).checked) {
		if ($(s)) {
			$(s).style.display='block';
		}
	}
	else {
		if ($(s)) {
			$(s).style.display='none';
		}
	}
	if ($(m).checked) {
		if ($(h)) {
			$(h).style.display='none';
		}
	}
}

// Radio button hide/display generic - array version
// Separate to keep compatibility with old code (different input required)
function rdarr(m,s,h){
    if ($(m).checked) {
        if ($(s)) {
            for (i=0;i<s.length;i++) {
                $(s[i]).style.display='block';
            }
        }
    }
    else { 
        if ($(s)) {
            for (i=0;i<s.length;i++) {
                $(s[i]).style.display='none';
            }
        }
    }
    if ($(m).checked) {
        if ($(h)) {
            for (i=0;i<h.length;i++) {
                $(h[i]).style.display='none';
            }
        }
    }
}


// Select box hide/display generic - keyword based (t)!.
function sd(m,s,t) {
	$(s).style.display='none';
	for (i=0;i<t.length;i++) {
		if ($(m).getValue()==t[i]) $(s).style.display='block';
	}
}

// Select infobox hide/display generic (id based).
function si(m,t) {
	for (i=0;i<t.length;i++) {
		var tname='in'+t[i];
		$(tname).style.display='none';
		if ($(m).getValue()==$(t[i])) {
			$(tname).style.display='block';
		}
	}
}

// Select box hide/display generic - keyword based (t)!.
// Out of use.
function asd(m,s,t) {
	//var selectmenu=document.getElementById(m);
	var chosenoption=$(m).options[$(m).selectedIndex];
	alert('Servus!');
	if (chosenoption.value=="Annet"){
		alert('Was anderes');
	}
}

function numonly(val,length) {
	val=val.replace(/[\D]/g,'');

	var expr = "(\\d{"+length+"}).*$";
	var re = new RegExp(expr,'gi');
	val=val.replace(re,'$1');

	return val;
}

function buttonEnable(obj, button){
	var activatebutton=document.getElementById(button);
	if(!obj.checked) {
		activatebutton.disabled=true;
	}
	else {
		activatebutton.disabled=false;
	}
}

 function textcd(field, count, max) {
 //if (field.value.length > max)
	 //field.value = field.value.substring(0, max);
 //else
	 count.value = max - field.value.length;
 }

function calendar_changed(id){
	var inn=$('cal'+id);
	var out=$('at'+id);

	var d = inn.calendar_date_select.selected_date.stripTime();
//   $('debug_field').innerHTML=d.getFullYear()+","+d.getMonth()+","+d.getDate();
//   $('debug_field').innerHTML=d.getTime()+":"+Math.floor((d.getTime()+3)/1000);
	out.value=Math.floor((d.getTime()+3)/1000);
}

// Works only when included after calendar_date_select is included
	_translations = {
		"OK": "OK",
		"Now": "Nå",
		"Today": "I dag"
	}

	Date.weekdays = $w("S M Ti O To F L");

	Date.months = $w("januar februar mars april mai juni juli august september oktober november desember" );

	var adate=new Date();
	
// CalendarDateSelect.format = :finnish;

