﻿//========================================================
// Beyond.com JS library
// Property of Beyond.com 5/13/2009
// 
// beyond lightbox
//========================================================

//globals
var userAgent = navigator.userAgent;
var isValid = true;
var curBox = new myBeyondBox();
var beyondBoxHtml = '<div id="barrier" style="display:none;filter: alpha(opacity=0);-moz-opacity: .0;opacity: .0;background: #333333;"></div><div id="beyondBox" class="beyondBoxLBX" style="height:250px;width:490px;display:none;background:transparent;"></div>'

$(document).ready(function () {
    $("body").append(beyondBoxHtml);
});


//========================================================
// submit validation logic, not currently used
// using legacy validation logic
//========================================================
function submitReg() {
    isValid = true;
    $(parentDiv).find("input").submit();
    $(parentDiv).find("textArea").submit();
    if (isValid == true) {
        //do something
    }
}

//========================================================
//FROM legacy lightbox validation logic
//========================================================

//Front end validation of registration form fields
function validFormFields() {
    //Grab field values from F form
    var strFirstName = document.Registration.FFirstName.value;
    var strLastName = document.Registration.FLastName.value;
    var strEmail = document.Registration.FEAdd.value;
    var strIndustry = document.Registration.FCareerFocus1.value;
    var strJobTitle = document.Registration.FTitle.value;
    var strCountryState;
    if (document.Registration.FCountryState) {
        strCountryState = document.Registration.FCountryState.value;
    }
    else {
        strCountryState = 'NA';
    }
    var strPostalCode = document.Registration.FZipCode.value;

    //Start checking lengths of fields (lengths equal to those accepted by DB fields)
    var bAlertThrown = !(validFieldLength_new(strFirstName, "first name", 1, 50));
    if (!bAlertThrown) { bAlertThrown = !(validFieldLength_new(strLastName, "last name", 1, 50)); }
    if (!bAlertThrown) { bAlertThrown = !(validFieldLength_new(strEmail, "email", 1, 100)); }
    if (!bAlertThrown) { bAlertThrown = !(validFieldLength_new(strJobTitle, "job title", 1, 100)); }
    if (!bAlertThrown) { bAlertThrown = !(validFieldLength_new(strPostalCode, "postal code", 1, 10)); }
    //Check email validity
    if (!bAlertThrown) {
        bAlertThrown = !(validateEmailRegex(strEmail) & validateEmailBlacklist(strEmail) & validationEmailTypos(strEmail));
        if (bAlertThrown) {
            alert("Please verify your email address. A valid email address is required.");
        }
    }

    //Verify industry value
    if (!bAlertThrown) {
        if (strIndustry == 174) {
            alert("Please select your industry of interest from the drop down list provided.");
            bAlertThrown = true;
        }
    }
    //Verify country/state value (if it exists)
    if (!bAlertThrown) {
        if (strCountryState == '') {
            alert("Please select your location of interest from the drop down list provided.");
            bAlertThrown = true;
        }
    }

    return (!bAlertThrown);
}

//determine if the user filled out any item on the form
function anyFieldFilled() {

    var strFirstName = document.Registration.FFirstName.value;
    var strLastName = document.Registration.FLastName.value;
    var strEmail = document.Registration.FEAdd.value;
    var strJobTitle = document.Registration.FTitle.value;
    var strPostalCode = document.Registration.FZipCode.value;

    if (strFirstName == '' && strLastName == '' && strEmail == '' && strJobTitle == '' && strPostalCode == '') {
        return false;
    }
    else {
        return true;
    }

}

//On click of the submit button, validate fields and then submit them to action page
function submitTasks_new(formName) {
    if (anyFieldFilled() == true) {
        var bValidFormInput = validFormFields();
        if (bValidFormInput) {
            $(formName).submit();
        }
    } else {
        close();
    }
}

//--------------------------------------------------------------------------------------------
// function: validFieldLength_new(strValue, strName, iMin, iMax)
// description: pass value of field, friendly name of field, min and max length, returns boolean
// true if length of strValue falls within min and max, false otherwise
//--------------------------------------------------------------------------------------------
function validFieldLength_new(strValue, strName, iMin, iMax) {
    if ((iMin <= strValue.length) && (strValue.length <= iMax)) {
        return true;
    } else {
        alert("Please verify your " + strName + ". A valid " + strName + " is " + iMin + " to " + iMax + " characters long.");
        return false;
    }
}


//--------------------------------------------------------------------------------------------
// utilities
//--------------------------------------------------------------------------------------------
function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}


