//not very pretty and DRY, hopefully will fix it later. someday.
elTemplates = {
	text : new Template(
		'<div class="form_item" id="form_item_#{prefix}" style="display:none">' +
		'<div class="handle"><input type="hidden" name="elspos[]" value="#{prefix}"></div>' +
		'<div class="form_type"><img src="/images/admin/forms/#{form_type}.gif"><input type="hidden" name="form_config[#{prefix}][form_type]" value="#{form_type}"></div>' +
		'<div class="form_title"><input type="text" name="form_config[#{prefix}][form_title]"></div>' +
		'<div class="form_req"><input type="checkbox" name="form_config[#{prefix}][form_req]"> 必須<br>' +
		'<input type="radio" name="form[form_respmail]" value="#{prefix}">返事用メール</div>' +
		'<div class="form_content">&nbsp;</div>' +
		'<div class="form_delete"><input type="button" value="削除" onclick="custom_forms_removeItem(#{prefix})"></div>' +
		'<div class="clear"></div>' + 
		'</div>'),
	textarea : new Template(
		'<div class="form_item" id="form_item_#{prefix}" style="display:none">' +
		'<div class="handle"><input type="hidden" name="elspos[]" value="#{prefix}"></div>' +
		'<div class="form_type"><img src="/images/admin/forms/#{form_type}.gif"><input type="hidden" name="form_config[#{prefix}][form_type]" value="#{form_type}"></div>' +
		'<div class="form_title"><input type="text" name="form_config[#{prefix}][form_title]"></div>' +
		'<div class="form_req"><input type="checkbox" name="form_config[#{prefix}][form_req]"> 必須</div>' +
		'<div class="form_content">&nbsp;</div>' +
		'<div class="form_delete"><input type="button" value="削除" onclick="custom_forms_removeItem(#{prefix})"></div>' +
		'<div class="clear"></div>' + 
		'</div>'),
	radio : new Template(
		'<div class="form_item" id="form_item_#{prefix}" style="display:none">' +
		'<div class="handle"><input type="hidden" name="elspos[]" value="#{prefix}"></div>' +
		'<div class="form_type"><img src="/images/admin/forms/#{form_type}.gif"><input type="hidden" name="form_config[#{prefix}][form_type]" value="#{form_type}"></div>' +
		'<div class="form_title"><input type="text" name="form_config[#{prefix}][form_title]"></div>' +
		'<div class="form_req"><input type="checkbox" name="form_config[#{prefix}][form_req]"> 必須</div>' +
		'<div class="form_content"><textarea name="form_config[#{prefix}][form_content]"></textarea></div>' +
		'<div class="form_delete"><input type="button" value="削除" onclick="custom_forms_removeItem(#{prefix})"></div>' +
		'<div class="clear"></div>' + 
		'</div>'),
	checkbox : new Template(
		'<div class="form_item" id="form_item_#{prefix}" style="display:none">' +
		'<div class="handle"><input type="hidden" name="elspos[]" value="#{prefix}"></div>' +
		'<div class="form_type"><img src="/images/admin/forms/#{form_type}.gif"><input type="hidden" name="form_config[#{prefix}][form_type]" value="#{form_type}"></div>' +
		'<div class="form_title"><input type="text" name="form_config[#{prefix}][form_title]"></div>' +
		'<div class="form_req"><input type="checkbox" name="form_config[#{prefix}][form_req]"> 必須</div>' +
		'<div class="form_content"><textarea name="form_config[#{prefix}][form_content]"></textarea></div>' +
		'<div class="form_delete"><input type="button" value="削除" onclick="custom_forms_removeItem(#{prefix})"></div>' +
		'<div class="clear"></div>' + 
		'</div>'),
	select : new Template(
		'<div class="form_item" id="form_item_#{prefix}" style="display:none">' +
		'<div class="handle"><input type="hidden" name="elspos[]" value="#{prefix}"></div>' +
		'<div class="form_type"><img src="/images/admin/forms/#{form_type}.gif"><input type="hidden" name="form_config[#{prefix}][form_type]" value="#{form_type}"></div>' +
		'<div class="form_title"><input type="text" name="form_config[#{prefix}][form_title]"></div>' +
		'<div class="form_req"><input type="checkbox" name="form_config[#{prefix}][form_req]"> 必須</div>' +
		'<div class="form_content"><textarea name="form_config[#{prefix}][form_content]"></textarea></div>' +
		'<div class="form_delete"><input type="button" value="削除" onclick="custom_forms_removeItem(#{prefix})"></div>' +
		'<div class="clear"></div>' + 
		'</div>'),
	confirm_message : new Template(
		'<div id="confirm_message" style="display:none"><img src="/images/ok.gif" align="absmiddle">フォーム送信完了です。お問い合わせありがとうございました。</div>'
		)
};



