﻿(function($) {
    var 
    // Will speed up references to window, and allows munging its name.
	window = this,
    // Will speed up references to undefined, and allows munging its name.
	undefined;
   
    
    var hideDelayTimer = null;
    
// Add utility methods to String objects.
String.prototype.startsWith = function(substring) {    
    return this.indexOf(substring, 0) === 0;
}

SearchQuery = function() {
    this.keywords = '';
    this.category = '';
    this.city = '';
    this.state = '';
    this.zipCode = '';
    this.pageIndex = 0;
    this.pageSize = 20;
    this.employment = '';
    this.education = '';
    this.experience = '';
    this.radius = '';
    this.country  = '';
};

SearchQuery.prototype.toQueryString = function() {
    var
        me = this,
       //AG:01/26/2010: commented this to check for rovein site  and 
       //add only serachresult page only for roevin site
     //queryString = adecco.jobsearch.variationLabelPath[0] + adecco.config.searchResultPage;
     //queryString = adecco.config.searchResultPage.toLowerCase().indexOf("roevin") > 0 ? 			
      //  		    adecco.config.searchResultPage :
      //  		    adecco.jobsearch.variationLabelPath[0] + adecco.config.searchResultPage;
        
     queryString = window.location.href.toLowerCase().indexOf(adecco.jobsearch.SiloURL) > 0 ? 			
        		    adecco.jobsearch.SiloURL + '/job-seekers/job-search/Pages/search-results.aspx?' :
        		    adecco.jobsearch.variationLabelPath[0] + adecco.config.searchResultPage;
        	
     queryString += 'kws=' + escape(me.keywords);
    //Updated by Anil to fix the issue - See all on recent-jobs is throwing job service exception.
    if(me.category == null)	{
		me.category='';
	}
	if(me.employment == null)	{
		me.employment='';
	}
	if(me.education == null)	{
		me.education='';
	}
	if(me.experience == null)	{
		me.experience='';
	}
    queryString += '&cat=' + escape(me.category);
    queryString += '&emp=' + escape(me.employment);
    queryString += '&edu=' + escape(me.education);
    queryString += '&exp=' + escape(me.experience);
    if(escape(me.radius) == "" || escape(me.radius) == null|| me.radius == null)
         queryString += '&rds=' + adecco.config.defaultDistanceRadius;
    else
        queryString += '&rds=' + escape(me.radius);
    
    if (me.pageIndex && me.pageIndex > 0) {
        queryString += '&pdx=' + escape(me.pageIndex);
    }

    queryString += '&cnty=' + escape(me.country);
    //extract city, state and zipcode from location
    parseLocation(me.zipCode);    
    
    if(SearchQuery.city != null)
        queryString += '&cty=' + escape(SearchQuery.city);
    if(SearchQuery.state != null)    
        queryString += '&stt=' + escape(SearchQuery.state);   
    if(SearchQuery.zipCode != null) 
        queryString += '&zip=' + escape(SearchQuery.zipCode);   

    // end of parsing code
    
    
    return queryString;
};



})(jQuery);


//*****************************************************************************
// jQuery additions

// Remove the 'filter' attribute after fading in/out
// otherwise IE7 will display ugly text using Windows' Cleartype rendering
// see bottom of http://blog.bmn.name/tag/jquery
//*****************************************************************************
jQuery.fn.customFadeIn = function(speed, callback) {
	return this.animate( {opacity: "show" }, speed,
		function() {
			if (jQuery.browser.msie)
				this.style.removeAttribute("filter");
			if (jQuery.isFunction(callback)) {
				this.callback = callback;
				this.callback();
			}
		}
	);
};

jQuery.fn.customFadeOut = function(speed, callback) {
	return this.animate( {opacity: "hide" }, speed,
		function() {
			if (jQuery.browser.msie)
				this.style.removeAttribute("filter");
			if (jQuery.isFunction(callback)) {
				this.callback = callback;
				this.callback();
			}
		}
	);
};

