﻿var HTML_WAIT = '<div style=\'width:100%;height:100;text-align:center;\'><img src=\'/assets/images/ajax-loader.gif\' style=\'margin-top:100px;\'></div>'
var HTML_STATUS_BOX='<div class=\'statusBx\' id=\'bvisible\'></div>'
var HTML_EMAIL_BOX='<div class=\'statusBx\' id=\'bEmail\'></div>'
var HTML_NI_BOX='<div class=\'cancelBx\' id=\'bCancel\'></div>'
var HTML_ARCHIVE_BOX='<div class=\'archiveBx\' id=\'bArchive\'></div>'
var HTML_STAFFING_S_BOX='<div class=\'staffingbx\' id=\'bStaffing\'></div>'
var HTML_JUNK_BOX = '<div id=\'jnk\'></div>'
var hidChemail='<input type=\'hidden\' id=\'hidchemail\' name=\'hidchemail\' />'
   var checkToDelete=0;
var speed="fast"
var isRecruiter = false
var delayedStatusAction = ''
var savedJsList ='' //invited/saved/etc js from a previous page

$(document).ready(function() {
    $('#bucket').html(HTML_STATUS_BOX + HTML_EMAIL_BOX + HTML_EMAIL_BOX + HTML_NI_BOX + HTML_ARCHIVE_BOX + HTML_HIDDEN_CTLS + HTML_STAFFING_S_BOX + HTML_JUNK_BOX + hidChemail)

 persistSaveJSFromCookie()

 $(".chkAll").click(
    function (){
        if (this.checked){
            $(".chkMsg").each(
                function (i){
                    if (!this.checked){
                       this.checked=true;
                       msgCheck(this);
                    }
                }
             );
        }else{
             $(".chkMsg").each(
                function (i){
                    if (this.checked){
                       this.checked=false;
                       msgCheck(this);
                    }
                }
             );
        
        }
    
    }
  
 );
 
  $(".chkAllInv").click(
    function (){
        if (this.checked){
            $(".chkInv").each(
                function (i){
                    if (!this.checked){
                       this.checked=true;
                       invCheck(this);
                    }
                }
             );
        }else{
             $(".chkInv").each(
                function (i){
                    if (this.checked){
                       this.checked=false;
                       invCheck(this);
                    }
                }
             );
        
        }
    
    }
  
 );
 
 
   $(".chkAllNi").click(
    function (){
        if (this.checked){
            $(".chkDel").each(
                function (i){
                    if (!this.checked){
                       this.checked=true;
                       niCheck(this);
                    }
                }
             );
        }else{
             $(".chkDel").each(
                function (i){
                    if (this.checked){
                       this.checked=false;
                       niCheck(this);
                    }
                }
             );
        
        }
    
    }
  
 );
 
   $(".chkAllUns").click(
    function (){
        if (this.checked){
            $(".chkSave").each(
                function (i){
                    if (!this.checked){
                       this.checked=true;
                       saveCheck(this);
                    }
                }
             );
        }else{
             $(".chkSave").each(
                function (i){
                    if (this.checked){
                       this.checked=false;
                       saveCheck(this);
                    }
                }
             );
        
        }
    
    }
  
 );
 
  $(".chkAllArch").click(
    function allArchCheck(){
        
        if (this.checked){
            $(".chkArchive").each(
                function (i){
                    if (!this.checked){
                       this.checked=true;
                        archiveCheck(this);
                    }
                }
             );
        }else{
             $(".chkArchive").each(
                function (i){
                    if (this.checked){
                       this.checked=false;
                        archiveCheck(this)
                    }
                }
             );
             
        }
    
    }
  
 );

 
 function msgCheck(cbx){
    if (invChecked+ unsChecked+checkToArchive+checkToDelete>0){cbx.checked=false;return false;}
    if (cbx.checked){
                msgChecked +=1   
                $(".td" + this.value).css("background-color","#E6E8FA")
            }else{
                msgChecked -=1
                $(".td" + this.value).css("background-color","")
            }
            if (msgChecked==0){
             $(".msg").text("");
             $("#dbulkMsg").hide();
             $("#dnotes").show();
            }else{
                $("#dnotes").hide();
                $("#dbulkMsg").show();
                $(".msg").text("Message (" + msgChecked + ")");
            }
 }
 
 
 function niCheck(cbx){
        if (msgChecked+unsChecked+checkToArchive+invChecked>0){cbx.checked=false;return false}
        
        if (cbx.checked){
               checkToDelete +=1  
               $(".td" + this.value).css("background-color","#E6E8FA")
            }else{
                checkToDelete -=1
                $(".td" + this.value).css("background-color","")
            }
            if (checkToDelete==0){
             $("#dArch").hide();
             $(".del").text("");
             $("#dacthead").show()
            
            }else{
                $("#dacthead").hide()
                $("#dArch").show();
                $(".del").text("Archive (" + checkToDelete + ")");
             
            }
 
 }

 function invCheck(cbx){
    if (msgChecked+unsChecked+checkToArchive+checkToDelete>0){cbx.checked=false;return false}
    if (cbx.checked){
                invChecked +=1   
                $(".td" + this.value).css("background-color","#E6E8FA")
            }else{
                invChecked -=1
                $(".td" + this.value).css("background-color","")
            }
            if (invChecked==0){
             $(".inv").text("");
             $("#dbulkInv").hide();
             $("#dnotes").show();
             $("#dacthead").show()
            }else{
                $("#dacthead").hide()   
                $("#dnotes").hide();
                $("#dbulkMsg").hide();
                $("#dbulkInv").show();
                $(".inv").text("Bulk Invite (" + invChecked + ")");
            }
 }
 function saveCheck(cbx){
 
    if (msgChecked+invChecked+checkToArchive+checkToDelete>0){cbx.checked=false;return false}
    if (cbx.checked){
                unsChecked +=1   
                $(".td" + this.value).css("background-color","#E6E8FA")
            }else{
                unsChecked -=1
                $(".td" + this.value).css("background-color","")
            }
            if (unsChecked==0){
             $(".uns").text("");
             $("#dbulkUnsave").hide();
             $("#dnotes").show();
             $("#dacthead").show()
            }else{
                $("#dacthead").hide()
                $("#dnotes").hide();
                $("#dbulkMsg").hide();
                $("#dbulkInv").hide();
                $("#dbulkUnsave").show();
                $(".uns").text("Unsave (" + unsChecked + ")");
            }
 }
 

        $(".chkMsg").click(function(){
            msgCheck(this)
        });

        $(".chkInv").click(function(){
            
            invCheck(this)
        });
        $(".chkSave").click(function(){
            
            saveCheck(this)
        });
 
        $(".chkDel").click(function(){
           niCheck(this)
            
        });
 
 
 
});
  var checkToMsg =0

        var checkToArchive =0
   function archiveCheck(cbx){
            if (msgChecked+invChecked+unsChecked+checkToDelete>0){cbx.checked=false;return false}
   
            if (cbx.checked){
                checkToArchive +=1   
                $(".td" + this.value).css("background-color","#E6E8FA")
            }else{
                checkToArchive -=1
                $(".td" + this.value).css("background-color","")
            }
            if (checkToArchive==0){
             $(".arch").text("").hide();
             $("#darch").hide();
             ;
             $("#dacthead").show()
            
            }else{
                $("#dacthead").hide()
                $(".arch").show().text("Archive (" + checkToArchive + ")");
                $("#darch").show();
             
            }
        }

 
 var invChecked=0
 var unsChecked=0
 var msgChecked=0

