﻿/**
HEALTHONE STAFFING
RN JOBS Search
Author: Chris DuBois
Date:   July 24, 2008

For more information, check out:
http://healthonestaffing.com/myhealthone/widget

**/


/**
CONFIGURATION PARAMETERS
 */
var pipe_url = 'http://pipes.yahoo.com/healthone/nursejobsv4?';
var r = '';

// Initialization
var resultsPageNum = 1;
var resultsPerPage = 15;
var selectedJob = 0;
var firstListedPage = 1;
var numListedPages = 12;

//if (titleLength==null) var titleLength = 17;

//var isDetailMode = false;

var cache = new Array();
var cacheChunkSize = 45;

var jobList = new Array();
var viewingJobList = new Array();
var jobs;

// Yahoo Pipes initialization
var yp = new Array();
var idx = 0;

// Search Parameters
var Profession = '';
var JobType = '';
var Shift = '';
var Setting = '';
var Specialty = '';
var State = '';

	    
/**
DATA RETRIEVAL
 */
function newSearch () {
    cache = new Array();
    resultsPageNum = 1;
    selectedJob = 0;
    isDetailMode = false;
    getParameters();
    getData();
} 
function getParameters() {
    Profession = document.getElementById('select_profession').value;
	JobType = document.getElementById('select_jobtype').value;
	Shift = document.getElementById('select_shift').value;
	Setting  = document.getElementById('select_setting').value;
	Specialty  = document.getElementById('select_specialty').value;
	State  = document.getElementById('select_state').value;
}
function getData () {
    var callback_obj = "yp[" + idx + "]";
    var url=pipe_url+'_render=json&_run=1';
    
    var from = cache.length;
    var to   = cache.length + cacheChunkSize;
        
    url+='&Profession='+Profession;
	url+='&JobType='+JobType;
	url+='&Shift='+Shift;
	url+='&Setting='+Setting;
	url+='&Specialty='+Specialty;
	url+='&State='+State;
	url+='&from='+from;
	url+='&to='+to;
	url+='&r='+r;
		    

    yp[idx] = new YPipesJobs (url, callback_obj);
    yp[idx].requestJSON ();
    idx++;
}

// The YPipesJobs constructor

function YPipesJobs (ypipes_url, obj_name) {
  this.url = ypipes_url + "&_callback=" + obj_name + ".jsonHandler";
}

// The requestJSON method: it builds the script tag
// that launches our request to the Yahoo! server.

YPipesJobs.prototype.requestJSON = function () {

  // Dynamically create a script tag. This initiates
  // a request to the Yahoo! server.

  var head = document.getElementsByTagName("head").item(0);
  var script = document.createElement ("script");
  script.src = this.url;
  head.appendChild (script);
}

// The jsonHandler method: this is our callback function.
// It's called when the JSON is returned to our browser
// from Yahoo!.
YPipesJobs.prototype.jsonHandler = receiveData;

//
function receiveData(json) {
    cache = cache.concat(json.value.items);
    display();
}

/**
DISPLAY
 */
 
// Display job data.  If currently requested job data doesn't exist in the cache,
// request more using the getData() method.
function display() {
    // Display Loading... message
    setLoading(true);

    if (cache.length==0) {
        display_jobs();
    }
    else if (isDetailMode & (selectedJob+1) > cache.length) {
        getData();
    } 
    else if (!isDetailMode & ((resultsPageNum-1)*resultsPerPage+1) > cache.length) {
        getData();    
    } else {
        // Call function to display HTML for currently selected jobs
        display_jobs();
    }
}

