////////////////////////////////////////////////////////////////////////////////
// GLOBALS
////////////////////////////////////////////////////////////////////////////////

// JavsScript debugging level.
//  0 = Production mode, don't debug
//  1 = Only show errors
//  2 = Show every call in an alert (you may see a *lot* of alerts)
var g_jsDebugLevel = 0

// Used by document creator page to know if a resume has already been created
var g_useExistingResume = false

// Used by document creator page to know if it is being used by a one-page job app
var g_onePageJobApp = false

// When the user presses enter, click this button
var g_defaultButtonId = ''

// Used to prevent multiple form submits
var g_isFormSubmitted = false

////////////////////////////////////////////////////////////////////////////////
// MISCELLANEOUS
////////////////////////////////////////////////////////////////////////////////

// Handles onKeyPress event for the body tag.  Sometimes returns false to negate
// the keypress event.
function body_onKeyPress(e) {
    var isIE = document.all ? true : false
    var elt = isIE ? e.srcElement : e.target
    var tagName = elt.tagName.toLowerCase()
    var type = elt.type ? elt.type.toLowerCase() : ''

    if (tagName == 'textarea' || tagName == 'a' || (tagName == 'input' && type == 'submit')) {
        return true
    }
    var key = isIE ? window.event.keyCode : e.which
    if (key == 13 && g_defaultButtonId != '') {
        document.getElementById(g_defaultButtonId).click()
    }
    return key != 13
}

String.prototype.startsWith = function(str) {
    return 0 == this.indexOf(str) ? true : false
};

// if no args, set focus to first field of first form
// if arg is type object, call focus method
// if arg is type string, try the following in given order
//  1. use arg as id
//  2. use arg as field def code of non-repeated field
//  3. use arg as data area name, field def code of repeated field
function pc_setFocus() {
    if (document.forms.length < 1 || document.forms[0].elements.length < 1) {
        return
    }
    var form = document.forms[0]
    var elts = form.elements
    var field = 0

    if (arguments.length == 0) {
        var elementIndex = 0
        do {
            field = elts[elementIndex]
        } while (field.type == 'hidden' && ++elementIndex < elts.length)

        if (field.type == 'hidden') {
            field = 0
        }
    }
    else if (1 == arguments.length && 'string' == typeof arguments[0]) {
        field = document.getElementById(arguments[0])
        if (! field) {
            field = elts['com.peopleclick.cp.formdata.' + arguments[0]]
        }
        if (! field) {
            field = elts['com.peopleclick.cp.unfieldeddata.' + arguments[0]]
        }
    }
    else {
        // This shouldn't happen.
    }

    if (field) {
        field.focus()
        // window.scrollTo(0, findPosY(field))
    }
}

function findPosY(obj)
{
    var curtop = 0;
    if (obj.offsetParent)
    {
        while (obj.offsetParent)
        {
            curtop += obj.offsetTop
            obj = obj.offsetParent;
        }
    }
    else if (obj.y)
        curtop += obj.y;
    return curtop;
}

function underConstruction() {
    alert('Feature has not been completed.')
    return false
}

// A utility function that can be hooked up to a textbox to force the first letter to be capitalized.
// This is a frequent requirement for our customers ERP systems.
function capitalizeFirstLetter(textbox)
{
    text = textbox.value;
    fl = text.charAt(0);
	fw = fl.toUpperCase() + text.substr (1);
	textbox.value = fw;
}


function submitToSelfCluster(theForm, theFunctionName, theActionName, clusterInputName, theSelectedInput)
{
    theForm.action              = theActionName + ".do";
    theForm.functionName.value  = theFunctionName;
 
    for (var i =0; i< theForm.length; i++)
    {
    	var e = theForm.elements[i];
    	if (e.name == clusterInputName)
    	{
    		e.value = theSelectedInput;
    		//alert(e.name + ":" + e.value);
    	}
    }

    theForm.submit();
}

function submitToSelf(theForm, theFunctionName, theActionName, theSelectedInput)
{
    theForm.action              = theActionName + ".do";
    theForm.functionName.value  = theFunctionName;
    theForm.submit();
}

////////////////////////////////////////////////////////////////////////////////
// GENERIC (NON)WINDOW POPUP
////////////////////////////////////////////////////////////////////////////////

