﻿/// <reference path="adecco.core.js" />
/// <reference path="json2.js" />
(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,

	PREF_LOCATION_COOKIE_NAME = 'my_location';
    var config = {
        jobTitlesAutocompleteService: '/_layouts/AdeccoGroup/WebParts/JobSearch/services/JobTitles.ashx',
        jobTitlesAutocompleteMinChars: 2,
        locationAutocompleteService: '/_layouts/AdeccoGroup/WebParts/JobSearch/services/locations.ashx',
        jobSearchService: '/_layouts/AdeccoGroup/WebParts/JobSearch/services/JobSearch.ashx',
        roundedCornerRadius: '5px',
        defaultMaxRecentJobs: 10
    };

    adecco.LocationManager = {
        PREF_LOCATION_COOKIE_NAME: 'pref_location',
        _observers: [],

        _notifyLocationChanged: function() {
            var i, observer;
            if (this._observers.length) {
                for (i = 0; i < this._observers.length; i++) {
                    try {
                        observer = this._observers[i];

                        if (typeof (observer.context) === "undefined") {
                            observer.target[observer.callbackName].apply(observer.target);
                        }
                        else {
                            observer.target[observer.callbackName].apply(observer.target, observer.context);
                        }
                    } catch (exception) {
                        log.error(exception);
                    }
                }
            }
        },

        getPreferredLocation: function() {
            return adecco.getCookie(this.PREF_LOCATION_COOKIE_NAME);
        },

        setPreferredLocation: function(value) {
            /// <summary>Sets the preferred location for the current user.</summary>
            adecco.setCookie(this.PREF_LOCATION_COOKIE_NAME, value, 365);
            this._notifyLocationChanged();
        },

        openLocationWindow: function(event) {
            var 
                sender = $(event.target),
                webPart;

            try {

                // bug fix: Ali: don't open if there's already a popup open
                if ($('.pop-over').length > 0) {
                    $('.pop-over').remove();
                }

                // Get the Web Part associated with the current element.
                webPart = sender.parents('.web-part');

                // Get the alignment (currently only implemented for left
                /*
                var leftAligned = (sender.parents('.location-left-align').length > 0) ? true : false;
                var rightAligned = (sender.parents('.location-right-align').length > 0) ? true : false;
                */

                var uiCopy = webPart.find('.set-location-popup').clone();


                // adding a null reference check
                $('input.autocomplete', uiCopy).autocomplete(config.locationAutocompleteService, {
                    minChars: 2,
                    selectFirst: false,
                    extraParams: { clientid: adecco.quicksearch._gsdClientId }
                }).setOptions({
                    resultsClass: 'ac_results location',
                    width: $('input.autocomplete', uiCopy).width()
                });


                $('.job-quick-search').unbind('keypress');

                adecco.showContentInPopover(uiCopy, {
                    x: event.pageX,
                    y: event.pageY,
                    className: 'set-location-popover'
                });

                $('.set-location-popup').keypress(function(event) {
                    if (event.which == '13') {
                        $('input.set-location-button', '.pop-over').click();
                    }
                });
            } finally {
                event.preventDefault();
            }
        },

        addObserver: function(destination, callback, context) {
            this._observers.push({ target: destination, callbackName: callback, context: context });
        }
    };
    adecco.PreferenceManager = {

        isLocalStorageAvailable: function() {
            // Use type coercion to return a boolean.
            return (typeof (window.localStorage) !== 'undefined');
        },

        getPreference: function(name) {
            if (this.isLocalStorageAvailable()) {
                // Read from HTML5 local storage
                return localStorage.getItem(name);
            } else {
                // Read from cookie.
                return adecco.getCookie(name);
            }
        },

        setPreference: function(name, value) {
            log.info('Setting preference "' + name + '": ' + value);

            if (this.isLocalStorageAvailable()) {
                // Store in HTML5 local storage
                localStorage.setItem(name, value);
            } else {
                // Store in cookie.
                adecco.setCookie(name, value);
            }

            return this;
        },

        getPreferenceObject: function(name) {
            var prefValue = this.getPreference(name);

            if (prefValue) {
                return JSON.parse(prefValue);
            }
            return null;
        },

        setPreferenceObject: function(name, value) {
            var valueText = JSON.stringify(value);
            this.setPreference(name, valueText);
        }
    };

    adecco.jobsearch = {

        getFavoriteLocation: function() {
            adecco.PreferenceManager.getPreference('preferred_location');
        },

        setFavoriteLocation: function(value) {
            adecco.PreferenceManager.setPreference('preferred_location', value);
        }
    };

    adecco.jobsearch.SearchManager = {
        SEARCH_CRITERIA_COOKIE_NAME: 'search_criteria',

        saveSearchCriteria: function(searchCriteria) {
            if (typeof (searchCriteria) !== 'string') {
                return;
            }
            var 
                oldSearchCriteriaCookieValue,
                newSearchCriteriaCookieValue,
                allSearchCriteria;

            // Deserialize the cookie value into an array.
            oldSearchCriteriaCookieValue = adecco.getCookie(this.SEARCH_CRITERIA_COOKIE_NAME) || '[]';
            allSearchCriteria = JSON.parse(oldSearchCriteriaCookieValue);
            //Bug 3325: added code to handle case insensitive issue
            allSearchCriteria.push(jQuery.trim(searchCriteria.toLowerCase()));

            allSearchCriteria = jQuery.unique(allSearchCriteria);

            // Serialize the new array back into the cookie.
            newSearchCriteriaCookieValue = JSON.stringify(allSearchCriteria);
            adecco.setCookie(this.SEARCH_CRITERIA_COOKIE_NAME, newSearchCriteriaCookieValue, 365);
        }
    };

    adecco.jobsearch.PagingManager = function() {
        this.DEFAULT_PAGE_SIZE = 10;
        this.numJobsPerPage = 0;
        this._currentPageNumber = 1;
        this.jobs = [];
        this._isInitialized = false;
    }

    adecco.jobsearch.PagingManager.prototype = {

        initialize: function(numberJobsPerPage) {
            if (typeof (numberJobsPerPage) === 'string') {
                numberJobsPerPage = parseInt(numberJobsPerPage);
            }
            if (!this._isInitialized) {
                this._currentPageNumber = 1;
            }
            this.numJobsPerPage = numberJobsPerPage || this.DEFAULT_PAGE_SIZE;
            this._isInitialized = true;

            log.debug('Shortlist Paging Manager is now initialized');
        },

        setJobs: function(jobs) {
            this.jobs = jobs;
        },

        getTotalPageNum: function() {
            var pages = 1;
            if (this._isInitialized) {
                if (this.numJobsPerPage === 0) {
                    throw { message: 'Division by zero' };
                }

                pages = this.jobs.length / this.numJobsPerPage;
                pages = Math.floor(pages);
                if ((this.jobs.length % this.numJobsPerPage) >= 1) {
                    pages++;
                }
            }
            return pages;
        },

        getCurrentPageNumber: function() {
            return this._currentPageNumber;
        },

        setCurrentPageNumber: function(value) {
            this._currentPageNumber = value;
        },

        getPagingContent: function(pageNumber) {
            var pageJobs = [];

            if (this._isInitialized) {
                var maxJobIndex = pageNumber * this.numJobsPerPage;
                var minJobIndex = maxJobIndex - this.numJobsPerPage;
                for (minJobIndex; minJobIndex < maxJobIndex; minJobIndex++) {
                    //alert(minJobIndex + ", " + jobs[minJobIndex]);
                    if (this.jobs[minJobIndex]) {
                        pageJobs.push(this.jobs[minJobIndex]);
                    }
                }
            }
            return pageJobs;
        }
    };

    adecco.jobsearch.ShortListManager = {

        _gsdClientId: '',
        pagingManager: new adecco.jobsearch.PagingManager(),

        initialize: function(config) {
            // GSD Client ID
            if (config.gdsClientId) {
                this._gsdClientId = config.gdsClientId;
            }
        },

        getAllJobs: function() {
            var shortList = adecco.PreferenceManager.getPreferenceObject('jobsearch_shortlist') || [];

            return shortList;
        },

        isShortListed: function(jobId, jobCollection) {
            var 
            jobList = jobCollection || this.getAllJobs(),
            i;

            for (i = 0; i < jobList.length; i++) {
                if (jobList[i] === jobId) {
                    return true;
                }
            }
            return false;
        },

        addJob: function(jobId) {
            log.debug('Adding job to shortlist (' + jobId + ')');

            var shortList = this.getAllJobs();
            if (this.isShortListed(jobId, shortList)) {
                return;
            }

            shortList.push(jobId);
            adecco.PreferenceManager.setPreferenceObject('jobsearch_shortlist', shortList);
            if ($(".isShortListOnPage").val() == "true") {
                refreshSLMenuItem();
            }
        },

        removeJob: function(jobId) {
            log.debug('Removing job from shortlist (' + jobId + ')');

            var shortList = this.getAllJobs(), i, index;
            if (!this.isShortListed(jobId, shortList)) {
                return;
            }

            index = -1;
            for (i = 0; i < shortList.length; i++) {
                if (shortList[i] === jobId) {
                    index = i;
                    break;
                }
            }

            if (index >= 0) {
                shortList.splice(index, 1);
                adecco.PreferenceManager.setPreferenceObject('jobsearch_shortlist', shortList);
                if ($(".isShortListOnPage").val() == "true") {
                    refreshSLMenuItem();
                }
            }
        },

        clearShortList: function() {
            var resourceStrings = adecco.jobsearch.resourceStrings;
            if (confirm(resourceStrings['ShortList_ConfirmMSG'])) {
                adecco.PreferenceManager.setPreferenceObject('jobsearch_shortlist', "");

                // Update the star status on the jobs currently displayed.
                if (adecco.jobsearch.resultsController) {
                    adecco.jobsearch.resultsController._view.setNeedsDisplay();
                }

                this.refreshShortList();
            }
        },

        //Added by CandidatePortal on 12/07/2011
        clearFavoriteList: function() {
            var resourceStrings = adecco.jobsearch.resourceStrings;
            adecco.PreferenceManager.setPreferenceObject('jobsearch_shortlist', "");
            // Update the star status on the jobs currently displayed.
            if (adecco.jobsearch.resultsController) {
                adecco.jobsearch.resultsController._view.setNeedsDisplay();
                this.refreshShortList();
            }
        },

        //End by CandidatePortal

        refreshShortList: function() {
            //debugger;
            var that = this;

            refreshSLMenuItem();
            if ($(".pop-over").length > 0) {
                $(".pop-over").remove();
            }

            this.pagingManager.initialize($(".slPageSize").val());

            // Display the popover with a spinner inside while loading the ShortList data/content.
            var spinnerView = $('<div />')
                .addClass('spinner-view');

            adecco.showContentInPopover(spinnerView, {
                x: $(".ShortList").position().left + ($(".ShortList").width() / 2),
                y: $(".ShortList").position().top + 30,
                className: "shortlist-manager"
            });

            this.getShortListData(function(data) {
                var totalPageNumshor, tListView;

                // Set the data returned from the service as the list of short-listed jobs.
                that.pagingManager.setJobs(data);

                // Compute the current page index.
                totalPageNum = that.pagingManager.getTotalPageNum();
                if (that.pagingManager.getCurrentPageNumber() > totalPageNum) {
                    that.pagingManager.setCurrentPageNumber(totalPageNum);
                }

                // Get the ShortList View for that list.
                shortListView = that.getShortListView(data);
                while (shortListView.indexOf('</div>,<div') != '-1') {
                    shortListView = shortListView.replace('</div>,<div', '</div><div');
                    shortListView = shortListView.replace('</div>_<div', '</div><div');
                }


                // Display the view in a content popover.
                adecco.showContentInPopover(shortListView, {
                    x: $(".ShortList").position().left + ($(".ShortList").width() / 2),
                    y: $(".ShortList").position().top + 30,
                    className: "shortlist-manager"
                });
            });
        },

        toggleShortList: function() {
            //debugger;
            if ($(".pop-over").length > 0) {
                $(".pop-over").fadeOut(400, function() { $(".pop-over").remove(); });
            } else {
                this.refreshShortList();
            }
        },


        getShortListData: function(callback) {
            
            var 
                allJobs,
                communicationException,
                that = this;

            allJobs = this.getAllJobs();
            if (allJobs && allJobs.length > 0) {
                $.ajax({
                    type: "GET",
                    url: "/_layouts/AdeccoGroup/WebParts/JobSearch/services/ShortListDetails.ashx",
                    dataType: 'json',
                    data: 'clientid=' + $('#jobresult-part-clientid').val() +
                            '&shrtlst=' + allJobs,
                    cache: true,
                    success: function(result) {
                        if (callback) {
                            callback(result);
                        }
                    },
                    error: function(eventArg) {
                        communicationException = { message: 'Communication error', data: eventArg };
                        throw communicationException;
                    }
                });
            } else {
                callback([]);
            }
        },

        getPagingHtml: function() {
            //debugger;
            var totalPages = this.pagingManager.getTotalPageNum();
            var currPage = this.pagingManager.getCurrentPageNumber();
            var totalDisplay = 5;

            var firstPage = (currPage > 2) ? currPage - 2 : 1;
            var lastPage = (firstPage + 4 >= totalPages) ? totalPages : firstPage + 4;

            // Bug ID : #DE2070 Closed On : 07th-june-2011 Remarks: Added cellpadding='4' and Space on anchor.
            //Bug ID : #DE2486 Closed On : Aug 04,2011 Remarks : Added currPage check to hide paging if no results
            var result = '';
            if (totalPages > 1) {
                var result = "<table style='width:auto' cellspacing='5' cellpadding='4'><tr>";
                if (currPage != 1) { result += "<td style='text-align: left'><a href='javascript:adecco.jobsearch.ShortListManager.previousPage();'>Prev</a></td>"; } else { result += "<td>Prev</td>"; }
                for (firstPage; firstPage <= lastPage; firstPage++) {
                    if (firstPage == currPage) {
                        result += "<td style='font-weight:bold;'>&nbsp<a href='javascript:adecco.jobsearch.ShortListManager.displayPage(" + firstPage + ")'>" + firstPage + "</a></td>";
                    }
                    else {
                        result += "<td>&nbsp<a href='javascript:adecco.jobsearch.ShortListManager.displayPage(" + firstPage + ")'>" + firstPage + "</a></td>";
                    }
                }
                if (currPage != lastPage) { result += "<td style='text-align:right'>&nbsp<a href='javascript:adecco.jobsearch.ShortListManager.nextPage();'>Next</a></td>"; } else { result += "<td>&nbspNext</td>"; }
                result += "</tr></table>";
            }
            return result;
        },

        getShortListView: function(data) {
            //debugger;
            var 
                data = data || [],
                resourceStrings = adecco.jobsearch.resourceStrings,
                pageNum,
                pagedJobs;

            var controls = "<div class='controls' sizcache='1' sizset='2'>" +
                            '<ul sizcache="1" sizset="2"><li class="jsSprite delete">' +
                            "<a href=\"javascript:adecco.jobsearch.ShortListManager.deleteShortList('%(Id)s');\">" +
                            "<img alt='' src='/_layouts/AdeccoGroup/WebParts/JobSearch/images/blank.gif' />" +
                            "</a></li><LI class='jsSprite email' style='padding:0px;' sizcache='0' sizset='3'>" +
            //Bug ID : #DE2954 Closed On : 15th-August-2011 Remarks: Added shareJobUrl on link.
                           "<a href='%(shareJobUrl)s' onclick='$(this).modal({width:560, height:360}).open(); return false;'>" +
            // "<a href='/Pages/results.aspx?id=%(Id)s'>" +
                            '<img alt="" src="/_layouts/AdeccoGroup/WebParts/JobSearch/images/blank.gif" />' +
                            '</a></li><li class="details" sizcache="0" sizset="4">' +
                            '<a href="%(JobDetailsUrl)s" target="%(target)s">%(text_fullInfo)s &gt;&gt;</a></li></ul></div>';

            var template = [];
            template.push('<div class="ms-WPBody" style="width:400px; text-align:left">');
            template.push('<div class="job-entry">');
            template.push('<div><a class="job-title" href="%(JobDetailsUrl)s" target="%(target)s">');
            template.push('%(Title)s&nbsp;<span style="font-size: smaller; font-weight:normal"><span style="font-style:italic">in</span> %(City)s</span>');
            template.push('</a>');
            //template.push('<div class="job-descr" style="margin-top: 8px;">%(Jobreference)s</div>');
            template.push('<div class="job-descrs">%(Description)s</div>');
            template.push(controls);
            template.push('</div></div></div>');
            var templateString = template.join('');

            var shortListView = [];
            var resourceStrings = adecco.jobsearch.resourceStrings;

            if (data.length > 0) {
                pageNum = this.pagingManager.getCurrentPageNumber();

                //Bug ID : #DE2062 Closed On : 06th-June-2011 Remarks: added default value for Page Number if it is Zero or Null.
                if (pageNum == 0) {
                    pageNum = 1;
                }

                pagedJobs = this.pagingManager.getPagingContent(pageNum);

                // Render each job
                $.each(pagedJobs, function(key, item) {
                    var individualJobView = '';
                    var descriptionvalues = '';
                    //var jobreference = ' ';
                    var finaldescription = ' ';

                    if (item != null) {

                        //jobreference = item.Description.substring(0, 42);
                        descriptionvalues = item.Description.substring(0, 334);
                        ///(<br ?\/?>)*/g, ""
                        // /(<([^>]+)>)/ig, ""
                        finaldescription = descriptionvalues.replace(/(<br ?\/?>)*/g, "")



                        individualJobView = $.sprintf(templateString, {
                            'Id': item.Id,
                            'Title': item.Title,
                            //'Jobreference': jobreference,
                            'Description': finaldescription,
                            'State': (item.Address.ProvinceOrState != null && item.Address.ProvinceOrState != "") ? ", " + item.Address.ProvinceOrState : "",
                            'City': item.Address.City,
                            'JobDetailsUrl': adecco.jobsearch.resultsController.getJobDetailsUrl(item),
                            //Bug ID : #DE2954 Closed On : 15th-August-2011 Remarks: Added shareJobUrl on link.
                            'shareJobUrl': adecco.jobsearch.resultsController.getShareJobUrl(item),
                            'text_fullInfo': $("#fullInfoText").val(),
                            'target': $("#jobdetailstarget").val()
                        });
                    }

                    shortListView.push(individualJobView);
                });
            }
            else {
                shortListView.push('<div class="ms-WPBody">The short list is empty</div>');
            }
            var shorListWrapper = [];

            shorListWrapper.push('<table class ="ms-WPBody"><tr><td>');

            if (data.length > 0) { // Bug ID : #DE2488 Closed On : 03-Aug-2011 Remarks:Render "Clear All" only if there are records.
                // Add "Clear all" button
                shorListWrapper.push('<div class="jsSprite delete" style="width:100%;">');
                shorListWrapper.push('<a href="javascript:adecco.jobsearch.ShortListManager.clearShortList();">');
                shorListWrapper.push('<img alt="" src="/_layouts/AdeccoGroup/WebParts/JobSearch/images/blank.gif"/>');
                shorListWrapper.push('<span>');
                shorListWrapper.push(resourceStrings['ShortList_ClearALL']);
                shorListWrapper.push('</span></a></div>');
            }

            shorListWrapper.push("</td><td><div class='shortlistsprite close' style='text-align: right;' onClick='javascript:adecco.jobsearch.ShortListManager.toggleShortList();'>");
            shorListWrapper.push('<img alt="" src="/_layouts/AdeccoGroup/WebParts/JobSearch/images/blank.gif" />');
            shorListWrapper.push('</div></td></tr></table>');
            shorListWrapper.push(shortListView);
            shorListWrapper.push('<div class ="ms-WPBody paging-ShortList" style="font-size:small; text-align=center">');
            shorListWrapper.push(this.getPagingHtml());
            shorListWrapper.push('</div>');

            return shorListWrapper.join('');
        },

        displayPage: function(pageNumber) {
            this.pagingManager.setCurrentPageNumber(pageNumber);
            this.refreshShortList();
        },

        nextPage: function() {
            this.pagingManager.setCurrentPageNumber(this.pagingManager.getCurrentPageNumber() + 1);
            this.refreshShortList();
        },

        previousPage: function() {
            this.pagingManager.setCurrentPageNumber(this.pagingManager.getCurrentPageNumber() - 1);
            this.refreshShortList();
        },

        deleteShortList: function(jobId) {
            var shortList = this.getAllJobs();
            var index = -1;
            for (i = 0; i < shortList.length; i++) {
                if (shortList[i] == jobId) {
                    index = i;
                    break;
                }
            }

            if (index >= 0) {
                shortList.splice(index, 1);
                adecco.PreferenceManager.setPreferenceObject('jobsearch_shortlist', shortList);
            }

            // Update the star status on the jobs currently displayed.
            if (adecco.jobsearch.resultsController) {
                adecco.jobsearch.resultsController._view.setNeedsDisplay();
            }

            this.refreshShortList();
        }
    };

    adecco.quicksearch = {
        _gsdClientId: '',
        _resultsPage: '',

        _jobCategories: {
            gsdClientId: '',
            jobResultsUrl: '',
            seeAllUrl: '',
            maxRecentJobs: config.defaultMaxRecentJobs,
            titleText: '',
            recentJobsCountText: 'recent jbos in'
        },

        initialize: function(config) {
            // GSD Client ID
            if (config.gdsClientId) {
                this._gsdClientId = config.gdsClientId;
            }

            // Results Page
            if (config.resultsPage) {
                this._resultsPage = config.resultsPage;
            }

        },

        initializeJobCategories: function(config) {
            // GSD Client ID
            if (config.gdsClientId) {
                this._jobCategories.gsdClientId = config.gdsClientId;
            }

            // Max number of results
            if (config.maxRecentJobs) {
                this._jobCategories.maxRecentJobs = config.maxRecentJobs;
            }

            // Search Results URL
            if (config.jobResultsUrl) {
                this._jobCategories.jobResultsUrl = config.jobResultsUrl;
            }

            // See All URL
            if (config.seeAllUrl) {
                this._jobCategories.seeAllUrl = config.seeAllUrl;
            }

            // Title
            if (config.titleText) {
                this._jobCategories.titleText = config.titleText;
            }

            // "x recent jobs in [category]" text
            if (config.recentJobsCountText) {
                this._jobCategories.recentJobsCountText = config.recentJobsCountText;
            }
        },

        trim: function(str) {

            str = str.replace(/^\s+/, '');
            for (var i = str.length - 1; i >= 0; i--) {
                if (/\S/.test(str.charAt(i))) {
                    str = str.substring(0, i + 1);
                    break;
                }
            }

            return str;
        },

        openResultsPage: function() {

            var qry = '', rgn = '', rawKeywords = '', kws = '';
            var placeHolderValue = $('input[name$="txtKeyword"]').attr('placeholder');

            //Check if Search keyword textbox contains only placeholder text
            if (placeHolderValue != $('input[name$="txtKeyword"]').val()) {
                rawKeywords = $('input[name$="txtKeyword"]').val();
            }

            myLoc = adecco.LocationManager.getPreferredLocation();
            kws = encodeURIComponent($.trim(rawKeywords)).replace(/%20/g, '+');

            qry += '?kws=' + kws;
            if (myLoc.length > 0) {
                var loc = adecco.quicksearch.htmlDecode($('#myLocation').html()).split(',');
                qry += '&cty=' + encodeURIComponent($.trim(loc[0])).replace(/\s/g, '+');

                if (loc.length > 1) {
                    qry += '&reg=' + encodeURIComponent($.trim(loc[1])).replace(/\s/g, '+');
                }
            }

            adecco.jobsearch.SearchManager.saveSearchCriteria(rawKeywords);

            // Initialize the page to the following URL
            //            var targetlocation = this._resultsPage + qry;

            //            // There is some error in IE where HTML entities get encoded for the URL
            //            // this catch will only resolve the one case where &reg will be converted
            //            if (navigator.userAgent.search(/MSIE/i) >= 0) {
            //                document.location.href = targetlocation.replace('&reg=', '&amp;reg=');
            //            }
            //            else {
            //                document.location.href = targetlocation;
            //            }
            return true;
        },

        openResultsPageQuick: function() {
            var 
                qry = '',
                rgn = '',
                rawKeywords = $('#job-search-short').hasClass('placeholder') ? '' : $('#job-search-short').val(),
                kws = '',
            //myLoc = $('#myLocation').html(),
                myLoc = adecco.LocationManager.getPreferredLocation(),
                rememberSearchCheckbox = $('input[name="remember-search"]');

            kws = encodeURIComponent($.trim(rawKeywords)).replace(/%20/g, '+');

            qry += '?kws=' + kws;
            if (myLoc.length > 0) {
                var loc = adecco.quicksearch.htmlDecode($('#myLocation').html()).split(',');
                qry += '&cty=' + encodeURIComponent($.trim(loc[0])).replace(/\s/g, '+');

                if (loc.length > 1) {
                    qry += '&reg=' + encodeURIComponent($.trim(loc[1])).replace(/\s/g, '+');
                }
            }

            // "Remember My Search"
            if (rememberSearchCheckbox.is(':checked')) {
                log.debug('Remembering the search criteria "' + rawKeywords + '".');

                adecco.jobsearch.SearchManager.saveSearchCriteria(rawKeywords);
            }

            var targetlocation = this._resultsPage + qry;

            if (navigator.userAgent.search(/MSIE/i) >= 0) {
                document.location.href = targetlocation.replace('&reg=', '&amp;reg=');
            }
            else {
                document.location.href = targetlocation;
            }
            return true;
        },


        updateLocation: function(txtLocation) {
            var location, cty, reg;
            var locationUrl = "";

            // Update the Set My Location Link with the new location text
            $('.location-value').html(txtLocation);

            // Construct the new location parameters for the new URL
            location = $.trim(txtLocation).split(',');
            if (location[0] != "") {
                if (location.length === 1) {
                    locationUrl += 'cty=' + $.trim(location[0]);
                }
                else if (location.length === 2) {
                    locationUrl += 'cty=' + $.trim(location[0]) + '&reg=' + $.trim(location[1]);
                }
                ///Bug ID : #DE2057; Remarks: the call to 
                // Update the Categories Links placed inside if condition to prevent appending &, if the user clicks set Location button with empty text in popup
                this.updateLinks(".category-name a", locationUrl);
                // Update the "See All" Link
                this.updateLinks(".see-all a", locationUrl);
            }
        },

        updateLinks: function(element, locationUrl) {
            var href, hrefSplit, params, baseUrl, newUrl,
				pairs, keyValue;

            // Iterate over all specified links and update their URLs
            $(element).each(function(index) {
                href = $(this).attr('href');
                hrefSplit = href.split('?');
                baseUrl = hrefSplit[0];

                newUrl = baseUrl + '?';

                // Add existing parameters (not cty or reg) from old URL to new URL.
                if (hrefSplit.length > 1) {
                    params = hrefSplit[1];
                    pairs = params.split('&');

                    for (var i = 0; i < pairs.length; i++) {
                        keyValue = pairs[i].split('=');
                        if (keyValue[0] !== "cty" && keyValue[0] !== "reg") {
                            newUrl += pairs[i] + '&';
                        }
                    }
                }

                newUrl += locationUrl;
                $(this).attr("href", newUrl)
            });
        },

        onLocationUpdated: function() {
            this.updateLocation(adecco.LocationManager.getPreferredLocation());
        },


        htmlEncode: function(value) {
            return $('<div/>').text(value).html();
        },

        htmlDecode: function(value) {
            return $('<div/>').html(value).text();
        },

        onSetLocationClicked: function(source, setMyLocationText) {

            var 
            locationFlyout = $(source).parents('.set-location-popup')[0],
            locationTextbox = $('input[type="text"]', locationFlyout);

            var location = $.trim(locationTextbox.val());
            $('.ac_results').hide();

            // If textbox is empty, reset the cookie and remove location
            if (location == "") {
                adecco.LocationManager.setPreferredLocation("");
                $('.location-value').html(setMyLocationText);
                // Close the popup
                $(locationFlyout).parents('.pop-over').remove();
                return;
            }

            // Update the Preferred Location
            if (locationTextbox.length) {
                adecco.LocationManager.setPreferredLocation(adecco.quicksearch.htmlEncode(location));
            }

            // Close the popup
            $(locationFlyout).parents('.pop-over').remove();

            //Bug ID : #DE2057; Remarks:if All Categories is not selected then update the jobs for recent location and already selected category.
            //            if ($('.category-selector').get(0).selectedIndex > 0) {
            //                adecco.quicksearch.onRecentJobsCategoryChanged($('.category-selector'));
            //            }
        },

        onRecentJobsCategoryChanged: function(source) {

            var categoryId = $(source).val(),
                webPart = $(source).parents('.web-part')[0],
                searchServiceParams,
                location,
                that = this;
            var locationUrl = "";

            // Hide the "no jobs found" and "error" divs
            $(webPart).find('.not-found').hide();
            $(webPart).find('.error').hide();

            // Construct the new location parameters for the new URL
            location = $.trim(adecco.LocationManager.getPreferredLocation()).split(',');
            if (location[0] != "") {
                if (location.length === 1) {
                    locationUrl += 'cty=' + $.trim(location[0]);
                }
                else if (location.length === 2) {
                    locationUrl += 'cty=' + $.trim(location[0]) + '&reg=' + $.trim(location[1]);
                }
            }

            if (categoryId === '') {
                // "All Categories" selected
                $('.see-all a', webPart).attr('href', this._jobCategories.seeAllUrl);
                log.info('User selected "All Categories');

                // Update the "See All" Link
                this.updateLinks(".see-all a", locationUrl);

                // Set the title back to its normal text.
                $('.job-category-title', webPart).text(this._jobCategories.titleText);

                $('.recent-jobs', webPart).hide();
                $('.category-list', webPart).show();
            } else {
                // Specific category selected.
                log.info('User selected Job Category "' + categoryId + '"');

                // TODO: Display a loading spinner.

                //location = adecco.LocationManager.getPreferredLocation().split(',');
                searchServiceParams = {
                    cat: categoryId,
                    clientid: this._jobCategories.gsdClientId,
                    psz: this._jobCategories.maxRecentJobs,
                    cty: $.trim(location[0]),
                    reg: $.trim(location[1]),
                    rds: $("#searchDistanceRadius").val()
                };

                $.ajax({
                    url: config.jobSearchService,
                    data: searchServiceParams,
                    dataType: "json",
                    success: function(data) {
                        var titleText,
						jobListView, i, jobItem, jobItemView,
						locationText, recentJobsContainer,
						seeAllUrl;

                        // Set the number of jobs in the title.
                        titleText = data.TotalNumberOfResults + ' ' + that._jobCategories.recentJobsCountText;
                        $('.job-category-title', webPart).text(titleText);

                        // Show the "no jobs found"
                        if (data.Results.length === 0) {
                            $(webPart).find('.not-found').fadeIn();
                        }

                        jobListView = $('<ul/>');
                        // Add jobs to the list.
                        for (i = 0; i < data.Results.length; i++) {
                            jobItem = data.Results[i];
                            jobItemView = $('<li><a href="' +
                            //jobItem.URI +
							$("#jobdetailspageurl").val() + '?job-id=' + jobItem.Id +
							'">' + jobItem.Title + '</a></li>');

                            // Add job location info.
                            try {
                                locationText = jobItem.Address.City;

                                if (jobItem.Address.ProvinceOrState) {
                                    locationText += ', ' + jobItem.Address.ProvinceOrState;
                                }
                            } catch (ex) {
                                locationText = '';
                            }

                            $('<div/>')
                            .addClass('job-location')
                            .text(locationText)
                            .appendTo(jobItemView);

                            // Finally, append the job view to the list.
                            jobItemView.appendTo(jobListView);
                        }

                        // Set the list as the content of the "recent jobs" container.
                        recentJobsContainer = $('.recent-jobs', webPart);
                        recentJobsContainer.html(jobListView);

                        $('.category-list', webPart).hide();
                        recentJobsContainer.show();
                    },
                    error: function() {
                        $('.category-list', webPart).hide();
                        $(webPart).find('.error').fadeIn();
                    }
                });

                // Update "See All" link.
                seeAllUrl = that._jobCategories.jobResultsUrl;
                seeAllUrl += '?cat=' + categoryId;

                // Add location information if available from cookie
                if (location[0] != "") {
                    if (location.length === 1) {
                        seeAllUrl += '&cty=' + $.trim(location[0]);
                    }
                    else if (location.length === 2) {
                        seeAllUrl += '&cty=' + $.trim(location[0]) + '&reg=' + $.trim(location[1]);
                    }
                }

                $('.see-all a', webPart).attr('href', seeAllUrl);
            }
        },

        //Updated pageDidFinishLoading to accept JSON object to implement autocomplete for multiple controls on a page.
        //Each control might have it's own Service URL
        //Dev: Vinay Rohlan
        //Bug #2067
        //Date: 30-May-2011
        pageDidFinishLoading: function(config) {
            // Setup autocomplete

            if ($.fn.autocomplete) {
                //if config is an object [JSON object]
                if (typeof config == "object")// dynamically set Service URL for corresponding control ids in JSON object
                {
                    for (var i = 0; i < config.controls.length; i++) {
                        $("#" + config.controls[i].elementId).autocomplete(config.controls[i].serviceURL, {

                            minChars: 2,

                            selectFirst: false,

                            extraParams: { clientid: adecco.quicksearch._gsdClientId }

                        }
                         );
                    }
                }
                else // Old code which registered autocomplete on all input controls having class='autocomplete'
                {
                    $('input.autocomplete').autocomplete('/_layouts/AdeccoGroup/WebParts/JobSearch/services/JobTitles.ashx', {
                        minChars: 2,
                        selectFirst: false,
                        extraParams: { clientid: adecco.quicksearch._gsdClientId }
                    }
                );
                }
            }


            // Setup placeholders for all browsers
            if ($.fn.placeholder) {
                $('input[placeholder], textarea[placeholder]').placeholder();
            }

            // Register event handler for the "Change Location" links.
            $('.change-location').click(function(e) {
                adecco.LocationManager.openLocationWindow(e);
                setTimeout(function() {
                    $('.set-location-popover .textbox').focus();
                }, 500);
            });

            // Register event handler(s) when the preferred location changes.
            adecco.LocationManager.addObserver(adecco.quicksearch, 'onLocationUpdated');

            // Close Set My Location popup if user clicks anywhere outside of popup

            //            $(document).click(function(event) {
            //                var sender = $(event.target);
            //                $('.ac_results').hide();

            //                if (!sender.hasClass("change-location") && !sender.hasClass(".pop-over")) {
            //                    $('.pop-over').remove();
            //                }
            //            });

            $(document).ready(function() {

                // Set the location when enter is pressed
                $('#job-search-short').keypress(function(event) {
                    if (event.which == '13') {
                        $('input.search').click();
                    }
                });

            });

        },

        showPopUp: function(e) {
            if (!e) {
                e = window.event;
            }

            e.cancelBubble = true;

            if (e.stopPropagation) {
                e.stopPropagation();
            }

            return true;
        },

        closePopup: function() {
            $('.ac_results').hide();
            $('.pop-over').remove();
        }
    };

    // Random test functions.
    function showFavLoc() {
        alert(adecco.LocationManager.getPreferredLocation());
    }

    function setFavLoc() {
        var txtBox = document.getElementById('fave_loc');

        adecco.LocationManager.setPreferredLocation(txtBox.value);

        return false;
    }

    // DOM-load complete events
    $(function() {

        // Enable rounded corners
        if (typeof ($.fn.corner) !== 'undefined') {
            $('.rounded-corners').corner(config.roundedCornerRadius);
        }
    });
})(jQuery);

