﻿var countJobs = 10;
var activePage = 1;

//Global variables for "filter".
var jobTypeID = null;
var dataPostedID = null;
var sourceID = null;
var categoryID = null;
var slrMin = null;
var slrMax = null;
var ratePerHourID = null;
var distanceID = null;
var slrID = null;
var jobTitle = null;

function sL()
{           
    sR = c4jRequestInit();
    
    if(sR)
    {
        start = start + count;

        var url = GetHtmlPageUrl() + "?o=" + o + "&q=" + q + "&l=" + l + "&c=" + c
                + "&s=" + s + "&p=" + p + "&t=" + t + "&start=" + start + "&count=" + count
                + ((jobTypeID != null) ? "&fjt=" + jobTypeID : "")
                + ((dataPostedID != null) ? "&fdp=" + dataPostedID : "")
                + ((sourceID != null) ? "&fsrc=" + sourceID : "")
                + ((categoryID != null) ? "&fctg=" + categoryID : "")
                + ((slrMin != null) ? "&fslrmin=" + slrMin : "")
                + ((slrMax != null) ? "&fslrmax=" + slrMax : "")
                + ((ratePerHourID != null) ? "&frph=" + ratePerHourID : "")
                + ((distanceID != null) ? "&fd=" + distanceID : "")
                + ((src != null) ? "&src=" + src : "")
                + ((slrID != null) ? "&fslrid=" + slrID : "")
                + ((jobTitle != null) ? "&ft=" + encodeURIComponent(jobTitle) : "");
        
        sR.onreadystatechange = sLD;
        sR.open("get",url,true);
        sR.send(null);
    }
} 

function GetVacancies(el, startIndex)
{      
    document.getElementById("loading").style.visibility = "visible";
    var ajax = c4jRequestInit();
    countJobs = el.value;
    
    if(ajax)
    {
        var url = GetHtmlPageUrl() + "?o=" + o + "&q=" + q + "&l=" + l + "&c=" + c
                + "&s=" + s + "&p=" + p + "&t=" + t + "&start=" + startIndex + "&count=" + ((countJobs == 100) ? 10 : countJobs)
                + ((jobTypeID != null) ? "&fjt=" + jobTypeID : "")
                + ((dataPostedID != null) ? "&fdp=" + dataPostedID : "")
                + ((sourceID != null) ? "&fsrc=" + sourceID : "")
                + ((categoryID != null) ? "&fctg=" + categoryID : "")
                + ((slrMin != null) ? "&fslrmin=" + slrMin : "")
                + ((slrMax != null) ? "&fslrmax=" + slrMax : "")
                + ((ratePerHourID != null) ? "&frph=" + ratePerHourID : "")
                + ((distanceID != null) ? "&fd=" + distanceID : "")
                + ((src != null) ? "&src=" + src : "")
                + ((slrID != null) ? "&fslrid=" + slrID : "")
                + ((jobTitle != null) ? "&ft=" + encodeURIComponent(jobTitle) : "");

        ajax.onreadystatechange = function() {
            if (ajax.readyState == C4J_REQUEST_COMPLETE) {
                if (!ajax.responseText)
                    return;

                document.getElementById("srl").innerHTML = ajax.responseText;

                if (countJobs == 100) {
                    count = 10;
                    start = 10;
                    sL();
                }

                GetResultsCount();
                SetCountAndTimeInfo();
                Paginations();
                scroll();
                document.getElementById("loading").style.visibility = "hidden";
            }
        };
        ajax.open("get",url,true);
        ajax.send(null);
    }
}

function SetCountAndTimeInfo() {
    if (results > 0) {
        GetSrrcElement().innerHTML = "<b>" + document.getElementById("hfResultsStr").value + "</b>&nbsp;&nbsp;results in&nbsp;&nbsp;<b>" 
            + document.getElementById("hfTimeStr").value + "</b>&nbsp;&nbsp;seconds.";
    }
    else {
        GetSrrcElement().innerHTML = "No results found.";
    }
}

