﻿(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,

	adecco = window.adecco = window.adecco || {},
	PREF_LOCATION_COOKIE_NAME = 'prefered_location',
	PREF_LOCATION_RECENTJOBS_COOKIE_NAME = 'prefered_location_recentjobs',
	PREF_CATEGORY_COOKIE_NAME = 'prefered_category',
	PREF_FEATURED_ARTICLE_CATEGORY_COOKIE_NAME = 'prefered_featured_article_category';
    
    var config = {
        defaultDistanceRadius: 10,
        defaultAutocompleteMinChars: 2,
        jobTitlesAutocompleteService: '/_layouts/adeccov2/svc/JobTitles.ashx',
        jobTitlesAutocompleteMinChars: 3,
        cssComponent: '/_layouts/adeccov2/css/jobsearch.css',
        carouselCssComponent: '/_layouts/adeccov2/css/jquery.jcarousel.css',
        featuredMediaService: '/_layouts/adeccov2/svc/FeatureMedia.ashx',
        searchResultPage: (window.location.href.indexOf('engineeringandtechnical') > -1 ? 			//TJF r9 10/5/09
        		   '/engineeringandtechnical/career-services/CareerServices/Pages/SearchResults.aspx?' :
        		   '/JobSeekers/JobSearch/Pages/SearchResults.aspx?'),
        insertCssComponent: true,
        animationSpeed: 'medium',
        recentJobsService: '/_layouts/adeccov2/svc/RecentJobs.ashx',
        recentJobsLocationWaterMark: '[Enter zip code]',
        recentJobsNoJobsFoundMsg: 'No jobs were found',
        locationAutocompleteService: '/_layouts/adeccov2/svc/Proximity.ashx',
        carouselOpacityLevel: 0.75,
        
        youtube: {
            fullscreen: {width: 480, height: 385},
            widescreen: {width: 480, height: 295}
        }
    };
    var hideDelayTimer = null;
    
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]);
            }
        });
    }
}

// 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 = '';
};

SearchQuery.prototype.toQueryString = function() {
    var
        me = this,
        queryString = config.searchResultPage;
    queryString += 'kws=' + escape(me.keywords);
    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)
         queryString += '&rds=' + config.defaultDistanceRadius;
    else
        queryString += '&rds=' + escape(me.radius);
    
    if (me.pageIndex && me.pageIndex > 0) {
        queryString += '&pdx=' + escape(me.pageIndex);
    }
    
    //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;
};

adecco.jobsearch = {
    getPreferedLocation: function() {
        var preferedLocation = getCookie(PREF_LOCATION_COOKIE_NAME);
        return preferedLocation;
    },

    setPreferedLocation: function(preferedLocation) {
        setCookie(PREF_LOCATION_COOKIE_NAME, preferedLocation, 365);
    },

    getPreferedCategory: function() {
        var preferedLocation = getCookie(PREF_CATEGORY_COOKIE_NAME);
        return preferedLocation;
    },

    setPreferedCategory: function(preferedLocation) {
        setCookie(PREF_CATEGORY_COOKIE_NAME, preferedLocation, 365);
    },

    pageDidFinishLoading: function() {
        // Register autocomplete to specific inputs
    $('input.job-titles').autocomplete(config.jobTitlesAutocompleteService, { minChars: config.jobTitlesAutocompleteMinChars, selectFirst: false });
        
        // autoFill set to true to automatically pick up the best match
        $('input.job-location').autocomplete(config.locationAutocompleteService, {
            cacheLength: 1
            , minChars: config.defaultAutocompleteMinChars, selectFirst: false 
        });

        // Add watermarks
        $('.job-search-toolbar input').watermark();
        //$('input.job-titles').watermark();
        
        // Register event handlers
        var js = adecco.jobsearch;
        $('.advanced-toggle').click(js.onAdvancedSearchClicked);
        $('.find-jobs-button').click(js.onSearchClicked);

        // Register event for enter key inside keywords and location text boxes
        //This is commented out to fix TFS issue 2807. Please delete this comment and commented out 
        //code after client reviews for initial launch. -Rob Reagan
        $('input.job-titles').keyup(js.onEnterKeyPressed);
        $('input.job-location').keyup(js.onEnterKeyPressed);    
        
        if (config.insertCssComponent) {
            ensureCssFile(config.cssComponent);
        }
        
        //TJF r9 10/6/09  Added t display advanced search is used from prior search TFS 2915
            if (getQuerystring('cat') != '' ||
                getQuerystring('emp') != '' ||
                getQuerystring('edu') != '' ||
                getQuerystring('exp') != '' ||
                getQuerystring('rds', '10') != '10')
                    adecco.jobsearch.toggleAdvancedSearch();
    },
    
    toggleAdvancedSearch: function() {
        $('.advanced-search').slideToggle(config.animationSpeed);
    },
    
    onAdvancedSearchClicked: function(event) {
        adecco.jobsearch.toggleAdvancedSearch();
        event.preventDefault();
    },
    
    doSearch: function(searchWidget) {
        if (!searchWidget) {
            return;
        }
        
        var searchParams, targetUrl, hasErrors = false;
        
        searchParams = new SearchQuery();
        searchParams.keywords = $('.job-titles', searchWidget).val();
        searchParams.zipCode = $('.job-location', searchWidget).val();
        searchParams.category = $('[name="job-search-category"]', searchWidget).val();
        searchParams.employment = $('[name="job-search-employment"]', searchWidget).val();
        searchParams.education = $('[name="job-search-education"]', searchWidget).val();
        searchParams.experience = $('[name="job-search-experience"]', searchWidget).val();
        searchParams.radius = $('[name="job-search-radius"]', searchWidget).val();
        
        if (hasErrors) {
            
        } else {
            targetUrl = searchParams.toQueryString();
            if (targetUrl) {
                document.location = targetUrl;
            }
        }                               
    },
    
     onEnterKeyPressed: function(event) {
        if(event.keyCode == 13){    
            //$('.find-jobs-button').click(adecco.jobsearch.onSearchClicked);  
            var
                me = adecco.jobsearch,
                source = event.currentTarget
                ,searchWidget, location;
            
            // Find the ancestor that holds the whole widget.
            try {
                searchWidget = $(source).parents('.job-search-toolbar');
                
                // Get the location and save it.
                location = $('.job-location', searchWidget).val();
                me.setPreferedLocation(location);
                
                // Perform the actual search
                me.doSearch(searchWidget);            
            } finally {
                event.preventDefault();
            }                 
        }
    },
    
    onSearchClicked: function(event) {
        var
            me = adecco.jobsearch,
            source = event.currentTarget
            ,searchWidget, location;
        
        // Find the ancestor that holds the whole widget.
        try {
            searchWidget = $(source).parents('.job-search-toolbar');
            
            // Get the location and save it.
            location = $('.job-location', searchWidget).val();
            me.setPreferedLocation(location);
            
            // Perform the actual search
            me.doSearch(searchWidget);            
        } finally {
            event.preventDefault();
        }                       
    }
};

