﻿//Search Object
var Search = {
    cache: {
        jobPosts: new Array(),
        results: new Array()
    },

    col1Template: null,
    colTemplate: null,
    header: null,

    delayDetails: null,
    showingDetails: null,

    popupDetails: true,
    popupDescriptions: true,

    init: function () {
        this.col1Template = $('col1Template').innerHTML;
        this.colTemplate = $('colTemplate').innerHTML;
        this.search();
    },

    //called onsubmit for the filter form
    filterChanged: function () {
        //reset the cache
        this.cache.jobPosts = new Array();
        this.cache.results = new Array();
        this.search();
        return false;
    },

    //empty out the search results table
    empty: function () {
        var jobsTable = $('jobsTable');
        //empty out ot the job table and start from scratch;
        while (jobsTable.hasChildNodes()) {
            jobsTable.removeChild(jobsTable.firstChild);
        }
    },

    //set the header column for the search results table
    addHeader: function () {
        var jobsTable = $('jobsTable');
        jobsTable.insertRow(0);
        for (var i = 0, j = 0; i < Search.header.length; i += 2) {
            //do not add a row of there is no major header
            if (Search.header[i] == null) { continue; }
            jobsTable.rows[0].insertCell(-1);
            jobsTable.rows[0].cells[j].className = "colhead";
            jobsTable.rows[0].cells[j].innerHTML = Search.header[i];
            if (Search.header[i + 1] != null) {
                jobsTable.rows[0].cells[j].innerHTML += " / " + Search.header[i + 1];
            }
            j++;
        }
    },

    //display section for no jobs
    displayNoMatch: function () {
        Search.empty();
        $('noMatch').style.display = '';
    },


    //send the filter to the server
    search: function () {
        Search.empty();
        $('searchLoading').style.display = '';
        request("/Jobs/Search", document.forms["filter"], function () {
            //parse the response data into an object
            $('searchLoading').style.display = 'none';

            var jobs = eval('(' + arguments[0] + ')');
            if (jobs == null) { return; }

            var jobsTable = $('jobsTable');
            Search.popupDescriptions = jobs.popupDescriptions;
            Search.popupDetails = jobs.popupDetails;

            //remove the loading dialog
            if (jobs == null) { return; }

            if (jobs.Rows.length == 0) {
                Search.displayNoMatch();
                return; ;
            }

            //set the table header
            Search.header = jobs.Header;



            //add the table data
            for (var i = 0; i < jobs.Rows.length; i++) {
                Search.cache.results[jobs.Rows[i].Row] = jobs.Rows[i];
            }

            Search.showJobs(1, 50);
        });
    },

    //show jobs in the 'jobs' array between the start
    //and stop index. Shouldn't have to check if the jobs
    //between indices actually exist.
    showJobs: function (start, length) {
        var jobsTable = $('jobsTable');
        var rows = Search.cache.results;

        //reset the table to empty
        Search.empty();
        Search.addHeader();

        //add the cached data to the table between rows of interest
        for (var i = start; i < start + length && this.cache.results[i]; i++) {
            var row = jobsTable.insertRow(-1);
            row.className = i % 2 == 0 ? "even" : "odd";
            //add each column with 
            for (var j = 0; j < Search.header.length; j += 2) {
                if (Search.header[j] == null) { continue; }
                var cell = row.insertCell(-1);
                cell.className = "col" + (j >> 1);
                if (j == 0) {
                    cell.innerHTML = Search.transformCol1(
            rows[i].JobPostID,
            rows[i].Columns[0],
            rows[i].Description,
            rows[i].Columns[1]
          );
                } else {
                    cell.innerHTML = Search.transform(rows[i].Columns[j], rows[i].Columns[j + 1]);
                }
            }

        }

    },

    transformCol1: function (JobPostID, title, description, value2) {
        if (value2 == null) { value2 = ""; }
        var output = new String(this.col1Template);

        var titleRef = title.replace(new RegExp("[^A-Za-z1-9]", "g"), "-");
        output = output.replace(new RegExp('#titleRef#', "g"), titleRef);
        output = output.replace(new RegExp('#title#', "g"), title);       
        output = output.replace(new RegExp('#description#', "g"), description);
        output = output.replace(new RegExp('#JobPostID#', "g"), JobPostID);
        output = output.replace(new RegExp('#value2#', "g"), value2);

        return output;

    },

    //transform the job result HTML by search/replace
    transform: function (value1, value2) {
        if (value2 == null) { value2 = ""; }

        var output = new String(this.colTemplate);
        output = output.replace(new RegExp('#value1#', "g"), value1);
        output = output.replace(new RegExp('#value2#', "g"), value2);

        return output;
    },

    //show the short description popup
    showDetails: function (anchor, row) {
        if (Search.popupDetails == false) { return; }
        var stopDelay = function () {
            if (Search.delayDetails != null) {
                clearTimeout(Search.delayDetails);
                Search.delayDetails = null;
            }

            this.onmouseout = null;
        }

        stopDelay();
        anchor.onmouseout = stopDelay;
        this.hideDetails();
        this.delayDetails = setTimeout(
      function () {
          Search.showingDetails = $('details' + row);
          Search.showingDetails.style.display = "block";
          Search.delayDetails = null;
      }, 300
    );
    },

    //hide details currently being displayed
    hideDetails: function () {
        if (Search.showDetails == false) { return };
        if (this.showingDetails != null) {
            this.showingDetails.style.display = "none";
            this.showingDetails = null;
        }
    },

    //present the full job description
    showDescription: function (jobID, jobTitle) {
        if (Search.popupDescriptions == false) {
            if (jobTitle == null) {
                jobTitle = "title";
            }
            window.location = "/jobs/" + jobTitle + "/" + jobID;
            return;
        };

        //show the loading grind
        $('loadingDescription').style.display = 'block';
        $('presentation').innerHTML = '';

        var onload = function (jp) {
            //hide the loading grind
            $('loadingDescription').style.display = 'none';
            $('presentation').appendChild(jp.document);
            jp.setPage(0);
        }

        this.hideDetails();
        var presenter = $('descriptionOverlay');
        presenter.style.display = 'block';

        //if the item is not in the cache load it first, then call the onload event
        if (this.cache.jobPosts[jobID] == null) {
            this.cache.jobPosts[jobID] = new JobPresentation(jobID, onload);
        } else {
            onload(this.cache.jobPosts[jobID]);
        }

        currentDescription = this.cache.jobPosts[jobID];
    },

    hideDescription: function () {
        var presenter = $('descriptionOverlay');
        presenter.style.display = '';
    },

    //apply to the given job
    apply: function (jobID) {
        request("/Jobs/Apply/" + jobID, null, function () {
            var status = arguments[0];

            if (status == "success") {

            } else if (status == "not logged in") {
                window.location = "/account/register/" + jobID;
            }
        });
    }
}