/**
	@class
	@description Toggler
*/
REFRESH_APP.toggler = {
	active: false,
	/**
		Init
	*/
	init: function($button, $content) {
		$button.click( function(e) {
			e.preventDefault();
			if (REFRESH_APP.toggler.active) {
				$content.slideUp();
				REFRESH_APP.toggler.active = false;
			} else {
				$content.slideDown();
				REFRESH_APP.toggler.active = true;
			}
		});
	}
	
};

REFRESH_APP.ConditionalRadioFields = function() {
	var conditionalClass = ".has-conditional-fields";
	
	// init
	$(conditionalClass + ":checked").each(function() {
		_changeState(this.id);
	});

	// events
	$(conditionalClass).live("click", function() {
		_changeState(this.id);
	});
	
	// private
	function _changeState(id) {
		$(".show-" + id).show();
		$(".hide-" + id).hide();
	}
	
};

/**
	@namespace Register object
*/
REFRESH_APP.submission = {

	/**
		Initializes REFRESH_APP.register; Grabs 'id' from body tag and executes init to corresponding sub-object
	*/
	init: function() {
	
		jQuery(function($) {
		
			REFRESH_APP.submission.formHighlighting.init( $('form.highlighting') );
			var id = $('body').attr('id');
			REFRESH_APP.submission[id].init();
			REFRESH_APP.submission.tooltips.init();
			//REFRESH_APP.submission.checkFB();
			new REFRESH_APP.ConditionalRadioFields();
		});
		
		
		$(window).load(function() {
			$(".btn-savecontinue").click(function(e) {				
				var bodyId = $("body").attr("id");

				if(bodyId == "submitIdea") { 
					_gaq.push(['_trackEvent', 'application', 'idea submission save', 'Step 1 - Your Idea']);
				} else if(bodyId == "submitBasics") {
					_gaq.push(['_trackEvent', 'application', 'idea submission save', 'Step 2 - The Basics']);
				} else if(bodyId == "projectDetails") {
					_gaq.push(['_trackEvent', 'application', 'idea submission save', 'Step 3 - Project Details']);
				} else if(bodyId == "tasks") {
					_gaq.push(['_trackEvent', 'application', 'idea submission save', 'Step 4 - Planning']);
				} else if(bodyId == "media") {
					_gaq.push(['_trackEvent', 'application', 'idea submission save', 'Step 5 - Photo & Video']);
				} else if(bodyId == "submitPreview") {
					_gaq.push(['_trackEvent', 'application', 'idea submission save', 'Step 6 - Review & Finalize']);
				}
			});
		});
	},
	
	checkFB: function() {
	
		$('#facebook-logout-submit').live('click', function(e) {
			e.preventDefault();
			FB.Connect.logoutAndRedirect(this.href);
		});
		
		FB_RequireFeatures(["Connect"], function() {
		
			FB.Connect.get_status().waitUntilReady(function(status) {
				switch(status) {
					case FB.ConnectState.connected:
						$("#submit-message").html('<h1>To submit an Idea <a id="facebook-logout-submit" href="/index/logout?' + Math.floor(Math.random()*10000) + '">sign out</a> from Facebook.</h1>');
						$('.empty-border').hide();
						$("#idea").hide();
					break;
					case FB.ConnectState.appNotAuthorized:
					case FB.ConnectState.userNotLoggedIn:
					break;
				}
			});
		
		}); 	
	},
	
	/**
		Initializes REFRESH_APP.register; Grabs 'id' from body tag and executes init to corresponding sub-object
	*/
	message: {
		/**
			Initialize
		*/
		init: function() {
			//
		}
	},

	/**
		Initializes REFRESH_APP.register; Grabs 'id' from body tag and executes init to corresponding sub-object
	*/
	confirmation: {
		/**
			Initialize
		*/
		init: function() {
			//
		}
	}

};

REFRESH_APP.submission.init();

//	-----------------------------
//	    SUBMISSION STEP: Idea
//	-----------------------------

/**
	Handles registration step: The Idea
*/
REFRESH_APP.submission.submitIdea = {
	applicantTypeNum: "",
	submissionContainers: "",
	extendedValidation: "",
	/**
		Initializes theIdea
	*/
	init: function() {
		var submission = REFRESH_APP.submission,
			self = this;
			
		self.submissionContainers = $(".submitter-type-container");
						
		// label click
		this.setupCategoryActiveState();
		
		submission.charCountdown.init('.textarea-help');
		//REFRESH_APP.submission.theIdea.validateForm( $('#form-idea') );
		this.grantUpdating();
		
		this.setValidation(function() {
			// applicant type
			self.applicantType();			
		});

		submission.superFields.numericMask( $('body') );
		REFRESH_APP.toggler.init( $('a#toggle-keydates'), $('#col-set-keydates') );
		
		// show question if you select new pepsi challenge
		self.challengeQuestion();
		
		submission.autoSave.init( { url:'/myidea/details/autosave/1', time:0 } );
	},
	/**
		Validation for theIdea
	*/
	challengeQuestion: function() {
		var $cq = $(".challenge-question"),
			$selected = $(".categories .selected");
			
		if($selected.get(0) != null && $selected.find("h3").html().search("Pepsi Challenge") != -1) {
			$cq.show();
		}
		
		$("#choose-category input").click(function(e) {
			var $desc = $(e.target).parents(".category-wrap").find("h3");
				
			if($desc.get(0).innerHTML.search("Pepsi Challenge") == -1) {
				$cq.hide();				
			} else {
				$cq.show();
			}
		});
		
	},
	/**
		Validation for theIdea
	*/
	setupCategoryActiveState: function() {
		
		$("#choose-category input").click(function() {
			$(".category-wrap").removeClass("selected");
			var $wrap = $(this).parents(".category-wrap");
				$wrap.addClass("selected");
			
			try {
				$.cookie("category", $.trim( $wrap.find("h3").text() ) );
			} catch(e) {}
		});
		
		$("#choose-category input:checked").click();
	},
	/**
		Validation for theIdea
	*/
	setValidation: function(cbf) {
		REFRESH_APP.general.getScript('/js/submit/validation-idea.js', cbf);
		//$.getScript('/js/submit/validation-idea.js');
	},
	updateValidationRules: function() {
		var self = this;
		$('#idea').validate().settings.rules = $.extend({}, defaultRules, extendedRules[self.extendedValidation]);	
	},
	setExtendedValidation: function() {
		var self = this;
		
		// this is to determine which validation obj gets used in validation-idea.js
		if (self.applicantTypeNum == 1) {
			self.extendedValidation = "individual";
			if($("input[name=hasPartnerOrganization]:checked").val() === "true") {
				self.extendedValidation = "individual-extended";
			}
		} else if(self.applicantTypeNum == 2) {
			self.extendedValidation = "non-profit";
		} else if(self.applicantTypeNum == 3) {
			self.extendedValidation = "business";
		}
		
		this.updateValidationRules();
	},
	/**
		Show a different form based on who is applying
	*/
	applicantType: function() {
		var self = this,
			$yourType = $("#your-type"),
			$selected = $yourType.find("input:checked"),
			$containers = $yourType.find(".submitter-type-container"),
			$fields = $containers.find("input");
		
		$fields.attr("disabled", "disabled");
		
		$yourType.find(".tab input[type=radio]").click(function(e) {	

			$yourType.removeClass("applicant-type-" + self.applicantTypeNum);

			if(self.applicantTypeNum) {
				$(".submitterTypeId-" + self.applicantTypeNum).find(".error").remove();
			}

			self.applicantTypeNum = $(this).val();
			
			// toggle enabled/disabled on fields so there are no name clashes
			$fields.attr("disabled", "disabled");			
			$(".submitterTypeId-" + self.applicantTypeNum).find("input").attr("disabled","");
			
			$yourType.addClass("applicant-type-" + self.applicantTypeNum);
			
			self.setExtendedValidation();
		});
		
		// yes, I'm teaming up
		$("#hasPartnerOrganization-1").click(function() {
			self.extendedValidation = "individual-extended";
			self.updateValidationRules();
		});
		// no, I'm not teaming up
		$("#hasPartnerOrganization-2").click(function() {
			self.extendedValidation = "individual";
			self.updateValidationRules();
		});
		
		if($selected.get(0) != null) {
			$selected.trigger("click");
			// todo: figure out why extendedValidation isn't getting set right
			self.setExtendedValidation();
		}
		
	},
	/**
		Update values for grant selection
	*/
	grantUpdating: function() {
		var limits = new Array();
		var $mt = $('#monetaryTierId');
		var $g = $mt.siblings('p.grants');
		var $s = $g.find('span');
		limits[1] = 20;
		limits[2] = 15;
		limits[3] = 15;
		limits[4] = 10;
		$s.html(limits[$mt.val()]);
		$('#monetaryTierId').change( function() {
			$s.html(limits[ $(this).val() ]);
		}); 
	}
};



