// fix ie6 image flicker bug
try { document.execCommand('BackgroundImageCache', false, true);} catch(e) {}

$(document).ready(function(){
	
	$('input#location').focus(function() {
		$(this).addClass(' clicked');
	});
	
	$('form#header_search_form').submit(function() 
	{
		if (!($('input#location').is('.clicked')))
		{
			$('input#location').attr('value', '');
		}
	});
	
	
	// Handle new window links (since target=_blank is deprecated
	$(".external").click(function(){
 		var newWindow = window.open(this.getAttribute('href'), '_blank');
  		if (newWindow) {
			if (newWindow.focus) {
				newWindow.focus();
				return false;
			}
  		} else {
			return true;
		}
	});
	// Pop a confirmation message on any inputs, links with class of confirm
	$('.confirm').click(function() {
		var answer = confirm("Are you sure?");
		return answer;
	});
	
	$('#check_all').livequery('click', function(event) {
		$('input.deletion').attr('checked', 'checked');
		$(this).attr('id', 'uncheck_all');
		return false;
	});
	
	$('#uncheck_all').livequery('click', function(event) {
		$('input.deletion').attr('checked', '');
		$(this).attr('id', 'check_all');
		return false;
	});
	
	// hide floated labels in header
	$('input.clear').focus(function()
	{
		$(this).attr('value', '').unbind();
	});
	
	$('form#package_change label.show_hilite input').click(function() 
	{
		$('label.hilite_on').removeClass('hilite_on');
		$(this).parent('label').addClass('hilite_on');
	});
	
	// jq ui tabs

	if ($('body').is('#page_dashboard'))
	{
		$('body#page_dashboard .tabs').tabs({selected: 2});
	}
	else
	{
		$('.tabs').tabs();	
	}
	
	
	// jq ui date
	$('.cal').datepicker();
	
	$('a.hint').click(function() {
		var target = $(this).attr('id') + '_details';
		$('#'+target).show();
		$('body').addClass('hint_on');
	});
	
	
	$('body.hint_on').livequery('click', function(event) { 
		$('span.hint').hide();
		$(this).removeClass('hint_on');
	});
	
	// prompts in messages
	$('textarea.write').focus(function()
	{
		$('#body_prompt').hide();
	});
	
	$('#body_prompt').click(function() {
		$(this).hide();
		$('textarea.write').focus();
		setCaretPosition('body', 0);
		
	});
	
	$('textarea.write').blur(function()
	{
		if ($(this).attr('value') == '')
		{
			$('#body_prompt').show();
		}
	});
	
	$('.verified').append('<img src="/assets/images/gui/icon_small_check.gif" />');
	

	// highlight table rows
	$('table.tablesorter tr').hoverClass('hover');
	// Any link with class ajax will attept to load the result into a node with the id LINKID_result.
	// or will update itself if it has the class self
	$("a.ajax").livequery('click', function(event) {
		$(this).html('<img src="/assets/shared/images/gui/loader_small.gif" />');
		// ajax query string is added to tell the view_manager to serve the ajax view
		var target_url 		= $(this).attr('href')+'?ajax';
		var this_id 		= $(this).attr('id');
		var self_update 	= $(this).is('.self');
		var target_node 	= this_id+'_result';	
		$.get(target_url,
			function(data){
				if (self_update) {
					$('#'+this_id).after(data).remove();
				} else {
					$('#'+target_node).html(data).highlightFade({color:'#FDF88B',speed:2000,iterator:'sinusoidal'});
				}
			}
		);
		return false;
	});

	window.onunload = function() {
		$('input.loading').removeClass('loading');
	}
	
	// Hide submit button while waiting for response
	$("form.show_loading").livequery('submit', function(event) {
		$('input.show_loader').addClass('loading').attr('value', '  Searching');
	});
	// Add class of hilite to any element and it gets flashed
	$('.hilite').highlightFade({color:'#FDF88B',speed:2000,iterator:'sinusoidal'});


	// Dev notes
	$('div.TODO').hoverClass('hover');
	
	// Feeds get "pinball" style linking
	$("ul.feed li").addClass('pinball').hoverClass('hover');
	$("ul.feed li").click(function(){
		var url = $(this).children('a').get(0).attr('href');
		var newWindow = window.open(url, '_blank');
  		if (newWindow) {
			if (newWindow.focus) {
				newWindow.focus();
				return false;
			}
  		} else {
			return true;
		}
	});	

// FORMS ----------------------------------------------------------
	// Let inputs get a class of focus on focus because IE6/IE6 won't otherwise
	$('input, textarea').livequery('focus', function(event) { $(this).addClass('focus');	});
	$('input, textarea').livequery('blur', function(event) { 	$(this).removeClass('focus'); });
	


	// add a class of hilite to all select options for Other
	$('select option[@value=Other]').livequery(function(event) { $(this).addClass('add_option'); });

	// Trigger display of extra input via SELECT (wrapped in .freeform) when needed	
	$('select.freeform').livequery('change', function(event) { 
		var this_id = $(this).attr('id');
		if ($(this).attr('value') == 'Other') {
			$('span#freeform_'+this_id).addClass('active').slideDown('fast').highlightFade({color:'#FDF88B',speed:2000,iterator:'sinusoidal'});
		} else if ($('span.freeform').is('.active')) {
			$('span#freeform_'+this_id).removeClass('active').slideUp('fast');
		}
	});
	// Trigger via checkbox
	$('input.freeform').livequery('click', function(event) { 
		var this_id = $(this).attr('id');
		if ($(this).is(":checked")) {
			$('span#freeform_'+this_id).addClass('active').slideDown('fast');
		} else {
			$('span#freeform_'+this_id).removeClass('active').slideUp('fast');
		}
	});
	// Hide associated input
	$('span.freeform:not(.open)').livequery(function(event) { $(this).css('display', 'none'); });
	
	// Search forms need city to set to all and vanish when regions are set to all
	$('form.search input#region').livequery('change', function(event) {
		if ($(this).attr('value') == 0) {
			$('#city_label').toggle();
			$('#city').attr('value', 0);
		}
	});
	
	// Add a text link for to reveal the Edit colleges button when editing profiles
	$('form:not(.submitted) span.freeform.trigger_college').before('<p><a href="#" class="trigger_college">Edit College Details</a></p>');	
		$('a.trigger_college').click(function() {
			$('span.freeform').addClass('active').slideDown('fast').highlightFade({color:'#FDF88B',speed:2000,iterator:'sinusoidal'});
			$(this).hide();
			return false;
		});

	// Cascade selects
	$('select.update_button').livequery('change', function(event) {
							// ?ajax query string triggers ajax awareness in framework
		var this_action 	= $('form.dynamic_regions').attr('action')+'?ajax';
		var this_value 		= $(this).attr('value');
		var this_id 		= $(this).attr('id');
		var this_name 		= $(this).attr('name');
							// send the same POST array key that the submit button for this select would
		var this_trigger 	= $(this).parent('label').next('input.update_button').attr("name");
							// get the target id to update ... also name of value key
		var this_target 	= $(this).parent('label').next('input.update_button').attr("id");
							// the submit button will have an id like update_SELECT where SELECT is the target to be updated
		var this_target 	= this_target.substring(7);
		// default callback is replace - custom called via a string off a hyphen on the update_button ID: update_SELECT-callback
		var callback = 'replace';
		var tmp = this_target.split('-');
		if (typeof(tmp[1])!='undefined') { 
			this_target = tmp[0]; 
			callback = tmp[1]; 
		}
		$(this).after('<img class="loading" id="'+this_id+'_loading" src="/assets/shared/images/gui/blue_loader.gif" alt="loading content" />');
		$('#'+this_target).attr('disabled', 'disabled');
		$.ajax({type: "POST",url: this_action, data: this_name+"="+this_value+"&"+this_trigger+"=1&this_target="+this_target,
  			success: function(data){
    			if (callback == 'replace') {
					$('#'+this_target).after('&nbsp;'+data+'&nbsp;').remove();
				} else if (callback=='colleges_and_cities') {
					// custom callback for reg form where colleges and cities updated via region
					$('#college_label, span.freeform:not(.permanent)').remove();
					$('#update_college-colleges_and_cities').after(data);					
				} else if (callback=='second_colleges_and_cities') {
					// custom callback for reg form where colleges and cities updated via region
					$('#second_college_label, span.freeform:not(.permanent)').remove();
					$('#update_second_college-second_colleges_and_cities').after(data);					
				}
				$('#'+this_target).attr('disabled', '');
				$('#'+this_id+'_loading').remove();
  			}
		});
		return false;
	});
	// hide the submits that not js users get
	$('input.update_button:not(.nohide)').livequery(function(event) { $(this).hide();	});	
	
	// Clone and increment resume fieldsets
	$("input.get_repeat:not('.del')").livequery('click', function(event) {
		var this_id 		= $(this).attr('id');
							// grab the index of which expandable from the buttons id after colon
		var tmp 			= this_id.split(':');
		var mode 			= tmp[0];
		var key 			= parseInt(tmp[1]);
		var next			= (parseInt(key))+1;
		var tmp 			= mode.split('-');
		var this_section 	= tmp[1]; 
		
		var fieldset 		= $(this).parent('fieldset').html();
		fieldset = fieldset.replace(new RegExp(this_section+"_"+key, "g" ), this_section+"_"+next);
		fieldset = fieldset.replace(new RegExp("add-"+this_section+":"+key, "g" ), "add-"+this_section+":"+next);
		// workhistory has that damned extra underscore. 
		// a workaround involved removing it form some fields.
		// this is a workaround for that workaround
		if (this_section == 'work_history') {
			fieldset = fieldset.replace(new RegExp("workhistory_"+key, "g" ), "workhistory_"+next);
		}
				
		fieldset = '<fieldset class="repeats clearfix" id="'+this_section+'_fieldset_'+next+'">'+fieldset+'</fieldset>';
		$(this).parent('fieldset').after(fieldset);
		$('#'+this_section+'_fieldset_'+next+' textarea, #'+this_section+'_fieldset_'+next+' input:not(.submit)').each(function() {
			$(this).val('');
		});
		$('#'+this_section+'_fieldset_'+next+' select').each(function() {
			$(this).attr('selectedIndex', '-1');
		});
		$('#'+this_section+'_fieldset_'+next).highlightFade({color:'#FDF88B',speed:100});
		$(this).after('<input type="submit" name="remove-'+this_section+'" value="Remove" class="submit get_repeat del"  />').remove();
 		return false;
	});
	$("input.get_repeat.del").livequery('click', function(event) {
		$(this).parent('fieldset').remove();
	});
// MESSAGES ----------------------------------------------------------
	// Hide the resume_preview button unless you have a resume selected in your message
	$('input#resume_preview').hide();
	// Show when we do
	$('select#resume_select').change(function() {
		
		if ((this.value == 0) || (this.value.indexOf("upload:") == 0)) {
			$('input#resume_preview').hide().removeClass('active');
		} else {
			$('input#resume_preview').not('.active').addClass('active').show().highlightFade({color:'#FDF88B',speed:2000,iterator:'sinusoidal'});
		}
	});
	$('input#send_message').hoverClass('hover');
	
	
	$("#active_jobs").sortable({ 
	    connectWith: ["#paused_jobs"], 
	    placeholder: "ui-selected", 
	    revert: true, 
	    axis:           'y', 
	      start: function(e, ui) { 
	    	$("ul.job_listing li a").bind("click", function(){
			  return false;
			});
	    },
	    stop: function(e, ui) { 
	    	$("ul.job_listing li a").unbind('click');
	    	$("ul.job_listing li a").bind("click", function(){
			  return true;
			});
	    },
	    beforeStop: function(e, ui) { 
	    	var dropped_on = ui.item.parent('ul').attr("id"); 
	    	var dropped = ui.item.attr("id"); 
	    	var call_uri = $('#'+dropped+' a.pause').attr("href"); 
	    	if (dropped_on == 'active_jobs')
	    	{
		    	process_status(call_uri);
	    	}
	    	else
	    	{
	    		process_status(call_uri);
	    	}
	   	}
	}); 
	$("#paused_jobs").sortable({ 
	    connectWith: ["#active_jobs"], 
	    placeholder: "ui-selected", 
	    revert: true, 
	    axis:           'y', 
	    start: function(e, ui) { 
	    	$("ul.job_listing li a").bind("click", function(){
			 return false;
			});
	    },
	    stop: function(e, ui) { 
	    	$("ul.job_listing li a").unbind('click');
	    	$("ul.job_listing li a").bind("click", function(){
			  return true;
			});
	    },
	    
	    beforeStop: function(e, ui) { 
	    	var dropped_on = ui.item.parent('ul').attr("id"); 
	    	var dropped = ui.item.attr("id"); 
	    	var call_uri = $('#'+dropped+' a.pause').attr("href"); 
	    	if (dropped_on == 'active_jobs')
	    	{
		    	process_status(call_uri);
	    	}
	    	else
	    	{
	    		process_status(call_uri);
	    	}
	   	}
	});

	function process_status(uri)
	{
		$.get(uri, function(data){
		  
		});
	}

	$('#confirmModalContainer').livequery(function(event) {
		$(this).draggable();
	});
	


// ADMIN ----------------------------------------------------------------------
	$('ul.select').hoverClass('hover');
	
	$("#benefit_form ul").sortable({ 
		    placeholder: "ui-selected", 
		    forcePlaceholderSize: true, 
		    revert: true, 
		    containment: 'parent',
		    axis:           'y',
			stop: function(e, ui) { 
	    		update_list($(this).attr('id'));
	   		}
	});

	
});

