/**
* Various javascript functions for JS+
*@author SM Dev <noemail@noemail.com>
*$Id: jsplus.js,v 1.121 2009/08/21 14:23:33 jkytola Exp $
*/


/**
* Common initialization
*
*@access public
*@return void
*/
$(document).ready(function()
{
	//Simple double submit prevention
	$('form').submit(function()
	{
		$(':submit', this).click(function()
		{  
			return false;  
		});  
	});

	// make external links open in new windows
	$('a[rel=external]').attr('target', '_new');

	// put spans in legends so we can position them
	$('legend').filter(function()
	{
		return ($(this).children('span:first-child').length == 0);
	})
	.wrapInner('<span></span>');

	// initialize a dialog object
	$("#dialog").dialog(
	{
		autoOpen: false,
		modal: true, 
		draggable: false, 
		resizable: false,
		overlay: 
		{
			opacity: 0.5, 
			background: "#000"
		},
		open: lightbox_open_cb,
		close: lightbox_close_cb,
		height: 475,
		width: 550,
		buttons:
		{
			"Close": function()
			{
				$(this).dialog("close");
			}
		} 
	});

	// init tutorial videos
	var opts = 
	{
		height: 720,
		width: 787
	};
	$(".tutorial_popup").each(function () {
		$(this).bind("click", function () {
			lightbox($(this).attr('title'), $(this).attr('href'), opts);
			return false;
		});
	});

	initializeTargetExpressLinks();
});



var FLASH_FADE_IN = 500;
var FLASH_KEEP_ON = 2500;
var FLASH_FADE_OFF = 1500;

/**
* Reset the visibitly of a flash message
*
*@access public
*@param string id of the message
*@return void
*/
function resetFlashMessage()
{
	$('#flash_message').removeClass('error').removeClass('success').css({visibility: 'hidden'});
}

/**
* Flash message
*
*@access public
*@param string class of the flash message
*@param string the flash message
*@return void
*/
function flashMessage(cls, msg)
{
	$('#flash_message').addClass(cls);

	msg = (msg == null) ? "" : msg;
	$('#flash_message').html(msg);

	// annimate flash message
	$('#flash_message')
	.css({
		opacity: 0,
		visibility: 'visible'
	})
	.animate({opacity: 1}, FLASH_FADE_IN, "linear", function()
	{
		$(this).animate({opacity: 1}, FLASH_KEEP_ON, "linear", function()
		{ 
			/* keep on
			$(this).animate({opacity: 0}, FLASH_FADE_OFF, "linear", function()
			{ 
				$(this)
				.css({
					// when all done, reset visibilty to hidden
					visibility: 'hidden'
				}).removeClass(cls);
			}) 
			*/
		})
	});
}

/**
* Make a lightbox
*
*@access public
*@param string - title of lightbox
*@param content - id of div, or url to grab content from
*@param hash of options to override from default
*@return void
*/
function lightbox(title, content, new_opts)
{
	var new_opts = (new_opts) ? new_opts : {};
	// some defaults/resets
	new_opts['height'] = (new_opts['height']) ? new_opts['height'] : 475;
	new_opts['width'] = (new_opts['width']) ? new_opts['width'] : 550;
	if (!new_opts['buttons'])
	{
		new_opts['buttons'] =
		{
			"Close": function()
			{
				$(this).dialog("close");
			}
		} 
	}

	new_opts['title'] = title;

	// add a child div to the content so we can pad correctly
	$('#dialog').append('<div></div>');
	if (content)
	{
		if (content.substring(0,1) == '/')
			$('#dialog div:first-child').load(content, lightbox_load_cb);
		else if (content.substring(0,1) == '#')
			$('#dialog div:first-child').html($(content).html());
		else
			$('#dialog div:first-child').html(content);
	}

	$('#dialog').dialog('option', new_opts).dialog('open');
}