/*
	Creates a temporary display message that overlays any content on the page.
	Message disappears when the mouse leaves the message window. Display properties
	of the window are defined in the css class "pc-rtg-infoWindowPopup".
	
	@in p_refObj: object that anchors, or positions the message window
	@in p_msg: display message - may contain HTML
*/
function displayInfoWindowPopup(p_refObj, p_msg) {
	var oWindow = getInfoWindowFrame();
	var oBillBoard = getInfoWindowDiv(oWindow);
	
	oBillBoard.innerHTML = p_msg;
	
	// repositioning before the popup is displayed for those browsers that don't 
	// allow element repositioning with the display on
	oWindow.style.left = oBillBoard.style.left = dqbCalculateOffset(p_refObj, "offsetLeft", 0);
	oWindow.style.top = oBillBoard.style.top = dqbCalculateOffset(p_refObj, "offsetTop", 0);
	oWindow.style.width = oBillBoard.offsetWidth;
	oWindow.style.height = oBillBoard.offsetHeight;
	
	oWindow.style.display = oBillBoard.style.display = "";
	
	if(oWindow.style.pixelWidth == 0) {
	// resizing for those browsers that render elements without size until they are displayed
		oWindow.style.width = oBillBoard.offsetWidth;
		oWindow.style.height = oBillBoard.offsetHeight;
	}
}

// Retrieve the floating frame that acts as a new window
function getInfoWindowFrame() {
	var sObjID = "fraInfoWindowObject";
	var oFrame = document.getElementById(sObjID);
	
	if(oFrame == null) {
		oFrame = createInfoWindowFrame(sObjID);
	}
	return oFrame;
}

// Retrieve the div that acts as the canvas for a message
function getInfoWindowDiv(oFrame) {
	var sObjID = "divInfoWindowObject";
	var oDiv = document.getElementById(sObjID);
	
	if(oDiv == null) {
		oDiv = createInfoWindowDiv(sObjID, oFrame);
	}	
	return oDiv;
}

function createInfoWindowFrame(sObjID) {
	var obj = document.createElement("IFRAME");

	// these properties are required and should not be changed
	obj.id = sObjID;
	obj.style.position = "absolute";
	obj.scrolling = "no";
	obj.frameBorder = "0";
	obj.style.display = "none";
	
	return document.body.appendChild(obj);
}

function createInfoWindowDiv(sObjID, oFrame) {
	var obj = document.createElement("DIV");
	
	// these properties are required and should not be changed, 
	// although "className" can be modified
	obj.id = sObjID;
	obj.style.position = "absolute";
	obj.style.zIndex = 100;
	obj.style.display = "none";
	obj.className = "pc-rtg-infoWindowPopup";
	obj.onmouseout = function(evt)
	{
		evt = (evt) ? evt : ((event) ? event : null);
		
		var sLeft = parseInt(dqbCalculateOffset(obj, "offsetLeft", 0));
		if(document.body.clientLeft) sLeft +=  document.body.clientLeft;
		var sTop = parseInt(dqbCalculateOffset(obj, "offsetTop", 0));
		if(document.body.clientTop) sTop += document.body.clientTop;
		
		// close window when the pointer is truly outside the div boudary
		if(evt.clientX <= sLeft+2 || evt.clientY <= sTop+2 || evt.clientX >= sLeft-2 + obj.offsetWidth || evt.clientY >= sTop-2 + obj.offsetHeight) {
			obj.style.display = "none";
			oFrame.style.display = "none";
		}
	}
	
	return document.body.appendChild(obj);
}

////////////////////////////////////////////////////////////////////////////////
// WORKFLOWS
////////////////////////////////////////////////////////////////////////////////

function onClick_Prev(form)
{
    debugEnterMethod(arguments, 1)

    return runWorkflow(form, 'back')
}

function onClick_Next(form)
{
    debugEnterMethod(arguments, 1)

    return runWorkflow(form, 'next')
}

// This method is how we go back to the workflow
// if we have left.  In example preview (which can be called
// anytime by a candidate).
function onClick_Current(form)
{
    debugEnterMethod(arguments, 1)

    return runWorkflow(form, 'current')
}

