/* Copyright (c) 2006 Xprima.com Corporation, All Rights Reserved */
/*
============================= Notes ================================
Author(s):
  Francis Caporuscio

Dependencies:
  YAHOO
  YAHOO.util.Dom
  YAHOO.util.Connect
====================================================================
*/



/* -------------------------------------------------------------- */
/* Missing Elements/Functions - Verify and Update                 */
/* -------------------------------------------------------------- */
/*
if(typeof(undefined) == "undefined") {
  undefined = "undefined";
}
*/

if(typeof(Function.prototype.apply) == "undefined") {
  /* apply() function obtained on youngpup.net -- also where prototype got it */
  Function.prototype.apply = function(oScope, args) {
    var sarg = [];
    var rtrn, call;

    if (!oScope) oScope = window;
    if (!args) args = [];

    for (var i = 0; i < args.length; i++) {
      sarg[i] = "args[" + i + "]";
    }

    call = "oScope.__applyTemp__(" + sarg.join(",") + ");";
    oScope.__applyTemp__ = this;
    rtrn = eval(call);
    delete oScope.__applyTemp__;
    return rtrn;
  }
}

if(typeof(Array.prototype.push) == "undefined") {
  Array.prototype.push = function() {
    for(var i = 0; i < arguments.length; i++) {
      this[this.length] = arguments[i];
    }
  };
}

if(typeof(Array.prototype.pop) == "undefined") {
  Array.prototype.pop = function() {
    element = this[this.length - 1];
    this.length--;
    return element;
  };
}

if(typeof(Array.prototype.shift) == "undefined") {
  Array.prototype.shift = function() {
    var i = 0;
    var b = this[0];
    for(i; i < this.length - 1; i++)
      this[i] = this[i+1];
    this.length--;
    return b
  };
}



/* -------------------------------------------------------------- */
/* Miscellaneous Functions                                        */
/* -------------------------------------------------------------- */
function $e() {
  var elements = new Array();
  for (var i = 0; i < arguments.length; i++) {
    var element = arguments[i];
    if(typeof element == 'string') {
      element = document.getElementById(element);
    }
    
    if (arguments.length == 1)
      return element;
    
    elements.push(element);
  }
  return elements;
}

function getCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  }
  else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if(end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}


/* -------------------------------------------------------------- */
/* XLib                                                           */
/* -------------------------------------------------------------- */
var XLib = new Object();

XLib.getElement = function(elemid) { return document.getElementById(elemid); }
XLib.setDisplayStyle = function(obj, display) { obj.style.display = display; }

XLib.browserInfo = { browserSupported: true, majVer:0, minVer:0, isIE:false, agent:"" };
XLib.browserInfo.agent = navigator.userAgent.toLowerCase();
XLib.browserInfo.IsIE = XLib.browserInfo.agent.indexOf("msie") != -1;
if(XLib.browserInfo.IsIE) {
  XLib.browserInfo.majVer = navigator.appVersion.match(/MSIE (.)/)[1];
  XLib.browserInfo.minVer = navigator.appVersion.match(/MSIE .\.(.)/)[1];
  if(XLib.browserInfo.majVer < 6) {
    XLib.browserInfo.browserSupported = false;
  }
}

XLib.setInnerHTML = function(obj, html)
{
  if(obj != null) {
    try { obj.innerHTML = html; }
    catch(err) {}
  }
}

XLib.getCheckBoxesWithPartialName = function(partialname, checked)
{
  var e = new Array();
  var elements = document.getElementsByTagName("INPUT");
  for(var i = 0; i < elements.length; i++) {
    var attr = elements[i].getAttribute("TYPE");
    if(attr != null && attr.toUpperCase() == "CHECKBOX") {
      var name = elements[i].getAttribute("NAME");
      if(name != null && name.toLowerCase().substring(0, partialname.length) == partialname.toLowerCase()) {
        if(checked == null || (checked && elements[i].checked)) {
          e[e.length] = elements[i];
        }
      }
    }
  }
  return e;
}

XLib.fader = function(objid, opacity, step, speed, display)
{
  o = document.getElementById(objid);
  if(o != null) {
    try { o.style.MozOpacity=opacity / 100; }
    catch(e) {}
    try { o.filters.alpha.opacity=opacity; }
    catch(e) {}

    n_opacity = opacity + step;
    params = "'" + objid + "'," + n_opacity + "," + step + "," + speed + ",'" + display + "'";

    if(n_opacity < 100 && n_opacity > 0) {
      o.style.display = 'block';
      setTimeout('XLib.fader(' + params + ')', speed);
    }
    else {
      if(n_opacity <= 0) o.style.display = display;
    }
  }
}