jQuery.fn.customFadeTo = function(speed, to, callback) {
	return this.animate( {opacity: to }, speed,
		function() {
			if ((to == 1) && jQuery.browser.msie)
				this.style.removeAttribute("filter");
			if (jQuery.isFunction(callback)) {
				this.callback = callback;
				this.callback();
			}
		}
	);
};
//*****************************************************************************

//*****************************************************************************
// Methods to show a overlay a transparent grey background and a "loading" animated gif.
//*****************************************************************************
(function($){
	
	/**
	 * Displays loading mask over selected element.
	 *
	 * @param label Text message that will be displayed on the top of a mask besides a spinner (optional). 
	 * 				If not provided only mask will be displayed without a label or a spinner.  	
	 */
	$.fn.mask = function(label){
		this.unmask();
		
		if(this.css("position") == "static") {
			this.addClass("masked-relative");
		}
		
		this.addClass("masked");
		
		var maskDiv = $('<div class="loadmask"></div>');
		
		//auto height fix for IE
		if(navigator.userAgent.toLowerCase().indexOf("msie") > -1){
			maskDiv.height(this.height() + parseInt(this.css("padding-top")) + parseInt(this.css("padding-bottom")));
			maskDiv.width(this.width() + parseInt(this.css("padding-left")) + parseInt(this.css("padding-right")));
		}
		
		this.append(maskDiv);
		
		var maskMsgDiv = $('<div class="loadmask-msg" style="display:none;"></div>');
		
		this.append(maskMsgDiv);
			
		//calculate center position
		maskMsgDiv.css("top", Math.round(this.height() / 2 - (maskMsgDiv.height() - parseInt(maskMsgDiv.css("padding-top")) - parseInt(maskMsgDiv.css("padding-bottom"))) / 2)+"px");
		maskMsgDiv.css("left", Math.round(this.width() / 2 - (maskMsgDiv.width() - parseInt(maskMsgDiv.css("padding-left")) - parseInt(maskMsgDiv.css("padding-right"))) / 2)+"px");
			
		maskMsgDiv.show();
	};
	
	/**
	 * Removes mask from the element.
	 */
	$.fn.unmask = function(label){
		this.find(".loadmask-msg,.loadmask").remove();
		this.removeClass("masked");
		this.removeClass("masked-relative");
	};
 
})(jQuery);
//*****************************************************************************

/**
 * This jQuery plugin displays pagination links inside the selected elements.
 *
 * @author Gabriel Birke (birke *at* d-scribe *dot* de)
 * @version 1.2
 * @param {int} maxentries Number of entries to paginate
 * @param {Object} opts Several options (see README for documentation)
 * @return {Object} jQuery Object
 */
