﻿// ** 3DCV Helper Functions
// ** Generated on 4 Aug 2008 - TNewman
function exportCV() {
    $.facebox(function() {
        $.get("/WebControls/3DCV/SelectExport.aspx?export=1", function(data) {
            $.facebox(data);
        })
    })
}
function preview3DCV() {
    $.facebox(function() {
        $.get("/WebControls/3DCV/Preview.aspx", function(data) {
            $.facebox(data);
        })
    })
}
function AMAddAchievement() {
    var newValue = $("select[id$='ddlAchList']").val();
    if (!AMDupeCheck("achievementContainer", newValue))
        return false;
    var oNew = document.createElement('div');
    $(oNew).attr("style", "width:100%;display:block;margin-bottom:5px;");
    $(oNew).load("/WebControls/Viewers/GetItem.aspx", { achievement: newValue });
    $("#achievementContainer").append(oNew);
}

function AMAddReference() {
    var newValue = $("select[id$='ddlRefList']").val();
    if (!AMDupeCheck("referenceContainer", newValue))
        return false;
    var oNew = document.createElement('div');
    $(oNew).attr("style", "width:100%");
    $(oNew).load("/WebControls/Viewers/GetItem.aspx", { reference: newValue });
    $("#referenceContainer").append(oNew);
}

function AMDupeCheck(container, checkID) {
    if ($("#" + container).find("input[value='" + checkID + "']").length > 0) {
        alert('You already have this item on your hardcopy CV.');
        return false;
    } else if ($("#" + container).find("input").length > 2) {
        alert('You may have a maximum of three items on your hardcopy CV.');
        return false;
    } else
        return true;
}

function AMRemoveItem(srcItem) {
    $(srcItem).parents('div:eq(1)').remove();
}

function AMDisplaySelectedJobs(srcValue) {
    $("#jobContainer").load("/WebControls/Viewers/GetJobs.aspx", { amount: srcValue });
}
function openPreview3DCV() {
    window.open('/WebControls/3DCV/Preview.aspx?previewStatement=' + $("select[id$='ddlPreviewStatements']").val(), 'previewWindow', '');
    $.facebox.close();
}