// TODO: Delete this function
function getJobHtml(item, template) {
}

function pageLoad() {
    refreshSLMenuItem();
    adecco.jobsearch.ShortListManager.pagingManager.initialize($(".slPageSize").val());
    $("<input type='hidden' name='shortlist' value='true' class='isShortListOnPage' />").appendTo("body");
}

//Bug DE2177:Closed On 19/July:Dev:Vinay/Pooja
//Remarks:Function to display message for more than 19 characters  & append it to Textbox div class to accomodate in all zones
function VerifySearchLen(obj) {

    var flag = true;
    var flagerror = false;
    var delimitedString;
    var hasSpace = false;
    var hasLocSpace = false;
    var validSpace = true;
    var validLocSpace = true;

    var keyword = document.getElementById(obj.controlIds[0].id).value;
    var location = document.getElementById(obj.controlIds[1].id).value;

    var elMessageDiv = document.getElementById('qsErrorMessageDiv');
    var elLocMessageDiv = document.getElementById('qsErrorMessageDivLoc');


    //Check if keyword and location have seperator "," , ";" or space
    if (keyword.indexOf(" ") != -1) {
        hasSpace = true;

    }
//    if (hasSpace) {

//        validSpace = validateInputLength(' ', keyword);


//        if (!validSpace) {

//            //var elMessageDiv = document.getElementById('qsErrorMessageDiv');
//            if (elMessageDiv == null && typeof elMessageDiv != 'undefined') {
//                elMessageDiv = document.createElement('DIV');
//                elMessageDiv.setAttribute('id', 'qsErrorMessageDiv');
//                elMessageDiv.className = 'Display-Message';
//                var ElementDiv = document.getElementById(obj.controlIds[0].id).parentNode.parentNode;
//                ElementDiv.appendChild(elMessageDiv);
//            }
//            elMessageDiv.innerHTML = obj.errorMessage;


//            flag = false;
//        }
//        else {

//            if (elMessageDiv != null || typeof elMessageDiv != 'undefined') {
//                try {

//                    elMessageDiv.innerHTML = "";
//                }
//                catch (e) {

//                }
//                //elMessageDiv.style.display = "none";
//            }

//        }
//    }

//    else {
//        if (keyword.length > 14) {



//            if (elMessageDiv == null && typeof elMessageDiv != 'undefined') {
//                elMessageDiv = document.createElement('DIV');
//                elMessageDiv.setAttribute('id', 'qsErrorMessageDiv');
//                elMessageDiv.className = 'Display-Message';
//                var ElementDiv = document.getElementById(obj.controlIds[0].id).parentNode.parentNode;
//                ElementDiv.appendChild(elMessageDiv);

//            }
//            elMessageDiv.innerHTML = obj.errorMessage;
//            flag = false;
//        }
//        else {

//            if (elMessageDiv != null || typeof elMessageDiv != 'undefined') {
//                try {

//                    elMessageDiv.innerHTML = "";
//                    //elMessageDiv.style.display = "none";
//                }
//                catch (e) {


//                }
//            }

//        }

//    }

    //For Location keyword
    if (location.indexOf(" ") != -1) {
        hasLocSpace = true;

    }

    if (hasLocSpace) {

        validLocSpace = validateInputLength(' ', location);

        if (validLocSpace == false) {

            //var elLocMessageDiv = document.getElementById('qsErrorMessageDivLoc');
            if (elLocMessageDiv == null && typeof elLocMessageDiv != 'undefined') {
                elLocMessageDiv = document.createElement('DIV');
                elLocMessageDiv.setAttribute('id', 'qsErrorMessageDivLoc');
                elLocMessageDiv.className = 'Display-Message';
                var ElementDiv = document.getElementById(obj.controlIds[1].id).parentNode.parentNode;
                ElementDiv.appendChild(elLocMessageDiv);
            }
            elLocMessageDiv.innerHTML = obj.errorMessage;
            flag = false;
        }
        else {
            if (elLocMessageDiv != null && typeof elLocMessageDiv != 'undefined') {
                try {
                    elLocMessageDiv.innerHTML = "";
                }
                catch (e) {
                }
            }
        }

    }

    else {
        if (location.length > 14) {


            //var elLocMessageDiv = document.getElementById('qsErrorMessageDivLoc');
            if (elLocMessageDiv == null && typeof elLocMessageDiv != 'undefined') {

                elLocMessageDiv = document.createElement('DIV');
                elLocMessageDiv.setAttribute('id', 'qsErrorMessageDivLoc');
                elLocMessageDiv.className = 'Display-Message';
                var ElementDiv = document.getElementById(obj.controlIds[1].id).parentNode.parentNode;
                ElementDiv.appendChild(elLocMessageDiv);
            }
            elLocMessageDiv.innerHTML = obj.errorMessage;
            flag = false;
        }
        else {
            if (elLocMessageDiv != null && typeof elLocMessageDiv != 'undefined') {
                try {

                    elLocMessageDiv.innerHTML = "";
                }
                catch (e) {
                }
            }
        }
    }




    return flag;

    return valid;
}