adecco.homepage = {
    docLibUrl: {},
 
    onCarouselItemMouseOver: function(evt) {
        $(this).fadeTo('def', 1);
    },
    
    onCarouselItemMouseOut: function(evt) {
        $(this).fadeTo('fast', config.carouselOpacityLevel);
    },

    registerCarouselItemsCallback: function() {
        var i, carouselItems = $('.media-carousel ul li');
        carouselItems.each(function(index, elt) {
            var me = $(this);
            me.fadeTo('fast', config.carouselOpacityLevel);
            me.hover(adecco.homepage.onCarouselItemMouseOver, adecco.homepage.onCarouselItemMouseOut);
            $('a', me).click(adecco.homepage.didSelectCarouselItem);
        });
    },
    
    handleSelectedCarouselItem: function(event, elt, autoplay) {
        var
            item = elt,
            id = getQuerystring('id', '', item.href),
            url = config.featuredMediaService + '?m=' + id + '&url=' +  adecco.homepage.docLibUrl[0],
            widget = $(item).parents('.media-carousel').get(0),
            carousel = $('.jcarousel-skin-adecco', widget),
            targetContainer = $('.current-media', widget);
        
        $.getJSON(url,
            function(data) {
                // Set title & summary
                $('.title-inner', widget).html(data.Title);
                $('.subtitle', widget).html(data.Summary);
                
                var contentWidth = carousel.width();
                adecco.homepage.handleMedia(data, targetContainer, {width: contentWidth, height:null}, autoplay);
            });
        
        if (event && event.preventDefault) {
            event.preventDefault();
        }    
    },
    
    didSelectCarouselItem: function(event) {
        adecco.homepage.handleSelectedCarouselItem(event, this, true);        
    },
    
    handleMedia: function(media, targetContainer, targetDimension, autoplay) {
        /// <summary>Selects the appriopriate method to handle the media</summary>
        var
            me = this
            ,dimension = config.youtube.widescreen
            ,posterFrame = null;            
        
        if (media.PosterFrameUrl)
        {
            dimension = config.youtube.widescreen
            posterFrame = $('<img/>')
                .attr('src', media.PosterFrameUrl)
                .css({
                    'width': dimension.width,
                    'height': dimension.height
                });
                        
            // Remove any existing media before adding the poster frame
            $(targetContainer).html('');
            $(targetContainer).append(posterFrame);
        }
        
        if (media.ContentUrl) {
            if (media.ContentUrl.startsWith('http://www.youtube.com')) {
                // Use YouTube widescreen format
                var videoSize = config.youtube.widescreen;
                
                // Add an onClick event handler to the poster frame or play directly if no frame.
                if (posterFrame) {
                    posterFrame.click(function () {
                        me.handleYouTubeVideo(media.ContentUrl, targetContainer, videoSize, true);
                    });
                } else {
                    me.handleYouTubeVideo(media.ContentUrl, targetContainer, videoSize, autoplay);
                }                
            }
        } else if (media.Content) {
            // Handle the HTML content of the media.
            this.handleHtmlContent(media.Content, targetContainer);
        } else {
            // Media has no content URL and no HTML content. Nothing to do really...
        }
    },
    
    handleYouTubeVideo: function(url, targetContainer, videoSize, autoplay) {
        ///<summary>Inserts the YouTube video located at 'url' into targetContainer.</summary>
        videoSize = videoSize || config.youtube.fullscreen;
        var videoId, isWatchUrl;
        
        // Remove any existing media before adding a placeholder
        targetContainer.html('');
        
        // Ensure YouTube URL is correcyly setup
        isWatchUrl = url.startsWith('http:\/\/www.youtube.com\/watch\?v=');
        if (isWatchUrl) {
            videoId = getQuerystring('v', '', url);            
            url = 'http://www.youtube.com/v/' + videoId;
        }
        
        // Inject a placeholder since the YouTube object will replace the element.        
        var placeholderId = new Date().getTime();
        $('<div id="' + placeholderId +'"/>').appendTo(targetContainer);
        
        var params = {
            allowScriptAccess: 'always'
            ,wmode: 'transparent'            
         };
        var atts = { id: 'myytplayer'};
        var fullUrl = url + '&enablejsapi=1&playerapiid=ytplayer';
        
        // The following function is automatically called by the YouTube player when ready.
        var oldHandler = window.onYouTubePlayerReady;
        window.onYouTubePlayerReady = function(playerId) {
            var ytplayer = document.getElementById(atts.id)
            
            if (ytplayer && autoplay === true) {
                // Start playing the video.
                ytplayer.playVideo();
            }                                
            window.onYouTubePlayerReady = oldHandler;            
        }
        // Embed the YouTube player.
        swfobject.embedSWF(fullUrl, placeholderId, videoSize.width, videoSize.height, '8', null, null, params, atts);
    },
    
    handleHtmlContent: function(content, targetContainer) {
        ///<summary>Inserts the given content in the targetContainer</summary>
        $(targetContainer).html(content);
    },
    
    pageDidFinishLoading: function() {
        // Setup carousel, but only if plugin is available (to avoid error messages)
        
        if ($.jcarousel) {
            ensureCssFile(config.carouselCssComponent);
            adecco.homepage.registerCarouselItemsCallback();
            
            var
                carousels = $('.media-carousel ul'),
                items = $('li:first a', carousels);
            carousels.jcarousel({auto:0, wrap: 'last'});
            
             //Simulate a click on the first element
            items.each(function (index, elt) {
                adecco.homepage.handleSelectedCarouselItem(null, elt, false);                
            });
        }
    }    
};