/**
* lightbox open callback
*
*@access public
*@return void
*/
function lightbox_open_cb()
{
	$('#wrapper .content').css('visibility', 'hidden');
	$('#dialog').find('a[rel=external]').attr('target', '_new');
}

/**
* lightbox close callback
*
*@access public
*@return void
*/
function lightbox_close_cb()
{
	// force reload to clear out audio
	$('#dialog div:first-child').load('/_content');
	$('#wrapper .content').css('visibility', 'visible');
	$('#dialog').html('');
}

/**
* lightbox load callback
*
*@access public
*@return void
*/
function lightbox_load_cb()
{
	$(this).find('a[rel=external]').attr('target', '_new');
 	$(this).find('input').each(function()
	{
		$(this).keypress(function (e)
		{
			if (e.which == 13)
				return false;
		});
	});
}


/**
* Fire deletion
*
*@access public
*@param string the page to post
*@param string the domid for the deletion
*@param string the node id for display update
*@param string (html) the message to show 
*@param int the height of the popup
*@param int the width of the popup
*@param function the close callback
*@return void
*/
function deleteItem(page, domid, id, msg, height, width, remove_cb)
{
	var msg = (msg) ? msg : '';
	var height = (height) ? height : 150;
	var width = (width) ? width : 300;

	resetFlashMessage();

	var title = 'Are you sure?';
	var opts = 
	{
		height: height,
		width: width,
		buttons:
		{
			"Cancel": function()
			{
				$(this).dialog("close"); 
			} ,
			"Remove": function()
			{
				var other = new Array(id, remove_cb);
				k_remoteRequest(getURLStarter()+'/_status/'+page, 'deleteCallback', domid+'=true', other, true, true);
				$(this).dialog("close"); 
			}
		}
	};
	lightbox(title, msg, opts);
}

/**
* Handle the deletion transaction
*
*@access public
*@param object
*@param const
*@return void
*/
function deleteCallback(request, status)
{
	var id = request.otherParams[0];
	var cb = request.otherParams[1];
	switch(status)
	{
		case K_AJAX_NOT_SUPPORTED:
			flashMessage('error', 'Sorry, your browser does not appear to support remote requests.');
			break;
		case K_AJAX_LOADING:
			document.body.style.cursor = 'wait';
			$('#js_icon_'+id).toggle();
			$('#delete_'+id).toggle();
			break;
		case K_AJAX_COMPLETE_FAILURE:
			document.body.style.cursor = 'default';
			var errorID = getErrorID(request.getResponseText());
			flashMessage('error', 'Sorry, we could not complete your request at this time..' + errorID);
			break;
		case K_AJAX_COMPLETE_SUCCESS:
			document.body.style.cursor = 'default';
			// trim result
			var result = request.getResponseText().replace(/^\s\s*/, '').replace(/\s\s*$/, '');
			if (result != 'OK')
			{
				flashMessage('error', 'Sorry, there was an error completing your request.');
				return;
			}
			var row = $('#delete_parent_'+id);
			if (row)
			{
				row.remove();
				if (cb)
				{
					cb();
				}
				flashMessage('success', 'Item Removed!');
			}
			else
				flashMessage('error', 'Sorry, there was an error completing your request.');
			break;
	}
}

/**
* Make remote login request and send the user to the new place
*
*@access public
*@param int
*@param int
*@param resource
*@param string
*@param string
*@return void
*/
function remoteLogin(system, companyid, popupHandle, dest, postfix)
{
	var url = getURLStarter() + '/request/InitiateRemoteLogin/' + system + '/' + companyid;

	if (dest)
	{
		url = url + '/' + dest;
	}
	var rand = Math.floor(Math.random()*1000);
	url = url + '?rand=' + rand;

	var params = new Object();
	params[0] = popupHandle;
	params[1] = postfix;

	k_remoteRequest(url, 'remoteLoginCallback', null, params, true, true);
}