function validateInputLength(seperator, keyword) {
    var valid = true;
    var splittedKeyword = keyword.split(seperator);
    if (splittedKeyword.length == 1) {
        if (splittedKeyword[0].length > 14) {
            valid = false;

        }
    }
    else {
        for (var counter = 0; counter < splittedKeyword.length; counter++) {
            delimitedString = splittedKeyword[counter];
            if (delimitedString.length > 14) {
                valid = false;
                break;
            }
        }
    }

    return valid;
}

function refreshSLMenuItem() {
    var 
        shortListMenuItem = $(".ShortList span"),
        currentText = shortListMenuItem.text(),
        shortList = [],
        numberOfJobs;

    shortList = adecco.jobsearch.ShortListManager.getAllJobs();
    numberOfJobs = shortList.length;
    shortListMenuItem.text(currentText.split(' (')[0] + ' (' + numberOfJobs + ')');
}

$(document).ready(function() {

    $elTextLocation = $('input[id$=\"txtLocation\"]');
    setTimeout(SwitchSliderViews, 15); //call function after interval of 15 ms as certain other scripts in JS file are called after 5 ms of document ready that append elements in slider.
    $elTextLocation.blur(SwitchSliderViews); // add blur handler
});

$(document).ready(function() {

    if (document.getElementById('AdvDistanceSliderHandle')) {

        document.cookie = "distSliderReset=0";

        $elTextLocation = $('input[id$=\"txtLocation\"]');
        setTimeout(SwitchSliderViews, 15); //call function after interval of 15 ms as certain other scripts in JS file are called after 5 ms of document ready that append elements in slider.
        $elTextLocation.blur(SwitchSliderViews); // add blur handler
    }

});