jQuery.fn.pagination = function(maxentries, opts){
	opts = jQuery.extend({
		items_per_page:10,
		num_display_entries:10,
		current_page:0,
		num_edge_entries:0,
		link_to:"#Next",
		prev_text:"Prev",
		next_text:"Next",
		ellipse_text:"...",
		prev_show_always:true,
		next_show_always:true,
		callback:function(){return false;}
	},opts||{});
	
	return this.each(function() {
		/**
		 * Calculate the maximum number of pages
		 */
		function numPages() {
			return Math.ceil(maxentries/opts.items_per_page);
		}
		
		/**
		 * Calculate start and end point of pagination links depending on 
		 * current_page and num_display_entries.
		 * @return {Array}
		 */
		function getInterval()  {
			var ne_half = Math.ceil(opts.num_display_entries/2);
			var np = numPages();
			var upper_limit = np-opts.num_display_entries;
			var start = current_page>ne_half?Math.max(Math.min(current_page-ne_half, upper_limit), 0):0;
			var end = current_page>ne_half?Math.min(current_page+ne_half, np):Math.min(opts.num_display_entries, np);
			return [start,end];
		}
		
		/**
		 * This is the event handling function for the pagination links. 
		 * @param {int} page_id The new page number
		 */
		function pageSelected(page_id, evt){
			current_page = page_id;
			drawLinks();
			var continuePropagation = opts.callback(page_id, panel);
			if (!continuePropagation) {
				if (evt.stopPropagation) {
					evt.stopPropagation();
				}
				else {
					evt.cancelBubble = true;
				}
			}
			return continuePropagation;
		}
		
		/**
		 * This function inserts the pagination links into the container element
		 */
		function drawLinks() {
			panel.empty();
			var interval = getInterval();
			var np = numPages();
			// This helper function returns a handler function that calls pageSelected with the right page_id
			var getClickHandler = function(page_id) {
				return function(evt){ return pageSelected(page_id,evt); }
			}
			// Helper function for generating a single link (or a span tag if it's the current page)
			var appendItem = function(page_id, appendopts){
				page_id = page_id<0?0:(page_id<np?page_id:np-1); // Normalize page id to sane value
				appendopts = jQuery.extend({text:page_id+1, classes:""}, appendopts||{});
				if(page_id == current_page){
					var lnk = jQuery("<span class='current'>"+(appendopts.text)+"</span>");
				}
				else
				{
					var lnk = jQuery("<a>"+(appendopts.text)+"</a>")
						.bind("click", getClickHandler(page_id))
						.attr('href', opts.link_to.replace(/__id__/,page_id));
						
						
				}
				if(appendopts.classes){lnk.addClass(appendopts.classes);}
				panel.append(lnk);
			}
			// Generate "Previous"-Link
			if(opts.prev_text && (current_page > 0 || opts.prev_show_always)){
				appendItem(current_page-1,{text:opts.prev_text, classes:"prev"});
			}
			// Generate starting points
			if (interval[0] > 0 && opts.num_edge_entries > 0)
			{
				var end = Math.min(opts.num_edge_entries, interval[0]);
				for(var i=0; i<end; i++) {
					appendItem(i);
				}
				if(opts.num_edge_entries < interval[0] && opts.ellipse_text)
				{
					jQuery("<span>"+opts.ellipse_text+"</span>").appendTo(panel);
				}
			}
			// Generate interval links
			for(var i=interval[0]; i<interval[1]; i++) {
				appendItem(i);
			}
			// Generate ending points
			if (interval[1] < np && opts.num_edge_entries > 0)
			{
				if(np-opts.num_edge_entries > interval[1]&& opts.ellipse_text)
				{
					jQuery("<span>"+opts.ellipse_text+"</span>").appendTo(panel);
				}
				var begin = Math.max(np-opts.num_edge_entries, interval[1]);
				for(var i=begin; i<np; i++) {
					appendItem(i);
				}
				
			}
			// Generate "Next"-Link
			if(opts.next_text && (current_page < np-1 || opts.next_show_always)){
				appendItem(current_page+1,{text:opts.next_text, classes:"next"});
			}
		}
		
		// Extract current_page from options
		var current_page = opts.current_page;
		// Create a sane value for maxentries and items_per_page
		maxentries = (!maxentries || maxentries < 0)?1:maxentries;
		opts.items_per_page = (!opts.items_per_page || opts.items_per_page < 0)?1:opts.items_per_page;
		// Store DOM element for easy access from all inner functions
		var panel = jQuery(this);
		// Attach control functions to the DOM element 
		this.selectPage = function(page_id){ pageSelected(page_id);}
		this.prevPage = function(){ 
			if (current_page > 0) {
				pageSelected(current_page - 1);
				return true;
			}
			else {
				return false;
			}
		}
		this.nextPage = function(){ 
			if(current_page < numPages()-1) {
				pageSelected(current_page+1);
				return true;
			}
			else {
				return false;
			}
		}
		// When all initialisation is done, draw the links
		drawLinks();
        // call callback function
        opts.callback(current_page, this);
	});
}