/**
* Handle the remote login transaction
*
*@access public
*@param object
*@param const
*@return void
*/
function remoteLoginCallback(request, status)
{
	switch(status)
	{
		case K_AJAX_NOT_SUPPORTED:
			flashMessage('error', 'Sorry, your browser does not appear to support remote requests.');
			break;
		case K_AJAX_LOADING:
			document.body.style.cursor = 'wait';
			break;
		case K_AJAX_COMPLETE_FAILURE:
			document.body.style.cursor = 'default';
			var errorID = getErrorID(request.getResponseText());
			flashMessage('error', 'Sorry, we could not complete your request at this time..' + errorID);
			break;
		case K_AJAX_COMPLETE_SUCCESS:
			document.body.style.cursor = 'default';

			// check for addtn'l stuff to tack on
			var win = request.otherParams[0];
			if (!win)
				win = window;

			// make sure it's a window & that we have a url
			if (typeof(win) == 'object' && win.open)
			{
				var url = request.getResponseText();
				var regexp = /^(http|https):\/\//;
				var is_url = regexp.test(url);

				if(request.otherParams[1])
					url += request.otherParams[1];

				if (is_url)
				{
					// ok, send them to a window with the link
					win.focus();
					win.location = url;
					return;
				}
				else
				{
					win.close();
				}
			}

			flashMessage('error', 'Sorry, there was an error completing your request.');

			break;
	}
}



function toggle_account_mode()
{
	$('#getting_started_check').toggleClass('getting_started_off');

	$('#command_center').find('ul').toggle();
	$('#more_info').toggle();
	$('#snap_shot').toggle();

	// send the request to update settings
	var url = getURLStarter() + '/request/ToggleGettingStarted/'+($('#getting_started_check').hasClass('getting_started_off')?0:1);
	k_remoteRequest(url, 'toggle_account_mode_callback', null, null, null, true);
}

/**
* toggle account mode callback
*
*@access public
*@param object
*@param const
*@return void
*/
function toggle_account_mode_callback(request, status)
{
	switch(status)
	{
		case K_AJAX_NOT_SUPPORTED:
			flashMessage('error', 'Sorry, your browser does not appear to support remote requests.');
			break;
		case K_AJAX_LOADING:
			document.body.style.cursor = 'wait';
			break;
		case K_AJAX_COMPLETE_FAILURE:
			document.body.style.cursor = 'default';
			var errorID = getErrorID(request.getResponseText());
			flashMessage('error', 'Sorry, we could not complete your request at this time..' + errorID);
			break;
		case K_AJAX_COMPLETE_SUCCESS:
			document.body.style.cursor = 'default';
			break;
	}
}

/**
* Hover actions for tabbed navigation 
*
*@access public
*@param sting container id
*@return void
*/
function tabNavHover(id)
{
	$('#'+id).find('li').each(function()
	{
		if (!$(this).hasClass('active'))
		{
			$(this).css('background-position', '0 0');
			$(this).children()
				.mouseover(function() {
					$(this).parent().css('background-position', '0 -41px');
				})
				.mouseout(function() {
					$(this).parent().css('background-position', '0 0');
				})
				.mousedown(function() {
					$(this).parent().css('background-position', '0 -83px');
				})
				.mouseup(function() {
					$(this).parent().css('background-position', '0 0');
				})
		}
		else
		{
			$(this).css('background-position', '0 -130px');
			$(this).children()
				.unbind('mouseover')
				.unbind('mouseout')
				.unbind('mousedown')
				.unbind('mouseup');
		}
	});
}

/**
* initialize the country/state selectors
*
*@access public
*@return void
*/
function initCountryStates()
{
	// find country selectors with country_XX as a classname
	// and pair them with state selectors with state_XX as classname
	$(".state_country").each(function()
	{
		var state = $(this).find('.state');
		var country = $(this).find('.country');

		country.change(function()
		{
			updateStates(state.attr('id'), country.attr('id'));
		});

		if (country.attr('orig') && country.val() == '')
		{
			country.val('-1');
			country.change();
		}
		else if (country.val() == '')
		{
			country.val('US');
			country.change();
		}
	});
}