XLib.setOpacity = function(o, opacity)
{
  if(o != null) {
    try { o.style.MozOpacity = opacity / 100; }
    catch(e) {}
    try { o.filters.alpha.opacity = opacity; }
    catch(e) {}
  }
}

XLib.createEl = function(nodetype, uniqueid, strict)
{
  var el = document.createElement(nodetype);
  if(uniqueid != null) {
    if(!strict && typeof("YAHOO") != "undefined") {
      el.setAttribute("id", YAHOO.util.Dom.generateId(el, uniqueid));
    }
    else {
      el.setAttribute("id", uniqueid);
    } 
  }
  return el;
}

XLib.applyStyles = function(el, styles)
{
  if(typeof("YAHOO") != "undefined" && typeof(YAHOO.util.Dom) != "undefined") {
    var S = YAHOO.util.Dom.setStyle;
    for(stylename in styles) {
      S(el, stylename, styles[stylename]);
    }
  }
}


XLib._serializeObject = function(o) {
  var s = "";
  if(o != null) {
    if(o.nodeName == null) {
      for(var i in o) {
        if(i.charAt(0) != "_") {
          if(s != "") s += ", ";
          s += '"' + i + '": ';
          switch(typeof(o[i])) {
            case "string":
              s += '"' + o[i] + '"';
              break;
            case "object":
              s += this._serializeObject(o[i]);
              break;
            case "undefined":
              s += "null";
              break;
            default:
              s += o[i].toString();
              break;
          }
        }
      }
    }
    else {
      return '$e("' + o.id + '")';
    }
    return "{ " + s + " }";
  }
  return "--";
};

XLib._unserializeObject = function(o) {
  var ser = "";
  try { eval("ser = " + o); }
  catch(err) {}
  return ser;
};


XLib.base64Keys = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
XLib.encode64 = function(input) {
  var output = "";
  var chr1, chr2, chr3 = "";
  var enc1, enc2, enc3, enc4 = "";
  var i = 0;

  do {
     chr1 = input.charCodeAt(i++);
     chr2 = input.charCodeAt(i++);
     chr3 = input.charCodeAt(i++);

     enc1 = chr1 >> 2;
     enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
     enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
     enc4 = chr3 & 63;

     if(isNaN(chr2)) {
       enc3 = enc4 = 64;
     }
     else if(isNaN(chr3)) {
       enc4 = 64;
     }

     output += XLib.base64Keys.charAt(enc1) + XLib.base64Keys.charAt(enc2) + XLib.base64Keys.charAt(enc3) + XLib.base64Keys.charAt(enc4);
     chr1 = chr2 = chr3 = "";
     enc1 = enc2 = enc3 = enc4 = "";
  }
  while(i < input.length);
  return output;
}

XLib.decode64 = function(input) {
  var output = "";
  var chr1, chr2, chr3 = "";
  var enc1, enc2, enc3, enc4 = "";
  var i = 0;

  // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
  input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

  do {
     enc1 = XLib.base64Keys.indexOf(input.charAt(i++));
     enc2 = XLib.base64Keys.indexOf(input.charAt(i++));
     enc3 = XLib.base64Keys.indexOf(input.charAt(i++));
     enc4 = XLib.base64Keys.indexOf(input.charAt(i++));

     chr1 = (enc1 << 2) | (enc2 >> 4);
     chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
     chr3 = ((enc3 & 3) << 6) | enc4;

     output += String.fromCharCode(chr1);

     if (enc3 != 64) {
       output = output + String.fromCharCode(chr2);
     }
     if(enc4 != 64) {
       output = output + String.fromCharCode(chr3);
     }
     chr1 = chr2 = chr3 = "";
     enc1 = enc2 = enc3 = enc4 = "";
  }
  while (i < input.length);
  return output;
}

/* -------------------------------------------------------------- */
/* XAds                                                           */
/* -------------------------------------------------------------- */
var XAds = function(args) {
  this.id = args.element_id;
  this.slot = args.slot;
  this.page = args.page;
  this.keys = [ args.key1, args.key2, args.key3, args.key4 ];
  this.region = args.region ? args.region : null;
  this.version = 2;
};

