/**
 * Search results
 *
 * @author $Author:$
 * @copyright 2007 JobSpeed
 * @filesource
 * @link http://www.jobspeed.com.au/index.php
 * @package JobSpeed
 * @subpackage SearchFunctions
 */
 
  var total_pages;
  var current_page;
  var id_result_box = "result_box";
  var id_paging_box = "paging_box";
  var div_translation;
  var result_loading;

  function initSearch(page) {
  
    if (! page) {
      page = 1;
    }
    
    total_pages = search_result_paged.length - 1;

    if (page < 1 || page > total_pages) {
      page = 1;
    }

    current_page = page;
    loadResults();
  }

  function loadResults() {
    div_translation = new Array();
    result_loading = new Array();
    
    clearResults();
    createPaging();
    
    var count = 1;
    search_result_paged[current_page].each(function(job_id) {
      loadResult(count, job_id);
      div_translation[job_id] = count;
      count++;
    });
}

  function loadStuckResult(div_id, job_id) {
    if(result_loading[job_id] > 0) {
        loadResult(div_id, job_id);
    }
  }

  // load a result, after failure 3sec before next try, after 10sec no result -> new request
  function loadResult(div_id, job_id) {
    job_id = parseInt(job_id, 10);
    if (job_id > 0) {
      // loading (and timeout)
      result_loading[job_id]++;
      $("job"+ div_id).innerHTML = "<div align='center'><img src='images/loading.gif' border='0' alt='"+ result_loading[job_id] +"x'></div>"
      setTimeout("loadStuckResult("+ div_id +", "+ job_id+")", 10000);
       
      new Ajax.Request("includes/ajax/jskResultMini.php?job_id=" + job_id + "&div_id=" + div_id, {
                         method: 'get',
                         onFailure: function(transport) {
                                        result_loading[job_id] = 0;
                                        $("job"+ div_id).innerHTML = "<div align='center'><i>Timeout in retrieving result, trying again in a few seconds.</i></div>";
                                        setTimeout("loadResult("+ div_id +", "+ job_id+")", 3000);
                                    },
                         onSuccess: function(transport) {
                                        result_loading[job_id] = 0;
                                        createResult(transport, div_id, job_id);
                                    }
                         });
    } else {
      permFailedResult(div_id);
    }
  }

  function createResult(transport, div_id, job_id) {
    var job_data = transport.responseText.split(':sk:');
    createHTMLResult(div_id, job_id, job_data[0], job_data[1], job_data[2], job_data[3], job_data[4], job_data[5], job_data[6]);

    // make sure we process the first one
    // we do it here so we know the id's exist
    if (div_id == 1) {
      loadResultDetail(job_id);
      focusJob("1");
    }
  }

  function permFailedResult(div_id) {
    var div = $("job"+ div_id);
    div.innerHTML = "Failed to retrieve result information";
  }

  function clearResults() {
    // clean the pageing array
    search_result_paged[current_page].compact();

    // vars
    var html = "";
    var main_class = "";
    var main_style = "";
    var result_box = $(id_result_box);
    var num_results = search_result_paged[current_page].length;

    // memory leak check
    if(num_results > 8) {
        num_results = 8;
    }

    for(var n=1; n <= num_results; n++) {
      // first result has a different class
      if(n == 1) {
          main_class = "boxheader";
      } else {
          main_class = "list";
      }
        
      // if there is a 8th result it has no bottom line
      if(n != 8) {
          main_style = "border-bottom: 1px solid #7E7E7E";
      } else {
          main_style = "";
      }
        
      // add it to the list
      html += "<div id='job"+ n +"' class='"+ main_class +"' style='"+ main_style +"'></div>\n";
    }
    
    // dump
    result_box.innerHTML = html;
  }

  function loadResultDetail(job_id) {
    clearResultDetail();

    if(job_id.length == 0) {
        $("detail_desc").innerHTML = "";
        return;
    } else {
        new Ajax.Request("includes/ajax/jskResultDetail.php?job_id=" + job_id, {
                         method: 'get',
                         onSuccess: showResultDetail});
    }
}

