var J = jQuery.noConflict();
function hexFromRGB (r, g, b) {
	var hex = [
		r.toString(16),
		g.toString(16),
		b.toString(16)
	];
	J.each(hex, function (nr, val) {
		if (val.length == 1) {
			hex[nr] = '0' + val;
		}
	});
	return hex.join('').toUpperCase();
}
J(document).ready(function(){
	
	var fields = new Array();
	var values = new Array();
	
	J('.ci').each(function(i){
		J(this).removeClass('ci').addClass('ci'+i);
		fields.push('ci'+i);
		values.push(J(this).val());

		J(this).focus(function(){
			if(J(this).val() == values[i]) {
				J(this).val('');
			}
		});
		J(this).blur(function(){
			var valStore = values[i];
			if(J(this).val()==''){
				J(this).val(valStore);
			}
		})
	});
	
	
	J('#pick_stack').change(function(){
		window.location.href = J(this).val();
	})
	
	
	J('#flashnotice').effect("highlight",{},5000,function(){
		J(this).slideUp(1000);
	});
	
	
	
	J('#task-checkbox-id:checked').each(function() {
		J.post("/tasks/toggle", { task: "1"} );
	});
	J('.request .subject').each(function(){
		var completed = J(this).attr('title').replace('% Complete', '');
		if(completed > 50) {
			var bgcolor = Math.ceil(255-(255*(completed-50)*2/100))+ ", 255, 0";
		} else {
			var bgcolor = "255, " + Math.ceil(255*completed*2/100) + ", 0";
		}
		J(this).parents('.request').find('.percentage').css({
			"background-color": "rgb(" + bgcolor + ")" 
		});
	})
	
	J('#percentage').each(function(){
		var completed = J(this).find('span').attr('title').replace('% Complete', '');
		if(completed > 50) {
			var bgcolor = Math.ceil(255-(255*(completed-50)*2/100))+ ", 255, 0";
		} else {
			var bgcolor = "255, " + Math.ceil(255*completed*2/100) + ", 0";
		}
		J('#percentage #progress').css({
			"background-color" : "rgb(" + bgcolor + ")",
			"width" : completed + "%"
		});
		if(completed == 0) {
			J('#percentage').addClass('incomplete');
		} else if(completed == 100) {
			J('#percentage').addClass('complete');
			J('#percentage #progress').css('width', '99.65%');
		}
	})
	
	J('#sidebar.collapsable .sidebox').not('.tasks, .show, .attachments').hide();
	J('#sidebar.collapsable h2').not('.empty').click(function(e){
		e.preventDefault();
		if(J(this).siblings('div.sidebox').is(':visible')){
			J(this).removeClass('open').siblings('div.sidebox').slideUp('fast');
		} else {
			
			J(this).addClass('open').siblings('div.sidebox').slideDown('fast');
		}
		
	})
	
	//	Contact Info form filling for Newoutgoing requests
	J('#requests #sidebar .contactlist a').click(function(e){
		e.preventDefault();
		J('#new_request #email').val(J(this).find('.email').text());
		J('#new_request #first_name').val(J(this).find('.first').text());
		J('#new_request #last_name').val(J(this).find('.last').text());
		J('#new_request #company_name').val(J(this).find('.company span').text());
		if(J('#request_regarding').val() == ""){
			J('#request_regarding').focus();
		} else {
			J('#request_text').focus();
		}
	})
	
	
	//	Search resizing due to CSS fails
	J('#sidebar #contact_search #search_terms').width(J('#sidebar #contact_search #search_terms').width()-34);
	J('#search #sidebar #search_terms').width(J('#search #sidebar #search_terms').width()-34);
	window.onresize = function(){
		J('#sidebar #contact_search #search_terms, #search #sidebar #search_terms').width('100%');
		J('#sidebar #contact_search #search_terms').width(J('#sidebar #contact_search #search_terms').width()-34);
		J('#search #sidebar #search_terms').width(J('#search #sidebar #search_terms').width()-34);
	}
	J('#search #search_terms').focus();
	J('#search_terms').not('.ci').click(function(){
		this.select();
	})
	J('#search .search_retry').click(function(e){
		e.preventDefault();
		J('#search_terms').select().effect("highlight",{},3000);
	})
	
	J('.tools').hide();
	J('.request, #search li.contact, #contacts li.contact, #requests #tracker_list li, #site_tracker li, .my_reminders li, #task_list li').live('mouseover mouseout',function(event){
		if (event.type == 'mouseover'){
			J(this).find('.tools').show();
		} else {
			J(this).find('.tools').hide();
		}
	})
	J('#requests #site_tracker .tools a').attr('title', 'Delete this tracker');
	
	
	//grab id of div, insert faq text from the hidden div
	J('input.faq').click(function () {
		if(J(this).is(':checked')){
			var faq_id = J(this).val();
	    	J("#requestreply_text").val(jQuery.trim(J("#faq_text_" + faq_id).text()));    
		}
		else {
			J("#requestreply_text").val('');
		}
	});

	J('input.document').click(function() {
			disableSend();
		    var checkValue = J(this).val();
		if(J(this).is(':checked')){
		    J.get("/requests/toggledoc/1/"+checkValue, activateSend());
		}
		else {
			J.get("/requests/toggledoc/0/"+checkValue, activateSend());
		}
	});
	
	J('#contacts div.additionalinfo, .blank div.additionalinfo, #stacks div.additionalinfo').hide();
	J('#contacts h4.additionalinfo, .blank h4.additionalinfo, #stacks h4.additionalinfo').toggle(function(){
		J(this).find('small').text('(Click to hide)').end().next('.additionalinfo').slideDown('slow');
	}, function(){
		J(this).find('small').text('(Click to show)').end().next('.additionalinfo').slideUp('slow');
	})
	
	function progressBarAdjust(complete) {
		if (complete) {
			var completed = 100;
		} else {
			var totalTasks = J('#task_list input.task').size() + J('#tracker_list input.task').size();
			if(totalTasks > 0){
				var completedTasks = J('#task_list input.task:checked').size() + J('#tracker_list input.task:checked').size();
				var completed = Math.round(completedTasks/totalTasks*100);
			} else {
				var completed = 0;
			}
		}
		if(completed > 50) {
			var color = Math.ceil(255-(255*(completed-50)*2/100))+ ", 255, 0";
		} else {
			var color = "255, " + Math.ceil(255*completed*2/100) + ", 0";
		}
		J('#percentage span').text(completed+"% Complete").attr('title', completed+"% Complete");
		J('#percentage #progress').animate({
			backgroundColor : "rgb(" + color + ")",
			width : completed + "%"
		}, 'slow');
		if(completed == 0) {
			J('#percentage').removeClass('complete').addClass('incomplete');
		} else if(completed == 100) {
			J('#percentage').removeClass('incomplete').addClass('complete');
			J('#percentage #progress').animate({'width' : '99.65%'}, 'fast');
		} else {
			J('#percentage').removeClass('complete').removeClass('incomplete');
		}
	}
	J('#requests #request_checkbox').click(function(){
		var checkValue = J(this).val();
		if(J(this).is(':checked')){
			J.get("/requests/toggledone/1/"+checkValue);
			J('#task_list input.task').attr("disabled", "disabled");
			J('#toggle_done label span').text('Request complete');
			progressBarAdjust(true);
		} else {
			J.get("/requests/toggledone/0/"+checkValue);
			J('#task_list input.task').removeAttr('disabled');
			J('#toggle_done label span').text('Mark this request as complete');
			progressBarAdjust();
		}
	})

	J('#dashboard .request .percentage_wrap .percentage').hover(function(){
		J(this).css('margin-top', '-'+J(this).parent().height()/2+'px');
		J(this).addClass('complete').wrapInner('<span class="text" />');
		J(this).find('.text').hide();
		J(this).append('<span class="completetext">Complete?</span>');
	}, function(){
		J(this).css('margin-top', '0');
		J(this).removeClass('complete').find('.completetext').remove();
		var amount = J(this).find('.text').text()
		J(this).find('.text').show().replaceWith(amount);
	})
	
	J('#dashboard .request .percentage_wrap .complete').live('click', function(){
		var checkValue = J(this).parents('tr.request').attr('id').replace('request_', '');
		J.get("/requests/toggledone/1/"+checkValue);
		J(this).parents('tr.request').fadeOut('slow', function(){
			J(this).parents('tr.request').remove();
		})
	})
	
	J('input.task').live('click', function() {
	    var checkValue = J(this).val();
		var requestID = J('#task_list').attr('class').replace('request', '');
		progressBarAdjust();
	if(J(this).is(':checked')){
	    J.get("/tasks/toggle/1/"+checkValue, function() {
			
		});
	}
	else {
		J.get("/tasks/toggle/0/"+checkValue, function() {
			
		});
	}
	});

	// J('input.request_done').click(function() {
	//     var checkValue = J(this).val();
	// if(J(this).is(':checked')){
	//     J.get("/requests/toggledone/1/"+checkValue);
	// }
	// else {
	// 	J.get("/requests/toggledone/0/"+checkValue);
	// }
	// });
	
	J('#add_request_box').hide();
	J('.addrequest').click(function(e){
		e.preventDefault();
		if (J('#add_request_box').is(':visible')) {
			J('#pop_shield').remove();
			J(this).next('#add_request_box').hide();
		} else {
			J('body').prepend('<div id="pop_shield"></div>');
			J('#pop_shield').click(function(){
				J(this).remove();
				J('#add_request_box').hide();
			})
			J(this).next('#add_request_box').show();
			J(window).one('keydown', function(e){
				if(e.keyCode == 27) {
					J('#pop_shield').remove();
					J('#add_request_box').hide();
				}
			})
		}
	})
	
	//	Email Forwarding
		J('#forward_box form').hide();
		J('#request_forward').click(function(e){
			e.preventDefault();
			J('#forward_box form .message').remove();
			if (J('#forward_box form').is(':visible')) {
				J('#pop_shield').remove();
				J(this).next('#forward_box form').hide();
			} else {
				J('body').prepend('<div id="pop_shield"></div>');
				J('#pop_shield').click(function(){
					J(this).remove();
					J('#forward_box form').hide();
				})
				J(this).next('#forward_box form').show();
				J(window).one('keydown', function(e){
					if(e.keyCode == 27) {
						J('#pop_shield').remove();
						J('#forward_box form').hide();
					}
				})
			}
		})
		J('#forward_box #forward_submit').click(function(e){
			e.preventDefault();
			J('#forward_box form .message').remove();
			
			var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
			var email_recipient = J('#forward_email').val();
			if(reg.test(email_recipient) == false) {
				J('#forward_box form').append('<p class="message error">Please enter a valid email address.</p>');
			} else {
			
				J('#forward_submit').hide().after('<span class="loader"></span>');
				J.get('/requests/forward/'+J('#requestid').val()+'?email='+email_recipient, function(){
					J('#forward_box form').append('<p class="message">This request was forwarded to '+email_recipient+'</p>');
					J('#forward_box form .loader').remove();
					J('#forward_submit').fadeIn('slow');
				})
			}
		})
	
	
	// Request Response
	J('#requests #respond').hide();
	J('#requests a.respondlink').click(function(e){
		e.preventDefault();
		J(this).slideUp('fast');
		J('#respond').slideDown('fast', function(){
			window.location.hash = 'respond';
		});
	})
	J('#requests #respond a.close').click(function(e){
		e.preventDefault();
		J('#requests a.respondlink').slideDown('fast');
		J('#respond').slideUp('fast');
	})
	
	//	Adding Canned Response to request reply
		J('#respond #cannedresponses').change(function(){
			var spacer = J('#respond #message').val() != "" ? "\n\n" : "";
			J('#respond #message').val(J('#respond #message').val().replace(/[\s\r\n]+$/, '')+spacer+J('#respond #cannedresponses').val());
		})
	//	Adding Signature to request reply
		J('#respond #add_signature').click(function(){
			var signature = J(this).val().replace(/[\r]/g, '');
			if(J(this).is(':checked')){
				var spacer = J('#respond #message').val() != "" ? "\n\n" : "";
				J('#respond #message').val(J('#respond #message').val().replace(/[\s\r\n]+$/, '')+spacer+signature);
			} else {
				J('#respond #message').val(J('#respond #message').val().replace(signature, ''));
			}
		})
	
	
	//	Task List Re-order/pruning
		function taskPrune(){
			var totalTasks = J('#task_list_items li').size();
			var completedTasks = J('#task_list_items li :checked').size();
			var hideTasks = false;
			var hiddenTasks = 0;
			J('#task_list_items li input').each(function(i){
				i++;
				if(i>5 && J(this).is(':checked')) {
					if(i<totalTasks-1 || hideTasks){
						hideTasks = true;
						J(this).parents('li').hide()
						hiddenTasks ++;
					}
				}
			})
			if(hideTasks){
				J('#task_list_items').append('<li id="showtasks">Show '+hiddenTasks+' more completed tasks...</li>');
				J('#showtasks').click(function(e){
					e.preventDefault();
					J(this).remove();
					J('#task_list_items li:hidden').fadeIn();
				})
			}
		}
		taskPrune();
	
	//	Seach Results Pruning
		J('.results div.table').each(function(){
			var totalresults = J(this).find('tr').size();
			var type = J(this).find('h3').text();
			if(totalresults > 5){
				J(this).find('table').after('<div class="viewmore"><a href="#">View All '+totalresults+' '+type+'</a></div>');
				J(this).find('tr').each(function(){
					if(J(this).index() > 4){
						J(this).hide();
					}
				})
			};
		})
		J('.results div.list').each(function(){
			var totalresults = J(this).find('li').size();
			var type = J(this).find('h3').text();
			if(totalresults > 5){
				J(this).find('list').after('<div class="viewmore"><a href="#">View All '+totalresults+' '+type+'</a></div>');
				J(this).find('li').each(function(){
					if(J(this).index() > 4){
						J(this).hide();
					}
				})
			};
		})
		J('.results .table .viewmore').click(function(e){
			e.preventDefault();
			J(this).siblings('table').find('tr').fadeIn();
			J(this).remove();
		})
		J('.results .list .viewmore').click(function(e){
			e.preventDefault();
			J(this).siblings('ul').find('li').show();
			J(this).remove();
		})
		
	
	
	//	New Task Submission
		J('#add_task').submit(function(){
			addNewTask();
			return false;
		})
		J('#add_task input[type="submit"]').click(function(){
			addNewTask();
			return false;
		})
		function addNewTask(){
			J.post(J('#add_task').attr('action'), J('#add_task').serialize(), function(){
				J('#task_list').load('/requests/'+J('#request_id').val()+' #task_list form', function(){
					J('#task_description').val('');
					taskPrune();
					progressBarAdjust();
					J('#requests #task_list li .tools').hide();
					J('#requests #task_list li').hover(function(){
						J(this).find('.tools').show();
					}, function(){
						J(this).find('.tools').hide();
					})
				});
			})
		}
	
	//	Request Reply submission
		J('#request_email #sendresponse').click(function(){
			if(J('#subject').val()==''){
				alert('Please enter a Subject for your message.');
				return false;
			}
			else if(J('f').val()==''){
				alert('Hey... you can\'t submit a blank Message!');
				return false;
			}
			// var dataString = J('#request_email').serialize();
			// J.ajax({
			// 	type:		"POST",
			// 	url:		J('#request_email').attr('action'),
			// 	data:		dataString,
			// 	success:	function() {
			// 		alert('We did it!')
			// 	}
			// })
			// 
			// return false;
		})
		
		J('#requestreplies .attachment_list').hide();
		J('#requestreplies .attachment_total').toggle(function(){
			J(this).next('.attachment_list').slideDown('fast');
			return false;
		}, function(){
			J(this).next('.attachment_list').slideUp('fast');
			return false;
		})
		
	
	//	Map Resize
		J('#sidebar #map').resizable({ handles: 's', maxHeight: 600 });
	
	
	//	Form Codes
		J('#formcodes .code_section > div').not('.embedded').hide();
		J('#formcodes .tabs a').click(function(e){
			e.preventDefault();
			if(!J(this).is('.active')) {
				J(this).addClass('active').siblings('.active').removeClass('active');
				var tabname = J(this).attr('href').substr(1);
				J('.code_section .'+tabname).show().siblings('div').hide();
			}
		})
		J('#formcodes #aslink').click(function(){
			if(J(this).is(':checked')){
				J('#standalonecode').val('<a href="'+J('#standaloneaddress').val()+'" title="'+J('#standalonename').val()+'" rel="nofollow">Submit a Question/Request &rsaquo;</a>');
			} else {
				J('#standalonecode').val(J('#standaloneaddress').val());
			}
		})
		J('#formcodes textarea').click(function(){
			J(this).select();
		})
		J('#formcodes .radios input[type="radio"]').click(function(){
			if(J('#formcodes #darksite').is(':checked')) {
				J(this).parents('.selection').animate({ backgroundColor: "#27334E", color: "#fff" }, 750);
				J('#embeddedcode').val(J('#embeddedcode').val().replace('shade=light', 'shade=dark'));
			} else {
				J(this).parents('.selection').animate({ backgroundColor: "#E6E6FD", color: "#27334E" }, 750);
				J('#embeddedcode').val(J('#embeddedcode').val().replace('shade=dark', 'shade=light'));
			}
		})
		J('h2.formcode').not('.open').next('#formcodes').hide();
		J('h2.formcode').click(function(e){
			e.preventDefault();
			J(this).toggleClass('open');
			if(J(this).is('.open')){
				J('#formcodes').slideDown('fast');
			} else {
				J('#formcodes').slideUp('fast');
			}
		})
		
	//	Stack Deletion
		J('#stacks .delete_warning').click(function(e){
			e.preventDefault();
			J('body').append('<div id="popup_matte"><div id="popup_wrap" class="warning"><div id="popup_content"></div></div></div>');
			J('#popup_content').load(this.href+' #delete_stack');
			J(window).one('keydown', function(e){
				if(e.keyCode == 27) {
					J('#popup_matte').remove();
				}
			})
			J('#popup_matte, a.cancel').click(function(e){
				J('#popup_matte').remove();
				return false;
			})
		})
	
	//	Account Cancellation
		J('#settings .delete_warning').click(function(e){
			e.preventDefault();
			J('body').append('<div id="popup_matte"><div id="popup_wrap" class="warning"><div id="popup_content"></div></div></div>');
			J('#popup_content').load(this.href+' #delete_account', function(){
				J('#cancellationreason_reason').select();
				J('#cancellationreason_reason').focus(function(){
					if(J(this).val() == 'Enter your reason for cancellation here.') {
						J(this).val('');
					}
				})
			});
			J(window).one('keydown', function(e){
				if(e.keyCode == 27) {
					J('#popup_matte').remove();
				}
			})
			J('a.cancel').live("click", function(e){
				e.preventDefault();
				J('#popup_matte').remove();
				return false;
			})

		})
	
	//	Intro Video
		J('#home #screenshot a').click(function(e){
			e.preventDefault();
			J('body').append('<div id="popup_matte"><div id="popup_wrap"><div id="popup_content"></div></div></div>');
			J('#popup_content').append('<object width="640" height="385"><param name="movie" value="http://www.youtube.com/v/lnA3X6OJJvo&hl=en_US&fs=1&rel=0&color1=0x3a3a3a&color2=0x999999&hd=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/lnA3X6OJJvo&hl=en_US&fs=1&rel=0&color1=0x3a3a3a&color2=0x999999&hd=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="640" height="385"></embed></object>');
			J(window).one('keydown', function(e){
				if(e.keyCode == 27) {
					J('#popup_matte').remove();
				}
			})
			J('#popup_content').click(function(){
				return false;
			})
			J('#popup_matte, a.cancel').click(function(){
				J('#popup_matte').remove();
				return false;
			})
		})
	
	//	Plans Definitions
		J('#plans a.explanation').hover(function(){
			J(this).next('div.explanation').fadeIn('slow');
		}, function(){
			J(this).next('div.explanation').hide();
		})
	
	//	Contact Autocomplete
		if (J('body').attr('id') == "contacts") {
			J.post('/contacts/fullcontactlist', function(data) {
				J("#search_terms").autocomplete({
					source: data.split(','),
					delay: 0,
					minLength: 1
				});
			});
		}
		J('#contact_search #search_terms').keydown(function(e){
			if(e.keyCode == 13) {
				J('#contactsearch').submit();
			}
		})
		J('#contact_search ul a').live('click',function(){
			J('#contactsearch').submit();
		})
		
	//	Unread Reply Shift to top (Dashboard)
		J('#dashboard .new_reply').each(function(){
			J(this).parent().prepend(this);
		})
		J('#dashboard .dash_requests table').each(function(){
			var newreplies = J(this).find('.new_reply');
			if(newreplies.size() > 1);
			var flippedreplies = new Array();
			newreplies.each(function(){
				flippedreplies.push(this);
			})
			newreplies.remove();
			flippedreplies.reverse();
			J(this).prepend(flippedreplies);
		})
	
	
	//	Requests Percentage Sort
		if(J('#central').hasClass('sort_percentage')){
			var elements = J('#requestlist .request');
			function sortElements(a,b){
				var compA = J(a).attr('class').substr(8);
				var compB = J(b).attr('class').substr(8);
				return (compA - compB);
			}
			J('#requestlist').html(elements.sort(sortElements));
		}
		J('.sidebar_stack_id .sort_stack, .sidebar_percentage .sort_percentage, .sidebar_created_at .sort_recent').each(function(){
			J(this).html(this.innerHTML.replace('Sort', 'Sorted'));
		})
		J('#sidebar .sort_reverse').click(function(e){
			e.preventDefault();
			var elements = new Array();
			J('#requestlist .request').each(function(){
				elements.push(this);
			})
			elements.reverse();
			J('#requestlist').html('');
			for (i=0;i<elements.length;i++){
				J('#requestlist').append(elements[i]);
			}
			if(J('.sidebar_created_at .sort_recent').text() != "Sorted oldest to newest") {
				J('.sidebar_created_at .sort_recent').text("Sorted oldest to newest");
			} else {
				J('.sidebar_created_at .sort_recent').text("Sorted newest to oldest");
			}
		})
		J('#sidebar #hide_complete').click(function(){
			if(J(this).is(':checked')){
				J('.request.100').hide();
			} else {
				J('.request.100').show();
			}
		})
		J('#sidebar #hide_new').click(function(){
			if(J(this).is(':checked')){
				J('.request.-1').hide();
			} else {
				J('.request.-1').show();
			}
		})
		
		//	Search Results Filters
			J('.results .filterset input').click(function(){
				var set = J(this).attr('id').substr(5);
				if(J(this).is(':checked')){
					J('.list_'+set).hide();
				} else {
					J('.list_'+set).show();
				}
			})
		
		
		//	Request Regarding Dropdown
		J('#request_stack_id').change(function(){
			J.post('/requests/changereqcat/'+J('#request_id').val()+'/'+J(this).val());
		})
		
		
		
		// On/Off Switches
		J('input.on_off_switch').iphoneStyle();
		J('#documents .iPhoneCheckContainer').click(function(){
			var docID = J(this).find(':checkbox').attr('id').substr(9);
			if(J(this).find(':checkbox').is(':checked')){
				J.post('/documents/toggleautomation/'+docID+'/1');
			} else {
				J.post('/documents/toggleautomation/'+docID+'/0');
			}

		})
		J('#admin .iPhoneCheckContainer').click(function(){
			var userID = J(this).find(':checkbox').attr('id').substr(13);
			if(J(this).find(':checkbox').is(':checked')){
				J.post('/admin/makeorbreakadmin/'+userID, '&value=1');
			} else {
				J.post('/admin/makeorbreakadmin/'+userID, '&value=0');
			}

		})
		
		//	Document Links
		J('#public_links .aslink').click(function(){
			if(J(this).is(':checked')){
				J(this).parents('li').find('.link_code').val('<a href="'+J(this).parents('li').find('.doc_address').val()+'" title="'+J(this).parents('li').find('.doc_title').val()+'" rel="nofollow">'+ J(this).parents('li').find('.doc_title').val() +'</a>')
			} else {
				J(this).parents('li').find('.link_code').val(J(this).parents('li').find('.doc_address').val());
			}
		})
		J('#public_links textarea').click(function(){
			J(this).select();
		})
		
		
		//	Datepickers
		J('#create_link .exactdate, #create_link_form').hide();
		J('#public_links .create_new_link').click(function(){
			J('#create_link_form').slideDown('fast');
			if(J(this).is('input')){
				J(this).slideUp('fast');
			}
			return false;
		})
		J('#arblinktracker_valid_on, #arblinktracker_expires_on').datepicker();
		J('#arblinktracker_valid_on_select, #arblinktracker_expires_on_select').change(function(){
			if(J(this).val() == ''){
				J(this).next('.exactdate').fadeIn('fast');
			} else {
				J(this).next('.exactdate').hide();
			}
		});
		
		//	New Tracker
		if(!J('#new_tracker #feedmatch_tracker_type_r').is(":checked")){
			J('#new_tracker .radio_indent').hide();
		}
		J('#new_tracker .radioset input').click(function(){
			if(J('#new_tracker #feedmatch_tracker_type_r').is(":checked")){
				J('#new_tracker .radio_indent').slideDown('fast');
			} else {
				J('#new_tracker .radio_indent').slideUp('fast');
			}
		})
		
		//	Highrise settings
			J('#settings #highrise_settings .closed').hide();
			J('#settings #highrise_settings a.edit').toggle(function(){
				J('#settings #highrise_settings .closed').slideDown('fast');
				return false;
			}, function(){
				J('#settings #highrise_settings .closed').slideUp('fast');
				return false;
			})
		
		//	Less Accounting Settings
			J('#less_export_form').remove();
			J('#less_import_form form').append('<input class="button" id="less_export" type="submit" value="Export Contacts to Less Accounting" />');
			J('#less_accounting_settings #less_export').click(function(){
				J(this).parent().attr('action', '/contacts/laexport');
			})
			
		//	Focus-first inputs
			J('input.focusfirst').select();
			
		//	Wufoo Choose Form
			J('#wufoo_chooseform div').click(function(){
				J(this).find('input').attr('checked', 'checked');
			})
			
		//	Threshold Slider
			if(undefined===window.threshold){
				window.threshold = [];
			}
			J('#threshold_slide').slider({
				value: threshold,
				min: 3,
				max: 7,
				step: 1,
				change: function(event, ui) {
					J.post('/stacks/setq/'+stack+'/'+ui.value);
				}
			})
			
		//	Load Blog Posts on Dashboard
			J('#dashboard #sidebar').prepend('<h2>From the Sense Blog <a class="rss_feed" href="http://blog.madewithsense.com/rss">RSS</a></h2><div id="blogposts" class="loading section"><div id="postscontainer"></div></div>');
			J('#sidebar #blogposts #postscontainer').hide().load('/getblogposts', function(){ J(this).slideDown('fast'); J('#sidebar #blogposts').removeClass('loading'); });
		
	
}) // end of document.ready