//	-------------------------------
//	    SUBMISSION STEP: Basics
//	-------------------------------

/**
	Handles registration step: The Basics
*/
REFRESH_APP.submission.submitBasics = {
	/**
		Initializes theBasics
	*/
	init: function() {
		REFRESH_APP.submission.submitBasics.setValidation();
		REFRESH_APP.submission.submitBasics.pageCleanup();
		REFRESH_APP.submission.superFields.numericMask( $('body') );
		REFRESH_APP.selectBirthday.init();
		REFRESH_APP.captcha.init();
		REFRESH_APP.submission.autoSave.init( { url:'/myidea/details/autosave/1', time:0 } );
	},
	/**
		Validation for theBasics
	*/
	setValidation: function() {
		REFRESH_APP.general.getScript('/js/submit/validation-basics.js');
		//$.getScript('/js/submit/validation-basics.js');
	},
	/**
		Clean up some visuals for zend fixing
	*/
	pageCleanup: function() {
		//$('<p class="or">&ndash; OR &ndash;</p><label><strong>I am</strong></label>').insertAfter( $('label[for=affiliationId-1]') );
		$('input[name=affiliationId]:not(:first)').addClass('tipped');	
	}
};


//	--------------------------------------------
//	    SUBMISSION STEP: Basics (Short form)
//	--------------------------------------------

/**
	Handles registration step: The Basics
*/
REFRESH_APP.submission.submitBasicsShort = {
	/**
		Initializes theBasics
	*/
	init: function() {
		REFRESH_APP.submission.submitBasicsShort.setValidation();
		REFRESH_APP.submission.submitBasics.pageCleanup();
		REFRESH_APP.submission.superFields.numericMask( $('body') );
		REFRESH_APP.submission.autoSave.init( { url:'/myidea/details/autosave/1', time:0 } );
	},
	/**
		Validation for theBasics
	*/
	setValidation: function() {
		REFRESH_APP.general.getScript('/js/submit/validation-basics-short.js');
		//$.getScript('/js/submit/validation-basics-short.js');
	}
};


//	----------------------------------------
//	    Project Admin
//	----------------------------------------

/**
	Handles Project Admin
*/
REFRESH_APP.submission.ideaAdmin = {

	checkError: function(e) {
	
		var parent = $(this).parents('div.edit-field');
	
		if(e.type === 'onshow') {
			$('span.edit-error',parent).remove();
			parent.find('div.edit-link').append('<span class="edit-error">Errors</span>');
		} 
		
		if(e.type === 'onafterhide')  {
		
			var len = parent.find('p.error:visible').length;
			if(len < 1) {
				parent.find('span.edit-error').remove();
			}
		
		}
			
	},

	init: function() {
		setTimeout(function() {
			$("#updated").fadeOut("slow");
		}, 1000);
		$('.tipped').removeClass('tipped');
		$('#admin div.edit-field').addClass('edit-field-open');
		REFRESH_APP.submission.charCountdown.init('.textarea-help');
		REFRESH_APP.submission.findYoutubeVideo.init( $('#videoLink') );
		REFRESH_APP.submission.ideaAdmin.setValidation();
		REFRESH_APP.submission.richText.init( { onchange:function(){} } );
		REFRESH_APP.submission.multiFields.init();
		REFRESH_APP.submission.superFields.init();
		REFRESH_APP.submission.ideaAdmin.fieldsetLinks();
	},
	
	setValidation: function() {
		REFRESH_APP.general.getScript('/js/submit/validation-edit.js');
	},
	
	fieldsetLinks: function() {
	
		$('#admin div.edit-link').find('a.edit-title, a.edit-icon').live('click',function(e) {
		
			e.preventDefault();
			var obj = $(this);
			var parent = obj.parents('div.edit-field');
			if(parent.hasClass('edit-field-open')) {
				parent.removeClass('edit-field-open');
			} else {
				$('#admin div.edit-field-open').removeClass('edit-field-open');
				parent.addClass('edit-field-open');
			}
		
		});
	
	}

}



//	----------------------------------------
//	    SUBMISSION STEP: Project Details
//	----------------------------------------