// Display Job helper function.
function display_jobs() {
    
    var total = getTotal(jobs);
    if (total == 0) {
		makeNoResultsMessages();
	}
    else {
        setLoading(false);
		// generate HTML listing the locations and update the page DOM so the user will see the HTML
		var results_header_div = document.getElementById('div_results_header');	
		results_header_div.innerHTML = '<h3 class="BlueText">Search Results:</h3><p>Check the &quot;Add Job&quot; checkbox next to each job you want to apply for.&nbsp;Then click "APPLY TO SELECTED JOBS" at the bottom of the page to submit your selections. </p>';

		var result_items_div = document.getElementById('div_result_items');	
		// Clear results area
		result_items_div.innerHTML = '';
	
		
		var i = 0;
		
		viewingJobList = new Array();
		
		
		for(i=0;i < total; i++) {
				
				// Display the job in the cache at index i if it is on this page.
				// e.g. page 2 = from cache[(2-1)*10-1] to cache[2*10-1] = 
				// from cache[9] to cache[19]
				if (i>=(resultsPageNum-1)*resultsPerPage && 
					i<=resultsPageNum*resultsPerPage-1) {
										
	                var j = new JobInfo(cache[i]);
					
					var jobDetailHTML='<table class="details" border=0 cellpadding=0 cellspacing=0><tr><td colspan="2"><h3><a href="http://www.healthonestaffing.com/MyHealthone/Search/JobDetail.aspx?Job='+j.id+'">'+j.title+'</a></h3></td></tr>';
					jobDetailHTML+='<td class="detailHeader">Setting-Specialty</td><td>'+j.settingspecialty+'</td></tr>';
					jobDetailHTML+='<td class="detailHeader">Duration (weeks)</td><td>'+j.duration+'</td></tr>';
					jobDetailHTML+='<td class="detailHeader">Shift</td><td>'+j.shift+'</td></tr>';
					jobDetailHTML+='<td class="detailHeader">Job Type</td><td>'+j.type+'</td></tr>';
					jobDetailHTML+='<td class="detailHeader">Location</td><td>'+j.city+', '+j.state+'</td></tr>';
					jobDetailHTML+='<td class="detailHeader">Description</td><td>';
					jobDetailHTML+='<img onmouseover="document.body.style.cursor=\'pointer\'" onmouseout="document.body.style.cursor=\'default\'" onclick="javascript:switchVisibility('+j.id+');switchPlusMinus(this);return false" src="plus.gif" border=0>';
					jobDetailHTML+='<div id="div_jobdesc'+j.id+'" class="invisible"><table border=0 cellspacing=0 cellpadding=0>'+j.description+'</table></div></td></tr>';
					jobDetailHTML+='</table>';
					
					// Add this to the list of jobs being viewed.
					viewingJobList.push(j.id);
										
					var thisJobHTML='<div id="div_job'+j.id+'" class="topborder">';
					
					thisJobHTML += '<table border=0 cellpadding=0 cellspacing=0>';
					thisJobHTML += '<tr>';
					thisJobHTML+= '<td class="middle">' + jobDetailHTML + '</td>';
					thisJobHTML+='<td class="right"><input id="chk'+j.id+'" '+makeCheckmark(j.id)+' type="checkbox" onclick="javascript:addRemoveJob('+j.id+');return true"/></td>';
					
					result_items_div.innerHTML += thisJobHTML;				
				}
		}	
		// Make the pager.
		makeResultsPager(total);
		updateApplyNowLink();
		setSelectedJob(selectedJob);
	}
	
}


function setLoading(on) {
	if (on) {
		document.getElementById('loading_span').innerHTML = '&nbsp;Loading...&nbsp;&nbsp;';
	} else {
		document.getElementById('loading_span').innerHTML = '';
	}
}
function setSelectedJob(id) {
	if (id!=0) {
		if (contains(viewingJobList,selectedJob)) {
			var deselectedTD = 'div_job'+selectedJob;
			document.getElementById(deselectedTD).setAttribute('class','');
		    selectedJob=id;
			var selectedTD = 'div_job'+selectedJob;
			document.getElementById(selectedTD).setAttribute('class','selected');
		} else {
		    selectedJob=id;
		}
	}
}

function makeNoResultsMessages() {
    setLoading(false);
		document.getElementById('div_apply').innerHTML ='';
		document.getElementById('div_apply2').innerHTML ='';
		document.getElementById('div_results_header').innerHTML='';
		document.getElementById('div_results_pager').innerHTML='';
			
		document.getElementById('div_status').innerHTML = '<p>Your search did not return any results. Try changing your search parameters.</p>';
	
}

// If the provided job id is in the current list of selected jobs, return ' checked '.  This text is placed
// inside the input tag.  Otherwise return ''.
function makeCheckmark(id) {
	var checkmark = '';
	var isChecked = contains(jobList,id);
	if (isChecked) checkmark=' checked ';
	return checkmark;
}