function showSlider(id){
J(id).animate({"height": "toggle"}, { duration: 1000 });
}

function disableSend() {
	J('#sendresponse').bind("click", function(){
		return false;
	}).val('Please Wait...');
}
function activateSend() {
	J('#sendresponse').unbind("click").val('Send');
}

function accountLimitWarning() {
	var warned = J.cookie('dispatchAccountWarning');
	if(warned != 'true'){
		J('body').append('<div id="popup_matte"><div id="popup_wrap" class="warning"><div id="popup_content"></div></div></div>');
		J('#popup_content').html('<h2>Account Limit Reached</h2><div class="warning_content section"><p>Your Dispatch Solo account has reached its limit of 100 requests this month.  Your requests will still be received by Dispatch (so they are completely safe), but they will not be visible until you upgrade your account.  If you do nothing, your hidden requests will appear next calendar month.</p><p>Please upgrade your account now to instantly get access to more than 100 requests per month.  Just click the link below, then click the link under Plan Level and select a new plan.  When you upgrade, your hidden requests will show up immediately.</p><div class="buttons"><p class="question"><strong>Would you like to upgrade your account now?</strong></p><a href="/settings/upgradesolo" class="button"><strong>Yes, upgrade my account now.</strong></a><a href="#" class="button cancel">No, hide this notice.</a></div></div>');
		J(window).one('keydown', function(e){
			if(e.keyCode == 27) {
				J('#popup_matte').remove();
			}
		})
		J('#popup_matte, a.cancel').click(function(){
			J('#popup_matte').remove();
			var oneday = 1000 * 60 * 60 * 24;
			var now = new Date();
			if (now.getMonth() == 11) {
			    nextMonth = new Date(now.getFullYear() + 1, 0, 1);
			} else {
			    nextMonth = new Date(now.getFullYear(), now.getMonth() + 1, 1);
			}
			var expiration = Math.round(Math.abs(nextMonth.getTime() - now.getTime())/oneday);
			J.cookie('dispatchAccountWarning', true, { expires: expiration });
			return false;
		})
	}
}





