
function wtfReloadSection(sect,spinner,extraparams) {

	var params = {};

	if (extraparams) params = extraparams;

	spinner && $(spinner) && $(spinner).update("<img src='/images/iconsets/myfonts/spinner.gif' alt='spinner' class='spinner32'>");

	$A(sect.split(",")).each(function(s) {
	
		params.display = s;

		new Ajax.Request(window.location.href, {
			'parameters': params,
			'method': 'get',
			'onSuccess': function(xmlhttp) {
	
				$('wtf_' + s + '_overlord').replace(xmlhttp.responseText);
				Behaviour.apply();
	
			}
		});

	});

}


function wtfSubmitReply(butt) {

	if (!butt) butt = $('wtf_reply_post');
	else butt = $(butt);

	var theform = butt.up('form');

	var errors = false;
	$('wtf_reply_form').select('td.required, div.required').invoke('removeClassName','required');

	if (!$('wtf_identify_check').checked && $F('wtf_reply_textarea').length == 0)
	{
		alert("Please identify a font or include a message.");
		return;
	}

	var do_font_stuff = $('wtf_identify_check').checked;

	if (do_font_stuff)
	{
		$A(['text','url','name']).each(function(k) {

			var field = $("wtf_identify_" + k);
			
			field.disabled = false;
			if (!/\S/.test(field.value))
			{
				errors = true;
				field.up('td').previous().addClassName('required');
			}

		});
	}

	if (errors)
	{
		alert("Please fill in missing fields.");
		return;
	}

	var params = theform.serialize(true);
	params.ajax = 1;	
	params.preview = (butt.id == 'wtf_reply_preview') ? 1 : 0;

	if (do_font_stuff && !/^https?:\/\/.*\//.test($F('wtf_identify_url')))
	{
		errors = true;
		alert("Font URL appears to be invalid.");
		$('wtf_identify_url').up('td').previous().addClassName('required');
		return;
	}

	var doSubmission = function(myparams) {
		new Ajax.Request(theform.readAttribute('action'), {
			'parameters': myparams,
			'onSuccess': function(xmlhttp) {
	
				if (myparams.preview)
				{
					popupBox("<h3>Preview</h3><div style='border:1px solid gray;margin:12px 0px;padding:12px;'>" + xmlhttp.responseText + "</div><div style='text-align:right'><input type='button' value='Cancel' onclick='hidePopupBox();'> or <input type='button' value='Post' onclick=\"wtfSubmitReply(); hidePopupBox();\"></div>");
				}
				else
				{
					if (do_font_stuff || typeof(myparams["extra_fields[MarkSolved]"]) != 'undefined')
						window.location.reload();
					else
						wtfReloadSection('posts',theform);
				}
	
			}
		});
	};


	if (params.preview || !do_font_stuff)
	{
		doSubmission(params);
		return;
	}

	new Ajax.Request("ajax_style_list.php", {
		'parameters': { 
			'url' : $F('wtf_identify_url'),
			'text': $F('wtf_identify_text')
		},
		'onSuccess': function(xmlhttp) {

			var style;
			if (style=parseInt(xmlhttp.headerJSON))
			{
				params["fontid[StyleID]"] = style;
			}
			else if (style=xmlhttp.responseJSON)
			{
				params["fontid[URL]"] = style.myfontsURL;
				params["fontid[FontName]"] = style.name;
				params["fontid[StyleID]"] = style.id;
			}
			else if (xmlhttp.responseText.length)
			{
				var winheight = document.viewport.getDimensions().height;
				var bodywidth = $('pagebody').getWidth();
				var img = $('wtf_image').down('img');
				var imgpos = img.cumulativeOffset();
				var imgsize = img.getDimensions();
				var maxheight = winheight - 150;


				var stylelist = $('wtf_stylelist_popup');
				
				if (!stylelist)
				{
					stylelist = $(new Element('div', {'id': 'wtf_stylelist_popup'})).hide();
					$('pagebody').insert(stylelist);

					stylelist.setStyle({
						'top': (imgpos.top) + "px",
						'left': (imgpos.left + imgsize.width + 12) + "px",
						'width': "480px"
					});
				}

				stylelist.hide();
				stylelist.update(xmlhttp.responseText);
				stylelist.style.height = maxheight + "px";
				Behaviour.apply();

				window.scroll(0,imgpos.top - 50);
				stylelist.show();

				var uldiv = $('wtf_style_list');
				var ulheight = uldiv.down('ul').getHeight();
				
				if (ulheight > maxheight)
					uldiv.style.height = maxheight + "px";
				else
					uldiv.style.height = (ulheight + 12) + "px";

				stylelist.style.height = (stylelist.down('form').getHeight()+12) + "px";
				
				return;
			}

			doSubmission(params);
		}
	});

}


var wtfCaseBehaviour = {

	'div.wtf_idfont a.remove_id' : function(el) {

		Behaviour.RUN_EVERY_TIME.push('div.wtf_idfont a.remove_id');
		el.stopObserving('click');
		el.observe('click',function(evt) {

			evt.stop();
			
			if (!confirm("Really remove this identification?"))
				return;	

			new Ajax.Request(el.href + "&ajax=1", {
				'method': 'get',
				'onSuccess': function(xmlhttp) {
					wtfReloadSection('ids',el.up('div.wtf_idfont'));
				}
			});
		});
	},
	
	'#wtf_case_page a.dispute' : function(el) {

		Behaviour.RUN_EVERY_TIME.push('#wtf_case_page a.dispute');
		el.stopObserving('click');

		el.observe('click', function(evt) {
		
			evt.stop();

			el.next('form').show();

		});
	},

	'#wtf_case_page form.wtf_dispute_form': function(theform) {

		Behaviour.RUN_EVERY_TIME.push('#wtf_case_page form.wtf_dispute_form');
		theform.stopObserving('submit');
		theform.observe('submit',function(evt) {

			evt.stop();

			var params = theform.serialize(true);
			params.ajax = 1;

			if (!/\S/.test(params.reason))
			{
				alert("Please enter a reason for your dispute.");
				return;
			}
			
			new Ajax.Request(theform.readAttribute('action'), {
				'parameters': params,
				'onSuccess': function(xmlhttp) {

					if (xmlhttp.headerJSON && xmlhttp.headerJSON.error)
					{
						if (xmlhttp.headerJSON.errormsg)
							alert(xmlhttp.headerJSON.errormsg);

						return;
					}
						
					wtfReloadSection('ids',theform);

				}
			});

		});

	},

	'#wtf_case_page form.wtf_dispute_form input[type=reset]': function(el) {

		Behaviour.RUN_EVERY_TIME.push('#wtf_case_page form.wtf_dispute_form input[type=reset]');
		el.stopObserving('click');
		el.observe('click',function(evt) {

			el.up('form').hide();

		});

	},	

	'div.wtf_id_links a.undispute': function(el) {

		Behaviour.RUN_EVERY_TIME.push('div.wtf_id_links a.undispute');
		el.stopObserving('click');
		el.observe('click',function(evt) {

			evt.stop();

			new Ajax.Request(el.href + "&ajax=1",{
				'method': 'get',
				'onSuccess': function(xmlhttp) {
					wtfReloadSection('ids',el.up('div.wtf_idfont'));
				}
			});
		});

	},
	
	'div.wtf_id_links a.change_sample_text': function(el) {

		Behaviour.RUN_EVERY_TIME.push('div.wtf_id_links a.change_sample_text');

		el.stopObserving('click');
		el.observe('click',function(evt) {

			evt.stop();
			
			var tempform = el.next('form').cloneNode(true);
			tempform.id = "";

			popupBox(tempform);

		});

	},

	'form.wtf_change_sample_text': function (theform) {

		Behaviour.RUN_EVERY_TIME.push('form.wtf_change_sample_text');

		theform.stopObserving('submit');
		theform.observe('submit',function(evt) {

			evt.stop();

			var inputs = theform.serialize(true);
/*
			var params = {
				'transparent': '1',
				'background': '#F5F5F5',
				'width': $('wtf_font_ids').getWidth() - 24,
				'size'
			};
*/
			
			var params = {
				'ajax': '1',
				'action': 'updateidrow',
				'threadid': inputs.threadid,
				'idid': inputs.idid,
				'update[SampleText]': inputs.text,
				'update[SampleSize]': inputs.size
			};

			hidePopupBox();

			new Ajax.Request(theform.readAttribute('action'), {
				'parameters': params,
				'onSuccess': function(xmlhttp) {

					wtfReloadSection('ids');

				}
			});
		});

	},
	
	'form.wtf_change_sample_text input[type=reset]': function (el) {

		Behaviour.RUN_EVERY_TIME.push('form.wtf_change_sample_text input[type=reset]');

		el.stopObserving('click');
		el.observe('click', hidePopupBox);

	},
	
	'a.close_dispute' : function(el) {
		el.onclick = function() {
				var idid = el.id.match(/_(\d+)/)[1];
	 		$('dispute_form_' + idid).hide();
			$('dispute_reason_' + idid).value= '';

			return false;
		}
 	},

	'div.wtf_idfont_render a': function(el) {
 		el.onclick = function() {
			var container = el.up('div');
			var idid = container.id.match(/_(\d+)$/)[1];
			container.hide();
			$('wtf_id_admin_' + idid).show();
			$('dispute_form_' + idid).hide();
			return false;
		}
 	},
 	
	'a.close_render_edit' : function(el) {
		el.onclick = function() {
			var idid = el.id.match(/_(\d+)/)[1];
	 		$('wtf_id_admin_' + idid).hide();

			return false;
		}
 	},

 	'#wtf_change_status a' : function(el) {

		Behaviour.RUN_EVERY_TIME.push('#wtf_change_status a');
		el.stopObserving('click');
		el.observe('click',function(evt) {
			$('wtf_change_status').hide();
			$('wtf_change_status_menu').show();
			evt.stop();
		});

	},

 	'div.wtf_status a' : function(el) {

		Behaviour.RUN_EVERY_TIME.push('div.wtf_status a');
		el.stopObserving('click');
		el.observe('click', function(evt) {

			evt.stop();

			if (el.up('#wtf_current_status'))
			{
				$('wtf_change_status').toggle();
				$('wtf_change_status_menu').toggle();
				return;
			}

			new Ajax.Request(el.href + "&ajax=1", {
				'method': 'get',
				'onSuccess': function(xmlhttp) {

					wtfReloadSection('status','wtf_status_overlord');
					wtfReloadSection('posts');

				}
			});

			var theold = $('wtf_current_status').down('div.wtf_status');
			var thenew = el.up('div.wtf_status');
			var newparent = thenew.parentNode;

			theold.parentNode.replaceChild(thenew,theold);

			newparent.insertBefore(theold,$('wtf_close_status_menu'));

			$('wtf_change_status_menu').hide();
			$('wtf_change_status').show();
		});
 	},

	'#wtf_close_status_menu': function(el) {
	
		Behaviour.RUN_EVERY_TIME.push('#wtf_close_status_menu');
		el.stopObserving();
		el.observe('click',function(evt) {

			$('wtf_change_status_menu').hide();
			$('wtf_change_status').show();
			evt.stop();

		});

	},

	'div.wtf_forum_post a.delete_message' : function(el) {

		Behaviour.RUN_EVERY_TIME.push('div.wtf_forum_post a.delete_message');
		el.stopObserving('click');
		el.observe('click', function(evt) {

			evt.stop();

			if (!confirm("Really delete message?")) return;

			new Ajax.Request(el.href + "&ajax=1", {
				'method': 'get',
				'onSuccess': function(xmlhttp) {

					wtfReloadSection('posts');

				}
			});

			var thepost = el.up('div.wtf_forum_post');

			thepost.style.backgroundColor = '#FFCCCC';
			
		});			

	},

	'div.wtf_forum_post a.edit_message' : function(a) {

		Behaviour.RUN_EVERY_TIME.push('div.wtf_forum_post a.edit_message');
		a.stopObserving('click');
		a.observe('click',function(evt) {

			var msgid = parseInt(a.href.match(/msgid=(\d+)/)[1]);

			if (msgid <= 0) return;

			var theform = $('msg_edit_form_'+msgid);

			try {

				var textarea = theform.down('textarea');

				textarea.writeAttribute('rows', Math.ceil(textarea.innerHTML.length / 40));

			} catch (er) {}

			$('msg_'+msgid).hide();

			theform.show();

			a.up('div.wtf_message_meta').hide();

			evt.stop();
			
		});

	},

	'div.wtf_forum_post form': function(theform) {

		Behaviour.RUN_EVERY_TIME.push("div.wtf_forum_post form");

		if (!theform.resetMessageForm)
			theform.resetMessageForm = window.resetMessageForm;

		theform.stopObserving('submit');
		theform.observe('submit', function(evt) {

			var params = theform.serialize(true);
			params.ajax=1;

			new Ajax.Request(theform.readAttribute('action'), {
				'parameters': params,
				'onSuccess': function(xmlhttp) {

					wtfReloadSection('posts','msg_edit_form_' + params.msgid);

				},
				'onFailure': function(xmlhttp) {

					theform.resetMessageForm();

				}
			});

			evt.stop();

		});

	},

	'div.wtf_forum_post form input[type=reset]' : function(el) {

		Behaviour.RUN_EVERY_TIME.push('div.wtf_forum_post form input[type=reset]');

		el.stopObserving('click');
		el.observe('click',function() {

			el.up('form').reset(); //MessageForm();
			el.up('form').hide();
			el.up('div.wtf_forum_post').down('div.wtf_message_meta').show();
			
			var msgid = parseInt(el.up('form').id.match(/msg_edit_form_(\d+)/)[1]);

			if (msgid > 0) 
				$('msg_'+msgid).show();			

		});

	},

 	
 	'#wtf_post_login_link': function(a) {

		Behaviour.RUN_EVERY_TIME.push("#wtf_post_login_link");
		a.stopObserving('click');
		a.observe('click',function(evt) {

			evt.stop();

			showPopupLogin('Please sign in to post.');

			Event.observe(document,'myfonts:loggedin',function() {

				wtfReloadSection('posts','wtf_post_login');

			});

		});

 	},
 	
 	'#wtf_subscribe_form': function(theform) {

		Behaviour.RUN_EVERY_TIME.push("#wtf_subscribe_form");
		theform.stopObserving('submit');
		theform.observe('submit',function(evt) {

			evt.stop();

			var notify = theform.getInputs('hidden','notify')[0].value;

			wtfReloadSection('sidebar',theform, { 'notify' : notify });

			if ($('wtf_reply_notify'))
				$('wtf_reply_notify').checked = notify;

		});

 	},
 	
 	'#wtf_identify_check': function(chk) {

		Behaviour.RUN_EVERY_TIME.push('#wtf_identify_check');
		chk.stopObserving('click');
		chk.observe('click',function(evt) {

			if (chk.checked) {
				chk.up('div.wtf_check_float').addClassName('on');
				$('wtf_identify_table').show();
				$('wtf_additional_comment').show();
			}
			else
			{
				chk.up('div.wtf_check_float').removeClassName('on');
				$('wtf_identify_table').hide();
				$('wtf_additional_comment').hide();
			}

		});

 	},
 	
 	'#wtf_notafont_check': function(chk) {

		Behaviour.RUN_EVERY_TIME.push('#wtf_notafont_check');
		chk.stopObserving('click');
 		chk.observe('click',function(evt) { $('wtf_similar_check').checked = chk.checked; });

	},

	'#wtf_identify_url': function(el) {

		Behaviour.RUN_EVERY_TIME.push('#wtf_identify_url');
		el.stopObserving('blur');
		el.observe('blur',function(evt) {

			if (!/myfonts\.com/.test($F('wtf_identify_url')))
				return;

			var namefield = $('wtf_identify_name');
			namefield.disabled = true;

			var oldvalue =	namefield.value;

			namefield.value = "Looking up name...";

			new Ajax.Request("ajax_get_name.php", {
				'parameters': { 'url' : el.value },
				'onSuccess': function(xmlhttp) {
					
					var fontname = xmlhttp.responseText;
					
					if (fontname.length)
					{
						namefield.value = fontname;
						namefield.disabled = true;
					}
					else
					{
						namefield.disabled = false;
						namefield.value = oldvalue;
					}
				}
			});

		})

	},

 	'#wtf_reply_form': function(theform) {

		Behaviour.RUN_EVERY_TIME.push("#wtf_reply_form");
		theform.stopObserving('submit');
		theform.observe('submit',function(evt) { evt.stop(); });

	},
	
	'#wtf_reply_preview, #wtf_reply_post': function(butt) {

		Behaviour.RUN_EVERY_TIME.push("#wtf_reply_preview, #wtf_reply_post");
		butt.stopObserving('click');
		butt.observe('click',function(evt) { window.wtfSubmitReply(butt); });

 	},
 	
 	'#wtf_stylelist_popup form': function(theform) {

		Behaviour.RUN_EVERY_TIME.push('#wtf_stylelist_popup form');
		theform.stopObserving('submit');
 		theform.observe('submit',function(evt) { evt.stop(); });
	},
 	
 	'#wtf_stylelist_popup input[type=button]': function(butt) {

		Behaviour.RUN_EVERY_TIME.push('#wtf_stylelist_popup input[type=button]');
		butt.stopObserving('click');
		butt.observe('click',function(evt) {

			$('wtf_stylelist_popup').hide();

			if (butt.value == 'Cancel') return;

			$('wtf_identify_url').value = butt.up('form').serialize(true).stylechoose;

			wtfSubmitReply();

		});

 	}
 	
};

Behaviour.register(wtfCaseBehaviour);