﻿function getStyleObject(objectId) 
{
    // cross-browser function to get an object's style object given its id
    if(document.getElementById && document.getElementById(objectId)) {
	// W3C DOM
	return document.getElementById(objectId).style;
    } else if (document.all && document.all(objectId)) {
	// MSIE 4 DOM
	return document.all(objectId).style;
    } else if (document.layers && document.layers[objectId]) {
	// NN 4 DOM.. note: this won't find nested layers
	return document.layers[objectId];
    } else {
	return false;
    }
} // getStyleObject

function changeObjectVisibility(objectId, newVisibility) 
{
    // get a reference to the cross-browser style object and make sure the object exists
    var styleObject = getStyleObject(objectId);
    if(styleObject) {
	styleObject.visibility = newVisibility;
	return true;
    } else {
	// we couldn't find the object, so we can't change its visibility
	return false;
    }
} // changeObjectVisibility
	
function hideCurrentQuickBarPopup() 
{     
    // note: we've stored the currently-visible popup on the global object window.currentlyVisiblePopup
    if(window.currentlyVisiblePopup) 
	 {
		changeObjectVisibility(window.currentlyVisiblePopup, 'hidden');
	
		var layername = window.currentlyVisiblePopup + 'Anchor';
		var curObj = document.getElementById(layername);
		curObj.style.backgroundImage = "none";
		
		//we need to show drop down lists in IE6.0 and earlier that we hid earlier
        if(isIE6OrEarlier())  
            showAllDropDowns();
	
		window.currentlyVisiblePopup = false;
    }
} // hideCurrentPopup	
	

function isIE6OrEarlier()
{
    var userAgent = navigator.userAgent;
     var ieIndex = userAgent.indexOf("MSIE");
     if (ieIndex > 0) 
     {
         ieVer = userAgent.substring(ieIndex + 5, ieIndex + 8);
         if (ieVer <= 6.0)
            return true;
     }
     
   return false;
}     	
	
function showQuickBarPopup(targetObjectId, eventObj) 
{
    document.onclick = hideCurrentQuickBarPopup;
      
	 if(window.currentlyVisiblePopup == targetObjectId)
	 {
	 	//the user clicked on the opener again, and it is already opened
		//in this case we close the window
		hideCurrentQuickBarPopup();
		return;
	 }
	 
	 if(eventObj) 
	 {
			// hide any currently-visible popups
			hideCurrentQuickBarPopup();
			// stop event from bubbling up any farther
			eventObj.cancelBubble = true;
			// and make it visible
			if( changeObjectVisibility(targetObjectId, 'visible') ) 
			{
	    		// if we successfully showed the popup
	    		// store its Id on a globally-accessible object
	    		window.currentlyVisiblePopup = targetObjectId;
	    		
	    		//we need to start by hiding drop down lists in IE6.0 and earlier
                if(isIE6OrEarlier())  
                hideAllDropDowns();

				var obj = getStyleObject(targetObjectId);
    		  if(obj) 
			  {
				  if(navigator.userAgent.indexOf('Firefox')==-1)
				  {
	    		  		obj.top =  25 + 'px';
				  }
				  else
				  {
	    		  		obj.top =  30 + 'px';
				  }
			  }
			  
				var layername = targetObjectId + 'Anchor';
				var curObj = document.getElementById(layername);
				curObj.style.backgroundImage = "url(http://img.icbdr.com/images/JS/Widgets/selbg.gif)";
				
	    		return true;
			} 
			else 
			{
	    		// we couldn't show the popup, boo hoo!
	    		return false;
			}
    } 
	 else 
	 {
			// there was no event object, so we won't be able to position anything, so give up
			return false;
    }
} // showPopup
	
	
function switchToUser(obj)
{
   if(obj.value == 'nurse in 30339' && (obj.style.color == 'gray' || obj.style.color == ''))
	{
		obj.value = '';
		obj.style.color = 'black';
	}
	
	if(obj.value != 'nurse in 30339' && (obj.style.color == 'gray' || obj.style.color == ''))
	{
	    obj.style.color = 'black';
	}	
}	

function checkIfBlank(obj)
{
   if(obj.value == '')
	{
		obj.value = 'nurse in 30339';
		obj.style.color = 'gray';
	}
}

function validateQuickBarSearch(theForm)
{

    if( (theForm.s_keyinloc.value == '') || (theForm.s_keyinloc.value == 'nurse in 30339' && (theForm.s_keyinloc.style.color == 'gray' || theForm.s_keyinloc.style.color == '')) )
    {
        return false;
    }
}

