﻿hasHappened = new Boolean();
var redirectUrl;
blnToastListFull = new Boolean();
var iToastIntervalId;
function ReceiveServerData(arg, context) {
}
function UpdateValidator(state, elName) {
    ValidatorEnable(document.getElementById(elName), state);
}
//function to capture javascript errors and log them using in
//Emah using the ClientErrorHandler
window.onerror = function(msg, url, linenumber) {

    var thisdata = {  message: msg,
                    scriptUrl: url,
                    pageUrl: location.href,
                    lineNumber: linenumber
                }
    $.post("/Handlers/ClientErrorHandler.ashx", thisdata, null, "json");
}
//Switches on and off the essential flags
function essentialSwitch(obj1, obj2, checkboxcollection, imgClassOn, imgClassOff, tooltipOn, tooltipOff, checkboxExact, imgExact) {
    var chkBoxCollection = checkboxcollection.split('|');
    var essFlag = document.getElementById(obj1);
    var essImage = document.getElementById(obj2);
    var allOnFlag = true;
    
    if (essFlag.checked == true) {
        essFlag.checked = false;
        essImage.alt = tooltipOff;
        essImage.title = tooltipOff;
        essImage.className = imgClassOff;
        //essImage.src = imgOff;
        for (var i = 0; i < chkBoxCollection.length; i++)
        {
            if (!document.getElementById(chkBoxCollection[i]).checked){
                allOnFlag = false;
                break;
            }   
        }
        if (!allOnFlag) {
            document.getElementById(checkboxExact).checked = false;
            document.getElementById(imgExact).className = imgClassOff + "Exact";
        }
    }
    else {
        essFlag.checked = true;
        essImage.alt = tooltipOn;
        essImage.title = tooltipOn;
        //essImage.src = imgOn;
        essImage.className = imgClassOn;
        //essImage.setAttribute("class", imgClassOn);
        for (var i = 0; i < chkBoxCollection.length; i++)
        {
            if (!document.getElementById(chkBoxCollection[i]).checked){
                allOnFlag = false;
                break;
            }   
        }
        if (allOnFlag) {
            document.getElementById(checkboxExact).checked = true;
            document.getElementById(imgExact).className = imgClassOn + "Exact";
        }
    }
}

function essentialSwitchAll(initcheckbox, initimg, checkboxcollection, imgcollection, imgClassOn, imgClassOff, tooltipOn, tooltipOff, fromCheckBox, bReset) {
    var chkBoxCollection = checkboxcollection.split('|');
    var imgCollection = imgcollection.split('|');
    var essFlag = document.getElementById(initcheckbox);
    var essImage = document.getElementById(initimg);
    var currStat = essFlag.checked;

    //it is from hitting the checkbox, therefor invert the status
    if (fromCheckBox.toLowerCase() === 'true')
        currStat = !essFlag.checked;
    
    //it is a reset, therefor fake a false, to set everything to true
    if (bReset.toLowerCase() === 'true')
        currStat = false;
    
    //set to false
    if (currStat == true) {
        //essImage.src = imgOff;
        essImage.className =  imgClassOff + "Exact";
        essFlag.checked = false;
        for (var i = 0; i < chkBoxCollection.length; i++) 
            document.getElementById(chkBoxCollection[i]).checked = false;

        for (var i = 0; i < imgCollection.length; i++) {
            //document.getElementById(imgCollection[i]).src = imgOff;
            document.getElementById(imgCollection[i]).className = imgClassOff;
            document.getElementById(imgCollection[i]).alt = tooltipOff;
            document.getElementById(imgCollection[i]).title = tooltipOff;
        }

    } else {
        //essImage.src = imgOn;
        essImage.className = imgClassOn + "Exact";
        essFlag.checked = true;
        for (var i = 0; i < chkBoxCollection.length; i++)
            document.getElementById(chkBoxCollection[i]).checked = true;

        for (var i = 0; i < imgCollection.length; i++) {
            //document.getElementById(imgCollection[i]).src = imgOn;
            document.getElementById(imgCollection[i]).className = imgClassOn;
            document.getElementById(imgCollection[i]).alt = tooltipOn;
            document.getElementById(imgCollection[i]).title = tooltipOn;
        }
    }
}

//onblur and pa
function loadFieldTempValue(obj, objStyle, defaultText) {
    var ttobj = document.getElementById(obj);
    if (ttobj.value == '' || ttobj.value == defaultText) {
        ttobj.className = objStyle + "A";
        ttobj.value = defaultText;
    }
}

//onfocus
function clearFieldTempValue(obj, objStyle, objStyleAlt, defaultText) {
    var ttobj = document.getElementById(obj);
    if (ttobj.className == objStyle) {
        ttobj.value = '';
        ttobj.className = objStyleAlt;
    }
}

//Reset DDL
function resetDropDownList(obj, defaultValue) {
    var ttobj = document.getElementById(obj);
    ttobj.selectedindex = 0
    ttobj.options[0].selected = true;

    for (var i = 0; i < ttobj.options.length; i++) {
        if (ttobj.options[i].value == defaultValue) {
            ttobj.options[i].selected = true;
            return;
        }
    }
}
//hides the results grid
function hideResultsGrid(obj) {
    var ttobj = document.getElementById(obj);
    if (ttobj)
        ttobj.className = 'displayNone';
}

//Clear textbox
function clearTextBox(obj) {
    var ttobj = document.getElementById(obj);
    if(ttobj != null) {
        ttobj.value = '';    
    }
}

function getPageSizeWithScroll() {
    if (window.innerHeight && window.scrollMaxY) {
        // Firefox         
        yWithScroll = window.innerHeight + window.scrollMaxY;
        xWithScroll = window.innerWidth + window.scrollMaxX;
    }
    else if (document.body.scrollHeight > document.body.offsetHeight) { // all but Explorer Mac
        yWithScroll = document.body.scrollHeight;
        xWithScroll = document.body.scrollWidth;
    }
    else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
        yWithScroll = document.body.offsetHeight;
        xWithScroll = document.body.offsetWidth;
    }
    arrayPageSizeWithScroll = new Array(xWithScroll, yWithScroll);
    //alert( 'The height is ' + yWithScroll + ' and the width is ' + xWithScroll );
    return arrayPageSizeWithScroll;
}

//returns the available height and width of the screen
function getViewPort() {
    var viewportwidth;
    var viewportheight;

    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight

    if (typeof window.innerWidth != 'undefined') {
        viewportwidth = window.innerWidth,
          viewportheight = window.innerHeight
    }

    // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)

    else if (typeof document.documentElement != 'undefined'
         && typeof document.documentElement.clientWidth !=
         'undefined' && document.documentElement.clientWidth != 0) {
        viewportwidth = document.documentElement.clientWidth,
        //viewportheight = document.documentElement.clientHeight - use offsetHeight instead, seems to work better
           viewportheight = (document.documentElement.clientHeight > document.body.offsetHeight) ? document.documentElement.clientHeight : document.body.offsetHeight;
    }

    // older versions of IE

    else {
        viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
           viewportheight = document.getElementsByTagName('body')[0].clientHeight
    }
    arrayViewPort = new Array(viewportwidth, viewportheight);
    //alert( 'The height is ' + yWithScroll + ' and the width is ' + xWithScroll );
    return arrayViewPort;

}