/**
	Handles registration step: Project Details
*/
REFRESH_APP.submission.projectDetails = {

	/**
		Set hidden groups show/hide actions
	*/
	setHiddenGroups: function() {
		var $containers = $('#locationTypeId-1,#locationTypeId-2,#locationTypeId-3,#locationTypeId-4,#locationTypeId-5'),
			$groups = $('#locationTypeId-1-group,#locationTypeId-2-group,#locationTypeId-3-group,#locationTypeId-4-group,#locationTypeId-5-group'),
			groupHTML = {};
			
			// remove HTML from dom when not selected so other fields don't get passed along
			$groups.each(function() {
				groupHTML[this.id] = $(this).html();
			});

		_changeSelectedSubForm = function(id) {
			$groups.hide();
			$groups.find("input,select").attr("disabled","disabled");
			$groups.html("");
			
			$("#project-location .error").remove();
			
			var $id = $('#' + id + '-group');			
			$id.show(); 
			$id.html(groupHTML[id + "-group"]);
			$id.find("input,select").attr("disabled","");
		};
		
		$containers.each(function() {
			var obj = $(this);
			if(obj.attr('checked') == true) {
				var id = obj.attr('id');
				$('#' + id + '-group').show();
			}
		});

		$containers.click(function(e) {
			var id = $(this).attr('id');
			_changeSelectedSubForm(id);
		});
		
		_changeSelectedSubForm($("#project-location .label-radio input:checked").attr("id"));
	},
	
	/**
		Initializes projectDetails
	*/
	init: function() {
		if($.cookie("PEPSI_HEAVY_REGISTRATION") == "true") {		
			pageTracker._setCustomVar(1, 'account-type', 'pepsi-heavy', 2);
			pageTracker._trackEvent('Account', 'registration', 'heavy');
			REFRESH_APP.gaCustomVars.reset();
			
			$.cookie("PEPSI_HEAVY_REGISTRATION", "false", {secure: false, domain: document.domain, path: "/"});
		}
		
		$('#project-links select').find("option[value=14]").remove();
		REFRESH_APP.submission.charCountdown.init('.textarea-help');
		
		this.setValidation();
		this.setHiddenGroups();
		
		REFRESH_APP.submission.autoSave.init( { url:'/myidea/details/autosave/1', time:60 } );
		REFRESH_APP.submission.richText.init( { onchange:REFRESH_APP.submission.autoSave.change });
		
		this.toggleNameTitle();
		this.pageCleanup();
		//REFRESH_APP.submission.projectDetails.toggleSetInit( $('#budget-source'), 'Y', $('#budget-source .fieldset-counter') );
		//REFRESH_APP.submission.projectDetails.toggleSetInit( $('#project-staff'), '2', $('#project-staff .field-multiples') );
		//REFRESH_APP.submission.projectDetails.toggleSetInit( $('#project-start'), '2', $('#project-start .start-group') );
		//$('#staffingTypeId-2').addClass('tipped');
	
	},

	/**
		Toggle set
	*/
	toggleSetInit: function(inputContainer, triggerValue, setContainer) {
		setContainer.hide();
		var inputs = $('input[type=radio]', inputContainer);
		inputs.each(function() {
			var obj = $(this);
			obj.data('setContainer',setContainer);
			obj.data('triggerValue',triggerValue);
			if(this.checked) REFRESH_APP.submission.projectDetails.toggleSetCheck( $(this) );
		});
		inputs.click(function() {
			REFRESH_APP.submission.projectDetails.toggleSetCheck($(this));
		});
	},
	
	toggleSetCheck: function(obj) {
		var triggerValue = obj.data('triggerValue');
		var setContainer = obj.data('setContainer');
		if ( obj.val() == triggerValue ) {
			setContainer.show();
		} else {
			setContainer.hide();
		}
	},

	/**
		Validation for projectDetails
	*/
	setValidation: function() {
		REFRESH_APP.general.getScript('/js/submit/validation-details.js');
	},

	/**
		Validation for projectDetails
	*/
	toggleNameTitle: function() {
		$p = $('#your-type');
		$nt = $('#name-title span');
		// handle initial
		var v = $p.find('input:checked').val();
		if ( v==null || v==='1' ) {
			$nt.html('yourself');
		} else {
			$nt.html('your organization');				
		}
		// handle change
		$p.find('input[name=submitterTypeId]').change( function() {
			var v = $p.find('input:checked').val();
			if ( v==null || v==='1' ) {
				$nt.html('yourself');
			} else {
				$nt.html('your organization');				
			}
		});
	},
	/**
		Clean up some visuals for zend fixing
	*/
	pageCleanup: function() {
		/*$('#project-location input[name=locationTypeId]').each( function() {
			$me = $(this);
			id = $me.attr('id');
			$('#'+id+'-group').insertAfter( $('label[for='+id+']') );
		});*/
	}

};

//	-------------------------------
//	    SUBMISSION STEP: Tasks
//	-------------------------------
/**
	Handles registration step: Task entry
*/
REFRESH_APP.submission.tasks = {
	/**
		Initializes theBasics
	*/
	init: function() {
		this.setValidation();
		REFRESH_APP.submission.multiFields.init();		
		REFRESH_APP.submission.superFields.init();		
		REFRESH_APP.submission.autoSave.init( { url:'/myidea/tasks/autosave/1', time:0 } );
		
		// all the tasks textareas
		$(".limited").maxlength()
	},
	/**
		Validation for media
	*/
	setValidation: function() {
		REFRESH_APP.general.getScript('/js/submit/validation-tasks.js');
	}
};


//	-------------------------------
//	    SUBMISSION STEP: Photos and Videos
//	-------------------------------

/**
	Handles registration step: Photos and Video
*/
REFRESH_APP.submission.media = {
	/**
		Initializes theBasics
	*/
	init: function() {
		this.setValidation();
		
		REFRESH_APP.submission.findYoutubeVideo.init( $('#videoLink') );
		REFRESH_APP.submission.superFields.init();
		
		REFRESH_APP.submission.autoSave.init( { url:'/myidea/media/autosave/1', time:0 } );
	},
	/**
		Validation for media
	*/
	setValidation: function() {
		REFRESH_APP.general.getScript('/js/submit/validation-media.js');
		// $.getScript('/js/submit/validation-basics.js');
	}
};

//	--------------------------------
//	    SUBMISSION STEP: Preview
//	--------------------------------

/**
	Handles registration step: Contact Information
*/
REFRESH_APP.submission.submitPreview = {
	/**
		Initializes
	*/
	init: function() {
		$('#projectUrl').slugify('#projectUrl'); 
		this.setValidation();
		this.customFieldset();
		REFRESH_APP.submission.previewAccordian.init();
		REFRESH_APP.submission.findYoutubeVideo.initStatic( $('#videoLink') );
	},
	setUrlValidity: function(input, callback) {
		$projectUrlValid = $("#projectUrlValid"),
		$projectUrlError = $("p[htmlfor=projectUrlValid]");
		
		$.getJSON("/myidea/validprojecturl?projecturl=" + input.val(), function(data) {
			if(data.isValid) {
				$projectUrlValid.val("true");
				callback(true);
				$projectUrlError.hide();	
			} else {
				$projectUrlValid.val("");
				callback(false);
				$projectUrlError.show();	
			}
		});
	},
	/**
		Validation
	*/
	setValidation: function() {
		REFRESH_APP.general.getScript('/js/submit/validation-preview.js');
	},
	/**
		Custom fieldset handling
	*/
	customFieldset: function() {
		$('#urlIdea, #tags').blur(function() {
			$(this).parents('fieldset').removeClass('highlight');
		});
	}
};


//	--------------------------------
//	    HELPERS
//	--------------------------------

