$(document).ready(function(){

	// ColorBox popup forms:
	// 1. be able to insert multiple forms on a page.
	// 2. be able to have the CMS react as normal to the submissions and errors.
	// 3. be able to add images that will link to each form.
	// Will forms ever have the same field ID? That would make error detection difficult if there were
	// many forms and the same field IDs on the same forms.
	// http://bit.ly/rrZzAB

	$(".monkForm").each(function(){
	
		// Define form vars
		var formID = $(this).attr("id");
		var formImg = "#" + formID + "-image";
		var formTitle = formID.replace(/-/g," ");
		
		// Produce form links
		if ($(formImg).length) {
			// If images are set
			$(formImg).wrap('<p><a class="formLink" rel="'+ formID +'" href="#" style="text-transform:capitalize;"></a></p>');
		} else {
			// If there is no image
			$(this).before('<p><a class="formLink" rel="'+ formID +'" href="#" style="text-transform:capitalize;">'+ formTitle +'</a></p>');
		}
		
	});
	

	// Popup rules
	if(window.location.href.indexOf("ferr") <= 0) {
	
		// NORMAL POPUP
		$(".formLink").colorbox({
			width:500,
			height:650,
			close:"CANCEL",
			inline:true,
			href:function(){
			    return "#" + $(this).attr('rel');
		    },
		    onOpen:function(){
		    	var popupForm = "#" + $(this).attr('rel');
		    	$(popupForm).show();
		    },
		    onCleanup:function(){
		    	var popupForm = "#" + $(this).attr('rel');
		    	$(popupForm).hide();
		    }
		});
         
    } else {
	
		// ERROR POPUP
         $(".formLink").colorbox({
			open:true,
			width:500,
			height:650,
			close:"CANCEL",
			inline:true,
			href:function(){
				return "#" + $(".monkForm:has(.error)").attr("id");
		    },
			onComplete:function(){
		    	var popupForm = "#" + $(".monkForm:has(.error)").attr("id");
		    	$(popupForm).show();
		    },
		    onCleanup:function(){
		    	var popupForm = "#" + $(".monkForm:has(.error)").attr("id");
		    	$(popupForm).hide();
		    }
		});
         
    
    }

	// Custom thank-you
	if ($('span.mcms_form_thank_you').length) {
		$("#content img[id*='-image']").remove();
		$('span.mcms_form_thank_you').parent().wrapAll('<div id="thanks-div" />');
		$('#thanks-div').replaceWith("<p style='font-weight:bold;font-style:italic;'>Thanks very much for submitting!</p>");
	}

});