//returns the available size of window, the height betwen the menus at the top and the scrollbar at the bottom, as you see it.
function getWindowSize() {
    var myWidth = 0, myHeight = 0;
    if (typeof (window.innerWidth) == 'number') {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    arrayWindowSize = new Array(myWidth, myHeight);
    return arrayWindowSize;

}

function DisplayLogoutPopUp() {
    var loadUrl = "/secure/LogoutPopup.aspx";
    var ajax_load = "<img src='/i/progress_indicator.gif' alt='loading...' />";
    $("#modalBody")
            .html(ajax_load)
            .load(loadUrl + " #Signout");
}

function DisplayDeleteUserPopUp(tableRow, divMessage, lblMessage, userId, userName, activeUserCount, TotalUserCount, enabledClass) {
    var loadUrl = "/secure/administration/DeleteUserPopup.aspx?tr=" + tableRow + "&dm=" + divMessage + "&lm=" + lblMessage + "&uid=" + userId + "&un=" + userName + "&auc=" + activeUserCount + "&tuc=" + TotalUserCount + "&ec=" + enabledClass + "";
    var ajax_load = "<img src='/i/progress_indicator.gif' alt='loading...' />";
    $("#modalBody")
            .html(ajax_load)
            .load(loadUrl + " #DeleteUser");
}

//doSplash('modalPage', 'modalContainer', 'modal', '300', '500', 'modalPageiframe')
function doSplash(obj1, obj2, obj3, iwidth, iheight, iframe, background) {
    var el1 = document.getElementById(obj1);
    var el2 = document.getElementById(obj2);
    var el3 = document.getElementById(obj3);
    var el4 = document.getElementById(iframe);

    scroll(0, 0);
    el1.style.display = 'block';
    el3.style.width = iwidth + "px";
    
    //Get the screen height and width
    var maskHeight = $(document).height();
    var maskWidth = $(window).width();

    //Set heigth and width to mask to fill up the whole screen
    $('#' + iframe + '').css({ 'width': maskWidth, 'height': maskHeight });
    $('#' + background + '').css({ 'width': maskWidth, 'height': maskHeight });

    //transition effect
    $('#' + iframe + '').show();
    $('#' + background + '').css('opacity', 0.8).show();
    $('#' + obj2 + '').show();

    //Get the window height and width
    var winH = $(window).height();
    var winW = $(window).width();

    
    //Set the popup window to center
    $('#' + obj2 + '').css('top', winH / 2 - $('#' + obj2 + '').height() / 2);
    $('#' + obj2 + '').css('left', winW / 2 - $('#' + obj2 + '').width() / 2);
}

//hides the modal
function hideSplash(obj1) {
    var el = document.getElementById(obj1);
    if (el) {
        el.style.display = 'none';
    }
}

//dynamically switching stylessheets
function loadjscssfile(filename, filetype) {
    if (filetype == "js") { //if filename is a external JavaScript file
        var fileref = document.createElement('script')
        fileref.setAttribute("type", "text/javascript")
        fileref.setAttribute("src", filename)
    }
    else if (filetype == "css") { //if filename is an external CSS file
        var fileref = document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    if (typeof fileref != "undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref)
}
function removejscssfile(filename, filetype) {
    var targetelement = (filetype == "js") ? "script" : (filetype == "css") ? "link" : "none" //determine element type to create nodelist from
    var targetattr = (filetype == "js") ? "src" : (filetype == "css") ? "href" : "none" //determine corresponding attribute to test for
    var allsuspects = document.getElementsByTagName(targetelement)
    for (var i = allsuspects.length; i >= 0; i--) { //search backwards within nodelist for matching elements to remove
        if (allsuspects[i] && allsuspects[i].getAttribute(targetattr) != null && allsuspects[i].getAttribute(targetattr).indexOf(filename) != -1)
            allsuspects[i].parentNode.removeChild(allsuspects[i]) //remove element by calling parentNode.removeChild()
    }
}
function createjscssfile(filename, filetype) {
    if (filetype == "js") { //if filename is a external JavaScript file
        var fileref = document.createElement('script')
        fileref.setAttribute("type", "text/javascript")
        fileref.setAttribute("src", filename)
    }
    else if (filetype == "css") { //if filename is an external CSS file
        var fileref = document.createElement("link")
        fileref.setAttribute("rel", "stylesheet")
        fileref.setAttribute("type", "text/css")
        fileref.setAttribute("href", filename)
    }
    return fileref
}
function replacejscssfile(oldfilename, newfilename, filetype) {
    var targetelement = (filetype == "js") ? "script" : (filetype == "css") ? "link" : "none" //determine element type to create nodelist using
    var targetattr = (filetype == "js") ? "src" : (filetype == "css") ? "href" : "none" //determine corresponding attribute to test for
    var allsuspects = document.getElementsByTagName(targetelement)
    for (var i = allsuspects.length; i >= 0; i--) { //search backwards within nodelist for matching elements to remove
        if (allsuspects[i] && allsuspects[i].getAttribute(targetattr) != null && allsuspects[i].getAttribute(targetattr).indexOf(oldfilename) != -1) {
            var newelement = createjscssfile(newfilename, filetype)
            allsuspects[i].parentNode.replaceChild(newelement, allsuspects[i])
        }
    }
}

//change stylesheet
function changeStyle(StyleID) {
    removejscssfile("/s/1.css", "css")
    removejscssfile("/s/4.css", "css")
    removejscssfile("/s/6.css", "css")
    loadjscssfile("/s/" + StyleID + ".css", "css")
    //updateCSSPostA('UpdateCSS|'+ StyleID,"");
    updateCSSPost(StyleID);
}
//changes the css file
function updateCSSPost(StyleID) {
    var data = { "StyleID": "" + StyleID + "" };
    $.ajax({
        type: "Get",
        url: "/../Handlers/UpdateCSSHandler.ashx",
        dataType: "json",
        data: data,
        cache: false,
        async: true
    });
}
//function updateCSSPostA(val, context) {
//    updateCSSOnServer(val, context);
//}
//hides an element
function hideElement(id) {
    var me = document.getElementById(id);
    me.style.display = "none";
}

function changeTxtBoxValue(txtBox, newValue) {
    var me = document.getElementById(txtBox);
    me.value = newValue;
}

// Maximum word length
function checkWordLen(obj, wordLen) {
    var len = obj.value.split(/[\s]+/);
    if (len.length > wordLen) {
        obj.oldValue = obj.value != obj.oldValue ? obj.value : obj.oldValue;
        obj.value = obj.oldValue ? obj.oldValue : "";
        return false;
    }
    return true;
}
//Max character length for texxt area
function textCounter(field, maxlimit) {
    if (field.value.length > maxlimit) // if too long...trim it!
        field.value = field.value.substring(0, maxlimit);
}

function loactionRadiusCheck(location, radius, stdClass) {
    var loc = document.getElementById(location);
    var rad = document.getElementById(radius);

    if (loc.className == stdClass && loc.value != '' && rad.value == '') {
        if (rad.disabled == false)
            rad.value = '50';
    }
    if (loc.value == '')
        rad.value = '';
}

//when page has loaded run jQuery
$(document).ready(function() {

    //this handles when we navigate away from the search page
    //without saving a search
    bindNavAway();
    



    //round Corner Buttons
    $('.btn').each(function() {
        var b = $(this);
        var tt = b.text() || b.val();
        if ($(':submit,:button', this)) {
            b = $('<a>').insertAfter(this).addClass(this.className).attr('id', this.id);
            $(this).remove();
        }
        b.text('').css({ cursor: 'pointer' }).prepend('<i></i>').append($('<span>').text(tt).append('<i></i><span></span>'));
    });
    $('.btna').each(function() {
        var b = $(this);
        var tt = b.text() || b.val();
        if ($(':submit,:button', this)) {
            b = $('<a>').insertAfter(this).addClass(this.className).attr('id', this.id);
            $(this).remove();
        }
        b.text('').css({ cursor: 'pointer' }).prepend('<i></i>').append($('<span>').text(tt).append('<i></i><span></span>'));
    });
    //
    $('.Tags').click(function(event) {
        $('.Tags').removeClass("bold")
        $(this).addClass("bold");
    });
});


function hideLoginError(errorPnl) {
    if (document.getElementById(errorPnl)) {
        document.getElementById(errorPnl).style.display = 'none';
    }
}

//search overlay when search button clicked
function showSearchingScreen() {
    $('.RG').slideUp("slow");
    var obj = $('#bodyRepeat')
    var oHeight = obj.height();
    var oWidth = obj.width();
    var searchingContent = "<div id='searchLoadingDiv' class='rgLoading' style='width:" + (oWidth - 2) + "px; height:" + oHeight + "px;'><div>Searching</div><br /><br /><img src='/i/loadingGrid.gif' alt='loading' /></div>"; ;
    obj.prepend(searchingContent).fadeIn('slow');
}

//This function validates the search form before postback
function validateSearchForm(txtFrom, lblFrom, strFromError, txtTo, lblTo, strToError, strToFromError, txtLocationRadius, lblLocationRadius, strLocRadError, txtLocation, strLocationError) {
    //moves the tags from the ul li list to a hidden field
    addjson_Tags();
    addjson_Nationality();
    addjson_Language();
    
    var Message = '';
    var star = '<span style="color:red;">*</span>'
    var distLabel = $('#' + lblLocationRadius + '');
    //clean up the label from previous error
    distLabel.children().remove();
    
    var isFromInt = new Boolean(false);
    var isToInt = new Boolean(false);
    //LocationRadius checking
    var LocationRadius = document.getElementById(txtLocationRadius).value;
    if (LocationRadius != '') {
        if (!validateIsPositiveInt(LocationRadius)) {
            Message += strLocRadError + '\n';
            distLabel.append(star);
        }
    }
    //Check location
    var Location = document.getElementById(txtLocation).value;
    if (Location != '') {
        if (!SubmitSearchForm(txtLocation, 'StandardError', strLocationError)) {
            Message += strLocationError + '\n';
        }
    }
    //Check if error has been raised
    if (Message != '') {
        var Message2 = 'Your search has the following error(s) \n';
        Message2 += Message
        alert(Message2);
        return false;
    }
    else {
        //clear the fields with temp values in them
        onclickClearFieldTempValues();
        //return true so search runs
        setSearchButtonClick();
            return true;
        }
}
//validate a field is a positive int
function validateIsPositiveInt(field) {
    PosIntpat = /^[1-9]+[0-9]*$/;
    if (!PosIntpat.test(field)) {
        return false;
    }
    return true;
}
//validate a filed is an int
function validateIsInt(field) {
    PosIntpat = /^\d+$/;
    if (!PosIntpat.test(field)) {
        return false;
    }
    return true;
}

//Tool tip function
var tooltip = function() {
    var id = 'tt';
    var top = 3;
    var left = 3;
    var maxw = 300;
    var speed = 10;
    var timer = 20;
    var endalpha = 95;
    var alpha = 0;
    var tt, t, c, b, h;
    var ie = document.all ? true : false;
    return {
        show: function(v, w) {
            if (tt == null) {
                tt = document.createElement('div');
                tt.setAttribute('id', id);
                t = document.createElement('div');
                t.setAttribute('id', id + 'top');
                c = document.createElement('div');
                c.setAttribute('id', id + 'cont');
                b = document.createElement('div');
                b.setAttribute('id', id + 'bot');
                tt.appendChild(t);
                tt.appendChild(c);
                tt.appendChild(b);
                document.body.appendChild(tt);
                tt.style.opacity = 0;
                tt.style.filter = 'alpha(opacity=0)';
                document.onmousemove = this.pos;
            }
            tt.style.display = 'block';
            c.innerHTML = v;
            tt.style.width = w ? w + 'px' : 'auto';
            if (!w && ie) {
                t.style.display = 'none';
                b.style.display = 'none';
                tt.style.width = tt.offsetWidth;
                t.style.display = 'block';
                b.style.display = 'block';
            }
            if (tt.offsetWidth > maxw) { tt.style.width = maxw + 'px' }
            h = parseInt(tt.offsetHeight) + top;
            clearInterval(tt.timer);
            tt.timer = setInterval(function() { tooltip.fade(1) }, timer);
        },
        pos: function(e) {
            var u = ie ? event.clientY + document.documentElement.scrollTop : e.pageY;
            var l = ie ? event.clientX + document.documentElement.scrollLeft : e.pageX;
            tt.style.top = (u - h) + 'px';
            tt.style.left = (l + left) + 'px';
        },
        fade: function(d) {
            var a = alpha;
            if ((a != endalpha && d == 1) || (a != 0 && d == -1)) {
                var i = speed;
                if (endalpha - a < speed && d == 1) {
                    i = endalpha - a;
                } else if (alpha < speed && d == -1) {
                    i = a;
                }
                alpha = a + (i * d);
                tt.style.opacity = alpha * .01;
                tt.style.filter = 'alpha(opacity=' + alpha + ')';
            } else {
                clearInterval(tt.timer);
                if (d == -1) { tt.style.display = 'none' }
            }
        },
        hide: function() {
            clearInterval(tt.timer);
            tt.timer = setInterval(function() { tooltip.fade(-1) }, timer);
        }
    };
} ();

//Scrolls the screen to a candidate on the results grid
function scrollToCandidateOnGrid(candidateId) {
    var x = $("#trResultsRow" + candidateId + "").offset().left;
    var y = $("#trResultsRow" + candidateId + "").offset().top;
    window.scrollTo(x, y - 220);
}

//This adds the tag in the search page to a hidden div when
//the search button is clicked
function addjson_Tags() {
    var objOutPut = "";
    var liCollection = $("ul.token-input-list-facebook").children("li");
    if (liCollection.length > 0) {
        for (var i = 0; i < liCollection.length - 1; i++) {
            var p = $('p', liCollection[i]);
            objOutPut = objOutPut + "{\"id\": \"" + p[0].id + "\",  \"name\": \"" + p[0].innerHTML.replace(/\"/gi,"\\\"") + "\", \"agency\":" + (p.hasClass("a") ? true : false) + "}";
            if (i < liCollection.length-2)
                objOutPut = objOutPut + ",";
        }
        objOutPut = "[" + objOutPut + "]";
        $('.TagCollection').val(objOutPut);
    }
}

//clears the tag tokens and hidden json field
function clearTags() {
    //clear the hidden value which holds the json string
    $('.TagCollection').val("");
    //remove all the children of the ul which are a token
    $("ul.token-input-list-facebook").children("li.token-input-token-facebook").remove();
}

function addjson_Nationality() {
    var objOutPut = "";
    var liCollection = $("ul.token-input-list-facebook-nationality").children("li");
    if (liCollection.length > 0) {
        for (var i = 0; i < liCollection.length - 1; i++) {
            var p = $('p', liCollection[i]);
            objOutPut = objOutPut + "{\"id\": \"" + p[0].id + "\",  \"name\": \"" + p[0].innerHTML.replace(/\"/gi, "\\\"") + "\"}";
            if (i < liCollection.length - 2)
                objOutPut = objOutPut + ",";
        }
        objOutPut = "[" + objOutPut + "]";
        $('.NationalityCollection').val(objOutPut);
    }
}

//clears the tag tokens and hidden json field
function clearNationality() {
    //clear the hidden value which holds the json string
    $('.NationalityCollection').val("");
    //remove all the children of the ul which are a token
    $("ul.token-input-list-facebook-nationality").children("li.token-input-token-facebook").remove();
}

function addjson_Language() {
    var objOutPut = "";
    var liCollection = $("ul.token-input-list-facebook-language").children("li");
    if (liCollection.length > 0) {
        for (var i = 0; i < liCollection.length - 1; i++) {
            var p = $('p', liCollection[i]);
            objOutPut = objOutPut + "{\"id\": \"" + p[0].id + "\",  \"name\": \"" + p[0].innerHTML.replace(/\"/gi, "\\\"") + "\"}";
            if (i < liCollection.length - 2)
                objOutPut = objOutPut + ",";
        }
        objOutPut = "[" + objOutPut + "]";
        $('.LanguageCollection').val(objOutPut);
    }
}

//clears the tag tokens and hidden json field
function clearLanguage() {
    //clear the hidden value which holds the json string
    $('.LanguageCollection').val("");
    //remove all the children of the ul which are a token
    $("ul.token-input-list-facebook-language").children("li.token-input-token-facebook").remove();
}

//This displays and builds the loading screen
//on the results grid
function buildLoadingScreen() {
    //inject string html into dom
    $('.RG').prepend(loadingGridHTML).fadeIn('slow');
    //find the class .rgLoading and set styles
    $('.rgLoading').css("height", function() {
        return $('.RG').height() + 'px';
    });
    $('.rgLoading').css("width", function() {
        return $('.RG').width() + 'px';
    });
    $('.rgLoading').css("top", function(){
        return ($('.RG').position().top + 12) + "px";
    });
    //scroll to the top of the page quickly
    $('html, body').animate({ scrollTop: 0 }, 'fast');
}

//###jquery live functions

//used for actions menu hover over event on results grid
$(".ActionsMenu").live("click", function() {
    $('.ActionsMenuList').slideToggle();
});
//blocks the enter key from firing in the add tags modal
$('.txtAddTagBox').live('keydown', function(e) {
    if (e.which == 13 || e.which == 9) {
        e.preventDefault();
        return false;
    }
});
//Removes the unRead class when the Candidate Profile link is clicked on the results grid
$('.CandidateProfileLink').live('click', function(){
   $(this).parents().removeClass('UnRead'); 
});

//binds the auto complete functionality to the Add tag box
function bindAddTagAutoComplete() {
    autoCompleteUrl = $('#autoCompleteUrl').val();
    $(".txtAddTagBox").autocomplete(autoCompleteUrl, 
                                    {minChars: 2, 
                                    maxItemsToShow: 10
                                });
    $('.txtAddTagBox').focus();
}


//SaveSearch Success
function displaySuccessModal(result, displayDiv) {
    $get(displayDiv).innerHTML = result;
    $get(displayDiv).className = "";
    var id = "dialog";
    var winH = $(window).height();
    var winW = $(window).width();
    $('#' + id + '').css('top', winH / 2 - $('#' + id + '').height());
    $('#' + id + '').css('left', winW / 2 - $('#' + id + '').width() / 2);
    $('#' + id + '').fadeIn(1000)
                            .delay(2500)
                            .fadeOut(1000)
                            .hover(function() {
                                $(this).clearQueue();
                            },
                              function() {
                                  $(this).delay(1000).fadeOut(1000)
                              });
    $('.window .close').click(function(e) {
        //Cancel the link behavior
        e.preventDefault();
        $('.window').hide();
    });
}

//displays the navigate away unsaved search screen
function displayNavAway(displayDiv) {
    //laod in the unsaved search popup
    var loadUrl = "/secure/search/UnSavedSearchPopup.aspx";
    $.ajax({
        type: "Get",
        url: loadUrl,
        dataType: "html",
        data: "",
        cache: false,
        success: function (result) {
            if (result != "") {
                $("#" + displayDiv + "").empty().html(result).removeClass();
                displayModalMask($("#UnSavedSearch"), true);

                //bind click event to the continue button
                $('.window .ContinueButton').click(function (e) {
                    //Cancel the link behavior
                    e.preventDefault();
                    $('.SimpleModal').hide();
                    //detect if were trying to log out if throw logout out splash
                    if (redirectUrl.indexOf("logout.aspx") > 0) {
                        DisplayLogoutPopUp();
                        doSplash('modalPage', 'modalContainer', 'modal', '300', '500', 'modalPageiframe', 'modalBackground');
                        return false;
                    }
                    else {
                        //continue to redirect to where we were goin
                        window.location.replace(redirectUrl);
                    }

                });

                //bind click event to save search button
                $('.window .SaveThisSearch').click(function (e) {
                    //Cancel the link behavior
                    e.preventDefault();
                    $('.SimpleModal').hide();
                    loadSaveSearchDisplay();
                });

                //bind click event to close button
                $('.window .close').click(function (e) {
                    //Cancel the link behavior
                    e.preventDefault();
                    $('.SimpleModal').hide();
                });

                //set this back to false so that
                //the popup gets thrown next time global variable
                hasHappened = false;
            }
        },
        error: function (e) {
            //alert(e.responseText);
        }
    });
}

//bind saved search modal events
function bindSavedSearchEvents(){
    //Get the text from the hidden fields
    var saveText = $('.SaveSearchContainer #hdnSave').val();
    var replaceText = $('.SaveSearchContainer #hdnReplace').val();

    //if the selected radio is an already saved search populate the text field with the search name
    //and change the text on the button
    if ($('.SaveSearchContainer ul.SavedSearches input:radio:checked').val() > 0) {
        $('#txtSearchName').val($('.SaveSearchContainer ul.SavedSearches input:radio:checked').parent().next('div').children('label').text().trim());
        $('.SaveSearchContainer .button').text(replaceText);
    }

    //bind to the enter event in the text box and prevent postback
    //calling save search data instead
    $('#txtSearchName').bind('keydown', function(e) {
        if (e.which == 13) {
            e.preventDefault();
            saveSearchData();
        }
    });
    //Bind saved search Cancel button
    $('.SaveSearchContainer .CancelButton').bind('click', function(e) {
        hideSplash('SaveSearchModalPage');
    });
    //Bind the save search button
    $('.SaveSearchContainer .button').bind('click', function(e) {
        saveSearchData();
    });

    //bind click event on radio buttons to populate search name field and
    //search button text
    $(".SaveSearchContainer ul.SavedSearches input:radio").bind('click', function(e) {
        if ($(this).val() > 0) {
            $('#txtSearchName').val($(this).parent().next('div').children('label').text().trim());
            $('.SaveSearchContainer .button').text(replaceText);
        }
        else {
            $('#txtSearchName').val("");
            $('.SaveSearchContainer .button').text(saveText);
        }
    });
}

//Checks to see if a search has been saved or not?
function savedSearchChecker() {

    $.ajax({
        async: false,
        cache: false,
        type: 'GET',
        url: '/secure/search/Handlers/SearchChecker.ashx',
        data: '',
        contentType: 'application/json; charset=utf-8',
        dataType: 'html',
        success: function(result) {
            if (result == "") {
                isSaved = true;
            }
            else {
                isSaved = false;
            }
        },
        error: function() {
            isSaved = true;
        }
    });
    return isSaved;
}


function bindNavAway(){
    $('.navAway').bind("click", function(e) {
        var query = parent.location.toString();
        if (query.indexOf("search.aspx") > 0) {
            blnIsSaved = new Boolean();
            blnIsSaved = savedSearchChecker();
            if (blnIsSaved == false && hasHappened == false) {
                hasHappened = true;
                redirectUrl = e.currentTarget.toString();
                displayNavAway("modalDisplay");

                //prevent the redirect
                e.preventDefault();
                return false;
            }
            else {
                hasHappened = false;
                if (e.currentTarget.toString().indexOf("logout.aspx") > 0) {
                    e.preventDefault();
                    DisplayLogoutPopUp();
                    doSplash('modalPage', 'modalContainer', 'modal', '300', '500', 'modalPageiframe', 'modalBackground');
                    return false;
                }
            }
        }
        else {
            //if we are not on the search page and the logout button has been clicked
            if (e.currentTarget.toString().indexOf("logout.aspx") > 0) {
                e.preventDefault();
                DisplayLogoutPopUp();
                doSplash('modalPage', 'modalContainer', 'modal', '300', '500', 'modalPageiframe', 'modalBackground');
                return false;
            }
        }
    });
}


function setToastTimer(options) {
    //override the settings with options that have been passed in
    var settings = $.extend({
        ilistMaxLength: 5,
        iPollTime: 60000,
        sMaxSearchMessage: 'You have new search alerts',
        iRecruiterId: 0,
        iAgencyId:0,
        sHandlerUrl:'',
        toastSlideSpeed: 1000,
        searchAlertsTitle: "New Candidates"
        
    }, options);
    
    //build the url
    sUrl = settings.sHandlerUrl + "?r=" + settings.iRecruiterId + "&a=" + settings.iAgencyId;
    //get the toast body which we are going to inject data into
    var toastBody = $('.ToastBody');
    
    //make the ajax call to retrieve any results
    $.ajax({
        async: false,
        cache: false,
        type: 'GET',
        url: sUrl,
        data: '',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        success: function(result) {
            //check if we have results
            if (result && result != "" && result.length) {
                if ($('#ToastHolder').is(":visible")) {
                    //we just need to bind the new data
                    populate_Toast(result, toastBody, settings.ilistMaxLength, settings.sMaxSearchMessage, settings.searchAlertsTitle);
                }
                else {
                    populate_Toast(result, toastBody, settings.ilistMaxLength, settings.sMaxSearchMessage, settings.searchAlertsTitle);
                    
                    //show the toast
                    $('#ToastHolder').slideToggle(settings.toastSlideSpeed);
                }
            }
        },
        error: function() {
            //something went wrong don't alert the user
        }
    });

    //after toast has run call itself again
    iToastIntervalId = setTimeout(function() {
        setToastTimer(options);
    }, settings.iPollTime);
 
}

//This creates the ul li list for the toast
function populate_Toast(results, toastBody, listMaxLength, sMaxSearchMessage, sSearchAlertsTitle) {
    //Create the ul and add a class
    var this_liList = $('<ul/>')
    .addClass('ToastList');
    //Make sure we nave results
    if (results.length) {
        //work out if we have more than the require toast limit
        if (results.length <= listMaxLength) {
            for (var i in results) {
                if (results.hasOwnProperty(i)) {
                    //Add the results to the ul list
                    var this_li = $("<li><a href='/secure/search/search.aspx?ssid=" + results[i].SavedSearchId + "' class='navAway toastLink'>" + results[i].SearchName + "</a> - <a href='/secure/search/search.aspx?ssid=" + results[i].SavedSearchId + "' class='navAway'>" + results[i].NumberNewCandidates + "</a></li>")
                    .appendTo(this_liList);
                }
            }
            //empty the toast of any data and show results
            toastBody.empty();
            var this_searchAlertsTitle = $('<h1>' + sSearchAlertsTitle + '</h1>');
            this_searchAlertsTitle.appendTo(toastBody)
            this_liList
            .appendTo(toastBody)
            .fadeIn(3000);
        }
        else {
            //display generic results
            displayToastMessage(toastBody, sMaxSearchMessage);
        }
        //rebind the navigate away script as we are injecting more
        //links into the dom
        bindNavAway();
    }

}
//displays the toast message if to many results
function displayToastMessage(toastBody, sMaxSearchMessage) {
    blnToastListFull = true;
    toastBody.empty();
    var this_li = $("<ul class=\"MaxMessage\"><li><a href='/secure/search/SavedSearches.aspx' class='navAway toastLink'>" + sMaxSearchMessage + "</a></li></ul>")
    .appendTo(toastBody);
}


function refineReportsSetDateTime(txtFrom, txtTo, sDateFrom, sDateTo){
    $('#' + txtFrom + '').val(sDateFrom);
    $('#' + txtTo + '').val(sDateTo);
}


// Feedback methods

$(function() {
    var feedbackTab = {
        speed: 300,
        containerWidth: $('.feedback-panel').outerWidth(),
        containerHeight: $('.feedback-panel').outerHeight(),
        tabWidth: $('.feedback-tab').outerWidth(),
        init: function() {
            $('.feedback-panel').css('height', feedbackTab.containerHeight + 'px');
            $('a.feedback-tab').click(function(event) {
                if ($('.feedback-panel').hasClass('open')) {
                    $('.feedback-panel').animate({ left: '-' + feedbackTab.containerWidth }, feedbackTab.speed)
                            .removeClass('open');
                } else {
                    $('.feedback-panel').animate({ left: '0' }, feedbackTab.speed)
                            .addClass('open');
                }
                return false;
                event.preventDefault();
            });
        }
    };

    feedbackTab.init();
    $(".feedbackbutton").click(function() {
        var feedbacksubject = $("select#feedbacksubject").val();
        var feedbackmessage = $("textarea#feedbackmessage").val();
        var feedbackphone = $("input#feedbackphone").val();
        var feedbackcontact = $("input#feedbackcontact").is(':checked');
        var response_message = "<p>" + $('#hndThanksMessage').val() + "</p>";
        var dataString = 'feedbacksubject=' + feedbacksubject + '&feedbackmessage=' + feedbackmessage + '&feedbackphone=' + feedbackphone + '&feedbackcontact=' + feedbackcontact;
        if (feedbackmessage == "") {
            $('#feedbackerror').html("<strong>" + $('#hndFeedbackerror').val() +"</strong>");
            $('#feedbackmessage').css("background-color", "#FFFFE0");
            $("#feedbackerror").delay(3000).fadeOut(800, 0);
        } else {
            $.ajax({
                type: "POST",
                url: "/secure/feedback/Handlers/feedback.ashx",
                data: dataString,
                success: function(result) {
                    
                        $('#feedback-form-wrap').html("<div id='feedback-response-message'></div>");
                        $('#feedback-response-message').html("<p>" + response_message + "</p>")
							.hide()
							.fadeIn(500)
							.animate({ opacity: 1.0 }, 1000);
                        $(".feedbackclose").click(function(event) {
                        $('.feedback-panel').animate({ left: '-' + feedbackTab.containerWidth }, feedbackTab.speed)
                            .removeClass('open');
                            event.preventDefault();
                        });
                    
                }
            });
        }
        return false;
    });
});


//Start Message Center
function loadMessageCenter() {
    var this_macroList;
    var this_emailList;
    var recipients;
    var errorRecipients;
    var uploadedFile;
    $.ajax({
        type: "GET",
        url: "/secure/messageCenter/Handlers/LoadMessageCenterSendMessage.ashx",
        data: "",
        cache: false,
        dataType: "json",
        success: function (result) {
            //alert("success");
            if (result != null) {
                //read the json data into variables
                var controlHTML = result.HtmlControl;
                var ajaxErrorStatus = result.AjaxErrorStatus;
                recipients = result.ToRecipients;
                errorRecipients = result.ErrorRecipients;
                var macros = result.MessageMacros;

                //see if we have an error
                if (ajaxErrorStatus.IsError == false) {

                    $('#msModal').html(controlHTML);

                    this_macroList = $(".ms-message-input-button-list");
                    this_emailList = $(".token-input-list-ms");

                    //add the recipients
                    for (var i in recipients) {
                        if (recipients.hasOwnProperty(i)) {
                            insert_messagecenter_recipient(recipients[i].CandidateId, recipients[i].FirstName, recipients[i].LastName, recipients[i].EmailAddress)
                        }
                    }
                    //add the macros
                    for (var i in macros) {
                        if (macros.hasOwnProperty(i)) {
                            create_messagecenter_macro(macros[i]);
                        }
                    }
                    //hide the message center
                    $(".ms-close").click(function () {
                        display_messagecenter_cancel();
                    });

                    //cancel button click
                    $(".ms-cancel").click(function (e) {
                        display_messagecenter_cancel();
                        e.preventDefault();
                        return false;
                    });

                    $(".ms-send").click(function (e) {
                        send_message();
                        e.preventDefault();
                        return false;
                    });

                    //bind the file uploader stuff
                    bindFileUploader();

                    //show the modal
                    //$('#msModal').show();


                    $('#txtMessage').change(function () {
                        textCounter(document.getElementById('txtMessage'), 1000);
                    })
                    .keyup(function () {
                        textCounter(document.getElementById('txtMessage'), 1000);
                    })
                    .keydown(function () {
                        textCounter(document.getElementById('txtMessage'), 1000);
                    });


                    //
                    if (errorRecipients.length > 0) {
                        displayModalMask($("#MSInvalidEmail"), true);
                        
                        
                        if (recipients.length > 0) {
                            $('.ms-close-button', '#MSInvalidEmail').click(function (e) {
                                $("#MSInvalidEmail").remove();
                                e.preventDefault();
                                return false;
                            });
                        }
                        else {
                            $('.ms-close-button', '#MSInvalidEmail').hide();
                        }

                        $('.ms-return-button', '#MSInvalidEmail').click(function (e) {
                            $("#MSInvalidEmail").remove();
                            $(".ms-send-message").remove();
                            clear_messagecenter();
                            e.preventDefault();
                            return false;
                        });



                    }


                    displayModalMask($("#SendMessage"), true);
                }
                else {
                    //this is where we will manage any errors
                    //alert(ajaxErrorStatus.ErrorMessage);
                    switch (ajaxErrorStatus.ErrorType) {
                        case 1:
                            //Session Expired

                            $('#modalDisplay')
                            .html(controlHTML)
                            .removeClass("displayNone");
                            displayModalMask($("#SessionExpired"), true);



                            break;
                        case 2:
                            //No candidates selected
                            $('#modalDisplay')
                            .html(controlHTML)
                            .removeClass("displayNone");
                            displayModalMask($("#NoCandidatesSelected"), true);

                            $('.close', '#NoCandidatesSelected').click(function (e) {
                                //Cancel the link behavior
                                e.preventDefault();
                                $('#modalDisplay').empty();
                            });

                            $('#OKButton', '#NoCandidatesSelected').click(function (e) {
                                //Cancel the link behavior
                                e.preventDefault();
                                $('#modalDisplay').empty();
                                return false;
                            });


                            break;
                        case 3:
                            //To many candidates selected
                            $('#modalDisplay')
                            .html(controlHTML)
                            .removeClass("displayNone");
                            displayModalMask($("#ToManyCandidatesSelected"), true);

                            $('.close', '#ToManyCandidatesSelected').click(function (e) {
                                //Cancel the link behavior
                                e.preventDefault();
                                $('#modalDisplay').empty();
                            });

                            $('#OKButton', '#ToManyCandidatesSelected').click(function (e) {
                                //Cancel the link behavior
                                e.preventDefault();
                                $('#modalDisplay').empty();
                                return false;
                            });

                            break;
                    }
                }
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            //alert(XMLHttpRequest + "\n\n" + textStatus + "\n\n" + errorThrown);
        }
    });


    // inserts a recipient into the to field
    function insert_messagecenter_recipient(id, firstname, lastname, email) {
        var this_token = $("<li><p id=\"" + id + "\">" + firstname + "&nbsp;" + lastname + "&nbsp;" + email + "</p></li>")
        .addClass("token-input-token-ms")
        .appendTo(this_emailList);

        $("<span>x</span>")
        .addClass("token-input-delete-token-ms")
        .appendTo(this_token)
        .click(function() {
            delete_messagecenter_recipient($(this).parent());
            return false;
        });
    }

    //remove the recipient from the list
    function delete_messagecenter_recipient(recipient) {
        removeFromRecipients(recipient.children(':first')[0].id)
        recipient.remove();
        if (recipients != null && recipients.length <= 0) {
            loadNoCandidatesSelected();
        }
    }

    //add a macro to the list of auto fields
    function create_messagecenter_macro(macro) {
        var this_macro = $("<li><p>" + macro + "</p></li>")
        .addClass("ms-message-input-button")
        .appendTo(this_macroList)
        .click(function() {
            $('#txtMessage').insertAtCaret($(this).text());
        });
    }

    //clear the fields aand empty the variables
    function clear_messagecenter() {
        this_macroList.empty();
        this_emailList.empty();
        emptyArray(recipients);
        emptyArray(uploadedFile);
        emptyArray(errorRecipients);
        $('#txtSubject').val('');
        $('#txtMessage').val('');
        clearFileUploader();
        $('#msModal').html('');
    }

    //clears the file uploader fields values will need rebinding
    //call bindFileUploader after calling this function
    function clearFileUploader() {
        $('#fakefilepc').val('');
        $('#uploader').html($('#uploader').html());
    }
    
    //send the messages
    function send_message() {
        var replacer;
        var messageBody = $('#txtMessage').val();
        var subject = $('#txtSubject').val();
        var errorSubject = $('#MsErrorMessageSubject');
        errorSubject.empty();
        var errorMessageBody = $('#MsErrorMessageBody');
        errorMessageBody.empty();
        var messageData = {
            "Subject": "" + subject + "",
            "Attachment": "" + JSON.stringify(uploadedFile, replacer) + "",
            "Message": "" + messageBody + "",
            "Recipients": "" + JSON.stringify(recipients, replacer) + ""
        }
        //check the message body and subject are not empty
        if (messageBody != '' && subject != '') {
            
            //do something here to show the message is sending
            $('#msModal').hide();
            //try sending the message
            $.ajax({
                type: "POST",
                url: "/secure/messageCenter/Handlers/SendMessageHandler.ashx",
                data: messageData,
                dataType: "json",
                success: function (result) {
                    if (result != null) {
                        var ajaxErrorStatus = result.AjaxErrorStatus;
                        var htmlControl = result.HtmlControl;
                        if (ajaxErrorStatus.IsError == false) {
                            $('#msModal').show();
                            $('#msModal').html(htmlControl);
                            displayModalMask($('#MessageSent'), false);
                            $('.close', '#MessageSent').click(function (e) {
                                e.preventDefault();
                                $('.window').hide();
                            });

                            $("#dialog", "#MessageSent")
                            .delay(1500)
                            .fadeOut(1000, function () {
                                $('#msModal').empty();
                            })
                            .hover(function () {
                                $(this).clearQueue();
                            },
                              function () {
                                  $(this).delay(1000)
                                  .fadeOut(1000, function () {
                                      $('#msModal').empty();
                                  });

                              });

                        }
                        else {
                            switch (ajaxErrorStatus.ErrorType) {
                                case 1:
                                    $('#modalDisplay')
                                    .html(controlHTML)
                                    .removeClass("displayNone");
                                    displayModalMask($("#SessionExpired"), true);
                                    break;
                                default:
                                    $('#msModal').show();
                                    $('#modalDisplay')
                                    .html(htmlControl)
                                    .removeClass("displayNone");
                                    displayModalMask($("#GenericError"), true);
                                    $('.close', '#GenericError').click(function (e) {
                                        e.preventDefault();
                                        $('#GenericError').remove();
                                    });
                            }
                        }
                    }
                    else {
                        //Noting came back from the handler
                        //alert("an unexpected error has occurred");
                    }
                }
            });
        }
        else {
            //handle Required fields
            if (subject == '') {

                var this_errorA = $("<div><p>" + $('#hndSubjectError').val() + "</p></div>")
                .addClass("ms-error")
                .appendTo(errorSubject);
            }
            if (messageBody == '') {
                var this_errorB = $("<div><p>" + $('#hndMessageBodyError').val() + "</p></div>")
                .addClass("ms-error")
                .appendTo(errorMessageBody);
            }
        }
    }
    //removes the recipent from the recipents data set
    function removeFromRecipients(id) {
        for (var i = 0; i < recipients.length; i++) {
            if (recipients[i].CandidateId == id) {
                recipients.remove(i);
                break;
            }
        }
    }
    //empty the array of data
    function emptyArray(arr) {
        if (arr != null) {
            for (var i = 0; i < arr.length+1; i++) {
                arr.remove(i);
            }
        }
    }

    function displayUploadErrorMessage(message) {
        var uploadedHolder = $('#uploaded');
        uploadedHolder.empty();
        var this_error = $("<div><p>" + message + "</p></div>")
        .addClass("ms-error")
        .appendTo(uploadedHolder);

        $("<a href='#'>" + $('#hndTryAgain').val() + "</a>")
        .addClass("ms-error-retry")
        .appendTo(this_error)
        .click(function() {
            removeFileUploadErrorMessage($(this).parent());
            return false;
        });
    }
    
    //displays the result of the uploaded file
    function addUploadedfile(uploadedFile) {
        var fileSize = "";
        //convert the file to kb
        fileSize = (uploadedFile.FileSize / 1024);
        if (fileSize > 1024) {
            fileSize = (fileSize / 1024).toFixed(1) + " mb";
        }
        else {
            fileSize = fileSize.toFixed(1) + " kb";
        }
        var uploadedHolder = $('#uploaded');
        uploadedHolder.empty();
        var this_file = $("<div><p id=\"" + uploadedFile.UploadId + "\">" + uploadedFile.FileName + " <span>(" + fileSize + ")</span></p></div>")
        .addClass("ms-uploaded-file")
        .appendTo(uploadedHolder);

        $("<span>x</span>")
        .addClass("ms-uploaded-file-delete")
        .appendTo(this_file)
        .click(function() {
            delete_uploaded_file($(this).parent());
            return false;
        });

    }
    //makes a call to delete the message in the cache
    //and removes the file from screen
    function delete_uploaded_file(file){
        $.ajax({
            type: "POST",
            url: "/secure/messageCenter/Handlers/DeleteUploadedFileHandler.ashx",
            data: uploadedFile,
            dataType: "json",
            success: function(result) {
                if (result != null) {
                    if (result.IsError == false) {
                        uploadedFile = null;
                        //remove the file token
                        file.remove();
                        //clear the file uploader data
                        clearFileUploader();
                        //rebind the file uploader events
                        bindFileUploader();
                        //show the file uploader
                        $('#uploader').show();
                    }
                    else {
                        //this is where we will manage any errors
                        //alert(result.ErrorMessage);
                    }
                }
            },
            error: function(e) {
                //alert(e.responseText);
            }
        });
    }

    function removeFileUploadErrorMessage(message) {
        //remove the file token
        message.remove();
        //clear the file uploader data
        clearFileUploader();
        //rebind the file uploader events
        bindFileUploader();
        //show the file uploader
        $('#uploader').show();
    }
    
    //binds the file uploader functionality
    function bindFileUploader() {
        $(function() {
            $('#filepc').change(function() {
                $('#fakefilepc').val($(this).val());
                $('#uploader').hide();
                var uploadingGif = "<img src='/i/progress_indicator.gif' alt='loading...' />";
                $('#uploaded').html(uploadingGif).show()
                $('#filepc').upload('/../secure/messageCenter/Handlers/FileUploadHandler.ashx', function(res) {
                    if (res.AjaxErrorStatus.IsError == false) {
                        uploadedFile = { "UploadId": res.UploadId, "FileType": res.FileType, "FileSize": res.FileSize, "FileName": res.FileName };
                        addUploadedfile(uploadedFile);
                    }
                    else {
                        //manage the error
                        displayUploadErrorMessage(res.AjaxErrorStatus.ErrorMessage);
                    }

                }, 'json');
            });
        });
    }
    //loads the no candidates selected modal
    function loadNoCandidatesSelected() {
        $.ajax({
            type: "Get",
            url: "/../secure/messageCenter/Handlers/NoCandidatesSelectedHandler.ashx",
            dataType: "html",
            success: function(result) {
                if (result != "") {
                    $('#msModal').append(result);
                    displayModalMask($("#NoCandidatesSelected"), true);
                    $('.close', '#NoCandidatesSelected').click(function(e) {
                        //Cancel the link behavior
                        e.preventDefault();
                        $('#msModal').empty();
                    });
                    $('.close-button', '#NoCandidatesSelected').click(function(e) {
                        //Cancel the link behavior
                        e.preventDefault();
                        $('#msModal').empty();
                    });
                }
            },
            error: function(e) {
                //alert("loadNoCandidatesSelected \n" + e.responseText);
            }
        });
    }

    function display_messagecenter_cancel() {
        $.ajax({
            type: "Get",
            url: "/../secure/messageCenter/Handlers/CancelMessageConfirmHandler.ashx",
            dataType: "html",
            success: function(result) {
                if (result != "") {
                    $('#msModal').append(result);
                    displayModalMask($("#MessageCancel"), true);
                    $('.ms-cancel-button', '#MessageCancel').click(function(e) {
                        $('#MessageCancel').remove();
                        e.preventDefault();
                        return false;
                    });
                    $('.ms-ok-button', '#MessageCancel').click(function(e) {
                        $('#msModal').empty();
                        e.preventDefault();
                        return false;
                    });
                }
            },
            error: function(e) {
                //alert("loadNoCandidatesSelected \n" + e.responseText);
            }
        });
    }
}
//End Message Center

//removes an item from an array based on value
Array.prototype.remove = function(from, to) {
    var rest = this.slice((to || from) + 1 || this.length);
    this.length = from < 0 ? this.length + from : from;
    return this.push.apply(this, rest);
};

//used for inserting
$.fn.insertAtCaret = function (tagName) {
    return this.each(function () {
        if (document.selection) {
            //IE support
            this.focus();
            sel = document.selection.createRange();
            sel.text = tagName;
            this.focus();
        } else if (this.selectionStart || this.selectionStart == '0') {
            //MOZILLA/NETSCAPE support
            startPos = this.selectionStart;
            endPos = this.selectionEnd;
            scrollTop = this.scrollTop;
            this.value = this.value.substring(0, startPos) + tagName + this.value.substring(endPos, this.value.length);
            this.focus();
            this.selectionStart = startPos + tagName.length;
            this.selectionEnd = startPos + tagName.length;
            this.scrollTop = scrollTop;
        } else {
            this.value += tagName;
            this.focus();
        }
    })
};

//call to load the expired session
function sessionExpired() {
    $.ajax({
        type: "Get",
        url: "/Handlers/SessionExpiredHandler.ashx",
        dataType: "html",
        success: function(result) {
            if (result != null) {
                $('#modalDisplay')
                .html(result)
                .show();
                displayModalMask($("#SessionExpired"), true)
            }
        },
        error: function(e) {
            //alert(e.responseText);
        }
    });
}



//displays the modal pass in the out container
function displayModalMask(container, blnShowMask) {
    var winH = $(window).height();
    var winW = $(window).width();
    $("#dialog", container).css('top', winH / 2 - $("#dialog", container).height() / 2)
                            .css('left', winW / 2 - $("#dialog", container).width() / 2)
                            .fadeIn(500);
    if (blnShowMask == true) {
        //Get the screen height and width  
        var maskHeight = $(document).height();
        var maskWidth = $(window).width();
        //Set height and width to mask to fill up the whole screen and transition affect
        $('#mask', container).css({ 'width': maskWidth, 'height': maskHeight })
                        .fadeTo("slow", 0.5)
                        .fadeIn(300);
    }
}

function ErrorFeedbackClearBox(element, sDefaultMessage, sErrorMessage, sStartClass, sErrorClass) {
    var thisElement = $("#" + element + "");
    if (thisElement.val() == sDefaultMessage || thisElement.val() == sErrorMessage) {
        thisElement.val("").removeClass(sErrorClass).removeClass(sStartClass).addClass(sStartClass);
    }
}

function ErrorFeedbackReset(element, sDefaultMessage, sErrorMessage, sStartClass, sErrorClass){
    var thisElement = $("#" + element + "");
    if (thisElement.val() == sDefaultMessage || thisElement.val() == sErrorMessage || thisElement.val() == '') {
        thisElement.val(sDefaultMessage).removeClass(sErrorClass).removeClass(sStartClass).addClass(sStartClass);
    }
}

function validateErrorFeedbackForm(element, sDefaultMessage, sErrorMessage, sErrorClass) {
    var thisElement = $("#" + element + "");
    if (thisElement.val() == sDefaultMessage || thisElement.val() == sErrorMessage || thisElement.val() == '') {
        thisElement
            .val(sErrorMessage)
            .addClass(sErrorClass);
        return false;
    }
}
function validateErrorFeedbackFormA(txtMessage, sDefaultMessage, sErrorMessage, sErrorClass, txtName, sDefaultName, sTextBoxErrorClass, sNameErrorMessage, txtEmail, sDefaultEmail, sEmailErrorMessage) {
    var thisElement = $("#" + txtMessage + "");
    //var nameErrorContainer = $("#" + lblNameError + "");
    //var emailErrorContainer = $("#" + lblEmailError + "");
    //Clear previous values
    //nameErrorContainer.text('');
    //emailErrorContainer.text('');
    blnReturnValue = new Boolean();
    blnReturnValue = true;
    if (thisElement.val() == sDefaultMessage || thisElement.val() == sErrorMessage || thisElement.val() == '') {
        thisElement
            .val(sErrorMessage)
            .addClass(sErrorClass);
        blnReturnValue = false;
    }
    var name = $("#" + txtName + "");
    if (name.val() == '' || name.val() == sDefaultName) {
        //nameErrorContainer.text(sNameErrorMessage);
        name.val(sNameErrorMessage).addClass(sTextBoxErrorClass);
        blnReturnValue = false;
    }
    var email = $("#" + txtEmail + "");

    if (email.val() == '' || email.val() == sDefaultName || email.val() == sEmailErrorMessage) {
        email.val(sEmailErrorMessage).addClass(sTextBoxErrorClass);
        blnReturnValue = false;
    }
    else {
        blnValidEmail = new Boolean();
        blnValidEmail = IsValidEmail(email.val());
        if (!blnValidEmail) {
            email.val(sEmailErrorMessage).addClass(sTextBoxErrorClass);
            blnReturnValue = false;
        }
    }

    return blnReturnValue;
}

function regexNumericOnly(element, sDefaultValue) {
    var value = $("#" + element + "").val();
    if (value != sDefaultValue) {
        value = value.replace(new RegExp("[^0-9]", "g"), "");
        $("#" + element + "").val(value);
    }
}

//Admin Section

//delete user
function deleteUser(tableRow, divMessage, lblMessage, userId, userName, activeUserCount, TotalUserCount, enabledClass) {
    $("#" + divMessage + "").addClass("displayNone").removeClass("Success").removeClass("bold").removeClass("Error");

    var myuserId = { "userId": "" + userId + ""};
    $.ajax({
        type: "Get",
        url: "/../secure/administration/Handlers/DeleteUser.ashx",
        dataType: "json",
        data: myuserId,
        cache: false,
        success: function (result) {
            if (result != "") {
                if (result.IsError == false) {
                    var totalUsers = $("#" + TotalUserCount + "").text();
                    var totalUsersCount = parseInt(totalUsers);
                    var activeUsers = $("#" + activeUserCount + "").text();
                    var activeUsersCount = parseInt(activeUsers);
                    var tr = $("#" + tableRow + "");

                    $("#" + divMessage + "").removeClass("displayNone").addClass("Success").addClass("bold");
                    $("#" + lblMessage + "").text(userName + " Deleted");
                    $("#" + TotalUserCount + "").text(totalUsersCount - 1);

                    //if the className of the user is active set true
                    if (tr.attr("class") == enabledClass) {
                        $("#" + activeUserCount + "").text(activeUsersCount - 1);
                    }
                    tr.hide();
                }
                else {
                    $("#" + divMessage + "").removeClass("displayNone").addClass("Error").addClass("bold");
                    $("#" + lblMessage + "").text(userName + " Deletetion Failed");
                }
            }
        },
        error: function (e) {
            $("#" + divMessage + "").removeClass("displayNone").addClass("Error").addClass("bold");
            $("#" + lblMessage + "").text(userName + " Deletetion Failed");
        }
    });

}

//Enable and disable a user on the user grid
function enableDisableUser(tableRow, userId, enableDisableButton, ActiveImage, DisableImage, enabledClass, disabledClass, activeText, disabledText, activeUsersLabel) {
    var myuserId = { "userId": "" + userId + ""};
    $.ajax({
        type: "Get",
        url: "/../secure/administration/Handlers/EnableDisableUser.ashx",
        dataType: "json",
        data: myuserId,
        cache: false,
        success: function (result) {
            if (result != "") {
                if (result.IsError == false) {
                    var activeUsers = $("#" + activeUsersLabel + "").text();
                    var activeUsersCount = parseInt(activeUsers);
                    var tr = $("#" + tableRow + "");
                    var btn = $("#" + enableDisableButton + "");
                    if (tr.attr("class") == enabledClass) {
                        tr.removeClass(enabledClass).addClass(disabledClass);
                        btn.attr("src", DisableImage);
                        btn.attr("title", disabledText);
                        $("#" + activeUsersLabel + "").text(activeUsersCount - 1);
                    }
                    else {
                        tr.addClass(enabledClass).removeClass(disabledClass);
                        btn.attr("src", ActiveImage);
                        btn.attr("title", activeText);
                        $("#" + activeUsersLabel + "").text(activeUsersCount + 1);
                    }
                }
            }
        },
        error: function (e) {
            //alert(e.responseText);
        }
    });
}

//Reporting
function runReport(sReportType, txtFromDate, txtToDate, cbEnableDisableUsers) {
    var reportContainer = $('#ReportData');
    reportContainer.html("<image src='/i/progress_indicator.gif' alt='Loading'/>");
    switch (sReportType) {
        case "NetworkUpdates":
            runNetworkUpdatesReport(txtFromDate, txtToDate, reportContainer);
            break;
        case "CVProcessing":
            runCVProcessingReport(txtFromDate, txtToDate, reportContainer);
            break;
        case "Users":
            runUserReport(txtFromDate, txtToDate, cbEnableDisableUsers, reportContainer);
            break;
    }
}
//Run user report
function runUserReport(txtFromDate, txtToDate, cbEnableDisableUsers, reportContainer) {
    var fromDate = $('#' + txtFromDate + '').val();
    var toDate = $('#' + txtToDate + '').val();

    enableDisableUsers = new Boolean();
    if ($('#' + cbEnableDisableUsers + ':checked').val() != null) {
        enableDisableUsers = true;
    }
    var data = { "enableDisableUsers": "" + enableDisableUsers + "", "fromDate": "" + fromDate + "", "toDate": "" + toDate + "" };
    $.ajax({
        type: "Get",
        url: "/../secure/reports/Handlers/loadUserActivityHandler.ashx",
        dataType: "json",
        data: data,
        cache: false,
        success: function (result) {
            if (result != "") {
                if (result.AjaxErrorStatus.IsError == false) {
                    reportContainer.html(result.HtmlControl);
                    $('.reportsExportButton').show();
                }
                else {
                    switch (result.AjaxErrorStatus.ErrorType) {
                        case 1: //Session Expired
                            $('#SessionExpiredHolder')
                            .html(result.HtmlControl)
                            .show();
                            displayModalMask($("#SessionExpired"), true)
                            reportContainer.html("");
                            break;
                        case 2: //Unexpected Error
                            reportContainer.html(result.HtmlControl);
                            break;
                        case 3: //Invalid date range
                            reportContainer.html(result.HtmlControl)
                            break;
                    }
                }
            }
        }
    });
}

//run Cv processing Report
function runCVProcessingReport(txtFromDate, txtToDate, reportContainer) {
    var fromDate = $('#' + txtFromDate + '').val();
    var toDate = $('#' + txtToDate + '').val();
    var data = { "fromDate": "" + fromDate + "", "toDate": "" + toDate + "" };
    $.ajax({
        type: "Get",
        url: "/../secure/reports/Handlers/loadCVProcessingHandler.ashx",
        dataType: "json",
        data: data,
        cache: false,
        success: function (result) {
            if (result != "") {
                if (result.AjaxErrorStatus.IsError == false) {
                    reportContainer.html(result.HtmlControl);
                    $('.reportsExportButton').show();
                }
                else {
                    switch (result.AjaxErrorStatus.ErrorType) {
                        case 1: //Session Expired
                            $('#SessionExpiredHolder')
                            .html(result.HtmlControl)
                            .show();
                            displayModalMask($("#SessionExpired"), true)
                            break;
                        case 2: //Unexpected Error
                            reportContainer.html(result.HtmlControl);
                            break;
                        case 3: //Invalid date range
                            reportContainer.html(result.HtmlControl)
                            break;
                    }
                }
            }

        }
    });
}

//run network update report
function runNetworkUpdatesReport(txtFromDate, txtToDate, reportContainer){
    var fromDate = $('#' + txtFromDate + '').val();
    var toDate = $('#' + txtToDate + '').val();
    var data = { "fromDate": "" + fromDate + "", "toDate": "" + toDate + "" };

    $.ajax({
        type: "Get",
        url: "/../secure/reports/Handlers/loadNetworkUpdatesHandler.ashx",
        dataType: "json",
        data: data,
        cache: false,
        success: function (result) {
            if (result != "") {
                if (result.AjaxErrorStatus.IsError == false) {
                    reportContainer.html(result.HtmlControl);
                    $('.reportsExportButton').show();
                }
                else {
                    switch (result.AjaxErrorStatus.ErrorType) {
                        case 1: //Session Expired
                            $('#SessionExpiredHolder')
                            .html(result.HtmlControl)
                            .show();
                            displayModalMask($("#SessionExpired"), true)
                            break;
                        case 2: //Unexpected Error
                            reportContainer.html(result.HtmlControl);
                            break;
                        case 3: //Invalid date range
                            reportContainer.html(result.HtmlControl)
                            break;
                    }
                }
            }

        }
    });
}

//Sort gids
function sortReportGrid(sReportType, sSortColumn, eId) {
    var element = $('#' + eId + '');
    element.html("<image src='/i/progress_indicator.gif' alt='Loading'/>");
    switch (sReportType) {
        case "NetworkUpdates"://Not Used
            break;
        case "CVProcessing": //Not used
            break;
        case "Users":
            sortUserActivity(sSortColumn, element);
            break;
    }
}

//Sort the user activity grid
function sortUserActivity(sSortColumn, element){
    var data = { "SortColumn": "" + sSortColumn + ""};
    $.ajax({
        type: "Get",
        url: "/../secure/reports/Handlers/SortUserActivityHandler.ashx",
        dataType: "json",
        data: data,
        cache: false,
        success: function (result) {
            if (result != "") {
                if (result.AjaxErrorStatus.IsError == false) {
                    element.html(result.HtmlControl);
                }
                else {
                    switch (result.AjaxErrorStatus.ErrorType) {
                        case 1: //Session Expired
                            $('#modalDisplay')
                            .html(result)
                            .show();
                            displayModalMask($("#SessionExpired"), true)
                            break;
                        case 2: //Unexpected Error
                            element.html(result.HtmlControl);
                            break;
                        case 3: //Invalid sort column passed
                            element.html(result.HtmlControl);
                            break;
                    }
                }
            }
        }
    });
}

function IsValidEmail(email) {
    var filter = new RegExp("[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?");
    return filter.test(email);
}


//function switchPage(pageNumber) {
//    if (pageNumber > 0) {
//        buildLoadingScreen();
//        //PageMethods.SwitchPage(pageNumber, OnSucceeded, OnFailed);

//        var data = { "pid": "" + pageNumber + "" };
//        $.ajax({
//            type: "Get",
//            url: "/../secure/search/Handlers/SearchResultsSwitchPage.ashx",
//            dataType: "json",
//            data: data,
//            cache: false,
//            success: function (result) {
//                $('.RG').html(result);
//            },
//            error: function (e) {
//                $('.RG').html(e.responseText);
//            }
//        });
//    }
//}