function GetResultsCount() {
    var resultsCount = null;
    
    try
    {
        resultsCount = document.getElementById("hfResults").value;
    }
    catch(ex)
    {
        resultsCount = null;
    }

    if (resultsCount != null) {
        results = resultsCount;
    }
}

function OnFilterItemClick(el, isUndo) {
    activePage = 1;
    RatePerHourAndSalaryConflict(el, isUndo);
    GetVacancies(document.getElementById("ddlCountJobs"), 0);
    
    var nodes = el.parentNode.childNodes;
    if (isUndo) {
        for (i = 0; i < nodes.length; i++) {
            if (nodes[i].className != "count") {
                nodes[i].style.display = "none";
            }
        }
        el.parentNode.firstChild.style.display = "";        
    }
    else {        
        for (i = 0; i < nodes.length; i++) {
            nodes[i].style.display = "";
        }
        el.style.display = "none";

        var parentLIs = el.parentNode.parentNode.childNodes;
        for (i = 0; i < parentLIs.length; i++) {
            if (parentLIs[i].firstChild != el) {
                for (j = 0; j < parentLIs[i].childNodes.length; j++) {
                    if (parentLIs[i].childNodes[j].className != "count") {
                        parentLIs[i].childNodes[j].style.display = "none";
                    }
                }
                parentLIs[i].firstChild.style.display = "";
            }
        }
    }
}

function OnFilterItemClickWithRedirect(el, filterType, url) {
    $.ajax({
        type: "GET",
        url: GetFilterHandlerUrl() + "?ftype=" + filterType,
        async: false
    });
    el.href = url;
}

function RatePerHourAndSalaryConflict(el, isUndo) {
    if (!isUndo) {
        if (ratePerHourID != null) {
            slrMax = null;
            slrMin = null;
            var parentLIs = GetUlSalary().childNodes;            
            for (i = 0; i < parentLIs.length; i++) {
                parentLIs[i].childNodes[0].style.display = "";
                parentLIs[i].childNodes[1].style.display = "";
                parentLIs[i].childNodes[2].style.display = "none";
                parentLIs[i].childNodes[3].style.display = "none";
            }
        }
        else if (slrMax != null && slrMin != null) {
            ratePerHourID = null;
            var parentLIs = GetUlRatePerHour().childNodes;            
            for (i = 0; i < parentLIs.length; i++) {
                parentLIs[i].childNodes[0].style.display = "";
                parentLIs[i].childNodes[1].style.display = "";
                parentLIs[i].childNodes[2].style.display = "none";
                parentLIs[i].childNodes[3].style.display = "none";
            }
        }
    }
}

function Paginations() {
    if (document.getElementById("ddlCountJobs").value != 100) {
        var countPages = Math.ceil(results / document.getElementById("ddlCountJobs").value);
        var pagesHtml = "";
        
        if (countPages > 1) {
            if (activePage != 1) {
                pagesHtml = pagesHtml + '<a href="javascript:void(0);" onclick="GoToPage(' + (activePage - 1) + ');" class="non-active">prev</a>';
            }

            var interval = GetInterval(countPages, activePage);

            for (i = interval[0]; i < interval[1]; i++) {
                pagesHtml = pagesHtml + '<a href="javascript:void(0);" class="'
                                + (((i + 1) == activePage) ? 'active' : 'non-active') + '" onclick="GoToPage(' + (i + 1) + ');">' + (i + 1) + '</a>';
            }
            
            if (activePage != countPages) {
                pagesHtml = pagesHtml + '<a href="javascript:void(0);" onclick="GoToPage(' + (activePage + 1) + ');" class="non-active">next</a>';
            }

            document.getElementById("paginations").innerHTML = pagesHtml;
        }
        else {
            document.getElementById("paginations").innerHTML = "";
        }
    }
    else {
        document.getElementById("paginations").innerHTML = "";
    }
}

