﻿/*============================================
  Enumerations
============================================*/
var TableType = {
  "Search": 1,
  "Saved": 2,
  "Matched": 3
};


/*============================================
  Structures
============================================*/
var Sorting = {
  "Field": '',
  "Direction": 1
};


/*============================================
  Methods
============================================*/
function buildResults(){
  // Set the default type
  var type = tableType ? tableType : TableType.Search;

  var searchRecords = document.getElementById('searchRecords');
  var searchResults = document.getElementById('searchResults');
  
  // Set the Results text
  if (vehicles.Vehicles.length == 0){
    // What type of results are these
    switch (type){
      case TableType.Search:
        searchRecords.innerHTML = 'No Vehicles could be found matching the specified criteria.';
        break;
      case TableType.Matched:
        searchRecords.innerHTML = 'No vehicles could be found matching your Buying Profile.';
        break;
      case TableType.Saved:
        searchRecords.innerHTML = 'You currently have no saved vehicles.';
        break;
    }
  }else{
    // Get the Max Allowed Results
    var allowed = vehicles.Allowed ? vehicles.Allowed : 250;
  
    // What type of results are these
    switch (type){
      case TableType.Search:
        if (vehicles.Vehicles.length == allowed){
          searchRecords.innerHTML = 'Over ' + allowed + ' Vehicles(s) found, ' +
            'this is more than the maximum number that can be displayed.<br />' +
            'Please refine your search.';
        }else{
          searchRecords.innerHTML = vehicles.Vehicles.length + ' Vehicle(s) found.';
        }
        break;
      case TableType.Saved:
        searchRecords.innerHTML = vehicles.Vehicles.length + ' Vehicle(s) saved.';
        break;
      case TableType.Matched:
        searchRecords.innerHTML = vehicles.Vehicles.length + ' Vehicle(s) matched.';
        break;
    }
  }
  
  var tbody = searchResults.tBodies[0];
  // Remove the existing rows from the table body
  while (tbody.rows.length > 0){
    tbody.deleteRow(0);
  }
  // Fill the Search Results
  if (vehicles.Vehicles.length){
    for (var i = 0; i < vehicles.Vehicles.length; i++){
      // Create the Table row
      var tr = document.createElement('tr');
      if (i % 2 == 1) tr.className = 'hl';
      tr.style.cursor = 'pointer';
      tr.onclick = row_OnClick;
      tr.title = 'Click on Vehicle to view it\'s details';
      
      // Create the cells
      var td;
      td = document.createElement('td');
      td.innerHTML = vehicles.Vehicles[i].fldVehicle;
      tr.appendChild(td);
      td = document.createElement('td');
      td.innerHTML = vehicles.Vehicles[i].fldYearLetter;
      tr.appendChild(td);
      td = document.createElement('td');
      td.innerHTML = vehicles.Vehicles[i].fldBodyTypeDesc;
      tr.appendChild(td);
      td = document.createElement('td');
      td.innerHTML = vehicles.Vehicles[i].fldFuelType;
      tr.appendChild(td);
      td = document.createElement('td');
      td.innerHTML = vehicles.Vehicles[i].fldTransType;
      tr.appendChild(td);
      td = document.createElement('td');
      td.innerHTML = vehicles.Vehicles[i].fldMiles;
      tr.appendChild(td);
      td = document.createElement('td');
      td.innerHTML = vehicles.Vehicles[i].fldDate;
      tr.appendChild(td);
      td = document.createElement('td');
      td.innerHTML = vehicles.Vehicles[i].fldStatus.substr(0,1) ;
      tr.appendChild(td);
      td = document.createElement('td');
      td.className = 'options';
      if (vehicles.Vehicles[i].fldUserID){
        var img = document.createElement('img');
        img.width = img.height = '16';
        if (type == TableType.Search || type == TableType.Matched){
          img.src = '/images/tools/save.png';
          img.alt = img.title = 'Save this Vehicle';
          img.onclick = saveTicket_OnClick;
        }else{
          img.src = '/images/tools/delete.png';
          img.alt = img.title = 'Remove this Vehicle';
          img.onclick = removeTicket_OnClick;
        }
        td.appendChild(img);
      }
      if (vehicles.Vehicles[i].fldHasPhotos){
        img = document.createElement('img');
        img.width = img.height = '16';
        img.src = '/images/tools/camera.png';
        img.alt = img.title = 'View photos';
        img.onclick = viewPhoto_OnClick;
        td.appendChild(img);
      }
      tr.appendChild(td);

      tbody.appendChild(tr);
    }
  }else{
    // Add a full span cell
    var tr = document.createElement('tr');
    var td = document.createElement('td');
    td.colSpan = 9;
    td.innerHTML = 'There is nothing to display';
    td.style.textAlign = 'center';
    tr.appendChild(td);
    tbody.appendChild(tr);
  }
  
  // Hide the Search help if it exists
  if (document.getElementById('searchHelp')){
    document.getElementById('searchHelp').style.display = 'none';
    searchRecords.style.display = 'block';
    try{
      searchResults.style.display = 'table';
    }catch (ex){
      searchResults.style.display = 'block';
    }
  }
}


/*============================================
  Event Handlers
============================================*/
function printResults_OnClick(){
  var obj = document.getElementById('searchResults');

  try{
    obj.style.display = 'table';
    printObject(obj, 'TipsTrade Vehicle Search Results');
  }catch (ex){
    /*  IE
        When setting the style.display to block, the change isn't reflected in the
        style attribute, so it's not displayed in the next window (The default display property is 'none')
        So, just print the whole damn page
    */
    window.print();
  }
}