// ----------------------------------------------------------------
// Jquery methods for content widgets such as LatestNews
// ----------------------------------------------------------------
adecco.contentwidget = {
    currentPopup: null,
    totalDivs: 0,
    contentClassName: 'rotate-content',
    transitionTimeClassName: 'input-transition-time',
    transitionTime: 10000,
 
    // --------------------------------------------------
    // Hides the existing html element and fades in the next element.
    // --------------------------------------------------
    rotateElement: function(x) {
        var cw = adecco.contentwidget;
    
        var y = x;
        if (x == cw.totalDivs) y = 1; else y++;
        $("#rotate" + x).hide();
        $("#rotate" + y).customFadeIn("fast");
        setTimeout(function() { cw.rotateElement(y)}, cw.transitionTime);
    },

    // --------------------------------------------------
    // Initializes the html element content rotation.
    // --------------------------------------------------
    initContentRotation: function() {
        var cw = adecco.contentwidget;
        
        // initialize number of div elements to rotate.
        $("." + cw.contentClassName).attr("id", function(arr) {
            cw.totalDivs++;
            return "rotate" + (arr + 1);
        })

        // hide all rotatable elements except the first one.
        $("." + cw.contentClassName + ":eq(0)").show();
        $("." + cw.contentClassName + ":eq(0)").siblings().hide();

        // get the transition time.
        cw.transitionTime = parseInt($("." + cw.transitionTimeClassName).val());

        cw.rotateElement(0);
    },
    
    initHoverOver: function() {
        $('.bubble-main').each(function() {
        
            // options
            var distance = 0;
            var time = 250;
            var hideDelay = 500;
            var showDelay = 500;

            // tracker
            var hideDelayTimer = null;
            var showDelayTimer = null;

            var beingShown = false;
            var shown = false;

            var trigger = $('.bubble-trigger', this);
            var popup = $('.bubble-content', this).css('opacity', 0);

            // set the mouseover and mouseout on both element
            $([trigger.get(0), popup.get(0)]).mouseover(function(e) {
                // stops the hide event if we move from the trigger to the popup element
                if (hideDelayTimer) clearTimeout(hideDelayTimer);

                // don't trigger the animation again if we're being shown, or already visible
                if (beingShown || shown) {
                    return;
                } 
                else {
                    showDelayTimer = setTimeout(function() {
                
                        beingShown = true;

                        // get height width of the browser window and the popup bubble
                        var windowWidth = $(window).width();
                        var windowHeight = $(window).height();
                        var popupWidth = (popup).width();
                        var popupHeight = (popup).height();

			// get the top/left coordinates of popup relative to the container
			var position = $(popup).parent().position(); // position relative to container
			var docOffset = $(popup).parent().offset(); // position relative to document

                        // calculate position of popup based on current mouse position
                        // also, prevent hover over from being cut off from edges of browser window.                                            
                        var popupLeftPos = docOffset.left; //e.clientX;
                        var popupTopPos = docOffset.top; //e.clientY;
                        var popupRightPos =  popupLeftPos + popupWidth;
                        var popupBottomPos =  popupTopPos + popupHeight;
 
			var posX = position.left;
			var posY = position.top + 20;

                        if (popupRightPos > windowWidth)
                        {
                            // the right of the popup bubble goes past the browser window
                            // popupLeftPos = windowWidth - popupWidth - 15;

			    // calculate negative left offset
			    posX += ((windowWidth - popupWidth - 15) - docOffset.left);
                        }
                        if (popupBottomPos > windowHeight)
                        {
                            // the bottom of the popup bubble goes past the browser window
                            // popupTopPos = windowHeight - popupHeight - 15;

			    // calculate negative top offset
			    posY += ((windowHeight - popupHeight - 15) - docOffset.top);
                        }

                        // hide any prev popup
                        if (adecco.contentwidget.currentPopup != null)
                        {
                            adecco.contentwidget.currentPopup.css('display', 'none');
                        }
                        adecco.contentwidget.currentPopup = popup;
                
                        // reset position of popup box
                        popup.css({
                            position: 'absolute',
                            top: posY, //top: popupTopPos,
                            left: posX, //left: popupLeftPos,
                            display: 'block' // brings the popup back in to view
                        })

                        // (we're using chaining on the popup) now animate it's opacity and position
                        .animate({
                            top: '-=' + distance + 'px',
                            opacity: 1
                        }, time, 'swing', function() {
                            // once the animation is complete, set the tracker variables
                            beingShown = false;
                            shown = true;
                        });
                    }, showDelay);
                }
         
            }).mouseout(function() {
                // reset the timer if we get fired again - avoids double animations
                if (hideDelayTimer) clearTimeout(hideDelayTimer);
                if (showDelayTimer) clearTimeout(showDelayTimer);

                // store the timer so that it can be cleared in the mouseover if required
                hideDelayTimer = setTimeout(function() {
                    hideDelayTimer = null;
                    popup.animate({
                        top: '-=' + distance + 'px',
                        opacity: 0
                    }, time, 'swing', function() {
                        // once the animate is complete, set the tracker variables
                        shown = false;
                        // hide the popup entirely after the effect (opacity alone doesn't do the job)
                        popup.css('display', 'none');
                    });
                }, hideDelay);
            });
        });
    },
    
    init: function()
    {    
        adecco.contentwidget.initHoverOver();
        adecco.contentwidget.initContentRotation();
    }
    
}; // end of adecco.contentwidget

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;
}