function update_list(id)
{
	// just run through the list resetting all the sort values
	var count = 0;
	$('#'+id+' li input.sort_value').each(function() 
	{
		count++;
		$(this).attr('value', count);
	});
}

$('input.no_resume_confirm').click(function() {
	
	send_confirm("Job limit reached");
	return false;
});

					
function send_confirm(message, callback) {
	$('#confirm').modal({
		close:false, 
		overlayId:'confirmModalOverlay',
		containerId:'confirmModalContainer', 
		onShow: function (dialog) {
			dialog.data.find('.message').append(message);

			// if the user clicks "yes"
			dialog.data.find('.yes').click(function () {
				// close the dialog
				$.modal.close();
				$('form#message').submit();
				return true;
			});
			dialog.data.find('.no').click(function () {
				return false;
				// close the dialog
				$.modal.close();
			});
		}
	});
}					
					
function ui_confirm(message, callback) {
	$('#confirm').modal({
		close:false, 
		overlayId:'confirmModalOverlay',
		containerId:'confirmModalContainer', 
		onShow: function (dialog) {
			dialog.data.find('.message').append(message);

			// if the user clicks "yes"
			dialog.data.find('.yes').click(function () {
				// call the callback
				if ($.isFunction(callback)) {
					callback.apply();
				}
				// close the dialog
				$.modal.close();
			});
		}
	});
}

function setCaretPosition(elemId, caretPos) {
    var elem = document.getElementById(elemId);

    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}