function playSplashVideo(videoAddress) {
    $(document).bind('close.facebox', function() {
        $("#splashVideo").remove();
    });
    $.facebox(function() {
        $.post("/WebControls/3DCV/VideoPlayer.aspx", { videoURL: videoAddress }, function(data) {
            $.facebox(data);
        })
    })
}
function helpTabClick(selectedTab) {
    if (!$("li[name='helpTab" + selectedTab + "']").hasClass("current")) {
        $("li[name^='helpTab']").removeClass("current");
        $("li[name='helpTab" + selectedTab + "']").addClass("current");
        $("div[name^='helpText']").hide();
        $("div[name='helpText" + selectedTab + "']").show();
    }
    return;
}
var displayName = '';
function checkDisplayName() {
    displayName = $("input[name$='txtUsername']").val();
    $("#checkResult").load("/WebControls/Verification/VerifyUsername.aspx", { check: displayName }, function() {
        if ($("#checkResult").html().indexOf("Success") > 0) {
            updateDisplayName(displayName);
        } else {
            updateDisplayName('yourname');
        }
    })
}
function confirmDisplayName() {
    $("#checkResult").load("/WebControls/Verification/VerifyUsername.aspx", { confirm: true }, function() {
        return true;
    })
}
function clearDisplayName() {
    $("span[@id^='displayName']").html('yourname');
    $("#checkResult").html('');
}
function updateDisplayName(newName) {
    $("span[@id^='displayName']").html(newName);
}
// functions to handle work locations
var dupLocation = false;
function addNewLocation() {
    dupLocation = false;
    $("input[name='intLocation']").each(function(iItem) { if ($("select[name$='ddlLocations']").val() == $(this).val()) { dupLocation = true; return false; } });
    if (dupLocation) {
        alert('You have already added this location.'); return;
    }
    var oNew = document.createElement('div');
    $(oNew).load("/WebControls/Links/Locations.aspx", { locationID: $("select[name$='ddlLocations']").val() });
    $("#locationContainer").append(oNew);
    $("#locationMessage").text("Your selected locations : ");
}
function removeLocation(srcControl) {
    $(srcControl).parent().remove();
    if ($("input[name='intLocation']").size() < 1)
        $("#locationMessage").text("Please add one or more locations.");
}
function updateLocations(srcElement) {
    var selCountryID = $(srcElement).val();
    $("#locationList").load("/WebControls/Links/Locations.aspx", { "countryID": selCountryID });
}
// functions to handle external links on the general page
var newLinkName = '';
var newLinkURL = '';
var dupLinkURL = false;
function addNewLink() {
    newLinkName = $("input[@id='newLinkName']").val();
    newLinkURL = $("input[@id='newLinkURL']").val();
    if (newLinkName.length > 0 && newLinkURL.length > 0) {
        dupLinkURL = false;
        $("input[name='strExternalURL']").each(function(iItem) { if (newLinkURL == $(this).val()) { dupLinkURL = true; return false; } });
        if (dupLinkURL) {
            alert('You have already added this address.'); return;
        }
        var oNew = document.createElement('div');
        $(oNew).load("/WebControls/Links/ExternalLinks.aspx", { linkName: newLinkName, linkURL: newLinkURL });
        $("#linkContainer").append(oNew);
    } else {
        alert('Please supply both a name and a URL to add an external link');
    }
}
function removeLink(srcControl) {
    $(srcControl).parent().remove();
}
function moveLinkUp(srcControl) {
    var curItem = $(srcControl).parent();
    var prevItem = $(curItem).prev();
    if (prevItem != undefined)
        $(prevItem).insertAfter(curItem);
}
function moveLinkDown(srcControl) {
    var curItem = $(srcControl).parent();
    var nextItem = $(curItem).next();
    if (nextItem != undefined)
        $(nextItem).insertBefore(curItem);
}
// functions to drive job history / reference link
function checkPresentRole(srcElement) {
    var periodSelector = $(srcElement).parents('div:eq(0)').find("select[name='strJNoticePeriod']");
    if (srcElement.value == "Yes") {
        $(periodSelector).removeAttr("onchange"); $(periodSelector).unbind("change");
    } else {
        $(periodSelector)[0].selectedIndex = 0; $(periodSelector).change(function() { this.selectedIndex = 0; });
    }
}
function checkRoleSalaries(srcElement) {
    var salaryInput = $(srcElement).parents('div:eq(0)').find("input[name='strJSalary']");
    var oteInput = $(srcElement).parents('div:eq(0)').find("input[name='strJOTE']");
    if (isNaN($(salaryInput).val()))
        $(salaryInput).val("0");
    else if (isNaN($(oteInput).val()))
        $(oteInput).val("0");
    else if (parseFloat($(salaryInput).val()) > parseFloat($(oteInput).val()))
        $(oteInput).val($(salaryInput).val());
}

function removeFromRef(srcElement, newItem) {
    if (!newItem)
        $("[name='intRContext']").removeOption($(srcElement).parents('div:eq(0)').find("[name='intJID']").val());
    else {
        var clearPane = $(srcElement).parents('div:eq(0)')
        var containerPane = $(srcElement).parents('div:eq(1)')
        $("[name='intRContext']").removeOption($(containerPane).prev().find('select')[0].options[$(clearPane).prevAll().length].text);
    }
}

function addToRef(srcElement) {
    var copyPane = $(srcElement).parents('div:eq(0)')
    var titleText = '';
    $(copyPane).find("[id^='paneTitle']").each(function(i) {
        if (i > 0) titleText += ' - ';
        if (this.tagName == 'SELECT')
            titleText += this.options[this.selectedIndex].text;
        else
            titleText += $(this).val();
    });
    if (titleText.length == 0) {
        return;
    };
    $("[name='intRContext']").addOption(titleText, titleText);
}
// functions to drive multi-panel input controls
var paneIndex = -9999;

