$().ready(function(){
	try {
		$('a[rel*=facebox]').facebox();
		jQuery.facebox.settings.opacity = 0.5;
		jQuery.facebox.overlay = true;
		$('#menu_slim').html($('#section-menu').html())
	} catch(e) {

	}
	
	try {
		tb_init('a.thickbox, area.thickbox, input.thickbox');
	} catch(e) {

	}
	
	//label2value();	

	tooltip();
	
	$("a[class^='faq_']").each(function() {
		$(this).click(function() {
			answer = $(this).nextAll("div[class^='faq_']:first");
			if(answer.is(':hidden') ) {
				answer.fadeIn('fast');
				this.className='faq_active';
			} else {
				answer.fadeOut('fast');
				this.className='faq_question';
			}			
			return false;
		});
	});
});



function load_facebox(url) {
	jQuery.facebox(function() { 
		jQuery.get(url, function(data) {
			jQuery.facebox(data)
		})
	})
}

function clearFlashNotices() {
	$('#notice_success').blindUp();
	$('#notice_error').blindUp();
	$('#notice_notice').blindUp();
}
function init_navigation(show_wide) {
	if (show_wide == true) {
		$('#navigation').hide();
		$('#navigation_footer').hide();
		$('#navigation_slim').show();
		$('#navigation_slim').css('top', $('#main_content .box.heading:first').offset().top);
		$('#main_content').css('width', '100%')
		$('#site_info').css('width', '100%')
		$('#main_content .box.heading h2:first').css('marginLeft', '60px');
	} else {
		$('#navigation').show();
		$('#navigation_slim').hide();
	}
}


function toggle_navigation() {
	if ($('#navigation').css('display') == 'none') {
		try {
			set_menu_width(false)
			$('#main_content').animate({width:'79.25%'}, 750);
			$('#site_info').animate({width:'79.25%'}, 750);
			$('#main_content .box.heading h2:first').animate( {'marginLeft':'0px'}, 750);
			//setTimeout("$('#navigation').animate({width:'16.75%'}, 200)", 850);
			//setTimeout("$('#navigation').toggle('fast')", 850);
			setTimeout("$('#navigation').toggle('fast')", 850);
			setTimeout("$('#navigation_footer').toggle('fast')", 850);
			setTimeout("$('#navigation_slim').toggle('fast')", 850);
			setTimeout("$('#btn_menu_toggle').attr('src','/images/admin/btn_horiz_contract.png');",850);
		} catch(e) {}
	} else {
		try {
			set_menu_width(true)
			$('#navigation').toggle('fast');
			$('#navigation_footer').toggle('fast');
			$('#navigation_slim').toggle('fast');
			$('#navigation_slim').css('top', $('#main_content .box.heading:first').offset().top);
			setTimeout("$('#main_content').animate({width:'100%'}, 750);", 200);
			setTimeout("$('#site_info').animate({width:'100%'}, 750);", 200);
			setTimeout("$('#btn_menu_toggle').attr('src','/images/admin/btn_horiz_expand.png');",750);
			setTimeout("$('#main_content .box.heading h2:first').animate( {'marginLeft':'60px'}, 750);", 250);
		} catch(e) {}
	}
}

function trim(str) {
	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
}

function reset_labels() {
	$("label").each(function(){
		obj = document.getElementById($(this).attr("for"));
		if (obj) {
			if(($(obj).attr("type") == "text") || (obj.tagName.toLowerCase() == "textarea")){	
				var text = $(this).text();
				if (trim($(obj).val()) == text) {
					$(obj).val('')
				}
			}
		}
	});
}

this.label2value = function() {	

	var inactive = "inactive";
	var active = "active";
	var focused = "focused";
	try {
		$("label").each(function(){
			obj = document.getElementById($(this).attr("for"));
			if (obj) {
				if(($(obj).attr("type") == "text") || (obj.tagName.toLowerCase() == "textarea")){	


					var text = $(this).text();
					$(this).css("display","none");		

					if (trim($(obj).val()) == '' || trim($(obj).val()) == text) {	
						$(obj).addClass(inactive);		
						$(obj).val(text);
					} else {
						$(obj).addClass(active);
					}		
					$(obj).focus(function(){	
						$(this).addClass(focused);
						$(this).removeClass(inactive);
						$(this).removeClass(active);								  
						if($(this).val() == text) $(this).val("");
					});	
					$(obj).blur(function(){	
						$(this).removeClass(focused);													 
						if($(this).val() == "") {
						$(this).val(text);
							$(this).addClass(inactive);
						} else {
							$(this).addClass(active);		
						};				
					});				
				};	
			}
		});
	} catch(e) {
		;
	}
	
};




// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults
function update_hidden_dates(id, prefix) {
	var date_string = $('#'+id).val();
	var element_id = '';
	if (prefix == '') {
		element_id = id;
	} else {
		element_id = prefix+'_'+id;
	}
	var date_arr = date_string.split('/');
	var year  = date_arr[2];
	var month = date_arr[0];
	var day   = date_arr[1];
	if (parseFloat(year) < 100) {
		year = parseFloat(year) + 2000;
	}
	
	$('#'+element_id+'_1i').val(year);
	$('#'+element_id+'_2i').val(month);
	$('#'+element_id+'_3i').val(day);
	// alert('#'+prefix+'_'+id+'_1i')
	// alert($('#'+prefix+'_'+id+'_1i').val() + "-" + $('#'+prefix+'_'+id+'_2i').val() + "-" + $('#'+prefix+'_'+id+'_3i').val())
	
}

/*
 * Tooltip script 
 * powered by jQuery (http://www.jquery.com)
 * 
 * written by Alen Grakalic (http://cssglobe.com)
 * 
 * for more info visit http://cssglobe.com/post/1695/easiest-tooltip-and-image-preview-using-jquery
 *
 */
 
function loading(id, size) {
	if (size == undefined) {
		$('#'+id).html('<div class="ajax-loader"><img src="/images/admin/icon_ajax_loader.gif"/></div>')
	} else {
		if (true || size == 'small') {
			$('#'+id).html('<image src="/images/ajax-loader.gif" />')
		}
	}
}

this.tooltip = function(){	
	/* CONFIG */		
		xOffset = 10;
		yOffset = 30;	
	
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
	/* END CONFIG */		
	$(".tooltip").hover(function(e){
		if ($(this).attr('title') != '') {
			$(this).attr('t', $(this).attr('title'))
			$(this).attr('title', '')
		}
		if ($('#tooltip').length == 0) {
			$("body").append("<div id='tooltip'>"+ $(this).attr('t') +"</div>");
		} else {
			$('#tooltip').html($(this).attr('t'));
		}
		// alert("innerwidth: " + (window.innerWidth - 20) + " < " + (e.pageX))
		if ((window.innerWidth - 20) < (e.pageX + xOffset + 250)) {
			$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset - 255) + "px")
			.css("width", '200px')
			.fadeIn("fast");
		} else {
			$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px")
			.fadeIn("fast");
		}
			
    },
	function(){
		if ($(this).attr('t') != "") {
			$(this).attr('title', $(this).attr('t')); 
			$(this).attr('t', '');
		}
		$("#tooltip").remove();
    });	
	$("a.tooltip").mousemove(function(e){
		if ((window.innerWidth - 20) < (e.pageX + xOffset + 250)) {
			$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset - 255) + "px")
			.css("width", '200px');
		} else {
			$("#tooltip")
			.css("top",(e.pageY - xOffset) + "px")
			.css("left",(e.pageX + yOffset) + "px");
		}
		
	});			
};









function toggle(id) {
	if ($('#'+id).css('display') == 'none') {
		$('#'+id).blindDown();
	} else {
		$('#'+id).blindUp();
	}
}

function open_if_needed(id) {
	if ($('#'+id).css('display') == 'none') {
		$('#'+id).blindDown();
	}
}

function close_if_needed(id) {
	if ($('#'+id).css('display') != 'none') {
		$('#'+id).blindUp();
	}
}


/* Tooltip JS */
var cX = 0; var cY = 0;
function UpdateCursorPosition(e){ cX = e.pageX; cY = e.pageY;}
function UpdateCursorPositionDocAll(e){ cX = event.clientX; cY = event.clientY;}
if(document.all) { 
	document.onmousemove = UpdateCursorPositionDocAll; 
} else { 
	document.onmousemove = UpdateCursorPosition; 
}

