﻿/*============================================
  Methods
============================================*/
function getJobs(frm, lat, lng){
  // Create the post data
  var data = new Array();
  data.push('category=' + frm.category.value);
  data.push('range=' + frm.range.value);
  data.push('location=' + (frm.range.value ? escape(frm.location.value) : ''));
  if (lat && lng){
    data.push('lat=' + lat);
    data.push('lng=' + lng);
  }else if (! frm.range.value){
    data.push('lat=51.482');
    data.push('lng=0');
  }
  
  ajax.setReadyStateChanged(function (resp){
    if (! resp.responseText) return;
    
    // Parse the response and check what was returned
    var obj = eval('(' + resp.responseText + ')');
    if (obj.Jobs){
      // Set the Jobs, and write them
      jobs = obj.Jobs;
      writeJobs();
    }else if (obj.Places){
      // Set the Places and write them
      places = obj.Places;
      writePlaces();
    }else{
      alert('The place couldn\'t be found');
    }
  });
  ajax.send('POST', './getJobs.aspx', true, data.join('&'));
}

function gotoPlace(index){
  // Set the selected location
  document.getElementById('searchJobs').location.value = places[index].address

  // Get the jobs
  getJobs(document.getElementById('searchJobs'),
    places[index].lat, places[index].lng);

  // Tidy up the places
  places = null;
}

function showJobInfo(index){
  // Get the Job
  var job = jobs[index];
  var pt = new GLatLng(job.fldLat, job.fldLon);
  
  // Tabs
  var tabs = new Array();
  var content;
  
  // Info tab
  content = '<div class=\'jobInfoPosition\'>' + job.fldCategory + '</div>' +
    '<div class=\'jobInfo\'><table>' +
    '<tr><td class=\'label\'>Company:</td><td>' + job.fldCompany + '</td></tr>' +
    '<tr><td class=\'label\'>Franchise:</td><td>' + job.fldFranchise + '</td></tr>' +
    '<tr><td class=\'label\'>Salary:</td><td>' + job.fldSalary + '</td></tr>' +
    '<tr><td class=\'label\'>Hours:</td><td>' + job.fldHours + '</td></tr>' +
    '<tr><td class=\'label\'>Description:</td><td>' + job.fldDescription.replace(/\r\n/g, '<br />') + '</td></tr>' +
    '<tr><td class=\'label\'>Benefits:</td><td>' + job.fldBenefits.replace(/\r\n/g, '<br />') + '</td></tr>' +
    '<tr><td class=\'label\'>Contact:</td><td>' + job.fldContact +
    (job.fldEmail ? '<br />E: <a href=\'mailto:' + job.fldEmail + '\'>' + job.fldEmail + '</a>' : '') +
    (job.fldPhone ? '<br />T: ' + job.fldPhone : '') + '</td></tr>' +
    '<tr><td class=\'label\'>Updated:</td><td>' + job.fldUpdated.substr(0, 10) + '</td></tr>' +
    '</tr></table></div>';
  tabs.push(new GInfoWindowTab('Information', content));
  
  // Address
  content = '<div class=\'jobAddress\'>' + job.fldCompany + '<br />' +
    job.fldFormattedAddressNoOrg.replace(/\r\n/g, '<br />') + '</div>';
  tabs.push(new GInfoWindowTab('Address', content));
  
  // Location
  content = '<div id=\'detailMap\'></div>';
  tabs.push(new GInfoWindowTab('Location', content));

  gmap.openInfoWindowTabsHtml(pt, tabs);
  
  // Show the location map
  var detailMap = new GMap2(document.getElementById('detailMap'));
  detailMap.setCenter(pt, 14);
  detailMap.addOverlay(new GMarker(pt), {title: job.fldCompany});
}

