(function() { 

    function checkReferrer (ref) 
    {
        var is_scraper = 0;        
        var scraper_sites = [
                             'simplyhired.co.uk','jobrapido.co.uk','job-job.co.uk',
                             'icjobs.de','vast.com','careerbuilder.co.uk','careerbuilder.com',
                             'clickajob.co.uk','jobsite.co.uk','employon.com','careerjet.co.uk','optioncarriere.com',
                             'jobsafari.co.uk','workcircle.com','jopit.com','jobs.myspace.com','indeed.com',
                             'indeed.co.uk'
                            ];

        for (x = 0; x < scraper_sites.length; x++) 
        {
            if (ref.indexOf(scraper_sites[x]) != -1) 
            {
                location.replace("http://" + location.hostname + "/help/referrer-help.shtml");
                return false;
            }
        }
        
        return true;
    }

    checkReferrer(document.referrer);
    
})();


s1JS.Jobs.Job = {};
s1JS.Jobs.Job.Display = 
{
    detail_height: null,  // cache for
    $loader: null,        // multiple requests
    /*
     *  Load up the default events for the display page
     */
    init:function()
    {     
        var $contact_box = $('#contact-information');       
        
        this.detail_height = $('#right-col').height() - $contact_box.height();
        this.$loader = $('#left-col-loading');
        
        // Initiate functionality exclusive to JS
        // i.e show the search results, hide the contact box and resize the loader    
        $('#search-results').show();        
        if(document.getElementById('contact-apply'))
        {
            $contact_box.hide();
        }
        this.setLoaderHeight();  
        
        $('#store-job').click(this.storeJob);
        $('#show-contact').click(function(e) { $contact_box.slideToggle("fast"); return false; });
       
        // attach the AJAX process to the apply button        
        // UPDATE 18/09/2008 - TURN THIS OFF FOR OPERA/WEBKIT BROWSERS.
        //                     THE IFRAME WAY OF DOING THIS IS A HACK AND IS CONTRIBUTING TO 20~50 ASJS01
        //                     ERRORS PER DAY ONLY ON THOSE TWO BROWSERS. SOLVING ONE PROBLEM JUST RAISES ANOTHER.
        //                     i.e. NO SUPPORT === NO SUPPORT
        if(page_data.ajax_apply && ($.browser.msie || $.browser.mozilla)) 
        {
            
			//KM 18-04-2011: The AJAX method for applying is causing increasing errors. It is being disabled for the moment.
			
			//$('.job-apply, #contact-apply').click(s1JS.Jobs.ApplyProcess.setUpApply);
            //$('#contact-apply').attr('href', '#');
			
        }

        // set up the AJAX search results
        this.setPageData();     
        var results = new s1JS.Jobs.AjaxResults({page_data:page_data});
        results.doRequest();   
        results.updateSearchCookie(); // now that we've displayed the search, save it
        
        // set up the apply page if the page URL matches #apply
        if(document.location.hash.match("apply"))
        {
            s1JS.Jobs.ApplyProcess.setUpApply();
        } 
    },   
    /*
     *  Sets the height of the loader div so that it covers the contents of the left column
     */ 
    setLoaderHeight:function()
    {
        var column_height = $('#left-col').height();              
        (column_height > this.detail_height) ? this.$loader.height(column_height) : this.$loader.height(this.detail_height);
        this.$loader.show();
    },
    /*
     *  Extends the global page_data object with AJAX search results properties,
     *  this can't be done in the template (which would be easier) because to 
     *  locally cache the file, every value on the page has to be static.
     */     
    setPageData:function()
    {
        page_data.type = 'current';
        if (document.location.pathname.match(/\/featured\//))
        {
            page_data.type = 'featured';
        }    
    
        // Build our page_data based on cookie
        // or if no cookie fall back on vacancy criteria
        var query = s1JS.Jobs.Cookies.readCookie('search');   
        query = (query) ? unescape(query) : page_data.default_query_string;
        
        page_data.script = '/search/results.cgi';      
        var queryObj = s1JS.Jobs.createObjFromQuery(query);
        page_data.page = (queryObj['page']) ? parseInt(queryObj['page']) : 1;
        page_data.current_page = page_data.page;    
        page_data.number_per_page = 10;        
        
        // remove page for our AJAX search results
        query = s1JS.Jobs.createQueryFromObj(queryObj, {page:true});
        
        page_data.query_string = query;
        page_data.original_query_string = query;       
    },
    storeJob:function(e)
    {
        var url = $(this).attr('href');
        $.getJSON(url + '&js=1', function(data) { 
        
            if(data && data.unregistered)
            {
                document.location.href = '/myaccount/sign-in.shtml?return_to=' + escape(url);
            }
            else
            {
                $('ul.job-tools').after('<div class="friendly-message" style="padding: 3px; text-align: center;">This job has been stored to <a href="/myaccount/">your account</a>.</div>');
            }
        });
        return false;
    }
};  

s1JS.Jobs.ApplyProcess = 
{
    // this flag is to prevent multiple requests for the apply form being made
    running_apply: false,
    /*
     *  Sets up the apply form and any events needed 
     *
     *  @e    the event
     */
    setUpApply:function(e) 
    {
        // apply already set up or in the process of setting up
        if(s1JS.Jobs.ApplyProcess.running_apply)
        {
            // clicked after cancelling, so already set up
            if(document.getElementById('apply-holder') && $('#left-col-wrapper').css('display') == 'none')
            {
                $('#left-col-wrapper').show();
                $('#search-results').hide();
            }
            return false;
        }
        // set the flag to prevent multiple apply clicks
        s1JS.Jobs.ApplyProcess.running_apply = true;
        
        // show the loading div
        s1JS.Jobs.Job.Display.$loader.show();

        // request our apply form data
        $.getJSON("/apply/apply.cgi?vacancy_id=" + page_data.vacancy_id + "&js=1", 
            function(data) {

                var myTemplate = new s1JS.PerlTemplates({url: '/apply/apply-form.tmpl', data:data});
                var content = myTemplate.getContent();            

                // if search results is showing, slide it away before we show apply page
                var search = document.getElementById('search-results');
                if(search && search.style.display != 'none')
                {
                    $(search).hide();   
                }
                
                // insert the apply div after the loader, attach events
                // and resize the loader before hiding (to cover results)
                s1JS.Jobs.Job.Display.$loader.after(content);                   
                s1JS.Jobs.ApplyProcess.setUpApplyEvents();
                s1JS.Jobs.Job.Display.setLoaderHeight();                 
                s1JS.Jobs.Job.Display.$loader.hide();   
                $('html, body').animate({scrollTop:0}, 1000);
        });        
        return false;
    },
    /*
     *  Attach necessary event handlers into the apply form
     */
    setUpApplyEvents:function()
    {
        // back to search results/cancel application
        $('#cancel-apply-link').click(function() {
            $('#search-results').show();
            $('#left-col-wrapper').hide();        
            return false;
        });        
    
        // Flip between the document upload view since we're in the JS version
        $('#logged-in-js-view').show();
        $('#logged-in-default-view').hide();                
        $('#change-to-default-view').click(function(e) { 
            $('#logged-in-default-view').show();
            $('#logged-in-js-view').hide(); 
            return false;
        });    
    
        // sign in modal box
        if($('.sign-in-link').get(0) && !document.getElementById('sign-in-modal'))
        {
            s1JS.Jobs.createSignInForm({return_to: document.location.pathname + escape('#') + 'apply'});
        }
        else
        {
            $('#sign-in-return-to').val(document.location.pathname + escape('#') + 'apply');
            
            $('.sign-in-link', $('#left-col'))
                .click(function() {
                   $('#sign-in-modal').dialog("open"); 
                   return false;
            });        
        }
        
        
        // CHECK FOR NO CV ATTACHED AND ELIGIBLITY
        $('#submit-application').click(function() { 
        
            if(document.getElementById('is_eligible') && ! document.getElementById('is_eligible').checked)
            {
                alert('You must confirm that are eligible to work in the UK.');
                return false;
            }
        
        
            // check if the upload box exists and it's empty, if it exists or has a value then they pass
            if(document.getElementById('uploaded-file') && !document.getElementById('uploaded-file').value)
            {            
                var num_docs_selected = $('#doc-list').find('input:checked').length;
                if(num_docs_selected > 0)
                {
                    return true;
                }
            }
            else
            {
                return true;
            }            
 
            if(confirm('We recommend that you attach a CV before proceeding. Continue anyway?'))
            {
                return true;
            }
            else
            {
                return false;
            }
        });

        // Set up the AJAX post for a file upload, it's a special thing!
        var $form = $('#apply-form');        
        $form.prepend('<input type="hidden" name="js" value="1" />');
        
        // Make it a "niceForm"
        s1JS.Jobs.niceForms.apply($form);
        
        // set up validation
        var validator = new s1JS.Jobs.Validator(document.getElementById('apply-form'));
        validator.addRequired(['your_name','email','email2','covering_letter']);           
        validator.equal(['email','email2'], 'Your email addresses must match.');
        validator.email('email');
        
        new s1JS.Jobs.FileUpload({form: 'apply-form', callback: s1JS.Jobs.ApplyProcess.applySubmitHandler, loader:'left-col-loading', validator: validator});        
    },
    /*
     *  Callback function for our fancy AJAX FileUpload
     *
     *  @data    the JSON response from the apply submit script
     */
    applySubmitHandler:function(data)
    {
        // the response from the server is that they have already applied
        if(data.template_file && data.template_file.match("followup"))
        {
            var myTemplate = new s1JS.PerlTemplates({url: data.template_file, data:data, target:'left-col-wrapper'});
            myTemplate.render();        
    
            // attach a submit handler for our follow-up script, because this is also AJAX
            var $form = $('#followup-form');
            $form.prepend('<input type="hidden" name="js" value="1" />');
            
            // Make it a "niceForm"
            s1JS.Jobs.niceForms.apply($form);            
            
            $form.submit(s1JS.Jobs.ApplyProcess.followupSubmitHandler);
        }
        else if(data.message)
        {
            data.errorcode = 'JCA04';
            $('<div class="flora"><p>' + data.message + '</p><p>If this problem persists, please <a href="mailto:servicedesk@s1jobs.com">contact customer services</a> and quote the error ' + data.errorcode + '</div>')
                    .appendTo('#content')
                            .dialog({modal:true, width:400, title:"Apply Submission Error",  overlay: { opacity: 0.5, background: 'black' }, open: s1JS.Jobs.fastAds.hideAds, close: s1JS.Jobs.fastAds.showAds});
        }
        // the response from the server is a successful application
        else 
        {
            var myTemplate = new s1JS.PerlTemplates({url: data.template_file, data:data, target:'left-col-wrapper'});
            myTemplate.render();
            
            // attach events to the apply success page
            $('.benefits-link').click(function(e) {
                $('#benefits').slideToggle("fast");
                return false;
            });
            $('.close a').click(function(e) { 
                $('#benefits').slideUp("fast");                    
                return false;
            });
        }    
    },
    
    /*
     *  The submit handler for the apply follow-up form, basically just does an AJAX POST on the form
     *  
     *  @e    the event
     */
    followupSubmitHandler:function(e)
    {
        $this = $(this);
        var data = $this.serializeArray();
        $.post('/apply/followup-submit.cgi', data, 
                s1JS.Jobs.ApplyProcess.setUpFollowupSuccess,
               "json");
        return false;            
    },
    
    /*
     *  Creates the follow up response
     *
     *  @data    the JSON response from the followup-submit script
     */
    setUpFollowupSuccess:function(data)
    {
        var myTemplate = new s1JS.PerlTemplates({url:data.template_file, data:data, target:'left-col-wrapper'});
        myTemplate.render();       
    }
};

s1JS.Jobs.addLoader(function() { s1JS.Jobs.Job.Display.init(); });