/*
    Parse location infomration to get zip, city and state
*/
function parseLocation(location)
{
    var zipRegEx = "\d{5}(-\d{4})?$|^\D{1}\d{1}\D{1}\-?\ ?\d{1}\D{1}\d{1}$";
    if(adecco.config.isCanada) {        
        if(isValidZipCode(location) || isValidPostalCode(location))
        {
            SearchQuery.zipCode = trim(location);
            return;
        }
    }
    
    
    var locationInfo = location.toString().split(',');
    
    // test code to get autosuggest value
    // var oSuggest = $("#job-location")[0].autocompleter;
    // oSuggest.findValue();   
    // end of text code
    
       // zip, city, state
    if (locationInfo.length == 3)
    {
        SearchQuery.zipCode = trim(locationInfo[0]);
        SearchQuery.city = trim(locationInfo[1]);
        SearchQuery.state = trim(locationInfo[2]);
        
        //alert("Zip: " + SearchQuery.zipCode + ",City: " + SearchQuery.city + ",State: " + SearchQuery.state);
    }
    // city, state
    if (locationInfo.length == 2)
    {
        SearchQuery.city = trim(locationInfo[0]);
        SearchQuery.state = trim(locationInfo[1]);       
        //alert("City: " + SearchQuery.city + ",State: " + SearchQuery.state);
    }
    // 1) Contains zipcode - 10007
    // 2) Last or last two words are state names - "Springfield New Jersey"
    // 3) If not 1 or 2 then assume city name - "Springfield"
    if (locationInfo.length == 1)
    {
        var splitLocation = locationInfo[0].split(" ");
        
        //assuming only first word can be zipcode
        if(isValidZipCode(splitLocation[0]) || isValidPostalCode(splitLocation[0]))
        {
            SearchQuery.zipCode = trim(splitLocation[0]);
            //alert("Zip: " + splitLocation[0]);
        }
        //assume the state code will be the last word in the location (works only for state abbreviations) e.g. NJ
        else if(isStateAbbreviation(splitLocation[splitLocation.length - 1]) || isProvinceAbbreviation(splitLocation[splitLocation.length - 1]))
        {
            SearchQuery.state = trim(splitLocation[splitLocation.length - 1]);
            //alert("State:" + SearchQuery.state);
            if(splitLocation.length > 1)
            {
                //remove state name form location to get the city name
                SearchQuery.city = trim(location.replace(SearchQuery.state, ""));
                //SearchQuery.city = trim(splitLocation[0]);
                //alert("City:" + SearchQuery.city);
            }
        }
        //check if the last word in the location is state name e.g. Utah
        else if(isStateFullName(splitLocation[splitLocation.length - 1]) || isProvinceFullName(splitLocation[splitLocation.length - 1]))
        {
            SearchQuery.state = trim(splitLocation[splitLocation.length - 1]);
            //alert("State one:" + SearchQuery.state);
            if(splitLocation.length > 1)
            {
                //remove state name form location to get the city name
                SearchQuery.city = trim(location.replace(SearchQuery.state, ""));
                //SearchQuery.city = trim(splitLocation[0]);
                //alert("City:" + SearchQuery.city);
            }        
        }
        //check if last two words in the location are state names e.g. New York
        else if(splitLocation.length > 1 && isStateFullName(splitLocation[splitLocation.length - 2] + " " + splitLocation[splitLocation.length - 1]) 
                || splitLocation.length > 1 && isProvinceFullName(splitLocation[splitLocation.length - 2] + " " + splitLocation[splitLocation.length - 1])
                )
        {
            SearchQuery.state = trim(splitLocation[splitLocation.length - 2] + " " + splitLocation[splitLocation.length - 1]);
            //alert("State two:" + SearchQuery.state);
            if(splitLocation.length > 2)
            {
                //remove state name form location to get the city name
                SearchQuery.city = trim(location.replace(SearchQuery.state, ""));
                //SearchQuery.city = trim(splitLocation[0]);
                //alert("City:" + SearchQuery.city);
            }
        }
        else 
        {
            // assign entire location to city field
            SearchQuery.city = trim(location);
            //alert("City only:" + SearchQuery.city);
        }
    }
    
}
function trim(stringToTrim)
{
    return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function isValidZipCode(value) {
   //var re = /^\d{5}([\-]\d{4})?$/;
   var re = /(^\d{5}$)|(^\d{5}-\d{4}$)/;            
   //var re = /^\d{5}(-\d{4})?$|^\D{1}\d{1}\D{1}\-?\ ?\d{1}\D{1}\d{1}$/;
   return (re.test(value));
}

function isValidPostalCode(value) {
   var re = /^\D{1}\d{1}\D{1}\-?\d{1}\D{1}\d{1}$/   ;
   
   if(adecco.config.isCanada) {
        re = /^([a-zA-Z]\d[a-zA-Z])( *-? *)(\d |\d[a-zA-Z] |\d[a-zA-Z]\d)$/ ;
   }
   
   return (re.test(value));
}
function isStateAbbreviation(state){  
    var states = "|AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY|";
    return state.length == 2 && states.indexOf(state.toString().toLocaleUpperCase()) > 0;
}

function isProvinceAbbreviation(province){
    var provinces = "|AB|BC|MB|NB|NL|NS|NT|NU|ON|PE|QC|SK|YT|";
    return province.length == 2 && provinces.indexOf(province.toString().toLocaleUpperCase()) > 0;
}
        
function isStateFullName(state){    
    var _stateNames = new StringBuilder();    
            
    _stateNames.append("Alabama|");
    _stateNames.append("Alaska|");
    _stateNames.append("Arizona|");
    _stateNames.append("Arkansas|");
    _stateNames.append("California|");
    _stateNames.append("Colorado|");
    _stateNames.append("Connecticut|");
    _stateNames.append("Delaware|");
    _stateNames.append("District of Columbia|");
    _stateNames.append("Florida|");
    _stateNames.append("Georgia|");
    _stateNames.append("Hawaii|");
    _stateNames.append("Idaho|");
    _stateNames.append("Illinois|");
    _stateNames.append("Indiana|");
    _stateNames.append("Iowa|");
    _stateNames.append("Kansas|");
    _stateNames.append("Kentucky|");
    _stateNames.append("Louisiana|");
    _stateNames.append("Maine|");
    _stateNames.append("Maryland|");
    _stateNames.append("Massachusetts|");
    _stateNames.append("Michigan|");
    _stateNames.append("Minnesota|");
    _stateNames.append("Mississippi|");
    _stateNames.append("Missouri|");
    _stateNames.append("Montana|");
    _stateNames.append("Nebraska|");
    _stateNames.append("Nevada|");
    _stateNames.append("New Hampshire|");
    _stateNames.append("New Jersey|");
    _stateNames.append("New Mexico|");
    _stateNames.append("New York|");
    _stateNames.append("North Carolina|");
    _stateNames.append("North Dakota|");
    _stateNames.append("Ohio|");
    _stateNames.append("Oklahoma|");
    _stateNames.append("Oregon|");
    _stateNames.append("Pennsylvania|");
    _stateNames.append("Rhode Island|");
    _stateNames.append("South Carolina|");
    _stateNames.append("South Dakota|");
    _stateNames.append("Tennessee|");
    _stateNames.append("Texas|");
    _stateNames.append("Utah|");
    _stateNames.append("Vermont|");
    _stateNames.append("Virginia|");
    _stateNames.append("Washington|");
    _stateNames.append("West Virginia|");
    _stateNames.append("Wisconsin|");
    _stateNames.append("Wyoming|");
    
    return _stateNames.toString().toLocaleUpperCase().indexOf("|" + state.toString().toLocaleUpperCase() + "|") > 0;
}

function isProvinceFullName(province)
{
    var provinceNames = new StringBuilder();
    
    provinceNames.append("Alberta|");
    provinceNames.append("British Columbia|");
    provinceNames.append("Manitoba|");
    provinceNames.append("New Brunswick|");
    provinceNames.append("Newfoundland and Labrador|");
    provinceNames.append("Northwest Territories|");
    provinceNames.append("Nova Scotia|");
    provinceNames.append("Nunavut|");
    provinceNames.append("Ontario|");
    provinceNames.append("Prince Edward Island|");
    provinceNames.append("Quebec|");
    provinceNames.append("Saskatchewan|");
    provinceNames.append("Yukon|");

    return provinceNames.toString().toLocaleUpperCase().indexOf("|" + province.toString().toLocaleUpperCase() + "|") > 0;
}

function StringBuilder(value)
{
    this.strings = new Array("");
    this.append(value);
}

// Appends the given value to the end of this instance.
StringBuilder.prototype.append = function (value)
{
    if (value)
    {
        this.strings.push(value);
    }
}

// Clears the string buffer
StringBuilder.prototype.clear = function ()
{
    this.strings.length = 1;
}

// Converts this instance to a String.
StringBuilder.prototype.toString = function ()
{
    return this.strings.join("");
}

/*
    End of location parsing code
*/


// AR 9/22/2010 Moved out of jQuery scope block so components moved to separate files can access these.
function getCookie(cookieName) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(cookieName + "=");
        if (c_start != -1) {
            c_start = c_start + cookieName.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return '';
}

function setCookie(cookieName, value, expiredays, path) {
    var
        expirationDate = new Date()
        ,expires
        ,path;
    
    // Set the expiration date
    expirationDate.setDate(expirationDate.getDate() + expiredays);
    expires = (expiredays == null) ? '' : ';expires=' + expirationDate.toUTCString();
    
    // Set the path (default to "/")
    path = ';path=' + (path || '/');
    
    document.cookie = cookieName + '=' + escape(value) + expires + path;
}

function getStylesheets($head) {    
    $head = $head || $('head');
    var stylesheets = $head.children('link[rel="stylesheet"]');
        
    return stylesheets;
}

function ensureCssFile(filename) {
    var absolutized, cssLinks, i, wasFound = false, $link;
    $head = $('head');
    cssLinks = getStylesheets($head);
    
    absolutized = window.location.protocol + '//' + window.location.host + '/' + filename;
    for (i=0; i < cssLinks.length; i++) {
        $link = cssLinks[i];
        if ($link.href === absolutized) {
            wasFound = true;
            break;
        }
    }
    
    if (!wasFound) {
        $link = $('<link href="' + filename + '" rel="stylesheet" type="text/css" />')
        .appendTo($head);                
    }
}

function getQuerystring(key, defaultValue, url)
{
  url = url || window.location.href;
  defaultValue = defaultValue || '';
  key = key.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regex = new RegExp("[\\?&]"+key+"=([^&#]*)");
  var qs = regex.exec(url);
  if(qs == null)
    return defaultValue;
  else
    return qs[1];
}

function onEnterKey(elt, callback) {
    if (elt && callback && typeof (callback) === 'function') {
        elt.keypress(function(e) {            
            if (e.which == 13) {
                callback.apply(elt, [e]);
            }
        });
    }
}

function logThis(message)
{
   $("#footer").append("<p>" + message + "</p>");
}

function getPosition(obj)
{
   var curLeft = 0;
   var curTop = 0;
   if (obj.offsetParent) {
      do {
	curLeft += obj.offsetLeft;
	curTop += obj.offsetTop;
      } while( obj = obj.offsetParent);
   }
   var position = new Object();
   position.left = currLeft;
   position.top = currTop;
   return position;
}
// AR 9/22 changes end.