/**
	Handles multiple image upload fields
*/
REFRESH_APP.submission.multipleImages = {

	/**
		Clear error messages and print new error message if any.
	*/
	clearError: function(obj,error) {
		obj = $('#'+obj).parent();
		$('p.error', obj).remove();
		$('div.uploading', obj).remove();
		if(error) {
			obj.append('<p generated="true" class="error">'+error+'</p>');
		}
	},

	/**
		AjaxUpload OnComplete callback.  If the file were uploaded, show the uploaded image, remove "uploading" div, show next field and change value of hidden input.
		If not, show the error.		
	*/	
	oncomplete: function(file,data) {
	
		if(typeof(data.error) != 'undefined') {
			var self = REFRESH_APP.submission.multipleImages;
			self.clearError(data.field);
			if(data.error != '') {
				self.clearError(data.field,data.error);
			} else {
				var img = new Image();
				img.width = '120';
				var url = '/images/submit/photo.jpg';
				if(data.url) url = unescape(data.url);
				var obj = $('#'+data.field).parent();
				
				// make it work in IE on dev
				url = document.location.protocol + "//" + window.location.host + "/image_uploads/" + url.split("/image_uploads/")[1];
				
				$(img).load(function () {
					var self = REFRESH_APP.submission.multipleImages;
					$('div.uploading', obj).remove();
					$('input.input-text', obj).before(this);
					obj.next().addClass('image-wrap-visible');
					self.addHoverEvent(obj);
					pageTracker._trackEvent('Idea Submission Process', 'add another photo');
				}).error(function() {
					self.clearError(data.field,'Error: Image failed to upload. Please try again.');
				}).attr('src', url);
				var pathField = data.field.split('Upload').join('Path');
				$('#'+pathField).val(data.path);
			}
		}

	},
	
	/**
		Add AjaxUpload feature to field.
	*/	
	addAjaxUpload: function(obj) {
		var self = this;
		new AjaxUpload(obj, {
			name: obj.id + 'AjaxUpload',
			data: {
				'field' : obj.id,
				'upload' : obj.id + 'AjaxUpload'
			},
			action: self.url,
			autoSubmit: true,
			responseType: 'json',
			onSubmit: self.onsubmit,
			onComplete: self.oncomplete
		});
	},
	
	/**
		Add hover event to field wrap, in order to show the remove button and number.
	*/		
	addHoverEvent: function(obj) {
		obj.unbind('mouseenter mouseleave');
		obj.hover(function() {
			$(this).addClass('image-wrap-over');
		}, function() {
			$(this).removeClass('image-wrap-over');;
		});
	},
	
	/**
		Add remove button event to reset each field wrap.
	*/	
	addRemoveAction: function() {

		$('div.image-multiples .btn-remove').live('click',function(e) {
			e.preventDefault();
			var parent = $(this).parent();
			parent.removeClass('image-wrap-over image-wrap-done').unbind('mouseenter mouseleave');
			$('img',parent).remove();
			$('input[type="hidden"]',parent).val('');
			pageTracker._trackEvent('Idea Submission Process', 'remove photo');
		});
		
	},
	
	/**
		AjaxUpload OnSubmit callback.  Check for file extension, if it's ok, remove last error message, last uploaded image and last "uploading" div.
		Add class ".image-wrap-done" to field wrap, hidding the input file and label.  Add a "uploading" div to indicate that the file will be uploaded.
	*/	
	onsubmit: function(field,ext) {
		var self = REFRESH_APP.submission.multipleImages;
		if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
			self.clearError(this._button.id,'Error: invalid file extension');
		    return false;
		} else {
			var obj = $('#'+this._button.id).parent();
			$('img', obj).remove();
			$('p.error', obj).remove();
			$('div.uploading', obj).remove();
			obj.addClass('image-wrap-done');
			obj.prepend('<div class="uploading">Uploading</div>');
			return true;
		}
	},
	
	/**
		Initialize the script.  Add AjaxUpload feature to all input file fields inside div ".image-multiples", 
		add remove button events and if there is saved content show hidden field wraps.
	*/	
	init: function(params) {

		var self = this;
		this.url = params.url;
				
		$('div.image-multiples .input-text').each(function() {
		
			var parent = $(this).parent();
			
			if($('img',parent).length > 0) {
				self.addHoverEvent(parent);
				parent.addClass('image-wrap-done image-wrap-visible');
				parent.next().addClass('image-wrap-visible');
			}

			self.addAjaxUpload(this);
			
		});
		
		self.addRemoveAction();
		
	}
	
};

function formatCurrency(strValue) {
	if(strValue.length < 1) return '';
	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);
	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intCents = dblValue%100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
	return (dblValue);
}

/**
	Manages form "super fields".
*/
REFRESH_APP.submission.superFields = {

	/**
		do the Math of money masked fields
	*/
	doMath: function() {
		var sum = 0;
		$('#project-budget input.mask-money').each(function() {
			var n = parseInt($(this).val().toString().replace(/\$|\,/g,''),10);
			if(n>0) sum+= n;
		});
		REFRESH_APP.submission.superFields.calculatorTotal.text(formatCurrency(sum.toString()));
		$('#project-budget input.mask-money').trigger('focusout');
	},
	
	/**
		Apply numeric mask
	*/
	numericMask: function(container) {
		$("input.mask-numeric, input.mask-money", container).numeric();
		if($('#planning').length > 0) {
			$("input.mask-money").live('keyup',REFRESH_APP.submission.superFields.doMath);
			$("#project-budget").live('click',function() {
				$("#planning").validate().element("#project-budget input.mask-money:first");
			});
		}
	},

	/**
		Apply money mask, onChange of money masked fields, do the Math
	*/
	moneyMask: function(container) {
		var obj = $("input.mask-money", container);
		obj.unmaskMoney();
		obj.maskMoney( {symbol:"", onchange:REFRESH_APP.submission.superFields.doMath } )
	},
	

	/**
		Get "super fields" script and load necessary form objects
	*/	
	init: function() {
		this.calculatorTotal = $('#budget-total span');
		REFRESH_APP.general.getScript('/js/library/jquery.superfields.js', function() {
			$(function(){
				REFRESH_APP.submission.superFields.numericMask( $('body') );
				REFRESH_APP.submission.superFields.doMath();
				REFRESH_APP.submission.datepicker.init();	
				REFRESH_APP.submission.multipleImages.init( { url:'/photo/upload/width/120' } );
				REFRESH_APP.submission.imageUpload.init( { url:'/photo/upload/width/435', input:'submitterImageUpload', container:'jcrop-wrap', image:'submitterImagePath', crop:'jcrop-image', preview:'jcrop-preview' } );
			});
		});
		//$.getScript('/js/library/jquery.superfields.js', ... );
	}
	
};