// ----------------------------------------------------------------
// Jquery methods for jobsearchresults
// ----------------------------------------------------------------
adecco.jobsearchresults = {
    currentExpandedDesc: null,
    currentShortenDesc: null,
    
        initHoverOver: function() {
        $('.searchListItem').each(function() {
        
            // options
            var distance = 0;
            var time = 250;
            /*var hideDelay = 500;*/
            /*var showDelay = 500;*/
            var hideDelay = 400;
            var showDelay = 400;

            // tracker
            var hideDelayTimer = null;
            var showDelayTimer = null;

            var beingShown = false;
            var shown = false;

             var triggerContainer = $('.job-search-results-moredetails', this);
            var trigger = $('.job-search-results-moredetails-button', this);
           var expandedDesc = $('.job-search-results-description', this);
            var shortenDesc = $('.searchListItemShortDesc', this);
            var closeDesc = $('.searchListItemCloseDesc', this);

            // set the mouseover event on the title
            $([trigger.get(0)]).mouseover(function(e) {
                // stops the hide event if we move from the trigger to the expandedDesc element
                if (hideDelayTimer) clearTimeout(hideDelayTimer);

                // don't trigger the animation again if we're being shown, or already visible
                if (beingShown || shown) {
                    return;
                } 
                else {
                    showDelayTimer = setTimeout(function() {         
                        beingShown = true;
                        
                        // show the expandedDesc box                        
                        expandedDesc.show();
                        shortenDesc.hide();
                        closeDesc.show();
                        trigger.hide();
                        triggerContainer.hide();

                        beingShown = false;
                        shown = true;
                        
                    }, showDelay);
                }
         
            }).mouseout(function() {
                // reset the timer if mouse oves out of trigger zone before time elapses               
                if (showDelayTimer) clearTimeout(showDelayTimer);
            });
            
            $([closeDesc.get(0)]).click(function() {
                expandedDesc.hide();
                shortenDesc.show();
                closeDesc.hide();
                trigger.show();
                triggerContainer.show();
                shown = false;      
            });
            
            });                 
    },
    
    init: function()
    {    
        adecco.jobsearchresults.initHoverOver();
        //Hover over for What you are looking for widget
        adecco.lookingforwidget.initHoverOver();
    }
    
}; // end of adecco.jobsearchresults    