/*!
// iPhone-style Checkboxes jQuery plugin
// Copyright Thomas Reynolds, licensed GPL & MIT
*/
(function(J, iphoneStyle) {

// Constructor
J[iphoneStyle] = function(elem, options) {
  this.Jelem = J(elem);
  
  // Import options into instance variables
  var obj = this;
  J.each(options, function(key, value) {
    obj[key] = value;
  });
  
  // Initialize the control
  this.wrapCheckboxWithDivs();
  this.attachEvents();
  this.disableTextSelection();
  
  if (this.resizeHandle)    { this.optionallyResize('handle'); }
  if (this.resizeContainer) { this.optionallyResize('container'); }
  
  this.initialPosition();
};

J.extend(J[iphoneStyle].prototype, {
  // Wrap the existing input[type=checkbox] with divs for styling and grab DOM references to the created nodes
  wrapCheckboxWithDivs: function() {
    this.Jelem.wrap('<div class="' + this.containerClass + '" />');
    this.container = this.Jelem.parent();
    
    this.offLabel  = J('<label class="'+ this.labelOffClass +'">' +
                         '<span>'+ this.uncheckedLabel +'</span>' +
                       '</label>').appendTo(this.container);
    this.offSpan   = this.offLabel.children('span');
    
    this.onLabel   = J('<label class="'+ this.labelOnClass +'">' +
                         '<span>'+ this.checkedLabel +'</span>' +
                       '</label>').appendTo(this.container);
    this.onSpan    = this.onLabel.children('span');
    
    this.handle    = J('<div class="' + this.handleClass + '">' +
                         '<div class="' + this.handleRightClass + '">' +
                           '<div class="' + this.handleCenterClass + '" />' +
                         '</div>' +
                       '</div>').appendTo(this.container);
  },
  
  // Disable IE text selection, other browsers are handled in CSS
  disableTextSelection: function() {
    if (!J.browser.msie) { return; }

    // Elements containing text should be unselectable
    J.each([this.handle, this.offLabel, this.onLabel, this.container], function(el) {
      J(el).attr("unselectable", "on");
    });
  },
  
  // Automatically resize the handle or container
  optionallyResize: function(mode) {
    var onLabelWidth  = this.onLabel.width(),
        offLabelWidth = this.offLabel.width(),
        newWidth      = (onLabelWidth < offLabelWidth) ? onLabelWidth : offLabelWidth;

    if (mode == 'container') { newWidth += this.handle.width() + 15; }
    this[mode].css({ width: newWidth });
  },
  
  attachEvents: function() {
    var obj = this;
    
    // A mousedown anywhere in the control will start tracking for dragging
    this.container
      .bind('mousedown touchstart', function(event) {          
        event.preventDefault();
        
        if (obj.Jelem.is(':disabled')) { return; }
          
        var x = event.pageX || event.changedTouches[0].pageX;
        J[iphoneStyle].currentlyClicking = obj.handle;
        J[iphoneStyle].dragStartPosition = x - (parseInt(obj.handle.css('left'), 10) || 0);
      })
    
      // Utilize event bubbling to handle drag on any element beneath the container
      .bind('iPhoneDrag', function(event, x) {
        event.preventDefault();
        
        if (obj.Jelem.is(':disabled')) { return; }
        
        var p = (x - J[iphoneStyle].dragStartPosition) / obj.rightSide;
        if (p < 0) { p = 0; }
        if (p > 1) { p = 1; }
      
        obj.handle.css({ left: p * obj.rightSide });
        obj.onLabel.css({ width: p * obj.rightSide + 4 });
        obj.offSpan.css({ marginRight: -p * obj.rightSide });
        obj.onSpan.css({ marginLeft: -(1 - p) * obj.rightSide });
      })
    
        // Utilize event bubbling to handle drag end on any element beneath the container
      .bind('iPhoneDragEnd', function(event, x) {
        if (obj.Jelem.is(':disabled')) { return; }
        
        if (J[iphoneStyle].dragging) {
          var p = (x - J[iphoneStyle].dragStartPosition) / obj.rightSide;
          obj.Jelem.attr('checked', (p >= 0.5));
        } else {
          obj.Jelem.attr('checked', !obj.Jelem.attr('checked'));
        }

        J[iphoneStyle].currentlyClicking = null;
        J[iphoneStyle].dragging = null;
        obj.Jelem.change();
      });
  
    // Animate when we get a change event
    this.Jelem.change(function() {
      if (obj.Jelem.is(':disabled')) {
        obj.container.addClass(obj.disabledClass);
        return false;
      } else {
        obj.container.removeClass(obj.disabledClass);
      }
      
      var new_left = obj.Jelem.attr('checked') ? obj.rightSide : 0;

      obj.handle.animate({         left: new_left },                 obj.duration);
      obj.onLabel.animate({       width: new_left + 4 },             obj.duration);
      obj.offSpan.animate({ marginRight: -new_left },                obj.duration);
      obj.onSpan.animate({   marginLeft: new_left - obj.rightSide }, obj.duration);
    });
  },
  
  // Setup the control's inital position
  initialPosition: function() {
    this.offLabel.css({ width: this.container.width() - 5 });

    var offset = (J.browser.msie && J.browser.version < 7) ? 3 : 6;
    this.rightSide = this.container.width() - this.handle.width() - offset;

    if (this.Jelem.is(':checked')) {
      this.handle.css({ left: this.rightSide });
      this.onLabel.css({ width: this.rightSide + 4 });
      this.offSpan.css({ marginRight: -this.rightSide });
    } else {
      this.onLabel.css({ width: 0 });
      this.onSpan.css({ marginLeft: -this.rightSide });
    }
    
    if (this.Jelem.is(':disabled')) {
      this.container.addClass(this.disabledClass);
    }
  }
});

// jQuery-specific code
J.fn[iphoneStyle] = function(options) {
  var checkboxes = this.filter(':checkbox');
  
  // Fail early if we don't have any checkboxes passed in
  if (!checkboxes.length) { return this; }
  
  // Merge options passed in with global defaults
  var opt = J.extend({}, J[iphoneStyle].defaults, options);
  
  checkboxes.each(function() {
    J(this).data(iphoneStyle, new J[iphoneStyle](this, opt));
  });

  if (!J[iphoneStyle].initComplete) {
    // As the mouse moves on the page, animate if we are in a drag state
    J(document)
      .bind('mousemove touchmove', function(event) {
        if (!J[iphoneStyle].currentlyClicking) { return; }
        if (event.pageX != J[iphoneStyle].dragStartPosition) { J[iphoneStyle].dragging = true; }
        event.preventDefault();
    
        var x = event.pageX || event.changedTouches[0].pageX;
        J(event.target).trigger('iPhoneDrag', [x]);
      })

      // When the mouse comes up, leave drag state
      .bind('mouseup touchend', function(event) {        
        if (!J[iphoneStyle].currentlyClicking) { return; }
        event.preventDefault();
    
        var x = event.pageX || event.changedTouches[0].pageX;
        J(J[iphoneStyle].currentlyClicking).trigger('iPhoneDragEnd', [x]);
      });
      
    J[iphoneStyle].initComplete = true;
  }
  
  return this;
}; // End of J.fn[iphoneStyle]

J[iphoneStyle].defaults = {
  duration:          200,                       // Time spent during slide animation
  checkedLabel:      'ON',                      // Text content of "on" state
  uncheckedLabel:    'OFF',                     // Text content of "off" state
  resizeHandle:      true,                      // Automatically resize the handle to cover either label
  resizeContainer:   true,                      // Automatically resize the widget to contain the labels
  disabledClass:     'iPhoneCheckDisabled',
  containerClass:    'iPhoneCheckContainer',
  labelOnClass:      'iPhoneCheckLabelOn',
  labelOffClass:     'iPhoneCheckLabelOff',
  handleClass:       'iPhoneCheckHandle',
  handleCenterClass: 'iPhoneCheckHandleCenter',
  handleRightClass:  'iPhoneCheckHandleRight'
};

})(jQuery, 'iphoneStyle');
