/**
HEALTHONE STAFFING
RN JOBS WIDGET
Author: Chris DuBois
Date:   May 26, 2008

For more information, check out:
http://healthonestaffing.com/myhealthone/widget

**/


/**
CONFIGURATION PARAMETERS
 */
var pipe_url = 'http://pipes.yahoo.com/healthone/nursejobsv4?';

// Initialization
var resultsPageNum = 1;
var resultsPerPage = 10;
var selectedJob = 0;

if (titleLength==null) var titleLength = 17;

var isDetailMode = false;

var cache = new Array();
var cacheChunkSize = 30;

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;
    isDetailMode = false;
    selectedJob = 0;
    getData();
} 

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+='&r='+r;
	url+='&from='+from;
	url+='&to='+to;
		    

    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
    showTab('loading');

    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 if (!isDetailMode) {
		showTab('jobs');

		var div_content = document.getElementById('div_content');	
		div_content.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="job" border=0 cellpadding=0 cellspacing=0>';
					jobDetailHTML+='<tr>';
					jobDetailHTML+='<td class="plus"><img  onmouseover="document.body.style.cursor=\'pointer\'" onmouseout="document.body.style.cursor=\'default\'" onclick="javascript:document.body.style.cursor=\'default\';selectedJob='+i+';isDetailMode=true;display();return false" src="http://healthonestaffing.com/gadgets/plus.gif" border=0></td>';
					jobDetailHTML+='<td class="title"><a href="#"  onmouseover="document.body.style.cursor=\'pointer\'" onmouseout="document.body.style.cursor=\'default\'" onclick="javascript:document.body.style.cursor=\'default\';selectedJob='+i+';isDetailMode=true;display();return false">'+stripTitle(j.title,titleLength)+'</a></td>';
					jobDetailHTML+='<td class="state">'+j.state+'</td>';
					jobDetailHTML+='<td class="checkbox"><input id="chk'+j.id+'" '+makeCheckmark(j.id)+' type="checkbox" onclick="javascript:addRemoveJob('+j.id+');return true"/></td>';
					jobDetailHTML+='</tr>';
					
					var thisJobHTML='<div id="div_job'+j.id+'" >'+jobDetailHTML+'</div>';
					div_content.innerHTML+=thisJobHTML;
					// Add this to the list of jobs being viewed.
					viewingJobList.push(j.id);					
				}
		}	
		// Make the pager.
		document.getElementById('div_controls_left').innerHTML = '';
	    document.getElementById('div_controls_right').innerHTML = '<a id="a_apply" href="">Apply Now &raquo;</a>';
		makeResultsPager(total, false);
		updateApplyNowLink();
		setSelectedJob(selectedJob);
	}
	else {
	    var i = selectedJob;
        makeResultsPager(total,true);
        
        
	    var j = new JobInfo(cache[i]);
	    dh =   document.getElementById('div_content');
	    var html = '<div id="div_detail"><table border=0 cellpadding=0 cellspacing=0>';
	    html += '<tr><td class="minus"><img onmouseover="document.body.style.cursor=\'pointer\'" onmouseout="document.body.style.cursor=\'default\'" onclick="javascript:resultsPageNum = Math.ceil((selectedJob+1)/resultsPerPage);isDetailMode=false;display();return false" src="http://healthonestaffing.com/gadgets/minus.gif" border=0>';
	    html += '</td><td class="h1header" colspan=2><a href="'+j.link+'">'+j.title+'</a></td><td></td></tr>';
	    html += '<tr><td></td><td class="h1left">Setting</td><td class="h1right">'+fixSettingSpecialty(j.settingspecialty)+'</td><td></td></tr>';
	    html += '<tr><td></td><td class="h1left">Openings</td><td class="h1right">'+j.openings+'</td><td></td></tr>';
	    html += '<tr><td></td><td class="h1left">Shift</td><td class="h1right">'+j.shift+'</td><td></td></tr>';
	    html += '<tr><td></td><td class="h1left">Job Type</td><td class="h1right">'+j.type+'</td><td></td></tr>';
	    html += '<tr><td></td><td class="h1left">Location</td><td class="h1right">'+j.city+', '+j.state+'</td><td></td></tr>';
	    html += '<tr><td></td><td class="h1left">Description</td><td class="h1right">'+stripTitle(j.description,60)+'</td><td></td></tr>';
	    html += '</table>';
	    //html += '<p class="p_learn_more"><a href="http://www.healthonestaffing.com/">Learn more about nursing opportunities with HealthOne Staffing.</a></p>';
        html += '<p class="p_add_job">Add this job: <input id="chk'+j.id+'" '+makeCheckmark(j.id)+' type="checkbox" onclick="javascript:addRemoveJob('+j.id+');return true"/></p>';
        html += '</div>';
	    dh.innerHTML = html;
    	
    	
	    document.getElementById('div_controls_left').innerHTML = '<a href="irr" onclick="javascript:resultsPageNum = Math.ceil((selectedJob+1)/resultsPerPage);isDetailMode=false;display();return false" >&laquo; Back</a>';

	}
}