/**
 * nums mapping
 * 0 - job id
 * 1 - job title
 * 2 - full description
 * 3 - logo image tag (img)
 * 4 - Contact name
 * 5 - Contact phone
 * 6 - Request / Display - contact option
 * 7 - Shortlisted - checked="checked" or / ''
 * 8 - Residency string
 * 9 - Residency span
 */
  function showResultDetail(transport) {
    var nums = transport.responseText.split(':sk:');

    var job_id = nums[0];

    var residencyString = '';
    var shortlisted = '';
    var residencySpan = '';

    // job title
    $('texthint').innerHTML = nums[1];
    $('refer_jobid').innerHTML  = "<input type='hidden' name='referjobid' value='" + job_id + "' />";
    
    var job_detail = "<p align='center'>" + nums[3] + "</p>" + nums[2] + "<p></p>";
    
    if (nums[6] == 'Request' || nums[6] == 'Display') {

      if (nums[6] == 'Request') {
        // contact details on request
        job_detail += "<div id='contactDisplay' align='left'><a href='#' onclick='countDisplay(" + job_id + "); return false;' class='redtext'>VIEW CONTACTS</a></div>";
      } else if (nums[6] == 'Display') {
        job_detail += "<div align='left' class='redtext'>Contact: " + nums[4] + "<br />Phone: " + nums[5] + "</div>";
      }
      
      residencyString = nums[8];
      shortlisted     = nums[7];
      residencySpan   = nums[9];

    } else {
      // no contacts
      residencyString = nums[5];
      shortlisted     = nums[4];
      residencySpan   = nums[6];
    }

    if (residencyString == "1") {
      $('displayStatusMsg3').innerHTML = "";
    } else {
      $('displayStatusMsg3').innerHTML = residencyString;
    }

    $('ShortValue').innerHTML        = "<input name='shortListCheck' id='shortListCheck' type='checkbox' value='Yes' onclick='return checkstatus(" + job_id + ",\"" + residencyString + "\",1);' " + shortlisted + " />";
    $('displayStatusMsg2').innerHTML = residencySpan;
    $('form_apply_status').innerHTML = "<input name='applyforjobs' type='submit' class='button2' id='job_apply' value='APPLY' onclick='pageTracker._trackPageview(\"/application/apply\"); return checkstatus(" + job_id + ",\"" + residencyString + "\",0);' />";

    job_detail += "<input type='hidden' name='job_id' value='" + job_id + "' />"
    
    $('detail_desc').innerHTML = job_detail;
    $('job_apply').disabled = false;
  }

  function clearResultDetail() {
    $('job_apply').disabled           = true;
    $('texthint').innerHTML           = "&nbsp;";
    $('detail_desc').innerHTML        = "<br /><div align='center'><img src='images/loading.gif' border='0'></div>";
    $('refer_jobid').innerHTML        = "&nbsp;";
    $('displayStatusMsg1').innerHTML  = "&nbsp;";
    $('ShortValue').innerHTML         = "&nbsp;";
    $('displayStatusMsg2').innerHTML  = "&nbsp;";
    $('displayStatusMsg3').innerHTML  = "&nbsp;";
  }

  function createHTMLResult(div_id, job_id, job_title, job_start_desc, job_location, job_published_date, job_benefits, shortlisted, cv_submitted) {
    var inner_class;
    var title_class;
    
    var div          = $('job' + div_id);
    div.div_id       = div_id;
    div.job_id       = job_id;
    div.shortlisted  = shortlisted;
    div.cv_submitted = cv_submitted;
    div.onclick      = function() {
                         focusJob(this.div_id);
                         loadResultDetail(this.job_id);
                       };
    
    switch (div_id) {
      case 1:
        inner_class = " widthFix";
        break;
      default:
        inner_class = "";
    }
    
    // shortlisted && cv_submitted
    if (cv_submitted == 1) {
      title_class = "greentext";
    } else if (shortlisted == 1) {
      title_class = "redtext";
    } else {
      title_class = "nonetext";
    }
    
    // transform data into printable stuff
    html = "<div id='resultpopup' class='leftsearchresult'>"
         +     "<div>"
         +         "<h1 id='headingJob"+ job_id +"' class='"+ title_class +"'>"+ job_title +"</h1>"+ job_start_desc
         +     "</div>"
         + "</div>"
         + "<div class='popupmessageresult" + inner_class +"'>"
         +     job_location + "<br />"
         +     job_benefits + "<br/>"
         +     job_published_date
         + "</div>"
         + "<div style='clear:both;'></div>";
    div.innerHTML = html;
}

  function resetPaging() {
  
    // set page in session
    new Ajax.Request("includes/ajax/jskSearchPage.php",
      { method: 'post',
        parameters: {page: '1'},
        onSuccess: function(transport) {
          return true;
        }
      }
    );
    
    return true;
  }

  // build the paging links under the results
  function createPaging() {
    var html = "";

    // set page in session
    new Ajax.Request("includes/ajax/jskSearchPage.php", {parameters: "page=" + current_page}, {method: 'post'});

    // reload banners
    
	var t = document.getElementById('topBanner');
    t.src = 'http://www.cogsdigital.com/adapp/adserv_launchv1.aspx?ifr=1&siteid=773&adposition=1' + '&' + Math.round(Math.random() * 10000);
	
    var b = document.getElementById('bottomBanner');
    b.src = 'http://www.cogsdigital.com/adapp/adserv_launchv1.aspx?ifr=1&siteid=773&adposition=3' + '&' + Math.round(Math.random() * 10000);
    
    // first && previous
    if (current_page > 1) {
      html += "<span class='firstnav'><a href='#' onclick='gotoFirstResults();return false;'>FIRST</a></span>";
      html += "<span class='prevnav'><a href='#' onclick='gotoPrevResults();return false;'>PREV</a></span>";
    } else {
      html += "<span class='firstnav' style='color: #ccc'>FIRST</span>";
      html += "<span class='prevnav' style='color: #ccc'>PREV</span>";
    }

    html += "<span class='numbernav'>";

    // we are at the start
    if(current_page <= 4) {
      start_page = 1;
      if(total_pages >= 8) {
        end_page = 8;
      } else {
        end_page = total_pages;
      }
    // we are at the end
    } else if(total_pages - 5 < current_page) {
        if (total_pages - 7 < 1) {
          start_page = 1;
        } else {
          start_page = total_pages - 7;
        }
        end_page = total_pages;
    // we are in the middle!
    } else {
      start_page = current_page - 3;
      end_page = current_page + 4;
    }

    // spell it out
    for (var page_number=start_page; page_number <= end_page; page_number++) {
        if (page_number != current_page) {
          html += "<a href='#' onclick='gotoPageResults("+ page_number +");return false;'>"+ page_number +"</a>";
        } else {
          html += "<strong>"+ page_number +"</strong>";
        }
        if (page_number != end_page) {
          html += " | ";
        }
    }
    
    html += "</span>";

    // next && last
    if (current_page < total_pages) {
      html += "<span class='nextnav'><a href='#' onClick='gotoNextResults();return false;'>NEXT</a></span>";
      html += "<span class='lastnav'><a href='#' onClick='gotoLastResults();return false;'>LAST</a></span>";
    } else {
      html += "<span class='nextnav' style='color: #ccc'>NEXT</span>";
      html += "<span class='lastnav' style='color: #ccc'>LAST</span>";
    }

    // replace current values
    $(id_paging_box).innerHTML = html;
  }

  // show the first page with results
  function gotoFirstResults() {
    if(current_page != 1) {
        current_page = 1;
        loadResults();
    }
  }

  // show the last page with results
  function gotoNextResults() {
    if(current_page < total_pages) {
        current_page += 1;
        loadResults();
    }
  }

  // fast forward to a specified page
  function gotoPageResults(page) {
    current_page = page;
    loadResults();
  }

  // show the previous page with results
  function gotoPrevResults() {
    if (current_page > 1) {
      current_page -= 1;
      loadResults();
    }
  }

  // show the next page with results
  function gotoLastResults() {
    if (current_page != total_pages) {
      current_page = total_pages;
      loadResults();
    }
  }