function writeJobs(){
  if (! jobs) return;
  
  // Clear the existing overlays
  gmap.clearOverlays();
  
  // Bounds to zoom to
  var bounds = new GLatLngBounds();
  
  // Get the current category
  var showCategories = (document.getElementById('searchJobs').category.value == '');
  
  // Write the job options
  var info = document.getElementById('mapInfo');
  if (jobs.length){
    // At least one job was found
    info.innerHTML = 'Jobs found near <strong>' + document.getElementById('searchJobs').location.value +
      '</strong>';
    var ol = document.createElement('ol');
    ol.className = 'jobs';
    for (var i = 0; i < jobs.length; i++){
      var range = jobs[i].fldRange;
      if (range < 1){
        range = Math.round(100 * range) / 100;
      }else if (range < 10){
        range = Math.round(10 * range) / 10;
      }else{
        range = Math.round(range);
      }
    
      // Append the List item
      var li = document.createElement('li');
      var link = document.createElement('a');
      link.jobIndex = i;
      link.href = null;
      link.innerHTML = jobs[i].fldCompany;
      link.title = 'Click for more details';
      link.className = 'nohover';
      li.appendChild(link);
      link.onclick = liJob_OnClick;
      if (showCategories){
        var div = document.createElement('div');
        div.innerHTML = jobs[i].fldCategory;
        li.appendChild(div);
      }
      ol.appendChild(li);

      // Add the placemark
      var pt = new GLatLng(jobs[i].fldLat, jobs[i].fldLon);
      var marker = new GMarker(pt, {title: jobs[i].fldCompany});
      marker.jobIndex = i;
      gmap.addOverlay(marker);
      GEvent.addListener(marker, 'click', jobMarker_OnClick);
      
      // Extend the bounds over the point
      bounds.extend(pt);
    }
    info.appendChild(ol);
    var viewAll = document.createElement('a');
    viewAll.href = null;
    viewAll.innerHTML = 'View all';
    viewAll.style.fontWeight = 'bold';
    viewAll.className = 'nohover';
    viewAll.onclick = viewAll_OnClick;
    info.appendChild(viewAll);
    
    // Fit the map to the bounds
    gmap.setCenter(bounds.getCenter(), gmap.getBoundsZoomLevel(bounds));
  }else{
    // Nothing was found
    info.innerHTML = '<strong>We couldn\'t find any Positions matching the criteria given</strong>';
  }
}

function writePlaces(){
  if (! places) return;
  
  // Clear the existing overlays
  gmap.clearOverlays();
  
  // Bounds to zoom to
  var bounds = new GLatLngBounds();
  
  // Write the place options
  var info = document.getElementById('mapInfo');
  info.innerHTML = '<strong>Did you mean?</strong>';
  var ol = document.createElement('ol');
  ol.className = 'places';
  for (var i = 0; i < places.length; i++){
    // Append the List item
    var li = document.createElement('li');
    var link = document.createElement('a');
    link.href = null;
    link.innerHTML = places[i].address;
    link.placeIndex = i;
    link.className = 'nohover';
    link.onclick = liPlace_OnClick;
    li.appendChild(link);
    ol.appendChild(li);
    
    // Add the placemark
    var pt = new GLatLng(places[i].lat, places[i].lng);
    var marker = new GMarker(pt, {title: places[i].address});
    marker.placeIndex = i;
    gmap.addOverlay(marker);
    GEvent.addListener(marker, 'click', placeMarker_OnClick);
    
    // Extend the bounds over the point
    bounds.extend(pt);
  }
  info.appendChild(ol);
  
  // Fit the map to the bounds
  gmap.setCenter(bounds.getCenter(), gmap.getBoundsZoomLevel(bounds));
}


/*============================================
  Event Handlers
============================================*/
function jobMarker_OnClick(e){
  // Show the job info
  showJobInfo(this.jobIndex);
}

function liJob_OnClick(e){
  // Show the job info
  showJobInfo(this.jobIndex);

  return false;
}

function liPlace_OnClick(e){
  // Get the point to go to
  gotoPlace(this.placeIndex);

  return false;
}

function location_OnFocus(e){
  (e.srcElement ? e.srcElement : e.target).select();
}

function placeMarker_OnClick(){
  // Get the point to go to
  gotoPlace(this.placeIndex);
}

function range_OnChange(sender){
  sender.form.location.disabled = (sender.value == '');
}

function searchJobs_OnSubmit(frm){
  // Has a valid location been given
  if (frm.range.value){
    if ((! frm.location.value) || frm.location.value == 'Placename or Postcode'){
      alert('A location is needed first');
      frm.location.focus();
      return false;
    }
  }
  
  // Do the search
  getJobs(frm, null, null);

  return false;
}

function viewAll_OnClick(e){
  // Zoom to all the results
  var bounds = new GLatLngBounds();
  for (var i = 0; i < jobs.length; i++){
    bounds.extend(new GLatLng(jobs[i].fldLat, jobs[i].fldLon));
  }
  gmap.setCenter(bounds.getCenter(), gmap.getBoundsZoomLevel(bounds));
  
  return false;
}
