/* jshint node: true */
/* global document, location, Primus: false */
'use strict';

var url = require('url');
var reTrailingSlash = /\/$/;

/**
  ### loadPrimus(signalhost, callback)

  This is a convenience function that is patched into the signaller to assist
  with loading the `primus.js` client library from an `rtc-switchboard`
  signaling server.

**/
module.exports = function(signalhost, callback) {
  var script;
  var baseUrl;
  var basePath;
  var scriptSrc;

  // if the signalhost is a function, we are in single arg calling mode
  if (typeof signalhost == 'function') {
    callback = signalhost;
    signalhost = location.origin;
  }

  // read the base path
  baseUrl = signalhost.replace(reTrailingSlash, '');
  basePath = url.parse(signalhost).pathname;
  scriptSrc = baseUrl + '/rtc.io/primus.js';

  // look for the script first
  script = document.querySelector('script[src="' + scriptSrc + '"]');

  // if we found, the script trigger the callback immediately
  if (script && typeof Primus != 'undefined') {
    return callback(null, Primus);
  }
  // otherwise, if the script exists but Primus is not loaded,
  // then wait for the load
  else if (script) {
    script.addEventListener('load', function() {
      callback(null, Primus);
    });

    return;
  }

  // otherwise create the script and load primus
  script = document.createElement('script');
  script.src = scriptSrc;

  script.onerror = callback;
  script.addEventListener('load', function() {
    // if we have a signalhost that is not basepathed at /
    // then tweak the primus prototype
    if (basePath !== '/') {
      Primus.prototype.pathname = basePath.replace(reTrailingSlash, '') +
        Primus.prototype.pathname;
    }

    callback(null, Primus);
  });

  document.body.appendChild(script);
};
@@ -83,34 +83,8 @@
 ';%0A%0A
-var url = require('url');%0A
 var 
@@ -108,16 +108,16 @@
  /%5C/$/;%0A
+
 %0A/**%0A  #
@@ -378,16 +378,60 @@
 back) %7B%0A
+  var anchor = document.createElement('a');%0A
   var sc
@@ -455,24 +455,8 @@
 rl;%0A
-  var basePath;%0A
   va
@@ -644,24 +644,100 @@
 rigin;%0A  %7D%0A%0A
+  // initialise the anchor with the signalhost%0A  anchor.href = signalhost;%0A%0A
   // read th
@@ -805,53 +805,8 @@
 ');%0A
-  basePath = url.parse(signalhost).pathname;%0A
   sc
@@ -1618,24 +1618,31 @@
     if (
-basePath
+anchor.pathname
  !== '/'
@@ -1683,16 +1683,23 @@
 e = 
-basePath
+anchor.pathname
 .rep
@@ -1844,6 +1844,7 @@
 t);%0A
-
 %7D;
+%0A

Use an a tag to parse the href