﻿// Add support for jQuery
/// <reference path="jquery-1.2.6-vsdoc.js" />
 
/*global Adecco*/
/*global $*/
/*global jQuery*/
/*global OnModuleIsDone*/

/* Extend the base String type */
if (typeof String.prototype.isInteger === 'undefined') {
    String.prototype.isInteger = function () {
        /// <summary> Returns true if the string contains an integer, false otherwise. </summary>
        var isThisAnInteger = (/^\d+$/).test(this);
        return isThisAnInteger;
    };
}

if (typeof String.prototype.isNumber === 'undefined') {
    String.prototype.isNumber = function () {
        /// <summary> Returns true if the string contains a number, false otherwise. </summary>
        var isThisANumber = (/^\d+(\.\d+)?$/).test(this);
        return isThisANumber;
    };
}

if (typeof String.prototype.isEmpty === 'undefined') {
    String.prototype.isEmpty = function() {
        /// <summary> Returns true if the string is not empty, false otherwise </summary>
        var isThisEmpty = (this.length === 0);
        return isThisEmpty;
    };
}

if (typeof String.prototype.isNonEmpty === 'undefined') {
    String.prototype.isNonEmpty = function () {
        /// <summary> Returns true if the string is not empty, false otherwise </summary>
        var isThisNonEmpty = (this.length !== 0);
        return isThisNonEmpty;
    };
}

if (typeof String.prototype.isValidDate === 'undefined') {
    String.prototype.isValidDate = function() {

        var splitResult = this.split("/");
        var isDateValid = true;
        if (splitResult.length === 3) {

            var theFullDate = new Date(this.toString());
            var year = theFullDate.getFullYear();
            isDateValid = isDateValid && (splitResult[2].length===4) && (Number(year) === Number(splitResult[2]));
            var month = theFullDate.getMonth();
            isDateValid = isDateValid && (Number(month) === Number(splitResult[0] - 1));
            var date = theFullDate.getDate();
            isDateValid = isDateValid && (Number(date) === Number(splitResult[1]));

            return isDateValid;
        }
        return false;

        //var isThisValidDate = (/^\d{1,2}\/\d{1,2}\/\d{4}$/).test(this);
        //return isThisValidDate;
    };
}

if (typeof String.prototype.isZipCode === 'undefined') {
    String.prototype.isZipCode = function () {
        var isThisValidZip = (/^[0-9]{5}([\- \/]?[0-9]{4})?$/).test(this);
        return isThisValidZip;
    };
}