// 
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() {
		document.getElementById('div_pager').innerHTML='';
		var html = '<p>Your search did not return any results. Try modifying your search using the Advanced tab above.</p>';
		html += '<p>Do you use RSS feeds?  You can hear about job opportunities that match your selected interests.</p>';
		html += '<p><a id="link_get_notified" href="'+makeRssLink()+'"><img src="http://www.feedburner.com/fb/images/pub/feed-icon16x16.png" alt="" style="vertical-align:middle;border:0;padding-right:2px;"/>Get Job Notifications.</a></p>';

		document.getElementById('div_content').innerHTML = html;
		document.getElementById('div_controls_left').innerHTML = '';
	    document.getElementById('div_controls_right').innerHTML = '';
		
}

// 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 updateApplyNowLink() {
	var url = 'http://www.healthonestaffing.com/myhealthone/Apply/JobSubmission.aspx?JobIDList=';
	url+=jobList.join(',');
	url+='&r='+r;
	document.getElementById('a_apply').setAttribute("href",url);
}
function switchDetailMode() {
    // if it's inDetailMode, make resultsPageNum equal to what page current selectedJob is
    if (isDetailMode) {
        resultsPageNum = Math.ceil(selectedJob/resultsPerPage);
    }
    // otherwise, make selectedJob equal to the first job on the current page
    else {
        selectedJob = (resultsPageNum-1)*resultsPerPage+1;
    }
    // switch the boolean isDetailMode
    isDetailMode = (!isDetailMode);
    
}
function makeResultsPager(count, isDetails) {
        var div = document.getElementById('div_pager');
		var html = '<table><tr><td>';
        var thisMin = (resultsPageNum-1) * resultsPerPage+1;
        var thisMax = resultsPageNum * resultsPerPage;
        if (isDetails) html += (selectedJob+1)+' of '+count;
        else html += thisMin +'-'+Math.min(thisMax,count) + ' of '+count;
		var totalPages = count/resultsPerPage;
		if (totalPages!=Math.floor(totalPages)) totalPages = Math.floor(totalPages)+1;
		html+='</td><td id="td_pager_buttons">';
		if (isDetails) {
		    if (selectedJob>0)html += '<a href="#" onclick="javascript:selectedJob-=1;display();return false">&laquo; Previous</a>&nbsp;';            
            //else html += '&laquo;&nbsp;';         
		    if (selectedJob<count-1) html += '&nbsp;<a href="#" onclick="javascript:selectedJob+=1;display();return false">Next &raquo;</a> ';     
		    //else html += '&raquo;&nbsp;'; 
		} else {
		    if (resultsPageNum>1)html += '<a href="#" onclick="javascript:resultsPageNum-=1;display();return false">&laquo; Previous</a>&nbsp;';            
            //else html += '&laquo;&nbsp;';         
		    if (resultsPageNum<totalPages) html += '&nbsp;<a href="#" onclick="javascript:resultsPageNum+=1;display();return false">Next &raquo;</a> ';     
		    //else html += '&raquo;&nbsp;';   
		}
        
        
        html+='</td></tr></table>';
        div.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('select_profession').value;
		    JobType = document.getElementById('select_jobtype').value;
		    Setting  = document.getElementById('select_setting').value;
		    Specialty  = document.getElementById('select_specialty').value;
		    State  = document.getElementById('select_location').value;
		    Shift = document.getElementById('select_shift').value;
}
function makeRssLink() {
    var url = pipe_url;
//		    url+='Profession='+Profession;
		    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 showTab(name) {
    switch (name) {
        case 'jobs':
            document.getElementById('a_title').setAttribute("class","selected");
            document.getElementById('a_advanced').setAttribute("class","deselected");
            document.getElementById('a_help').setAttribute("class","deselected");
            break;
        case 'advanced':
            var html = 'What kind of job do you want?<br/>';
            html+='<table><tr><td> <select id="select_jobtype" onchange="updateRssLink()"> </select></td></tr><tr><td> <select id="select_setting" onchange="makeSpecialtiesDropDown(this);updateRssLink()""></select></td></tr> <tr> <td>  <select id="select_specialty"  onchange="updateRssLink()" disabled></td></tr> <tr><td> <select id="select_location" onchange="updateRssLink()"> </select> </td></tr><tr> <td> <select id="select_shift" onchange="updateRssLink()"></select></td></tr></table><p></p><table><tr><td></td><td><a href="#" id="link_get_notified" class="a_controls" onclick="getSearchParameters();newSearch();return false">Search Jobs &raquo;</a><p></p></td></tr><tr><td><a id="link_get_notified_img" href="'+makeRssLink()+'"><img src="http://www.feedburner.com/fb/images/pub/feed-icon16x16.png" alt="" style="vertical-align:middle;border:0;padding-right:2px;"/></a></td><td><a href="'+makeRssLink()+'">Get Job Notifications</a></td></tr></table>';
            document.getElementById('div_pager').innerHTML='&nbsp;';
            document.getElementById('div_content').innerHTML = html;
            document.getElementById('a_title').setAttribute("class","deselected");
            document.getElementById('a_advanced').setAttribute("class","selected");
            document.getElementById('a_help').setAttribute("class","deselected");
            document.getElementById('div_controls_right').innerHTML = '';
            document.getElementById('div_controls_left').innerHTML = '';
            
//            makeDropDowns(document.getElementById('select_profession'));
            makeDropDowns(document.getElementById('select_jobtype'));
            makeDropDowns(document.getElementById('select_setting'));
            makeDropDowns(document.getElementById('select_specialty'));
            makeDropDowns(document.getElementById('select_location'));
            makeDropDowns(document.getElementById('select_shift'));
            break;
        case 'help':
            document.getElementById('a_title').setAttribute("class","deselected");
            document.getElementById('a_advanced').setAttribute("class","deselected");
            document.getElementById('a_help').setAttribute("class","selected");
            document.getElementById('div_pager').innerHTML='&nbsp;';
            document.getElementById('div_content').innerHTML = '<p><b>Find RN Jobs</b><br/> In the "RN Jobs" tab, you can page through your job results using the &laquo; and &raquo; buttons near the top of the widget.  You can change what kinds of jobs are shown in the "Search Jobs" tab.</p><p>Want to add the RN Jobs widget to your blog or website?  Check out the <a href="http://healthonestaffing.com">HealthOne Staffing</a> <a href="http://healthonestaffing.com/myhealthone/widget">Blogger Referral Program.</a></p>';
           
            document.getElementById('div_controls_right').innerHTML = '';
            document.getElementById('div_controls_left').innerHTML = ''; 
            break;
        case 'loading':
            document.getElementById('div_pager').innerHTML='';
            document.getElementById('div_content').innerHTML = 'Job data loading... Please wait.';
            break;
        default:
        break;
    }
    
}
function fixSettingSpecialty(s) {
    var t = s.toString().split('-');
    return t[0]+'- '+t[1];
}

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;
	}