//brettOOP============================================================================================================================================
function myBeyondBox() {
    //PRIVATE MEMBERS
    /*
    _formName: '';
    _boxURL: '';
    not implemented yet
    _barrierColor: 'black';
    _borderColor: 'black';
    _height: '200';
    _width: '200';
    */

    //PRIVATE METHODS
    function showBeyondBoxJS(context) {
        if (userAgent.match("MSIE 6.0") == "MSIE 6.0")
            close(); //remove when lightbox fixed for IE6
        else {
            //set box dimensions
            $(context.formName).css("height", context.height + "px").css("width", context.width + "px");
            $(context.formName).css("margin-top", "-" + context.height / 2 + "px").css("margin-left", "-" + context.width / 2 + "px");

            //animate showing of barrier and box
            setTimeout(function () { $("#barrier").show().animate({ opacity: "0.25" }, 1000); }, 500);
            setTimeout(function () { $(context.formName).fadeIn(1000); }, 1000);
        }
    }
    function wireUpEvents(context) {
        if (!context.isModal) {
            $("#barrier").click(function () {
                context.close();
            });
        }
        $("#lbxForm").submit(function () {
            var myValidator = new FormValidation();

            if (myValidator.ValidateAll($('#lbxForm'))) {
                if (context.popUpMethod)
                    context.popUpMethod();
                submitLightbox();
            }
            //return false to make sure link doesn't execute
            return false;
        });
    }
    function setBeyondBoxContent(context) {
        $.get(context.boxURL, function (data) {
            $(context.formName).html(data);
            wireUpEvents(context);
        });
    }
    function processSuccess(context) {
        context.successMethod();
    }

    //PUBLIC MEMBERS
    return {
        success: false,
        reload: false,
        isModal: '',
        formName: '',
        boxURL: '',
        height: '',
        width: '',
        loginOnSuccess: false,

        //PUBLIC METHODS
        //handle click on a marker
        successMethod: null,
        failureMethod: function () {
            $("#ajaxSpinner").remove();
            $(".lbx_submit_btn").show();
        },
        closeMethod: null,
        popUpMethod: null,
        displayBox: function () {
            showBeyondBoxJS(this);
            setBeyondBoxContent(this);
            //$( ".beyondBox" ).draggable();
            return false;
        },
        resetContent: function () {
            setBeyondBoxContent(this);
            return false;
        },
        //build google map
        close: function () {
            $("#barrier").hide();
            $(".beyondBoxLBX").hide();
            //destroy contents of lightbox
            $("#lightbox").html("");
            if (this.closeMethod)
                this.closeMethod();
        },
        successActivity: function () {
            if (this.reload) {
                window.location.reload();
                return false;
            }
            else if (this.successMethod) {
                if (this.loginOnSuccess)
                    isLoggedIn = true;
                processSuccess(this);
            }
        }
    };
}
//brettOOP============================================================================================================================================

//======================================================================================================================
// showLightbox
//======================================================================================================================
// url(req):		path to lightbox content
// height(req):		height of lightbox with content for centering
// width(req):		width of lightbox with content for centering
// isModal:			disables click on on barrier calling close method
// reload:			bool whether or not to reload page after success
// successMethod:	executed if form posted with a success response
// closeMethod:		executed if user clicks X on lightbox or clicks the barrier when not modal
// failureMethod:	executed if user exits form after failing to submit form
// popUpMethod:		use popupUpMethod to bypass browser popup blocks when doing ajaxy things before showing a popup
//======================================================================================================================
function showLightbox(url, height, width, isModal, reload, successMethod, closeMethod, failureMethod, popUpMethod) {
    curBox.formName = '#beyondBox';
    curBox.height = height;
    curBox.width = width;
    curBox.boxURL = url;
    curBox.isModal = isModal;
    curBox.reload = reload != undefined ? reload : false;

    //set callbacks for success/close/failure
    if (successMethod)
        curBox.successMethod = successMethod;
    if (!curBox.closeMethod && closeMethod)
        curBox.closeMethod = closeMethod;
    if (failureMethod)
        curBox.failureMethod = failureMethod;
    if (popUpMethod)
        curBox.popUpMethod = popUpMethod;

    curBox.displayBox();
    return false;
}

//lightbox code
function submitLightbox() {
    //show spinner while processing ajax call
    $(".lbx_submit_btn").hide().after('<img id="ajaxSpinner" src="/common/images/jobsearchresults/ajax-loader.gif" />');

    var inputs = $("#lbxForm input:input, #lbxForm select");
    var data = {};

    for (var i = 0; i < inputs.length; i++) {
        var control = inputs[i];
        if ($(control).is(':checkbox'))
            data[$(control).attr('id')] = $(control).is(":checked") ? "on" : "";
        else
            data[$(control).attr('id')] = $(control).val();
    }
    return ajaxPost($("#lbxForm").attr("action"), data, 'N');
}