// ----------------------------------------------------------------
// Jquery methods for the My Adecco login toolbar.
// ----------------------------------------------------------------
adecco.myadeccotoolbar = {

    init: function()
    {
        var animationTimeOpen = 300;
        var animationTimeClose = 0;
        var widthSigninLinks = "256px";
        var widthSigninFields = "384px";
    
        var signinLinks = $(".myadecco-toolbar-signin-links");
        var signinFields = $(".myadecco-toolbar-signin-fields");
        var errorLabel = $(".myadecco-toolbar-signin-error .lblError");
        
        $(".expand-btn", signinLinks).click(function() {       
            $(signinLinks).animate({width: "0px"}, animationTimeOpen, 
                function() 
                {
                    $(signinLinks).hide();
                } 
            );
            $(signinFields).animate({width: widthSigninFields}, { queue:false, duration:animationTimeOpen });
            
            $('input[type="text"]:eq(0)', signinFields).focus();
            
            return false;
        });
        
        $(".close-btn", signinFields).click(function() {       
            $('input[type="text"]', signinFields).val('').focus();
            $('input[type="password"]', signinFields).val('').focus();
            $(signinLinks).animate({width: widthSigninLinks}, { queue:false, duration:animationTimeClose });
            $(signinFields).animate({width: "0px"}, animationTimeClose, 
            function() 
            {                
                $(signinFields).hide();
            } 
        );
            
            // Clear error message and textboxes.
            //$(input[type="text"], signinFields).text('');
            errorLabel.text('');
            return false;
        });
        
        var errorMsg = errorLabel.text();
        
        // page load logic
        if (errorMsg != null && errorMsg != "")
        {
            $(signinLinks).hide();
            $(signinFields).show();
        }
        else{
            $(signinLinks).animate({width: widthSigninLinks}, { queue:false, duration:animationTimeClose });
            $(signinFields).animate({width: "0px"}, animationTimeClose, 
                function() 
                {
                    $(signinFields).hide();
                } 
            );
        }
        
        //$("input[type:'text']", signinFields).value('');
        
        $(".myadecco-toolbar-signin-fields input").watermark();
    }

}; // end of adecco.myadeccotoolbar

// ----------------------------------------------------------------
// Jquery methods for featured article summaries.
// ----------------------------------------------------------------
adecco.featuredarticles = {

    classFeaturedArticlesDropDown : ".featured-articles-dropdown",
    urlFeaturedArticlesHandler : "/_layouts/adeccoV2/svc/ArticleSummaryHandler.ashx",
    
    docLibUrls: {},
    maxArticles: {},
    featuredArticlesOnlys: {},
    articleTemplatePageUrls: {},
    maxArticleTitleLengthChars: {},
    maxHoverOverLengthChars: {},
    
    requestFeaturedArticles : function(id, selectedCategory)
    {    
        var me = adecco.featuredarticles;
                
        me.setPreselectedDropDownValue(selectedCategory);
        
        var widget = $("#" + id).parents('.content-widget');
                
        var params = {
            docLibUrl : me.docLibUrls[id],
            maxArticles : me.maxArticles[id],
            featuredArticlesOnly : me.featuredArticlesOnlys[id],
            category : selectedCategory,
            articleTemplatePageUrl: me.articleTemplatePageUrls[id],
            maxArticleTitleLengthChars: me.maxArticleTitleLengthChars[id],
            maxHoverOverLengthChars: me.maxHoverOverLengthChars[id]
        };
        
        $.ajax( {
            url : me.urlFeaturedArticlesHandler,
            data : params,
            success : function(data) { me.processFeaturedArticles(data, id); },
            type : "POST",
            cache : false,
            dataType : "json"
        } );
        
        widget.mask();
    },
    
    processFeaturedArticles : function(data, id)
    {
        var me = adecco.featuredarticles;
    
        var widget = $("#" + id).parents('.content-widget');
        var articleBodyContainer = $('.list-body', widget);
        var existingArticles = $(articleBodyContainer).children();
        
        existingArticles.hide();
        articleBodyContainer.html(data.html).hide().fadeIn("fast");
        
        adecco.contentwidget.initHoverOver();

        widget.unmask();
    },
        
    getPreselectedDropDownValue: function() {    
        var selectedDropDownValue = getCookie(PREF_FEATURED_ARTICLE_CATEGORY_COOKIE_NAME);
        return selectedDropDownValue;
    },

    setPreselectedDropDownValue: function(selectedDropDownValue) {
        setCookie(PREF_FEATURED_ARTICLE_CATEGORY_COOKIE_NAME, selectedDropDownValue, 365);
    },
    
    init : function()
    {
        var me = adecco.featuredarticles;
    
        $(me.classFeaturedArticlesDropDown).change( function() { me.requestFeaturedArticles(this.id, $(this).val()); });
        
    }

}; // end of adecco.featuredarticles

