﻿/* ---------- MAIN SITE JAVASCRIPT [W.AUSTIN @ WORKSUNIT : 06/2010] ---------- */

// ---- LOGIN & REGISTER | VALIDATION
// apply required class
function applyRequired(element) {
    var validNotice = $(element).siblings("span.validation"); 
    if($(validNotice).length >= 1) {
        $(element).addClass('required');
    }
}
// is this input required?
function checkRequired(element) {
    if($(element).hasClass('required')) {
        return true;
    } else {
        return false;
    }
}

//is this input email valid?
function checkEmailValidation(element) {
    if($(element).hasClass('validationemail')) {
        return true;
    } else {
        return false;
    }
}

function validateEmail(element) {
   var reg = /^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;
   var address = $(element).val();
   return reg.test(address);
}


// checking singular input fields (when focus out of input)
function checkField(element, quietcheck) {
    var isRequired = checkRequired($(element));
    var isEmail = checkEmailValidation($(element));
    var fieldValue = $(element).val();
    if(isRequired && fieldValue == "") {
        if(quietcheck != true) {
            $(element).siblings("span.validation").css('display','block');
        }
        return false;
    }
    else if(isEmail && !validateEmail(element)){
        if(quietcheck != true) {
            $(element).siblings("span.validation").css('display','block');
        }
        return false;
    }
    
     else {
        if(quietcheck != true) {
            $(element).siblings("span.validation").css('display','none');
        }
        return true;
    }
}
// checking all input fields (when submit clicked)
function checkAllFields(element, quietcheck) {
    var getFieldset = $(element).parents('fieldset');
    var invalidCount = 0;
    $(getFieldset).contents().find('input').each(function() {
        var isFieldValid = checkField($(this), quietcheck);
        if(isFieldValid == false) {
            invalidCount++;
        }
    });
    if(invalidCount > 0) {
        return false;
    } else {
        return true;
    }
}
// 
function countInvalids(element) {
    var quietcheck = true;
    var quietIsValid = checkAllFields(element, quietcheck)
    var getFieldset = $(element).parents('fieldset');
    if(quietIsValid) {
        $(getFieldset).find('input[type=submit]').each(function() {
            if($(this).hasClass('disabled')) {
                $(this).removeClass('disabled');
            }
        });
    } else {
        $(getFieldset).find('input[type=submit]').each(function() {
            if($(this).hasClass('disabled')) {
            } else {
                $(this).addClass('disabled');
            }
        });
    }
}   
// when the submit button is checked
function submitCheck(element) {
    var isValid = checkAllFields(element);
    return isValid;
}
// ----- CANDIDATE TOOLS OPEN & CLOSE
function openCandidateTools() {
    $('#Top li a:visible').children('span').attr('class','icon arrow-white-down');
    $('.head-inset').slideDown(1000).addClass('open');
}
function closeCandidateTools() {
    $('.head-inset').slideUp(1000).removeClass('open');
    $('#Top li a:visible').children('span').attr('class','icon arrow-white');
}
// ----- SAVED JOBS OPEN, CLOSE & COUNT CHECK
function checkSJCount() {
    if($('#jobCount').text() > "0") {
        $('.saved-jobs').css('cursor', 'pointer')
            .append("<span class='icon arrow-grey'></span>");
    }
}
function openSavedJobs(){
    $('ul.saved-list').slideDown(400, function() {
        if($.browser.msie) { // IE only as it cant render fadein without nasty black borders appearing
        } else {
            $('ul.saved-list li').each(function() {
                 $(this).animate({ opacity: 1 }, 400);
            });
        }
    });
    $('.saved-jobs span.icon.arrow-grey').attr('class','icon arrow-grey-down');
}
function closeSavedJobs(){
    if($.browser.msie) { // IE only as it cant render fadein without nasty black borders appearing
         $('ul.saved-list').slideUp(400);
    } else {
        $('ul.saved-list li').each(function() {
            $(this).animate({ opacity: 0 }, 400);      
        });
        setTimeout(function() { $('ul.saved-list').slideUp(400) }, 400);
    }
    $('.saved-jobs span.icon.arrow-grey-down').attr('class','icon arrow-grey');
}
// ----- SIMPLE DROPDOWN SELECT TO ACTIVATE SUBMIT
function enableSubmit(element) {
    var submit = $(element).siblings('input[type=submit]');
    var selectVal = $(element).val();
    if(selectVal != "0") 
        $(submit).removeAttr('disabled').removeClass('disabled');
    else 
        $(submit).attr('disabled','disabled').addClass('disabled');
}    
// ----- UPDATE FORM BUTTON ACTIONS  ----- NOTE: COMMENTED BITS ARE FOR WHEN THE FORM IS UPDATED VIA AJAX NOT POSTBACK
function hideUpdated(element, fieldset) {
    $(element).val("Update").removeClass("disabled");
    $(fieldset).children('p.form-note').slideUp(400);
    //$(getFieldset).find('input').each(function() {
    //    $(this).removeAttr('disabled'); 
    //});
    setTimeout(function() { $(fieldset).children('p.form-note').remove(); }, 400);
}
function updateForm(element) {
    $(element).val("Updated!").addClass("disabled");
    getFieldset = $(element).parents('fieldset');
    //$(getFieldset).find('input').each(function() {
    //    $(this).attr('disabled','disabled'); 
    //});
    var message = "<p class='form-note text-blue'>Your account details have successfully been updated.</p>";
    $(message).prependTo(getFieldset).slideDown(400);
    setTimeout(function() { hideUpdated(element, getFieldset); }, 7000);
}
// ---- POPUP FUNCTIONALITY
function showPopup(element) {
    if($.browser.msie) { // IE only as it cant render fadein to an opacity, nor position fixed elements correctly
        var getXPos = (document.body.offsetWidth / 2) - 250; 
        $('.overlay').css('display','block');
        $('.popup-wrap').css({
            'display': 'block',
            'left' : getXPos + 'px'
        });
    } else {
        $('.overlay').fadeIn(400);
        setTimeout(function() { $('.popup-wrap').fadeIn(400); }, 200);
    } 
    var getRel = $(element).attr('rel');
    $('#button-yes').attr('rel', getRel);
}
function hidePopup() {
    if($.browser.msie) {
        $('.overlay').css('display','none');
        $('.popup-wrap').css('display','none');
    } else {
        $('.overlay').fadeOut(400);
        setTimeout(function() { $('.popup-wrap').fadeOut(400); }, 200);
    }
}
function replaceDelete(element) {
    var getId = $(element).attr('id');
    var fakeDeleteButton = "<a onclick='showPopup(this)' rel='" + getId + "' class='text-blue'>Delete</a>";
    $(element).parent().append(fakeDeleteButton);
}
function confirmDelete(element) {
    var getId = $(element).attr('rel');
    $('#'+getId).click();
}