function runWorkflow(form, direction)
{
    debugEnterMethod(arguments, 2)

    form.functionName.value='navigate'
    form.direction.value=direction
    form.submit()
    return false
}

function runFunction(form, functionName, direction)
{
    debugEnterMethod(arguments, 3)

    form.functionName.value=functionName
    form.direction.value=direction
    form.submit()
    return false
}

function onClick_SubmitJobApplication(form)
{
    debugEnterMethod(arguments, 1)

    return runFunction(form, 'submitApplication', '');
}

function exitWizard(form, functionName, exitStatus, direction)
{
    debugEnterMethod(arguments, 4)

    form.exitStatus.value=exitStatus
    form.direction.value=direction
    return runFunction(form, functionName, direction)
}

////////////////////////////////////////////////////////////////////////////////
// DOCUMENT CREATOR
////////////////////////////////////////////////////////////////////////////////

// Called when the user clicks the "Resume Builder" link.
function onClick_ResumeBuilderLink(formName) {
    debugEnterMethod(arguments, 1)

    if (g_onePageJobApp) {
        return runFunction(document.forms[formName], 'startResumeBuilder', 'next')
    }
    else {
        document.getElementById('builderRadio').checked=true
        return runFunction(document.forms[formName], 'navigate', 'next')
    }
}

var saveResumeChecked = false

// Used by job app's resume page if saving the resume is possible
function onChange_resumeMethodRadio()
{
    debugEnterMethod(arguments, 0)

    var repoRadio = document.getElementById('repositoryRadio')
    var usingRepo = repoRadio && repoRadio.checked

    if (usingRepo)
    {
    	var chkSaveResume = document.getElementById('saveResumeCheckbox');
    	if (chkSaveResume != null)
    	{
        	chkSaveResume.disabled = true;
        	chkSaveResume.checked = false;
        }
        var txtDocTitle = document.getElementById('com.peopleclick.cp.unfieldeddata.DOCUMENT_TITLE');
        if (txtDocTitle != null)
        {
        	txtDocTitle.disabled = true;
        }
    }
    else
    {
        document.getElementById('saveResumeCheckbox').disabled = false
        document.getElementById('com.peopleclick.cp.unfieldeddata.DOCUMENT_TITLE').disabled = ! saveResumeChecked
        var resumeCheck = document.getElementById('saveResumeCheckbox');
        if (resumeCheck)
        {
            resumeCheck.checked = saveResumeChecked
        }
    }
}

// Used by job app's resume page is saving the resume is possible
function onClick_saveResumeFromJobApp()
{
    debugEnterMethod(arguments, 0)

    saveResumeChecked = document.getElementById('saveResumeCheckbox').checked
    var document_title = document.getElementById('com.peopleclick.cp.unfieldeddata.DOCUMENT_TITLE')
    document_title.disabled = ! saveResumeChecked
    if (saveResumeChecked) {
        document_title.focus()
    }
}

////////////////////////////////////////////////////////////////////////////////
// ACCOUNT SUMMARY PAGE
////////////////////////////////////////////////////////////////////////////////

function onClick_Register()
{
    debugEnterMethod(arguments, 0)

    document.loginForm.functionName.value='getRegistrationPage'
    document.loginForm.submit()
    return false
}

function onClick_Login()
{
    debugEnterMethod(arguments, 0)

    document.loginForm.functionName.value='login'
    document.loginForm.submit()
    return false
}

function onClick_Goto(actionValue, functionNameValue)
{
    debugEnterMethod(arguments, 2)

    document.loginForm.action = actionValue
    document.loginForm.functionName.value = functionNameValue
    document.loginForm.submit()
    return false
}

////////////////////////////////////////////////////////////////////////////////
// JAVASCRIPT DEBUGGING
////////////////////////////////////////////////////////////////////////////////