function stripTitle(a,size) {
    if (a.length>size-3) {
        a=a.substring(0,size);
        a+='...';
    }
    return a;
}

// 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;
  }
 
}



function buildBadge() {
    var html = '<div id="div_app">';
    html+='<div id="div_menu">';
    html+='<a id="a_title" href="#" class="selected"  onclick="javascript:showTab(\'jobs\');newSearch();return false">RN Jobs</a> ';
    html+='<a id="a_advanced" href="#" class="deselected"  onclick="javascript:showTab(\'advanced\');return false">Search Jobs</a> ';
    html+='<a id="a_help" href="#" class="deselected"  onclick="javascript:showTab(\'help\');return false">?</a>';
    html+='</div>';
    html+='<div id="div_pager">  </div>  <div id="div_content">  </div>';
    html+='<div id="div_controls"><div id="div_controls_left"><a id="a_control_left" href=""></a></div><div id="div_controls_right"><a id="a_apply" href="">Apply Now &raquo;</a></div>  </div>';
    html+='<div id="div_footer"><a href="http://www.healthonestaffing.com/myhealthone/Search/Jobs.aspx">Nursing Jobs</a> by <a href="http://healthonestaffing.com/">HealthOne Staffing</a>  </div>';
    html+='</div>';
    document.getElementById('div_h1badge').innerHTML=html;
}
buildBadge();
newSearch();
