UCLU.jobsearch = {
    //config
    
    resultsPerPage: 10,
    
    // no more config
    
    searchString: '',
    params: {},
    
    init: function() {          
        this.params.jq = UCLU.util.getQueryParameter('jq');
        this.params.tag = UCLU.util.getQueryParameter('tag');   
        this.offset = UCLU.util.getQueryParameter('start') || 0;
            
        if (UCLU.jobfilename=='search.php' || this.params.jq || this.params.tag || this.offset) {
             YAHOO.util.Event.onAvailable('search-results', function() {
                 UCLU.jobsearch.doSearch();
             });
        } 

        if (UCLU.jobfilename=='search.php') {
            YAHOO.util.Event.onAvailable('jq', function() {
                this.value = UCLU.jobsearch.params.jq||'';
            });
    
            YAHOO.util.Event.addListener('jobsearch', 'submit', function(e){
                if (e) YAHOO.util.Event.stopEvent(e);
                UCLU.jobsearch.params.jq = $('jq').value;
                UCLU.jobsearch.doSearch();
            });
        } else
        if (UCLU.jobfilename!='index.php' && !this.params.tag) {
            this.params.tag = UCLU.jobpagename;
        }

        // Check if user is logged in
        if (community.getUsername()) { 
            // Add event handlers to subscribe buttons
            YAHOO.util.Event.addListener('subscribe-email', 'mouseup', this.handleSubscribe);
            YAHOO.util.Event.addListener('subscribe-homepage', 'mouseup', this.handleSubscribe);

            // Retrieve saved searches
            YAHOO.util.Event.onAvailable('jobs-saved-searches', function() {
                community.callCustomMethod('GET', 'jobs-get-saved-searches',
                    {
                        success: function(o) {
                            var r = eval(o.responseText);
                            var h = '';
                            if (r.length==0) {
                                h = 'None found';
                            } else 
                            for (var i=0; i < r.length; i++) {
                                h += '<a href="' + r[i].url + '">' + r[i].name + '</a>';
                            }
                            $('jobs-saved-searches').innerHTML = h;
                            UCLU.util.redraw('right');
                        }
                    }
                )               
            });
        }
    },
    
    doSearch: function() {
        $('search-header').innerHTML = 'Searching...';
        $('search-results').innerHTML = '';

        var terms = [{ _type: 'term-query', field: 'template', required: 'true', value: 'Vacancy' }];
       
        if (this.params.jq) {
            terms.push({ _type: 'parsed-query', field: 'freetext', required: 'true', value: this.params.jq });
            terms.push({ _type: 'term-query', field: 'itemName', required: 'false', value: this.params.jq });
            this.searchString = ' for "' + this.params.q + '"';
        } else {
            // order by most recent first
            terms.push({ _type: 'sort', field: 'creationDate', reverse: 'true' });
        }

        if (this.params.tag) {
            terms.push({ _type: 'term-query', field: 'tag',         value: this.params.tag });
            this.searchString += ' with tag <i>' + this.params.tag + '</i>';
        }

        this.query = luckit.newQuery(terms, function(res){UCLU.jobsearch.handleResponse(res)});
        
        this.query.search({
            limit: this.resultsPerPage,
            offset: this.offset-0+1
        });

     },
    
    handleResponse: function(res) {
        if (res.total == 0) {
            $('search-header').innerHTML = 'No matching jobs were found';
            return;
        }
        
        var resultsHtml = '';
        
        for (var i=0; i<res.results.length; i++) {
            var r = res.results[i];
            
            resultsHtml += '<div class="search-result">';
            
            var jobTitle = r.getField('jobTitle'),
                employerName = r.getField('employerName'),
                location = r.getField('location');
            
            if (location)
                jobTitle += ', ' + location;

            resultsHtml += '<h3><a href="' + r.getField('path') + '">'
                        +  (res.offset+1+i) + '. ' + jobTitle
                        +  '</a></h3>';
        
            var text = r.getField('shortDescription');
            resultsHtml += '<p>' + text + '</p>';

            var hours = r.getField('hours');        
            if (hours)
                resultsHtml += 'Working hours: '+ hours + '<br />';
            var payRate = r.getField('payRate');        
            if (payRate)
                resultsHtml += '£' + payRate + ' per hour' + '<br />';

            var lcCategory = r.getField('lc-category');
            var tags = r.getField('tag', true);
            
            if (tags) {
                var items = [];
                                
                for (var j=0; j<tags.length; j++)
                    items.push('<a rel="tag" href="find-a-job/index.php?tag=' + tags[j] + '">' + tags[j] + '</a>');

                if (items.length) {
                    resultsHtml += '<div class="search-result-tags"><b>Tags:</b> '
                                +  items.join(', ')
                                +  '</div>';
                }
            }
            
            resultsHtml += '</div>';
        }
        
        var paginationHtml = '';
        
        if (res.total > this.resultsPerPage) {
            var pages = [];
            
            for (var i=0; i<res.total; i += this.resultsPerPage)
                pages.push({start: i});
                        
            var prev = null, next = null;
            
            for (var i=1; i<pages.length; i++)
                if (pages[i].start == this.offset)
                    prev = pages[i-1].start;
            
            for (var i=0; i<pages.length-1; i++)
                if (pages[i].start == this.offset)
                    next = pages[i+1].start;
                        
            htmlLinks = [];
            
            htmlLinks.push(
                prev != null ? '<a class="search-prev" href="' + this.getSearchUrl({start:prev}) + '">Previous</a>'
                             : 'Previous'
            );

            for (var i=0; i<pages.length; i++) {
                var html = i+1;
                
                if (pages[i].start != this.offset)
                    html = '<a href="' + this.getSearchUrl({start: pages[i].start}) + '">' + html + '</a>';
                
                htmlLinks.push(html);
            }

            htmlLinks.push(
                next != null ? '<a class="search-next" href="' + this.getSearchUrl({start:next}) + '">Next</a>'
                             : 'Next'
            );
            
            paginationHtml += htmlLinks.join(' - ');
        }
            
        $('search-header').innerHTML = 'Found '+res.total + ' matching job' + (res.total != 1 ? 's' : '');
        $('search-results').innerHTML = resultsHtml;
        
        if (paginationHtml != '') {
            $('search-pagination').innerHTML = paginationHtml;
            $('search-pagination').style.display = '';
        }

        this.offset = 0;
    },
    
    getSearchUrl: function(opts) {
        var params = this.params;
        
        if (typeof(opts) != 'undefined')
            for (var i in opts)
                params[i] = opts[i];
        
        var ps = [];
        
        for (var i in params)
            if (typeof(params[i]) != 'undefined') ps.push(i + '=' + escape(params[i]));
        
        return 'find-a-job/search.php?' + ps.join('&');
    },

    handleSubscribe: function(e) {
        if (e) YAHOO.util.Event.stopEvent(e);
            
        if (!$('subscribe-module')) {
            var html = '<div class="hd">&#160;</div>' +
                       '<div class="bd">' +
                           '<p>'+
                               '<label for="search-name">Save search as </label>' +
                               '<input type="text" name="search-name" id="search-name">' +
                           '</p>' +
                           '<p>'+
                               '<input type="checkbox" name="email-alert" id="email-alert" value="true" class="subscribe-checkbox"' +
                               (this.id=='subscribe-email' ? ' checked' : '') +
                               '><label for="email-alert"> Send me email alerts</label>' +
                           '</p>' +
                           '<p>' +
                               '<button type="button" id="subscribe-save" title="Save">' + 
                                    '<img src="styling/i/subscribe-save.gif" alt="Save">' +
                               '</button>' +
                               '<a href="javascript:void(0)" id="subscribe-cancel">Cancel</a>' +
                           '</p>' +
                       '</div>' +
                       '<div class="ft">&#160;</div>';

            var div = document.createElement("div");
            div.className = 'module fill';
            div.id = 'subscribe-module';

            $('jobsearch').parentNode.insertBefore(div, $('jobsearch'));
            div.innerHTML = html;

            YAHOO.util.Event.addListener('subscribe-save', 'click', UCLU.jobsearch.handleSubscribeSave);
            YAHOO.util.Event.addListener('subscribe-cancel', 'click', function(e) {
                if (e) YAHOO.util.Event.stopEvent(e);
                $('subscribe-module').style.display = 'none';
            });
        } else if ($('subscribe-module').style.display == 'none') {
            $('subscribe-module').style.display = 'block';
        } else {
            $('subscribe-module').style.display = 'none';
        }
    },
    
    handleSubscribeSave: function(e) {
        UCLU.jobsearch.params.jq = $('jq').value;

        var searchName = $('search-name').value; // TODO: trim spaces
        if (!searchName) {
            // TODO: standardize error handling 
            alert('Please supply a name for the search');
            $('search-name').focus();
            return;
        }

        // TODO: xml escape values
        var url = UCLU.jobsearch.getSearchUrl().replace(/&/g,'&amp;');

        var payload = '<JobsSavedSearch>' +
            '<name>' + searchName + '</name>' +
            '<url>' + url + '</url>' +
            '<emailAlert>' + $('email-alert').checked + '</emailAlert>' ;

        if (UCLU.jobsearch.params.jq) {
            payload += '<freetext>' + UCLU.jobsearch.params.jq + '</freetext>';
        }
        if (UCLU.jobsearch.params.tag) {
            payload += '<category>' + UCLU.jobsearch.params.tag + '</category>';
        }

        payload += '</JobsSavedSearch>';

        //alert('debug: '+payload); return;
        community.saveObject('JobsSavedSearch', 
            null, 
            { success: UCLU.jobsearch.handleSaveSuccess }, 
            payload
        );
   },

   handleSaveSuccess: function(response) {
       $('subscribe-module').style.display = 'none';
       // Write into "saved searches" list
       var a = document.createElement("a");
       a.href = UCLU.jobsearch.getSearchUrl();
       a.appendChild(document.createTextNode($('search-name').value));
       $('jobs-saved-searches').appendChild(a);
   }

 }

UCLU.jobsearch.init();