function removePane(srcElement) {
    var clearPane = $(srcElement).parents('div:eq(0)')
    var containerPane = $(srcElement).parents('div:eq(1)')
    var paneSelector = $(containerPane).prev().find('select')
    paneSelector.removeOption($(clearPane).prevAll().length);
    $(clearPane).remove();
    paneSelector.selectedIndex = 0;
    $(containerPane).children('div:eq(0)').show();
}
function addPane(srcElement, container) {
    var copyPane = $(srcElement).parents('div:eq(0)')
    var containerPane = $(srcElement).parents('div:eq(1)')
    var paneSelector = $(containerPane).prev().find('select')
    var titleText = '';
    $(copyPane).find("[id^='paneTitle']").each(function(i) {
        if (i > 0) titleText += ' - ';
        if (this.tagName == 'SELECT')
            titleText += this.options[this.selectedIndex].text;
        else
            titleText += $(this).val();
    });
    if (titleText.length == 0) {
        alert('Please complete the item before adding.');
        return;
    };
    paneIndex++;
    var newPane = $(copyPane).clone();
    $(copyPane).find('select').each(function(i) {
        $(newPane).find('select')[i].selectedIndex = this.selectedIndex;
    });
    $(copyPane).find('textarea').each(function(i) {
        $(newPane).find('textarea')[i].value = this.value;
    });
    $(newPane).find('#paneAdd').hide(); $(newPane).find('#paneRemove').show();
    $(newPane).appendTo(containerPane)

    $(newPane).find("select[id^='srcListMML_']").attr("id", "srcListMML_" + paneIndex);
    $(newPane).find("select[id^='selListMML_']").attr("id", "selListMML_" + paneIndex);
    $(newPane).find("input[name='strControlSuffix']").val(paneIndex);

    $(copyPane).find('input,textarea').val('');
    paneSelector.addOption(paneIndex, titleText);
    $(containerPane).children('div').hide();
    $(newPane).show();
}
function selectPane(srcElement) {
    var containerPane = $(srcElement).parents('div:eq(0)').next();
    $(containerPane).children('div').hide();
    $(containerPane).children('div:eq(' + srcElement.selectedIndex.toString() + ')').show();
}
// Function to handle multiple item pick list tools
function addSelItems(typeName, maxItems, typeId) {
    if (!isNaN(maxItems) & maxItems > 0)
        if ($("#selList" + typeName + " option").length == maxItems)
        return;

    $("#srcList" + typeName).copyOptions("#selList" + typeName);
    $("#selList" + typeName).sortOptions();

    if (!isNaN(maxItems) & maxItems > 0)
        $("#selList" + typeName + " option:gt(" + (maxItems - 1) + ")").remove();

    $("#selList" + typeName).parents('div:eq(0)').find('input[name=strMMLCSV]').val(new String($("#selList" + typeName).val()).replace(/,/gi, '|'));
}
function remSelItems(typeName) {
    $("#selList" + typeName).removeOption(/./, true);
    $("#selList" + typeName).sortOptions();

    $("#selList" + typeName).parents('div:eq(0)').find('input[name=strMMLCSV]').val(new String($("#selList" + typeName).val()).replace(/,/gi, '|'));
}
function addSelItem(typeName) {
    var newValue = $("#addList" + typeName).val();
    $("#srcList" + typeName).addOption(newValue, newValue);
    $("#srcList" + typeName).sortOptions();
}
function prepSelItems() {
    $("select[id^='selList']").selectOptions(/./);
}
// Quick snipper for field limit item
function textLimit(srcElement) {
    $(srcElement).next().text('[' + $(srcElement).val().length.toString() + '/' + $(srcElement).attr('maxlength') + ']');
}
function textLimitML(srcElement, limit) {
    if ($(srcElement).html().length > limit) {
        $(srcElement).html($(srcElement).html().substr(0, 200));
        alert('No more than ' + limit + ' characters can be used in this text box.');
    }
    $(srcElement).next().text('[' + $(srcElement).html().length.toString() + '/' + limit + ']');
}
// Generic function for form submits
function beforeSubmit() {
    try {
        $("select[id^='selList']").selectOptions(/./);

        $("input[name='strMMLCSV']").each(function (i) {
            var sValue = new String($(this).parents("div:eq(0)").find("select[id^='selList']").val()).replace(/,/gi, '|');
            if (sValue == "null")
                sValue = "";

            $(this).val(sValue);
        });
    } catch (e) { }

    try {
        //return true; //Page_ClientValidate();
        if (Page_IsValid != undefined && (!Page_IsValid))
            return false;
        else
            return true;
    }
    catch (e) {
        return true;
    }
}
// Function to handle dimension panels
function showDimPanel(iPanel) {
    $("#dimPanel" + iPanel).show();
    $("#openButton" + iPanel).hide();
    $("#closeButton" + iPanel).show();
}
function hideDimPanel(iPanel) {
    $("#dimPanel" + iPanel).hide();
    $("#openButton" + iPanel).show();
    $("#closeButton" + iPanel).hide();
}
// Functions to handle validation
function selectValidator() {
    var currentAch = $("#validatorDetail").val();
    $("#valScore" + currentAch).html("");
    $("#valText" + currentAch).load("/WebControls/3DCV/Validator.aspx", { achDetail: currentAch, selectedValidator: $("#validatorList").val() });
    $.facebox.close();
}
function checkValidator(srcElement) {
    if (srcElement.value.indexOf('V') > -1)
        $("#delValidator").removeAttr("disabled");
    else
        $("#delValidator").attr("disabled", "true");
}
function deleteValidator() {
    var valList = $("#validatorList");
    $.post("/WebControls/3DCV/Validator.aspx", { deleteValidator: $(valList).val() });
    $(valList).removeOption($(valList).val());
}
function removeValidator(currentAchItem) {
    $("#valText" + currentAchItem).load("/WebControls/3DCV/Validator.aspx", { removeValidator: currentAchItem });
}
function createValidator() {
    var currentAch = $("#validatorDetail").val();
    $("#valScore" + currentAch).html("");
    $("#valText" + currentAch).load("/WebControls/3DCV/Validator.aspx", { achDetail: currentAch,
        valFName: $("#validatorFName").val(), valSName: $("#validatorSName").val(),
        valEmail: $("#validatorEmail").val(), valPhone: $("#validatorPhone").val(),
        valJobTitle: $("#validatorJobTitle").val()
    });
    $.facebox.close();
}
// Function to handle dimension highlighting
function setDimHighlight(srcCheckbox) {
    // check for a maximum of three scored items
    var scoreCount = 0;
    $("input[name='blnScored']").each(function() { if (this.checked) { scoreCount++; } });
    if (scoreCount > 3) { srcCheckbox.checked = false; alert('You may choose a maximum of three items for your score chart.'); return; }
    if (srcCheckbox.name == "blnVisible") {
        if (!srcCheckbox.checked) {
            $("#achPanel" + $(srcCheckbox).val()).addClass("blockpanels2deactive").removeClass("blockpanels2active");
            $("#achPanel" + $(srcCheckbox).val()).find("input[name='blnScored']").attr("checked", "");
        }
    } else {
        if (srcCheckbox.checked) {
            $("#achPanel" + $(srcCheckbox).val()).addClass("blockpanels2active").removeClass("blockpanels2deactive");
            $("#achPanel" + $(srcCheckbox).val()).find("input[name='blnVisible']").attr("checked", "checked");
        }
        else
            $("#achPanel" + $(srcCheckbox).val()).addClass("blockpanels2deactive").removeClass("blockpanels2active");
    }
}
// Functions for quick tips
function openTip(iItem) {
    $("div[id^='quickTip']").hide(); $("img[id^='openTip']").show(); $("img[id^='closeTip']").hide();
    $("#closeTip" + iItem).show(); $("#openTip" + iItem).hide(); $("#quickTip" + iItem).show();
}
function closeTip(iItem) {
    $("#openTip" + iItem).show(); $("#closeTip" + iItem).hide(); $("#quickTip" + iItem).hide();
}