function SwitchSliderViews() {

    // enable/disable slider depending on the value of location textbox
    if ($elTextLocation.val() != null || typeof($elTextLocation.val()) != 'undefined') {
        if ($elTextLocation.val().length == 0 || $elTextLocation.val() == $elTextLocation.attr('placeholder')) {
            document.cookie = "distSliderReset=1";
            
                $("#AdvDistanceSliderHandle").slider("option", "disabled", true);
           
        }
        else {
            document.cookie = "distSliderReset=0";
          
                $("#AdvDistanceSliderHandle").slider("option", "disabled", false);
          

        }
    }
}


//added code for delete cookies on advance search button click

$(document).ready(function() {

    $('input[id$=\"SearchButtonID\"]').click(function() {
        getSliderVariable();
        ClearRangeCookies();
    });

});

function ClearRangeCookies() {
    var dats = new Date();
    dats.setTime(dats.getTime() - (1 * 1 * 60 * 60 * 1000 + 29000 - 3600000 + 1990000));
    var expires = '; expires=' + dats.toUTCString();
    var path = ';path=/';
    document.cookie = 'yexpRange=0' + expires + path;
    document.cookie = 'distRange=0' + expires + path;
    document.cookie = 'postedageRange=0' + expires + path;
}

function ClearDroDwonCookies() {
    var dats = new Date();
    dats.setTime(dats.getTime() - (1 * 1 * 60 * 60 * 1000 + 29000 - 3600000 + 1990000));
    var expires = '; expires=' + dats.toUTCString();
    var path = ';path=/';
    document.cookie = 'sft=0' + expires + path;
    document.cookie = 'ctp=0' + expires + path;
    document.cookie = 'ind=0' + expires + path;
    document.cookie = 'edu=0' + expires + path;
    document.cookie = 'ctr=0' + expires + path;
    document.cookie = 'cat=0' + expires + path;
    
}