function makeResultsPager(count) {
        var div = document.getElementById('div_results_pager');
		div.innerHTML = '<b>Pages:</b> ';
		var totalPages = count/resultsPerPage;
		if (totalPages!=Math.floor(totalPages)) totalPages = Math.floor(totalPages)+1;

		// Make sure first listed page is no less than 1.
		firstListedPage=Math.max(1,firstListedPage);
		
		// If the listed pages do not include the first page, show an '...' link at the beginning.  
		// This link decrements resultsPageNum and firstListedPage.
		if (firstListedPage>1)div.innerHTML += '&nbsp;&nbsp;<a href="#" onclick="javascript:resultsPageNum='+(resultsPageNum-1)+';firstListedPage='+(firstListedPage-1)+';display();return false">&laquo; Previous</a>&nbsp;&nbsp;';            

		// For each page, make links to that page.
		for (var k = firstListedPage;k<=Math.min(firstListedPage+numListedPages,totalPages);k++) {
			if (resultsPageNum==k) div.innerHTML += '<b>'+k + '</b> ';
			else div.innerHTML += '<a href="#" onclick="javascript:resultsPageNum='+k+';display();return false">'+k+'</a> ';     
		}
		
		// If the listed pages do not include the last page, show an '...' at the end.
		// This link increments resultsPageNum and firstListedPage.
		if (firstListedPage+numListedPages<totalPages) div.innerHTML += '&nbsp;&nbsp;<a href="#" onclick="javascript:resultsPageNum='+(resultsPageNum+1)+';firstListedPage='+(firstListedPage+1)+';display();return false">Next &raquo;</a> ';     
		
        		
}
function updateApplyNowLink() {
	var url = 'http://www.healthonestaffing.com/myhealthone/Apply/JobSubmission.aspx?JobIDList=';
	url+=jobList.join(',');
	html = '';
	html += '<table border=0 cellpadding=0 cellspacing=0>';
	html += '<tr>';
	html+= '<td class="middle"><a href="'+url+'" id="apply_now_a"><img alt="Apply Now"  onmouseover="NewButtonRollover(this,true)" onmouseout="NewButtonRollover(this,false)" src="apply_jobs_off.gif" border="0" /></a> </td>';
	html += '<td class="right">Add Job';
	html += '</td></tr></table></div>';
	document.getElementById('div_apply').innerHTML = html;
	document.getElementById('div_apply2').innerHTML = html;
	
}
// Called when a job's checkbox is clicked
function addRemoveJob(id) {
	if (contains(jobList,id)) jobList = remove(jobList,id);
	else jobList.push(id);
	updateApplyNowLink(); 
}
function JobInfo(job) {
	this.id = job.JobID;
	this.title = job.JobTitle;
	this.profession = job.Profession;
	this.duration = job.Duration;
	this.type = job.JobType;
	this.openings = job.NumOpenings;
	this.settingspecialty = job.SettingSpecialty;
	this.shift = job.Shift;
	this.city = job.City;
	this.state = job.State;
	this.zip = job.Zip;
	if (job.PublicDescription == null) this.description = "";
	else this.description = job.PublicDescription;
	this.total = job.Total;
	this.link = job.link;
}
function getTotal(jobs) {
    if (cache.length>0) return cache[0].Total;
    else return 0;
}
function getSearchParameters() {
		    Profession = document.getElementById('profession_select').value;
		    JobType = document.getElementById('jobtype_select').value;
		    Setting  = document.getElementById('setting_select').value;
		    Specialty  = document.getElementById('specialty_select').value;
		    State  = document.getElementById('location_select').value;
		    Shift = document.getElementById('shift_select').value;
}
function makeRssLink() {
    var url = pipe_url;
		    url+='JobType='+JobType;
		    url+='&Shift='+Shift;
		    url+='&Setting='+Setting;
		    url+='&Specialty='+Specialty;
		    url+='&State='+State;
		    url+='&r='+r;
    return url+'&_render=rss';
}
function updateRssLink() {
    getSearchParameters();
    document.getElementById('link_get_notified').setAttribute("href",makeRssLink());
}

function contains(a,b) {
	for (var i = 0, length = a.length; i < length; i++)
	  if (a[i] == b) return true;
	return false;
	}