function hideAllDropDowns()
{
    var collS = document.getElementsByTagName("SELECT");
    for (var i=0; i<collS.length; i++)
        collS[i].style.visibility = 'hidden';
}

function showAllDropDowns()
{
    var collS = document.getElementsByTagName("SELECT");
    for (var i=0; i<collS.length; i++)
        collS[i].style.visibility = 'visible';
}


/* AJAX FUNCTIONS*/
var g_CBFeedManager = null;
var g_curpage = '';
var g_CBJobRecommendationsFeed = 'gadget/jobrecommendationsgadgetxml.aspx';    
var g_CBXMLDoc = null;
var g_jobrecDivId = 'QBRecommendedJobs';
var g_ErrorFlag = false;
var g_JobRecsLoadedForPage = false;
var g_spinnerRunning = false;

//messages
var L_IDENTIFY_TEXT		    = "We couldn't find your user profile";
var L_CANTCONNECT_TEXT		= "Error retrieving data.<br/>Please check your connection";
var L_UNEXPECTEDERR_TEXT	= "An unexpected Error has occured. Please try later";
var ERR_XMLNORESULTS		= "No jobs were found.<br/>Please try changing your <a href=jobseeker/resumes/jobrecommendationspref.aspx>current location</a>."

SetupAjaxPath();
InitializeFeedManager();

function SetupAjaxPath()
{
    //setup correct path
    if(typeof ajaxRelativePrefix != 'undefined')
    {
	    // prefix page with relative path prefix var that was inserted by MatrixPage - need to trim off AJAX part
	    var quickbarPrefix = ajaxRelativePrefix.replace('AJAX', 'rtq');
	    g_CBJobRecommendationsFeed = quickbarPrefix + g_CBJobRecommendationsFeed;
    }
    else
    {
        //try careerbuilder.com	    
        g_CBJobRecommendationsFeed = 'http://www.careerbuilder.com/rtq' + g_CBJobRecommendationsFeed;
    }
    
}

