oobayly / AutoVRM4All

// ==UserScript==
// @name       AutoVRM4All
// @namespace  https://github.com/oobayly
// @version    0.1.4
// @description  Automatically populates the VRM, Miles, VIN, etc
// @grant      none
// @match      http://bimmer.work/*
// @match      http://carnapper.co.uk/car/*
// @match      http://gnnew.glass-net.co.uk/*
// @match      https://www.vehicleenquiry.service.gov.uk/*
// @match      https://www.check-mot.service.gov.uk/*
// @match      https://valuationanywhere.cap.co.uk/*
// @copyright  2015 - A subscriber who wanted more.
// @require    http://code.jquery.com/jquery-latest.js
// @require    https://cdnjs.cloudflare.com/ajax/libs/jquery-dateFormat/1.0/jquery.dateFormat.min.js
// ==/UserScript==

// See http://wiki.greasespot.net/@grant
this.$ = this.jQuery = jQuery.noConflict(true);

$(document).ready(function() {
  var TYPES = {
    INVALID: null,
    BIMMER_WORK: /bimmer.work/,
    CAR_NAPPER: /carnapper.co.uk/,
    DVLA_VEHICLE_ENQUIRY: /www.vehicleenquiry.service.gov.uk/,
    DVLA_MOT_HISTORY: /www.check-mot.service.gov.uk/,
    GLASS_NET: /gnnew.glass-net.co.uk/,
    VALUATION_ANYWHERE: /valuationanywhere.cap.co.uk/
  };

  var params = {
    path: null,
    type: TYPES.INVALID,
    manufacturer: null,
    miles: null,
    vin: null,
    vrm: null,
    // CAP ID lookup
    capID: null,
    month: null,
    year: null,
    // Glass Code lookup
    glassCode: null
  };

  var main = function() {
    parseArgs();
    
    switch (params.type) {
      case TYPES.BIMMER_WORK: {
        if (params.vin) {
          $("input[name='vin']").val(params.vin.substr(-7));
        }
        break;
      }

      case TYPES.CAR_NAPPER: {
        $(".display-none").removeClass("display-none");
        $("#disable-gallery").remove();
        $(".hidden-image").removeClass("hidden-image");
        break;
      }
        
      case TYPES.DVLA_MOT_HISTORY:
      case TYPES.DVLA_VEHICLE_ENQUIRY: {
        if ($("form").length) {
          vrmLookupDVLA();
        } else if (params.type === TYPES.DVLA_VEHICLE_ENQUIRY) {
          injectCopyDVLA();
        }
        break;
      }
        
      case TYPES.GLASS_NET: {
        if (params.path === "" || params.path === "index" || params.path === "Default.aspx" || params.path === "mobile-index") {
          if (params.glassCode) {
          } else if (params.vrm || params.miles) {
            vrmLookupGlass();
          }
        } else if ((/^(mobile-vehicle\/vehicle-valuation|mobile-vrm-lookup)/).test(params.path)) {
          //addGlassCodeLink();
          injectCopyGlass();
        }
        break;
      }
        
      case TYPES.VALUATION_ANYWHERE: {
        if (params.path === "" || (/^default(.aspx)?/i).test(params.path)) {
          if (params.capID) {
            capIDLookup();
          } else if (params.vrm || params.miles) {
            vrmLookupCap();
          }
        } else if ((/^Valuation(\.aspx)?/i).test(params.path)) {
          injectCapIDLink();
          injectCopyCap();
        }
        
        // We already pay for the damn service, why do we need an advert taking up half the page.
        $("#blackbookplus-upgrade").remove();
        break;
      }
        
      default:
        break;
        
    }
  };
  
  var capIDLookup = function() {
    $("#vlBrowse a")[0].click();

    $("#capIDcont input").val(params.capID);
    $("#vmMMDMile input").val(params.miles);

    var sel = $("#vlReg select");
    sel.first().val(params.month);
    sel.last().val(params.year);

    window.setTimeout(function() {
      $("#SearchCAPid a")[0].click();
    }, 250);
  };
  
  // Copies the specified object to the clipboard as a JSON encoded string
  var copyData = function(data) {
    var vals = "";
    for (var key in data) {
      vals += key + ":" + data[key] + "\n";
    }

    var text = $("<pre></pre>");
    text.html(vals);
    
    $(document.body).append(text);
    var range = document.createRange();
    range.selectNode(text[0]);
    window.getSelection().addRange(range);

    try {  
      // Now that we've selected the anchor text, execute the copy command  
      document.execCommand('copy');  
    } catch(err) {  
      alert("Couldn't copy text to clipboard: " + err);
    } finally {
    }
  };
  
  // Formats the specified text as a date
  var getDate = function(text, format) {
    return $.format.date(Date.parse(text), format || "dd/MM/yy");
  }
  
  var injectCapIDLink = function() {
    // Get the mileage
    var miles = $("#your-mileage").val().replace(/[^0-9]/g, "");

    // Information is now stored in the summary table
    var items = $(".summary-container .list-table li");

    // Registration date
    var dateField = items.find("span:contains('Registration Date')");
    var regDate = new Date(dateField.next().text());
    var month = regDate.getMonth() + 1;
    var year = regDate.toLocaleString("en-GB", { year: "numeric" });

    // Derivative description - search the manufacturer-panel for something that looks like a CAP ID
    var idContainer = null;
    var id, derivative;
    for (var item of $(".manufacturer-panel .col-car-details li").toArray()) {
      var match = $(item).text().match(/^\[([0-9]+)\] (.+)/);
      if (match) {
        idContainer = $(item);
        id = match[1];
        derivative = match[2];
        break;
      }
    }

    if (!id)
      return;

    idContainer.empty();
    $("<a>", {
      href: "/#" + JSON.stringify({
        capID: id,
        miles: miles,
        month: month,
        year: year
      }),
      title: "Use this to find another a similar vehicle.",
      target: "_blank",
    }).text("[" + id + "]").appendTo(idContainer);
    $("<span>").text(" " + derivative).appendTo(idContainer);
  };
  
  var injectCopyCap = function() {
    var button = $("<button>", {
      "class": "copy_button btn btn-sm cap-btn-green",
    });
    button.text("Copy Valuation Values");
    $("#fn_ShowPDFDialog").after(button);
    button.before(document.createTextNode(" "));

    button.on("click", function(e) {
      try {
        var data = {};

        var monthly = $("#blackbookTplWrapper .table-va-values");
        var live = $("#blackbookLiveTplWrapper .table-va-values");

        data.CAPClean = monthly.find(".clean").text().replace(/[^0-9]/g, "");
        data.CAPAverage = monthly.find(".average").text().replace(/[^0-9]/g, "");
        data.CAPBelow = monthly.find(".below").text().replace(/[^0-9]/g, "");
        data.CAPLiveClean = live.find(".clean").text().replace(/[^0-9]/g, "");
        data.CAPLiveAverage = live.find(".average").text().replace(/[^0-9]/g, "");
        data.CAPLiveBelow = live.find(".below").text().replace(/[^0-9]/g, "");

        data.CAPMileage = $("#your-mileage").val();
        data.CAPDate = $("#your-date").val();

        // Information is now stored in the summary table
        var items = $(".summary-container .list-table li");
        var field;

        // VED
        field = items.find("span:contains('Vehicle Excise Duty')");
        data.VED = field.next().text();

        // ID
        field = items.find("span:contains('CAP ID')");
        data.CAPID = field.next().text();

        // Vehicle description
        field = items.find("span:contains('Manufacturer')");
        data.CAPNotes = field.next().text();
        field = items.find("span:contains('Model')");
        data.CAPNotes += " " + field.next().text();
        field = items.find("span:contains('Trim')");
        data.CAPNotes += " " + field.next().text();
        
        copyData(data);
        
      } catch (e) {
        console.error(e);
        alert("Data couldn't be copied:\n" + e);
        
      }
    
      e.preventDefault();
    });
  };
  
  var injectCopyDVLA = function() {
    var button = $("<input>", {
        type: "button",
        value: "Copy Details",
        "class": "button",
    });
    $(".registrationNumber").parent().after(button);

    button.on("click", function(e) {
      var data = {
        MOTDue: getDate($(".isValidMot p, .isInvalidMot p").text().split(/:/)[1].trim(), "MM/yy"),
        VEDDue: getDate($(".isValidTax p, .isInvalidTax p").text().split(/:/)[1].trim(), "MM/yy")
      };

      copyData(data);
    });
  };
  
  var injectCopyGlass = function() {
    var button = $("<input>", {
      type: "button",
      value: "Copy Valuation Values",
      "class": "mainBT w0BT",
    });
    $("input[name='mileage_submit']").after(button);

    button.on("click", function(e) {
      try {
        var container = $(".valuation_result");
        
        var data = {};

        data.GlassValue = parseInt(container.find("span:contains('Basic value')").first().next().text().replace(/[^0-9.]/g, ""));
        data.GlassTotal = parseInt(container.find("span:contains('Adjusted value total')").first().next().text().replace(/[^0-9.]/g, ""));
        data.GlassAdjustmentMiles = parseInt($("#mileage").val()) / 1000;
        data.GlassDate = $(".val_from").text().replace(/Valuation for /, "");

        // Vehicle description
        data.GlassNotes = $("div.fl.head_techinfo").text();

        copyData(data);
        
      } catch (e) {
        console.error(e);
        alert("Data couldn't be copied:\n" + e);
        
      }
      
      e.preventDefault();
    });
  };

  // Parse the URL arguments
  var parseArgs = function() {
    var path = window.location.pathname.substr(1);
    params.path = path;

    var parsed = null;
    if (window.location.hash) {
      var hash = decodeURIComponent(window.location.hash.substr(1));
      try {
        parsed = JSON.parse(hash);
        if (typeof parsed !== "object")
            parsed = null;
      } catch (e) {
        console.log("Couldn't parse '" + hash + "': " + e);
      }
    }

    if (!parsed) {
      parsed = {};

      // Parse the URI and extract all the QueryString name-value pairs
      querystring = window.location.search;
      querystring = querystring.substring(querystring.indexOf('?')+1).split('&');
      var pair;
      // march and parse
      for (var i = querystring.length - 1; i >= 0; i--) {
        pair = querystring[i].split('=');
        parsed[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
      }
    }

    $.extend(params, parsed);
    
    // Fix any invalid parameters
    if (!(params.miles = parseInt(params.miles)))
      params.miles = null;
    if (params.vin)
      params.vin = params.vin.toLocaleUpperCase().replace(/\s/g, "");
    if (params.vrm)
      params.vrm = params.vrm.toLocaleUpperCase().replace(/\s/g, "");
    
    // Determine which page is being viewed
    $.each(TYPES, function(key, item) {
      if (window.location.hostname.match(item)) {
        params.type = TYPES[key];
      }
    });
  }
  
  var vrmLookupCap = function() {
    // Round miles up to the next 1000
    var miles = 1000 * Math.ceil((params.miles || 0) / 1000, 0);

    if (params.vrm)
      $("#tbVRM").val(params.vrm);
    if (miles)
      $("#tbMiles").val(miles);

    // Only execute the search if we have both the VRM and the Mileage
    if (params.vrm && miles) {
      $(".fn_VRMLookup")[0].click();
    }
  }
  
  var vrmLookupDVLA = function() {
    console.log(params);
    var man = (params.manufacturer || "").toLocaleUpperCase();
    switch (man) {
      case "MG Motor":
        man = "MG";
        break;
        
      case "Rolls-Royce":
        man = "ROLLS ROYCE";
        break;
        
    }
    
    if (params.type === TYPES.DVLA_MOT_HISTORY) {
      $("#registration").val(params.vrm || "");
      $("#manufacturer").val(man);

      if (params.vrm && man)
        $("div.action input[type='submit']").trigger("click");
      
    } else if (params.type === TYPES.DVLA_VEHICLE_ENQUIRY) {
      $("#MainContent_txtSearchVrm").val(params.vrm || "");
      $("#MainContent_MakeTextBox").val(man);

      if (params.vrm && man)
        $("#MainContent_butSearch").trigger("click");
      
    }
  }
  
  var vrmLookupGlass = function() {
    var isMobile = (params.path === "mobile-index");
    
    // Round miles up to the next 1000
    var miles = 1000 * Math.ceil((params.miles || 0) / 1000, 0);
    
    if (params.vrm) {
      if (isMobile) {
        $("#registration_number").val(params.vrm);
      } else {
        $("#vrms_reg_no").val(params.vrm);
      }
    }
    if (miles) {
      if (isMobile) {
        $("#mileage").val(miles);
      } else {
        $("#vrms_mileage").val(miles);
      }
    }

    // Only execute the search if we have both the VRM and the Mileage
    if (params.vrm && miles) {
      if (isMobile) {
        $("#login_submit").trigger("click");
      } else {
        $("#find_value_vrm").trigger("click");
      }
    }
  }

  main();
});