﻿
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();                
        
        if(adecco.config.isCanada) {
            // Use the category specified in the web part properties
            var categoryWPProperty = "";
            try{
                categoryWPProperty = document.getElementById("_categoryWPProperty").getAttribute("value");
            }catch(error){}   
             if(categoryWPProperty != "")
                requestParams.cat = categoryWPProperty;
        }
            
        // Display spinner during load
        $(widget).mask();
         
        // Execute the ASYNC request
        $.ajax( {
            url: adecco.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 = $('#_userCategory').attr('value');                    
        var categoryWPProperty = $('#_categoryWPProperty').attr('value');
        
        // 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;              
                  
        // Set category to the the value specified by content authors inside the web part property
        if(categoryWPProperty != "")
             requestParams.cat = categoryWPProperty;
              
        if (requestParams.loc == adecco.config.recentJobsLocationWaterMark || requestParams.loc == adecco.config.recentJobsLocationWaterMark_FR)
            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;
            }
        }                               
    },
    
    getParameter: function(name) {  
        name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  
        var regexS = "[\\?&]"+name+"=([^&#]*)";  
        var regex = new RegExp( regexS );  
        var results = regex.exec( window.location.href );  
        if( results == null )    
	        return "";  
        else    
	        return results[1];
    },
    
    toQueryString: function() {
        var
            me = this,
            queryString = adecco.jobsearch.variationLabelPath[0] + adecco.config.searchResultPage;
            queryString += '&cat=' + escape(me.category);
            if(escape(me.radius) == "" || escape(me.radius) == null)
                 queryString += '&rds=' + adecco.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(adecco.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(adecco.config.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() == adecco.config.recentJobsLocationWaterMark || locationLabel.text() == adecco.config.recentJobsLocationWaterMark_FR)
            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) {   
            if(adecco.jobsearch.variationLabelPath[0] == '/fr')
                locationEntered = adecco.config.recentJobsLocationWaterMark_FR;
            else
                locationEntered = adecco.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
        
        // Use the category specified in the web part properties
        var categoryWPProperty = $("#_categoryWPProperty").attr("value");
         if(categoryWPProperty != "")
            requestParams.cat = categoryWPProperty;

        // build context sensitive URL to view all jobs (using category and location)
        window.location = adecco.jobsearch.variationLabelPath[0] +  adecco.config.searchResultPage + "cat=" + requestParams.cat + "&loc=" + requestParams.loc;        
        
    },    
    
    pageDidFinishLoading: function() {
       var
            recentJobWidgets = $('.content-widget.recent-jobs'),
            jobCategoryDropdown = $('.recentjobs-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
        //});
    }    

};

$(document).ready(adecco.recentjobs.pageDidFinishLoading);