function AssignPosition(elem) {
	elem.style.left = (cX-225) + "px";
	if ((cY+10+55) > window.innerHeight) {
		elem.style.top = (cY-30) + "px";
	} else {
		elem.style.top = (cY-30) + "px";
	}
}

function ShowContent(id) {
	if(id.length < 1) { return; }
	var elem = document.getElementById(id);
	AssignPosition(elem);
	elem.style.display = "";
}

function FillContent(from_id, to_id) {
	var from_elem = document.getElementById(from_id);
	var to_elem = document.getElementById(to_id);
	to_elem.innerHTML = from_elem.innerHTML;
}

function HideContent(id) {
	if(id.length < 1) { return; }
	document.getElementById(id).style.display = "none";
	EmptyContent(id+"_content");
}

function EmptyContent(id) {
	var elem = document.getElementById(id).innerHTML = '';
}


function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}

function validateUSPhone( strValue ) {
	if (strValue == null) {
	return false;
	}
	var stripped = strValue.replace(/[\s()+-]|ext\.?/gi, "");
	// 10 is the minimum number of numbers required
	return ((/\d{10,}/i).test(stripped));

	
	
}

function openCenteredWindow(url, height, width, name, parms) {	
	var left = Math.floor( (screen.width - width) / 2);
	var top = Math.floor( (screen.height - height) / 2);
	var winParms = "top=" + top + ",left=" + left + ",height=" + height + ",width=" + width;
	if (parms) { winParms += "," + parms; }
	var win = window.open(url, name, winParms);
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
	return win;
}

function toggle_arrow(shared_id, color, location) {
	color = typeof(color) != 'undefined' ? color : 'white';
	location = typeof(location) != 'undefined' ? location : '';

	$('#'+shared_id).toggle('blind');
	//alert('images/admin/icon_arrow_up_'+color+'_'+ location +'toggle.png')
	if ($('#show_'+shared_id).attr('src').indexOf('images/admin/icon_arrow_up_'+color+'_'+ location +'toggle.png') != -1) {
		$('#show_'+shared_id).attr('src', '/images/admin/icon_arrow_down_'+color+'_'+ location +'toggle.png');
	} else { 
		$('#show_'+shared_id).attr('src', '/images/admin/icon_arrow_up_'+color+'_toggle'+ location +'.png');
	}
}



function showSpinner() {
  $("#spinme").removeClass("spinner");
}

function hideSpinner() {
  $("#spinme").addClass("spinner");
}

function toggleMaterials() {
  if ($(".materials_target").attr("disabled") == true) {
  $(".materials_target").removeAttr("disabled");
  } else {
  $(".materials_target").attr("disabled", "disabled");
  }
}



// this is a workaround function due to a bug in select drop downs in safari 
function submit_status_change_if_needed(course_id, index, size, old_status){
	var status = $('#course_' + course_id + '_status').val();
	if ( status == 'a' || status == 'u' ){
		$.ajax({async:true, beforeSend:function(request){loading('course_' + course_id);}, data:'status=' + $('#course_' + course_id + '_status option:selected').val(),dataType:'script',type:'put',url:'/courses/'+ course_id +'?index=' + index + '&size=' + size + '&update_status_inline_by_director=true'});
	} else {
		alert('Please set the status to either approved or unapproved.');
		$('#course_' + course_id + '_status').val(old_status);	
	}
}


function check_that_mailing_has_valid_state(mailing_id){
	var state = $('#mailing_' + mailing_id + '_state option:selected').val();	
	if ( state == 'sent' || state == 'rejected' ){
		return true;
	} else {
		alert('Please choose either \'send\' or \'reject\'.');
		$('#mailing_' + mailing_id + '_state').val('Please select');
		return false;	
	}
}



function setup_timer(id) {
	$.getScript('/workers/get_worker_progress/'+id);
	timer = setTimeout("setup_timer(" + id + ")", 3500);
}



function toggle_notes(user_id){
	var id = '#add_notes_' + user_id;

	$(id).toggle();

	id = '#toggle_notes_link_' + user_id;

	var	link = $(id);
	if ( link.html() == '+' )
		link.html('-');
	else
		link.html('+');
}

function format_currency(num) {
	num = isNaN(num) || num === '' || num === null || num < 0 ? 0.00 : num;
	return parseFloat(num).toFixed(2);
}
