﻿

function checkMaxSelected(select, maxSelected) {
    if (!select.storeSelections) {
        select.storeSelections = new Array(select.options.length);
        select.selectedOptions = 0;
    }
    for (var i = 0; i < select.options.length; i++) {
        if (select.options[i].selected && !select.storeSelections[i]) {
            if (select.selectedOptions < maxSelected) {
                select.storeSelections[i] = true;
                select.selectedOptions++;
            } else {
                select.options[i].selected = false;
            }
        } else if (!select.options[i].selected && select.storeSelections[i]) {
            select.storeSelections[i] = false;
            select.selectedOptions--;
        }
    }
}

function OpenRemote(URL) {
    var name = window.open(URL, "form","resizable=no,toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=yes,copyhistory=0,width=450,height=535");
    name.location = URL;
}

// --- Start section that attempts to handle people double clicking on submit buttons
// -- Note this only work successfully sometimes, but it is better than nothing.

var pageIsSubmittingRightNow = false;

function submitOnce(_event, ingnoreValidation) 
{
    if(Page_IsValid || ingnoreValidation)
    {   
        if (pageIsSubmittingRightNow) 
        {
            alert('Processing... Please wait.');
            if(typeof Event != 'undefined' && typeof Event.stop != 'undefined') Event.stop(_event);
        }
        else 
        {
            pageIsSubmittingRightNow = true;
        }
    }
}

// .NET's client side validation sets Page_IsValid
// if Page_IsValid is not yet defined, define it
if(typeof Page_IsValid == 'undefined') Page_IsValid = null;


// for the search pager
var setLocation = function(id, url) {
    document.location = url + $F(id);
};

// for the search pager
var setLocationEmployerJobPager = function(element, postbackLink, employerId) {
    var dropdown = $(element);
    var recordIndex = dropdown.options[dropdown.selectedIndex].value;
    var location = postbackLink + '?RecordIndex=' + recordIndex + '&EmployerId=' + employerId;     
   document.location = location;
};

var validateAnyInputForPostBack = function(className, id, url) {
    var returnValue = false;
    var requiredFields = $$('.' + className);
    requiredFields.each(function(field) {
        if (field.value.blank() == false) {
            returnValue = true;
            throw $break;
        }
    });
    if (!returnValue) {
        alert("Please select some criteria.");
        return false;
    }
    else {
        var name = $(id).name;
        WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(name, "", false, "", url, false, false))
    }
};

var validateSingleInputForPostBackWithLabel = function(className, requiredLabelName, id, url) {
    var returnValue = false;
    var requiredFields = $$('.' + className);
    requiredFields.each(function(field) {
        if (field.value.blank() == false) {
            returnValue = true;
            throw $break;
        }
    });
    
    if (!returnValue) {
        $(requiredLabelName).show();
        return false;
    }
    else {
        var name = $(id).name;
        WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(name, "", false, "", url, false, false))
    }
};


// Summary:
// validateSearchCriteria is used on the resume search page to validate
// that the user has entered a value for at least one of the search fields
// Parameters:
// e = event
// className = class name of fields to validate
// errorLabel = optional, id of error label field
var validateSearchCriteria = function(e, className, errorLabel) {
     
    var value = false;
    var fields = $$('.' + className);
    
    // check if any field has a value
    fields.each(function(field) {
        if (field.value.blank() == false) {
            value = true;
            throw $break;
        }
    });
        
    // no fields have a value
    if (!value) {
        
        // stop click/submit event
        Event.stop(e);
        
        // show error label
        if (errorLabel != null && errorLabel != 'undefined' && errorLabel != '') {
            $(errorLabel).show();
        }
        else {
            alert("Please select one or more search criteria.");
        }
    }    
    else { 
        checkKeywords(e);
    }
};

var checkKeywords = function(e) {    
    var keywords = $$(".search-keywords")[0].value;
    if ((keywords.include('<') || keywords.include('>'))) {
        Event.stop(e);
        alert("The keywords field cannot include HTML or special characters.  '<' or '>' are not allowed.");
        
    }
};


var textCounter = function(inputId, counterId, maxlimit) {
    var foo = $F(inputId);
    if (foo.length > maxlimit) { // if too long...trim it!
        $(inputId).value = foo.substring(0, maxlimit);
    }
    else {  // otherwise, update 'characters left' counter
        $(counterId).innerHTML = (maxlimit - foo.length);
        $(counterId).innerText = (maxlimit - foo.length);
    }
};

/*
    Updates the multiSelectList with the correct set of metro areas populated by whatever id is in the selectList
*/
var updateMetroAreaReferrals = function(selectListId, multiSelectListId) {
    var metroAreaId = $F(selectListId);
    if (metroAreaId != null && metroAreaId.length > 0 && metroAreaId != '00000000-0000-0000-0000-000000000000'){
        new Ajax.Updater(multiSelectListId, '/ajax/MetroAreaReferralTypes.ashx', {
            parameters: { MetroAreaId: metroAreaId }   
        });
    }
};

function isBadIE()
{var isBad=false;if(Prototype.Browser.IE){var rslt=navigator.appVersion.match(/MSIE (\d+\.\d+)/,'');isBad=(rslt!=null&&Number(rslt[1])<7);}
return isBad;}

function hideDialog(dialogId)
{$(dialogId).hide();}