/**
	Handles Profile Image upload and crop
*/
REFRESH_APP.submission.imageUpload = {

	/**
		Clear error messages, print new error message if any and clear some hidden fields
	*/
	clearError: function(error) {
		var self = this;
		var parent = self.input.parent();
		$('p.error', parent).remove();
		self.image.val('');
		self.imageCoords.val('');
		if(error) {
			parent.append('<p generated="true" class="error">'+error+'</p>');
			self.container.hide();
		}
	},

	/**
		Show image preview, update coordinates of hidden field
	*/
	showPreview: function(coords) {
		if(coords.h > 0 && coords.w) {
			var rx = 128 / coords.w;
			var ry = 128 / coords.h;
			var self = REFRESH_APP.submission.imageUpload;
			self.imageCoords.val(coords.x + ',' + coords.y + ',' + coords.w + ',' + coords.h);
			$('img',self.preview).css({
				width: Math.round(rx * self.imgWidth) + 'px',
				height: Math.round(ry * self.imgHeight) + 'px',
				marginLeft: '-' + Math.round(rx * coords.x) + 'px',
				marginTop: '-' + Math.round(ry * coords.y) + 'px'
			});
		}
	},

	/**
		AjaxUpload OnComplete callback.  Apply jcrop, remove class "loading" and show preview image.
	*/
	oncomplete: function(file, data) {
	
		if(typeof(data.error) != 'undefined') {
			var self = REFRESH_APP.submission.imageUpload;
			self.clearError();
			if(data.error != '') {
				self.clearError(data.error);
			} else {
				var img = new Image();
				var url = '/images/submit/jcrop.jpg';
				
				if(data.url) { 
					url = unescape(data.url);
				}
				
				url = url.split('#').join('%23');
				self.crop.append(img);
				self.image.val(data.path);
				self.imageCoords.val('0,0,100,100');
				
				// make it work in IE on dev
				url = document.location.protocol + "//" + window.location.host + "/image_uploads/" + url.split("/image_uploads/")[1];
				
				$(img).load(function () {
					var self = REFRESH_APP.submission.imageUpload;
					self.crop.removeClass('loading');
					self.imgWidth = $(this).width();
					self.imgHeight = $(this).height();
					
					var maxSize = Math.min(self.imgHeight, self.imgWidth);
						
					var coords = [0, 0, maxSize, maxSize];
					
					$('img', self.crop).Jcrop({
						onChange: REFRESH_APP.submission.imageUpload.showPreview,
						onSelect: REFRESH_APP.submission.imageUpload.showPreview,
						aspectRatio: 1,
						setSelect: coords
					});
					$('div.thumb',self.preview).html('<img src="'+url+'" />');
					pageTracker._trackEvent('Idea Submission Process', 'photo upload');
				}).error(function() {
					self.clearError('Error: Image failed to upload. Please try again.');
				}).attr('src', url);
			}
		}
		
	},
	
	/*
		AjaxUpload OnSubmit callback.  Check for file extension, if it's ok, remove last error message, last uploaded thumb and class "loading".
		Show container.
	*/	
	onsubmit: function(field,ext) {
		var self = REFRESH_APP.submission.imageUpload;
		if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
			self.clearError('Error: invalid file extension');
		    return false;
		} else {
			$('#submitterImageDisplay').hide();
			self.crop.html('').addClass('loading');
			$('div.thumb',self.preview).html('');
			self.clearError();
			self.container.show();
			return true;
		}
	},
	
	/**
		Check for saved values.  If there is an image inside the field wrap, apply jcrop, show the container and preview div.
	*/	
	checkSaved: function() {
	
		var self = this;
		var img = $('img',self.crop);
		if(img.length > 0) {
			self.container.show();
			var coords = self.imageCoords.val();
			if(coords.length>0) coords = coords.split(',');
			else coords = [0, 0, 100, 100];
			self.imgWidth = img.width();
			self.imgHeight = img.height();
			img.Jcrop({
				onChange: REFRESH_APP.submission.imageUpload.showPreview,
				onSelect: REFRESH_APP.submission.imageUpload.showPreview,
				aspectRatio: 1,
				setSelect: coords
			});
			var url = img.attr('src');
			$('div.thumb',self.preview).html('<img src="'+url+'" />');		
		}
	
	},
	
	/**
		Add AjaxUpload feature to field.
	*/	
	addAjaxUpload: function() {
	
		var self = this;
		new AjaxUpload('#'+self.inputId, {
			name: self.id + 'AjaxUpload',
			data: {
				'field' : self.inputId,
				'upload' : self.inputId + 'AjaxUpload'
			},
			action: self.url,
			autoSubmit: true,
			responseType: 'json',
			onSubmit: self.onsubmit,
			onComplete: self.oncomplete
		});
	
	},

	/**
		Initialize the script.  Get and save all DOM object, add AjaxUpload feature and check for saved values.
	*/
	init: function(params) {

		this.container = $('#'+params.container);
		this.crop = $('#'+params.crop);
		this.image = $('#'+params.image);
		this.imageCoords = $('#'+ params.input.split('Upload').join('Coords'));
		this.preview = $('#'+params.preview);
		this.inputId = params.input;
		this.input = $('#'+params.input);
		this.url = params.url;
		
		if(this.input.length > 0) {
			this.addAjaxUpload();
			this.checkSaved();
		}
		
	}
};


/**
	Create autoSave mechanism
*/
REFRESH_APP.submission.autoSave = {
	/**
		onChange event applied for each for element
	*/
	change: function() {
		//REFRESH_APP.submission.autoSave.changed = true;
	},
	/**
		onLoad POST event
	*/
	onload: function(resp) {
		//$('#form-saving').remove();
		//REFRESH_APP.submission.autoSave.setPostTimeOut();
		//pageTracker._trackEvent('Idea Submission Process', 'idea submission autosave', $('#grantCategory').val());
	},
	/**
		set POST timeout
	*/
	setPostTimeOut: function() {
		//var self = REFRESH_APP.submission.autoSave;
		//if(self.time == 0) return;
		//clearTimeout(self.timeOut);
		//self.timeOut = setTimeout(self.save,self.time);
	},
	/**
		POST form values
	*/
	save: function() {
		/*
		var self = REFRESH_APP.submission.autoSave;
		clearTimeout(self.timeOut);
		if(self.changed) {
			var saving = $('<div id="form-saving">' +msg_saving+ '</div>');
			$('body').append(saving);
			if(self.oldbrowsers){
				var scrollTop = $(window).scrollTop();
				var height = $(window).height();
				var width = $(window).width();
				saving.css({ 'position':'absolute','left':-saving.width()+(width/2), 'top':-saving.height()+(height/2)+scrollTop });
			}
			var vals = {}
			$("form select,form input,form textarea").each(function (i) {
				if (!$(this).is('button,:submit')) {
                    if ($(this).is(':radio') && $(this).attr('checked')==false) return;
                    vals[this.name] = $(this).is(':checkbox') ? 
                        $(this).attr('checked') : 
                        $(this).val();
                }
			});
			REFRESH_APP.submission.autoSave.changed = false;
	        $.ajax({
	            type: "POST",
	            data: vals,
	            url: self.url,
	            dataType: "json",
	            success: REFRESH_APP.submission.autoSave.onload,
	            error: function(resp, textStatus, errorThrown) {
	            	$('#form-saving').remove();
	            }
	        });
		
		} else {
			self.setPostTimeOut();
		}
		*/
	},
	/**
		Sets autoSave script.
	*/
	init: function(params) {
		/*window.onbeforeunload = function() {
			if(REFRESH_APP.submission.autoSave.changed) {
				return msg_not_saved;
			}
		};	
		this.time = params.time * 1000;
		this.url = params.url;
		this.setPostTimeOut();
		this.changed = false;
		this.oldbrowsers = ($.browser.msie && $.browser.version < 7);
		$("form input,form textarea").live('keypress',REFRESH_APP.submission.autoSave.change);
		$("form select, form input[type='checkbox'], form input[type='radio']").live('click',REFRESH_APP.submission.autoSave.change);
		*/
	}
};