XAds.prototype = {
  getURL: function() {
    return "/getabms.spy?s=" + escape(this.slot) + "&p=" + escape(this.page) + "&k1=" + escape(this.keys[0] || "") + "&k2=" + escape(this.keys[1] || "") + "&k3=" + escape(this.keys[2] || "") + "&k4=" + escape(this.keys[3] || "");
  },
  
  refresh: function() {
    var isValidRefreshType = false;
    if(this.slot == 'A' ||
       this.slot == 'BOX2' ||
       this.slot == 'H' ||
       this.slot == 'M' ||
       //this.slot == 'N' ||
       this.slot == 'B') isValidRefreshType = true;
       
    if(isValidRefreshType) {
      adcontainer = $e(this.id);
      if(adcontainer != null) {
        if(this.version == 2) {
          var kws = ""
          
          for(var i = 0; i < 4; i++)
            if((this.keys[i] || "").length > 0) kws += "&" + (this.keys[i] || "");
          
          var _scr_width = "";
          var _scr_height = "";
          
          if(this.slot == 'A') {
            _scr_width = "728";
            _scr_height = "90";
          }
          else if(this.slot == 'B') {
            _scr_width = "160";
            _scr_height = "600";
          }
          else if(this.slot == 'BOX2') {
            _scr_width = "300";
            _scr_height = "250";
          }
          else if(this.slot == 'N') {
            _scr_width = "300";
            _scr_height = "60";
          }
          else if(this.slot == 'M') {
            _scr_width = "20";
            _scr_height = "20";
          }
          else if(this.slot == 'H') {
            _scr_width = "213";
            _scr_height = "60";
          }
          
          var _fr = '<iframe src="http://ws.auto123.com/rabms/get/auto123/' + this.slot + this.page + '?region=' + this.region + kws + '" width="' + _scr_width + '" height="' + _scr_height + '"  marginheight="0" marginwidth="0" frameborder="0" scrolling="no" target="_blank"></iframe>';
          adcontainer.innerHTML = _fr;
        }
        else {
          var transaction = YAHOO.util.Connect.asyncRequest('GET', this.getURL(), {success:XAds_callback_success, failure:XAds_callback_failure, scope:this}, null);
        }
      }
    }
  }
};

var XAds_callback_success = function(o) {
  this.container = $e(this.id);
  if(this.container != null) {
    this.container.innerHTML = o.responseText;
  }
};

var XAds_callback_failure = function(o) {};

var XABMS = function() {
  this.ads = [];
  this.slotAds = {};
};

XABMS.prototype = {
  addAd: function(ad) {
    this.ads.push(ad);
    if(typeof(this.slotAds[ad.slot.toUpperCase()]) == "undefined") {
      this.slotAds[ad.slot.toUpperCase()] = [];
    }
    this.slotAds[ad.slot.toUpperCase()].push(ad);
  },
  
  createAd: function(args) {
    var ad = new XAds(args);
    this.addAd(ad);
  },
  
  getAdBySlot: function(slot) {
    if(typeof(this.slotAds[slot.toUpperCase()]) != "undefined") {
      var ads = this.slotAds[slot.toUpperCase()];
      if(ads.length > 0) return ads[0];
      else return new XAds({});
    }
    else {
      return new XAds({});
    }
  },
  
  hasSlot: function(slot) {
    if(typeof(this.slotAds[slot.toUpperCase()]) != "undefined")
      return true;
    return false;
  },
  
  refreshAllSlots: function() {
    for(var i = 0; i < this.ads.length; i++) {
      this.ads[i].refresh();
    }
  },
  
  refreshKnownKeywords: function(f) {
    var make = "";
    var model = "";
    
    if(typeof(f.make) != "undefined") {
      if(typeof(f.make.options) != "undefined") {
        if(f.make.selectedIndex >= 0) make = f.make.options[f.make.selectedIndex].value;
      }
      else if(typeof(f.make.value) != "undefined") {
        make = f.make.value;
      }      
    }
    
    if(typeof(f.model) != "undefined") {
      if(typeof(f.model.options) != "undefined") {
        if(f.model.selectedIndex >= 1) model = f.model.options[f.model.selectedIndex].value;
      }
      else if(typeof(f.model.value) != "undefined") {
        model = f.model.text;
      }
    }
    
    this.refreshKeyword("make", make, true);
    this.refreshKeyword("model", model);
    this.refreshAllSlots();
  },
  
  refreshKeyword: function(kw, value, alwaysSet) {
    if(kw == null) kw = "";
    if(value == null) value = "";
    
    if(kw != "") {
      kw = kw.toLowerCase();
      var match = kw + "=";
      var match_len = match.length;
      for(var i = 0; i < this.ads.length; i++) {
        var replaced = false;
        for(var j = 0; j < this.ads[i].keys.length; j++) {
          if(this.ads[i].keys[j] != null && this.ads[i].keys[j].toLowerCase().substring(0, match_len) == match) {
            this.ads[i].keys[j] = match + value;
            replaced = true;
          }
        }
        
        if(!replaced && alwaysSet) {
          replaced = false;
          for(var j = 0; j < this.ads[i].keys.length; j++) {
            if(this.ads[i].keys[j] == null) {
              this.ads[i].keys[j] = match + value;
              replaced = true;
            }
          }
        }
      }
    }
  }
};