function remove(a,b) {
	var c = new Array();
	for (var i = 0, length = a.length; i < length; i++)
	  if (a[i] != b) c.push(a[i]);
	return c;
	}


// Populate options dropdown given the descriptor.  Once chosen, get 
function makeSpecialtiesDropDown(select_setting) {
  var descriptor = select_setting.value;
  var options = [];
  if (descriptor=='') {
	options = ['-specialty-','Any'];
	}
  if (descriptor=='Acute/MS') {
	options = ['-specialty-','Any','Bariatric/GI','Burn Care Adult','Cancer/Onc: BMT','Cancer/Oncology','Cardiovascular','Diabetes/Endocrine','Float Pool','LTACH','Med/Surg','Med/Surg/Telemetry','Medical','Nephrology','Neurology','Ortho/neuro','Orthopedics','Plastic/Reconstructive','Pulmonary/Resp','Rehabilitation','Surgical/Post Op','Transplant Care','Trauma Acute','Urology/GU'];
  }
  if (descriptor=='Amb/OP') {
	options = ['-specialty-','Any','Cancer/Onc: Rad Rx','Clinic/Office','Day Care/Short Stay','Dialysis','Employee Health','Endoscopy/GI Lab','Infusion Nursing','Lab/phlebotomy','Occup Health','Pain Clinic','School Nursing'];
  }
  if (descriptor=='Crit Care') {
	options = ['-specialty-','Any','Anesthesia','Cath/Vasc Lab','CCU','ED/ER','ED/ER Peds','ED/ER Trauma I','Emerg Transport','ICU','ICU: Burn Care','ICU: CVICU','ICU: Medical','ICU: Neuro','ICU: Surgical','ICU: Trauma','OR','OR: Amb/OP','OR: Circ/scrub','OR: CVOR','PACU/PAR/RR','Urgent Care'];
  }
  if (descriptor=='LTC') {
	options = ['-specialty-','Any','Assisted Living','Foster Care','Residential','Sub Acute/SNF'];
}
  if (descriptor=='Step Down') {
	options = ['-specialty-','Any','Med/surg','Telemetry/PCU','Trauma'];
    }
  if (descriptor=='Other') {
	options = ['-specialty-','Any','Advanced Practice: CNS','Advanced Practice: CRNA','Advanced Practice: NP','Unknown','Administration','Case Management','Clinical Instructor','Corrections/Prison','CQI','ET/Wound/Skin','Home Health','Hospice','Infection Control','IV Therapy','Research','Specialty Not Listed','Staff Development','Utilization Review'];
	}
  if (descriptor=='Pediatrics') {
	options = ['-specialty-','Any','NICU','NICU II','NICU level III','NICU level IV/ECMO','Nursery','Peds Acute','Peds Burn Care','Peds Clinic','Peds Hem/Onc','Peds LTC','Peds Transport','PICU'];
	 }
  if (descriptor=='Psych/CD') {
	options = ['-specialty-','Any','ChemDep/ETOH Rx','Child/Adol','Eating Disorders','Geriatric','Psych'];
  }
  if (descriptor=='Womens Svcs') {
	options = ['-specialty-','Any','Antepartum','GYN','L&D','LDRP','Mother/Baby','Other','Post Partum','Womens Clinic'];
	  }
  
  var select_specialty = document.getElementById('select_specialty');
  select_specialty.innerHTML='';
  for (var i = 0; i < options.length; i++) {
	if (i<2) select_specialty.options[i] = new Option(options[i],""); // the first two options have null value
	else select_specialty.options[i]= new Option(options[i],options[i]);  
  }
  select_specialty.removeAttribute("disabled");
  
  // If -setting- has been selected, empty out specialty drop down list and disable it.
  if (descriptor=='') {
	select_specialty.setAttribute("disabled",true);
  }
}