// Call this at the top of every javascript method to enable debugging.
//  args = The arguments object
//  expectedArgCount = The number of arguments this method expects
//
// Example usage:
//   function foo(arg1, arg2) {
//     debugEnterMethod(arguments, 2)
//     ...
//   }
function debugEnterMethod(args, expectedArgCount) {
    // Quit if debug level is 0 or browser is IE
    if (g_jsDebugLevel == 0 || window.ActiveXObject) {
        return
    }
    var msg = ''
    // Handle errors
    var actualArgCount = args.length
    if (actualArgCount != expectedArgCount) {
        msg += 'ERROR: Wrong number of arguments.  Received ' + actualArgCount + ' and expected ' + expectedArgCount + '.'
    }
    // Handle warnings
    for (var i = 0; i < args.length; i++) {
        if (args[i] == undefined) {
            if (msg != '') {
                msg += '\n'
            }
            msg += 'WARNING: Argument #' + (i+1) + ' is undefined'
        }
    }
    // Handle extended debug info
    if (msg != '' || g_jsDebugLevel == 2) {
        if (msg != '') {
            msg += '\n\n'
        }
        msg += 'Entered method ' + args.callee.name + '('
        for (var i = 0; i < args.length; i++) {
            if (i > 0) {
                msg += ', '
            }
            var type = typeof args[i]
            if (args[i] == '[object HTMLFormElement]') {
                msg += 'form:' + args[i].name
            }
            else if (type == 'string') {
                msg += '"' + args[i] + '"'
            }
            else {
                msg += args[i]
            }
        }
        msg += ')'
        // TODO: Include a stack trace here
    }
    if (msg != '') {
        alert(msg)
    }
}

function debugObj(name, o, levels) {
    var debugWin = window.open('', '_blank', 'toolbar=no,menubar=no,scrollbars=both')
    var doc = debugWin.document
    doc.writeln('<HTML><HEAD><TITLE>Javascript dump of ' + name + ' ' + levels + ' levels deep</TITLE></HEAD><BODY><pre>')
    // doc.writeln(debugObjHelper(name, o, doc, levels))
    debugObjHelper(name, o, doc, levels)
    doc.writeln('</pre></BODY></HTML>')
    doc.close()
}

function debugObjHelper(name, o, doc, levels) {
    var msg = ''
    msg += name + ': ' + o + '   -- (' + (typeof o == 'object'?'object':'not an object') + ')\n'
    doc.write( name + ': ' + o + '   -- (' + (typeof o == 'object'?'object':'not an object') + ')\n')
    if (levels > 0 && typeof o == 'object') {
        for (propName in o) {
            if (propName != 'innerHTML' && propName != 'outerHTML' && propName != 'domConfig') {
                doc.writeln('eval('+name+'.'+propName+')')
                var prop = eval('o.'+propName)
                msg += debugObjHelper(name + '.' + propName, prop, doc, levels - 1)
                doc.write(debugObjHelper(name + '.' + propName, prop, doc, levels - 1))
            }
        }
    }
    return msg
}    


//prevents form to be submitted more than once    
function submitOnce() {
    if (!g_isFormSubmitted){
        g_isFormSubmitted = true;
        return true;
    }
    else {
        return false;
    }    
}

//disables the end date on the resume builder work history page if
//the "currently employed" check box is checked
function toggleEndDate(checkboxId, sectionNumber) {

    var elements = document.getElementsByName(checkboxId);
    //there's a hidden input element with this id, we don't want to get that element
    var i=0;
    var checkbox;
    while ((!checkbox) && i<elements.length)
    {
        var element = elements[i];
       if (element.type != 'hidden'){checkbox = element;}
       i++;
    }
        
    var disabled =  checkbox.checked;
    var checkboxIdPrefix = 'com.peopleclick.cp.formdata.repeater.CP_WH.';

    var day = document.getElementById(checkboxIdPrefix + sectionNumber + '.CP_WH_END_DATE__DAY');
    if (day != null)
    {
        day.disabled = disabled;
        if (disabled){day.value = '';}
    }
        
    var month = document.getElementById(checkboxIdPrefix + sectionNumber + '.CP_WH_END_DATE__MONTH');
    if (month != null)
    {
        month.disabled = disabled;
        if (disabled){month.value = '';}
    }	
        
    var year = document.getElementById(checkboxIdPrefix + sectionNumber + '.CP_WH_END_DATE__YEAR');
    if (year != null)
    {
        year.disabled = disabled;
        if (disabled){year.value = '';}
    }
}

// break out of frame for mobile site
function breakoutOfFrame()
{
  if (top.location != location) {
    top.location.href = document.location.href ;
  }
}