function showDialog(dialogId,evt) {
    var dialog=$(dialogId);
    var x;var y;var relativeY;
    var e = Event.element(evt);
    x = Position.cumulativeOffset(e)[0];
    y = Position.cumulativeOffset(e)[1]+(e.getHeight());
    relativeY = Position.page(e)[1];
    var bodyWidth=$$('body')[0].getWidth();
    var useTop=(relativeY<dialog.getHeight());
    var useLeft=(x+dialog.getWidth()<bodyWidth);
    var top="top";var bottom="bottom";
    if(useTop) {
        top += (useLeft) ? "_left" : "_right";
    } else { 
        bottom += (useLeft) ? "_left" : "_right";
    }
    var url = "url(/App_Themes/Default/Images/Dialog/";
    var ext = (isBadIE()) ? ".gif)" : ".png)";    
    $(dialogId+'Top').setStyle({backgroundImage:url+top+ext});
    $(dialogId+'Bottom').setStyle({backgroundImage:url+bottom+ext});
    $(dialogId+'Body').setStyle({backgroundImage:url+'body'+ext});    
    var top = ((useTop)?y:y-dialog.getHeight());
    var left = ((useLeft)?x:x-dialog.getWidth());
    dialog.setStyle({'left':left+'px','top':top+'px'});
    dialog.show();
}


var htmlValidator = function(sender, args) {        
    var regex = new RegExp(/<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/gim);
    args.IsValid = !regex.test(args.Value);    
    return args.IsValid;
}


function formatCurrency(num) 
{       
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
    cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+
    num.substring(num.length-(4*i+3));
    //return (((sign)?'':'-') + '$' + num + '.' + cents);
    return (((sign)?'':'-') + num + '.' + cents);
}


var Cookie = {
	set: function(name,value,seconds){
		if(seconds){
			d = new Date();
			d.setTime(d.getTime() + (seconds * 1000));
			expiry = '; expires=' + d.toGMTString();
		}else
			expiry = '';
		document.cookie = name + "=" + value + expiry + "; path=/";
	},
	get: function(name){
		nameEQ = name + "=";
		ca = document.cookie.split(';');
		for(i = 0; i < ca.length; i++){
			c = ca[i];
			while(c.charAt(0) == ' ')
				c = c.substring(1,c.length);
			if(c.indexOf(nameEQ) == 0)
				return c.substring(nameEQ.length,c.length);
		}
		return null
	},
	unset: function(name){
		Cookie.set(name,'',-1);
	}
}




var addToInbox = function(resumeId) {
    var link = $('add_to_inbox_' + resumeId);
    var icon = $('icon_' + resumeId);
    icon.src = "/App_Themes/Default/Images/Icons/spinner.gif";
    
    new Ajax.Request('/ajax/AddJobToInbox.ashx', {
        method: 'get',        
        parameters: { ResumeId: resumeId },
        onSuccess: function(transport) {
            link.innerHTML = 'Added to Inbox!';
            link.setStyle({fontWeight: 'bold'});
            new Effect.Highlight(link);
        },
        onFailure: function(transport) {
            link.innerHTML = 'Unable to add to Inbox!';
            new Effect.Highlight(link, {startcolor: '#ff0000', endcolor: '#ffffff'});
        },
        onComplete: function() {
            icon.src = "/App_Themes/Default/Images/Icons/modify.gif";
        }        
    });
    
};

var toggleSidebarLinks = function() {
    var others = $$('#left_sidebar a.other');
    if (others.length > 0) {
        others.invoke('observe', 'click', function(e){
            e.preventDefault();
            var link = $(e.target);
            ul = link.up('ul').previous('ul');
            
            if (!link.hasClassName('fewer')) {
                // If the link has not toggled the list... show it
                link.innerHTML = link.innerHTML.replace(/More/,'Fewer');
                link.addClassName('fewer');
                ul.removeClassName('other').addClassName('_other');            
            } else {
                // otherwise, hide it
                link.innerHTML = link.innerHTML.replace(/Fewer/,'More');
                link.removeClassName('fewer');
                ul.removeClassName('_other').addClassName('other');
            }
            
            // Now, find the other expanded list
            var otherUL = ul.siblings().find(function(u){ return u.hasClassName('_other') });
            if (otherUL != undefined) {
                // Hide it
                otherUL.removeClassName('_other').addClassName('other');
                
                // Find the link, toggle it and change the text.
                var otherLink = otherUL.next().down('a.other').removeClassName('fewer');
                otherLink.innerHTML = otherLink.innerHTML.replace(/Fewer/, 'More');
            }
        });
    }
};

var toggleSearchTerms = function() {
    var input = $('search_term');
    if (input != null) {
        var defaultValue = input.defaultValue;
        input.observe('focus', function(e) {
            if ($F(input) == defaultValue) {
                input.clear();
            }
        }).observe('blur', function(e) {
            if ($F(input) == '') {
                input.value = defaultValue;
            }
        });
    }
};


var bindSubmitOnceEvents = function() {
    $$('form').invoke('observe','submit',function(event){
        submitOnce(event);
    });
};

var bindTextCounters = function() {
    $$('.text-counter').each(function(tc){
        new Form.Element.Observer(tc.id,0.15,function(el,value){
            textCounter(tc.id,tc.readAttribute('maxlabel'),tc.readAttribute('maxlength'));
        });
    });
};

document.observe('dom:loaded',function(event){
    bindTextCounters();
    // not working as expected
    //bindSubmitOnceEvents();
    toggleSidebarLinks();
    toggleSearchTerms();
});