function InitializeFeedManager()
{
    try
    {
        g_CBFeedManager=new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch(e)
    {
        try
        {
            g_CBFeedManager=new ActiveXObject("Microsoft.XMLHTTP");
        }
        catch(oc)
        {
            g_CBFeedManager=null;
        }
    }

    if(!g_CBFeedManager && typeof XMLHttpRequest!="undefined")
    {
        g_CBFeedManager = new XMLHttpRequest();
    }
} 


function QuickBar_GetJobRecommendations(did, noofjobs, ipath, lrcode, curpage)
{
    //no need to call ajax again if we have the data already loaded on the page
    if(g_JobRecsLoadedForPage)
        return;
         
    if(!g_ErrorFlag)    
        displaySpinner();
        
    g_curpage = curpage;     
       
	g_CBFeedManager.onreadystatechange = processCallBack;
    g_CBFeedManager.open("GET", g_CBJobRecommendationsFeed+"?dossierdid="+ did + "&limit=" + noofjobs + "&ipath=" + ipath + "&lrcode=" + lrcode + " &gadgetRandom=" + getRandom(), true); 
    g_CBFeedManager.send(null);
}


function processCallBack()
{
    g_ErrorFlag = false; 
    var errMsg = "";
    
    if (g_CBFeedManager.readyState == 4)
    {
        // only if "OK"
            if (g_CBFeedManager.status == 200)
            {	
                if(g_CBFeedManager.responseText.substr(0,3) == L_IDENTIFY_TEXT) //we can't find the dossier
		        {
			        errMsg = L_IDENTIFY_TEXT;
			        g_ErrorFlag = true;
			        afterXMLLoad(errMsg);
		        }
                else
		        {
			        if (window.ActiveXObject)
			        {
			            //Internet Explorer
                        g_CBXMLDoc = new ActiveXObject("Msxml2.DOMDocument");
                        g_CBXMLDoc.load(g_CBFeedManager.responseXML);
                    }
			        else if(document.implementation && document.implementation.createDocument)
			        {
			            //Firefox And Mozilla
			            var oParser = new DOMParser;
			            g_CBXMLDoc = oParser.parseFromString(g_CBFeedManager.responseText, "text/xml");
                    } 
                    
			        var metaNode = g_CBXMLDoc.getElementsByTagName("metadata")[0];

			        //get the location that appears in the XML document - and save it!
			        var searchlocation = '';
			        if(metaNode.getElementsByTagName("searchlocation")[0].firstChild != null)
        			    searchlocation = metaNode.getElementsByTagName("searchlocation")[0].firstChild.nodeValue;  

			        var message = "";
			        //before setting up data, lets make sure everything is ok, i.e. our XML doc isnt reporting any errors
        		    if(metaNode.getElementsByTagName("message")[0].firstChild != null)
				        message = metaNode.getElementsByTagName("message")[0].firstChild.nodeValue;

			        if(message.indexOf(ERR_XMLNORESULTS) >= 0)	
			        {
				        //no results!
				        errMsg = ERR_XMLNORESULTS;
				        g_ErrorFlag = true;
			        }
			        else
			        {     

				        //get the last updated date from the XML document
				        //if(metaNode.getElementsByTagName("pubdate")[0].firstChild != null)
					        //g_lastUpdated = metaNode.getElementsByTagName("pubdate")[0].firstChild.nodeValue;

				        //get the dossierdid from the XML document
				        //if(metaNode.getElementsByTagName("dossierdid")[0].firstChild != null)
					        //g_dossierDID = metaNode.getElementsByTagName("dossierdid")[0].firstChild.nodeValue;		
   
				        //we're good up until now
				        errMsg = setupJRData(); //there might have been an error here - if so, the g_ErrorFlag should have been set
        				
			        }
			        afterXMLLoad(errMsg, "");
		        }	
            }
            else
            {
		        g_ErrorFlag = true;
		        errMsg = L_CANTCONNECT_TEXT;
		        afterXMLLoad(errMsg);
            }
     }
        
}

function setupJRData()
{
    var metaNode = g_CBXMLDoc.getElementsByTagName("metadata")[0];
    
    //get the location that appears in the XML document - and save it!
	var searchlocation = '';
	if(metaNode.getElementsByTagName("searchlocation")[0].firstChild != null)
        searchlocation = metaNode.getElementsByTagName("searchlocation")[0].firstChild.nodeValue; 

	var root = g_CBXMLDoc.getElementsByTagName("results")[0];
	var items = root.getElementsByTagName("job");

	g_totalCount = items.length;

  	//no jobs found for this location for this user
	if(g_totalCount == 0)
	{
		//no results!
		g_ErrorFlag = true;
		return ERR_XMLNORESULTS;
	}
	
    //stop spinner
    stopSpinner();	
	
	var tblDIV = document.getElementById(g_jobrecDivId);

	var TBL = null;
	TBL = document.createElement("TABLE");
	TBL.className = "quickbarjobsresults";
	TBL.id = "tblQuickBarRecommendedJobs";
	
	var TBODY = null;
	TBODY = document.createElement("TBODY");

	var TR = null;
	var TD = null;
	var link = null;
	var STRONG = null;
	var SPAN = null;
	var BR = null;
	
	//first make header with location
	var divJRHeader = document.getElementById('QBJRLocation');
	divJRHeader.appendChild(document.createTextNode(searchlocation + " "));
	
	//TR = document.createElement("TR");
    //TD = document.createElement("TD");
    //TD.className = "quickbarJRLocation";
    //TD.appendChild(document.createTextNode(searchlocation + " "));
    
    changeLink = document.createElement("a");
    changeLink.appendChild(document.createTextNode("[ change ]"));
    changeLink.href = '/jobseeker/resumes/jobrecommendationspref.aspx?returnURL=' + g_curpage;
    changeLink.title = 'Change Location for Recommended Jobs';
    
    divJRHeader.appendChild(changeLink);
    
    divJRHeader.style.borderBottomWidth = '1px';
    divJRHeader.style.borderBottomStyle = 'solid';
    divJRHeader.style.borderBottomColor = '#acb6d3';
    
    //TD.appendChild(changeLink);
    //TR.appendChild(TD);
    //TBODY.appendChild(TR);
    
	for (var i = 0 ; i < g_totalCount; i++) 
	{
		var item = items[i];

		var title = "";
		var company = "";
		var url = "";
		var dateposted = "";

		if(item.getElementsByTagName("title")[0].hasChildNodes())
			title = item.getElementsByTagName("title")[0].firstChild.nodeValue;			

		if(item.getElementsByTagName("company")[0].hasChildNodes())	
			company = item.getElementsByTagName("company")[0].firstChild.nodeValue;
			
		if(company == "")
		  company = "<private>";	

		if(item.getElementsByTagName("jobdetailsurl")[0].hasChildNodes())
			url = item.getElementsByTagName("jobdetailsurl")[0].firstChild.nodeValue;
			
		if(item.getElementsByTagName("dateposted")[0].hasChildNodes())
			dateposted = item.getElementsByTagName("dateposted")[0].firstChild.nodeValue;			
				
        TR = document.createElement("TR");
        TD = document.createElement("TD");
        
        if(i%2 == 0)
           TD.className = "title backgr";
        else
           TD.className = "title";
        
        
        STRONG = document.createElement("strong");
        
        //SPAN = document.createElement("span");
        //SPAN.className = "company";
        //SPAN.appendChild(document.createTextNode(" (" + company + ")" ));
        
        link = document.createElement("a");
        link.title = "Job posted on: " + getDateShortFormattedAndLongTime(dateposted);
        link.appendChild(document.createTextNode(title));
        
        //link.appendChild(SPAN);
        link.href = url;
        
        TD.appendChild(STRONG);
        TD.appendChild(link);
        
        BR = document.createElement("BR");
        TD.appendChild(BR);
        
        SPAN = document.createElement("span");
        SPAN.className = "company";
        SPAN.appendChild(document.createTextNode(company));
    
        TD.appendChild(SPAN);
        
        TR.appendChild(TD);
        TBODY.appendChild(TR);
        
	}
	
	TBL.appendChild(TBODY);
	tblDIV.appendChild(TBL);
	
	
	//now attach see all recommended jobs list to bottom of list
	var divJRFooter = document.getElementById('QBJRShowAll');
	Link = document.createElement("a");
    Link.appendChild(document.createTextNode("See All Recommended Jobs"));
    Link.href = '/jobseeker/resumes/mynewjobsrecommendationsorganized.aspx?ipath=JEYQ';
    Link.title = 'See All Recommended Jobs';
    divJRFooter.appendChild(Link);
	
	return "";
}

function afterXMLLoad(errMsg)
{
   if(g_ErrorFlag == false)
   {	
        //everything ok
        g_JobRecsLoadedForPage = true;  
   }
   else
   {
       	//stop spinner
        stopSpinner();
	//can't load job screen, since we are having an error.
        //lets display the error message
        oDIV = document.getElementById(g_jobrecDivId);
        oTBL = document.createElement("TABLE");
        oTBL.className = "quickbarjobsresults";
	    oTBL.id = "tblQuickBarRecommendedJobs";
        oTBODY = document.createElement("TBODY");
	    oTR = document.createElement('TR');
	    oTD = document.createElement('TD');
        oTD.innerHTML = "<div style='width:220px; height: 40px; text-align:center; padding-left:45px; padding-top: 60px;'>"+ errMsg +"</div>";
        oTR.appendChild(oTD);
        oTBODY.appendChild(oTR);
        oTBL.appendChild(oTBODY);
        oDIV.appendChild(oTBL);
           
   }
}


function displaySpinner()
{
    if(g_spinnerRunning)
        return;

    oDIV = document.getElementById(g_jobrecDivId);
    oTBL = document.createElement("TABLE");
    oTBL.className = "quickbarjobsresults";
	oTBL.id = "tblQuickBarRecommendedJobs";
    oTBODY = document.createElement("TBODY");
	oTR = document.createElement('TR');
	oTD = document.createElement('TD');
	oTD.id = "spinner";
    oTD.innerHTML = "<div style='width:220px; height: 40px; text-align:center; padding-left:60px; padding-top: 65px;'><img src=\"http://img.icbdr.com/images/js/widgets/loading.gif\" border=\"0\"><br/>Loading Your Job Recommendations...</div>";
    oTR.appendChild(oTD);
    oTBODY.appendChild(oTR);
    oTBL.appendChild(oTBODY);
    oDIV.appendChild(oTBL);
    
    g_spinnerRunning = true;   
}

function stopSpinner()
{  
    oDIV = document.getElementById(g_jobrecDivId);
    oDIV.innerHTML = ''; 
    
    g_spinnerRunning = false;
 } 


function getRandom()
{
	var nowTime = "";
	var thisdate = new Date();
	nowTime = thisdate.getTime();
	return nowTime;
}

function getDateShortFormattedAndLongTime(rawDate)
{
  //Day, Month Dayno hh:mm

 if(rawDate == "")
      return "";

 var weekday=new Array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
 var months=new Array("Jan","Feb","Mar","Apr","May","Jun","Jul", "Aug", "Sep", "Oct", "Nov", "Dec"); 

 var arrDateTime = rawDate.split("T");
 var arrDate = arrDateTime[0].split("-");
   var arrTime = arrDateTime[1].split(":");
 var myDate = new Date();
        myDate.setFullYear (parseInt(arrDate[0], 10),parseInt(arrDate[1], 10)-1,parseInt(arrDate[2], 10));
 
 var formattedDate = weekday[myDate.getDay()] + " " + months[myDate.getMonth()] + " " + myDate.getDate();
 var formattedTime = arrTime[0] + ":" + arrTime[1] + " EST"; 

 return formattedDate + ", " + formattedTime;
}