XLib.dimmerTimer = null;
XLib.setDimmer = function(parentID, topLeftAnchorID, bottomRightAnchorID, dimmerID, forceWidth) {
  if(XLib.browserInfo.browserSupported) {
    var b_el = $e(bottomRightAnchorID);
    t_xy = YAHOO.util.Dom.getXY($e(topLeftAnchorID));
    b_xy = YAHOO.util.Dom.getXY($e(bottomRightAnchorID));
    
    if(t_xy == false || b_xy == false)  {
      var width = 800;
      var height = YAHOO.util.Dom.getXY($e('floatend'))[1] - YAHOO.util.Dom.getXY($e("floatbegin"))[1];
    }
    else {
      if(forceWidth != null) {
        b_xy = [ t_xy[0] + forceWidth, b_xy[1] ];
      }
    
      var width = b_xy[0] - t_xy[0];
      //var width = 662;
      var height = b_xy[1] - t_xy[1];
    }
    
    if(dimmerID != null) {
      var divDimmer = $e(dimmerID);
    }
    else {
      var divDimmer = XLib.createEl("div");
      divDimmer.setAttribute("id", YAHOO.util.Dom.generateId(divDimmer, "dimmer"));
      
      XLib.applyStyles(divDimmer, {"background-color":"white",
                                    position:"absolute",left:YAHOO.util.Dom.getX($e(parentID)) - 1,
                                    top:YAHOO.util.Dom.getY($e(parentID)) - 1,
                                    width:width,
                                    height:height,
                                    opacity:0.8,
                                   "z-index":20});
        $e(parentID).appendChild(divDimmer);
    }
    
    if(divDimmer != null) {
      XLib.applyStyles(divDimmer, {width:width,height:height});
      XLib.dimmerTimer = setTimeout("XLib.setDimmer('" + parentID + "','" + topLeftAnchorID + "','" + bottomRightAnchorID + "','" + divDimmer.id + "')", 100);
    }
  }
}

/* -------------------------------------------------------------- */
/* XContentManager                                                */
/* -------------------------------------------------------------- */
var XContentManager = function() {
  this.transaction = null;
  this.timer = null;
};