var HTML_HIDDEN_CTLS=""
HTML_HIDDEN_CTLS+='<input type=\'hidden\' name=\'hidLegacyStatusChange\' id=\'hidLegacyStatusChange\' />'
HTML_HIDDEN_CTLS+='<input type=\'hidden\' name=\'hidDoSend\' id=\'hidDoSend\' />'
HTML_HIDDEN_CTLS+='<input type=\'hidden\' name=\'hidstatusid\' id=\'hidstatusid\' />'
HTML_HIDDEN_CTLS+='<input type=\'hidden\' name=\'hidjsid\' id=\'hidjsid\' />'
HTML_HIDDEN_CTLS+='<input type=\'hidden\' name=\'hidbulkjsids\' id=\'hidbulkjsids\' />'
HTML_HIDDEN_CTLS+='<input type=\'hidden\' name=\'hidjbid\' id=\'hidjbid\' />'
HTML_HIDDEN_CTLS+='<input type=\'hidden\' name=\'hidtestduedate\' id=\'hidtestduedate\' />'
HTML_HIDDEN_CTLS += '<input type=\'hidden\' name=\'hidtestid\' id=\'hidtestid\' />'
HTML_HIDDEN_CTLS+='<input type=\'hidden\' name=\'hidinterviewType\'  id=\'hidinterviewType\' />'
HTML_HIDDEN_CTLS += '<input type=\'hidden\' name=\'hidinverviewNumber\' id=\'hidinverviewNumber\' />'
HTML_HIDDEN_CTLS += '<input type=\'hidden\' name=\'interviewwith\' id=\'interviewwith\' />'
HTML_HIDDEN_CTLS+='<input type=\'hidden\' name=\'hidinverviewHour\' id=\'hidinverviewHour\' />'
HTML_HIDDEN_CTLS+='<input type=\'hidden\' name=\'hidinterviewMinute\' id=\'hidinterviewMinute\' />'
HTML_HIDDEN_CTLS+='<input type=\'hidden\' name=\'hidinterviewAmpm\' id=\'hidinterviewAmpm\' />'
HTML_HIDDEN_CTLS+='<input type=\'hidden\' name=\'hidinverviewDate\' id=\'hidinverviewDate\' />'

function checkEmail(e)
	{
		var returnVal;
		var regex = /^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$/;
	
		returnVal = regex.test(document.getElementById(e).value);

		return returnVal;
}

var isRankReportOpen = false;
function openRankReportOptions(jbid,source) {
    if (isOpenStatusOpen && lastSource == source) {
        return hideAndClearAll();
    }
    lastBoxOpened="rankreport"
    hideAndClearAll();
    suppressJtip = true;
    var y, x
    y = getAbsoluteTop(source) + 19; //set y position
    x = getAbsoluteLeft(source) + 100

    var x2
    x2 = getAbsoluteLeft(source) 

    $('#bvisible').html(HTML_WAIT);
    $('#bvisible').css({ left: x + "px", top: y + "px", width: "0px", height: "0px" });

    //$('#bvisible').slideToggle(speed);
    //$('#bvisible').animate({ width: "show" }, speed).animate({ left:"100px" },speed);
    //$('#bvisible').animate({ width: "hide" }, speed); 

    $("#bvisible").animate({
        left: x2,
        width: "225px",
        height: "175px"
    }, 500);


    
    

    $('#bvisible').load('/employer/tips/rankReportOptions.aspx?jbid=' + jbid)

}
function closeRankingReport() {
    hideAndClearAll();
}

function showRankingReport(jbid) {
    var url = '/employer/rankingreport.aspx'
    url = url + '?jobid=' + jbid
    if ($("#rdoRank").get(0).checked) {
        url = url + '&isPrerank=0'
    }else{
        url = url + '&isPrerank=1'
    }
    url = url + '&sortby=' + $("#slctSortRankBy").val()

    window.open(url)
    hideAndClearAll()
}