// ----------------------------------------------------------------
// Jquery methods for AllArticleWebPart.
// ----------------------------------------------------------------
adecco.allarticles = {
    pageSize : {},
    numItems : {},
    prevItems : {},
    //paginationContainerClass : {},
    
    handlePaginationClick : function(new_page_index, pagination_container)
    {
        var me = adecco.allarticles;
        
        var id = $(pagination_container).attr('id');
        var widget = $(pagination_container).parents('.content-widget');
        
        var prevItems = me.prevItems[id];
        prevItems.hide();
        
        var newItems = $('li:has(span[id="' + new_page_index + '"])', widget);
        me.prevItems[id] = newItems;
        newItems.show();
        $(newItems[0]).removeClass('first'); // to make sure we are not adding duplicate classes
        $(newItems[0]).addClass('first');
    },
    
    init : function()
    {
        // allArticlesInit is a function that exists only if the WebPart is present on the page.
        if (typeof(allArticlesInit) === 'function') {
            allArticlesInit();
        
            var me = adecco.allarticles;
            
            $(".pagination").each(function(i) {
                var id  = $(this).attr('id'); 
                var pageSize = me.pageSize[id];
                var numItems = me.numItems[id];
                
                var widget = $(this).parents('.content-widget');
                me.prevItems[id] = itemsToHide = $('li:has(span[id="0"])', widget).hide();
                
                $(this).pagination(numItems, {
                    num_edge_entries: 2,
                    num_display_entries: 8,
		            items_per_page : pageSize, 
		            callback : me.handlePaginationClick });		        
		    });
		}
    }
}; // end of adecco.allarticles

