// Surprise! IE doesn't have an indexOf Array method. D'oh!
// No matter, we'll add our own here if it doesn't exist already.
if (!Array.indexOf) {
  Array.prototype.indexOf = function(obj) {
    var i, length = this.length;
    for (i = 0; i < length; i++) {
      if (this[i] === obj) return i;
    };

    // If item does not exist in the array, return -1.
    return -1;
  };
};

// Stub out console.log, console.warn and console.error in case 
if (!window.console) {
  function noOp (string) { return; }

  var console = {
    log: noOp,
    warn: noOp,
    error: noOp
  };
};

var SHS_BUILD = 'shs.I76.14563M';
var SHS_KEY;
var SHS = {
  // Default environment variables. Do not change these here.
  build: SHS_BUILD,
  environment: "prod",
  domain: 'www.searshomeservices.com',
  original_static_path: '/:build/shs',
  dynamic_path: '/shs',
  protocol: 'http://',
  method:'GET',

  document: document,

  // If jQuery already exists on the page, and it's greater than or equal to 1.4
  // then just use the existing one for our code. Otherwise, load up jQuery 1.4
  // from our server.
  // Finally, return the newly loaded up version of jQuery.
  setJQuery: function(callback){
    if (SHS.$) {
      if (callback) { callback(); }
      return SHS.$;

    } else if (window.jQuery14 && window.jQuery14.fn.jquery >= "1.4") {
      SHS.$ = window.jQuery14
      loadJQPlugins();
      if (callback) { callback(); }

    } else {
      SHS.load('js', SHS.urlFor('/pes/standalone/jquery-1.4.2.min.js'), "jQuery14", function() {
        SHS.$ = window.jQuery14;
        loadJQPlugins();
      });
    };

    function loadJQPlugins () {
      SHS.load('js', SHS.urlFor('/pes/standalone/jquery-ui-1.8.custom.min.js'), 'jQuery14.ui', function() {
        SHS.load('js', SHS.urlFor('/pes/standalone/jquery.iframe.js'), 'jQuery14.fn.src', function() {
          SHS.load('js', SHS.urlFor('/pes/standalone/jquery.bgiframe.min.js'), 'jQuery14.fn.bgIframe', function() {
            if (callback) callback();
            return SHS.$;
          });
        });
      });
    }
    return false;
  },

  urlFor: function(path){
    var i, j,
        self = this,
        parts = [],
        paths = [this.domain, static_or_dynamic_path(), path],
        pathsLength = paths.length;

    for (i = 0; i < pathsLength; i++) {
      var p = paths[i],
          pathParts = p.match(/[\w\.\-\_\:]+/g),
          pathPartsLength = (pathParts && pathParts.length) || 0;

      if (p) {
        for (j = 0; j < pathPartsLength; j++) {
          var part = pathParts[j];
          if (part.length > 0) parts.push(part);
        }
      };
    };

    function static_or_dynamic_path () {
      return ((/\.(jpg|gif|png|js|css)$/).test(path) ? self.static_path : self.dynamic_path);
    }

    return this.protocol + parts.join("/");
  },

  sanitizePath: function() {
    SHS.static_path = SHS.original_static_path.replace(/\:build/, SHS.build) + "/";
    SHS.static_path = SHS.static_path.replace(/\/\//, "/");
    return SHS.static_path;
  },

  init: function(callback){
    var self = this;
    this.setJQuery(function() {
      SHS.load('js', SHS.urlFor('/pes/standalone/shs.validations.js'), "SHS.Validations", function() {
        SHS.load('js', SHS.urlFor('/pes/standalone/shs.lightbox.js'),'SHS.LightBox',function(){
          SHS.load('js', SHS.urlFor('/pes/standalone/shs.storelocator.js'),'SHS.StoreLocator',function(){
            SHS.load('js', SHS.urlFor('/pes/standalone/shs.scheduler.js'), "SHS.Scheduler", function() {
              SHS.load('js', SHS.urlFor('/pes/standalone/shs.automotive.js'), 'SHS.Automotive', function() {
                SHS.load('js', SHS.urlFor('/pes/standalone/shs.report.js'), "SHS.Report", function() {
                  SHS.load('js', SHS.urlFor('/pes/standalone/shs.maps.js'), 'SHS.Maps', function() {
                    callback();
                    self.loaded = true;
                  });
                });
              });
            });
          });
        });
      });
    });
  },

  secure_init: function(callback){
      SHS.protocol = 'https://';
      SHS.load('js', SHS.urlFor('/pes/standalone/SHS.rsa.js'), 'SHS.RSA', function() {
        SHS_KEY = new RSAKey();
        SHS_KEY.setPublic(
          "DEF68DAD6E9788770C165EB386AEFC46B706EF2F9D3EF07F177BFB65BAF401C49A69D47872A1576ACA5AA4607C32A37E98F152F903E05BC59C842C4E6711A6E39968EBD9F0C88CBD6B9D9D424B88AA37DE3292A0275DAEC76918DFA65C49D02736BCCBB8229F2BC0EEF1F31BF579BB737FC7C7B8F4B1F721B175E4DC05255EB7",
          "10001"
        );
        SHS.init(callback);
      });
  }
};


SHS.sanitizePath();

SHS.Loader = function() {
  var head = document.getElementsByTagName('head')[0];

  function createCSS (url) {
    var s = document.createElement('link');
    s.setAttribute('rel', 'stylesheet');
    s.setAttribute('type', 'text/css');
    s.setAttribute('media', 'screen');
    s.setAttribute('href', url);
    return s;
  }

  function createJS (url) {
    var s = document.createElement('script');
    s.setAttribute('type', 'text/javascript');
    s.setAttribute('src', url);
    return s;
  }

  function setOnLoadFor (watch, callback) {
    var timer = setInterval(function() {
      if (watchExists(watch)) {
        clearInterval(timer);
        if (callback) callback();
      };
    }, 50);
  }

  function insertElement (element) {
    (head)? head.appendChild(element) : document.body.appendChild(element);
  }

  function load (type, url, watch, callback) {
    var element;

    if (type == 'css'){
      element = createCSS(url);
    } else if (type == 'js'){
      element = createJS(url);
    }

    if (!watchExists(watch) && element !== undefined) {
      if (callback) setOnLoadFor(watch, callback);
      insertElement(element);
    }
  }

  function watchExists (watch) {
    return eval("typeof " + watch) != 'undefined';
  }

  return { load: load };
}();

SHS.load = SHS.Loader.load;