//Status functions

 var currjobid=0;
 var currJSID=0;
 var isOpenStatusOpen=false;
 var lastStatus;
 var lastBoxOpened=""
 function openStatusOptions(jbid,jsid,source,nocache){
  
    if (isOpenStatusOpen && lastSource==source){
         return hideAndClearAll();
    }   
    lastBoxOpened="status"
    hideAndClearAll();
    
    suppressJtip=true;
    
    currjobid=jbid;
    currJSID=jsid;
    var y,x
    y=getAbsoluteTop(source) + 19; //set y position
    x= getAbsoluteLeft(source)+100
    
    var x2
    x2= getAbsoluteLeft(source)-440
    
    $('#bvisible').html(HTML_WAIT);
    $('#bvisible').css({left: x+"px", top: y+"px",width: "0px",height:"0px"});
    
    //$('#bvisible').slideToggle(speed);
    //$('#bvisible').animate({ width: "show" }, speed).animate({ left:"100px" },speed);
    //$('#bvisible').animate({ width: "hide" }, speed); 
    
    $("#bvisible").animate({ 
        left: x2,
        width: "525px",
        height: "395px"
      }, 500 );

    
    //$('#bvisible').show('fast');
  
    
    $('#bvisible').load('/employer/tips/jsstatus.aspx?jbid=' + jbid +'&jsid=' + jsid + '&rnd=' + nocache)
    $('#hidjsid').val(jsid)
    $('#hidjbid').val(jbid)
    
  
    isOpenStatusOpen=true;
    lastSource=source;
    
    return false;
 }
 
 var isOpenArchive=false;
 function openArchive(jbid,jsid,source,nocache){
    if (isOpenArchive && lastSource==source){
         return hideAndClearAll();
    }   
    lastBoxOpened="archived"
  
    
    currjobid=jbid;
    currJSID=jsid;
    var y,x
    y=getAbsoluteTop(source) + 19; //set y position
    x= getAbsoluteLeft(source)+100
    var x2
    x2= getAbsoluteLeft(source)-405
   
    
    hideAndClearAll();
    
    suppressJtip=true;
    
    $('#bArchive').html(HTML_WAIT)
    //$('#bCancel').css({left: x+"px", top: y+"px"});
     $('#bArchive').css({left: x+"px", top: y+"px",width: "0px",height:"0px"});
  
     $("#bArchive").animate({ 
        left: x2,
        width: "500px",
        height: "100px"
      }, 500 );
    //$('#bCancel').show('fast');
    //$('#bCancel').slideToggle("slow");
    
    $('#bArchive').load('/employer/tips/jsclear.aspx?jbid=' + jbid +'&jsid=' + jsid + '&rnd=' + nocache)
    $('#hidjsid').val(jsid)
    $('#hidjbid').val(jbid)
    
     //also set the email location just in case we need it
    var y,x
    y=getAbsoluteTop(source) + 19; //set y position
    x= getAbsoluteLeft(source)-544
    $('#bvisible').css({left: x+"px", top: y+"px"});
    
    isOpenNotInterested=true;
    lastSource=source;
    
    return false;
 }
 
 var isOpenNotInterested=false;
 function openNotInterested(jbid,jsid,source,nocache,isBulk){
   
    
     if (isOpenNotInterested && lastSource==source){
         return hideAndClearAll();
    }  
  
      lastBoxOpened="ni"
      
    currjobid=jbid;
    currJSID=jsid;
    var y,x
    y=getAbsoluteTop(source) + 19; //set y position
    x= getAbsoluteLeft(source)+100
    var x2
    x2= getAbsoluteLeft(source)-280
   
    
    hideAndClearAll();
    
    suppressJtip=true;
    
    $('#bCancel').html(HTML_WAIT)
    //$('#bCancel').css({left: x+"px", top: y+"px"});
    $('#bCancel').css({ left: x + "px", top: y + "px", width: "0px", height: "0px" });
    
     
     $("#bCancel").animate({ 
        left: x2,
        width: "375px",
        height: "150px"
      }, 500 );
    //$('#bCancel').show('fast');
    //$('#bCancel').slideToggle("slow");
    
    $('#bCancel').load('/employer/tips/jsNotInterested.aspx?jbid=' + jbid +'&jsid=' + jsid + '&rnd=' + nocache + '&isBulk=' + isBulk)
    $('#hidjsid').val(jsid)
    $('#hidjbid').val(jbid)
    
     //also set the email location just in case we need it
    var y,x
    y=getAbsoluteTop(source) + 19; //set y position
    x= getAbsoluteLeft(source)-544
    $('#bvisible').css({left: x+"px", top: y+"px"});
    
    isOpenNotInterested=true;
    lastSource=source;
    
    return false;
 }
 
 
 //-----------\
 //SS methods
 //------------
 var isOpenSS=false;
 function openStaffingSources(jbid,source,nocache){
    if (isOpenSS && lastSource==source){
         return hideAndClearAll();
    }   
    lastBoxOpened="ss"
     
    currjobid=jbid;
  
    var y,x
    y=getAbsoluteTop(source) + 15; //set y position
    x= getAbsoluteLeft(source)
    var x2
    x2= getAbsoluteLeft(source)
    hideAndClearAll();
    
    $('#bStaffing').html(HTML_WAIT)
    //$('#bCancel').css({left: x+"px", top: y+"px"});
     $('#bStaffing').css({left: x+"px", top: y+"px",width: "0px",height:"0px"});
  
     $("#bStaffing").animate({ 
       // left: x2,
        width: "600px",
        height: "300px"
      }, 500 );
    //$('#bCancel').show('fast');
    //$('#bCancel').slideToggle("slow");
    
    $('#bStaffing').load('/employer/tips/staffing.aspx?jbid=' + jbid +'&rnd=' + nocache)
    
     //also set the email location just in case we need it
    var y,x
    y=getAbsoluteTop(source) + 15; //set y position
    x= getAbsoluteLeft(source)
    $('#bvisible').css({left: x+"px", top: y+"px"});
    
    isOpenSS=true;
    lastSource=source;
    
    return false;
 }
 function chkActivate(isChecked,ssid,agencyName,jbid,showAgencyWarning){

     if (showAgencyWarning) {
         if (isChecked) {
             if (confirm("You have selected to allow " + agencyName + " to submit candidates through the ATS for this position. \n To send an e-mail alert to " + agencyName + ", click 'OK'. Click 'Cancel' if you do not wish to send an e-mail alert?")) {
                 showStaffingEmail(ssid, jbid, isChecked)
             }

         } else {
             if (confirm("You have deselected " + agencyName + " as a staffing source for this position.  They will no longer be allowed to submit candidates through the ATS for this position.  Do you wish to send an e-mail alerting them of this?")) {
                 showStaffingEmail(ssid, jbid, isChecked)
             }
         }
     }
     //ajax call updats ss
    ActivateDeactivateSS(jbid, ssid, isChecked)
    //try to show/hide other ss link info
    if ($("#sss" + ssid).get(0) != null) {
        if (isChecked) {
            $("#sss" + ssid).show();
        } else {
            $("#sss" + ssid).hide();
        }
    }
 }
 //-----------\
 // end SS methods
 //------------ 
 
 
 
 function hideAndClearAll(){
    
    
    $('#JT').remove()
    
    $('#bvisible').hide()
    $('#bvisible').html('')
     $('#bvisible').css({overflow:"visible"});
    
    $('#bEmail').hide()
    $('#bEmail').html('')
     
    $('#bCancel').hide()
     $('#bCancel').html('')
     $('#bulkMedia').hide()
     $('#bStaffing').hide()
     $('#bStaffing').html('')
     isOpenStatusOpen=false;
     isOpenNotInterested=false;
     isOpenSS=false;
     lastBoxOpened = "";
     delayedStatusAction = "";
     //blind call out .. event like
     try {
        hideClearSubPage()
     } catch (e){}
     
 }
 function closeStatusOptions(){
   suppressJtip=false;
    $('#bvisible').hide()
    $('#bvisible').html('')
 }
 function closeNIOptions(){
   
   suppressJtip=false;
      $('#bCancel').hide()
     $('#bCancel').html('')
     
 }
 function closeArchiveOptions(){
   
        suppressJtip=false;
      $('#bArchive').hide()
     $('#bArchive').html('')
     
 }


 var muteEmail = false;
 function saveNIOptions(isBulk){
   var doArchive
   // if ($('#NIarchive').get(0).checked){
    //    $('#hidstatusid').val(8) //clear value
   //     doArchive=true
   // }
   // else{
   //passes now archive as well, and we're *calling* it an archived item
   //this may cause confusion, but it's teh way we're going for stereod
        $('#hidstatusid').val(13) //pass/ni/archive value
   //     doArchive=false
   // }
    
    //8 clare value
    if (document.getElementById('rdoNIActionEmail').checked){
        previewEmail=true;
    }else{
        previewEmail=false;
    }
    if (document.getElementById('rdoNINoEmail').checked) {
        muteEmail = true;
    } else {
        muteEmail = false;
    }
    //push values into the normal 'options' logic flow to handle showing
    //email popup, etc
    if (isBulk!=1){
        return saveStatusChange();
    }else{
        doBulk(previewEmail,doArchive,null,muteEmail)
    }
 }
 
 

 
 function saveArchiveOptions(){

        previewEmail=false;
	    $('#hidstatusid').val(8);
	  
    //push values into the normal 'options' logic flow to handle showing
    //email popup, etc
    return saveStatusChange();
 }
 
 function sendShareProfileEmail(jsid,jbid,source,mid){
    var y,x
    currjobid=jbid
    currJSID=jsid
    if (mid==null){
        mid=0;
    }
    
    y=getAbsoluteTop(source) + 19; //set y position
    x= getAbsoluteLeft(source)-544
    $('#bvisible').css({left: x+"px", top: y+"px"});
     
    $('#bvisible').html(HTML_WAIT)
   
    //$('#bvisible').show('fast');
    $('#bvisible').slideToggle(speed);
    $('#bvisible').load('/employer/tips/jsstatusemail.aspx?share=1&jbid=' + jbid +'&jsid=' + jsid + '&ajaxEmail=1&mid='+mid);
    
    
 }
 
 function sendAjaxEmail(){
   
    var hasAddress=false;
     var ret
    var emailToStr
    
    $(".chkEmail").each(
        function (i){
            if (this.checked){
                emailToStr+=this.value + ';';
                hasAddress=true;
            }
        }
    );
    
     if (!checkEmail('FromEmail')){
        alert('Please check the from and to email addresses to ensure they are valid email addresses.')
        return false;
    }

    
    if (!hasAddress){
        if (document.getElementById('emailto').value.indexOf("@")==-1){
            alert('Please check the from and to email addresses to ensure they are valid email addresses.')
            return false;
        }
    }
    
//    alert($('#privateURL').val())
//    alert($('#publicURL').val())
    
    //send emails to teh users who can log in, users added through checkboxes
    if (hasAddress){
    ret = CHAjax.EmployerActions.SendEmailbyAjax(emailToStr,$('#FromEmail').val(),$('#Subject').val(),$('#Message').val()+"\n\r" + $('#privateURL').val(),false,scb)
    }
    emailToStr=''
    emailToStr = $('#emailto').val() +';'
    //send slightly different email to those who can't. those who can't go to a public url
    if (document.getElementById('emailto').value.indexOf("@")!=-1){
        ret= CHAjax.EmployerActions.SendEmailbyAjax(emailToStr,$('#FromEmail').val(),$('#Subject').val(),$('#Message').val()+"\n\r" + $('#publicURL').val(),false,scb)
    }
    
    
     hideAndClearAll();
     
 }
 function closeAjaxEmail(){
     hideAndClearAll();
 }
 function scb(result, eventArgs)
{
    
  }
 
 
 
 function showStaffingEmail(ssid,jbid,bActivate){
    hideAndClearAll();
    $('#bvisible').html(HTML_WAIT)
    $('#bvisible').slideToggle(speed);
    
    if (bActivate){
        $('#bvisible').load('/employer/tips/jsstatusemail.aspx?ajaxemail=1&activatess=1&jbid=' + jbid + '&ssid=' + ssid);
    }else{
        $('#bvisible').load('/employer/tips/jsstatusemail.aspx?ajaxemail=1&deactivatess=1&jbid=' + jbid + '&ssid=' + ssid);
    }
 }


 function saveInvitedToCookie() {
     //save invited js's
     var tsList = ''
     var tArr = new Array();
     if (savedJsList.length > 2) {
         tArr = savedJsList.split(',');
     }
     var alreadyInvited;
     if (invChecked > 0) {
         jQuery.each($('.chkInv'), function () {
             alreadyInvited = false;
             if (this.checked) {
                 for (a = 0; a < tArr.length; a++) {
                     if (tArr[a] == this.value) {
                         alreadyInvited = true;
                     }
                 }
                 if (!alreadyInvited) {
                     tsList += this.value + ','
                 }
             }
         })
         $.cookie('invJS', tsList + savedJsList);
     }
 }

 function persistSaveJSFromCookie() {
     if ($.cookie('invJS') != null && $.cookie('invJS').split(',').length>1) {
         savedJsList = $.cookie('invJS');
         //alert(savedJsList);
         $("#dacthead").hide()
         $("#dnotes").hide();
         $("#dbulkMsg").hide();
         $("#dbulkInv").show();
         invChecked = $.cookie('invJS').split(',').length-1
         $(".inv").text("Bulk Invite (" + invChecked + ")");
         var tArr=savedJsList.split(',')
         for (a = 0; a <= invChecked; a++) {
             try {
                 $("#chkInv" + tArr[a]).get(0).checked = true;
             } catch (e) { }
         }

     }
     $.cookie('invJS', null);
 }

 function showBulkInvite(jbid,jsid,source,nocache){
 //
    var hasChecked
     var jslist=''
    hideAndClearAll()
    lastBoxOpened="msg"
    suppressJtip=true;

    if (jsid == 0) {

        var tArr = new Array();
        if (savedJsList.length > 2) {
            tArr = savedJsList.split(',');
        }
        var alreadyInvited;
        jQuery.each($('.chkInv'), function () {
            alreadyInvited = false;
            if (this.checked) {
                for (a = 0; a < tArr.length; a++) {
                    if (tArr[a] == this.value) {
                        alreadyInvited = true;
                    }
                }
                if (!alreadyInvited) {
                    jslist += this.value + ','
                }
            }
        })



 
        jslist += savedJsList;
        $('#hidbulkjsids').val(jslist)
        $('#jsid').val('')
    }
    else{
        if (invChecked>1){
            alert('To invite multiple jobseekers, use the \'Bulk Invite (' + invChecked + ')\' button above.')
            return false;
        }
        $('#hidjsid').val(jsid)
    }
    $('#hidjbid').val(jbid)
    currjobid = jbid;
    $('#hidstatusid').val(11)

    

    var y, x
    y = getAbsoluteTop(source) + 19; //set y position
    x = getAbsoluteLeft(source) + 100

    var x2
    x2 = getAbsoluteLeft(source) - 500

    $('#bvisible').html(HTML_WAIT);
    $('#bvisible').css({ left: x2 + "px", top: y + "px", width: "0px", height: "0px" });

   
    var rootDir='/employer'
    if (isRecruiter==true){
        rootDir='/recruiter'
    }
    currJSID = jsid;

    if (jsid == 0) {
        //alert(jslist);
        showBulkStatusemail(jbid, jslist, 11)
    } else {
        showStatusemail(11);
    }
    //ajaxInvite(jsid,jslist,jbid)
    
      
  
  
 }
 function showBulkUnsave(jbid,jsid,source,nocache){
 //
    var hasChecked
     var jslist=''
    hideAndClearAll()
    lastBoxOpened="msg"
    suppressJtip=true;
    
    if (jsid==0){
     jQuery.each($('.chkSave'),function(){
         if (this.checked){
          hasChecked=true;
          jslist += this.value + ','
         }
        })
         $('#hidbulkjsids').val(jslist)
        $('#jsid').val('')
    }
    else{
        if (unsChecked>1){
            alert('To invite multiple jobseekers, use the \'Bulk Invite (' + unsChecked + ')\' button above.')
            return false;
        }
        $('#hidjsid').val(jsid)
    }
    $('#hidjbid').val(jbid)
    var rootDir='/employer'
    if (isRecruiter==true){
        rootDir='/recruiter'
    }
    ajaxUnSave(jbid,jsid,jslist)
 }
 

  
 function showBulkMessageEmail(jbid,jsid,source,nocache){
 //
    var hasChecked
   
    var jslist=''
    hideAndClearAll()
    lastBoxOpened="msg"
    suppressJtip=true;
    
    if (jsid==0){
     jQuery.each($('.chkMsg'),function(){
         if (this.checked){
          hasChecked=true;
          jslist += this.value + ','
         }
        })
         $('#hidbulkjsids').val(jslist)
        $('#jsid').val('')
    }
    else{
        if (checkToMsg>1){
            alert('To send a message to multiple jobseekers, use the \'Send Message (' + checkToMsg + ')\' button above.')
            return false;
        }
        $('#hidjsid').val(jsid)
    }
    $('#hidjbid').val(jbid)

    var y,x
    y=getAbsoluteTop(source) + 19; //set y position
    x= getAbsoluteLeft(source)+100
    
    var x2
    x2= getAbsoluteLeft(source)-440
    
    $('#bvisible').html(HTML_WAIT);
    $('#bvisible').css({left: x+"px", top: y+"px",width: "0px",height:"0px"});

 $('#bvisible').show();
 
    $("#bvisible").animate({ 
        left: x2,
        width: "525px",
        height: "375px"
      }, 500 );
  $('#bvisible').html(HTML_WAIT)
 

    var rootDir='/employer'
    if (isRecruiter==true){
        rootDir='/recruiter'
    }
 
    if (jsid==0){
    
        $('#bvisible').load(rootDir + '/tips/jsstatusemail.aspx?chemail=1&noRefresh=1&JobSeekerIDs=' + jslist + '&jbid=' + jbid);
    }else{
    
         $('#bvisible').load(rootDir + '/tips/jsstatusemail.aspx?chemail=1&noRefresh=1&jsid=' + jsid + '&jbid=' + jbid);
    }
      
  
 }
 
 function showStatusemail(statusid){
 
 var y,x
    
    hideAndClearAll();
   
    
  
    $('#bvisible').html(HTML_WAIT)

    //$('#bvisible').show('fast');
    $("#bvisible").animate({
        width: "525px",
        height: "375px"
    }, 500);
    //$('#bvisible').slideToggle(speed);
    var additionalP =''
    if ($("#hidtestid").val()!= null && $("#hidtestid").val()!=''){
        additionalP = '&testid=' + $("#hidtestid").val()
    }
    if ($('#hidtestduedate').val()!=null && $('#hidtestduedate').val()!=''){

        additionalP += '&TestDueDate=' + encodeURIComponent($('#hidtestduedate').val());

    }
    if (statusid == 3) {
        additionalP = getAdditionalParams();
    }

    if (statusid == 11) {

    //additionalP += '&ajaxemail=1'
    }

    
    //OK, so we're going to delay this event by pusing it into a variable and then executing it only when the email sends.
    $('#bvisible').load('/employer/tips/jsstatusemail.aspx?norefresh=1&jbid=' + currjobid +'&jsid=' + currJSID + '&statusid=' + statusid + additionalP);
    //delayedStatusAction = '/employer/tips/jsstatusemail.aspx?jbid=' + currjobid + '&jsid=' + currJSID + '&statusid=' + statusid + additionalP;

 }
 
 
 function showBulkStatusemail(jbid,jsids,statusid){
 
 var y,x
    
    hideAndClearAll();
   
    
  
    $('#bvisible').html(HTML_WAIT)

    $("#bvisible").animate({
        width: "525px",
        height: "375px"
    }, 500);
    var isAjax = ''
    if (statusid == 11) {
       // isAjax='&ajaxemail=1'
    }

    
    $('#bvisible').load('/employer/tips/jsstatusemail.aspx?jbid=' + jbid + '&JobSeekerIDs=' + jsids + '&statusid=' + statusid + isAjax);
    
 
 }
 
 var previewEmail =false;

	
 function showHideSections(id,emailSelected)
	{
	
	//previewEmail=emailSelected;
	$('#hidstatusid').val(id);
		switch (id)
		{
			case 15: //testing
				getE('testing').style.display = '';
				getE('interviewing').style.display = 'none';
				break;
			case 3: //interviewing
				getE('testing').style.display = 'none';
				getE('interviewing').style.display = '';
				break;
			case 13: //emploeyr passes
				getE('testing').style.display = 'none';
				getE('interviewing').style.display = 'none';
				break;			
			default:
			try{
				getE('testing').style.display = 'none';
				getE('interviewing').style.display = 'none';
				}catch(e){}
		}
	}


	function isDate(dateStr) {

	    var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
	    var matchArray = dateStr.match(datePat); // is the format ok?

	    if (matchArray == null) {
	        //alert("Please enter date as either mm/dd/yyyy or mm-dd-yyyy.");
	        return false;
	    }

	    month = matchArray[1]; // p@rse date into variables
	    day = matchArray[3];
	    year = matchArray[5];

	    if (month < 1 || month > 12) { // check month range
	        //alert("Month must be between 1 and 12.");
	        return false;
	    }

	    if (day < 1 || day > 31) {
	        //alert("Day must be between 1 and 31.");
	        return false;
	    }

	    if ((month == 4 || month == 6 || month == 9 || month == 11) && day == 31) {
	        //alert("Month " + month + " doesn`t have 31 days!")
	        return false;
	    }

	    if (month == 2) { // check for february 29th
	        var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
	        if (day > 29 || (day == 29 && !isleap)) {
	            //alert("February " + year + " doesn`t have " + day + " days!");
	            return false;
	        }
	    }
	    return true; // date is valid
	}
	
    function saveStatusChange(){
    
        
        
        if ($('#hidstatusid').val()==''){
            alert('Please select a new status or click \'Close\' to cancel.');
            return false;
        }
     
        
        $('#hidLegacyStatusChange').val('1');
        switch (parseInt($('#hidstatusid').val()))
		{
		    case 15: //testing

		        if (!isDate($('#TestDueDate').val())) {
		            alert("Please enter a valid test due date and time");
		            return false;
		        }
                if (isNaN($('#TestID').val())){
                    alert("Please select a test");
		            return false;
                }
                //ie was freaking about abotu the slctTT for some reason when using jquery. fixed with DOM
		        $('#hidtestduedate').val($('#TestDueDate').val() + ' ' + $('#slctHour').val() + ':' + $('#slctMinute').val() + ' ' + document.getElementById('slctTT').options[document.getElementById('slctTT').selectedIndex].value);


		        try {
		            $('#hidtestid').val($('#TestID').get(0).options[$('#TestID').get(0).selectedIndex].value);
		        } catch (e) { }
		        break;
		    case 3: //interviewing
		        if (getE('InterviewTypeLive').checked) {
		            $('#hidinterviewType').val(1);
		        } else if (getE('InterviewTypeUnsched').checked) {
		            $('#hidinterviewType').val(0);
		        }
		        else {
		            $('#hidinterviewType').val(2);
		        }

		        $('#hidinverviewNumber').val($('#InterviewCount').get(0).options[$('#InterviewCount').get(0).selectedIndex].value);
		        $('#hidinverviewHour').val($('#InterviewHour').get(0).options[$('#InterviewHour').get(0).selectedIndex].value);
		        $('#hidinterviewMinute').val($('#InterviewMinute').get(0).options[$('#InterviewMinute').get(0).selectedIndex].value);
		        $('#hidinterviewAmpm').val($('#InterviewAMPM').get(0).options[$('#InterviewAMPM').get(0).selectedIndex].value);
		        $('#hidinverviewDate').val($('#InterviewDate').get(0).value);
		        var ivStr = "";
		        $('.chkInterview').each(function (index) {
		            if ($(this).get(0).checked) {
		                ivStr += $(this).val() + ',';
		            }
		        });
                
		        $('#interviewwith').val(ivStr);
		        break;
		}
		
		//13=not intersted. if not that status, then we look at the statuses
		//checkbox to determine if we send preview or not

		if ((lastBoxOpened != 'ni') && $('#hidstatusid').val() != 8) {
		    if ($('#chkPreview' + $('#hidstatusid').val()).get(0) == null) {
		        previewEmail = document.getElementById('rdoNIActionEmail').checked;
            } else {
		        previewEmail = $('#chkPreview' + $('#hidstatusid').val()).get(0).checked;
		    }

		        
		    
		}

		if (previewEmail) {
		    showStatusemail($('#hidstatusid').val());
		}else{

		   
		    document.location='/employer/xt_EmployerActivity.aspx?jsforjob=1&Action=' + $('#hidstatusid').val() + '&JobID=' + $('#hidjbid').val() + '&JobSeekerID=' +  $('#hidjsid').val() + getAdditionalParams()
		}
		
    }
    
    function getAdditionalParams(){
        if (fltrType==null){
            fltrType="";
        }
        var retstr='';
        switch (parseInt($('#hidstatusid').val()))
		    {
			    case 15: //testing
				    retstr += '&TestDueDate=' + $('#hidtestduedate').val();
				    retstr += '&TestID=' + $('#hidtestid').val();
				    break;
				case 3: //interviewing
				    
				    retstr += '&InterviewType=' + $('#hidinterviewType').val();
				    retstr += '&InterviewCount=' + $('#hidinverviewNumber').val();
				    retstr += '&InterviewHour=' + $('#hidinverviewHour').val();
				    retstr += '&InterviewMinute=' + $('#hidinterviewMinute').val();
				    retstr += '&InterviewAMPM=' + $('#hidinterviewAmpm').val();
				    retstr += '&InterviewDate=' + $('#hidinverviewDate').val();
				    retstr += '&interviewwith=' + $('#interviewwith').val();
				    break;
		    }
		    
		    retstr += '&currentpage=' + $('#hidCurrentPage').val();
		    retstr += '&pagesize=' + $('#hidPageSize').val();
		    retstr += '&cPos=' + $(window).scrollTop();

		    if (muteEmail) {
		        retstr += '&muteEmail=1'
		    }
		    
		    return retstr + '&rdoFilterType=' + fltrType
    }
    
    function sendNoTest(fcn){
        if (confirm('Your test will not be sent! Are you sure you want to cancel?')){
            fcn();
        }
        return false;
    }

    function sendEmail(dosend, optChemail) {

        
        
            if (optChemail != null && optChemail) {
                $('#hidchemail').val('true');
            }

            //$('#bvisible').html(HTML_WAIT)
            $('#hidDoSend').val(dosend);
            $('#hidLegacyStatusChange').get(0).form.submit();
    }
    
    
    function checkSend(ctl){
        setSendStatus(ctl.value,ctl.checked);
        
        if (ctl.checked){
            $('#divPreview' + ctl.value).slideToggle(speed);
             $('#divEdit' + ctl.value).slideToggle(speed);
            
            //$('#divPreview' + ctl.value).css({display: "inline"});
        }else{
            $('#chkPreview' + ctl.value).get(0).checked=false;
            $('#divPreview' + ctl.value).slideToggle(speed);
             $('#divEdit' + ctl.value).slideToggle(speed);
            //$('#divPreview' + ctl.value).css({display: "none"});
            //$('#divPreview' + ctl.value).slideToggle("slow");
        }
        
    }
    
    function doJsClear(){
	    
	}
    
    
    function setDisplayStatus(statusID,value){
        $.post("/employer/_ws/emailOptions.aspx",{updateType: "display", statusID: statusID, value: value });
    }
     function setSendStatus(statusID,value){
        $.post("/employer/_ws/emailOptions.aspx",{updateType: "send", statusID: statusID, value: value });
    }

    function setPreviewStatus(statusID,value){
        $.post("/employer/_ws/emailOptions.aspx",{updateType: "preview", statusID: statusID, value: value });
    }    
	// end Status functions


    var cacheJslist
    var cacheJsid
    var cacheJbid
    var cacheStatusid
    function ajaxInvite(jsid, jslist, jbid) {
        cacheJslist = jslist
        cacheJsid = jsid
        cacheStatusid = 11
        cacheJbid=jbid

           showStatusemail(11)

           return;
           


       }
       function ajaxInviteFinish(jsid, jslist, jbid) {
            //alert('finish invite')
           document.body.style.cursor = 'wait';
           $('#jnk').ajaxSuccess(function () {

               $("#hidFld1").get(0).form.submit();
           });
           if (jsid == 0) {
               //if (confirm('Do you want to invite all selected Jobseekers?')) {
                   $('#jnk').load('/employer/xt_EmployerActivity.aspx?bulkInvite=1&ajax=1&Action=Invite&JobID=' + jbid + '&jslist=' + jslist)
               //}
           } else {
                   // if (confirm('Do you want to invite this jobseeker?')) {
           alert('/employer/xt_EmployerActivity.aspx?ajax=1&Action=Invite&JobID=' + jbid + '&JobSeekerID=' + jsid);
                   $('#jnk').load('/employer/xt_EmployerActivity.aspx?ajax=1&Action=Invite&JobID=' + jbid + '&JobSeekerID=' + jsid)
              // }
           }
           document.body.style.cursor = 'default';
       }


	function ajaxSave(jobid,jsid){
            $('#jnk').ajaxSuccess(function() {
              document.location=document.location;
            }); 
            $('#jnk').load('/employer/xt_EmployerActivity.aspx?ajax=1&Action=Save&JobID=' + jobid +'&JobSeekerID=' + jsid)
            document.body.style.cursor = 'default';
    				        
        }
    	function ajaxUnSave(jobid,jsid,jslist){
            $('#jnk').ajaxSuccess(function() {
                
              document.location=document.location;
            }); 
            if (jsid==0){
                $('#jnk').load('/employer/xt_EmployerActivity.aspx?bulkUnsave=1&action=Unsave&ajax=1&JobID=' + jobid +'&jslist=' + jslist)
            }else{
                $('#jnk').load('/employer/xt_EmployerActivity.aspx?ajax=1&Action=Unsave&JobID=' + jobid +'&JobSeekerID=' + jsid)
            }
    				        document.body.style.cursor = 'default';
        }			    
    				    

    				    ///employer/xt_EmployerActivity.aspx?Action=Unsave&JobID=" & JobID & "&JobSeekerID=" & js.ID 

        // code for employer callback
        function closeEmployerCallback() {
            hideAndClearAll()
            lastBoxOpened = ""
        }
        function saveEmployerCallback(jsid, cbDate,cbHour,cbMin,cbtt,cbMessage) {
            var qs = ''
            qs = '&cbDate=' + cbDate + '&cbHour=' + cbHour + '&cbMin=' + cbMin + '&cbtt=' + cbtt + '&cbMessage=' + escape(cbMessage);
           
            $("#lblCBHolder").html('<label title=\'' + cbMessage + '\'>' + cbDate +  '</label>')
            
            $('#jnk').load('/employer/xt_EmployerActivity.aspx?JobSeekerID=' + jsid + '&setCallback=1&' + qs)
            lastBoxOpened = ""
            hideAndClearAll()

        }
        function deleteEmployerCallback(jsid) {
            if (confirm('Clear this callback?')) {
                $('#jnk').load('/employer/xt_EmployerActivity.aspx?JobSeekerID=' + jsid + '&setCallback=1&del=1')
                lastBoxOpened = ""
                hideAndClearAll()
            }
        }
        //

        function showEmployerCallback(jbid, jsid, source) {
            var hasChecked
            var jslist = ''
            if (lastBoxOpened == "empCallback") {
                hideAndClearAll()
                return false;
            } else {
                hideAndClearAll()

            }


            lastBoxOpened = "empCallback"
            suppressJtip = true;
            

            $('#hidjsid').val(jsid);
            $('#hidjbid').val(jbid);

            var y, x
            y = getAbsoluteTop(source) + 19; //set y position
            x = getAbsoluteLeft(source) 

            var x2
            x2 = getAbsoluteLeft(source) - 280

            $('#bvisible').html(HTML_WAIT);
            $('#bvisible').css({ left: x + "px", top: y + "px", width: "0px", height: "0px", overflow: "scroll" });

            $('#bvisible').show();

            $("#bvisible").animate({
                left: x2,
                width: "340px",
                height: "200px"
            }, 500);
            $('#bvisible').html(HTML_WAIT)
            $('#bvisible').load('/employer/tips/callback.aspx?jsid=' + jsid + '&jbid=' + jbid);
        }

        
        
        
        			    
   //CODE FOR EMPLOYER RATING