adecco.recentjobs = {
    refresh: function(widget, options) {
        var
            requestParams = {}
            categoryControl = $('select', widget),
            locationLabel = $('.location .view span', widget);

        options = options || {};
        
        if (!widget) {
            return;
        }
        
        // Set the request parameters
        requestParams.cat = options.categoryId || categoryControl.val();
        requestParams.loc = options.location || locationLabel.text();                
        
        // Display spinner during load
        $(widget).mask();
         
        // Execute the ASYNC request
        $.ajax( {
            url: config.recentJobsService,
            data: requestParams,
            success: function(data) { adecco.recentjobs.didRetrieveJobs(data, widget); },
            type: "POST"
        } );        
    },
    onSearchClicked: function(event) {
        var
            me = adecco.recentjobs;          
        try {          
            // Perform the actual search
            me.doSearch();            
        } finally {
            event.preventDefault();
        }                       
    },
    doSearch: function() {
        // Get the category and location val 
        var
            widget = $(this).parents('.content-widget.recent-jobs').get(0),
            requestParams = {}
            categoryControl = $('select', widget),
            locationLabel = $('.location .view span', widget);
        var
            options = options || {};      
        
        var userCategorValue = "";
        try{
            userCategorValue = document.getElementById("_userCategory").getAttribute("value");
        }catch(error){}
                    
        // Set the request parameters
        requestParams.cat = options.categoryId || categoryControl.val();
        requestParams.loc = options.location || locationLabel.text();
        
        if (requestParams.cat == "All Categories")
            requestParams.cat = "";   
        if(userCategorValue != "")
             requestParams.cat = userCategorValue;              
             
        if (requestParams.loc == config.recentJobsLocationWaterMark)
            requestParams.loc = "";    
        
        var searchParams, targetUrl, hasErrors = false;
        searchParams = new SearchQuery();
        searchParams.zipCode = requestParams.loc; 
        searchParams.category = requestParams.cat 
        searchParams.radius = "";
        
        if (hasErrors) {
            
        } else {
            targetUrl = searchParams.toQueryString();
            if (targetUrl) {
                document.location = targetUrl;
            }
        }                               
    },
    
    toQueryString: function() {
        var
            me = this,
            queryString = config.searchResultPage;
            queryString += '&cat=' + escape(me.category);
            if(escape(me.radius) == "" || escape(me.radius) == null)
                 queryString += '&rds=' + config.defaultDistanceRadius;
            else
                queryString += '&rds=' + escape(me.radius);
    
        //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;
    },
    didChangeCategory: function() {
        
        var currentWidget = $(this).parents('.content-widget.recent-jobs').get(0);
//            me = adecco.recentjobs,
//            currentWidget = $(this).parents('.content-widget.recent-jobs').get(0),
//            categoryId = $(this).val(),
//            url = config.recentJobsService,
//            requestParams = {};
//            
//        requestParams.cat = categoryId;        
//        
//        // Display spinner during load
//        $(currentWidget).mask();
//        
//        $.ajax( {
//            url: url,
//            data: requestParams,
//            success: function(data) { me.didRetrieveJobs(data, currentWidget); },
//            type: "POST"
//        } );
        adecco.recentjobs.refresh(currentWidget);
    },
    
    didRetrieveJobs: function(content, targetWidget) {
        
        if(content.toString().indexOf(config.recentJobsNoJobsFoundMsg) == -1)
        {              
            var
                currentWidget = $(this).parents('.content-widget.recent-jobs').get(0),
                me = $(this),
                locationContainer = $(me).parents('.location').get(0),
                viewPanel = $('.view', locationContainer), 
                editPanel = $('.edit-controls', locationContainer),
                locationLabel = $('span', viewPanel),
                textbox = $('input', editPanel);     
            
            //save location in cookie only if there were jobs returned for the location
            setCookie(PREF_LOCATION_RECENTJOBS_COOKIE_NAME, textbox.val(), 365);   
        }
        
        $('.list-body', targetWidget).replaceWith(content);
        adecco.contentwidget.initHoverOver();
        $(targetWidget).unmask();
    },
    
    toggleEditLocation: function(locationContainer) {
        var
            viewPanel = $('.view', locationContainer);
            editPanel = $('.edit-controls', locationContainer),
            isEditMode = $(viewPanel).is(':hidden'),
            current = null, target = null;
        
        current = isEditMode ? editPanel : viewPanel;
        target = isEditMode ? viewPanel : editPanel;
        
        current.hide();
        target.fadeIn('fast');         
    },
    
    editLocation: function(event) {
        var
            me = $(this),
            locationContainer = $(me).parents('.location').get(0),
            viewPanel = $('.view', locationContainer), 
            editPanel = $('.edit-controls', locationContainer),
            locationLabel = $('span', viewPanel),
            textbox = $('input', editPanel);
        
        // Set the textbox value to match the label. If water mark text then clear the text box.
        if(locationLabel.text() == config.recentJobsLocationWaterMark)
            textbox.val('');
        else
            textbox.val(locationLabel.text());        
        adecco.recentjobs.toggleEditLocation(locationContainer);
        
        event.preventDefault();
    },
    
    cancelEditLocation: function(event) {
        var
            locationContainer = $(this).parents('.location').get(0);                
        
        adecco.recentjobs.toggleEditLocation(locationContainer);
        event.preventDefault();
    },
    
    saveLocation: function(event) {
        var
            currentWidget = $(this).parents('.content-widget.recent-jobs').get(0),
            me = $(this),
            locationContainer = $(me).parents('.location').get(0),
            viewPanel = $('.view', locationContainer), 
            editPanel = $('.edit-controls', locationContainer),
            locationLabel = $('span', viewPanel),
            textbox = $('input', editPanel);

        // Set the textbox value to match the label. If the user cleared the textbox, revert
        //back to the default text of "[Enter zip code]"
        var locationEntered = textbox.val();
        locationEntered = trim(locationEntered);
        if (locationEntered.length == 0) {   
            locationEntered = config.recentJobsLocationWaterMark;
        }

        locationLabel.text(locationEntered);  
        
        //save location in cookie
        //setCookie(PREF_LOCATION_RECENTJOBS_COOKIE_NAME, textbox.val(), 365);
            
        adecco.recentjobs.toggleEditLocation(locationContainer);
        
        adecco.recentjobs.refresh(currentWidget);
        
        event.preventDefault();
    },
    
    viewAllJobs: function() {
        // Get the category and location val    
        var
            widget = $(this).parents('.content-widget.recent-jobs').get(0),
            requestParams = {}
            categoryControl = $('select', widget),
            locationLabel = $('.location .view span', widget);

        var
            options = options || {};
        
        if (!widget) {
            return;
        }
        
        // Set the request parameters
        requestParams.cat = options.categoryId || categoryControl.val();
        requestParams.loc = options.location || locationLabel.text(); // TODO: parse location
        
        // build context sensitive URL to view all jobs (using category and location)
        window.location = config.searchResultPage + "cat=" + requestParams.cat + "&loc=" + requestParams.loc;        
        
    },    
    
    pageDidFinishLoading: function() {
       var
            recentJobWidgets = $('.content-widget.recent-jobs'),
            jobCategoryDropdown = $('.accessory select', recentJobWidgets),
            editButton = $('.footer a.edit', recentJobWidgets),
            cancelButton = $('.footer .cancel', recentJobWidgets),
            saveButton = $('.footer .save', recentJobWidgets),
            viewAllButton = $('.footer .link-arrow', recentJobWidgets),
            textbox = $('.footer input', recentJobWidgets);
        
        // Register event handlers
        jobCategoryDropdown.change(adecco.recentjobs.didChangeCategory);
        editButton.click(adecco.recentjobs.editLocation);
        cancelButton.click(adecco.recentjobs.cancelEditLocation);
        saveButton.click(adecco.recentjobs.saveLocation);
        onEnterKey(textbox, adecco.recentjobs.saveLocation);
        viewAllButton.click(adecco.recentjobs.onSearchClicked);
        
        //Commented out on 10-7-2009 by Rob Reagan. This is a TEMPORARY fix to the issue of IE throwing a javascript
        //error when the autocomplete dropdown is visible and the user clicks the Save or Cancel button. see TFS issue
        //2854.
        // Register autocomplete to specific inputs
        //$('.recent-jobs .edit-controls input:text').autocomplete(config.locationAutocompleteService, {
        //    cacheLength: 1
        //    ,minChars: config.defaultAutocompleteMinChars
        //   
        //    ,width: 320
        //});
    }    

};