function custom_forms_addElement() {
	//alert("the type is:"+$F('new_field_type'))
 
	var fieldType = $F('new_field_type');
	var myDate = new Date();
	switch (fieldType) {
		case 'text':
		case 'textarea':
		case 'radio':
		case 'checkbox':
		case 'select':
			var tParams = {prefix : myDate.getTime()*100 + myDate.getMilliseconds(), form_type : fieldType};
			var el = new Insertion.Before('form_config_clearer', elTemplates[fieldType].evaluate(tParams));
			new Effect.BlindDown('form_item_'+tParams.prefix, {duration: 0.5});
			new Effect.Appear('form_item_'+tParams.prefix, {
				duration: 0.6,
				afterFinish : function() { custom_forms_recreateSortable() }
			});
			//recreating sortable stuff.
			custom_forms_recreateSortable();
			break;
		default:
			alert("unsupported element:" + fieldType);
	}
}

function custom_forms_removeItem(prefix) {
	var el = $('form_item_'+prefix);
	new Effect.BlindUp(el, { duration: 0.5 });
	new Effect.Fade(el, {
		duration: 0.6,
		afterFinish : function() { $('form_item_'+prefix).remove(); custom_forms_recreateSortable() }
	});
}

function custom_forms_recreateSortable() {
	Sortable.destroy('form_config');
	Sortable.create('form_config', {tag : 'div', handle : 'handle'});
}

function custom_forms_checkEntry(event) {
	var theForm = $('custom_form');
	var req_els = theForm.req_els;
	var mail_field = theForm.mail_field;
	var emailRegEx = /^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$/i;
	//alert("required elements: "+req_els);
	
	Event.stop(event);
	$('bntSubmit').disable();
	
	var flaggedEls = Array();
	var eltValue;
	req_els.each(function(elt) {
		switch (elt['type']) {
			case 'radio':
				eltValue = forms_getRadioValue(theForm, "form["+elt['prefix']+"]");
				break;
			case 'checkbox':
				eltValue = forms_getCheckboxValue(theForm, "form["+elt['prefix']+"][]")
				break;
			default: 
				//normal checking using prototype standard stuff
				eltValue = $F("form["+elt['prefix']+"]");
				break;
		}
		if (eltValue=="") {
			flaggedEls.push(elt['prefix']);
		}
	});
	
	//checking for correct email address
	if (mail_field!=false) {
		eltValue = $F("form["+parseInt(mail_field)+"]");
		if (eltValue.search(emailRegEx) == -1) {
			flaggedEls.push(mail_field);
		}
	}
	
	flaggedEls = flaggedEls.uniq();

	//clearing the current warnings first
	req_els.each(function(elt) {
			$('elt_req_'+elt['prefix']).removeClassName('warning');
	});

	if (flaggedEls.length==0) {
		//everything's good
		
		var url = "/form/"+$F('form_slug')+"/form_confirm"
		var data = theForm.serialize();
		$('custom_form_preview').hide();
		new Ajax.Updater('custom_form_preview', url, {
			method : 'post',
			parameters : data,
			onCreate: function() {
				new Effect.Appear('loader', {duration: 0.3});
			},
			onSuccess : function() {
				new Effect.Fade('custom_form_form', {duration: 0.5});
				//new Effect.BlindDown('custom_form_preview', {duration: 0.5, delay: 0.6});
				new Effect.Appear('custom_form_preview', {duration: 0.5, delay: 0.6});
			}
		})
	} else {
		//alert("Form had errors");
		//outlining flagged errors
		flaggedEls.each(function(elt) {
			var el = $('elt_req_'+elt).addClassName('warning');
			new Effect.Highlight(el, {keepBackgroundImage:true, endcolor: '#eeeeee', duration: 4});
		});
/*		flaggedEls.each(function(elt) {
			new Effect.Highlight('elt_req_'+elt, {keepBackgroundImage:true, endcolor: '#eeeeee', duration: 4});
		});*/
		new Effect.ScrollTo('elt_req_'+flaggedEls[0]);
		$('bntSubmit').enable();
	}

}

function forms_getRadioValue(theForm, radiogroupName) {
	var checked = theForm.getInputs("radio", radiogroupName).find(function(item)
	{ return item.checked; })
	return checked==undefined ? "" : checked.value;
}

function forms_getCheckboxValue(theForm, checkgroupName) {
	var checked = theForm.getInputs("checkbox", checkgroupName).findAll(function(item) 
	{ return item.checked; }).pluck("value");
	return checked.length==0 ? "" : checked;
}

function custom_forms_submit() {
	var theForm = $('custom_form');
	var url = "/form/"+$F('form_slug')+"/form_send"
	var data = theForm.serialize();
	
	new Ajax.Request(url, {
		method : 'post',
		parameters : data,
		onCreate: function() {
			new Effect.Appear('loader2', {duration: 0.3});
		},
		onSuccess: function() {
			custom_sendSuccess();
		},
		onFailure: function() {
			alert("There was an error submitting the form");
		}
	});
}

function custom_sendSuccess() {
	var el = new Insertion.Before('btnSubmitSet', elTemplates["confirm_message"]["template"]);
	new Effect.Fade('btnSubmitSet', {duration: 0.5});
	new Effect.Appear('confirm_message', {duration: 0.5, delay: 0.6});
}

function custom_forms_cancelConfirm() {
	$('loader').hide();
	new Effect.BlindDown('custom_form_form', {duration: 0.5});
	new Effect.Appear('custom_form_form', {duration: 0.5});
	new Effect.BlindUp('custom_form_preview', {duration: 0.5});
	new Effect.Fade('custom_form_preview', {duration: 0.5});
	$('bntSubmit').enable();
}