function closeEmployerRate(){
    hideAndClearAll()
    lastBoxOpened=""
}
function saveEmployerRate(jbid,jsid){
 
    var qs=''
    $(".ranksel").each(
        function (i){
            if ($(this).val()>0){
               qs=qs + this.id + '=' + $(this).val() + '&'
            }
        }
     );
       var loginid = $("#slctRankingsFor").val();
       var loginqs = ''
       if (loginid != null) {
           loginqs = 'lid=' + loginid + '&'
       }
       var preRank = $("#slctPreRank").val();
       if (preRank > 0) {
           
           $("#pr" + jsid).html('Pre-interview: ' + preRank)
       } else {
           $("#pr" + jsid).html('&nbsp;')
           
       }
       $('#jnk').load('/employer/xt_EmployerActivity.aspx?JobID=' + jbid + '&JobSeekerID=' + jsid + '&ranking=1&prerank=' + preRank + '&' + loginqs + qs)
       
    lastBoxOpened=""
       hideAndClearAll()
    
}

function reloadEmployerRate(jbid, jsid, loginid) {
    var loginid = $("#slctRankingsFor").val();
    var loginqs = ''
    if (!isNaN(loginid)) {
        loginqs = '&lid=' + loginid
    }

    $('#bvisible').html(HTML_WAIT)
    $('#bvisible').load('/employer/tips/employerjsrating.aspx?jsid=' + jsid + '&jbid=' + jbid + loginqs);
}