function makeDropDowns(select_x) {
  var options = [];
  var current = '';
  switch (select_x.getAttribute("id")) {
//    case "select_profession":
//        options = ['-profession-','Any','RN','LPN/LVN','OR Tech','Other'];
//        current = Profession;
//        break;
    case "select_jobtype":
        options = ['-job type-','Any','Travel','Per Diem','Local Contract','Perm'];
        current = JobType;
        break;
    case "select_setting":
        options = ['-setting-','Any','Acute/MS','Amb/OP','Crit Care','Step Down','LTC','Other','Pediatrics','Psych/CD','Womens Svcs'];
        current = Setting;
        break;
    case "select_specialty":
        options = ['-specialty-'];
        current = Setting;
        break;
    case "select_location":
        options = ['-location-','Any','AL','AK','AZ','AR','CA','CO','CT','DE','DC','FL','GA','HI','ID','IL','IN','IA','KS','KY','LA','ME','MD','MA','MI','MN','MS','MO','MT','NE','NV','NH','NJ','NM','NY','NC','ND','OH','OK','OR','PA','RI','SC','SD','TN','TX','UT','VT','VA','WA','WV','WI','WY','Outside United States'];
        current = State;
        break;
    case "select_shift":
        options = ['-shift-','Any','Day','Night','Eves','Variable','Other'];
        current = Shift;
        break;
    default:
        break;
  }
  select_x.innerHTML='';
  for (var i = 0; i < options.length; i++) {
	if (i<2) select_x.options[i] = new Option(options[i],""); // the first two options have null value
	else select_x.options[i]= new Option(options[i],options[i]); 
	// if the current parameter is empty, select the first option.
	// otherwise select the option matching the current parameter
    if (current=='')select_x.options[0].selected = true;
    else if (current==options[i]) select_x.options[i].selected = true;
  }
 
}
// Display Helper Functions

function showStatus(status) {
  document.getElementById('div_status').innerHTML = status;
}
function switchVisibility(ID) {
	var d = document.getElementById("div_jobdesc"+ID.toString()+"");
	if (d.getAttribute("class")=="invisible") {
	    d.setAttribute("class","visible");
	}
	else if (d.getAttribute("className")=="invisible") {
	    d.setAttribute("className","visible");
	}
	else if (d.getAttribute("class")=="visible") {
	    d.setAttribute("class","invisible");
	}
	else if (d.getAttribute("className")=="visible") {
	    d.setAttribute("className","invisible");
	}
	else {
	}
}
function NewButtonRollover(img, on)
{
    var src = img.getAttribute("src");
    var alt = img.getAttribute("alt");
    if(on)
    {
        var hover = src.substring(0,src.length - 8) + "_roll.gif";
        img.setAttribute("src",hover);
        img.setAttribute("alt",alt);
    }
    else
    {
        var hover = src.substring(0,src.length - 9) + "_off.gif";
        img.setAttribute("src",hover);
        img.setAttribute("alt",alt);
    }
}

function switchPlusMinus(img)
{
    var src = img.getAttribute("src");
    var f = src.substring(src.length - 8,src.length);
    if(f=="plus.gif") img.setAttribute("src",src.substring(0,src.length - 8) + "minus.gif");
    else img.setAttribute("src",src.substring(0,src.length - 9) + "plus.gif");
}		
// Querystring functions
function getQueryString() {
	// get the current URL
	 var url = window.location.toString();
	 //get the parameters
	 url.match(/\?(.+)$/);
	 var params = RegExp.$1;
	 // split up the query string and store in an
	 // associative array
	 var params = params.split("&");
	 var queryStringList = {};
	 
	 for(var i=0;i<params.length;i++)
	 {
		 var tmp = params[i].split("=");
		 queryStringList[tmp[0]] = unescape(tmp[1]);
	 }
	 if (params[0]!="") return queryStringList;
	 else return null;
}
function selectFromQueryString() {
	var qs = getQueryString();
	if (qs!=null) {
	    for (q in qs) {
		    // the querystrings must be profession
		    var controlName = 'select_'+q.toString().toLocaleLowerCase();
		    var control = document.getElementById(controlName);
		    if (control!=null) {
		        for (var i=0; i<control.options.length;i++) {
		           var s = qs[q];
			        var t = control.options[i].getAttribute("value");
			        if (isSubstring(s,t)) {
			            control.options.selectedIndex=i;
			            i=control.options.length;
			        }
		        }
		    }
	    }      
	    newSearch();
	}
}
function isSubstring(a,b) {
	return (b.toString().search(a.toString())!=-1);
}