// Register a callback when the Page is ready (DOM loaded).
$(document).ready(adecco.jobsearch.pageDidFinishLoading);
$(document).ready(adecco.contentwidget.init);
$(document).ready(adecco.jobsearchresults.init);
$(document).ready(adecco.myadeccotoolbar.init);
$(document).ready(adecco.featuredarticles.init);
$(document).ready(adecco.homepage.pageDidFinishLoading);
$(document).ready(adecco.recentjobs.pageDidFinishLoading);
$(document).ready(adecco.allarticles.init);

})(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}$";
    
    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]))
        {
            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]))
        {
            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]))
        {
            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]))
        {
            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{4})?$|^\D{1}\d{1}\D{1}\-?\ ?\d{1}\D{1}\d{1}$/;
   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 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 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
*/

// ----------------------------------------------------------------
// Jquery methods for Looking For? widget
// ----------------------------------------------------------------
adecco.lookingforwidget = {
    currentPopup: null,
    totalDivs: 0,
    contentClassName: 'rotate-content',
    transitionTimeClassName: 'input-transition-time',
    transitionTime: 10000,
    
    initHoverOver: function() {
        $('.looking-for-main').each(function() {
        
            // options
            var distance = 0;
            var time = 250;
            var hideDelay = 500;
            var showDelay = 500;

            // tracker
            var hideDelayTimer = null;
            var showDelayTimer = null;

            var beingShown = false;
            var shown = false;

            var trigger = $('.ms-sbplain', this);
            var popup = $('.looking-for-popup', this).css('opacity', 0);
            var recentJobsCategoryDropdown = document.getElementById('jobAreas');

            // set the mouseover and mouseout on both element
            $([trigger.get(0), popup.get(0)]).mouseover(function(e) {
                // stops the hide event if we move from the trigger to the popup element
                if (hideDelayTimer) clearTimeout(hideDelayTimer);

                // don't trigger the animation again if we're being shown, or already visible
                if (beingShown || shown) {
                    return;
                } 
                else {
                    showDelayTimer = setTimeout(function() {

                    beingShown = true;
                    //this is required because of an IE6 bug where dropdownlists bleed through divs.
                    //the only way to fix this in IE6 is to hide the dropdownlist when the div is shown, 
                        //and re-show the dropdownlist when the div is hidden. 
                        try{
                            recentJobsCategoryDropdown.style.visibility = 'hidden';
                        }catch(err){}

                        // get height width of the browser window and the popup bubble
                        var windowWidth = $(window).width();
                        var windowHeight = $(window).height();
                        var popupWidth = (popup).width();
                        var popupHeight = (popup).height();

                        // calculate position of popup based on current mouse position
                        // also, prevent hover over from being cut off from edges of browser window.                                            
                        var popupLeftPos = e.clientX;
                        var popupTopPos = e.clientY;
                        var popupRightPos =  popupLeftPos + popupWidth;
                        var popupBottomPos =  popupTopPos + popupHeight;
                        
                        if (popupRightPos > windowWidth)
                        {
                            // the right of the popup bubble goes past the browser window
                            popupLeftPos = windowWidth - popupWidth - 15;
                        }
                        if (popupBottomPos > windowHeight)
                        {
                            // the bottom of the popup bubble goes past the browser window
                            popupTopPos = windowHeight - popupHeight - 15;
                        }
                        
                        // hide any prev popup
                        if (adecco.lookingforwidget.currentPopup != null)
                        {
                            adecco.lookingforwidget.currentPopup.css('display', 'none');
                        }
                        adecco.lookingforwidget.currentPopup = popup;
                
                        // reset position of popup box
                        popup.css({
                            position: 'absolute', //'fixed',
                            //Do not need to change position (fixed)
                            top: 22, //popupTopPos,
                            left: 2, //popupLeftPos,
                            display: 'block' // brings the popup back in to view
                        })
                        //popup.slidUp('slow');
                        //$('.looking-for-popup').slideDown('slow');
                        
                        // (we're using chaining on the popup) now animate it's opacity and position
                        .animate({
                            top: '-=' + distance + 'px',
                            opacity: 1
                        }, time, 'swing', function() {
                            // once the animation is complete, set the tracker variables
                            beingShown = false;
                            shown = true;
                        });
                    }, showDelay);
                }
         
            }).mouseout(function() {
                // reset the timer if we get fired again - avoids double animations
                if (hideDelayTimer) clearTimeout(hideDelayTimer);
                if (showDelayTimer) clearTimeout(showDelayTimer);
                
                // store the timer so that it can be cleared in the mouseover if required
                hideDelayTimer = setTimeout(function() {
                    hideDelayTimer = null;
                    try{
                            recentJobsCategoryDropdown.style.visibility = 'visible';
                    }catch(err){}
                    popup.animate({
                        top: '-=' + distance + 'px',
                        opacity: 0
                    }, time, 'swing', function() {
                        // once the animate is complete, set the tracker variables
                        shown = false;
                        // hide the popup entirely after the effect (opacity alone doesn't do the job)
                        popup.css('display', 'none');
                    });
                }, hideDelay);
            });
        });
    },
    
    init: function()
    {    
        adecco.lookingforwidget.initHoverOver();
    }
    
}; // end of adecco.lookingforwidget