XContentManager.prototype = {
  changeContent: function(containerName, method, url, postParams, pageLanguage, refreshABMS, onComplete, forceWidth) {    
    this.containerName = containerName;
    this.refreshABMS = refreshABMS || false;    
    
    var el = $e(containerName);
    if(el != null) {
      if(XLib.browserInfo.browserSupported) {
        /*
        //var pWidth = (parseInt(YAHOO.util.Dom.getStyle(el, "width") || 0) + 5) + "px";
        //var pHeight = (parseInt(YAHOO.util.Dom.getStyle(el, "height") || 0) + 0) + "px";
        
        var e_xy = YAHOO.util.Dom.getXY($e('floatbottomright'));
        var b_xy = YAHOO.util.Dom.getXY($e("floatbegin"));
        if(e_xy == false || b_xy == false)  {
          var pWidth = 780;
          var pHeight = YAHOO.util.Dom.getXY($e('floatend'))[1] - YAHOO.util.Dom.getXY($e("floatbegin"))[1]
        }
        else  {
          var pWidth = e_xy[0] - b_xy[0];
          var pHeight = e_xy[1] - b_xy[1];
        }
        
        var divDimmer = XLib.createEl("div");
        XLib.applyStyles(divDimmer, {"background-color":"white",
                                     position:"absolute",left:YAHOO.util.Dom.getX(el) - 1,
                                     top:YAHOO.util.Dom.getY(el) - 1,
                                     width:pWidth,height:pHeight,
                                     opacity:0.8,"z-index":20});
        el.appendChild(divDimmer);
        */
        
        XLib.setDimmer(el.id, 'floatbegin', 'contentbright', null, forceWidth);
        
        var waitDiv = XLib.createEl("span");
        XLib.applyStyles(waitDiv, {"border-top":"1px solid #ee0000",
                                   "border-right":"1px solid #990000",
                                   "border-bottom":"1px solid #660000",
                                   "border-left":"1px solid #dd0000",
                                   "background-color":"#cc0000",
                                    color:"white",
                                    padding:"6px",
                                    position:"absolute",
                                    left:YAHOO.util.Dom.getX(el),
                                    top:YAHOO.util.Dom.getY(el),
                                    "z-index":21,
                                    margin:"20px",
                                    width:"444px",
                                   "font-weight":"bold",
                                   "text-align":"center"
                                  });
      }
      else {
        var waitDiv = XLib.createEl("div");
        var curStyle = waitDiv.getAttribute("style");
        curStyle.backgroundColor = "#cc0000";
        curStyle.padding = "6px";
        curStyle.color = "white";
        curStyle.position = "absolute";
        curStyle.zIndex = 21;
        curStyle.width = "500px";
        curStyle.margin = "20px";
        curStyle.textAlign = "center";
        curStyle.borderTop = "1px solid #ee0000";
        curStyle.borderRight = "1px solid #990000";
        curStyle.borderBottom = "1px solid #660000";
        curStyle.borderLeft = "1px solid #dd0000";
        curStyle.fontWeight = "bold";
        curStyle.left = "172";
        curStyle.top = "180";
        waitDiv.setAttribute("style", curStyle);
      }
      
      var progress = '<img src="/site/img/progress.gif" border="0">';
      
      if(pageLanguage == null) pageLanguage = "fr";
      if(pageLanguage == 'fr') {
        waitDiv.innerHTML = "&nbsp;<br>Téléchargement en cours. Veuillez patienter.<br><br>" + progress + "<br>&nbsp;";
      }
      else {
        waitDiv.innerHTML = "&nbsp;<br>Loading Data. Please wait.<br><br>" + progress + "<br>&nbsp;";
      }
      
      el.appendChild(waitDiv);
    }
    
    var callback = {
      success: this.callback_success,
      failure: this.callback_failure,
      scope: this,
      argument: [onComplete]
    };
    
    this._changeContent(method, url, postParams, callback, pageLanguage);
    return false; // in case it gets used with "onclick"
  },
  
  _changeContent: function(method, url, postParams, callback, pageLanguage) {
    if(pageLanguage == 'en') {
      this.timer = setTimeout("$e('" + this.containerName + "').innerHTML = 'This service is temporarily offline, please try again later.'", 8000);
    }
    else {
      this.timer = setTimeout("$e('" + this.containerName + "').innerHTML = 'Ce service est présentement hors-ligne.  Veuillez ré-essayer plus tard.'", 8000);
    }
    this.transaction = YAHOO.util.Connect.asyncRequest(method, url, callback, postParams);
  },
  
  callback_success: function(o) {
    clearTimeout(this.timer);
    this.transaction = null;
    var El = $e(this.containerName);
    if(El != null) {
      var contentBody = o.responseText;
      while(contentBody.length > 0 && (contentBody.substring(0,1) == '\n' || contentBody.substring(0,1) == '\r' || contentBody.substring(0,1) == ' ')) {
        contentBody = contentBody.substring(1);
      }
      El.innerHTML = contentBody;
      
      if(this.refreshABMS) {
        abmsManager.refreshAllSlots();
      }
    }
    
    clearTimeout(XLib.dimmerTimer);
    onComplete = o.argument[0];
    if(onComplete != null) {
      onComplete(true);
    }
  },

  callback_failure: function(o) {
    clearTimeout(this.timer);
    this.transaction = null;

    onComplete = o.argument[0];
    if(onComplete != null) {
      onComplete(true);
    }
  }
};

contentManager = new XContentManager();