function removeTicket_OnClick(e){
  if (confirm('Are you sure you want to remove this Vehicle?')){
    // Get the vehicle
    var vehicle = vehicles.Vehicles[this.parentNode.parentNode.sectionRowIndex];
     
    // Send the request to remove the message
    ajax.setReadyStateChanged(function (resp){
      // Test the resposne
      var reTicket = /^[\d]{6}[A-Z]{2}[\d]{4}$/;
      if (reTicket.test(resp.responseText)){
        // Get the index of the ticket removed
        var index = -1;
        for (var i= 0; i < vehicles.Vehicles.length; i++){
          if (vehicles.Vehicles[i].fldTicketID == resp.responseText){
            index = i;
            break;
          }
        }
        
        // Remove the Item
        vehicles.Vehicles.splice(index, 1);
        buildResults(vehicles.Vehicles);
        
        alert('The Vehicle has been removed');
      }else{
        alert(resp.responseText);
      }
    });
    ajax.send('GET', '/vehicles/ticket.aspx?id=' + vehicle.fldTicketID +
      '&action=remove', true, null);
  }
 
  // Don't allow the event to propagate
  if (window.event) window.event.cancelBubble = true;
  if (e.stopPropagation) e.stopPropagation();
}

function saveTicket_OnClick(e){
  // Get the vehicle
  var vehicle = vehicles.Vehicles[this.parentNode.parentNode.sectionRowIndex];
  
  // Send the request to save the message
  ajax.setReadyStateChanged(function (resp){
    if (resp.responseText) alert(resp.responseText);
  });
  ajax.send('GET', '/vehicles/ticket.aspx?id=' + vehicle.fldTicketID +
    '&action=save', true, null);
  
  // Don't allow the event to propagate
  if (window.event) window.event.cancelBubble = true;
  if (e.stopPropagation) e.stopPropagation();
}

function sortResults_OnClick(order){
  // Set the default type
  var type = tableType ? tableType : TableType.Search;

  // Which field should be sorted by
  switch (Math.abs(order)){
    case 1:
      Sorting.Field = 'fldVehicle';
      break;
    case 2:
      Sorting.Field = 'fldYearLetter';
      break;
    case 3:
      Sorting.Field = 'fldBodyTypeDesc';
      break;
    case 4:
      Sorting.Field = 'fldFuelType';
      break;
    case 5:
      Sorting.Field = 'fldTransType';
      break;
    case 6:
      Sorting.Field = 'fldMiles';
      break;
    case 7:
      Sorting.Field = 'fldDate';
      break;
    case 8:
      Sorting.Field = 'fldStatus';
      break;
  }
  // What direction was the sort requested
  if (order < 0){
    Sorting.Direction = -1;
  }else{
    Sorting.Direction = 1;
  }
  
  // Sort the Vehicles
  vehicles.Vehicles.sort(function(item1, item2){
    // Get the field that we want to sort by
    var obj1 = eval('item1.' + Sorting.Field);
    var obj2 = eval('item2.' + Sorting.Field);
    
    // Return the sort result
    if (obj1 > obj2) return 1 * Sorting.Direction;
    if (obj1 < obj2) return -1 * Sorting.Direction;
    return 0;
  });

  // Rebuild the Results table
  buildResults(vehicles.Vehicles);
}

function row_OnClick(e){
  // Get the Ticket details
  var ticket = vehicles.Vehicles[this.sectionRowIndex];
  
  // Generate the HTML for the Popup
  var title = 'Vehicle ID: ' + ticket.fldTicketID.substr(4,8);
  var text = '<div style=\'text-align: center;\'>' + 
    ticket.fldVehicle + '<br />' + 
    ticket.fldBodyTypeDesc + ', ' + ticket.fldFuelType + ', ' + 
    ticket.fldTransType + '<br />' + 
    ticket.fldMiles + ' miles<br />' + 
    'Origin: ' + ticket.fldOrigin + '<hr />' +
    'Status: ' + ticket.fldStatus + '<br />' +
    'For more details, please call quoting ' + ticket.fldTicketID.substr(4,8);
  
  // If the Vehicle's Reg # was given or it has an Image
  if (ticket.fldRegNumber){
    text += '<hr />Reg Number: ' + ticket.fldYearLetter +
      (ticket.fldRegNumber ? ' (' + ticket.fldRegNumber + ')' : '');
  }else if (ticket.fldHasImage){
    text += '<hr /><img src=\'http://intra.tipstrade.net/regnumbers/' +
      ticket.fldTicketID + '\' width=\'380px\' height=\'38px\' alt=\'Reg Number\' />';
  }
  // If there is in image, show the colour
  if (ticket.fldHasImage){
    text += '<hr /><img src=\'http://intra.tipstrade.net/colours/' +
      ticket.fldTicketID + '\' width=\'380px\' height=\'45px\' alt=\'Colour\' />';
  }
  
  text += '</div>';

  // Show the popup
  popup.Open(null, title, text);
}

function viewPhoto_OnClick(e){
  // Get the Ticket details
  var ticket = vehicles.Vehicles[this.parentNode.parentNode.sectionRowIndex];
  
  // Show the popup
  var parms = 'status=0,toolbar=0,location=0,menubar=0,width=646,height=530';
  if (screen.width) parms += ',left=' + parseInt((screen.width - 646) /2);
  if (screen.height) parms += ',top=' + parseInt((screen.height - 530) /2);
  var win = window.open('/vehicles/photos.aspx?id=' + ticket.fldTicketID, null,
    parms, true);
  
  // Don't allow the event to propagate
  if (window.event) window.event.cancelBubble = true;
  if (e.stopPropagation) e.stopPropagation();
}