/**
	Create rich text editors
*/
REFRESH_APP.submission.richText = {

	setCount: function() {
	
		var ed = this.editor;
		var obj = this.editorJQ;

		var strip = (ed.getContent()).replace(/(<([^>]+)>)/ig,"");
		var shortenText = '<span class="shorten"> (please shorten)</span>';
		var len = obj.data('maxlen');
		var $p = obj.parent().find('p.textarea-help');
		var newNum = len-strip.length;
		$('span.count',obj.parent()).html(newNum);
		$('#detailedDescription').trigger('focusout');
		if (newNum < 0) {
			$p.addClass('bad-count');
			if (!$p.find('span.shorten').length) {
				$p.append(shortenText);
			}
		} else if ($p.hasClass('bad-count')) {
			$p.removeClass('bad-count').find('span.shorten').remove();
		}
	
	},

	/**
		TinyMCE script onload event
	*/
	onload: function() {
		$(function(){
			$('textarea.tinyMCE').tinymce({
				script_url : '/js/library/tiny_mce/tiny_mce.js',
				theme : "advanced",
				plugins : "safari,spellchecker,paste",
				theme_advanced_buttons1: "bold,italic,|,bullist,numlist,|,link",
				theme_advanced_buttons2: "",
				theme_advanced_toolbar_location : "top",
				theme_advanced_toolbar_align : "left",
				valid_elements : "a[href|target=_blank],strong/b,i/em,br,p,ol,ul,li",
				onchange_callback : REFRESH_APP.submission.richText.onchange,
				force_br_newlines: true,
				paste_postprocess : function(pl, o) {
					REFRESH_APP.submission.richText.setCount();
				},
				setupcontent_callback: function() {
					$('#admin div.edit-field-open').removeClass('edit-field-open');
				},
				setup : function(ed) {
					var obj = $('#'+ed.id);
					obj.data('maxlen', 1000 );
					REFRESH_APP.submission.richText.editor = ed;
					REFRESH_APP.submission.richText.editorJQ = obj;
					ed.onKeyUp.add(function(ed, e) {
						REFRESH_APP.submission.richText.setCount();
					});
					ed.onMouseDown.add(function(ed, e) {
						$('#detailedDescription').focus();
					});
				}
			});
		});	
	},
	/**
		Gets TinyMCE script
	*/
	init: function(params) {
		this.onchange = params.onchange;
		$.getScript('/js/library/tiny_mce/jquery.tinymce.js',REFRESH_APP.submission.richText.onload);
	}
};


/**
	Create multi fields groups.  Controls add/remove fields of multi fields groups
*/
REFRESH_APP.submission.multiFields = {

	checkIfMore: function(group) {
		var length = $('div.field-wrap', group).not('div.field-wrap-first,div.field-visible').length;
		if(length > 0) {
			$('a.btn-add',group).show();
		} else {
			$('a.btn-add',group).hide();
		}
	},

	/**
		Show first of the hidden field.  The element will be cloned and moved to the last element of the list
	*/
	add: function(e) {
		e.preventDefault();
		var obj = $(this);
		var track = obj.text();
		pageTracker._trackEvent('Idea Submission Process', track);
		var parent = obj.parents('.field-multiples');
		var fieldWrap = $('div.field-wrap', parent).not('div.field-wrap-first,div.field-visible').eq(0);
		if(fieldWrap.length > 0) {
			// REFRESH_APP.submission.datepicker.unbind(fieldWrap);
			var newWrap = fieldWrap.clone().insertBefore(obj).addClass('field-visible');
			// REFRESH_APP.submission.datepicker.init(newWrap);
			REFRESH_APP.submission.multiFields.bindRemoveAction(newWrap);
			fieldWrap.remove();
			if(REFRESH_APP.submission.superFields.numericMask) REFRESH_APP.submission.superFields.numericMask(parent);
		}
		REFRESH_APP.submission.multiFields.checkIfMore(parent);
		REFRESH_APP.submission.autoSave.change();
		REFRESH_APP.submission.multiFields.renumber();
	},

	/**
		Hide removed field and empty its value
	*/
	remove: function(e) {
	
		e.preventDefault();
		
		var parent = $(this).parent();
		parent.find("textarea").html("");
		
		var track = parent.parent().find('a.btn-add').text();
		track = track.split('add another').join('remove');
		pageTracker._trackEvent('Idea Submission Process', track);
		parent.removeClass('field-visible');
		REFRESH_APP.submission.multiFields.checkIfMore(parent.parent());
		var field = $('input', parent);
		field.val('');
		
		$('img', parent).remove();
		if(REFRESH_APP.submission.superFields.numericMask) REFRESH_APP.submission.superFields.doMath();
		REFRESH_APP.submission.autoSave.change();
		
		REFRESH_APP.submission.multiFields.renumber();
	},

	/**
		Bind field remove action
	*/
	bindRemoveAction: function(elm) {
		$("a.btn-remove").live("click", REFRESH_APP.submission.multiFields.remove);
	},

	/**
		Bind all fields remove action
	*/
	bindRemoveActions: function() {
		$('div.field-multiples a.btn-remove').each(function() {
			REFRESH_APP.submission.multiFields.bindRemoveAction($(this).parent());
		});
	},
	/**
		Renumber the fields when added or removed
	*/
	renumber: function() {
		$(".field-visible .count-column span").each(function(i) {
			$(this).html(i + 1);
		});
	},
	/**
		Initializes multi fields groups
	*/
	init: function() {

		REFRESH_APP.submission.multiFields.bindRemoveActions();
		$('div.field-multiples input').each( function() {
			var obj = $(this);
			var val = obj.val();
			if(val.length > 0) obj.parents('.field-wrap').addClass('field-visible');
		} );
		$('div.field-multiples').each(function() {
			REFRESH_APP.submission.multiFields.checkIfMore($(this));
		});
		$('div.field-multiples a.btn-add').click(REFRESH_APP.submission.multiFields.add);

	}

};

/**
	Preview accordian
*/
REFRESH_APP.submission.previewAccordian = {

	/**
		Bind field remove action
	*/
	bindRemoveAction: function(elm) {

		elm.mouseover(function(e){
			e.stopPropagation();
			$('a.btn-remove', this.parentNode).hide();
			$('a.btn-remove', this).show();
		});

		$('a.btn-remove', elm).click(REFRESH_APP.submission.multiFields.remove);

	},

	/**
		Initializes preview accordian
	*/
	init: function() {
	
		$('.preview-fields').hide();

		$('fieldset.preview h3.fieldset-title').click( function(e) {
			if ( !(e.target.nodeName.toLowerCase() == 'a' && e.target.className == 'edit') ) {
				e.preventDefault();
				var $p = $(this).parents('fieldset.preview');
				var $f = $p.find('.preview-fields:visible');
				$('.preview-fields:visible').slideUp('slow');
				$('fieldset.preview-on').removeClass('preview-on');
				if ( !$f.length ) {
					$p.find('.preview-fields').slideDown('slow');
					$p.addClass('preview-on');
				}
			}
		});
		
		$('fieldset.preview').hover(
			function() {
				$(this).addClass('highlight');
			},
			function() {
				$(this).removeClass('highlight');
			}
		);

	}

};