function getSliderVariable() {

    var valueDistance = $("#AdvDistanceSliderHandle").slider("option", "values");
    var MaxDistanceValue = $("#AdvDistanceSliderHandle").slider("option", "max");

    ManageControlCookies(valueDistance, "dist",MaxDistanceValue);

    var valueDatePost = $(".date-posted.slider").slider("option", "values");
    var MaxDatePostValue = $(".date-posted.slider").slider("option", "max");

    ManageControlCookies(valueDatePost, "postedage",MaxDatePostValue);

    var valueYearPosted = $(".Years-posted.slider").slider("option", "values");
    var MaxYearPostedValue = $(".Years-posted.slider").slider("option", "max");

    ManageControlCookies(valueYearPosted, "yexp",MaxYearPostedValue);


    var valueContractType = $("#advddlShift").val();
    ManageDropDwnCookies(valueContractType, "sft");


    var valueContractType = $("#advddlContractType").val();
    ManageDropDwnCookies(valueContractType, "ctp");

    var valueContractType = $("#advddlIndustry").val();
    ManageDropDwnCookies(valueContractType, "ind");

    var valueContractType = $("#advddlEducationLevel").val();
    ManageDropDwnCookies(valueContractType, "edu");


    var valueContractType = $("#advddlCountry").val();
    ManageDropDwnCookies(valueContractType, "ctr");

    var valueContractType = $("#advddlJobCategory").val();
    ManageDropDwnCookies(valueContractType, "cat");


}