function checkPermission() {
    if($('.permission-radio input')[0].checked)
        allowed();
    else if ($('.permission-radio input')[1].checked)
        notAllowed();
    else
        uncheckedOnLoad(); //When both radio buttons are not checked on page load
}
function allowed() {
    $('.permission-radio').siblings('span:not(.validation-message,.permission-message)').css('display', 'block');
    $('.validation-message,.permission-message').css('display','none');
    $('.right-tabs.application').css('display','none');
    $('#spanPermissionDenied').hide();
}
function notAllowed() {
    $('.permission-radio').siblings('span:not(.validation-message,.permission-message)').css('display', 'none');
    $('.permission-message').css('display','block');
    $('.right-tabs.application').css('display','block');
    $('#spanPermissionDenied').show();
}
function uncheckedOnLoad() {
    $('.permission-radio').siblings('span').css('display', 'none');
    $('#spanPermissionDenied').hide();
}
// ---- FADE LEFT & RIGHT HEIGHT 
function fadeHeight() {
    var h = $('.home-splash').height();
    if ($('.grey-bar').length > 0) {
        var gh = $('.grey-bar').height();
        h = h + gh;
    }
    $('.fade-right, .fade-left').css('height', h+'px');
}

$(document).ready(function() {
    checkSJCount();
    fadeHeight();
    $('input').each(function() {
        applyRequired($(this));    
    });
    if($('.permission-radio').length > 0) {
        checkPermission();
    }
    $('.permission-radio input').change(function() { 
        checkPermission(); 
    });
    $('select.lone-select').change(function() {
         enableSubmit($(this));
     });
    // ---- INIT TOOLTIP PLUGIN
    $('.tooltip, .validation, span.cv-sent.tooltip, .truncated.tooltip').tooltip({
        track: true, 
        delay: 400, 
        showURL: false, 
        fixPNG: true, 
        extraClass: "pretty fancy", 
        top: -25, 
        left: 10,
        bodyHandler: function() {
            var helpText = $(this).text();
            if($(this).is('.truncated')) {
                var helpPopupHTML = "<p style='color:#000000;'>"+this.tooltipText+"</p>";
            } else {
                var helpPopupHTML = "<h3>"+this.tooltipText+"</h3>";
                helpPopupHTML += "<p>"+helpText+"</p><br />";
            }
            helpPopupHTML += "<p style='display:none' id='tooltip-msg'>(Left mouse click to hide this tooltip)</p>";
            setTimeout(function() { $("#tooltip-msg").fadeIn('slow') }, 1000);
            return $("<div />").html(helpPopupHTML);
        }
    });
    // ---- STYLE BREACRUMB CONTROL TO FOLLOW DESIGNS & ADD TITLES
    $('.breadcrumb a').each(function() {
        var text = $(this).text();
        $(this).attr('title', 'Click to return to the ' + text + ' page');
    });
    $('.breadcrumb a:last').attr('title', 'This is your current location');
    // ---- POSITION RIGHT TABS CORRECTLY [MAINLY FOR IE<=7]
    function positionRightList() {
        var getBrowserWidth = document.body.offsetWidth;
        var browserWidth = getBrowserWidth / 2;
        var getSiteWidth = $('.site-wrap').width();
        var siteWidth = getSiteWidth / 2;
        var rightPos = (browserWidth - siteWidth) -11; // minus 20 for actual tab layout
        $('.right-tabs').css('right',rightPos + 'px');
    }
    positionRightList();
    $(window).bind("resize", positionRightList);
    // ---- LOGIN & REGISTER | HIDE & SHOW
    // remove in-page anchoring
    $('.head-bar a[href=#Login],.head-bar a[href=/my_account/]').parent('li').addClass('no-background');
    $('.head-bar a[href=#Login],.head-bar a[href=#Register]').removeAttr('href').parent('li').css('display','block');
    // set click
    $('.head-bar .open-inset').click(function() {
        if($('.head-inset.open').length == 0) {
            openCandidateTools();
        } else {
            closeCandidateTools();
        }
    });
    // ---- LOGIN & REGISTER | VALIDATION
    $('fieldset input').blur(function() {
        var isRequired = checkRequired($(this));
        var fieldValue = $(this).val();
        if(isRequired && fieldValue == "") {
            $(this).siblings("span.validation").css('display','block');
        } else {
            $(this).siblings("span.validation").css('display','none');
        } 
        countInvalids($(this));
    });
    $('fieldset input').keydown(function() {
        countInvalids($(this));
    });
    $('.validation').click(function() {
        $(this).siblings('input').focus();
    });
    // ---- SECTOR CHOICE CONTINENT MAP & CHECKBOXES
    $('map area').hover(function() {
        var location = $(this).attr('id');
        $('#ImageMap').parent().addClass(location);
    }, function() {
        $('#ImageMap').parent().removeClass();
    });
    
    $('map area').click(function() {
        var location = $(this).attr('id');
        $('#ImageMap').removeClass();
        $('#ImageMap').addClass(location);
        $('ul.sector-choice').contents().find('input').each(function() {
            $(this).removeAttr('checked');
        });
        var relCheckbox = $('.sector-choice ul li label input[title=' + location + ']');
        $(relCheckbox).attr('checked','checked');
        $('.checkbox-glow').removeClass('highlight');
        $(relCheckbox).siblings('a').addClass('highlight');
        $('.grey-bar .btn.search.disabled').removeClass('disabled');
        $('.grey-bar .btn.search').attr('title', 'Search for jobs');
    });
    
    $('.sector-choice ul li').children().hover(function() {
        var location = $(this).children('span').text().replace(" ", "");
        $('#ImageMap').parent().addClass(location);
    }, function() {
        $('#ImageMap').parent().removeClass();
    });
    
    $('.sector-choice ul li label').focusin(function() {
        var location = $(this).children('span').text().replace(" ", "");
        $('#ImageMap').parent().addClass(location);
    });
    
    $('.sector-choice ul li label').focusout(function() {
        $('#ImageMap').parent().removeClass();
    });
    
    $('.sector-choice ul li label').keydown(function(event) {
        var location = $(this).children('span').text().replace(" ", "");
        if(event.keyCode == '13') {
            $(this).children('a').addClass('highlight');
            $('#ImageMap').removeClass();
            $('#ImageMap').addClass(location);
        }
    });
    
    $('.sector-choice ul li label').click(function() {
        var location = $(this).children('span').text().replace(" ", "");
        $(this).parent('li').siblings('li').children('input').removeAttr('checked');
        $(this).parent('li').siblings('li').children('label').children('a').removeClass('highlight');
        $(this).children('a').addClass('highlight');
        $(this).children('input').attr('checked','checked');
        $('#ImageMap').removeClass();
        $('#ImageMap').addClass(location);
        $('.grey-bar .btn.search.disabled').removeClass('disabled');
        $('.grey-bar .btn.search').attr('title', 'Search for jobs');
    });
    
    $('.sector-choice ul li label input').each(function() {
        var offset = $(this).position();
        $(this).parent('label').append("<a class='checkbox-glow' href='#Sector'></a>");
        $(this).siblings('a').css({
            'top' : offset.top
        });
        $(this).css('visibility','hidden');
    });
    
    $('.popup-wrap .disabled, .overlay').bind('click', function() { hidePopup(); });
    // ---- YOUR ACCOUNT ALERT FUNCTIONALITY
    $('#AddJobAlertLink').toggle(function() {
        $('.table-add-row').show(0);
        $(this).text("Cancel alert job add");
    }, function() {
        $('.table-add-row').hide(0);
        $(this).text("Add new job alert");
    });
    $('.EditJobAlertLink').toggle(function() {
        var getNextEditRow = $(this).parent('td').parent('tr').next('tr.table-edit-row');
        $(getNextEditRow).show(0);
        $(this).text("Cancel edit");
    },function() {
        var getNextEditRow = $(this).parent('td').parent('tr').next('tr.table-edit-row');
        $(getNextEditRow).hide(0);
        $(this).text("Edit");
    });
    // ---- CONTENT ACCORDION FUNCTIONALITY
    $('.accordion .top h1.header').toggle(function() {
        $(this).siblings('p').slideUp(400, function() {
            $(this).siblings('h1.header').css('margin-bottom', '0px');
        });
        $(this).siblings('span.icon').attr('class', 'icon arrow-grey');
    },function() {
        $(this).siblings('p').slideDown(400);
        $(this).siblings('span.icon').attr('class', 'icon arrow-grey-down');
        $(this).css('margin-bottom', '8px');
    });
    // ---- SAVED JOBS ACCORDION FUNCTIONALITY
    $('#savedJobLink').toggle(function() {
        if($('#jobCount').text() > "0") {
            openSavedJobs();
        } else {
           return;
        }
    }, function() {
        closeSavedJobs();
    });
});