/**
	@class
	@description Given an identifier, applies the datepick (calendar) plugin to the field.
*/
REFRESH_APP.submission.datepicker = {
	/**
		Initializes datepicker
	*/
	init: function($p) {
		var $dates = ($p) ? $p.find('.datepicker') : $('.datepicker');
		if ( $dates.length ) {
			var startDate = new Date();
			$dates.datepick({
				minDate: startDate,
				showOn: 'both',
				closeAtTop: false,
				//navigationAsDateFormat : true,
				hideIfNoPrevNext: true,
				changeMonth: false,
				changeYear: false,
				buttonImageOnly: true,
				buttonImage: '/images/submit/btn-date.png'
			});
			$('#datepick-div a').attr('href','');
		}
	},
	/**
		Unbind datepicker
	*/
	unbind: function($p) {
		var $dates = $p.find('.datepicker');
		$dates.datepick('destroy');
	}
	
};

/**
	@class
	@description Given an identifier, countsdown the number of characters allowed for a particular textfield; Expects 'textarea' and '.count' contained within the identifier.
*/
REFRESH_APP.submission.charCountdown = {

	/**
		Initializes charCountdown
	*/
	init: function(x) {
		if ( $(x).length ){
			$(x).each( function() {
				var $set = $(this).parents('fieldset');
				var $counter = $(this).find('.count');
				var countLimit = parseInt( $counter.html() );
				var $textarea = $set.find('textarea');
				REFRESH_APP.submission.charCountdown.updateCount($counter, $textarea, countLimit);
				REFRESH_APP.submission.charCountdown.watchText($counter, $textarea, countLimit);
			});
		}
	},
	
	/**
		Monitors the textarea via 'keyup'
	*/
	watchText: function($counter, $textarea, countLimit) {
		$textarea.keyup( function() {
			REFRESH_APP.submission.charCountdown.updateCount($counter, $textarea, countLimit);
		});
	},
	
	/**
		Updates the character count limit on screend
	*/
	updateCount: function($counter, $textarea, countLimit) {
		var shortenText = ' <span class="shorten">(please shorten)</span>';
		var text = $textarea.val();
		var len = text.length;
		if($textarea.hasClass('tinyMCE')) {
			var strip = text.replace(/(<([^>]+)>)/ig,"");
			len = strip.length;
		}
		var newNum = countLimit - len;
		var $p = $counter.parents('p.textarea-help');
		$counter.html( newNum );
		if (newNum < 0) {
			$p.addClass('bad-count');
			if (!$p.find('span.shorten').length) {
				$p.append(shortenText);
			}
		} else if ($p.hasClass('bad-count')) {
			$p.removeClass('bad-count').find('span.shorten').remove();
		}
	}
	
};


/**
	@class
	@description Gets video link's metadata
	
*/
REFRESH_APP.submission.findYoutubeVideo = {
	
	noMatch : '<p><em>We can\'t recognize the video you uploaded to YouTube. Please go to <a href="http://www.youtube.com" rel="external">www.YouTube.com</a> and make sure the video is enabled, has been made public and is searchable and then copy the YouTube URL into this form again.</em></p>',
	$results : $('<div class="clearfix" id="yt-results"></div>'),
	$loader : $('<img src="/images/global/icn-youtube-loader.gif" alt="" id="icn-yt-loader" />'),
	$container : false,
	$field : false,
	fieldVal : '',

	/**
		Initializes findYoutubeVideo
	*/
	init: function( $field ) {
		this.$field = $field;
		this.$container = $field.parents('.inner-fieldset');
		this.fieldVal = $field.val();
		// Set search on change
		$field.change( function() {
			if (this.fieldVal != $field.val()) {
				pageTracker._trackEvent('Idea Submission Process', 'video upload', $('#grantCategory').val());
				REFRESH_APP.submission.findYoutubeVideo.searchYoutube( $field.val() );
			}
		});
		// Set search on paste
		$field.bind('paste', function(e) {
			if (this.fieldVal != $field.val()) {
				$(this).keyup( function() {
					this.fieldVal = $field.val();
					REFRESH_APP.submission.findYoutubeVideo.searchYoutube( $field.val() );
					$(this).unbind('keyup');
				});
			}
		});
		// Do search on initial value
		REFRESH_APP.submission.findYoutubeVideo.searchYoutube( $field.val() );
	},

	/**
		Initializes static text in preview
	*/
	initStatic: function( $field ) {
		this.$field = $field;
		this.$container = $field.parents('.entry');
		this.fieldVal = $field.text();
		if ( this.fieldVal != '' ) {
			REFRESH_APP.submission.findYoutubeVideo.searchYoutube( this.fieldVal );
		}
	},

	/**
		Search youtube based on param
	*/	
	searchYoutube: function(link) {
		REFRESH_APP.submission.findYoutubeVideo.clearResults();
		if (link!=='') {
			this.$loader.insertAfter( this.$field );
			var v_id = REFRESH_APP.submission.findYoutubeVideo.parseId(link);
			if (v_id==='') {
				this.$results.html( this.noMatch );
				REFRESH_APP.submission.findYoutubeVideo.displayResults();
			} else {
			
				var url = 'http://gdata.youtube.com/feeds/videos?vq=' + 
					v_id + 
					'&max-results=1' + 
					'&alt=json-in-script' + 
					'&callback=REFRESH_APP.submission.findYoutubeVideo.showResult' +
					'&orderby=relevance' + 
					'&sortorder=descending' +
					'&format=5';
					
				if(REFRESH_APP.general.ssl) url = "/proxy/youtube?vq=" + v_id;
			
				// Create a JavaScript element that returns our JSON data
				var script = document.createElement('script');
				script.setAttribute('id', 'jsonScript');
				script.setAttribute('type', 'text/javascript');    
				script.setAttribute('src', url);
				document.documentElement.firstChild.appendChild(script);
			}
		}
	},
	
	/**
		Display results from YouTube search
	*/	
	showResult: function(data) {
		REFRESH_APP.submission.findYoutubeVideo.clearResults();
		if (data.feed.entry) {
			var entry = data.feed.entry[0];
			var v_id = REFRESH_APP.submission.findYoutubeVideo.parseId(entry.link[0].href);
			// Snatch standard youtube entry content
			var $html = $( entry.content.$t );
			// Extract description
			var td = $html.find('td')[1]; 
			var description = $(td).find('div:last span').html();
			
			var url = "http://img.youtube.com/vi/" + v_id + "/2.jpg";
			if(REFRESH_APP.general.ssl) url = "/proxy/youtubethumb?vid=" + v_id;
			
			var html = '<a href="'+entry.link[0].href+'" rel="external"><img src="' + url + '" alt="" /></a>';
			html = html + '<div class="details"><h4><a href="'+entry.link[0].href+'" rel="external">'+entry.title.$t+'</a></h4><p>'+description+'</p></div>';
			this.$results.html(html);
		} else {
			this.$results.html( this.noMatch );
		}
		REFRESH_APP.submission.findYoutubeVideo.displayResults();
	},
	
	/**
		Parse video ID from given URL
	*/
	parseId: function(link) {
		var codeMatch = link.match("[\\?&]v=([^&#]*)");
        if (!codeMatch) {
            codeMatch = link.match("http:\/\/youtu.be\/([A-Za-z0-9._%-]+){1}");
        }
		return (codeMatch) ? codeMatch[1] : '';
	},
	
	/**
		Display search results
	*/
	displayResults: function(link) {
		$('#icn-yt-loader').remove();
		this.$container.append( this.$results );
	},
	
	/**
		Clean out the results in the container
	*/
	clearResults: function() {
		$('#icn-yt-loader').remove();
		$('#yt-results').remove();
		this.$results.html('');
	}
	
};