function GetInterval(countPages, activePage) {
    var maxPagesForDisplay = 10;
    var maxPagehalf = Math.ceil(maxPagesForDisplay / 2);
    var upperLimit = countPages - maxPagesForDisplay;
    var start = activePage > maxPagehalf ? Math.max(Math.min(activePage - maxPagehalf, upperLimit), 0) : 0;
    var end = activePage > maxPagehalf ? Math.min(activePage + maxPagehalf, countPages) : Math.min(maxPagesForDisplay, countPages);
    return [start, end];
}

function GoToPage(page) {
    activePage = page;

    ShowLoadingInPaginations();

    GetVacancies(document.getElementById("ddlCountJobs"), (activePage - 1) * document.getElementById("ddlCountJobs").value);
}  

function ShowLoadingInPaginations()
{              
    for(i = 0; i < document.getElementById("paginations").childNodes.length; i++)
    {
        var el = document.getElementById("paginations").childNodes[i];
        
        if(el.className == "active")
        {
            el.style.background = "url(" + GetLoadingImg() + ") no-repeat scroll center";               
        }
    }
} 

function SubscribeAlert()
{
    var regex = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
    var email = document.getElementById("subscribe-email");
                    
    if(email)
    {
        if(Trim(email.value) == "" || !regex.test(Trim(email.value)))
        {
            alert("Invalid email address!");
        }
        else
        {
            var ajax = c4jRequestInit();
            if(ajax)
            {
                ajax.open("GET", GetSearchPageUrl() + "?email=" + Trim(email.value), false);
                ajax.send(null);
            }
            
            document.location = GetJobsByEmailUrl();
        }
    }
    else
    {
        alert("Invalid email address!");
    }
}

function ToCvUploader(a, v, s) {
    var ajax = c4jRequestInit();
    if (ajax) {
        ajax.open("GET", GetSearchPageUrl() + "?vparameter=" + v + "&sparameter=" + s, false);
        ajax.send(null);
    }
    a.href = GetIcvRegisterUrl();    
}

function CollapceExpande(span, item) {
    var ul = span.parentNode.parentNode.getElementsByTagName("ul")[item];

    if (typeof (ul) != 'undefined') {
        if (ul.style.display == "none") {
            ul.style.display = "block";
            SetCookie(span.id, item);            
            span.style.background = "transparent url(" + GetFilteExpand() + ") no-repeat scroll 0 3px";
        }
        else {
            ul.style.display = "none";
            DeleteCookie(span.id);
            span.style.background = "transparent url(" + GetFilterCollapce() + ") no-repeat scroll 2px 1px";
        }
    }    
}

function CheckFilters() {
    var ids = new Array("spanJobTitle", "spanMoreJobs", "spanMoreLocations", "spanJobType",
        "spanDatePosted", "spanDistance", "spanSlary", "spanRatePerHour",
        "spanJobsBySector", "spanJobSource", "spanRecentSearches");

    for (i = 0; i < ids.length; i++) {
        var el = GetCookie(ids[i]);

        if (el != null) {
            CollapceExpande(document.getElementById(ids[i]), el);
        }
    }
}

function SetAlweysOpenJobTitle() {
    try {
        if (GetUlJobTitleID()) {
            if (document.getElementById(GetUlJobTitleID()).style.display == "none") {
                document.getElementById(GetUlJobTitleID()).style.display = "block";
                document.getElementById("spanJobTitle").style.background = "transparent url(" + GetFilteExpand() + ") no-repeat scroll 0 3px";
            }
        }
    }
    catch (ex) { }
}

function ClearRecentSearch() {
    DeleteCookie("C4J_SEARCHES", "/");
    GetUlRecentSearches().innerHTML = "No options";
}

function GetGUID() {
    var guid = "";
    for (var i = 0; i < 32; i++)
        guid += parseInt(Math.random() * 16).toString(16);

    return guid;
}

function Trim(str) {
    str = str.replace('\\s+', ' ');
    str = str.replace(/(^\s+)|(\s+$)/g, '');

    return str;
} 

function  scroll()
{
      if ( document.documentElement && document.documentElement.scrollTop )
      {
            document.documentElement.scrollTop = 0;
      }
      else if ( document.body )
      {
            document.body.scrollTop = 0;
      }
}