/**
 * showShortListed
 * Update the page and database when the shortlist checkbox for a job is changed. 
 *
 * @param int job_id The id of the job to be worked on
 */
  function showShortListed(job_id) {
    new Ajax.Request("includes/ajax/jskShortlistJob.php?job_id="+ job_id, {method: 'get'});
    
    // correct the class
    var job_div = $("job"+ div_translation[job_id]);
    var job_div_heading = $("headingJob"+ job_id);
    
    if ($("shortListCheck").checked) {
      job_div.shortlisted = 1;
    } else {
      job_div.shortlisted = 0;
    }

    if(job_div.cv_submitted == 1) {
      job_div_heading.className = "greentext";
    } else if (job_div.shortlisted == 1) {
      job_div_heading.className = "redtext";
    } else {
      job_div_heading.className = "nonetext";
    }
  }

  // get contact information (and record view)
  function countDisplay(job_id) {
    new Ajax.Request("includes/ajax/jskJobContact.php?job_id=" + job_id + "&sid=" + Math.random(), {
      method: 'get',
      onSuccess: countDisplayResult
    });
  }

  function countDisplayResult(transport) {
    var nums = transport.responseText.split(':sk:');
    $('contactDisplay').innerHTML = "<div align='left' class='redtext'>Contact: "+ nums[0] +"<br />Phone: "+ nums[1]+"</div>";
  }
  
  function loadShortlist(page) {
    new Ajax.Request("includes/ajax/jskShortlist.php?page=" + page + "&sid=" + Math.random(), {
      method: 'get',
      onSuccess: updateShortlist
    });
  }
  
  function updateShortlist(transport) {
    var nums = transport.responseText.split(':sk:');
    $('shortlist').innerHTML = nums[0];
  }
  
  function setStatus(status) {
    new Ajax.Request('includes/ajax/jskStatus.php?status=' + status, {
      method: 'get',
      onSuccess: function(transport) {
        // alert('', transport.responseText);
      }
    });
  }