function ManageControlCookies(cntName, QueryStringParam,maxValue) {
    //debugger;

    if (typeof (cntName) !== 'undefined') {

        if (cntName.length > 0) {
            //if (cntName[0] > 0) {
            if (cntName[0] > 0 && cntName[0]<maxValue) {
                var fromValue = cntName[0];
                SetCntCookies(QueryStringParam, fromValue);
            }
            else {
                ExpireCookies(QueryStringParam, 0)
            }
        }
        else {
            ExpireCookies(QueryStringParam, 0)
        }
    }

}


function ManageDropDwnCookies(cntId, QueryStringParam) {

    var cntValue = $('#' + cntId).val();

    if (typeof (cntValue) !== 'undefined') {
        if (cntValue !== "") {
            var fromValue = cntValue;
            SetCntCookies(QueryStringParam, cntValue);
        }
        else {
            ExpireCookies(QueryStringParam, 0)
        }
    }
    else {
        ExpireCookies(QueryStringParam, 0)
    }

}


function ExpireCookies(associatedQueryStringParam, cntValue) {

    var dats = new Date();
    dats.setTime(dats.getTime() - (1 * 1 * 60 * 60 * 1000 + 29000 - 3600000 + 1990000));
    var expires = '; expires=' + dats.toUTCString();
    var path = ';path=/';
    document.cookie = associatedQueryStringParam + '=' + cntValue + expires + path;
}


function SetCntCookies(associatedQueryStringParam, cntValue) {

    var dats = new Date();
    dats.setTime(dats.getTime() + (1 * 1 * 60 * 60 * 1000 + 29000 - 3600000 + 1990000));
    var expires = '; expires=' + dats.toUTCString();
    var path = ';path=/';
    document.cookie = associatedQueryStringParam + '=' + cntValue + expires + path;
}

function JobGatogyCookiesClear() {
    ClearRangeCookies();
    ClearDroDwonCookies();
}