// Functions for upload tool
var multipleFileRefresh = false;
var swuf;
function uploadOpen(fieldName, multiFiles, fileTypes, updateElement, itemWidth, uid) {
    $.facebox(function() {
        $.post("/WebControls/Uploader/Upload.aspx", { field: fieldName, multi: multiFiles, permitted: fileTypes, update: updateElement, width: itemWidth }, function(data) {
            $.facebox(data);
            swfu = new SWFUpload({
                upload_url: "http://www.abintegro.com/includes/upload.asp?UserID=" + uid,
                flash_url: "/images/flash/swfupload.swf",
                file_size_limit: "102400",
                file_queue_limit: 20,
                file_types: "*.jpg;*.jpeg;*.gif;*.png;*.avi;*.mp3;*.mpg;*.mp4;*.mpeg;*.wmv;*.asf;*.doc;*.docx;*.xls;*.xlsx;*.ppt;*.pptx;*.wri;*.txt;*.rtf;*.pdf;",
                file_types_description: "Permitted 3DCV Files (Images,Movies,Docs)",
                button_image_url: "/Images/Buttons/BrowseFile.gif",
                button_width: 96,
                button_height: 31,
                button_action: SWFUpload.BUTTON_ACTION.SELECT_FILES,
                cursor: SWFUpload.CURSOR.HAND,
                button_placeholder_id: "uploadButtonBrowse",
                button_text: '',
                button_text_style: "",
                button_text_top_padding: 0,
                button_text_left_padding: 0,
                file_queued_handler: uploadFileAdded,
                upload_start_handler: uploadStart,
                upload_progress_handler: uploadFileProgress,
                upload_error_handler: uploadFileError,
                upload_success_handler: uploadFileSuccess,
                upload_complete_handler: uploadComplete,
                queue_complete_handler: queueComplete
            });
        })
    })
}
// Fired upon start of a queued file
function uploadBegin(iUser, bMultiFiles) {
    multipleFileRefresh = bMultiFiles;
    try {
        var titleFail = false;
        $("#uploadNewPanel").find("[id^='uploadFileTitle']").each(function(i) {
            if ($(this).val().length == 0)
                titleFail = true;
        });
        if (titleFail)
            return (alert('Please supply a title for each file.'));
        if (swfu.getStats().files_queued === 0)
            return (alert('Please select a file to upload.'));
        var file = swfu.getFile(0);
        $("#uploadButtonStart").hide(); $("#uploadButtonCancel").show();
        swfu.startUpload();
    }
    catch (ex) { };
}
// Catch cancel click with queue cancel
function uploadCancel() {
    swfu.cancelQueue();
}
// Function to display add file dialog
function uploadShowNew() {
    $("#uploadNew").show(); $("#uploadSelect").hide();
    $("li[id$='uploadTabSelect']").removeClass("current");
    $("li[id$='uploadTabNew']").addClass("current");
}
// Function to display select dialog
function uploadShowSelect() {
    $("#uploadNew").hide(); $("#uploadSelect").show();
    $("li[id$='uploadTabSelect']").addClass("current");
    $("li[id$='uploadTabNew']").removeClass("current");
}
// Function to remove a specific file from the list
function uploadRemoveFile(srcItem, fileID) {
    swfu.cancelUpload(fileID);
    $(srcItem).parents('div:eq(1)').remove();
}
// Fired upon each file start
var uploadStart = function(file) {
    try {
        swfu.addFileParam(file.id, "FileTitle", $("#uploadFileTitle" + file.id).val());
        $("#uploadProgress" + file.id).text("UPLOADING");
    } catch (ex) { }
    return true;
}
// Fired upon file add (one or many)
var uploadFileAdded = function(fileObject) {
    try {
        var oNew = document.createElement('div');
        $(oNew).addClass("uploaditem"); $(oNew).attr("style", "width:630px;padding:2px;");
        $(oNew).load("/WebControls/Uploader/UploadItem.aspx", { fileName: fileObject.name, fileID: fileObject.id, fileSize: fileObject.size });
        $("#uploadNewPanel").append(oNew);
    } catch (ex) { }
}
var uploadFileProgress = function(fileObject, bytesDone, bytesTotal) {
    var percent = Math.ceil((bytesDone / bytesTotal) * 100);
    $("#uploadProgress" + fileObject.id).text(percent + "%");
}
var uploadFileError = function(fileObject, errCode, errMessage) {
    $("#uploadFileRemove" + fileObject.id).hide();
    $("#uploadProgress" + fileObject.id).text("FAILED");
}
var uploadFileSuccess = function(fileObject, serverData) {
    $("#uploadFileRemove" + fileObject.id).hide();
    $("#uploadProgress" + fileObject.id).text("DONE");
}
var uploadComplete = function(fileObject) {
    if (this.getStats().files_queued === 0) {
        $("[id^='uploadFileRemove']").hide();
        $("#uploadButtonStart").show(); $("#uploadButtonCancel").hide();
        // TODO : Refresh file list pane
        refreshFilePanel(multipleFileRefresh);
        uploadShowSelect();
    }
}
var queueComplete = function(filesUploaded) {
    return;
}
function refreshFilePanel(bMultiFiles) {
    $("#uploadFilePanel").load("/WebControls/Uploader/UploadFiles.aspx", { multiFiles: bMultiFiles, fileFilter: $("#uploadFileType").val(), noSelect: $("#uploadSelectActive").val() });
}
function uploadEditFile(srcElement, fileID) {
    var newTitle = $("#editFileTitle" + fileID).val();
    if (newTitle.length == 0)
        return alert('Please enter a new title to continue.');
    $.post("/WebControls/Uploader/UploadFiles.aspx", { editFile: fileID, fileTitle: newTitle });
    $("#editFileTitle" + fileID).css({ backgroundColor: "#ffffff" });
}
function uploadDeleteFile(srcElement, fileID) {
    $.post("/WebControls/Uploader/UploadFiles.aspx", { deleteFile: fileID });
    $(srcElement).parents('div:eq(1)').remove();
}
function pickUploadFiles(fieldName, updateImage, itemWidth) {
    $("#uploadFilePanel").find("[name='uploadSelFileID']").each(function(i) {
        if (this.checked) {
            if ($(this).attr("type") == "radio")
                $("div[name='" + fieldName + "FileList']").empty();
            if (!checkUploadDuplicate(fieldName, this.value)) {
                if (updateImage.length > 0) {
                    var changeImage = $("img[id$='" + updateImage + "']");
                    if ((changeImage).attr("oldsrc") == undefined)
                        $(changeImage).attr("oldsrc", $(changeImage).attr("src"));
                    $(changeImage).attr("src", "/GetFile.aspx?requestedID=" + this.value + "&width=120&height=120");
                }
                var oNew = document.createElement('div');
                $(oNew).addClass("uploaditem"); $(oNew).css({ width: itemWidth, display: "block", marginBottom: "4px" }); $(oNew).load("/WebControls/Uploader/UploadItem.aspx", { fileID: this.value, field: fieldName, update: updateImage, fileName: $("#uploadSelFileName" + this.value).val() });
                $("div[name='" + fieldName + "FileList']").append(oNew);
            }
        }
    });
    $.facebox.close();
}
function checkUploadDuplicate(fieldName, newValue) {
    var foundValue = false;
    $("div[name='" + fieldName + "FileList']").find("input[name='" + fieldName + "ID']").each(function(i) {
        if (this.value == newValue) {
            foundValue = true; return false;
        }
    });
    return foundValue;
}
function removeUploadFiles(srcElement, updateImage) {
    if (updateImage.length > 0 && $("img[id$='" + updateImage + "']").attr("oldsrc") != undefined) {
        var changeImage = $("img[id$='" + updateImage + "']");
        $(changeImage).attr("src", $(changeImage).attr("oldsrc"));
    }
    $(srcElement).parents('div:eq(2)').remove();
}

function startPublish(editor, fnOnComplete) {
    var validatorList = '';
    $("input[name='intValidator']").each(function(i) {
        if (this.checked) validatorList += ',' + this.value;
    });
    $.facebox(function() {
        $.get("/WebControls/3DCV/PublishDialog.aspx", function(data) {
            $.facebox(data);
            $("#faceboxCloseButton").hide();
            $.post("/3DCV-Publish.aspx", { publish: true, validators: validatorList }, function(data) {
                if (fnOnComplete != null)
                    fnOnComplete();
                else {
                    $("#publishComplete").show();
                    $("#publishInProgress").hide();
                }
            });
        })
    })
}

function updateValEmailList() {
    var emails = new Array();
    $("input[name='intValidator']").each(function(i) {
        if (this.checked) {
            var email = $(this).parent().find("span").text();
            if (!listContains(emails, email)) {
                emails.push(email);
            }
        }
    });
    if (emails.length > 0)
        $("#valEmailList").text(emails.join(", "));
    else
        $("#valEmailList").text("No emails will be sent");
}
function listContains(array, test) {
    for (c = 0; c < array.length; c++)
        if (array[c] == test) return true;
    return false;
}