/**
	@class
	@description Sets highlighting for the fieldset container when an inner form field is active.
*/
REFRESH_APP.submission.formHighlighting = {

	/**
		Initializes formHighlighting
	*/
	init: function($form) {
		$fields = $form.find('textarea, select, input');
		$fields.each( function() {
			$(this).focus( function() {
				$form.find('fieldset.highlight').removeClass('highlight').trigger('unhighlight');
				$(this).parents('fieldset').addClass('highlight').trigger('highlight');
			});
		});
	}
		
};

/**
	@class
	@description Activates tooltip feature
*/

REFRESH_APP.submission.tooltips = {
	
	/**
		Sets initial code for displaying the tip and creates a jquery object
	*/
	$displayTip: $('<div class="tooltip-display" id="tooltip-active"><div class="top"></div><div class="bottom"></div></div>'),
	
	timeOut: null,

	/**
		Finds all tooltip classes and the field it targets from it's id.
		The ID of the tooltip should be 'tooltip-[field_id]'
	*/
	init: function() {
		var $tipped = $('.tipped');
		
		// safari doesn't focus radio buttons
		if($.browser.safari) {
			$("input[type=radio]").live("click", function() {
				$(this).trigger("focus");
			});
		}
		
		$tipped.each( function() {		
			if ( $(this).is('fieldset') ) {
				REFRESH_APP.submission.tooltips.watchContainerEvent( this );
			} else {
				REFRESH_APP.submission.tooltips.watchFieldEvent( this );
			}
		});
		$('div.tooltip-display').live('click',function(e) {
			clearTimeout(REFRESH_APP.submission.tooltips.timeOut);
		});
	},
	
	/**
		Handles the focus and blur events for the form field
	*/
	watchFieldEvent: function(field) {
		var $field = $(field);
		
		// Handle focus
		$field.focus( function() {			
			$('#tooltip-active').remove();
			clearTimeout(REFRESH_APP.submission.tooltips.timeOut);
			var $p = ($field.is('#detailedDescription')) ? $(this).parents('.fieldset-counter') : $(this).parents('fieldset');

			if($field.hasClass("new-tip")) {
				$p = $(this).parents(".new-tip-wrap")
			}
			
			var content = $p.find('.tooltip').html();
			REFRESH_APP.submission.tooltips.showTip( $field, content );
		});
		// Handle blur
		$field.blur( function() {
			clearTimeout(REFRESH_APP.submission.tooltips.timeOut);
			REFRESH_APP.submission.tooltips.timeOut = setTimeout(function() {
				$('#tooltip-active').remove();
			},100);
		});
	},
	
	/**
		Handles the event when container is highlighted
	*/
	watchContainerEvent: function(fieldset) {
		$(fieldset).bind('highlight', function() {
			clearTimeout(REFRESH_APP.submission.tooltips.timeOut);
			$('#tooltip-active').remove();
			var content = $(this).find('.tooltip').html();
			REFRESH_APP.submission.tooltips.showTip( $(this), content );
		});
		$(fieldset).bind('unhighlight', function() {
			$('#tooltip-active').remove();
		});
	},
	
	/**
		Grabs the original tooltip content and places it in the display tooltip
	*/
	showTip: function( $obj, content ) {
		$tip = REFRESH_APP.submission.tooltips.$displayTip;
		$tip.find('div.top').html(content);
		if ( $obj.is('fieldset') ) {
			$obj.find('.inner-fieldset').prepend( $tip );
		} else if ( $obj.parents('#employee-info').length ) {
			$tip.insertBefore( $obj.parents('.fieldset-group') );
		} else {
			if($obj.attr("type") === "radio") {
				$obj = $obj.parents(".new-tip-wrap").find("input[type=radio]").eq(0);
				$tip.insertBefore( $obj );
			} else {
				$tip.insertBefore( $obj );
			}
			
		}

	}
	
};


/* jQuery Numeric masking */

(function($){$.fn.alphanumeric=function(p){p=$.extend({ichars:"!@#$%^&*()+=[]\\\';,/{}|\":<>?~`.- ",nchars:"",allow:""},p);return this.each
(function()
{if(p.nocaps)p.nchars+="ABCDEFGHIJKLMNOPQRSTUVWXYZ";if(p.allcaps)p.nchars+="abcdefghijklmnopqrstuvwxyz";s=p.allow.split('');for(i=0;i<s.length;i++)if(p.ichars.indexOf(s[i])!=-1)s[i]="\\"+s[i];p.allow=s.join('|');var reg=new RegExp(p.allow,'gi');var ch=p.ichars+p.nchars;ch=ch.replace(reg,'');$(this).unbind('contextmenu');$(this).unbind('keypress');$(this).keypress
(function(e)
{if(!e.charCode)k=String.fromCharCode(e.which);else k=String.fromCharCode(e.charCode);if(ch.indexOf(k)!=-1)e.preventDefault();if(e.ctrlKey&&k=='v')e.preventDefault();});$(this).bind('contextmenu',function(){return false});});};$.fn.numeric=function(p){var az="abcdefghijklmnopqrstuvwxyz";az+=az.toUpperCase();p=$.extend({nchars:az},p);return this.each(function()
{$(this).alphanumeric(p);});};$.fn.alpha=function(p){var nm="1234567890";p=$.extend({nchars:nm},p);return this.each(function()
{$(this).alphanumeric(p);});};})(jQuery);

jQuery.fn.slugify = function(obj) {
    jQuery(this).data('obj', jQuery(obj));
    jQuery(this).keyup(function() {
        var obj = jQuery(this).data('obj');
        var slug = jQuery(this).val().replace(/\s+/g,'-').replace(/[^a-zA-Z0-9\-]/g,'').toLowerCase();
        obj.val(slug);
    });
}