function showEmployerRate(jbid,jsid,source,loginid){
    var hasChecked
    var jslist = ''
    var loginqs = ''
    if (loginid != null) {
        loginqs='&lid=' + loginid
    }

    if (lastBoxOpened=="empRate"){
        hideAndClearAll()
    
        return false;
    }else{
    hideAndClearAll()
    
    }
    
    
    lastBoxOpened="empRate"
    suppressJtip=false;
    
    
    $('#hidjsid').val(jsid);
    $('#hidjbid').val(jbid);

    var y,x
    y=getAbsoluteTop(source) + 19; //set y position
    x= getAbsoluteLeft(source)+100

    var x2
    x2= getAbsoluteLeft(source)-0

    $('#bvisible').html(HTML_WAIT);
    $('#bvisible').css({left: x+"px", top: y+"px",width: "0px",height:"0px",overflow:"scroll"});

    $('#bvisible').show();

    $("#bvisible").animate({ 
        left: x2,
        width: "320px",
        height: "500px"
      }, 500 );
    $('#bvisible').html(HTML_WAIT)
    $('#bvisible').load('/employer/tips/employerjsrating.aspx?jsid=' + jsid + '&jbid=' + jbid + loginqs);
}

function doRanking(newRank, jsid, jbid) {

    var currentRank = $("#hjsr" + jsid).val()
    $(".rnk" + jsid).each(
        function (index) {
            if (newRank >= $(this).attr("value") && newRank != currentRank) {
                $(this).get(0).src = "/assets/images/buttons/btn_star_on.png"
            } else {
                $(this).get(0).src = "/assets/images/buttons/btn_star_off.png"
            }
        }
    )

        var extraTxt = ''
        if (jbid != null) {
            extraTxt='&jbid=' + jbid
        }

        $("#hjsr" + jsid).val(newRank)
        if (newRank!=currentRank){
        $('#jnk').load('/employer/xt_Rank.aspx?noredir=1&ApplicantID=' + jsid + '&Rank=' + newRank + extraTxt)
        var dte = new Date();
        
        $("#rnkDiv" + jsid).attr("title", "Ranked: " + dte.getMonth() + '/' + dte.getDate() + '/' + dte.getFullYear())
        }else{
        $("#hjsr" + jsid).val(-1)
        $('#jnk').load('/employer/xt_Rank.aspx?noredir=1&clearRank=1&ApplicantID=' + jsid + '&Rank=' + newRank + extraTxt)
        }
    }

    //ajax functions
    function occupationAjax(obj, ctlid) {
        $.ajax({
            beforeSend: function () { $(obj).after("<img src='/assets/images/ajax-loader.gif' id='ajaxLoader' />"); },
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/xt/pubWS.asmx/OccupationList",
            data: "{'IndustryID':'" + $(obj).val() + "'}",
            dataType: "json",
            success: function (msg) {




                $("#" + ctlid).empty().append("<option value='0'></option>");
                for (var i = 0; i < msg.d.length - 1; i++) {
                    $("#" + ctlid).append("<option class='o" + msg.d[i].Value + "' value='" + msg.d[i].Value + "' sctitleid='" + msg.d[i].SCID + "'>" + msg.d[i].Name + "</option>");
                }



            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {

                alert(XMLHttpRequest);
                alert(textStatus);
            },
            complete: function () { $("#ajaxLoader").remove(); }
        });
    }

    function loadtemplate(ctl) {
        if ($(ctl).val() == 0) {
            
            return false;
        } else {

        $.get('/employer/_ws/getEmailTemplate.aspx?subj=1&id=' + $(ctl).val(), function (data) {
            
            $('#Subject').val(data);
            return true;
        });
        $.get('/employer/_ws/getEmailTemplate.aspx?msg=1&id=' + $(ctl).val(), function (data) {

            $('#Message').val(data);
            return true;
        });
        return true;
        }
}



/*
* Date Format 1.2.3
* (c) 2007-2009 Steven Levithan <stevenlevithan.com>
* MIT license
*
* Includes enhancements by Scott Trenda <scott.trenda.net>
* and Kris Kowal <cixar.com/~kris.kowal/>
*
* Accepts a date, a mask, or a date and a mask.
* Returns a formatted version of the given date.
* The date defaults to the current date/time.
* The mask defaults to dateFormat.masks.default.
*/

var dateFormat = function () {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
		    val = String(val);
		    len = len || 2;
		    while (val.length < len) val = "0" + val;
		    return val;
		};

    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
			    d: d,
			    dd: pad(d),
			    ddd: dF.i18n.dayNames[D],
			    dddd: dF.i18n.dayNames[D + 7],
			    m: m + 1,
			    mm: pad(m + 1),
			    mmm: dF.i18n.monthNames[m],
			    mmmm: dF.i18n.monthNames[m + 12],
			    yy: String(y).slice(2),
			    yyyy: y,
			    h: H % 12 || 12,
			    hh: pad(H % 12 || 12),
			    H: H,
			    HH: pad(H),
			    M: M,
			    MM: pad(M),
			    s: s,
			    ss: pad(s),
			    l: pad(L, 3),
			    L: pad(L > 99 ? Math.round(L / 10) : L),
			    t: H < 12 ? "a" : "p",
			    tt: H < 12 ? "am" : "pm",
			    T: H < 12 ? "A" : "P",
			    TT: H < 12 ? "AM" : "PM",
			    Z: utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
			    o: (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
			    S: ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
} ();

// Some common format strings
dateFormat.masks = {
    "default": "ddd mmm dd yyyy HH:MM:ss",
    shortDate: "m/d/yy",
    mediumDate: "mmm d, yyyy",
    longDate: "mmmm d, yyyy",
    fullDate: "dddd, mmmm d, yyyy",
    shortTime: "h:MM TT",
    mediumTime: "h:MM:ss TT",
    longTime: "h:MM:ss TT Z",
    isoDate: "yyyy-mm-dd",
    isoTime: "HH:MM:ss",
    isoDateTime: "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
    monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
    return dateFormat(this, mask, utc);
};

Date.prototype.addHours = function (h) {
    this.setTime(this.getTime() + (h * 60 * 60 * 1000));
    return this;
}
Date.prototype.addMinutes = function (m) {
    this.setTime(this.getTime() + (m * 60 * 1000));
    return this;
}