/**
* update the state selector
*
* @param string id of the state selector
* @param stsring id of the country selector
*@access public
*@return void
*/
function updateStates(stateSelID, countrySelID)
{
	var cID = $('#'+countrySelID+' option:selected')[0].value;
	if (cID == -1)
	{
		var hasEmpty = ($('#'+countrySelID+' option:first').val()?0:1);
		if (hasEmpty)
			$('#'+countrySelID).val('').change();
		var opts = 
		{
			height: 150,
			width: 300
		};
		lightbox("We're sorry", "JobSlinger Plus currently only supports US and Canadian users.", opts);
	}
	else
		k_remoteRequest(getURLStarter() + '/request/UpdateStates/' + cID, 'updateStatesCallback', null, [stateSelID, countrySelID]);	
}

/**
* callback for summary search
*
*@access public
*@param object
*@param string
*@return void
*/
function updateStatesCallback(request, status)
{
	switch(status)
	{
		case K_AJAX_NOT_SUPPORTED:
			flashMessage('error', 'Sorry, your browser does not appear to support remote requests.');
			break;
		case K_AJAX_LOADING:
			document.body.style.cursor = 'wait';
			break;
		case K_AJAX_COMPLETE_FAILURE:
			document.body.style.cursor = 'default';
			var errorID = getErrorID(request.getResponseText());
			flashMessage('error', 'Sorry, we could not complete your request at this time..' + errorID);
			break;
		case K_AJAX_COMPLETE_SUCCESS:
			document.body.style.cursor = 'default';

			var stateSelID = request.otherParams[0];
			var countrySelID = request.otherParams[1];

			var s = $('#'+request.otherParams[0]).html(request.getResponseText());
			break;
	}
}



/**
* put some gray helper text in an input
* and add an onclick to clear the text
*
*@access public
*@param input jquery-wrapped input
*@param string content
*@return void
*/
function grayInput($input, content)
{
	// might already have 'default' content
	var defaultContent = '';
	if($input.val())
		defaultContent = $input.val();

	$input.
		val((defaultContent?defaultContent:content)).
		addClass((defaultContent?'':'gray_input')).
		focus(function()
			{ 
				if($(this).val() == content)
					$(this).val('');
				
				$(this).
				removeClass('gray_input');
			}
			).
		blur(function()
			{
				if($(this).val() == '')
				{
					$(this).
					val(content).
					addClass('gray_input');
				}
			}
			);
}

var EnableTargetExpressRemoteLogin = true;
/**
* apply a remote login click action to all target exress links
*
* @access public
* @return void
**/
function initializeTargetExpressLinks()
{
	$('.target_express_link')
	.click(
		function()
		{
			if(!EnableTargetExpressRemoteLogin)
				return true;

			var obfuscated_id = this.href.split(/\//).reverse()[0];
			remoteLogin('jobslinger', '1', null, null, '/'+obfuscated_id);
			return false;
		}
	);
}

/**
* Returns the correct protocol and host
* for callbacks based on the current environment
*
*@access public
*@return string
*/
function getURLStarter()
{
	if(document.URL.slice(0,5) == 'http:')
		return 'http://www.jobslingerplus.com';
	else
		return 'https://www.jobslingerplus.com';
}


/**
* Returns the error id from the sd.tpl
*
*@access public
*@param string
*@return string
*/
function getErrorID(html)
{
	// check html results
	var errorID = $('#errorid', html).html();
	if (errorID)
		return ' Please contact support with reference-id '+errorID;

	// check xml results
	var regexp = new RegExp('<error_id>(.*)</error_id>');
	var errorArray = regexp.exec(html);
	if (errorArray)
	{
		var errorID = errorArray[1];
		if (errorID)
			return ' Please contact support with reference-id '+errorID;
	}
	
	return '';
}