if (typeof String.prototype.isEmail === 'undefined') {
    String.prototype.isEmail = function() {
    var isThisEmail = (/^\s*[A-Za-z0-9.\!\#\$%&'\*\+\-\/=\?\^_\`\{\|\}\~]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}\s*$/).test(this);
        return isThisEmail;
    };
}

if (typeof String.prototype.isThreeDigit === 'undefined') {
    String.prototype.isThreeDigit = function() {
        var isThisThreeDigit = (/^\d{3}$/).test(this);
        return isThisThreeDigit;
    };
}

if (typeof String.prototype.isFourDigit === 'undefined') {
    String.prototype.isFourDigit = function() {
        var isThisFourDigit = (/^\d{4}$/).test(this);
        return isThisFourDigit;
    };
}


if (typeof String.prototype.isValidGPA === 'undefined') {
    String.prototype.isValidGPA = function() {
        if (!/^\d{1,1}(\.\d{1,1})?$/.test(this)) {
            return false;
        }
        var gpa = parseFloat(this);
        if(gpa !== 'undefined' && gpa >= 0 && gpa <= 4) {
            return true;
        }
        return false;
    };
}

if (typeof String.prototype.isValidSalary === 'undefined') {
    String.prototype.isValidSalary = function() {
        if (! /^\d{1,6}(\.\d{1,2})?$/.test(this)) {
            return false;
        }
        var salary = parseFloat(this);
        if (salary !== 'undefined' && salary >= 0 && salary <= 1000000) {
            return true;
        }
        return false;
    };
}

if (typeof String.prototype.trim === 'undefined') {
    String.prototype.trim = function () {
        return this.replace(/^\s*/, "").replace(/\s*$/, "");
    };
}

if (!Adecco) {
    var Adecco = {
        minDBDateString : '01/01/1753' 
    };
}

if (!Adecco.bringToTop) {
    Adecco.bringToTop = function (name) {
        window.location.hash = name;
    };
}

// helper methods for UI enhancements
if (!Adecco.UI) {
    Adecco.UI = {};
}

Adecco.UI.toNextTextBoxById = function(id, scope, numchar) {

    // input argument check
    if (!id) {
        return;
    }

    // get a reference to the textbox
    var jTextBox = $('#' + id);

    // only continue if the current textbox exists
    // and the textbox's content length exceeds "numChar"
    if (jTextBox.length == 0 || jTextBox.val().length < numchar) {
        return;
    }

    // get all the textboxes in the specified scope
    // start search from DOM root if scope is not specified
    var jAllTextBoxes;
    if (scope === null || scope.isEmpty()) {
        jAllTextBoxes = $(':text:visible');
    }
    else {
        jAllTextBoxes = $('#' + scope + ' :text:visible');
    }

    // go thru all the textboxes in the page
    // and find the next textbox's id
    var currentId = jTextBox[0].id;
    var currentIndex = -1;
    var i;
    for (i = 0; i < jAllTextBoxes.length; i++) {
        if (jAllTextBoxes[i].id === currentId) {
            currentIndex = i;
            break;
        }
    }

    // when we get here, "currentIndex" should equal to the index of the current textbox
    // if currentIndex is still -1 at this point, MaskedInput box "current" is not found in the specified scope
    if (currentIndex < 0) {
        return; // do nothing
    }

    // if "currentIndex" happens to be the last item in the textbox collection
    // we should just leave the focus at the current textbox
    if (currentIndex >= jAllTextBoxes.length) {
        return; // do nothing
    }

    // set focus to the next textbox
    var nextTextBox = jAllTextBoxes[currentIndex + 1];
    $('#' + nextTextBox.id).focus();
}

Adecco.UI.toPrevTextBoxById = function(id, scope, numchar) {

    // input argument check
    if (!id) {
        return;
    }

    // get a reference to the textbox
    var jTextBox = $('#' + id);

    // only continue if the current textbox exists
    // and the textbox's content length exceeds "numChar"
    if (jTextBox.length == 0 || jTextBox.val().length > numchar) {
        return;
    }

    // get all the textboxes in the specified scope
    // start search from DOM root if scope is not specified
    var jAllTextBoxes;
    if (scope === null || scope.isEmpty()) {
        jAllTextBoxes = $(':text:visible');
    }
    else {
        jAllTextBoxes = $('#' + scope + ' :text:visible');
    }

    // go thru all the textboxes in the page
    // and find the next textbox's id
    var currentId = jTextBox[0].id;
    var currentIndex = -1;
    var i;
    for (i = 0; i < jAllTextBoxes.length; i++) {
        if (jAllTextBoxes[i].id === currentId) {
            currentIndex = i;
            break;
        }
    }

    // when we get here, "currentIndex" should equal to the index of the current textbox
    // if currentIndex is still -1 at this point, MaskedInput box "current" is not found in the specified scope
    if (currentIndex < 0) {
        return; // do nothing
    }

    // if "currentIndex" happens to be the first item in the textbox collection
    // we should just leave the focus at the current textbox
    if (currentIndex == 0) {
        return; // do nothing
    }

    // set focus to the next textbox
    var prevTextBox = jAllTextBoxes[currentIndex - 1];
    $('#' + prevTextBox.id).focus();
}

Adecco.UI.toPrevOrNextById = function(id, scope, toPrevNumChar, toNextNumChar) {
    // input argument check
    if (!id || toPrevNumChar >= toNextNumChar) {
        return;
    }

    // get a reference to the curret textbox
    var jTextBox = $('#' + id);

    if (jTextBox.val().length <= toPrevNumChar) {
        Adecco.UI.toPrevTextBoxById(id, scope, toPrevNumChar);
    }
    else if (jTextBox.val().length >= toNextNumChar) {
        Adecco.UI.toNextTextBoxById(id, scope, toNextNumChar);
    }
}

Adecco.UI.limitTextAreaLength = function(id, maxLength) {
    // input argument check
    if (!id) {
        return;
    }

    // get a reference to the curret textarea
    var textArea = $('#' + id);

    //check if greater then max length
    if (textArea.val().length >= maxLength) {
        //if so, trim the text so that is within max length
        var trimmed = textArea.val().substring(0, maxLength);
        textArea.val(trimmed);
    }
}

// method to move the focus to the next textbox
// the passed in parameter "current" must be a reference to a MaskedInput box
// scope is the id of an element in the DOM which contains "current" MaskedInput (pass empty to search from root)
// numChar indicates the number of characters entered before switching focus to the next MaskedInput
Adecco.UI.toNextTextBox = function(current, scope, numChar) {

    // input argument check
    if (!current || !current.masked || !current.masked.id) {
        return;
    }
    
    Adecco.UI.toNextTextBoxById(current.masked.id, scope, numChar);
};

Adecco.UI.toPrevTextBox = function(current, scope, numChar) {

    // input argument check
    if (!current || !current.masked || !current.masked.id) {
        return;
    }

    Adecco.UI.toPrevTextBoxById(current.masked.id, scope, numChar);
};

Adecco.UI.toPrevOrNext = function(current, scope, toPrevNumChar, toNextNumChar) {
    // input argument check
    if (!current || !current.masked || !current.masked.id || toPrevNumChar >= toNextNumChar) {
        return;
    }

    if (current.masked.value.length <= toPrevNumChar) {
        Adecco.UI.toPrevTextBox(current, scope, toPrevNumChar);
    }
    else if (current.masked.value.length >= toNextNumChar) {
        Adecco.UI.toNextTextBox(current, scope, toNextNumChar);
    }
}


if (!Adecco.Ajax) {
    Adecco.Ajax = {
        images: {
            ajaxBar: '/_layouts/adecco/images/ajax-bar.gif',
            ajaxSpinner: '/_layouts/adecco/images/ajax-loader-small.gif',
            sectionComplete: '/_layouts/adecco/images/jobapply/img_checkmark.gif',
            sectionIncomplete: '/_layouts/adecco/images/jobapply/img_no_checkmark.gif',
            continueEnabled: '/_layouts/adecco/images/jobapply/but_continue_off.gif',
            continueDisabled: '/_layouts/adecco/images/jobapply/but_continue_disabled.gif',
            snapArrowCollapsed: '/_layouts/adecco/images/jobapply/img_arrowholder_right.gif',
            snapArrowExpanded: '/_layouts/adecco/images/jobapply/img_arrowholder_down.gif'
        },
        parsedProfile: null
    };
}

Adecco.Ajax.doCallback = function (callback) {
/// <summary>
///     Calls the callback method of the specified control,
///     passing in the value of specified form element.
/// </summary>
    var element, elementValue, i;
    var parameters = [];
    if (typeof callback === 'string') {
        // Get the callback control from the global object.
        callback = window[callback];
    }
    
    for (i = 1; i < arguments.length; ++i) {
        element = arguments[i];
    
        if (typeof element === 'string') {
            // Get the element through jQuery
            element = $('#' + element);
        } else if (typeof element.val !== 'function') {
            // Element has not been augmented through jQuery
            element = $(element);
        }
        // Get the element value if element is not null or undefined.
        elementValue = element && element.val();
        
        parameters.push(elementValue);
    }
    
    // Peform the callback with a dynamic number of arguments (i.e the retrieved values).
    callback.callback.apply(callback, parameters);
};

Adecco.Ajax.onCallbackError = function(sender, eventArgs) {
    //alert(eventArgs.get_message());
};


Adecco.Ajax.DisableControl = function(control) {
    //disable the control and set the disabledControl css class
    var controlToDisable;
    if (typeof controlId === 'string') {
        controlToDisable = $('#' + control);
    } else {
        controlToDisable = $(control);
    }
    controlToDisable.addClass('disabledControl');
    controlToDisable.attr('disabled', 'disabled');
};

Adecco.Ajax.EnableControl = function(control) {
    //enable the control and remove the disabledControl css class
    var controlToEnable;
    if (typeof controlId === 'string') {
        controlToEnable = $('#' + control);
    } else {
        controlToEnable = $(control);
    }
    controlToEnable.removeClass('disabledControl');
    controlToEnable.removeAttr('disabled');
};

Adecco.forceInputCheck = function (sender, e) {
    if (sender.get_isInitialized() === true)
    {
        sender.render();
    }
};

Adecco.Ajax.initTextboxMaskedInput = function(context) {
    if (typeof context === 'undefined') {
        context = document;
    } else if (typeof context === 'string') {
        context = document.getElementById(context);
    }

    var allTextboxes = $('input[type="text"]', context);
    var digitsOnlyTextboxes = allTextboxes.filter('.allow-digits');

    digitsOnlyTextboxes.keypress(function(eventArgs) {
        var charCode = (eventArgs.which) ? eventArgs.which : eventArgs.keyCode;

        if (charCode > 31 && (charCode < 48 || charCode > 57)) {
            return false;
        }

        return true;
    });
};

Adecco.Ajax.updateSectionStatusImage = function (imageId, isDone)
{
    /// <summary>
    ///     Changes the specified image to reflect the "isDone" status.
    /// </summary>
    var image, imagePath;
    
    if (typeof imageId === 'string') {
        image = $('#' + imageId);
    } else {
        image = $(imageId);
    }
 
    if(image.length > 0)
    {
        if (isDone) {
            imagePath = this.images.sectionComplete;
        } else {
            imagePath = this.images.sectionIncomplete;
        }
        
        // Update the image source location/
        image.attr('src', imagePath);
    }
};

Adecco.Ajax.updateSectionStatus = function(divId, isDone) {
    var jDiv = $('#' + divId);

    if (jDiv.length > 0) {
        if (isDone) {
            jDiv.css("visibility", "hidden");
        }
        else {
            jDiv.css("visibility", "visible");
        }
    }
};

Adecco.Ajax.updateSnapArrowImg = function(snapRef, imgId) {
    if (snapRef && snapRef.get_isCollapsed) {
        if (snapRef.get_isCollapsed()) {
            $("#" + imgId).attr("src", Adecco.Ajax.images.snapArrowCollapsed);
        }
        else {
            $("#" + imgId).attr("src", Adecco.Ajax.images.snapArrowExpanded);
        }
    }
};

Adecco.Ajax.initializeModalPopups = function() {
    var iFrameId = 'ie6overlayhack';
    var htmlSource, theFrame;

    // This is only for IE6
    if ($.browser.msie && /6.0/.test(navigator.userAgent) || true) {
        if (document.getElementById(iFrameId)) {
            return;
        }

        var htmlSource = '<iframe id="' + iFrameId + '" frameborder="0" tabindex="-1" src="javascript:\'&lt;html&gt;&lt;/html&gt;\';"' +
                            ' style="position:absolute;width:1px;height:1px;top:0px;left:0px;border:0;display:block;z-index:0;filter:Alpha(Opacity=\'0\')" />';

        theFrame = document.createElement(htmlSource);
        document.body.appendChild(theFrame);
    }
};

Adecco.Ajax.onModalPopupShowing = function () {
    var theFrame;
    
    if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
        Adecco.Ajax.initializeModalPopups();
        theFrame = $('#ie6overlayhack');
        
        theFrame.css('width', 2000);
        theFrame.css('height', 2000);
    }
};

Adecco.Ajax.onModalPopupClosing = function() {
    var theFrame;

    if ($.browser.msie && /6.0/.test(navigator.userAgent)) {
        Adecco.Ajax.initializeModalPopups();
        theFrame = $('#ie6overlayhack');

        theFrame.css('width', 1);
        theFrame.css('height', 1);
    }
};

Adecco.Ajax.UploadResumeDialog = function (innerDialog) {
    this._innerDialog = window[innerDialog];
    //Adecco.Ajax.initializeModalPopups();
};

Adecco.Ajax.UploadResumeDialog.prototype = {
    show: function() {
        if (this._innerDialog) {
            Adecco.Ajax.onModalPopupShowing();
            this._innerDialog.show();
        }
    },

    close: function() {
        var iframe = $('#ie6overlayhack');
        if (this._innerDialog) {
            Adecco.Ajax.onModalPopupClosing();

            $('#upload-progress').hide();
            $('#upload-result').hide();
            $('#upload-controls').show();
            this._innerDialog.close();
        }
    },

    // Hide & close perform the same thing. This is just a convenience method.
    hide: function() {
        this.close();
    }
};

Adecco.Ajax.wasResumeUploadInitialized = false;

Adecco.Ajax.onFileUploading = function (frameId) {
    var theForm, hiddenFrame, originalTarget, originalEncType;
            
    frameId = frameId || 'aco_upload';
    
    theForm = document.forms[0];
    hiddenFrame = $(frameId);
    
    // Save the form's original values
    originalTarget = theForm.target;
    originalEncType = theForm.enctype;
        
    // Hide the upload controls and display the progress bar.
    $('#upload-controls').hide();
    $('#upload-result').hide();
    $('#upload-progress').show();
        
    theForm.target = frameId;
    
    // IE doesn't support modifying "enctype", we have to use "encoding".
    theForm.enctype = 'multipart/form-data';
    theForm.encoding = 'multipart/form-data';
    theForm.submit();
    
    // Restore the form's original values.
    theForm.target = originalTarget;
    theForm.enctype = originalEncType;
    theForm.encoding = originalEncType;
};

Adecco.Ajax.onFileUploaded = function (theFrame) {
    var result;
    if (theFrame.contentWindow.aco_uploadResult) {
        result = theFrame.contentWindow.aco_uploadResult;
        if (result.code === 1) {
            $('#upload-progress').hide();
            $('#upload-result').text(result.message);
            $('#upload-result').show();
            $('#buildProfileContainer').css('visibility', 'visible');
        } else if (result.code > 1) {
            $('#upload-progress').hide();            
            $('#upload-result').html('<span class="error">' + result.message + '</span>');
            $('#upload-result').show();
            $('#upload-controls').show();
        }
    }
};

Adecco.Ajax.initResumeUpload = function ()
{
    if (Adecco.Ajax.wasResumeUploadInitialized === true) {
        return;
    }
    
    var frameId = 'myFrame';
    
    var content = '<html><head></head><body style="margin:0"><form name="upload" id="upload" method="post" enctype="multipart/form-data">' +
                    '<input type="file" name="resume" />' +
                    '<input type="submit" value="Upload" id="upload-submit" />' +
                    '</form>' +
                    '<div id="upload-progress" class="upload-progress" style="display:none">' +
                        '<img src="' + Adecco.Ajax.images.ajaxBar + '" alt="" />' +
                        '<span><strong>Processing...</strong></span>' +
                    '</div>' +
                    '</body></html>';
    
    var frameWindow = window.frames[frameId] || document.getElementById(frameId);
    
    var theDoc = frameWindow.document || frameWindow.contentDocument;
    
    theDoc.open();
    theDoc.write(content);
    
    var theForm = theDoc.getElementById('upload');
    $(theForm).bind('submit', Adecco.Ajax.onResumeUploading);
    
    Adecco.Ajax.wasResumeUploadInitialized = true;
};

Adecco.Ajax.onResumeUploading = function ()
{
    var frameId = 'myFrame';

    var frameWindow = window.frames[frameId] || document.getElementById(frameId);
    var theDoc = frameWindow.document || frameWindow.contentDocument;

    var theForm = $(theDoc.getElementById('upload'));
    theForm.hide();

    var progressBlock = $(theDoc.getElementById('upload-progress'));
    progressBlock.show();
};

Adecco.Ajax.onBuildProfileClick = function (sender, event, resumeid)
{
    if (!cbkBuildProfile) {
        // Callback component is not defined.
        return;
    }
 
    Adecco.BuildProfile.setDismissCount(0);
 
    var selectDDL = document.getElementById(resumeid);
    
    // Save a reference to the sender.
    Adecco.Ajax.buildProfileSender = sender;
    
    sender = sender && $(sender);
    
    // Remove any previous error/confirmation message.
    // $('#build-profile-status').remove();
    
    // Register an event an event hander when the callback is complete.
    cbkBuildProfile.add_callbackComplete(Adecco.Ajax.notifyControlsOnProfileData);
    
    // Perform the asynchronous call.
    var index;
    var selectedUrl = null;
    for (index = 0; index < selectDDL.length; index++)
    {
        if (selectDDL.options[index].selected === true)
        {
             selectedUrl = selectDDL.options[index].value;
             break;
        }
    }
    
    if (selectedUrl !== null )
    {
        cbkBuildProfile.callback('buildProfile', selectedUrl);
    }
    
};

Adecco.Ajax.onBuildProfileComplete = function (message)
{    
};

Adecco.Ajax.onBuildProfileError = function ()
{    
};

Adecco.Ajax.notifyControlsOnProfileData = function () {
    var workEditCallback = window.cbkWorkHistoryEditRepeater;
    var educationEditCallback = window.cbkEducationEditRepeater;
    var contactEditCallback = window.cbkContactInformationEdit;
    var contactReviewCallback = window.cbkContactInformationReview;
    var callCounter = 0;
    
    if (Adecco.Ajax.parsedProfile) {
        
        // We have to notify the Contact Information, Work History and Education controls.
        if (window.snpWorkHistoryOuter && workEditCallback) 
        {
            workEditCallback.callback();
            callCounter++;
        }

        if (window.snpEducationOuter && educationEditCallback) 
        {            
            educationEditCallback.callback('expand');
            callCounter++;
        }
        
        if (window.snpContactInformation && contactReviewCallback && contactEditCallback) {
            if (snpContactInformation.get_isCollapsed()) {
                contactReviewCallback.callback();
                callCounter++;
            } else {
                contactEditCallback.callback('expand');
                callCounter++;
            }
        }
        
        Adecco.BuildProfile.setDismissCount(callCounter);
        setTimeout (function () { if (window.dlgPleaseWaitBuilding && dlgPleaseWaitBuilding.get_isShowing())
                                    {   dlgPleaseWaitBuilding.close('Timeout'); } }, callCounter * 3000);
    }   
};


Adecco.Ajax.toggleControl = function(controlId) {
    /// <summary>
    ///     Toggle the control with the given controlId between disable and enable
    /// </summary>
    var theControl;
    if (typeof controlId === 'string') {
        theControl = $('#' + controlId);
    } else {
        theControl = $(controlId);
    }

    if (theControl.attr('disabled')) //if disabled, enable it
    {
        Adecco.Ajax.EnableControl(theControl);
    }
    else //if enabled, disable it
    {
        Adecco.Ajax.DisableControl(theControl);
    }
};

Adecco.Ajax.setSignUpControlEmailAddress = function(emailAddressControl) {
    /// <summary>
    ///     set the email address shown in the sign up control to the given email address
    /// </summary>
    var theControl;
    if (typeof emailAddressControl === 'string') {
        theControl = window[emailAddressControl];
    } else {
    theControl = emailAddressControl;
    }
    if (theControl) {
        var email = theControl.Text;
        $('.signUplblEmail').text(email);
    }
};

/***********************************/
/* Build Profile functions         */
/***********************************/
if (!Adecco.BuildProfile) {
    Adecco.BuildProfile = {
        CallbackCounter: 0
    };
}

Adecco.BuildProfile.setDismissCount = function (cbkcount)
{
    this.CallbackCounter = cbkcount;
};

Adecco.BuildProfile.dismissPleaseWaitBuilding = function()
{    
    this.CallbackCounter --;
    if (this.CallbackCounter <= 0)
    {
        // dismiss the modal dialog.
        if (window.dlgPleaseWaitBuilding && dlgPleaseWaitBuilding.get_isShowing())
        {
            dlgPleaseWaitBuilding.close('Success');
        }
    }
};

/***********************************/
/* Passive Apply-related functions */
/***********************************/
if (!Adecco.PassiveApply) {
    Adecco.PassiveApply = {};
}

Adecco.PassiveApply.onUploadResumeClickValidate = function() {
    Adecco.JobCategory.hideAllWarningMessages();
    if (!Adecco.JobCategory.validate()) {
        return false;
    }
    return true;
};

Adecco.PassiveApply.onContinueWithoutResumeClick = function (callbackParameter) {
    Adecco.JobCategory.hideAllWarningMessages();
    if (!Adecco.JobCategory.validate()) {
        return;
    }
    cbkPassiveApply.callback(callbackParameter);
};

/*******************************/
/* Education-related functions */
/*******************************/
if (!Adecco.Education) {
    Adecco.Education = {
        ddlCountry: null,
        ddlState: null,
        txtMajorSubjects: null,
        txtSchoolName: null,
        txtGPA: null,
        btnEditCompleteId: null,
        snapImageId: null                
    };
}

Adecco.Education.initialize = function(configuration) {
    /// <summary>
    ///     Initializes the Education with dynamic control names.
    /// </summary>
    this.ddlCountry = configuration.country || null;
    this.ddlState = configuration.state || null;
    this.txtMajorSubjects = configuration.majorSubjects || null;
    this.txtSchoolName = configuration.schoolName || null;
    this.txtGPA = configuration.gpa || null;
    this.btnEditCompleteId = configuration.editButtonId || null;
    this.snapImageId = configuration.snapImageId || null;

    // Free up some memory
    delete Adecco.Education.initialize;
};

Adecco.Education.onMajorSubjectsKeyUp = function() {
    //limit the input length to 255
    Adecco.UI.limitTextAreaLength(this.txtMajorSubjects, 255);
};

Adecco.Education.onOuterSnapExpanded = function () {
    var educationEditCallback = window.cbkEducationEditRepeater;
    var educationReviewCallback = window.cbkEducationReview;

    if (window.snpEducation && educationReviewCallback && educationEditCallback) {
        if (snpEducation.get_isCollapsed()) {
            educationReviewCallback.callback();
        } else {
            educationEditCallback.callback('expand');
        }
    }
    
    Adecco.Education.updateEducationArrow();
};

Adecco.Education.EducationEditRepeaterCallbackComplete = function() {
    // hide the edit form
    $('#educationEditForm').hide();
    $('#addSchoolLink').show();

    // hide the repeater and show loading panel
    $('#divEducationRepeater').hide();
    $('#divEducationRepeaterLoadingPanel').show();
    Adecco.bringToTop('EducationTop');

};

Adecco.Education.doCallbackEdit = function () {
    setTimeout(function () { cbkEducationEditRepeater.callback('expand'); }, 500);
};

Adecco.Education.doCallbackReview = function () {
    setTimeout(function () { cbkEducationReview.callback('persist'); }, 500);
};

Adecco.Education.IsEducationComplete = function (isDone)
{
    Adecco.WizardProgress.OnModuleIsDone('educationIsDone', isDone);    
    Adecco.Ajax.updateSectionStatusImage('imgEduState', isDone);
};

Adecco.Education.doEditCallbackComplete = function() {
    var educationEditCallback = window.cbkEducationEditRepeater;

    // determine whether we're in edit mode by looking for the "edit button"
    // only do the callback when we're NOT in edit mode
    if ($('#' + this.btnEditCompleteId + ':visible').length <= 0) {
        if (educationEditCallback) {
            educationEditCallback.callback();
        }
    }
};

Adecco.Education.onCountryChange = function() {
    /// <summary>
    ///     disable the state dropdown if the country selected is not United States
    /// </summary>
    var stateControl = $('#' + this.ddlState);
    var countryControl = $('#' + this.ddlCountry);

    //if country selected is not united states, disable state control
    if (countryControl.val() === 'UNITED STATES') {
        Adecco.Ajax.EnableControl(stateControl);
    }
    //if country selected is united states, enable state control, and reset the state
    else {
        Adecco.Ajax.DisableControl(stateControl);
        stateControl.attr('selectedIndex', 0);
    }
};

Adecco.Education.validateFormDate = function () {
    var isValid = true;
    var fromMonths, toMonths, i;
    var fromDate, toDate;
    var fromMonth, fromYear, toMonth, toYear;
    
     // Parse "From" date
    fromMonths = $('#education-edit-container .from-month option');
    fromYear = $('#education-edit-container .from-year');
    fromYear = fromYear.val();

    for (i = 0; i < fromMonths.length; i++) {
        if (fromMonths[i].selected) {
            fromMonth = i;
            break;
        }
    }
    fromDate = new Date(fromYear, fromMonth, 1);

    // Parse "To" date
    toMonths = $('#education-edit-container .to-month option');
    toYear = $('#education-edit-container .to-year');
    toYear = toYear.val();

    for (i = 0; i < toMonths.length; i++) {
        if (toMonths[i].selected) {
            toMonth = i;
            break;
        }
    }
    toDate = new Date(toYear, toMonth, 1);

    // Compare From to To date.
    if (fromDate <= toDate) {
        isValid = isValid && true;
    } else {

        isValid = false;
    }
    return isValid;
};

Adecco.Education.validateFormSchool = function () {
    var isValid = true;
    // Check School Name
    var schoolName = $('#' + this.txtSchoolName+'_unmasked');
    if (schoolName.val().trim().isNonEmpty()) {
        isValid = isValid && true;
    } else {        
        isValid = false;
    }
    return isValid;
};

Adecco.Education.validateFormGPA = function() {
    // check GPA value
    var gpa = $('#' + this.txtGPA + '_unmasked');
    if (gpa.val().length === 0 || gpa.val().trim().isValidGPA()) {
        return true;
    }
    return false;
};

Adecco.Education.validateFormOnAction = function() {
    var isSchoolValid = true;
    var isDateValid = true;
    var isGPAValid = true;

    isSchoolValid = Adecco.Education.validateFormSchool();
    if (isSchoolValid === true) {
        $('#divEducationRequiredFieldMissingMessage').hide();
    }

    isDateValid = Adecco.Education.validateFormDate();
    if (isDateValid === true) {
        $('#divEducationDatesIncorrectMessage').hide();
    }

    isGPAValid = Adecco.Education.validateFormGPA();
    if (isGPAValid === true) {
        $('#divEducationGPAInvalid').hide();
    }

    return isDateValid && isSchoolValid && isGPAValid;
};

Adecco.Education.validateForm = function() {
    var isSchoolValid = true;
    var isDateValid = true;
    var isGPAValid = true;

    isSchoolValid = Adecco.Education.validateFormSchool();
    if (isSchoolValid === false) {
        $('#divEducationRequiredFieldMissingMessage').show();
    }

    isDateValid = Adecco.Education.validateFormDate();
    if (isDateValid === false) {
        $('#divEducationDatesIncorrectMessage').show();
    }

    isGPAValid = Adecco.Education.validateFormGPA();
    if (isGPAValid === false) {
        $('#divEducationGPAInvalid').show();
    }

    return isSchoolValid && isDateValid && isGPAValid;
};

Adecco.Education.getInvalidRptItemCount = function () {
    var invalids = $('.education-item-container.invalid').size();
    return invalids;
};

Adecco.Education.validateOnSubmit = function () {
    var imgEdu = document.getElementById('imgEducation');
    if (imgEdu === null ) {
        return true;
    }
    
    if (Adecco.Education.getInvalidRptItemCount() <= 0) {    
        return true;
    }
    return false;
};

Adecco.Education.updateMissingInfo = function (isDone) {
    Adecco.Ajax.updateSectionStatus('divEducationMissingInfo', isDone);
};

Adecco.Education.validate = function() {
    if (Adecco.Education.getInvalidRptItemCount() <= 0) {
        Adecco.Education.updateMissingInfo(true);
        $('#divEducationErrorSummary').hide();
        return true;
    }
    return false;
};

Adecco.Education.updateEducationArrow = function() {
    Adecco.Ajax.updateSnapArrowImg(snpEducationOuter, this.snapImageId);
};

Adecco.Education.transformValidateGPA = function(input) {
    // special transform validate for gpa masked input
    var theInput = input.masked.value;
    return theInput.isEmpty() || theInput.isValidGPA();
};

/**************************/
/* Work-related functions */
/**************************/
if (!Adecco.WorkHistory) {
    Adecco.WorkHistory = {
        count: 1,
        txtJobTitle: null,
        txtCompanyName: null,
        txtResponsibilities: null,
        btnEditComplete: null,
        ddlCountry: null,
        ddlState: null,
        snapImageId: null,
        toPresentcbx: null,
        imgAddButtionId:null,
        txtSalary:null
    };
}

Adecco.WorkHistory.getInvalidRptItemCount = function () {
    var invalids = $('.workhistory-item-container.invalid').size();
    return invalids;
};

Adecco.WorkHistory.initialize = function(configuration) {
    /// <summary>
    ///     Initializes the Work History with dynamic control names.
    /// </summary>

    this.txtJobTitle = configuration.jobTitle || null;
    this.txtCompanyName = configuration.companyName || null;
    this.txtResponsibilities = configuration.responsibility || null;
    this.btnEditCompleteId = configuration.editCompleteId || null;
    this.ddlCountry = configuration.country || null;
    this.ddlState = configuration.state || null;
    this.snapImageId = configuration.snapImageId || null;
    this.toPresentcbx = configuration.toPresentcbx || null;
    this.imgAddButtionId = configuration.imgAddButtionId || null;
    this.txtSalary = configuration.salary || null;

    // Free up some memory
    delete Adecco.WorkHistory.initialize;
};

Adecco.WorkHistory.isFormEditMode = function () {
    var imgbutton = $('#' + this.imgAddButtionId);
    if (imgbutton.is(':visible')) {
        return false;
    }
    return true;
};

Adecco.WorkHistory.onCountryChange = function() {
    /// <summary>
    ///     disable the state dropdown if the country selected is not United States
    /// </summary>
    var stateControl = $('#' + this.ddlState);
    var countryControl = $('#' + this.ddlCountry);

    //if country selected is not united states, disable state control
    if (countryControl.val() === 'UNITED STATES') {
        Adecco.Ajax.EnableControl(stateControl);
    }
    //if country selected is united states, enable state control, and reset the state
    else {
        Adecco.Ajax.DisableControl(stateControl);
        stateControl.attr('selectedIndex', 0);
    }
};

Adecco.WorkHistory.doCallbackReview = function () {
    //setTimeout(function () { cbkWorkHistoryReview.callback(); }, 500);
};

Adecco.WorkHistory.doCallbackEditRepeater = function() {
   // setTimeout(function() { cbkWorkHistoryEditRepeater.callback(); }, 500);
};

Adecco.WorkHistory.WorkHistoryEditRepeaterCallbackComplete = function() {
    // hide the edit form
    $('#EditWorkHistoryForm').hide();
    $('#addWorkLink').show();

    // hide the repeater and show loading panel
    $('#divWorkHistoryRepeater').hide();
    $('#divWorkHistoryRepeaterLoadingPanel').show();
    Adecco.bringToTop('WorkHistoryTop');
};

Adecco.WorkHistory.doWorkHistoryRepeaterCallbackCompleted = function() {
    var otherInfoOuterSnap = window.snpOtherInformationOuter;
    var otherInfoInnerSnap = window.snpOtherInformation;

    Adecco.BuildProfile.dismissPleaseWaitBuilding();
    $('#divWorkHistoryRepeaterLoadingPanel').hide();

    // refresh the other info panel if it's on the page
    if (otherInfoOuterSnap && otherInfoInnerSnap && window.cbkOtherInformationEdit && window.cbkOtherInformationReview) {
        // if the inner snap is collapsed, the control is in preview mode
        if (otherInfoInnerSnap.get_isCollapsed()) {
            // refresh the preview panel
            window.cbkOtherInformationReview.callback();
        }
        else {
            // refresh the edit panel
            window.cbkOtherInformationEdit.callback('expand');
        }
    }
};

Adecco.WorkHistory.doWorkHistoryCallbackCompleted = function() {
    var controlsToForceUpdate, i, item;
    var workEditCallback = window.cbkWorkHistoryEditRepeater;

    // determine whether we're in edit mode by looking for the "edit button"
    if ($('#' + this.btnEditCompleteId + ':visible').length > 0) {
        controlsToForceUpdate = [
            this.txtJobTitle,
            this.txtCompanyName
        ];

        for (i = 0; i < controlsToForceUpdate.length; i++) {
            item = controlsToForceUpdate[i];
            ComponentArt_MaskedInput_Blur(window[item]);
        }
    }
    else {
        // refresh the work history list
        if (workEditCallback) {
            workEditCallback.callback();
        }
    }
};


Adecco.WorkHistory.IsWorkHistoryComplete = function(isDone)
{
    Adecco.WizardProgress.OnModuleIsDone('workHistoryIsDone', isDone);
    Adecco.Ajax.updateSectionStatusImage('imgWorkHistoryState', isDone);
};

Adecco.WorkHistory.doOuterSnapExpand = function() {
    /// <summary>
    ///     Handle application streams where the outer snap is collapsed initially.
    /// </summary>

    Adecco.WorkHistory.updateWorkHistoryArrow();

    var workEditCallback = window.cbkWorkHistoryEditRepeater;
    var workReviewCallback = window.cbkWorkHistoryReview;

    if (window.snpWorkHistory && workReviewCallback && workEditCallback) {
        if (snpWorkHistory.get_isCollapsed()) {
            workReviewCallback.callback();
        } else {
            workEditCallback.callback();
        }
    }
};

Adecco.WorkHistory.updateWorkHistoryArrow = function() {
    Adecco.Ajax.updateSnapArrowImg(snpWorkHistoryOuter, this.snapImageId);
};

Adecco.WorkHistory.updateMissingInfo = function(isDone) {
    Adecco.Ajax.updateSectionStatus('divWorkHistoryMissingInfo', isDone);
};

Adecco.WorkHistory.validate = function() {
    if (Adecco.WorkHistory.getInvalidRptItemCount() !== 0) {
        // item in the repeater is invalid
        return false;
    }

    if (Adecco.WorkHistory.count > 0) {
        return true;
    }
    return false;
};

Adecco.WorkHistory.resetErrorMessage = function () {
    $('#divWorkHistoryRequiredFieldMissingMessage').hide();
    $('#divWorkHistoryFromDateAfterToDateInvalidMessage').hide();    
};

Adecco.WorkHistory.validateFormOnAction = function () {
    if (Adecco.WorkHistory.validateFormRequiredFields() === true) {
        // it is in add mode
        $('#divWorkHistoryRequiredFieldMissingMessage').hide();
    }
    
    if (Adecco.WorkHistory.validateFormDate () === true) {
        $('#divWorkHistoryFromDateAfterToDateInvalidMessage').hide();
    }

    if (Adecco.WorkHistory.validateFormSalary() === true) {
        $('#divWorkHistorySalaryInvalidMessage').hide();
    }
};

Adecco.WorkHistory.validateFormRequiredFields = function () {
    var isValid = true;
    var jobTitle = $('#' + this.txtJobTitle+'_unmasked');
    var companyName = $('#' + this.txtCompanyName+'_unmasked');
    var responsibility = $('#' + this.txtResponsibilities);
        
    // validiate the requried fields on the form
    if (jobTitle.val().trim().isNonEmpty() && companyName.val().trim().isNonEmpty() && responsibility.val().trim().isNonEmpty()) {
        isValid=true;
    }
    else {
        isValid = false;
    }
    return isValid;
};

Adecco.WorkHistory.validateFormDate = function () {
    var isValid = true;
    var fromMonths, toMonths, i;
    var fromDate, toDate;
    var fromMonth, fromYear, toMonth, toYear;
    var toPresent = document.getElementById(this.toPresentcbx);
    
    // Parse "From" date
    fromMonths = $('#workhistory-edit-container .from-month option');
    fromYear = $('#workhistory-edit-container .from-year');
    fromYear = fromYear.val();

    for (i = 0; i < fromMonths.length; i++) {
        if (fromMonths[i].selected) {
            fromMonth = i;
            break;
        }
    }
    fromDate = new Date(fromYear, fromMonth, 1);

    // Parse "To" date
    toMonths = $('#workhistory-edit-container .to-month option');
    toYear = $('#workhistory-edit-container .to-year');
    toYear = toYear.val();
    
    for (i = 0; i < toMonths.length; i++) {
        if (toMonths[i].selected) {
            toMonth = i;
            break;
        }
    }
    
    if (toPresent !== null && !toPresent.checked) {
        toDate = new Date(toYear, toMonth, 1);
    }
    else {
        toDate = new Date();
    }
    
    // Compare From to To date.
    if (fromDate <= toDate) {
        isValid = isValid && true;        
    } else {
        isValid = false;
    }
        
    return isValid;
};

Adecco.WorkHistory.validateFormSalary = function() {
    // special transform validate for salary masked input
    var theInput = $('#' + this.txtSalary).val();
    if (theInput.isEmpty()) {
        return true;
    }
    else {
        return theInput.isValidSalary()
    }
};

Adecco.WorkHistory.validateForm = function() {
    var isReqFieldsValid = true;
    var isDateValid = true;
    var isSalaryValid = true;

    Adecco.WorkHistory.resetErrorMessage();

    isReqFieldsValid = Adecco.WorkHistory.validateFormRequiredFields();
    if (isReqFieldsValid === false) {
        $('#divWorkHistoryRequiredFieldMissingMessage').show();
    }

    isDateValid = Adecco.WorkHistory.validateFormDate();
    if (isDateValid === false) {
        $('#divWorkHistoryFromDateAfterToDateInvalidMessage').show();
    }

    isSalaryValid = Adecco.WorkHistory.validateFormSalary();
    if (isSalaryValid === false) {
        $('#divWorkHistorySalaryInvalidMessage').show();
    }

    return isDateValid && isReqFieldsValid && isSalaryValid;
};

Adecco.WorkHistory.updateErrorSummary = function(isDone) {
    if (isDone === true) {
        $('#divWorkHistoryErrorSummary').hide();
    }
};

Adecco.WorkHistory.toggleResponsibilityCss = function () {
    var responsibility = $('#' + this.txtResponsibilities).val();
    if (responsibility.length > 0) {
        Adecco.WorkHistory.removeResponibilityCss();
    }
    else {
        $('#' + this.txtResponsibilities).addClass('invalid');
    }
};

Adecco.WorkHistory.removeResponibilityCss = function () {
    $('#' + this.txtResponsibilities).removeClass('invalid');
};

Adecco.WorkHistory.transformValidateSalary = function(input) {
    // special transform validate for salary masked input
    var theInput = input.masked.value;
    if (theInput.isEmpty()) {
        return true;
    }
    else {
        return theInput.isValidSalary()
    }
};

/****************************/
/* JobCategory functions */
/****************************/
if (!Adecco.JobCategory) {
    Adecco.JobCategory = {
        ddlCategory: null,
        txtLocation: null,
        lblCategoryMissingMessage:null,
        lblLocationMissingMessage:null
    };
}

Adecco.JobCategory.initialize = function(configuration) {
    /// <summary>
    ///     Initializes the Contct Info with dynamic control names.
    /// </summary>

    this.ddlCategory = configuration.category || null;
    this.txtLocation = configuration.location || null;
    this.lblCategoryMissingMessage = configuration.categoryMissingMessage || null;
    this.lblLocationMissingMessage = configuration.locationMissingMessage || null;

    Adecco.JobCategory.ResetCategorySelection();

    // Free up some memory
    delete Adecco.JobCategory.initialize;
};

Adecco.JobCategory.ResetCategorySelection = function() {
    //reset the selection
    $('#' + this.ddlCategory).val('-1');
};

Adecco.JobCategory.hideAllWarningMessages = function() {

    Adecco.JobCategory.setCategoryMissingMessageVisibility('hidden');
    Adecco.JobCategory.setLocationMissingMessageVisibility('hidden');
};

Adecco.JobCategory.setCategoryMissingMessageVisibility = function(visibility)
{
    var theControl;
    if (this.lblCategoryMissingMessage) {
        theControl = $('#' + this.lblCategoryMissingMessage);
        if (theControl) {
            theControl.css('visibility', visibility);
        }
    }
};

Adecco.JobCategory.setLocationMissingMessageVisibility = function(visibility)
{
    var theControl;
    if (this.lblLocationMissingMessage) {
        theControl = $('#' + this.lblLocationMissingMessage);
        if (theControl) {
            theControl.css('visibility', visibility);
        }
    }
};

Adecco.JobCategory.validate = function() {
    //validate the job category is selected and the zip code is entered
    var categoryDropDown;
    var locationTextbox;
    if (this.ddlCategory) {
        categoryDropDown = document.getElementById(this.ddlCategory);
    }
    if (this.txtLocation) {
        locationTextbox = document.getElementById(this.txtLocation.ClientControlId);
    }
    if (categoryDropDown) {
        if (categoryDropDown.value === '-1') {
            Adecco.JobCategory.setCategoryMissingMessageVisibility('visible');
            return false;
        }
    }
    if (locationTextbox) {
        if (!locationTextbox.value.isZipCode()) {
            Adecco.JobCategory.setLocationMissingMessageVisibility('visible');
            return false;
        }
    }
    return true;
};

/**********************************/
/* Contact Info-related functions */
/**********************************/
if (!Adecco.ContactInfo) {
    Adecco.ContactInfo = {
        txtFirstName: null,
        txtLastName: null,
        txtAddress1: null,
        txtCity: null,
        ddlState: null,
        txtZipCode: null,
        txtPrimaryPhoneAreaCode: null,
        txtPrimaryPhone1: null,
        txtPrimaryPhone2: null,
        snapImageId: null
    };
}

Adecco.ContactInfo.doCallbackReviewPersist = function ()
{
    setTimeout(function () { cbkContactInformationReview.callback("persist"); }, 500);
};

Adecco.ContactInfo.doCallbackEdit = function () {
    setTimeout(function () { cbkContactInformationEdit.callback(); }, 500);
};

Adecco.ContactInfo.onStateChange = function(sender) {
    var stateControl = $(sender);

    if (stateControl.val() === '') {
        stateControl.addClass('invalid');
    } else {
        stateControl.removeClass('invalid');
    }

    Adecco.ContactInfo.validate();
};

Adecco.ContactInfo.initialize = function(configuration) {
    /// <summary>
    ///     Initializes the Contct Info with dynamic control names.
    /// </summary>

    this.txtFirstName = configuration.firstName || null;
    this.txtLastName = configuration.lastName || null;
    this.txtAddress1 = configuration.address1 || null;
    this.txtCity = configuration.city || null;
    this.ddlState = configuration.state || null;
    this.txtZipCode = configuration.zip || null;
    this.txtPrimaryPhoneAreaCode = configuration.primaryPhoneAreaCode || null;
    this.txtPrimaryPhone1 = configuration.primaryPhone1 || null;
    this.txtPrimaryPhone2 = configuration.primaryPhone2 || null;
    this.txtSecondaryAreaCode = configuration.secondaryPhoneAreaCode || null;
    this.txtSecondaryPhone1 = configuration.secondaryPhone1 || null;
    this.txtSecondaryPhone2 = configuration.secondaryPhone2 || null;
    this.snapImageId = configuration.snapImageId || null;

    // Free up some memory
    delete Adecco.ContactInfo.initialize;
};

Adecco.ContactInfo.onPrimaryPhoneAreaCodeKeyUp = function() {
    if ($('#' + this.txtPrimaryPhoneAreaCode.masked.id).val().length >= 3) {
        $("#" + this.txtPrimaryPhone1.masked.id).focus();
    }
};

Adecco.ContactInfo.onPrimaryPhone1KeyUp = function() {
    if ($('#' + this.txtPrimaryPhone1.masked.id).val().length >= 3) {
        $("#" + this.txtPrimaryPhone2.masked.id).focus();
    }
};

Adecco.ContactInfo.onSecondaryAreaCodeKeyUp = function() {
    if ($('#' + this.txtSecondaryAreaCode.masked.id).val().length >= 3) {
        $("#" + this.txtSecondaryPhone1.masked.id).focus();
    }
};

Adecco.ContactInfo.onSecondaryPhone1KeyUp = function() {
    if ($('#' + this.txtSecondaryPhone1.masked.id).val().length >= 3) {
        $("#" + this.txtSecondaryPhone2.masked.id).focus();
    }
};


// client side contact info form validation
Adecco.ContactInfo.validateForm = function() {

    var jControl;

    // validate first name
    jControl = $('#' + this.txtFirstName.unmasked.id);
    if (jControl.val() === 'undefined' || !jControl.val().isNonEmpty()) {
        return false;
    }

    // validate last name
    jControl = $('#' + this.txtLastName.unmasked.id);
    if (jControl.val() === 'undefined' || !jControl.val().isNonEmpty()) {
        return false;
    }

    // validate address
    jControl = $('#' + this.txtAddress1.unmasked.id);
    if (jControl.val() === 'undefined' || !jControl.val().isNonEmpty()) {
        return false;
    }

    // validate city
    jControl = $('#' + this.txtCity.unmasked.id);
    if (jControl.val() === 'undefined' || !jControl.val().isNonEmpty()) {
        return false;
    }

    // validate state
    jControl = $('#' + this.ddlState);
    if (jControl.length === 0 || !jControl.val().isNonEmpty()) {
        return false;
    }

    // validate zip code
    jControl = $('#' + this.txtZipCode.unmasked.id);
    if (jControl.val() === 'undefined' || !jControl.val().isZipCode()) {
        return false;
    }

    // validate area code
    jControl = $('#' + this.txtPrimaryPhoneAreaCode.unmasked.id);
    if (jControl.val() === 'undefined' || !jControl.val().isThreeDigit()) {
        return false;
    }

    // validate phone number 1
    jControl = $('#' + this.txtPrimaryPhone1.unmasked.id);
    if (jControl.val() === 'undefined' || !jControl.val().isThreeDigit()) {
        return false;
    }

    // validate phone number 2
    jControl = $('#' + this.txtPrimaryPhone2.unmasked.id);
    if (jControl.val() === 'undefined' || !jControl.val().isFourDigit()) {
        return false;
    }

    // if we get here the form data is valid
    return true;
};

Adecco.ContactInfo.validate = function() {
    /// <summary>
    ///     Called by the container to validate controls.
    /// </summary>

    var controlsToValidate = [
        this.txtFirstName,
        this.txtLastName,
        this.txtAddress1,
        this.txtCity,
        this.ddlState,
        this.txtZipCode,
        this.txtPrimaryPhoneAreaCode,
        this.txtPrimaryPhone1,
        this.txtPrimaryPhone2
    ];

    // depending on the state of the inner snap, execute different validation code
    // if the inner snap is expanded(in edit mode), run the client side validation code
    // if the inner snap is collapsed(in preview mode), look at "isSessionDataValid"
    // isSessionDataValid is the result of the server-side validation code
    var isValid;
    if (snpContactInformation.get_isCollapsed()) {
        isValid = this.isSessionDataValid;
    }
    else {
        isValid = Adecco.Validation.validate(controlsToValidate);
    }

    // notify wizard when form is done
    this.updateContactIsDone(isValid);

    // remove "missing info" message and error summary if form is valid
    if (isValid === true) {
        this.updateMissingInfo(isValid);
        this.updateErrorSummary(isValid);

        // check review/edit profile if signup control is valid
        if (Adecco.SignUp.validateTermsOfUse() && Adecco.SignUp.validatePassword()) {
            Adecco.WizardProgress.OnModuleIsDone('reviewEditIsDone', true);
        }
    }

    return isValid;
};

Adecco.ContactInfo.updateContactIsDone = function (isDone) {
    Adecco.WizardProgress.OnModuleIsDone('contactInformationIsDone', isDone);
    Adecco.Ajax.updateSectionStatusImage('imgContactInfoState', isDone);
};

Adecco.ContactInfo.updateMissingInfo = function(isDone) {
    Adecco.Ajax.updateSectionStatus('divContactInfoMissingInfo', isDone);
};

Adecco.ContactInfo.updateErrorSummary = function(isDone) {
    if (isDone === true) {
        $('#divContactInfoErrorSummary').hide();
    }
};

Adecco.ContactInfo.updateContactInfoArrow = function() {
    Adecco.Ajax.updateSnapArrowImg(snpContactInformationOuter, this.snapImageId);
};

/***********************************/
/* ConfirmEmail-related functions */
/**********************************/
if (!Adecco.ConfirmEmail) {
    Adecco.ConfirmEmail = {
        txtEmailAddress: null,
        txtEmailAddressConfirm: null,
        txtInUseFlag: null
    };
}

Adecco.ConfirmEmail.initialize = function(configuration) {
    /// <summary>
    ///     Initializes the Confirm email with dynamic control names.
    /// </summary>

    this.txtEmailAddress = configuration.email || null;
    this.txtEmailAddressConfirm = configuration.emailConfirm || null;
    this.txtInUseFlag = configuration.inUseFlag || null;

    // Free up some memory
    delete Adecco.ConfirmEmail.initialize;
};

Adecco.ConfirmEmail.confirmEqual = function() {
    var isValid = false;
    
    if (this.txtEmailAddress && this.txtEmailAddressConfirm) {
        if (this.txtEmailAddress.masked && this.txtEmailAddressConfirm.masked) {
            var EmailAddress1 = jQuery.trim(this.txtEmailAddress.masked.value);
            var EmailAddress2 = jQuery.trim(this.txtEmailAddressConfirm.masked.value);
            isValid = (EmailAddress1 == EmailAddress2);
            return isValid;
        }
        }
    return isValid;
};

function CompareEmails(sender, args) {
    if(jQuery.trim(Adecco.ConfirmEmail.txtEmailAddress.masked.value) != "" && jQuery.trim(Adecco.ConfirmEmail.txtEmailAddressConfirm.masked.value) != "")
    {
        if(Adecco.ConfirmEmail.confirmEqual())
        {
            args.IsValid = true;
        }
        else
        {
            args.IsValid = false;
        }
     }
     else
     {
         args.IsValid = true;            
     }
};

Adecco.ConfirmEmail.resetErrorMessages = function () {
    $('#divConfirmEmailErrorSummaryMissing').hide();
    $('#divConfirmEmailErrorMissing').hide(); 
    $('#divConfirmEmailErrorSummaryMalformed').hide();
    $('#divConfirmEmailErrorMalformed').hide();             
    $('#divConfirmEmailErrorSummaryMismatch').hide();
    $('#divConfirmEmailErrorMismatch').hide();             
    $('#divConfirmEmailMissingInfo').css('visibility', 'hidden');
};


//TJF 2/19/09 Created trimWhiteSpace to take code from ConfirmEmail.validate and move it to this new method due to submission error on a new profile
Adecco.ConfirmEmail.trimWhiteSpace = function() {
    // trim the text in each textbox.


    if (this.txtEmailAddress && this.txtEmailAddress.get_text().length > 0) {
        /*  AA - 2/24/09: set_text() is currently throwing an exception, however it functions correctly.
        For the time being, the error will be caught to allow the rest of the application
        to function.
        */
        try {
            this.txtEmailAddress.set_text(jQuery.trim(this.txtEmailAddress.get_text()));
        }
        catch (e) {
            // do nothing here
        }
    }
    if (this.txtEmailAddressConfirm && this.txtEmailAddressConfirm.get_text().length > 0) {
        try {
            this.txtEmailAddressConfirm.set_text(jQuery.trim(this.txtEmailAddressConfirm.get_text()));
        }
        catch (e) {
            // do nothing here.
        }
    }
}

Adecco.ConfirmEmail.validate = function() {
    /// <summary>
    ///     Called by the container to validate controls.
    /// </summary>
    var isValid;
    
    
	//BK 3/3/09 No need for below code anymore
    /*
    var inUse;
    
    if (document.getElementById(this.txtInUseFlag) !== null) {
        inUse = document.getElementById(this.txtInUseFlag).value;
    }
    else {
        inUse = "false";
    }
    */
    
    Adecco.ConfirmEmail.resetErrorMessages();
    
    if (this.txtEmailAddress && this.txtEmailAddress.isValid() &&
        this.txtEmailAddressConfirm && this.txtEmailAddressConfirm.isValid() &&
        this.confirmEqual()) { //BK 3/3/09 Use to have:  && inUse =="false") {
            
            Adecco.ConfirmEmail.resetErrorMessages();
            isValid = true;
    }
    else {
        isValid = false;        
    }
    this.setConfirmEmailIsDone(isValid);
    return isValid;
};

Adecco.ConfirmEmail.setConfirmEmailIsDone = function(isDone) {
    Adecco.WizardProgress.OnModuleIsDone('confirmEmailIsDone', isDone);
    Adecco.Ajax.updateSectionStatusImage('imgConfirmEmailState', isDone);
};

Adecco.ConfirmEmail.validateOnSubmit = function() {
    var divImage = document.getElementById('imgConfirmEmail');
    if (divImage === null) {
        return true;
    }

    Adecco.ConfirmEmail.resetErrorMessages();

    var isValid = Adecco.ConfirmEmail.validate();
    if (isValid === false) {
        if (this.txtEmailAddressConfirm.isEmpty() || this.txtEmailAddressConfirm.isEmpty()) {
            // one of them is empty
            $('#divConfirmEmailErrorMissing').show();
        }
        else if (this.txtEmailAddress.isValid() === false || this.txtEmailAddressConfirm.isValid() === false) {
            // malformed
            $('#divConfirmEmailErrorMalformed').show();
        }
        else if (!this.confirmEqual()) {
            // must be a mismatch
            $('#divConfirmEmailErrorMismatch').show();
        }
        $('#divConfirmEmailErrorSummaryMissing').show();
        $('#divConfirmEmailMissingInfo').css('visibility', 'visible');
    }
    return isValid;
};

/****************************/
/* Branch-related functions */
/****************************/
if (!Adecco.BranchOffice) {
    Adecco.BranchOffice = {
        ddlOffices: null,
        txtBranchId: null,
        txtCity: null,
        ddlState: null,
        txtZip: null,
        anchMapThis: null 
    };
}

Adecco.BranchOffice.showBranchOfficeMap = function (element) {
    var ddlControl = document.getElementById(element);
    var selectedText, i;
    
    for (i = 0; i < ddlControl.length; i++)
    {
       if (ddlControl.options[i].selected === true)
       {
           selectedText = ddlControl.options[i].text;
           break;
       }
    }
    
    var htmlsafe = selectedText.replace(/ /g, '%20');
    window.open ('http://maps.live.com?where1='+htmlsafe);  
};

Adecco.BranchOffice.disableControls = function() 
{
    var ctlLen = arguments.length;
    var ctlTemp, i;
    for (i = 0; i < ctlLen; i++) {
        ctlTemp = $('#' + arguments[i]);
        if (ctlTemp !== null) {
            Adecco.Ajax.DisableControl(ctlTemp);
        }
    }
};

Adecco.BranchOffice.enableControls = function() 
{
    var ctlLen = arguments.length;
    var ctlTemp, i;
    for (i = 0; i < ctlLen; i++) {
        ctlTemp = $('#' + arguments[i]);
        if (ctlTemp !== null) {
            Adecco.Ajax.EnableControl(ctlTemp);
        }
    }
};

Adecco.BranchOffice.onBranchIdChange = function() 
{
    //var mutuallyExclusiveControls = [this.txtCity, this.ddlState, this.txtZip, this.ddlOffices];
    var mutuallyExclusiveControls = [this.ddlOffices];
    
    if ($('#' + this.txtBranchId).val() !== '') {
        this.disableControls.apply(this, mutuallyExclusiveControls);
    } else {
        this.enableControls.apply(this, mutuallyExclusiveControls);
        //Adecco.BranchOffice.onCityOrStateChange();
        //Adecco.BranchOffice.onZipChange();
    }
};

Adecco.BranchOffice.onOfficeChange = function() {
    /* var mutuallyExclusiveControls = [this.txtBranchId, this.txtCity, this.txtZip, this.ddlState];

    if ($('#' + this.ddlOffices).val() !== '-1') {
    this.disableControls.apply(this, mutuallyExclusiveControls);
    } else {
    this.enableControls.apply(this, mutuallyExclusiveControls);
    Adecco.BranchOffice.onCityOrStateChange();
    Adecco.BranchOffice.onZipChange();
    }  */

    if ($('#' + this.ddlOffices).val() === '-1') {
        //hide map location link
        $('#' + this.anchMapThis).hide();
    }
    else {
        //show map location link
        $('#' + this.anchMapThis).show();
    }
};

Adecco.BranchOffice.onCityOrStateChange = function() {
    var mutuallyExclusiveControls = [this.txtZip];

    if ($('#' + this.txtCity).val() !== '' || $('#' + this.ddlState).val() !== '') {
        this.disableControls.apply(this, mutuallyExclusiveControls);
    } else {
        if ($('#' + this.ddlOffices).val() !== '-1') {
            this.enableControls.apply(this, mutuallyExclusiveControls);
        }
        else {
            this.enableControls.apply(this, mutuallyExclusiveControls);
        }
    }
};

Adecco.BranchOffice.onZipChange = function ()
{
    var mutuallyExclusiveControls = [this.txtCity, this.ddlState];
    
    if ($('#' + this.txtZip).val() !== '') {
        this.disableControls.apply(this, mutuallyExclusiveControls);
    } else {
        if ($('#' + this.txtZip).val() !== '-1') {
        this.enableControls.apply(this, mutuallyExclusiveControls);
        }
        else {
            this.enableControls.apply(this, mutuallyExclusiveControls);
        }
    }
};

Adecco.BranchOffice.registerEventHandler_ddlOffices = function() {
    if (this.ddlOffices) {
        $('#' + this.ddlOffices).change(function() { Adecco.BranchOffice.onOfficeChange(); });

        // Adding an on keyup because the user might be changing values via the keyboard.
        $('#' + this.ddlOffices).keyup(function() { Adecco.BranchOffice.onOfficeChange(); });

        Adecco.BranchOffice.onOfficeChange();
    }

};

Adecco.BranchOffice.registerEventHandler_txtBranchId = function() {
    if (this.txtBranchId) {
        $('#' + this.txtBranchId).keyup(function() { Adecco.BranchOffice.onBranchIdChange(); });
    }
};

Adecco.BranchOffice.registerEventHandlers = function() {
    
    Adecco.BranchOffice.registerEventHandler_txtBranchId();

    if (this.txtZip) {
        $('#' + this.txtZip).keyup(function() { Adecco.BranchOffice.onZipChange(); });
    }

    if (this.txtCity) {
        $('#' + this.txtCity).keyup(function() { Adecco.BranchOffice.onCityOrStateChange(); });
    }

    Adecco.BranchOffice.registerEventHandler_ddlOffices();

    if (this.ddlState) {
        $('#' + this.ddlState).change(function() { Adecco.BranchOffice.onCityOrStateChange(); });

        // Adding an on keyup because the user might be changing values via the keyboard.
        $('#' + this.ddlState).keyup(function() { Adecco.BranchOffice.onCityOrStateChange(); });
    }

    // Free up some memory
    //delete Adecco.BranchOffice.registerEventHandlers;
};

Adecco.BranchOffice.initialize = function(configuration) {
    this.ddlOffices = configuration.ddlOffices || null;
    this.txtBranchId = configuration.branchId || null;
    this.txtCity = configuration.city || null;
    this.ddlState = configuration.state || null;
    this.txtZip = configuration.zip || null;
    this.anchMapThis = configuration.anchMapThis || null;

    $(function() { Adecco.BranchOffice.registerEventHandlers(); });
    $(function() { Adecco.BranchOffice.onOfficeChange(); });
    //$(function() { Adecco.BranchOffice.onBranchIdChange(); });

    // Free up some memory
    delete Adecco.BranchOffice.initialize;
};

Adecco.BranchOffice.validate = function() {
    if (this.txtBranchId && this.ddlOffices) {

        var inputBranchIdControl = $('#' + this.txtBranchId)[0];
        var ddlOfficeControl = $('#' + this.ddlOffices)[0];
        var isDone = inputBranchIdControl.value !== '' || ddlOfficeControl.value !== "-1";

        Adecco.WizardProgress.OnModuleIsDone('branchOfficeIsDone', isDone);
        return isDone;
    }
    return true;
};

/****************************/
/* Skills-related functions */
/****************************/
if (!Adecco.Skills) {
    Adecco.Skills = {
        lastSearchCriteria: 'ddl',
        timerID: 0,
        myCallback: null,
        collapseHeaderCallback: null,
        jobSkillsCount: 1, // set to 1 so that validate returns true when user control is not loaded
        snapImageId: null,

        initialize: function(configuration) {
            this.jobSkillsCount = configuration.jobSkillsCount || null;
            this.snapImageId = configuration.snapImageId || null;
        },

        validate: function() {
            if (this.jobSkillsCount > 0) {
                return true;
            }
            else {
                return false;
            }
        },

        updateMissingInfo: function(isDone) {
            Adecco.Ajax.updateSectionStatus('divSkillsMissingInfo', isDone);
        },

        updateErrorSummary: function(isDone) {
            if (isDone === true) {
                $("#divSkillsErrorSummary").hide();
            }
        },

        updateSkillsArrow: function() {
            if (snapSkillSection) {
                Adecco.Ajax.updateSnapArrowImg(snapSkillSection, this.snapImageId);
            }
        },

        searchSkills: function(cback, skillCatId) {
            var selectSkillCat = document.getElementById(skillCatId);
            var selectedSkillCatId = selectSkillCat.value;

            cback.callback(selectedSkillCatId);
        },

        deleteSkillGrid: function(gridId, rowId) {
            gridId.deleteItem(gridId.getItemFromClientId(rowId));
            gridId.callback();
            if (gridId.get_recordCount() === 0) {
                Adecco.WizardProgress.OnModuleIsDone('skillIsDone', false);
            }
        },

        insertSkillGrid: function(gridId, optionValue, optionText) {
            var myAddedRow = gridId.get_table().addEmptyRow();
            // set the value of the empty row
            myAddedRow.setValue(0, optionValue, 0);
            myAddedRow.setValue(1, optionText, 0);
            myAddedRow.setValue(2, 'category', 0);
            myAddedRow.setValue(3, 'new row', 0);
            var myAddedRowId = myAddedRow.get_clientId();
            var newitem = gridId.getItemFromClientId(myAddedRowId);
        },

        addSkillsToGrid: function(listboxId, gridId) {
            var ltboxResults = document.getElementById(listboxId);
            var item, i;
            for (i = 0; i < ltboxResults.length; i++) {
                item = ltboxResults.options[i];
                if (item.selected) {
                    this.insertSkillGrid(gridId, item.value, item.text);
                }
            }

            Adecco.Ajax.doCallback(gridId);
        },

        toggleSection: function(snapID, cbackHeader) {
            // Get the current state of the snap
            var snapState = snapID.get_isCollapsed();
            if (snapState === true) {
                // is collapsed
                snapID.expand();
            } else {
                // is expanded
                snapID.collapse();
                this.collapseHeaderCallback = cbackHeader;
                this.timerID = setTimeout(function() { cbackHeader.callback(); }, 1000);
            }
        },

        cbackHeaderTimer: function() {
            this.collapseHeaderCallback.callback();
        },

        isSkillsComplete: function(skillGridID) {
            /// <summary>
            ///     Checks the completeness of the section.
            /// </summary>
            var imgState;
            var bGridComplete = false;
            var isDone;

            if (skillGridID.recordNumber !== null &&
                skillGridID.get_recordCount() > 0) {
                bGridComplete = true;
                this.jobSkillsCount = skillGridID.get_recordCount();
            }

            isDone = (bGridComplete === true);
            Adecco.Ajax.updateSectionStatusImage('imgSkillState', isDone);
            Adecco.WizardProgress.OnModuleIsDone('skillIsDone', bGridComplete);

            // update "missing info" error message and error summary
            if (isDone === true) {
                this.updateMissingInfo(isDone);
                this.updateErrorSummary(isDone);
            }
            return isDone;
        }
    };
}

Adecco.Skills.canDeleteSkillsInGrid = function() {
    //if is more than one skills, allow delete, else, not delete and show message
    if ($('.MySkillsItem').length > 1) {
        $('#divSkillSetCannotDeleteMessage').hide();
        return true;
    }
    else {
        $('#divSkillSetCannotDeleteMessage').show();
        return false;
    }
};

Adecco.Skills.resetErrorMessage = function() {
    $('#divSkillSetCannotDeleteMessage').hide();
}
/********************************/
/* Other info-related functions */
/********************************/
if (!Adecco.OtherInfo) {
    Adecco.OtherInfo = {};
}

Adecco.OtherInfo.onOtherInformationSnapCollapsed = function() {
    //cbkOtherInformationEdit.callback('collapse');
    //setTimeout(function() { cbkOtherInformationReview.callback(); }, 500);
    setTimeout(function() { cbkOtherInformationReview.callback('persist'); }, 500);
};

Adecco.OtherInfo.onOtherInformationSnapExpanded = function () {
    setTimeout(function () { cbkOtherInformationEdit.callback('expand'); }, 500);
};

Adecco.OtherInfo.isOtherInfoComplete = function (isDone) {
    Adecco.Ajax.updateSectionStatusImage('imgOtherInfoState', isDone);
};

Adecco.OtherInfo.isNonEmpty = function isNonEmpty(id) {
    // get the text box with the given id
    var jTextbox = $("#" + id);

    // make sure the jquery selector returned something
    if (jTextbox.length > 0) {
        // if textbox is empty, then set the textbox's class to invalid
        if (jTextbox[0].value && jTextbox[0].value.isNonEmpty()) {
            jTextbox.removeClass("invalid");
        }
        else {
            jTextbox.addClass("invalid");
        }
    }
};

Adecco.OtherInfo.isInteger = function isInteger(id) {
    // get the text box with the given id
    var jTextbox = $("#" + id);

    // make sure the jquery selector returned something
    if (jTextbox.length > 0) {
        // if textbox is empty, then set the textbox's class to invalid
        if (jTextbox[0].value && jTextbox[0].value.isInteger()) {
            jTextbox.removeClass("invalid");
        }
        else {
            jTextbox.addClass("invalid");
        }
    }
};

Adecco.OtherInfo.isValidDate = function isValidDate(input) {
    // get the birthdate textbox
    var jBirthDate = $('#' + input.masked.id);

    // since birth date is not a required field
    // if we can't find the textbox or textbox is empty, return true
    if (jBirthDate.length === 0 || jBirthDate.val().length === 0) {
        return true;
    }

    // validate birthdate
    return jBirthDate.val().isValidDate();
}

Adecco.OtherInfo.initialize = function(configuration) {
    /// <summary>
    ///     Initializes the Other Information with dynamic control names.
    /// </summary>

    this.txtFullName = configuration.fullName || null;
    this.txtPrimaryAreaCode = configuration.primaryAreaCode || null;
    this.txtPrimaryTelNum1 = configuration.primaryTelNum1 || null;
    this.txtPrimaryTelNum2 = configuration.primaryTelNum2 || null;
    this.txtAltAreaCode = configuration.altAreaCode || null;
    this.txtAltTelNum1 = configuration.altTelNum1 || null;
    this.txtAltTelNum2 = configuration.altTelNum2 || null;
    this.txtBirthdate = configuration.birthDate || null;
    this.snapImageId = configuration.snapImageId || null;

    // Free up some memory
    delete Adecco.OtherInfo.initialize;
};

Adecco.OtherInfo.validate = function() {
    /// <summary>
    ///     Called by the container to validate controls.
    /// </summary>

    var controlsToValidate = [
        this.txtFullName,
        this.txtPrimaryAreaCode,
        this.txtPrimaryTelNum1,
        this.txtPrimaryTelNum2,
        this.txtAltAreaCode,
        this.txtAltTelNum1,
        this.txtAltTelNum2
    ];

    var isValid = Adecco.Validation.validate(controlsToValidate);
    this.updateOtherInfoIsDone(isValid);
    if (isValid === true) {
        this.updateMissingInfo(isValid);
    }
    return isValid;
};

Adecco.OtherInfo.validateOnAction = function() {
    // get the birthdate textbox
    var jBirthDate = $('#' + this.txtBirthdate.unmasked.id);

    // since birth date is not a required field
    // if we can't find the textbox or textbox is empty, return true
    if (jBirthDate.length === 0 || jBirthDate.val().length === 0) {
        return true;
    }

    // validate birthdate
    return jBirthDate.val().isValidDate();
};

Adecco.OtherInfo.updateOtherInfoIsDone = function(isDone) {
    Adecco.Ajax.updateSectionStatusImage('imgOtherInfoState', isDone);
};

Adecco.OtherInfo.updateOtherInfoArrow = function() {
    Adecco.Ajax.updateSnapArrowImg(snpOtherInformationOuter, this.snapImageId);
};

Adecco.OtherInfo.updateMissingInfo = function(isDone) {
    Adecco.Ajax.updateSectionStatus('divOtherInfoMissingInfo', isDone);
};

/*************************************/
/* Job Requirement-related functions */
/*************************************/
if (!Adecco.JobReq) {
    Adecco.JobReq = {
        txtDaysOfNotice: null,
        txtDirectHireRate: null,
        txtTempHireRate: null,
        txtPreferredWorkLocation: null,
        txtMaxTravelDistance: null,
        txtMaxTravelTime: null    
    };
}

Adecco.JobReq.onSnapCollapsed = function () {
    cbkJobRequirementsEdit.callback('collapse');
    setTimeout(function () { cbkJobRequirementsReview.callback(); }, 500);
};

Adecco.JobReq.onSnapExpanded = function () {
    setTimeout(function () { cbkJobRequirementsEdit.callback('expand'); }, 500);
};

Adecco.JobReq.initialize = function(configuration) {
    /// <summary>
    ///     Initializes the Job Requirements with dynamic control names.
    /// </summary>

    this.txtDaysOfNotice = configuration.daysOfNotice || null;
    this.txtDirectHireRate = configuration.directHireRate || null;
    this.txtTempHireRate = configuration.tempHireRate || null;
    this.txtPreferredWorkLocation = configuration.preferredWorkLocation || null;
    this.txtMaxTravelDistance = configuration.maxTravelDistance || null;
    this.txtMaxTravelTime = configuration.maxTravelTime || null;

    // initialize snap arrow image
    Adecco.JobReq.updateArrow();

    // Free up some memory
    delete Adecco.JobReq.initialize;
};

Adecco.JobReq.validate = function() {
    /// <summary>
    ///     Called by the container to validate controls.
    /// </summary>

    var controlsToValidate = [
        this.txtDaysOfNotice,
        this.txtDirectHireRate,
        this.txtTempHireRate,
        this.txtPreferredWorkLocation,
        this.txtMaxTravelDistance,
        this.txtMaxTravelTime
    ];

    var isValid = Adecco.Validation.validate(controlsToValidate);
    this.updateJobReqIsDone(isValid);
    if (isValid === true) {
        this.updateMissingInfo(isValid);
    }    
    
    return isValid;
};

Adecco.JobReq.validateForm = function() {
    var fromMonths, toMonths, i;
    var fromDate, toDate;
    var fromMonth, fromYear, toMonth, toYear;
    var container = 'job-req-edit-container';
    var isValid = this.validate();

    // Parse "From" date
    fromMonths = $('#' + container + ' .from-month option');
    fromYear = $('#' + container + ' .from-year');
    fromYear = fromYear.val();

    for (i = 0; i < fromMonths.length; i++) {
        if (fromMonths[i].selected) {
            fromMonth = i;
            break;
        }
    }
    fromDate = new Date(fromYear, fromMonth, 1);

    // Parse "To" date
    toMonths = $('#' + container + ' .to-month option');
    toYear = $('#' + container + ' .to-year');
    toYear = toYear.val();

    for (i = 0; i < toMonths.length; i++) {
        if (toMonths[i].selected) {
            toMonth = i;
            break;
        }
    }
    toDate = new Date(toYear, toMonth, 1);

    // Compare From to To date.
    if (fromDate <= toDate) {
        $('.jobReqDatesIncorrectMessage').hide();
        isValid = isValid && true;
    } else {
        $('.jobReqDatesIncorrectMessage').show();
        isValid = false;
    }

    return isValid;
};

Adecco.JobReq.updateJobReqIsDone = function(isDone) {
    Adecco.Ajax.updateSectionStatusImage('imgJobReqState', isDone);
};


Adecco.JobReq.updateArrow = function() {
    Adecco.Ajax.updateSnapArrowImg(snpJobRequirementsOuter, "jobReqSnapImage");
};

Adecco.JobReq.updateMissingInfo = function(isDone) {
    Adecco.Ajax.updateSectionStatus('divJobReqMissingInfo', isDone);
};

/*************************************/
/* Sign up control related functions */
/*************************************/
if (!Adecco.SignUp) {
    Adecco.SignUp = {
        MINIMUM_PASSWORD_LENGTH: 6,
        MAXIMUM_PASSWORD_LENGTH: 14,
        txtPassword: null,
        txtPasswordConfirm: null,
        cbxTermsOfUse: null
    };
}

Adecco.SignUp.initialize = function(configuration) {
    /// <summary>
    ///     Initializes the sign up control with dynamic control names.
    /// </summary>
    this.txtPassword = configuration.password || null;
    this.txtPasswordConfirm = configuration.passwordConfirm || null;
    this.cbxTermsOfUse = configuration.termsOfUse || null;

    // Free up some memory
    delete Adecco.SignUp.initialize;
};

Adecco.SignUp.notifyTermsOfUseWizard = function() {
    // notify the wizard terms of use is accepted
    var isDone = Adecco.SignUp.validateTermsOfUse();
    Adecco.WizardProgress.OnModuleIsDone('agreeToTermsIsDone', isDone);
    if (isDone) {
        //check off "Review/Edit Populated Fields" steps
        if (Adecco.ContactInfo.validate() && Adecco.WorkHistory.validate() && Adecco.Education.validate()) {
            Adecco.WizardProgress.OnModuleIsDone('reviewEditIsDone', true);
        }
    }

    // turn off the missing info tag
    if (isDone === true) {
        Adecco.SignUp.resetTermsOfUseErrorMessages();
    }

    if (Adecco.SignUp.validatePassword() === true) {
        Adecco.SignUp.resetPasswordErrorMessages();
    }

    if (isDone === true && Adecco.SignUp.validatePassword() === true) {
        Adecco.SignUp.resetHeaderErrorMessages();
    }
    return isDone;
};

Adecco.SignUp.validateTermsOfUse = function() {
    var checkbox = document.getElementById(this.cbxTermsOfUse);
    // if we can't find the checkbox, there's no point validating the value
    // just return true to caller
    if (checkbox === null) {
        return true;
    }

    var isDone;
    if (checkbox && checkbox.checked) {
        isDone = true;
    }
    else {
        isDone = false;
    }
    return isDone;
};


Adecco.SignUp.notifyPasswordWizard = function() {

    var isValid = Adecco.SignUp.validatePassword();
    Adecco.WizardProgress.OnModuleIsDone('choosePasswordInfoIsDone', isValid);

    if (isValid === true) {
        Adecco.SignUp.resetPasswordErrorMessages();
        //check off "Review/Edit Populated Fields" steps
        if (Adecco.ContactInfo.validate() && Adecco.WorkHistory.validate() && Adecco.Education.validate()) {
            Adecco.WizardProgress.OnModuleIsDone('reviewEditIsDone', true);
        }
    }

    if (Adecco.SignUp.validateTermsOfUse() === true) {
        Adecco.SignUp.resetTermsOfUseErrorMessages();
    }

    if (isValid === true && Adecco.SignUp.validateTermsOfUse() === true) {
        // turn off the missing info tag
        Adecco.SignUp.resetHeaderErrorMessages();
    }
    return isValid;
};

Adecco.SignUp.validatePassword = function() {

    // if we can't find the password boxes, there's not point validating the values
    // just return true to caller
    if (!document.getElementById(this.txtPassword) || !document.getElementById(this.txtPasswordConfirm)) {
        return true;
    }

    // retrieve the password values
    var password = $('#' + this.txtPassword).val();
    var confirm = $('#' + this.txtPasswordConfirm).val();

    var isValid = true;
    // validate passwords
    if (password && password.isNonEmpty() && password === confirm &&
        password.length >= this.MINIMUM_PASSWORD_LENGTH &&
        password.length <= this.MAXIMUM_PASSWORD_LENGTH) {
        isValid = true;
    }
    else {
        isValid = false;
    }
    return isValid;
};

Adecco.SignUp.validateOnSubmit = function () {
    var imgSignup = document.getElementById('imgSignup');
    if (imgSignup === null) {
        return true;
    }
    
    var isValid = Adecco.SignUp.validate();
 
    // reset all the errors.
    Adecco.SignUp.resetHeaderErrorMessages();
    Adecco.SignUp.resetPasswordErrorMessages();
    Adecco.SignUp.resetTermsOfUseErrorMessages();
 
    if (isValid === false)
    {
        $('#divSignUpMissingInfo').css('visibility', 'visible');
        
        // determine what is wrong.
        var password = $('#' + this.txtPassword).val();
        var confirm = $('#' + this.txtPasswordConfirm).val();
        
        if (Adecco.SignUp.validPasswordLength(password.length) === false ||
            Adecco.SignUp.validPasswordLength(confirm.length) === false )  {
            $('#divPasswordErrorInvalid').show();
            }
        else if (password !== confirm) {
            $('#divPasswordErrorMismatch').show();
        }
        
        if (Adecco.SignUp.validateTermsOfUse() === false) {
            $('#divTermsOfUseErrorMessage').show();
        }        
    }
        
    
    return isValid;
};

Adecco.SignUp.validate = function() {
    var missingInfo = document.getElementById('divSignUpMissingInfo');
    if (!missingInfo) {
        return true;
    }

    var isValid = true;
    this.notifyTermsOfUseWizard();
    var isPasswordValid = this.notifyPasswordWizard();
    if ($("#" + this.txtPassword).length > 0) {
        isValid = isPasswordValid;
    }
    else {
        isValid = true;
    }

    isValid = isValid && Adecco.SignUp.validateTermsOfUse();

    return isValid;
};

Adecco.SignUp.validPasswordLength = function (passwordLen) {
    if (passwordLen >= this.MINIMUM_PASSWORD_LENGTH &&
        passwordLen <= this.MAXIMUM_PASSWORD_LENGTH )  {
        // valid password
        return true;
    }
    else {
        // invalid password
        return false;
    }
};

/* change the CSS */
Adecco.SignUp.changePasswordCSS = function () {
    var password = $('#' + this.txtPassword).val();
    var confirm = $('#' + this.txtPasswordConfirm).val();
        
    if (Adecco.SignUp.validPasswordLength(password.length) )  {
        // valid password
        $('#' + this.txtPassword).removeClass('invalid');
    }
    else {
        // invalid password
        $('#' + this.txtPassword).addClass('invalid');
    }

    if ( Adecco.SignUp.validPasswordLength (confirm.length))  {
        // valid password format
        if (password === confirm ) {
            // mismatch password
            $('#' + this.txtPasswordConfirm).removeClass('invalid');
        }
        else {
            $('#' + this.txtPasswordConfirm).addClass('invalid');
        }
    }
    else {
        // invalid password
        $('#' + this.txtPasswordConfirm).addClass('invalid');
    }    
};

Adecco.SignUp.resetHeaderErrorMessages = function () {
    $('#divSignUpMissingInfo').css('visibility', 'hidden');
};

Adecco.SignUp.resetPasswordErrorMessages = function () {
    $('#divSignupErrorSummary').hide();
    $('#divPasswordErrorMismatch').hide();
    $('#divPasswordErrorInvalid').hide();
};

Adecco.SignUp.resetTermsOfUseErrorMessages = function () {
    $('#divTermsOfUseErrorMessage').hide();
};

/*****************************************/
/* Quick Skill control related functions */
/*****************************************/
if (!Adecco.QuickSkill) {
    Adecco.QuickSkill = {};
}

Adecco.QuickSkill.initialize = function(configuration) {
    this.selectSkillResults = configuration.selectSkills || null;
    this.snapImageId = configuration.snapImageId || null;

    // Free up some memory
    delete Adecco.QuickSkill.initialize;
};

Adecco.QuickSkill.doQuickSkillCallback = function(ddlObject) {
    // notify wizard that skills is not selected
    if (Adecco.WizardProgress.OnModuleIsDone) {
        Adecco.WizardProgress.OnModuleIsDone('skillIsDone', false);
        //Adecco.WizardProgress.OnModuleIsDone('reviewEditIsDone', false);
    }

    // do the callback
    var selectedvalue = ddlObject.value;
    if (cbkQuickSkills) {
        cbkQuickSkills.callback(selectedvalue);
    }
};

Adecco.QuickSkill.validate = function() {

    var jListBox = $("#" + this.selectSkillResults);

    // if list box does not exisy, control is not on the page
    // return true to not invalidate the submit
    if (jListBox.length === 0) {
        return true;
    }

    // check if the selected index is set
    var selectedIndex = jListBox.attr("selectedIndex");

    var isValid = false;
    if (selectedIndex >= 0) {
        isValid = true;
    }
    else {
        isValid = false;
    }

    Adecco.WizardProgress.OnModuleIsDone('skillIsDone', isValid);

    if (isValid === true) {
        //check off "Review/Edit Populated Fields" steps
        if (Adecco.ContactInfo.validate() && Adecco.WorkHistory.validate() && Adecco.Education.validate()) {
            Adecco.WizardProgress.OnModuleIsDone('reviewEditIsDone', true);
        }
        Adecco.QuickSkill.updateMissingInfo(isValid);
        Adecco.QuickSkill.updateErrorSummary(isValid);
    }

    return isValid;
};

Adecco.QuickSkill.saveSelectedSkills = function (listboxId, cbkId) {
    var ltboxResults = document.getElementById(listboxId);
    var item, i;
    var selected = '';
    for (i = 0; i < ltboxResults.length; i++) {
        item = ltboxResults.options[i];
        if (item.selected) {
           if (selected.length > 0) {
              selected = selected + ',';
           }
           selected = selected + item.value;
        }
    }

    cbkId.callback(selected);
};

Adecco.QuickSkill.updateQuickSkillArrow = function() {
    Adecco.Ajax.updateSnapArrowImg(snpQuickSkills, this.snapImageId);
};

Adecco.QuickSkill.updateMissingInfo = function(isDone) {
    Adecco.Ajax.updateSectionStatus('divQuickSkillsMissingInfo', isDone);
};

Adecco.QuickSkill.updateErrorSummary = function(isDone) {
    if (isDone === true) {
        $('#divSkillsErrorSummary').hide();
    }
};

/*******************************************************/
/* Job Eligibility control related functions */
/*******************************************************/
 
if (!Adecco.JobEligibility) {
    Adecco.JobEligibility = {};
}


Adecco.JobEligibility.initialize = function(configuration) {
    this.txtExpirationDate = configuration.txtExpirationDate || null;
    this.ddlSecurityClearanceType = configuration.ddlSecurityClearanceType || null;
};

Adecco.JobEligibility.validate = function() {

    var ddl = $("#" + this.ddlSecurityClearanceType);
    if(ddl.length > 0 && ddl[0].value !== "None"){
        var controlsToValidate = [this.txtExpirationDate];
        var isValid = (Adecco.Validation.validate(controlsToValidate) && Adecco.JobEligibility.validateOnAction());
        return isValid;
    }
    return true;
};

Adecco.JobEligibility.validateOnAction = function() {
    var jExpDate = $('#' + txtExpirationDate.masked.id);

    if (jExpDate.val().length === 0) {
        return true;
    }
    else {
        if (jExpDate.val() && jExpDate.val().isValidDate() &&
                Adecco.Validation.isOnOrAfterDate(jExpDate.val(), Adecco.minDBDateString)) {
            return true;
        }
    }
    return false;
};

/*******************************************************/
/* Job Apply Wizard Progress control related functions */
/*******************************************************/
if (!Adecco.WizardProgress) {
    Adecco.WizardProgress = { };
}

Adecco.WizardProgress.Initialize = function (divId, offset, interval) {
    
    //define universal reference to "jobApplyWizardDiv"
    this.wizardProgressDiv = $('#' + divId)[0]; // document.all? document.all.jobApplyWizardDiv : document.getElementById(divId);
    this.scrollBuffer = offset;

    //define reference to the body object in IE
    this.ieBody = (document.compatMode && document.compatMode != "BackCompat")? document.documentElement : document.body;

    setInterval(function () { Adecco.WizardProgress.SetPosition(); }, interval);
};

Adecco.WizardProgress.SetPosition = function () {

    //define scroll top point
    var documentScrollOffset = document.all? this.ieBody.scrollTop : pageYOffset;
    // the distance from window top to our div
    
    //if the user is using IE 4+ or Firefox/ NS6+
    if (document.all || document.getElementById){                                
        this.wizardProgressDiv.style.top = (documentScrollOffset <= this.scrollBuffer ? 0 : documentScrollOffset - this.scrollBuffer) + "px";
    }
};

Adecco.WizardProgress.OnModuleIsDone = function(eventKey, value)
{
    try
    {        
        var key;
        
        switch(eventKey)
        {
            case "confirmEmailIsDone":
                Adecco.WizardProgress.UpdateStepIsDone("JobApplyWizardStep1", value);
                Adecco.WizardProgress.UpdateStepIsDone("JobApplyWizardStep13", value);
                break;
            case "reviewEditIsDone":
                Adecco.WizardProgress.UpdateStepIsDone("JobApplyWizardStep3", value);
                Adecco.WizardProgress.UpdateStepIsDone("JobApplyWizardStep4", value);
                break;
            case "contactInformationIsDone":
                Adecco.WizardProgress.UpdateStepIsDone("JobApplyWizardStep2", value);
                break;
            case "workHistoryIsDone":
                Adecco.WizardProgress.UpdateStepIsDone("JobApplyWizardStep5", value);
                break;
            case "educationIsDone":
                Adecco.WizardProgress.UpdateStepIsDone("JobApplyWizardStep7", value);
                break;
            case "skillIsDone":
                Adecco.WizardProgress.UpdateStepIsDone("JobApplyWizardStep6", value);
                break;
            case "choosePasswordInfoIsDone":
                Adecco.WizardProgress.UpdateStepIsDone("JobApplyWizardStep10", value);
                break;
            case "agreeToTermsIsDone":
                Adecco.WizardProgress.UpdateStepIsDone("JobApplyWizardStep11", value);
                break;
            case "branchOfficeIsDone":
                Adecco.WizardProgress.UpdateStepIsDone("JobApplyWizardStep14", value);
                break;
        }
    }
    catch(e)
    {
        e.message = " Adecco.WizardProgress.OnModuleIsDone" + e.mesage;
        throw e;
    }
};

Adecco.WizardProgress.UpdateStepIsDone = function (key, value)
{
    if (window.keyToClientId && keyToClientId[key])
    {
        var image = $('#' + keyToClientId[key].toString())[0];

        if (image)
        {            
            image.src = value ? Adecco.Ajax.images.sectionComplete : Adecco.Ajax.images.sectionIncomplete;
        }
    }
};

/***************************************/
/* Profile container-related functions */
/***************************************/
if (!Adecco.Profile) {
    Adecco.Profile = {
        validationMessage : null
    };
}

Adecco.Profile.evalWorkEligbilityAnswers = function (authYes, authNo, over18Yes, over18No, transportYes, transportNo, buttonId)
{
    var selectedCount = 0, okButton;
    var numberOfItemsToProceed = 3;
    
    if(authYes.checked || authNo.checked)
    {
        selectedCount++;
    }

    if(over18Yes.checked || over18No.checked)
    {
        selectedCount++;
    }
    
    if(transportYes.checked || transportNo.checked)
    {
        selectedCount++;
    }
    
    if (typeof buttonId === "string") {
        okButton = $('#' + buttonId);
    } else {
        okButton = $(buttonId);
    }    
    
    if (selectedCount >= numberOfItemsToProceed)
    {
        okButton.removeAttr('disabled');
        okButton.attr('src', Adecco.Ajax.images.continueEnabled);
    }
    else
    {
        okButton.attr('disabled', 'disabled');
        okButton.attr('src', Adecco.Ajax.images.continueDisabled);
    }
};

Adecco.Profile.submitEligibility = function (authYes, authNo, over18Yes, over18No, transportYes, transportNo, callbackControl)
{
    var isAuthorized = false;
    var isAdult = false;
    var isTransportReliable = false;
    
    if (typeof callbackControl === 'string') {
        callbackControl = window[callbackControl];
    }
    
    isAuthorized = authYes && authYes.checked;
    isAdult = over18Yes && over18Yes.checked;
    isTransportReliable = transportYes && transportYes.checked;
    
    callbackControl.callback(isAuthorized, isAdult, isTransportReliable);
};

Adecco.Profile.validateOnLoad = function () {
    Adecco.ContactInfo.validate();
    Adecco.ConfirmEmail.validate();
    Adecco.OtherInfo.validate();
    Adecco.JobReq.validate();
    Adecco.BranchOffice.validate();
    Adecco.SignUp.validate();
    Adecco.QuickSkill.validate();
};

Adecco.Profile.validateOnSubmit = function() {
    // validate all the forms on the page
    // if form is not valid, then show "missing information" at the top of the section
    var isValid = true;
    var isCurrentFormValid = false;


    // validate confirm email control
    if (window.Adecco.ConfirmEmail.validateOnSubmit) {
        isCurrentFormValid = Adecco.ConfirmEmail.validateOnSubmit();
        isValid = isValid && isCurrentFormValid;
    }

    // validate the contact info form
    if (window.snpContactInformationOuter) {
        if (Adecco.ContactInfo.validate && Adecco.ContactInfo.updateMissingInfo) {
            isCurrentFormValid = Adecco.ContactInfo.validate();
            Adecco.ContactInfo.updateMissingInfo(isCurrentFormValid);

            // show validation summary error message for contact info
            if (isCurrentFormValid === false) {
                $('#divContactInfoErrorSummary').show();
            }

            // update the page's valid flag
            isValid = isValid && isCurrentFormValid;
        }
    }

    // validate the quick skills form, make sure the quick skill control is loaded
    if (window.snpQuickSkills) {
        if (Adecco.QuickSkill.validate && Adecco.QuickSkill.updateMissingInfo) {
            isCurrentFormValid = Adecco.QuickSkill.validate();
            Adecco.QuickSkill.updateMissingInfo(isCurrentFormValid);

            // show validation summary error message for contact info
            if (isCurrentFormValid === false) {
                $("#divSkillsErrorSummary").show();
            }

            // update the page's valid flag
            isValid = isValid && isCurrentFormValid;
        }
    }

    // validate the skills form
    if (window.snapSkillSection) {
        if (Adecco.Skills.validate && Adecco.Skills.updateMissingInfo) {
            isCurrentFormValid = Adecco.Skills.validate();
            Adecco.Skills.updateMissingInfo(isCurrentFormValid);

            // show validation summary error message for contact info
            if (isCurrentFormValid === false) {
                $("#divSkillsErrorSummary").show();
            }

            // update the page's valid flag
            isValid = isValid && isCurrentFormValid;
        }
    }

    // validate work history form
    if (window.snpWorkHistoryOuter) {
        if (Adecco.WorkHistory.validate && Adecco.WorkHistory.updateMissingInfo) {
            isCurrentFormValid = Adecco.WorkHistory.validate();
            Adecco.WorkHistory.updateMissingInfo(isCurrentFormValid);

            // show validation summary error message for contact info
            if (isCurrentFormValid === false) {
                $("#divWorkHistoryErrorSummary").show();
            }

            // update the page's valid flag
            isValid = isValid && isCurrentFormValid;
        }
    }

    // education
    if (Adecco.Education.validateOnSubmit) {
        isCurrentFormValid = Adecco.Education.validateOnSubmit();
        Adecco.Education.updateMissingInfo(isCurrentFormValid);

        if (isCurrentFormValid === false) {
            $("#divEducationMissingInfo").show();
            $("#divEducationErrorSummary").show();
        }

        // update the page's valid flag
        isValid = isValid && isCurrentFormValid;
    }

    // validate work eligibility
    if (Adecco.JobEligibility.validate) {
        isCurrentFormValid = Adecco.JobEligibility.validate();

        // show validation summary error message for contact info
        if (isCurrentFormValid === false) {
            $("#divJobEligibility").show();
        }

        // update the page's valid flag
        isValid = isValid && isCurrentFormValid;
    }

    /*
    // validate the job requirements form
    if (Adecco.JobReq.validate) {
    isCurrentFormValid = Adecco.JobReq.validate();
    // update the page's valid flag
    isValid = isValid && isCurrentFormValid;
    }

    // validate other information
    if (Adecco.OtherInfo.validate) {
    isCurrentFormValid = Adecco.OtherInfo.validate();
    // update the page's valid flag
    isValid = isValid && isCurrentFormValid;
    }
    */
    // validate sign up
    if (Adecco.SignUp.validateOnSubmit) {
        isCurrentFormValid = Adecco.SignUp.validateOnSubmit();
        // update the page's valid flag
        isValid = isValid && isCurrentFormValid;
        if (isCurrentFormValid === false) {
            $('#divSignUpMissingInfo').css('visibility', 'visible');
            $('#divSignupErrorSummary').show();
        }
    }

    return isValid;
};

Adecco.Profile.notifyControlRefresh = function() {

    // refresh work history on postback
    var workEditCallback = window.cbkWorkHistoryEditRepeater;
    if (window.snpWorkHistoryOuter && workEditCallback) {
        workEditCallback.callback();
    }

    // refresh education on postback
    var educationEditCallback = window.cbkEducationEditRepeater;
    if (window.snpEducationOuter && educationEditCallback) {
        educationEditCallback.callback();
    }

    // refresh other info on postback
    var otherInfoCallbackEdit = window.cbkOtherInformationEdit;
    var otherInfoCallbackReview = window.cbkOtherInformationReview;
    if (window.snpOtherInformation && otherInfoCallbackEdit && otherInfoCallbackReview) {
        if (snpOtherInformation.get_isCollapsed() === true) {
            otherInfoCallbackReview.callback();
        }
        else {
            otherInfoCallbackEdit.callback();
        }
    }
};

/************************/
/* Validation functions */
/************************/
if (!Adecco.Validation) {
    Adecco.Validation = {};
}

Adecco.Validation.validate = function(controls) {
    /// <summary>
    ///     Called by a user control to validate form, user control must pass in an array of controls to validate
    /// </summary>
    var isValid = true;
    var index;
    for (index in controls) {
    
        if(!controls[index]) {
            isValid = isValid && true;
            continue;
        }
        var theControl;
        if (controls[index].ClientControlId) {
            theControl = document.getElementById(controls[index].ClientControlId);
        }
        else {
            theControl = document.getElementById(controls[index]);
        }
        if (theControl && theControl.control) {
            if (typeof theControl.control.isValid === "function") {
                isValid = isValid && theControl.control.isValid();
            }
            else {
                isValid = isValid && theControl.control.isValid;
            }
        }
        else if (theControl) {
            isValid = isValid && (theControl.value.length > 0);
        }
    }
    return isValid;
};

Adecco.Validation.isInteger = function (input) {
    /// <summary>
    ///     Used by a MaskedInput control to validate an integer value
    /// </summary>
    var theInteger = input.masked.value + '';
    return theInteger.isInteger();
};

Adecco.Validation.isDecimal = function (input){
    /// <summary>
    ///     Used by a MaskedInput control to validate a decimal value
    /// </summary>
    var theDecimal = input.masked.value + '';
    return theDecimal.isNumber();
};

Adecco.Validation.isNonEmpty = function (input){
    /// <summary>
    ///     Used by a MaskedInput control to validate a non-empty field
    /// </summary>
    var theInput = input.masked.value;
    return (/^.+$/).test(theInput);
};

Adecco.Validation.isOnOrAfterDate = function (dateToCheckString, dateRequiredString){
    /// <summary>
    ///     Returns true if dateToCheck is on or after dateRequired, both strings
    /// </summary>
    if(dateToCheckString.isValidDate() && dateRequiredString.isValidDate()){
    
        var dateToCheck = new Date(dateToCheckString);
        var dateRequired = new Date(dateRequiredString);
        
        return dateToCheck >= dateRequired;    
    }
    else {
        return false;
    }
};

Adecco.Validation.isValidEmail = function(input) {
    var theInput = input.masked.value + '';
    return theInput.isEmail();
};

Adecco.Validation.isValidZipCode = function(input) {
    var theInput = input.masked.value;
    return theInput.isZipCode();
};

Adecco.Validation.isValidAreaCode = function(input) {
    var theInput = input.masked.value;
    return theInput.isThreeDigit();
};

Adecco.Validation.isValidPhone1 = function(input) {
    var theInput = input.masked.value;
    return theInput.isThreeDigit();
};

Adecco.Validation.isValidPhone2 = function(input) {
    var theInput = input.masked.value;
    return theInput.isFourDigit();
};

Adecco.Validation.isValidGPA = function(input) {
    var theInput = input.masked.value;
    return theInput.isValidGPA();
};

/* Event manager */


/*
On how to use the event manager
-------------------------------

Features on the server side
---------------------------
Register a handler for changes to a specific value represented by a key string
Read or write a value for a specific key

To register a handler, in the BaseUserControl, call:

protected virtual void RegisterHandlerWithEventManager(string key, string function) {...}

To set an value to be present when the pages loads:

protected virtual void RegisterStartValueWithEventManager(string key, string value) {...}

The handler should be registered before PreRender, say in the Page_Load. And the call to set a default value should be made during PreRender.


Features on the client side
---------------------------
Really the same. To register a handle call:

	eventManager.registerHandler("<key>", <function>);

To set a value before document has loaded:

	$(document).ready(
		function() {
				eventManager.setValue("<key>", <value>);
	 	   	   }
	);

and of course if after document has loaded, only:

	eventManager.setValue("<key>", <value>);

is enough.

Misc.
-----
There's currently neither a way to remove a handler nor a defined list of keys.

*/

Adecco.EventManager = function ()
{
    this.handlers = [];
};

Adecco.EventManager.prototype = 
{
    setValue: function (key,value){
        this[key] = value;
        
        this.notifyPropertyChange(key, value);
    },
    
    getValue: function (key){
        return this[key];
    },
    
    notifyPropertyChange: function (propertyName, newValue) {
        if(this.handlers[propertyName])
        {
            var i=0;
            var aHandler;
            for (i=0; i < this.handlers[propertyName].length; ++i)
            {
                aHandler = this.handlers[propertyName][i];
                aHandler(propertyName, newValue);
            }
        }
    },
    
    registerHandler: function (key, handler){
        if(!this.handlers[key])
        {
            this.handlers[key] = [];
        }
        this.handlers[key].push(handler);
    }
};

var eventManager = new Adecco.EventManager();

/*

Client-side signaling helpers
*****************************
These functions are use in the client side framework 
that usercontrols can use to specify which fields are required 
and when their value change check if the user control is done
with respect to the required information for saveing profile, 
and subsequently signal true or false through the EventManager.

To use this framework:

1. Override the RequiredFields property in the base user control
to specify which web controls are required

2. Set the property DoClientSideSignaling to true

3. Override the ControlName property, set a unique name, like the 
name of the codebehind class

4. Override EventManagerKey, preferably use a const in the 
user control code behind. This is the key identifying the 
event indicating that a user control is done/not done.

5. That same key from step 4 shall be properly switched on in the 
JobApplyWizardProgress mark up javascript code

6. If you need to call a custom function when a control
changes value, for example to turn on/off a "light" in the 
user control itself saying that it is done or not; override the 
OtherSignalingFunction if needed. The function will called with 
one boolean parameter indicating that if the control is done or not.

*/
function SignalIsDone (isValidArray, eventKey, otherSignalingCall)
{
    var isDone = true;
    jQuery.each(isValidArray, function (key, value) {
            if(!value)
            {
                isDone = false;
                return false;
            }
        }
    );
    
    if (otherSignalingCall) {
        otherSignalingCall(isDone);
    }
        
    eventManager.setValue(eventKey, isDone);
}

function ValidateControl (id, serverSideName, type, isValidArray, eventKey, otherSignalingCall)    
{       
    var control = $("#" + id)[0];
    
    if(control)
    {
        switch(type)
        {
            case "TextBox":
            case "DropDownList":
                isValidArray[serverSideName] = control.value !== '';                    
                break;
        }
    }
    
    SignalIsDone(isValidArray, eventKey, otherSignalingCall);
}

/************************/
/* MasterPage Javascript functions */
/************************/
if (!Adecco.MasterPage) {
    Adecco.MasterPage = {
    loginContainerId : 'loginContainer'
    };
}

// function to show the login div that is in the masterpage
Adecco.MasterPage.showLoginDiv = function () {
    var divSignInControl = document.getElementById('divSignInControlMarker');
    if (divSignInControl === null ) {
        $('#'+this.loginContainerId).slideDown('fast');
    }
};

// function to hide the login div that is in the masterpage
Adecco.MasterPage.hideLoginDiv = function (event) {
    var rel = (event.relatedTarget) ? event.relatedTarget : event.toElement;
    var tar = (window.event) ? event.srcElement : event.target;
    while (rel) {
        if (rel == tar || rel.id === this.loginContainerId) {
           return;
        }
        else if (rel.nodeName == 'BODY' ) {
            break;
        }
        rel=rel.parentNode;        
    }
    
    if (rel != tar || rel.nodeName == 'BODY' || rel === null) {        
        $('#'+ this.loginContainerId).hide();
    }
};

/* Enhancement 1786 - Provide user an error message if
   they haven't closed off any open zones on application page 
   
   Zones include:
   
   1. Contact Information (snpContactInformation)
   2. Work History (EditWorkHistoryForm)
   3. Education (educationEditForm)
   4. Skills (snapSkills)
   5. Job Eligibility (snpJobEligibility)
   6. Job Requirements (snpJobRequirements)
   7. Other info (snpOtherInformation)
   
   
   */

function editZonesOpen() {
    
    if ((!snpContactInformation.get_isCollapsed() && $('#divContactInfoPreviewSnap:visible') == 1) ||
        $('#EditWorkHistoryForm:visible').length == 1 ||
        $('#educationEditForm:visible').length == 1 ||
        !snapSkills.get_isCollapsed() ||
        !snpJobEligibility.get_isCollapsed() ||
        !snpOtherInformation.get_isCollapsed()) {
        
        window.alert('Please save your open items before clicking save profile!');
        return true;
        
    }

    return false;
    
}