$(document).ready(function(){
	
	$("#categories").change(function(event){

			if ($(this).val() != '0') {
			
				initRequest();
				
				$.getJSON('http://www.yola.com/pages/page_controller/abuse/' + $(this).val() ,
			        function(data){
					 //clear divs:
					 $("#action").fadeIn("slow");
					 $("#natureOfComplaint").fadeIn("slow");
					 
					 try{
					 
						  var action = "<h3>How we respond</h3>" + data.action;
						  var reportIt = data.natureOfComplaint;				  
	
						  if(typeof(data.form) == "undefined"){
						  	$("#abuse_email_link").fadeIn("slow");
							$("#mailto").html("<a href='mailto:abuse@yola.com?subject=" + data.title + "&body=URL of offending site:&lt;br/&gt;Would you like us to forward a copy of your complaint to the website owner?'>abuse@yola.com</a>");
						  } else if (data.form == "standard") {
						  	$("#abuse_form").fadeIn("slow");
						  } else {
							$("#abuse_form").fadeIn("slow");
							
							if(typeof(data.form.fields) != "undefined") {
								$.each(data.form.fields, function(i,field){							
									var formField = createElement(field);
									document.getElementById("extra_fields").appendChild(formField);			
								});	
							}
							
						  }

						  $("#abuse_subject").val(data.title);
						  $("#action").html(action);
						  $("#natureOfComplaint").html(reportIt);					  
						  $("#abuse_standard_form").validate({onfocusout: true});					 
					 
					 } catch(e) {}

		        });
			}
	 });
	
});

function initRequest(){
	$("#user_response").show();
	$("#abuse_email_link").hide();
	$("#abuse_form").hide();
	
    $("#extra_fields").html("");
    $("#action").html("");
    $("#natureOfComplaint").html("loading information...");
}

function createElement(field){
	var holderDiv = document.createElement("div");
	var input = document.createElement('input');
	var spanLbl = document.createElement("span");
	var clearerDiv = document.createElement("div");
	
	try{
		spanLbl.className = "label"
		lbl = document.createTextNode(field.label);
		spanLbl.appendChild(lbl);

		clearerDiv.className = "clearer";

		for (var name in field) {
			
			/* there is a problem with setting the class attribute in IE, have to use .className instead of setAttribute */
			if (name != 'className') {
				input.setAttribute(name,eval('field.' + name));				
			} else {
				input.className = eval('field.' + name);
			}
			
			//input.setAttribute(name,eval('field.' + name));
		}
	
		holderDiv.appendChild(spanLbl);
		holderDiv.appendChild(input);
		holderDiv.appendChild(clearerDiv);
	
		return holderDiv;
			
	} catch(e) {
		return false;
	}
}