if(typeof(XPRIMA) == "undefined") XPRIMA = {};
if(typeof(XPRIMA.PageUtils) == "undefined") XPRIMA.PageUtils = {};

XPRIMA.use_pic_ids = false;

XPRIMA.PageUtils.AJAX = function() {
  return {
    _pageids: {},
    
    swapPage: function(idkey, defid, pageid, parentid, ajax_url, onajaxbegin) {
      if(typeof(this._pageids[idkey]) == "undefined")
        this._pageids[idkey] = { selected: document.getElementById(defid), selid: defid };
      
      if(this._pageids[idkey].selid == pageid) return;

      var current_page = this._pageids[idkey].selected;
      var requested_page = document.getElementById(pageid);
      var parentnode = document.getElementById(parentid);
      if(requested_page == null && parentnode != null) {
        if(ajax_url != null) {
          var myanim = null;
          if(onajaxbegin != null && typeof(onajaxbegin) == "function") {
            myanim = onajaxbegin(true, parentnode);
          }
        
          var cb = {
            success: XPRIMA.PageUtils.AJAX.swapPage_success,
            failure: XPRIMA.PageUtils.AJAX.swapPage_failure,
            argument: [ idkey, defid, pageid, parentnode, onajaxbegin, myanim ]
          };
          YAHOO.util.Connect.resetFormState();
          YAHOO.util.Connect.asyncRequest("GET", ajax_url, cb, null);
        }
      }
      else {
        if(current_page != null)
          current_page.style.display = "none";
        requested_page.style.display = "";
        this._pageids[idkey].selected = requested_page;
        this._pageids[idkey].selid = pageid;
      }
    },
    
    swapPage_success: function(o) {        
      var idkey = o.argument.length > 0 ? o.argument[0] : "";
      var defid = o.argument.length > 1 ? o.argument[1] : "";
      var pageid = o.argument.length > 2 ? o.argument[2] : "";
      var parentnode = o.argument.length > 3 ? o.argument[3] : "";
      var onajaxbegin = o.argument.length > 4 ? o.argument[4] : "";
      var myanim = o.argument.length > 5 ? o.argument[5] : "";
      
      if(onajaxbegin != null && typeof(onajaxbegin) == "function") {
        if(myanim != null && myanim.isAnimated()) {
          myanim.stop();          
        }
        onajaxbegin(false, parentnode);
      }
      
      var d = document.createElement("div");
      d.setAttribute("id", pageid);
      d.setAttribute("style", "display: none;");
      d.innerHTML = o.responseText;
      parentnode.appendChild(d);
      
      // Check to make sure we can find our object!
      if(document.getElementById(pageid) != null) {
        XPRIMA.PageUtils.AJAX.swapPage(idkey, defid, pageid, parentnode.id, null);
      }
    },
    
    swapPage_failure: function(o) {    
      // silently ignore
    },
    
    loadContentIfNotExist: function(contentid, parentnode, url, onsuccess, onfailure, default_display) {
      var e = document.getElementById(contentid);
      if(e != null) {
        if(onsuccess != null && typeof(onsuccess) == "function") {
          onsuccess();
        }
      }
      else {
        var cb = {
          success: this.loadContentIfNotExist_success,
          failure: this.loadContentIfNotExist_failure,
          argument: [contentid, parentnode, onsuccess, onfailure, default_display]
        };
        
        YAHOO.util.Connect.asyncRequest("GET", url, cb, null);
      }
    },
    
    loadContentIfNotExist_success: function(o) {
      var contentid = (o.argument.length > 0) ? o.argument[0] : null;
      var parentnode = (o.argument.length > 1) ? o.argument[1] : null;
      var onsuccess = (o.argument.length > 2) ? o.argument[2] : null;
      var onfailure = (o.argument.length > 3) ? o.argument[3] : null;
      var ddisplay  = (o.argument.length > 4) ? o.argument[4] : null;
      
      if(parentnode != null) {
        var e = document.createElement("div");
        e.setAttribute("id", contentid);
        e.setAttribute("style", "display: " + (ddisplay == null ? 'block' : ddisplay));
        e.innerHTML = o.responseText;
        parentnode.appendChild(e);

        if(onsuccess != null && typeof(onsuccess) == "function") {
          onsuccess();
        }
      }
    },
    
    loadContentIfNotExist_failure: function(o) {
      var onfailure = (o.argument.length > 3) ? o.argument[3] : null;
      if(onfailure != null && typeof(onfailure) == "function") {
        onfailure();
      }
    },
    
    fancySwap : function(swapin, pnode) {
      if(swapin) {
        var a = new YAHOO.util.Anim(pnode, { opacity: { to: 0 }}, 0.4, YAHOO.util.Easing.easeNone);
        //var a = new YAHOO.util.Anim(pnode, { opacity: { to: 0.4 }}, 0.4, YAHOO.util.Easing.easeNone);
        a.animate();
      }
      else {
        //var a = new YAHOO.util.Anim(pnode, { opacity: { to: 1 }, width: { to: 484 }}, 0.4, YAHOO.util.Easing.easeNone);
        YAHOO.util.Dom.setStyle(pnode, "width", "484px");
        var a = new YAHOO.util.Anim(pnode, { opacity: { to: 1 }}, 0.1, YAHOO.util.Easing.easeNone);
        a.animate();
      }
    }
  }
}();

// Added ML Sep 16 2008
if(typeof(XPRIMA.Multimedia) == "undefined") XPRIMA.Multimedia = {}
XPRIMA.Multimedia.Video = function() {
  return {
    articles       :   [],
    photoPos       :    0,
    cycleTimer     : null,
    cycleTime      : 5000,
    
    // for YAHOO.util.Motion 
    photoPosFrom   :    0,
    photoCount     :    3,
    motionLeft     : null,
    motionRight    : null,
    leftAttribs    : { points: { by: [-85,0]}},
    rightAttribs   : { points: { by: [+85,0]}},
    motionDelay    : 0.4,
    motionFFLeft   : null,
    motionRewindR  : null,
    photoPosFromMax: 0,
    isInit         : false,
    nocycle        : false,
    
    stopTimer: function() {
      if(this.cycleTimer != null) {
        clearTimeout(this.cycleTimer);
        this.cycleTimer = null;
      }
    },
    
    setButtonState : function() {
      if(XPRIMA.Multimedia.Video.photoPosFrom == 0) {
        e=document.getElementById("move_left");
        if(e != null) e.style.display="none";
        e=document.getElementById("move_right");
        if(e != null) e.style.display= XPRIMA.Multimedia.Video.articles.length <=3 ? "none" : "";
      } else if(XPRIMA.Multimedia.Video.photoPosFrom == XPRIMA.Multimedia.Video.photoPosFromMax) {
        e=document.getElementById("move_left");
        if(e != null) e.style.display="";
        e=document.getElementById("move_right");
        if(e != null) e.style.display="none";
      } else {
        e=document.getElementById("move_left");
        if(e != null) e.style.display="";
        e=document.getElementById("move_right");
        if(e != null) e.style.display="";
      }
    },
    
    init: function(nocycle) {
      this.isInit = true;
      this.nocycle = (nocycle === true) ? true : false;
      XPRIMA.Multimedia.Video.photoPosFromMax = Math.floor( (XPRIMA.Multimedia.Video.articles.length - 1)  /  XPRIMA.Multimedia.Video.photoCount ) * XPRIMA.Multimedia.Video.photoCount; // Modify carefully.
      this.selectArticle(0);      
      var o = document.getElementById("mmslider-container");
      if(o != null) {
        var motionRewindR = new YAHOO.util.Motion("mmslider", { points: { by: [0, 0]}}, 0.1, YAHOO.util.Easing.easeNone);
        motionRewindR.animate();
        o.style.display = "";
        this.startTimer();
      }
      this.setButtonState();
    },

    startTimer: function() {
      if(!this.nocycle)
        this.cycleTimer = setTimeout("XPRIMA.Multimedia.Video.cycle()", this.cycleTime);
    },        
    
    updateData: function(pos) {
      if(pos < this.articles.length) {
        var art = this.articles[pos];
        if(art != null) {
          var th = document.getElementById("multimedia-video-featured-img");
          var t  = document.getElementById("multimedia-video-featured-titlelink");
          var e  = document.getElementById("multimedia-video-featured-entry-date");
          var d  = document.getElementById("multimedia-video-featured-duration");
          var l =  document.getElementById("multimedia-video-featured-link");
          var lbtn = document.getElementById("multimedia-video-featured-linkbtn");
          if(th!=null && t!=null && e!=null && d!=null) {
            //th.style.width="85px;";
            th.src=art.f != "" ? art.f : art.th;
            th.title=art.t;
            t.href=art.l;
            t.innerHTML=art.t;
            e.innerHTML=art.e;
            var dur="("+Math.floor(art.d/60)+":"+(art.d%60<10?'0':'')+art.d%60+")";
            d.innerHTML=dur;
            l.href=art.l;
            lbtn.href=art.l;
          }
        }
        for(var x = 0; x < this.articles.length; x++) {
          var p = document.getElementById("multimedia-video-featured-" + x.toString());
          if(p != null) {
            p.style.backgroundColor = (x == pos) ? "#538397" : "#F3F4F8";
          }
        }        
      }
    },
    
    moveRight: function() {
      var e = document.getElementById("move_right");
      if(e != null) e.blur();
      if(this.articles.length > (this.photoPosFrom + this.photoCount)) {
        this.stopTimer();
        if(this.motionRight == null) {
          this.motionRight = new YAHOO.util.Motion("mmslider", { points: { by: [-85 * this.photoCount, 0]}}, this.motionDelay, YAHOO.util.Easing.easeNone);
          this.motionRight.onComplete.subscribe(XPRIMA.Multimedia.Video.motionRightComplete);
        }
        this.motionRight.animate();
      }
    },
    
    moveLeft: function() {
      var e = document.getElementById("move_left");
      if(e != null) e.blur();
      if(this.photoPosFrom > 0) {
        this.stopTimer();
        if(this.motionLeft == null) {
          this.motionLeft = new YAHOO.util.Motion("mmslider", { points: { by: [85 * this.photoCount, 0]}}, this.motionDelay, YAHOO.util.Easing.easeNone);
          this.motionLeft.onComplete.subscribe(XPRIMA.Multimedia.Video.motionLeftComplete);
        }
        this.motionLeft.animate();
      }
    },
    
    motionLeftComplete: function() {
      XPRIMA.Multimedia.Video.photoPosFrom -= XPRIMA.Multimedia.Video.photoCount;
      XPRIMA.Multimedia.Video.setButtonState();
      XPRIMA.Multimedia.Video.photoPos = XPRIMA.Multimedia.Video.photoPosFrom;
      XPRIMA.Multimedia.Video.selectArticle(XPRIMA.Multimedia.Video.photoPos);
      XPRIMA.Multimedia.Video.startTimer();
    },
    
    motionRightComplete: function() {
      XPRIMA.Multimedia.Video.photoPosFrom += XPRIMA.Multimedia.Video.photoCount;
      XPRIMA.Multimedia.Video.setButtonState();
      XPRIMA.Multimedia.Video.photoPos = XPRIMA.Multimedia.Video.photoPosFrom;
      XPRIMA.Multimedia.Video.selectArticle(XPRIMA.Multimedia.Video.photoPos);
      XPRIMA.Multimedia.Video.startTimer();
    },
    
    rewind : function() {
      if(this.motionRewindR==null) {
        this.motionRewindR = new YAHOO.util.Motion("mmslider", { points: { by: [85 * this.photoPosFrom, 0]}}, this.motionDelay * 2, YAHOO.util.Easing.easeNone);
        this.motionRewindR.onComplete.subscribe(XPRIMA.Multimedia.Video.rewindComplete);
      }
      this.motionRewindR.animate();
    },
    
    rewindComplete: function() {
      XPRIMA.Multimedia.Video.photoPosFrom = 0;
      XPRIMA.Multimedia.Video.setButtonState();
      XPRIMA.Multimedia.Video.photoPos = XPRIMA.Multimedia.Video.photoPosFrom;
      XPRIMA.Multimedia.Video.selectArticle(XPRIMA.Multimedia.Video.photoPos);
      XPRIMA.Multimedia.Video.startTimer();
    },
    
    cycle: function(fromAMouseOver) {
      this.stopTimer();
      if(fromAMouseOver == null) fromAMouseOver = false;
      
      if(!fromAMouseOver) {
        this.photoPos++;
        if(this.photoPos >= this.articles.length)
          this.photoPos = 0;
        
        this.selectArticle(this.photoPos);
        if(this.photoPos == 0) {
          this.rewind();
        }
        else if(this.photoPos >= this.photoPosFrom + this.photoCount) {
          this.moveRight();
        }
        else {
          this.startTimer();
        }
      } else {
        this.startTimer();
      }
    },

    selectArticle: function(pos) {
      this.stopTimer();
      if(pos < this.articles.length) {
        this.updateData(pos);
        this.photoPos = pos;
    }
//      e = document.getElementById('dbg1');
//      if(e != null) {
//        e.innerHTML = 'this.photoPos=' + this.photoPos.toString() + ' this.photoPosFrom=' + this.photoPosFrom.toString();
//      }
    }
  }
}();

// Added ML Sep 29 2008
XPRIMA.Multimedia.Photo = function() {
  return {
    articles       :   [],
    photoPos       :    0,
    cycleTimer     : null,
    cycleTime      : 7000,
    
    // for YAHOO.util.Motion 
    photoPosFrom   :    0,
    photoCount     :    3,
    motionLeft     : null,
    motionRight    : null,
    leftAttribs    : { points: { by: [-85,0]}},
    rightAttribs   : { points: { by: [+85,0]}},
    motionDelay    : 0.4,
    motionFFLeft   : null,
    motionRewindR  : null,
    photoPosFromMax: 0,
    isInit         : false,
    nocycle        : false,
    
    stopTimer: function() {
      if(this.cycleTimer != null) {
        clearTimeout(this.cycleTimer);
        this.cycleTimer = null;
      }
    },
    
    setButtonState : function() {
      if(XPRIMA.Multimedia.Photo.photoPosFrom == 0) {
        e = document.getElementById("move_left_photo");
        if(e != null) e.style.display = "none";
        e = document.getElementById("move_right_photo");
        if(e != null) e.style.display = XPRIMA.Multimedia.Photo.articles.length <=3 ? "none" : "";;
      }
      else if(XPRIMA.Multimedia.Photo.photoPosFrom == XPRIMA.Multimedia.Photo.photoPosFromMax) {
        e = document.getElementById("move_left_photo");
        if(e != null) e.style.display = "";
        e = document.getElementById("move_right_photo");
        if(e != null) e.style.display = "none";
      }
      else {
        e = document.getElementById("move_left_photo");
        if(e != null) e.style.display = "";
        e = document.getElementById("move_right_photo");
        if(e != null) e.style.display = "";
      }
    },
    
    init: function(nocycle) {
      this.isInit = true;
      this.nocycle = (nocycle === true) ? true : false;
      XPRIMA.Multimedia.Photo.photoPosFromMax = Math.floor( (XPRIMA.Multimedia.Photo.articles.length - 1) / XPRIMA.Multimedia.Photo.photoCount ) * XPRIMA.Multimedia.Photo.photoCount; // Modify carefully.
      this.selectArticle(0);      
      var o = document.getElementById("photo-slider-container");
      if(o != null) {
        var motionRewindR = new YAHOO.util.Motion("photo-slider", { points: { by: [0, 0]}}, 0.1, YAHOO.util.Easing.easeNone);
        motionRewindR.animate();
        o.style.display = "";
        this.startTimer();
      }
      this.setButtonState();
    },

    startTimer: function(delayOverride) {
      sleepDelay = this.cycleTime;
      if (delayOverride!=null) {
        sleepDelay = delayOverride;
      }
      
      if(!this.nocycle)
        this.cycleTimer = setTimeout("XPRIMA.Multimedia.Photo.cycle()", sleepDelay);
    },        
    
    updateData: function(pos) {
      if(pos < this.articles.length) {
        var art = this.articles[pos];
        if(art != null) {
          var th = document.getElementById("multimedia-photo-featured-img");
          var t  = document.getElementById("multimedia-photo-featured-titlelink");
          var g  = document.getElementById("multimedia-photo-featured-gallery");
          var a  = document.getElementById("multimedia-photo-featured-abstract");
          var c  = document.getElementById("multimedia-photo-featured-count");  // coded
          var ar = document.getElementById("multimedia-photo-featured-article"); 
          var bt = document.getElementById("multimedia-photo-bigger-thumbnail");
          if (bt!=null && th != null && t!=null && g!=null && a!=null && c!=null && ar!=null) {
            th.src=art.f != "" ? art.f : art.th;
            th.title=art.t;
            t.innerHTML=art.t;
            t.href=art.g;
            g.href=art.g;
            a.innerHTML=art.a;
            c.innerHTML="("+ art.cnt + " photo"+ ((art.cnt > 1)?"s":"") +")";
            ar.href= art.art != "" && art.art != null ? art.art : 'gneh' ;
            bt.href= art.g;
          }
        }
        for(var x = 0; x < this.articles.length; x++) {
          var p = document.getElementById("multimedia-photo-featured-" + x.toString());
          if(p != null) {
            p.style.backgroundColor = (x == pos) ? "#538397" : "#F3F4F8";
          }
        }        
      }
    },
    
    moveRight: function() {
      var e = document.getElementById("move_right_photo");
      if(e != null) e.blur();
      if(this.articles.length > (this.photoPosFrom + this.photoCount)) {
        this.stopTimer();
        if(this.motionRight == null) {
          this.motionRight = new YAHOO.util.Motion("photo-slider", { points: { by: [-85 * this.photoCount, 0]}}, this.motionDelay, YAHOO.util.Easing.easeNone);
          this.motionRight.onComplete.subscribe(XPRIMA.Multimedia.Photo.motionRightComplete);
        }
        this.motionRight.animate();
      }
    },
    
    moveLeft: function() {
      var e = document.getElementById("move_left_photo");
      if(e != null) e.blur();
      if(this.photoPosFrom > 0) {
        this.stopTimer();
        if(this.motionLeft == null) {
          this.motionLeft = new YAHOO.util.Motion("photo-slider", { points: { by: [85 * this.photoCount, 0]}}, this.motionDelay, YAHOO.util.Easing.easeNone);
          this.motionLeft.onComplete.subscribe(XPRIMA.Multimedia.Photo.motionLeftComplete);
        }
        this.motionLeft.animate();
      }
    },
    
    motionLeftComplete: function() {
      XPRIMA.Multimedia.Photo.photoPosFrom -= XPRIMA.Multimedia.Photo.photoCount;
      XPRIMA.Multimedia.Photo.setButtonState();
      XPRIMA.Multimedia.Photo.photoPos = XPRIMA.Multimedia.Photo.photoPosFrom;
      XPRIMA.Multimedia.Photo.selectArticle(XPRIMA.Multimedia.Photo.photoPos);
      XPRIMA.Multimedia.Photo.startTimer();
    },
    
    motionRightComplete: function() {
      XPRIMA.Multimedia.Photo.photoPosFrom += XPRIMA.Multimedia.Photo.photoCount;
      XPRIMA.Multimedia.Photo.setButtonState();
      XPRIMA.Multimedia.Photo.photoPos = XPRIMA.Multimedia.Photo.photoPosFrom;
      XPRIMA.Multimedia.Photo.selectArticle(XPRIMA.Multimedia.Photo.photoPos);
      XPRIMA.Multimedia.Photo.startTimer();
    },
    
    rewind : function() {
      if(this.motionRewindR==null) {
        this.motionRewindR = new YAHOO.util.Motion("photo-slider", { points: { by: [85 * this.photoPosFrom, 0]}}, this.motionDelay * 2, YAHOO.util.Easing.easeNone);
        this.motionRewindR.onComplete.subscribe(XPRIMA.Multimedia.Photo.rewindComplete);
      }
      this.motionRewindR.animate();
    },
    
    rewindComplete: function() {
      XPRIMA.Multimedia.Photo.photoPosFrom = 0;
      XPRIMA.Multimedia.Photo.setButtonState();
      XPRIMA.Multimedia.Photo.photoPos = XPRIMA.Multimedia.Photo.photoPosFrom;
      XPRIMA.Multimedia.Photo.selectArticle(XPRIMA.Multimedia.Photo.photoPos);
      XPRIMA.Multimedia.Photo.startTimer();
    },
    
    cycle: function(fromAMouseOver) {
      this.stopTimer();
      if(fromAMouseOver == null) fromAMouseOver = false;
      
      if(!fromAMouseOver) {
        this.photoPos++;
        if(this.photoPos >= this.articles.length)
          this.photoPos = 0;
        
        this.selectArticle(this.photoPos);
        if(this.photoPos == 0) {
          this.rewind();
        }
        else if(this.photoPos >= this.photoPosFrom + this.photoCount) {
          this.moveRight();
        }
        else {
          this.startTimer();
        }
      } else {
        this.startTimer();
      }
    },

    selectArticle: function(pos) {
      this.stopTimer();
      if(pos < this.articles.length) {
        this.updateData(pos);
        this.photoPos = pos;
    }
//      e = document.getElementById('dbg1');
//      if(e != null) {
//        e.innerHTML = 'this.photoPos=' + this.photoPos.toString() + ' this.photoPosFrom=' + this.photoPosFrom.toString();
//      }
    }
  }
}();
/* ML Jan 17, 2011 No longer in use (was it ever ?)
  XPRIMA.Picolio = function() {
    return {
      _rootPath : "http://picolio.auto123.com",
      _switchDomain : function(src, cparams) {
        var valid = false;
        if(src != null && src != "" && src[0] == '/') {
          src = this._rootPath + src + cparams;
          valid = true;
        }
        else if(src.substring(0, 7) == "http://" && src.substring(0, _rootPath.length) != _rootPath) {
          parseduri = src.split("/");
          domain = parseduri[2];
          if(domain.indexOf("auto123") != -1) {
            src = this._rootPath;
            for(var i=3; i < parseduri.length; i++)
              src += "/" + parseduri[i];
            src += cparams;
            valid = true;
          }
        }
        return { valid:valid, src:src };
      },
      
      _switchPath : function(src) {
        reps = [
          ["/media/videos/", "/media-videos/"],
          ["/ArtImages/", "/art-images/"],
        ]
        
        for(var i = 0; i < reps.length; i++)
          src = src.replace(reps[i][0], reps[i][1]);
        return src;
      },    
      
      getImage : function(src, params) {
        var cparams = (params == null) ? "" : "/" + params.join("/");
        res = this._switchDomain(this._switchPath(src), cparams);
        return res.valid ? res.src : src;
      }
    }
  }();
*/
// Added ML Sep 30 2008
XPRIMA.Multimedia.Common = function() {
  return {
    init: function() {},
    stats : function() {},

    enableVideos: function(){
      if(XPRIMA.Multimedia.Video.isInit){ 
        XPRIMA.Multimedia.Video.startTimer();      
      } else {
        XPRIMA.Multimedia.Video.init();
      }
      XPRIMA.Multimedia.Photo.stopTimer();      
    },
    
    enablePhotos: function(){
      if(XPRIMA.Multimedia.Photo.isInit){ 
        XPRIMA.Multimedia.Photo.startTimer();      
      } else {
        XPRIMA.Multimedia.Photo.init();
      }
      XPRIMA.Multimedia.Video.stopTimer();      
    }
  }
}();

img_minus = new Image();
img_plus = new Image();
img_minus.src = "/site/img/used/bt_minus.gif";
img_plus.src = "/site/img/used/bt_plus.gif";

img_star_phase0 = new Image();
img_star_phase1 = new Image();
img_star_phase2 = new Image();
img_star_phase0.src = "/site/img/used/bstar_empty.gif";
img_star_phase1.src = "/site/img/used/bstar_half.gif";
img_star_phase2.src = "/site/img/used/bstar_full.gif";

x_ajax_http = null;

reviews_page_active = null;
review_nextInLine = 0;
review_cycleTimer = null;
reviews_featured_swap_lastActive = 0;

overview_tab = null;
overview_tabcontent = null;

tab_photo_video_current = null;
tab_content_photo_video_current = null;

car_photo_number = 1;
car_photo_switch = 0;
photo_main_slideshow_timer = null;

generic_tabs = {};
builder_packages = {};

function logOut(lng, pageurl, qs) {
  url = "http://www.auto123.com/logout.spy?lng=" + escape(lng) + "&url=" + escape(pageurl);
  if(qs != "") url += "&p=" + escape(qs);
  window.location.href = url;
  return false;
}

function showLoginForm() {
  var o = document.getElementById("loginbox");
  if(o != null) {
    o.style.display = "";
    /*document.forms.loginform.my123un.value = "";
    document.forms.loginform.my123pw.value = "";
    document.forms.loginform.my123un.focus();*/
    
    document.getElementById('my123unl').value = "";
    document.getElementById('my123pwl').value = "";
    document.getElementById('my123unl').focus();
  }
  return false;
}

function ajax_fetch(url) {
  if(x_ajax_http == null)
    x_ajax_http = _ajax_createObject();
  return _ajax_get(x_ajax_http, url);
};

function _ajax_createObject() {
  if(window.XMLHttpRequest) {
    return new XMLHttpRequest();
  }
  else if(window.ActiveXObject) {
    return new ActiveXObject("Microsoft.XMLHTTP");
  }
  return null;
};

function _ajax_get(http, url) {
  return _ajax_submit(http, false, "GET", url, null);
};

function _ajax_submit(http, async, method, url, postdata) {
  methodOK = false;
  method = (method != null && typeof(method) == "string") ? method.toUpperCase() : "";
  
  if(method == "GET") {
    methodOK = true;
    http.open(method, url, null);
  }
  else if(method == "POST") {
    methodOK = true;
    http.open(method, url, null);
    http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    http.setRequestHeader('Accept-Charset','ISO-8859-1');
  }
  if(methodOK)
    http.send(method == "POST" ? postdata : null);
  return http;
};

function strip(s) {
  var str = ''
  var begin = 0;
  var end;

  if(s == null || s == "") {
    return "";
  }
  end = s.length;

  while(begin < s.length && s.charAt(begin) == ' ') begin++;
  if(begin < s.length) {
    while(end > 0 && s.charAt(end - 1) == ' ') end--;

    if(begin < end) {
      str = s.substring(begin,end);
    }
  }
  return str;
}

function isBlank(s) {
  return (strip(s) == '');
}

function showHideBlock(blockid) {
  var o = document.getElementById(blockid);
  var link = document.getElementById(blockid + "link");
  var img = document.getElementById(blockid + "img");
  if(o != null) {
    if(link != null)
      link.innerHTML = (o.style.display == 'none') ? "hide" : "show";
    if(img != null)
      img.src = (o.style.display == 'none') ? img_minus.src : img_plus.src;
    o.style.display = (o.style.display == 'none') ? "" : "none";
  }

  o.blur();

  return false;
}

function showHideMoreInfo(elementID, state){
  var onElement = document.getElementById(elementID + "-on");
  var offElement = document.getElementById(elementID + "-off");
  var element = document.getElementById(elementID);
  
  if(state == 'on'){
    onElement.className = 'hidden';
    offElement.className = 'visible';
    
    element.className = 'visible';
    
    onElement.blur();
  }
  else{
    onElement.className = 'visible';
    offElement.className = 'hidden';
    
    element.className = 'hidden';
    
    offElement.blur();
  }
  
  return false;
}

function resubmit_dealer_search_form(pc, args) {
  f = args[0];
  errPC = args[1];
  f.PC.value = pc;
  dealer_search_form_validate(f, errPC);
}

function dealer_search_form_validate(f, errPC) {
  var pc = f.PC;
  
  //if(isBlank(pc.value)) {
  if(isBlank(pc.value) || !validatePC(f.PC, true, true)) {
    //alert(errPC);
    mainpcPopup(resubmit_dealer_search_form, [f,errPC], 314, 327);
    return false;
  }
  f.submit();
}

function reviews_swapVideoPhoto(showid, hideid) {
  var o1 = document.getElementById("tab_" + showid);
  var o2 = document.getElementById("tab_" + hideid);
  var i1 = document.getElementById("tab_img_" + showid);
  var i2 = document.getElementById("tab_img_" + hideid);

  if(o1 != null && o2 != null) {
    o1.style.display = "block";
    o2.style.display = "none";
  }

  if(i1 != null && i2 != null) {
    i1.src = i1.src.replace("_off.", "_on.");
    i2.src = i2.src.replace("_on.", "_off.");
    o1.blur();
  }

  return false;
}

function reviews_featured_swap(idx, o) {
  if(o != null) o.blur();

  if(idx < featured_reviews.length) {
    var feature = featured_reviews[idx];
    var title = document.getElementById("art_featured_title");
    var text = document.getElementById("art_featured_abstract");
    var img = document.getElementById("art_featured_img");
    var href = document.getElementById("art_featured_href");
    var tablebg = document.getElementById("art_featured_tbbg");
    var box = document.getElementById("art_featured_box" + idx.toString());
    var contest;

    if(title != null) title.innerHTML = '<a href="' + feature.link + '" style="color: black; text-decoration: none;">' + feature.title + '</a>';
    if(text != null) {
      text.innerHTML = '<a href="' + feature.link + '" style="color: black; text-decoration: none;">' + feature.text + '</a>';
    }
    if(href != null) href.href = feature.link;
    if(box != null) {
      if(reviews_featured_swap_lastActive != null) {
        var lastActive = document.getElementById("art_featured_box" + reviews_featured_swap_lastActive.toString());
        if(lastActive != null) {
          lastActive.className = "reviewboxoff";
          contest = lastActive.getAttribute("contest");
          if(contest != null && contest == "1") {
            lastActive.className += " contest";
          }
        }
      }
      box.className = "reviewboxon";
      contest = box.getAttribute("contest");
      if(contest != null && contest == "1") {
        box.className += " contest";
      }
    }
    
    if(tablebg != null && typeof(feature.bgimg) != "undefined" && feature.bgimg != "") {
      tablebg.style.background = "url(" + feature.bgimg + ") 0 0 no-repeat";
      if(img != null) {
        img.src = "/site/img/spacer.gif";
      }
    }
    
    if(tablebg == null || (typeof(feature.bgimg) != "undefined" && (feature.bgimg == "" || feature.bgimg == null)) && img != null) {
      img.src = feature.photo;
    }

    reviews_featured_swap_lastActive = idx;
  }

  return false;
}

/* // Hénène
function reviews_featured_swap(idx, o) {
  if(o != null) o.blur();
  
  if(idx < featured_reviews.length) {
    var feature = featured_reviews[idx];
    var title = document.getElementById("art_featured_title");
    var text = document.getElementById("art_featured_abstract");
    var img = document.getElementById("art_featured_img");
    var href1 = document.getElementById("art_featured_href1");
    var href2 = document.getElementById("art_featured_href2");
    var href3 = document.getElementById("art_featured_href3");
    var tablebg = document.getElementById("art_featured_tbbg");
    var tablebg2 = document.getElementById("art_featured_tbbg2");
    var box = document.getElementById("art_featured_box" + idx.toString());

    if(title != null) title.innerHTML = feature.title;
    if(text != null) text.innerHTML = feature.text;
    if(href1 != null) href1.href = feature.link;
    if(href2 != null) href2.href = feature.link;
    if(href3 != null) href3.href = feature.link;
    if(box != null) {
      if(reviews_featured_swap_lastActive != null) {
        var lastActive = document.getElementById("art_featured_box" + reviews_featured_swap_lastActive.toString());
        if(lastActive != null) {
          lastActive.className = "reviewboxoff";
        }
      }
      box.className = "reviewboxon";
    }
    
    if(tablebg != null && tablebg2 != null && typeof(feature.bgimg) != "undefined" && feature.bgimg != "") {
      tablebg.style.background = "url(" + feature.bgimg + ") 0 0 no-repeat;";
      tablebg2.style.background = "url(" + feature.bgimg + ") bottom left no-repeat;";
      if(img != null) {
        img.src = "/site/img/spacer.gif";
      }
    }
    
    if(tablebg == null || tablebg2 == null || (typeof(feature.bgimg) != "undefined" && (feature.bgimg == "" || feature.bgimg == null)) && img != null) {
      img.src = feature.photo;
    }

    reviews_featured_swap_lastActive = idx;
  }

  return false;
}
*/

function review_featured_mouseover(idx, o) {
  reviews_clearTimer();
  reviews_featured_swap(idx, o);
}

function review_featured_mouseout() {
  reviews_setTimer();
}

function reviews_cycler() {
  reviews_clearTimer();
  if(featured_reviews.length > 0) {
    review_nextInLine++;
    if(review_nextInLine >= featured_reviews.length)
      review_nextInLine = 0;

    reviews_featured_swap(review_nextInLine, null);
    reviews_setTimer();
  }
}

function reviews_clearTimer() {
  if(review_cycleTimer != null) {
    clearTimeout(review_cycleTimer);
    review_cycleTimer = null;
  }
}

function reviews_setTimer() {
  review_cycleTimer = setTimeout('reviews_cycler()', 5000);
}

function toggleVisibility(elemid, onchangefunc) {
  if(elemid != null) {
    var o = document.getElementById(elemid);
    if(o != null) {
      o.style.display = (o.style.display == 'none') ? '' : 'none';
      o.blur();

      if(onchangefunc != null) {
        onchangefunc(o);
      }
    }
  }
  return false;
}

function setVisible(elemid, b) {
  if(elemid != null) {
    var o = document.getElementById(elemid);
    if(o != null) {
      o.style.display = b ? "" : "none";
      o.blur();
    }
  }
  return false;
}

function talkback_respond(eid, rtbid) {
  var e = document.getElementById(eid);
  var f = document.getElementById("frmposttalkback");
  var o1 = document.getElementById("post_comment_response_node");
  var o2 = document.getElementById("post_comment_response");
  var o3 = document.getElementById("post_comment_response_date");
  var o4 = document.getElementById(eid + "d");
  var o5 = document.getElementById(eid + "n");
  if(e != null && f != null && o1 != null && o2 != null) {
    o1.style.display = "";
    o2.innerHTML = e.innerHTML;
    f.rtbid.value = rtbid;

    var newtitle = e.innerHTML;
    while(newtitle.length > 0 && newtitle.charAt(0) == ' ') newtitle = newtitle.substring(1);
    while(newtitle.length > 0 && newtitle.charAt(newtitle.length - 1) == ' ') newtitle = newtitle.substring(0, newtitle.length - 1);
    if(newtitle.toLowerCase().indexOf("re:") != 0)
      newtitle = "Re: " + newtitle;
    f.title.value = newtitle;

    if(o3 != null && o4 != null && o5 != null) {
      o3.innerHTML = ((o4.innerHTML != '') ? '<br>' : '') + o4.innerHTML + ' (<span class="bold">' + o5.innerHTML + '</span>)';
    }

    f.comment.focus();
  }

  return false;
}

function talkback_cancelResponse(f) {
  f.rtbid.value = "";
  f.title.value = "";

  var o1 = document.getElementById("post_comment_response_node");
  if(o1 != null) o1.style.display = "none";

  f.title.focus();
}

function reviews_pages_activate(pagenum) {
  var o = document.getElementById("reviews_page_" + pagenum.toString());
  if(o != null) {
    if(reviews_page_active == null && pagenum != 0)
      reviews_page_active = document.getElementById("reviews_page_0");

    if(reviews_page_active != null) {
      reviews_page_active.style.display = "none";
    }
    o.style.display = "";
    reviews_page_active = o;
  }
  return false;
}

function toggle_topics(lng) {
  if(lng != 'en' && lng != 'fr') { lng = 'fr'; }

  var texts = { en: { off: "More Topics", on: "Less Topics" }, fr: { off: "D'autres&nbsp;sujets", on: "Moins&nbsp;de&nbsp;sujets" } };
  var o = document.getElementById("moretopics");
  var e = document.getElementById("moretopicslink");
  if(o != null && e != null) {

    e.innerHTML = (o.style.display == 'none') ? texts[lng].on : texts[lng].off;
    o.style.display = (o.style.display == 'none') ? "" : "none";
    o.blur();
  }
  
  return false;
}

function photo_gallery_click(e, img) {
  return;
}

function setVisibilityByAttribute(tag, attribute, value, visibility) {
  els = document.getElementsByTagName(tag);
  if(els != null) {
    for(var i = 0; i < els.length; i++) {
      var a = els[i].getAttribute(attribute);
      if(a != null && (value == null || a.toLowerCase() == value.toLowerCase())) {
        els[i].style.display = visibility ? "block" : "none";
      }
    }
  }
}

function multimedia_all_media() {
  var f = document.getElementById("multimedia-search-form");
  var f2 = document.getElementById("frmMakeModelSearch");
  if(f != null) {
    f.cb_video.value = "1";
    f.cb_photo.value = "1";
  }
  if(f2 != null) {
    f2.cb_video.value = "1";
    f2.cb_photo.value = "1";
  }
  return setVisibilityByAttribute("div", "group", null, true);
}

function multimedia_videos() {
  var f = document.getElementById("multimedia-search-form");
  var f2 = document.getElementById("frmMakeModelSearch");
  if(f != null) {
    f.cb_video.value = "1";
    f.cb_photo.value = "";
  }
  if(f2 != null) {
    f2.cb_video.value = "1";
    f2.cb_photo.value = "";
  }
  setVisibilityByAttribute("div", "group", "video", true);
  setVisibilityByAttribute("div", "group", "photo", false);
  return false;
}

function multimedia_photos() {
  var f = document.getElementById("multimedia-search-form");
  var f2 = document.getElementById("frmMakeModelSearch");
  if(f != null) {
    f.cb_video.value = "";
    f.cb_photo.value = "1";
  }  
  if(f2 != null) {
    f2.cb_video.value = "";
    f2.cb_photo.value = "1";
  }  
  setVisibilityByAttribute("div", "group", "photo", true);
  setVisibilityByAttribute("div", "group", "video", false);
  return false;
}

function overview_tabActivation(section) {
  if(overview_tab == null) {
    overview_tab = document.getElementById("tab_btn_specs");
  }

  if(overview_tabcontent == null) {
    overview_tabcontent = document.getElementById("tab_specs");
  }

  var tab = document.getElementById("tab_btn_" + section);
  if(tab != null && tab.id != overview_tab.id) {
    var content = document.getElementById("tab_" + section);
    if(content != null) {
      overview_tab.className = "lightbluebg2";
      tab.className = "altlightbluebg";
      overview_tabcontent.style.display = "none";
      content.style.display = "block";
      overview_tab = tab;
      overview_tabcontent = content;
      tab.blur();
    }
  }

  return false;
}

function theysay_activate_page(pagenum, max_pages) {
  var o1 = document.getElementById("expert_reviews_page" + pagenum.toString());
  var p1 = document.getElementById("expert_reviews_pagelink" + pagenum.toString());
  if(o1 != null && p1 != null) {
    o1.style.display = 'block';
    p1.className = 'bold';
    for(var i = 0; i < max_pages; i++) {
      if(i + 1 != pagenum) {
        var o2 = document.getElementById("expert_reviews_page" + (i + 1).toString());
        var p2 = document.getElementById("expert_reviews_pagelink" + (i + 1).toString());
        if(o2 != null) o2.style.display = 'none';
        if(p2 != null) p2.className = ' ';
      }
    }
  }

  return false;
}

function toggle_rating_details(o, reviewid, lng, reloadbanners, idx) {
  var sEl = document.getElementById("short-rating-" + reviewid.toString());
  var dEl = document.getElementById("detailed-rating-" + reviewid.toString());
  var idpatch = (idx!=null?"idSummary"+idx.toString():"idSummary");
  var idS = document.getElementById(idpatch);
  if(sEl != null && dEl != null && idS != null) {
    var isShort = sEl.style.display != 'none';
    sEl.style.display = isShort ? "none" : "";
    dEl.style.display = isShort ? "" : "none";
    if(lng == 'en') {
      o.innerHTML = isShort ? "Summary Ratings" : "Complete Ratings";
      idS.innerHTML = isShort ? "Complete Ratings" : "Summary Ratings";
    }
    else {
      o.innerHTML = isShort ? "Sommaire" : "Détaillée";
      idS.innerHTML = isShort ? "Détaillée" : "Sommaire";
    }
    if (reloadbanners != null && reloadbanners==true) {
      abmsManager.refreshAllSlots();
    }
  }
  return false;
}
function tabs_photo_video(section) {
  if(tab_photo_video_current == null)
    tab_photo_video_current = document.getElementById("tab-videos");

  if(tab_content_photo_video_current == null)
    tab_content_photo_video_current = document.getElementById("tab-videos-content");

  var tab = document.getElementById("tab-" + section);
  if(tab != null && tab.id != tab_photo_video_current.id) {
    var content = document.getElementById("tab-" + section + "-content");
    if(content != null) {
      tab_photo_video_current.className = "lightbluebg2";
      tab.className = "altlightbluebg";
      tab_content_photo_video_current.style.display = "none";
      content.style.display = "block";
      tab_photo_video_current = tab;
      tab_content_photo_video_current = content;
      tab.blur();
    }
  }

  return false;
}

function carcontainer_consumercar_select_page(pagenum) {
  for(var i = 1;; i++) {
    var p = document.getElementById("consumer_reviews_page" + i.toString());
    if(p == null) break;
    p.style.display = (i == pagenum) ? 'block' : 'none';
  }
  return false;
}

function photo_main_setdefault(pid) {
  for(var i = 0; i < car_photos_all.length; i++) {
    if(car_photos_all[i].picid == pid) {
      car_photo_number = i + 1;
      break;
    }
  }
  photo_main_change_update();
  
  var a = new YAHOO.util.Anim("car-photo-src", { opacity: { to: 1 }}, 0.2, YAHOO.util.Easing.easeNone);
  a.animate();
}

function photo_main_set_default_pict(id1,id2,id3) {
  //XPRIMA.log('document.location.href='+document.location.href);  
  var l = document.location.href;
  // do we have an # in the path
  li=l.lastIndexOf("#")
  var pid = '';
  if (-1 != li ){
    pid = l.substr(li+1);
    if(pid && pid.length==22) {
      if(pid.match(/.*=.*/)) {
        pid='';
      }
    } else {
      pid='';
    }
  }
  if(id1!=null && id1!='' && id2!=null && id2!='' && id3!=null && id3!='' && pid != '') {
    toggleVisibilitySwap(id1,id2,id3);
  }
  photo_main_setdefault(pid);
}

function photo_main_slideshow() {
  if(photo_main_slideshow_isrunning())
    photo_main_slideshow_stop();
  else {
    toggleVisibilitySwap('photo-mode', 'mode-bigphoto', 'mode-bigphoto');
    var o = document.getElementById("car-photo-thumbnails-btn");
    if(o != null && o.style.display != "") { o.style.display = ""; }
    o = document.getElementById("car-photo-number-str");
    if(o != null && o.style.display != "") { o.style.display = ""; }
    
    car_photo_number--;
    photo_main_slideshow_start();
  }
}

function photo_main_slideshow_stop() {
  if(photo_main_slideshow_isrunning()) {
    clearTimeout(photo_main_slideshow_timer);
    photo_main_slideshow_timer = null;
    var btn = document.getElementById("car-photo-slideshow-btn");
    if(btn != null) {
      btn.value = btn.getAttribute("textview");
    }
  }
}

function photo_main_slideshow_start() {
  photo_main_change(1,true);
  photo_main_slideshow_timer = setTimeout('photo_main_slideshow_start()', 3000);
  var btn = document.getElementById("car-photo-slideshow-btn");
  if(btn != null) {
    btn.value = btn.getAttribute("textstop");
  }
}

function photo_main_slideshow_isrunning() {
  return photo_main_slideshow_timer != null ? true : false;
}

function photo_main_change(offset, checkSlideshow) {
  if(checkSlideshow != null && checkSlideshow && photo_main_slideshow_isrunning()) photo_main_slideshow();

  if(offset < 0) photo_main_change_previous();
  else if(offset > 0) photo_main_change_next();
  return false;
}

function photo_main_change_previous() {
  if(car_photo_number == 1)
    car_photo_number = car_photos.length;
  else
    car_photo_number--;
  photo_main_change_update(true);
}

function photo_main_change_next(current_number) {
  if(car_photo_number == car_photos.length)
    car_photo_number = 1;
  else
    car_photo_number++;
  photo_main_change_update(true);
}

function photo_tag_update_success(o) {
  if(o != null && typeof(photo_tags_cache[o.argument[0]]) == "undefined") {
    photo_tags_cache[o.argument[0]] = o;
  }
  

  eval("var resp = (" + o.responseText + ")");
  
  var table_tags = document.getElementById("phototags");
  var tr_vehiclelist = document.getElementById("photos-tags-vehicle-list");
  var td_vehiclelist = document.getElementById("photos-tags-vehicle-list-data");
  var tr_vehicledesc = document.getElementById("photos-tags-vehicledesc");
  var td_vehicledesc = document.getElementById("photos-tags-vehicledesc-data");
  var tr_bodystyle = document.getElementById("photos-tags-bodystyle");
  var td_bodystyle = document.getElementById("photos-tags-bodystyle-data");
  var tr_phototype = document.getElementById("photos-tags-phototype");
  var td_phototype = document.getElementById("photos-tags-phototype-data");
  var tr_context = document.getElementById("photos-tags-context");
  var td_context = document.getElementById("photos-tags-context-data");
  var tr_others = document.getElementById("photos-tags-others");
  var td_others = document.getElementById("photos-tags-others-data");
  var photo_caption = document.getElementById("car-photo-caption");
  
  var showTags = false;
  var html_others = "";
  
  var s_images = null;

  

  
  if(table_tags != null) {
    if(tr_vehiclelist != null && td_vehiclelist != null) {
      var html_vehicle = "";
      var html_bodystyle = "";
      var html_angle = "";
      
      for(var i = 0; i < resp.vehicles.length; i++) {
        var v = resp.vehicles[i];
        var elems = [v.year, v.make, v.model, v.trim];
        for(var j = 0; j < elems.length; j++) {
          if(elems[j] != null && typeof(elems[j]) != "undefined") {
            if(html_vehicle != "") html_vehicle += ", ";
            html_vehicle += '<a href="' + resp.browsetopicurl + '?topic=' + encodeURIComponent(elems[j]) + '">' + elems[j] + '</a>';
          }
        }
        
        if(v.bodystyle != null && typeof(v.bodystyle) != "undefined") {
          if(html_bodystyle != "") html_bodystyle += ", ";
          html_bodystyle += '<a href="' + resp.browsetopicurl + '?topic=' + encodeURIComponent(v.bodystyle) + '">' + v.bodystyle + '</a>';
        }
        
        if(v.anglename != null && typeof(v.anglename) != "undefined") {
          if(html_angle != "") html_angle += ", ";
          html_angle += v.anglename.en;
        }
        else {
          if(v.angle != null && typeof(v.angle) != "undefined") {
            if(html_angle != "") html_angle += ", ";
            //html_angle += '<a href="' + resp.browsetopicurl + '?topic=' + encodeURIComponent(v.angle) + '">' + v.angle + '</a>';
            html_angle += v.angle;
          }
        }
        
        if(v.color != null && typeof(v.color) != "undefined") {
          if(html_others != "") html_others += ", ";
          html_others += '<a href="' + resp.browsetopicurl + '?topic=' + encodeURIComponent(v.color) + '">' + v.color + '</a>';
        }
      }
      
      if(html_vehicle != "") {
        td_vehiclelist.innerHTML = html_vehicle;
        tr_vehiclelist.style.display = "";
        showTags = true;
      }
      else {
        tr_vehiclelist.style.display = "none";
      }
      
      if(html_bodystyle != "") {
        td_bodystyle.innerHTML = html_bodystyle;
        tr_bodystyle.style.display = "";
        showTags = true;
      }
      else {
        tr_bodystyle.style.display = "none";
      }

      if(html_angle != "") {
        if(photo_caption != null) {
          if(photo_caption.innerHTML != "") photo_caption.innerHTML += ", ";
          photo_caption.innerHTML += html_angle;
        }
        td_phototype.innerHTML = html_angle;
        tr_phototype.style.display = "";
        showTags = true;
      }
      else {
        tr_phototype.style.display = "none";
      }
    }
    
   
    
    if(tr_context != null) {
      if(resp.context != null && typeof(resp.context) != "undefined") {
        td_context.innerHTML = '<a href="' + resp.browsetopicurl + '?topic=' + encodeURIComponent(resp.context) + '">' + resp.context + '</a>';
        tr_context.style.display = "";
        showTags = true;
      }
      else {
        tr_context.style.display = "none";
      }
    }  
    
    if(tr_others != null) {
      for(var key in resp) {
        if(key != "browsetopicurl" && key != "context" && typeof(resp[key]) == "string" && key != "score" && key != "score_images") {
          if(html_others != "") html_others += ", ";
          html_others += '<a href="' + resp.browsetopicurl + '?topic=' + encodeURIComponent(resp[key]) + '">' + resp[key] + '</a>';
        }
        else if(key == "score_images") {
          s_images = resp[key];
        }
      }
      
      if(html_others != "") {
        td_others.innerHTML = html_others;
        tr_others.style.display = "";
        showTags = true;
      }
      else {
        tr_others.style.display = "none";
      }
     
      if(s_images != null) {
        var st = document.getElementById("ratingstars");
        
        setVisible("thanks", false); 
        setVisible("needlogin",false);
        setVisible("already_rated",false); 

        var rateInfo= document.getElementById("rating");
        if(rateInfo != null) {
          rateInfo.value=''
        }
        setVisible("rate_this",true);
        
        
        if(st != null) {
          st.innerHTML = s_images;          
        }
      }
    }
    
    if(showTags) {
      table_tags.style.display = "";
    }
    else {
      table_tags.style.display = "none";
    }
  }
  // added for gallery photos.
  else {
      for(var key in resp) {
      
      if (key == "score_images") {
        s_images = resp[key];
      }
    }
      if(s_images != null) {
        var st = document.getElementById("ratingstars");
        
        setVisible("thanks", false); 
        setVisible("needlogin",false);
        setVisible("already_rated",false); 
  
        var rateInfo= document.getElementById("rating");
        if(rateInfo != null) {
          rateInfo.value=''
        }
        setVisible("rate_this",true);        
      
      
      if(st != null) {
        st.innerHTML = s_images;        
      }
    }
  }
    
}

function photo_tag_update_failure(o) {

}

function old_view_full_size(w,h) {
//  var xy2 = YAHOO.util.Dom.getXY('mode-bigphoto');
  var o = document.getElementById("photo-fullsize");
  if(o != null) { // && o.width != "" && o.height != "") {
    photo_main_slideshow_stop();
    fadeCenterBox("photo-fullsize-container", w!=null ? w:o.width, h!=null ? h:o.height)
//    YAHOO.util.Dom.setXY('photo-fullsize-container',xy2);
//    YAHOO.util.Dom.setStyle('photo-fullsize-container','width', 775+'px');
//    YAHOO.util.Dom.setStyle('photo-fullsize-container','height',(775*3)/4+'px');
    
  }
  return false;
}

function fade_out_page(opt_callback) {
  YAHOO.util.Dom.setStyle("fadeblock", "display", "block");
  YAHOO.util.Dom.setStyle("fadeblock", "opacity", 0);
  YAHOO.util.Dom.setStyle("fadeblock", "width", YAHOO.util.Dom.getDocumentWidth() + "px");
  YAHOO.util.Dom.setStyle("fadeblock", "height", YAHOO.util.Dom.getDocumentHeight() + "px");
  var a = new YAHOO.util.Anim("fadeblock", { opacity: { from: 0, to: 0.6 } }, 0.2, YAHOO.util.Easing.easeNone);
  if(opt_callback != null && typeof(opt_callback) == "function") {
    a.onComplete.subscribe(opt_callback);
  }
  a.animate();
}

function get_real_element_dimension(elname,dimname,attrs,dim_override) {
  res = 0;
  if(dim_override==null) {
    res = parseInt(YAHOO.util.Dom.getStyle(elname,dimname));
  }
  else {
    res = parseInt(dim_override);
  }

  for (x in attrs) {
    res += parseInt(YAHOO.util.Dom.getStyle(elname,attrs[x]));
  }

  return res;  
}

function get_real_element_width(elname,width_override) {
  return get_real_element_dimension(elname,'width',['border-left-width','padding-left','border-right-width','padding-right'],width_override);
}

function get_real_element_height(elname,height_override) {
  return get_real_element_dimension(elname,'height',['border-top-width','padding-top','border-bottom-width','padding-bottom'],height_override);
}

function view_normal_size(cc) {
 YAHOO.util.Dom.setStyle("small-photo", "display", "");
 YAHOO.util.Dom.setStyle("margin-top-left", "padding-top", "0px");
                          
 YAHOO.util.Dom.setStyle("margin-top-right", "padding-top", "0px");
  if(typeof(temp_car_photos) != "undefined" ) 
    car_photos=temp_car_photos;
  isModeNormal=true;
  if( typeof(photo_main_slideshow_wasrunning) != "undefined" && photo_main_slideshow_wasrunning!= null && photo_main_slideshow_wasrunning!= false) {
      photo_main_slideshow_start();
  }
  YAHOO.util.Dom.setStyle('full-size-padder-center','display','none');
  YAHOO.util.Dom.setStyle('full-size-padder-right','display','none');
// YAHOO.util.Dom.setStyle('goback-vehicle-details','display','');
  YAHOO.util.Dom.setStyle('photo-viewer-tab','display','');
  YAHOO.util.Dom.setStyle('photo-viewer-tab-ul','display','');
  //YAHOO.util.Dom.setStyle('car-photo-container','display','');
  YAHOO.util.Dom.setStyle('link-full-size','display','');
  YAHOO.util.Dom.setStyle('link-smaller-size','display','none');
  YAHOO.util.Dom.setStyle('full-size-photo-container','display','none');
  YAHOO.util.Dom.setStyle('full-size-photo-container','position','absolute');
  YAHOO.util.Dom.setStyle('car-photo-src','display','');
  YAHOO.util.Dom.setStyle('title-h2-container','display','');
  YAHOO.util.Dom.setStyle('photo-index','display','');
  YAHOO.util.Dom.setStyle('tab-photos-slider','display','');  
  YAHOO.util.Dom.setStyle('tab-photos-slider-content','display','');
  YAHOO.util.Dom.setStyle('tab-photos-list','display',''); 
  YAHOO.util.Dom.setStyle('car-photo-mastercontainer','height',(cc==null?'570px':'363px')); // 570 //363 cc!=null
  YAHOO.util.Dom.setStyle('car-photo-container','height',(cc==null?'363px':'377px')); 
  var i = document.getElementById('car-photo-src');
  if(i!=null){
    i.src = car_photos[car_photo_number-1].p+'?scale=484x363';
  }
}
function patch_used(on) {
  if(on==null){
    on=false;
  }
  if(on) {
    YAHOO.util.Dom.setStyle('car-photo-container','height','596px');
    YAHOO.util.Dom.setStyle('car-photo-mastercontainer','height','596px');    
    YAHOO.util.Dom.setStyle('img-full-size-photo-container','display','');
    YAHOO.util.Dom.setStyle('img-full-size-photo-container','opacity',1);
  } else {
    YAHOO.util.Dom.setStyle('car-photo-container','height','430px');
    YAHOO.util.Dom.setStyle('car-photo-mastercontainer','height','434px');
    YAHOO.util.Dom.setStyle('img-full-size-photo-container','display','none');
  }
}

function view_full_size(w,h,cc){

  // These three for used cars only.
  YAHOO.util.Dom.setStyle("small-photo", "display", "none");
  YAHOO.util.Dom.setStyle("margin-top-left", "padding-top", "640px")
  YAHOO.util.Dom.setStyle("margin-top-right", "padding-top", "640px")
  YAHOO.util.Dom.setStyle('photo-viewer-tab','display','none');
  YAHOO.util.Dom.setStyle('photo-viewer-tab-ul','display','none');


  YAHOO.util.Dom.setStyle('car-photo-src','display','none');
  if(cc==null) {
    YAHOO.util.Dom.setStyle('img-full-size-photo-container','opacity',0);
  }
  isModeNormal=false;
  if(photo_main_slideshow_isrunning()){
    photo_main_slideshow_wasrunning = true;
  } else {
    photo_main_slideshow_wasrunning = false;
  }
  photo_main_slideshow_stop();
  YAHOO.util.Dom.setStyle('full-size-padder-center','display','');
  YAHOO.util.Dom.setStyle('full-size-padder-right','display','');
  YAHOO.util.Dom.setStyle('link-smaller-size','display','');
  YAHOO.util.Dom.setStyle('full-size-photo-container','display','');
  YAHOO.util.Dom.setStyle('full-size-photo-container','position','absolute');
  YAHOO.util.Dom.setStyle('link-full-size','display','none');
  YAHOO.util.Dom.setStyle('title-h2-container','display','none');
  YAHOO.util.Dom.setStyle('photo-index','display','none');
  YAHOO.util.Dom.setStyle('tab-photos-slider','display','none');
  YAHOO.util.Dom.setStyle('tab-photos-slider-content','display','none');
  YAHOO.util.Dom.setStyle('tab-photos-list','display','none'); 
  YAHOO.util.Dom.setStyle('car-photo-mastercontainer','height',(cc==null?'700px':'677px'));//677 // 700
  YAHOO.util.Dom.setStyle('car-photo-container','height',(cc==null?'670px':'0px')); 
  var i = document.getElementById('img-full-size-photo-container');
  if(i!=null) {
    photo_main_change_update();
  }
  temp_car_photos=car_photos;
  new_car_photos=[];
  for(var j=0;j<car_photos.length;j++) {
    if(car_photos[j].v==null) {
      new_car_photos[new_car_photos.length]=car_photos[j];
    }
  }
  car_photos=new_car_photos;
}

photo_tags_cache = {};

PHOTO_MAIN_CHANGE_MAX_HEIGHT = 363;
PHOTO_MAIN_CHANGE_MAX_WIDTH = 484;

function photo_main_change_update(update_counter) {
  if(typeof(isModeNormal) == "undefined") isModeNormal=false;
  if(update_counter)
    car_photo_switch++;
  if(update_counter && car_photo_switch != 0 && car_photo_switch % 3 == 0 && typeof(abmsManager) != "undefined") abmsManager.refreshAllSlots();
  
  var cpmc = document.getElementById("car-photo-mastercontainer");
  
  if(cpmc != null && cpmc.style.display != 'none' && document.getElementById("full-size-photo-container")!=null && document.getElementById("full-size-photo-container").style.display=='none' ){
    isModeNormal=true;
  }
  var photo = car_photos[car_photo_number - 1];
  if(photo != null) {
    if(photo.p.substring(photo.p.length - 1) == "?") {
      photo.p = photo.p.substring(0, photo.p.length - 1);
    }
    
    var photo_number = document.getElementById("car-photo-number");
    
    var photo_elem = document.getElementById(isModeNormal?"car-photo-src":"img-full-size-photo-container");
    var photo_caption = document.getElementById("car-photo-caption");
    var photo_date = document.getElementById("car-photo-date");
    var photo_articles = document.getElementById("car-photo-articles");
    var photo_src_link = document.getElementById("car-photo-src-link");
    
    if(photo_src_link != null && typeof(XPRIMA.use_pic_ids) != "undefined" && XPRIMA.use_pic_ids) {
      if(typeof(photo.picid) != "undefined") {
        window.location.href = "#" + photo.picid;
        photo_src_link.href = window.location.href;
      }
    }
    
    var raterid = document.getElementById("rateitrid");
    if(raterid != null) {
      raterid.value = photo.i;
    }
   
    if(typeof(photo_tags_cache[photo.i]) != "undefined") {
      photo_tag_update_success(photo_tags_cache[photo.i]);
      
    }
    else {
      // Begin AJAX request to update tags before we update the image...
      cb = {
        success: photo_tag_update_success,
        failure: photo_tag_update_failure,
        argument: [photo.i]
      };
      
      resource_tags_url = "/site/support/ajax_tagsforresource.spy?rid=" + photo.i.toString() + "&language=" + escape(js_auto123_language);
      YAHOO.util.Connect.resetFormState();
      YAHOO.util.Connect.asyncRequest("GET", resource_tags_url, cb, null);
      YAHOO.util.Connect.resetFormState();
    }
    
    if(photo_number != null && photo_elem != null) {
      photo_number.innerHTML = car_photo_number.toString();
      if(photo_caption != null) {
        photo_caption.innerHTML = photo.c;
        photo_caption.style.display = (photo.c != null && photo.c != "") ? "block" : "none";
      }
      
      if(photo.v != null) {
        // A handler was specified
        try {
          eval("var f = (" + photo.v + ")");
        }
        catch(e) {
          
          var f = null;
        }
        
        if(f != null && typeof(f) != "undefined") {
          f(photo);
          return;
        }
      }

      toggleVisibilitySwap('viewer-mode', 'viewer-photo', 'viewer-photo');
      YAHOO.util.Dom.setStyle(photo_elem.id, "opacity", 0);
      
      photo_elem.onload = function() { var an = new YAHOO.util.Anim(photo_elem.id, { opacity: { from: 0, to: 1 } }, 0.2, YAHOO.util.Easing.easeNone); an.animate(); };
      photo_elem.src = __uns__ ? photo.p + (isModeNormal ? "?scale=484x323" : "?scale=792x528") : photo.p;
      
      var large_photo = document.getElementById("photo-fullsize");
      if(large_photo != null) {
        large_photo.src = __uns__ ? photo.p + (isModeNormal ? "?scale=484x323" : "?scale=792x528") : photo.p;
      }
      
      if(!__uns__) {
        if(photo.w > PHOTO_MAIN_CHANGE_MAX_WIDTH) {
          new_h = photo.h * PHOTO_MAIN_CHANGE_MAX_WIDTH / photo.w;
          if(new_h > PHOTO_MAIN_CHANGE_MAX_HEIGHT) {
            photo_elem.style.width = (PHOTO_MAIN_CHANGE_MAX_WIDTH * PHOTO_MAIN_CHANGE_MAX_HEIGHT / new_h).toString() + "px";
            photo_elem.style.height = PHOTO_MAIN_CHANGE_MAX_HEIGHT.toString() + "px";
          }
          else {
            photo_elem.style.width = PHOTO_MAIN_CHANGE_MAX_WIDTH.toString() + "px";
            photo_elem.style.height = "";
          }
        }
        else {
          if(photo.h > PHOTO_MAIN_CHANGE_MAX_HEIGHT) {
            photo_elem.style.width = "";
            photo_elem.style.height = PHOTO_MAIN_CHANGE_MAX_HEIGHT.toString() + "px";
          }
          else {
            photo_elem.style.width = photo.w.toString() + "px";
            photo_elem.style.height = "";
          }
        }
      }

      if(photo_date != null) photo_date.innerHTML = photo.ed;
      //photo_elem.src = photo.p;

      if(photo_articles != null) {
        var HTML_Block = "";
        if(photo.a.length > 0 && typeof(car_photo_articles[photo.a[0]]) != "undefined") {
          for(var j = 0; j < photo.a.length; j++) {
            var articles = car_photo_articles[photo.a[j]];
            if(typeof(articles) != "undefined") {
              for(var i = 0; i < articles.length; i++) {
                HTML_Block += '<li><a href="' + articles[i].link + '">' + articles[i].title + '</a></li>';
              }
            }
          }
        }
        else {
          var deftext = photo_articles.getAttribute("defaulttext");
          if(deftext != null) {
            HTML_Block += "<li>" + deftext + "</li>";
          }
        }
        photo_articles.innerHTML = HTML_Block;
      }
    }
  }
}


function initImageSliders(paramObj) {
  var el;
  var elcount;
  var images;
  var tabname;
  
  p_imagesInView = (paramObj != null && typeof(paramObj.imagesInView) != "undefined") ? paramObj.imagesInView : 5;
  p_imageShift = (paramObj != null && typeof(paramObj.imageShift) != "undefined") ? paramObj.imageShift : p_imagesInView;
  p_imageWidth = (paramObj != null && typeof(paramObj.imageWidth) != "undefined") ? paramObj.imageWidth : 84;
  p_shiftBy = (paramObj != null && typeof(paramObj.shiftBy) != "undefined") ? paramObj.shiftBy : 420;

  if(car_photo_images_all != "") {
    tabname = "tab-photos-all";
    el = document.getElementById(tabname + "-content");
    if(el != null) {
      CarPhoto_All = new ImageShifter(el.id, { images:car_photo_images_all, imagesInView:p_imagesInView, imageShift:p_imageShift, className:'car-photo-selector-all', imageWidth:p_imageWidth, shiftBy:p_shiftBy, onclick:car_photo_select_image });
      elcount = document.getElementById(tabname + "-count");
      if(elcount != null)
        elcount.innerHTML = car_photo_imagesidx_all.length.toString();
    }

    tabname = "tab-photos-exterior";
    el = document.getElementById(tabname + "-content");
    if(el != null) {
      if(car_photo_images_exterior != "") {
        CarPhoto_Exterior = new ImageShifter(el.id, { images:car_photo_images_exterior, imagesInView:p_imagesInView, imageShift:p_imageShift, className:'car-photo-selector-exterior', imageWidth:p_imageWidth, shiftBy:p_shiftBy, onclick:car_photo_select_image });
        el = document.getElementById(tabname);
        if(el != null) {
          elcount = document.getElementById(tabname + "-count");
          if(elcount != null)
            elcount.innerHTML = car_photo_imagesidx_exterior.length.toString();
          el.style.display = "";
        }
      }
    }

    tabname = "tab-photos-interior";
    el = document.getElementById(tabname + "-content");
    if(el != null) {
      if(car_photo_images_interior != "") {
        CarPhoto_Interior = new ImageShifter(el.id, { images:car_photo_images_interior, imagesInView:p_imagesInView, imageShift:p_imageShift, className:'car-photo-selector-interior', imageWidth:p_imageWidth, shiftBy:p_shiftBy, onclick:car_photo_select_image });
        el = document.getElementById(tabname);
        if(el != null) {
          elcount = document.getElementById(tabname + "-count");
          if(elcount != null)
            elcount.innerHTML = car_photo_imagesidx_interior.length.toString();
          el.style.display = "";
        }
      }
    }

    tabname = "tab-photos-360view";
    el = document.getElementById(tabname + "-content");
    if(el != null) {
      if(car_photo_images_360 != "") {
        CarPhoto_360 = new ImageShifter(el.id, { images:car_photo_images_360, imagesInView:p_imagesInView, imageShift:p_imageShift, className:'car-photo-selector-view', imageWidth:p_imageWidth, shiftBy:p_shiftBy, onclick:car_photo_select_image });
        el = document.getElementById(tabname);
        if(el != null) {
          elcount = document.getElementById(tabname + "-count");
          if(elcount != null)
            elcount.innerHTML = car_photo_imagesidx_360.length.toString();
          el.style.display = "";
        }
      }
    }
  }
}

function car_photo_select_image(e, img) {
  photo_main_slideshow_stop();
  var idx = car_photo_indexes[img];
  if(__uns__ && idx == null) {
    var c = 0;
    for(i in car_photo_indexes) {
      if(img.indexOf(i + "/") == 0) {
        idx = c;
        break;
      }
      c++;
    }
  }
  
  if(typeof(idx) != "undefined" && idx != null) {
    car_photo_number = idx + 1;
    photo_main_change_update(true);
  }
  
  toggleVisibilitySwap('photo-mode', 'mode-bigphoto', 'mode-bigphoto');
  var o = document.getElementById("car-photo-thumbnails-btn");
  if(o != null && o.style.display != "") { o.style.display = ""; }
  o = document.getElementById("car-photo-number-str");
  if(o != null && o.style.display != "") { o.style.display = ""; }
  
  return false;
}

function filterOutMov(car_photo) {
  if(car_photo!=null) {
    if(car_photo.v!=null) {
      return false;
    } else {
      return true;
    }
  }
  return false;
}
function patch_car_photos() {
  fotos =[]
  for (var i=0;i<car_photos.length;i++) {
    if (car_photos[i].v==null) {
      fotos[fotos.length] = car_photos[i];
    }
  }
  car_photos=fotos;
}

function unpatch_car_photos(root) {
  var indexes;
  var i;
  indexes = car_photo_imagesidx_360;
  car_photos = [];
  for(i = 0; i < indexes.length; i++)
    car_photos[i] = car_photos_all[indexes[i]];
  car_photo_indexes = {};
  for(var pi = 0; pi < car_photos.length; pi++)
    car_photo_indexes[root + car_photos[pi].p] = pi;

}





function car_photo_build(indexes,filterHandler,list_to_use) {
  the_list = (list_to_use == null) ? car_photos : list_to_use;
  
  s = "";
  for(var i = 0; i < indexes.length; i++) {
    if(filterHandler!=null && typeof(filterHandler)=="function") {
      if (filterHandler(the_list[indexes[i]])) {
        if(s.length > 0) s += ",";
        s += the_list[indexes[i]].p;
      } 
    } else {
      if(s.length > 0) s += ",";
      s += the_list[indexes[i]].p;
    }
  }
  return s;
}

function tabs_activate(tabkey, tabid, default_tabid, abms_op) {
  if(typeof(generic_tabs[tabkey]) == "undefined")
    generic_tabs[tabkey] = { tab: document.getElementById(default_tabid), content: document.getElementById(default_tabid + "-content") };
  var tab = document.getElementById(tabid);
  var tab_content = document.getElementById(tabid + "-content");
  if(tab != null && generic_tabs[tabkey].tab.id != tabid) {
    generic_tabs[tabkey].tab.className = "lightbluebg2";
    if(generic_tabs[tabkey].content != null) {
      generic_tabs[tabkey].content.style.display = "none";
    }
    
    tab.className = "altlightbluebg";
    generic_tabs[tabkey].tab = tab;
    generic_tabs[tabkey].content = tab_content;
    
    if(tab_content != null) {
      tab_content.style.display = "";
    }
    if (abms_op != null && abms_op=="refresh_banners") {
      abmsManager.refreshAllSlots();
    }
    tab.blur();
  }
  return false;
}

function tabs_activate_sifr(tabkey, tabid, default_tabid) {
  if(typeof(generic_tabs[tabkey]) == "undefined")
    generic_tabs[tabkey] = { tab: document.getElementById(default_tabid), content: document.getElementById(default_tabid + "-content") };
  var tab = document.getElementById(tabid);
  var tab_content = document.getElementById(tabid + "-content");
  if(tab != null && generic_tabs[tabkey].tab.id != tabid) {
    generic_tabs[tabkey].tab.className = "lightbluebg2";
    if(generic_tabs[tabkey].content != null) {
      generic_tabs[tabkey].content.style.display = "none";
    }
    
    tab.className = "altlightbluebg";
    generic_tabs[tabkey].tab = tab;
    generic_tabs[tabkey].content = tab_content;
    
    if(tab_content != null) {
      tab_content.style.display = "";
    }
    
    tab.blur();
    abmsManager.refreshAllSlots();
  }
  
  if(typeof(sIFR) != "undefined") {
    sIFR.replace(helvetica, { selector: 'h2', css: [ '.sIFR-root { color: #067CAE; font-size:14px; text-align:left; font-weight:bold; text-transform: uppercase;}' ], wmode: 'transparent', tuneHeight:-6, offsetTop:0 });
    sIFR.replace(helvetica, { selector: 'h3', css: [ '.sIFR-root { color: #0076B1; font-size:14px; text-align:left; font-weight:bold; text-transform: uppercase;}' ], wmode: 'transparent', tuneHeight:-6, offsetTop:0 });
  }
  
  return false;
}

function toggleVisibilitySwap(tabkey, tabid, default_tabid, flagRefreshBanners) {
  if(typeof(generic_tabs[tabkey]) == "undefined")
    generic_tabs[tabkey] = { tab: document.getElementById(default_tabid), content: null };
    
  var tab = document.getElementById(tabid);
  if(tab != null) {
    if(tab.style.display == 'none')
      //tab.style.display = tab.style.display == 'none' ? "" : 'none';
      tab.style.display = "";
    if(generic_tabs[tabkey].tab != null && generic_tabs[tabkey].tab.id != tabid && tab.style.display != "none") {
      generic_tabs[tabkey].tab.style.display = "none";
    }
    generic_tabs[tabkey].tab = tab;
    tab.blur();
    if( flagRefreshBanners != null && flagRefreshBanners) {
      abmsManager.refreshAllSlots();
    }
  }
  return false;
}

function toggleVisibilityHide(tabkey) {
  if(typeof(generic_tabs[tabkey]) != "undefined") {
    var d = generic_tabs[tabkey];
    
    if(typeof(d.tab) != "undefined") {
      d.tab.style.display = "none";
    }
  }
  return false;
}

function car_photos_prepare_tab_photos(type, root) {
  var i;
  var indexes;

  photo_main_slideshow_stop();

  switch(type) {
    case 'all':
      indexes = car_photo_imagesidx_all;
      break;
    case 'exterior':
      indexes = car_photo_imagesidx_exterior;
      break;
    case 'interior':
      indexes = car_photo_imagesidx_interior;
      break;
    case '360view':
      indexes = car_photo_imagesidx_360;
      break;
    default:
      indexes = null;
      break;
  }

  if(indexes != null) {
    // Reset car_photos
    car_photo_number = 1;
    car_photos = [];
    for(i = 0; i < indexes.length; i++)
      car_photos[i] = car_photos_all[indexes[i]];

    // Reset car_photo_indexes
    car_photo_indexes = {};
    for(var pi = 0; pi < car_photos.length; pi++)
      car_photo_indexes[root + car_photos[pi].p] = pi;

    var max = document.getElementById("car-photo-number-max");
    if(max != null)
      max.innerHTML = car_photos.length.toString();
    photo_main_change_update();
  }
}

function perfectcar_listPackageContents(stuffid, desc, lng, carid) {
  var url = "builder_ajax_getpackage.spy?id=" + escape(stuffid.toString()) + "&lng=" + escape(lng) + "&carid=" + escape(carid.toString());
  var r = ajax_fetch(url);

  if(p != null) {
    var packageBoxID = "perfectcar-package-box";
    packageBox = document.getElementById(packageBoxID);
    if(packageBox == null) {
      var packageBox = document.createElement("div");
      packageBox.setAttribute("id", packageBoxID);
      packageBox.setAttribute("style", "display: none;");
      document.body.appendChild(packageBox);
    }
  }

  return false;
}

function compare_add_car(f, makeObj, modelObj, yearObj, make_startIdx, model_startIdx, year_startIdx) {
  if(make_startIdx == null) make_startIdx = 0;
  if(model_startIdx == null) model_startIdx = 0;
  if(year_startIdx == null) year_startIdx = 0;

  if(makeObj != null && modelObj != null && yearObj != null) {
    if(makeObj.selectedIndex >= make_startIdx && modelObj.selectedIndex >= model_startIdx && yearObj.selectedIndex >= year_startIdx) {
      f.submit();
    }
  }
  return false;
}

function my123_save(savetype, callbacks, waitIconElem, other_params) {
  /*
  SPECIAL NOTE!  This function take multiple arguments that use javascript's 'arguments'
  object... all parameters following the last element listed are: id1, id2, id3, ..., idN

  should get called by the proper save function... should not be called directly
  */

  if(waitIconElem) {
    waitIconElem.className = "wait-icon";
  }

  var url = "/site/support/my123_save," + new Date().getTime().toString() + ".spy?savetype=" + savetype;
  var success = false;
  
  var AVAILABLE_ARGS = 4;

  for(var i = AVAILABLE_ARGS; i < arguments.length; i++) {
    url += "&id" + (i - (AVAILABLE_ARGS - 1)).toString() + "=" + encodeURIComponent((arguments[i] && !isNaN(arguments[i])) ? arguments[i] : "");
  }
  
  if(other_params != null) {
    for(p in other_params) {
      url += "&" + p + "=" + encodeURIComponent(other_params[p]);
    }
  }

  var r = null;
  //var o = ajax_fetch(url);
  var o = createXMLHttpRequestObject();
  get_xmlwait(o, url);
  
  var responseText = (typeof(o.responseText) != "undefined") ? o.responseText : "";
  if(responseText == null) responseText = "";
  while(responseText.length > 0 && (responseText.charAt(0) == '\n' || responseText.charAt(0) == '\r')) {
    responseText = responseText.length > 1 ? responseText.substring(1) : "";
  }
  
    
  if(o.status == 200 && responseText.charAt(0) == "{") {
    eval("r = (" + responseText + ")");
    success = r.success;
  }

  if(waitIconElem) {
    waitIconElem.className = "";
  }

  if(success) {
    if(callbacks.success) {
      callbacks.success(o, callbacks.successArgs ? callbacks.successArgs : null);
    }
  }
  else {
    if(callbacks.failure) {
      callbacks.failure(o, r, callbacks.failureArgs ? callbacks.failureArgs : null);
    }
  }

  return false;
}

function my123_savecomparison(linkid, idlist) {
  var link = document.getElementById(linkid);
  if(link != null) {
    link.className = "wait-icon";
  }

  var callback = {
    success: my123_savecomparison_success,
    failure: my123_savecomparison_failure,
    successArgs: [linkid],
    failureArgs: [linkid]
  };

  var params = [3, callback, link];
  for(var i = 0; i < idlist.length; i++)
    params[params.length] = idlist[i];
  return my123_save.apply(this, params);
}

function my123_savecar(carid, linkid) {
  var link = document.getElementById(linkid);
  var parentNode;
  if(link != null && link.parentNode != null) {
    parentNode = link.parentNode;
    parentNode.className = "wait-icon";
  }

  var callback = {
    success: my123_savecar_success,
    failure: my123_savecar_failure,
    successArgs: [linkid],
    failureArgs: [linkid]
  };

  return my123_save(1, callback, parentNode, carid);
}

function finddealer_launch(url, pc) {
  document.location.href = url + "&KM=25&PC=" + encodeURIComponent(pc);
  return false;
}

function quickiequote_launch(url, pc) {
  document.location.href = url + "&PC=" + encodeURIComponent(pc);
  return false;
}

function compare_toggle_mysavedcars(elid) {
  var o = document.getElementById(elid == null ? "compare-mysavedcars" : elid);
  if(o != null) o.style.display = o.style.display == "none" ? "block" : "none";
}

function builder_view_package(language, carid, stuffid, parentid) {
  //return; // not ready

  var key = stuffid.toString() + "-" + parentid.toString();
  var pid = "package" + key + "-parent";
  var cid = "package" + key + "-content";
  var attr;

  var p = document.getElementById(pid);
  var c = document.getElementById(cid);

  if(p != null && c != null) {
    attr = c.getAttribute("fetched");
    if(p.style.display == "none" || attr == null) {
      if(attr == null) {
        c.innerHTML = '<div class="wait-icon" style="height: 30px;">&nbsp;</div>';
        p.style.display = "";

        var url = "/" + language + "/carcontainer/builder_ajax_getpackage.spy?carid=" + carid.toString() + "&id=" + stuffid.toString() + "&lng=" + escape(language);
        var cb = {
          success: builder_view_package_success,
          failure: builder_view_package_failure,
          argument: [p, c, language, carid]
        };

        YAHOO.util.Connect.resetFormState();
        YAHOO.util.Connect.asyncRequest("GET", url, cb, null);
      }
      else {
        p.style.display = "";
      }
    }
    else {
      p.style.display = "none";
    }
  }
  return;
}

function builder_view_package_success(o) {
  var p = o.argument[0];
  var c = o.argument[1];
  var l = o.argument[2];
  var carid = o.argument[3];

  if(p != null && c != null) {
    try {
      eval("var response = (" + o.responseText + ")");
    }
    catch(err) {
      var response = null;
    }

    if(response != null) {
      var t = ""
      var i;
      var op;
      t += '<div style="padding-bottom: 8px;"><table class="cleantable" style="width: 100%; border: 1px solid #dddddd; border-top: 0; font-size: 11px !important;">';
      for(i = 0; i < response.content.length; i++) {
        op = response.content[i];
        t += '<tr><td style="vertical-align: center; width: 14px; padding: 4px 0 0 0;"><img src="/site/img/perfectcar/dlister.gif" border="0" alt="" class="DepMarker"></td>';
        t += '<td style="vertical-align: center; padding: 3px 4px 3px 0;" colspan="' + (op.ispackage ? "1" : "3") + '">' + op.description;
        if(op.detail != null && op.detail != "")
          t += '<input type="button" class="packagebutton" value="?" onclick="alert(\'' + op.detail + '\');">';
        t += '</td>';

        if(op.ispackage && op.numchildren > 0) {
          t += '<td nowrap>&nbsp;</td>';
          t += '<td><input type="button" class="packagebutton" value="<spy=lng.viewpackage/>" onclick="blur(); builder_view_package(\'' + l + '\', ' + carid + ', ' + op.id + ', ' + op.parentid + ');"></td>';
        }

        t += '</tr>';
        if(op.ispackage && op.numchildren > 0) {
          t += '<tr id="package' + op.stuffid.toString() + '-' + op.parentid + '-parent" style="display: none;">';
          t += '<td colspan="2" id="package' + op.stuffid.toString() + '-' + op.parentid + '-content"></td>';
          t += '</tr>';
        }
      }
      t += '</table></div>';
      c.setAttribute("fetched", "1");
      c.innerHTML = t;
    }
  }
}

function builder_view_package_failure(o) {

}

function car_finder_search(f, url) {
  if(car_finder_timer != null) {
    clearTimeout(car_finder_timer);
    car_finder_timer = null;
  }
  
  var e = document.getElementById("car-finder-result-content");
  if(e != null) {
    setVisible("pleasewait", true);

    var callback = { success  : car_finder_search_success,
                     failure  : car_finder_search_failure,
                     argument : [e] };

    YAHOO.util.Connect.resetFormState();
    YAHOO.util.Connect.setForm(f.id);
    YAHOO.util.Connect.asyncRequest('POST', url, callback, null);
    YAHOO.util.Connect.resetFormState();
  }
}

function car_finder_search_success(o) {
  var e = o.argument[0];
  if(e != null) { // double check... shouldn't have to... but it's free!
    setVisible("pleasewait", false);
    e.innerHTML = o.responseText;
  }
}

function car_finder_search_failure(o) {
  setVisible("pleasewait", false);
}

function get_nodes_with_initialid(parent_node, nodetype, start_id, validator_func) {
  var o;
  var _objs;
  var objs = [];
  
  if(typeof(nodetype) == "string") {
    _objs = parent_node.getElementsByTagName(nodetype);
  }
  else {
    _objs = [];
    for(var i = 0; i < nodetype.length; i++) {
      _o = parent_node.getElementsByTagName(nodetype[i]);
      for(var j = 0; j < _o.length; j++) {
        _objs[_objs.length] = _o[j];
      }
    }
  }  
  
  for(var i = 0; i < _objs.length; i++) {
    o = _objs[i];
    if(o.id != "" && o.id != null && o.id.substring(0, start_id.length) == start_id && validator_func(o)) {
      objs[objs.length] = o;
    }
  }
  return objs;
}

function car_finder_cb_checker(obj) {
  return obj.checked;
}

function car_finder_checker(obj) {
  switch(obj.nodeName.toLowerCase()) {
    case 'input':
      return obj.checked;
    case 'select':
    case 'select-one':
      return (obj.selectedIndex > 0);
    default:
      return false;
  }
}

function car_finder_build_summary(form_id, nodetype, start_id, validator_func, attr) {
  var s = "";
  var f = document.getElementById(form_id);
  if(f != null) {
    var objs = get_nodes_with_initialid(f, nodetype, start_id, validator_func);
    for(var i = 0; i < objs.length; i++) {
      if(s != "") s += ", ";
      switch(objs[i].nodeName.toLowerCase()) {
        case 'input':
          s += objs[i].getAttribute(attr);
          break;
        case 'select':
        case 'select-one':
          s += objs[i].options[objs[i].selectedIndex].text;
          break;
      }      
    }
  }
  return s;
}

function car_finder_bymake_summary(o) {
  if(o != null) {
    var e = document.getElementById(o.id + "-summary");
    if(e != null) {
      if(o.style.display == "none")
        e.innerHTML = car_finder_build_summary("car-finder-form", "input", "m_", car_finder_cb_checker, "value");
      e.style.display = (o.style.display == 'none' ? "" : "none");
    }
  }
}

function car_finder_byprice_summary(o) {
  if(o != null) {
    var e = document.getElementById(o.id + "-summary");
    if(e != null) {
      if(o.style.display == "none")
        e.innerHTML = car_finder_build_summary("car-finder-form", "input", "p_", car_finder_cb_checker, "summary");
      e.style.display = (o.style.display == 'none' ? "" : "none");
    }
  }
}

function car_finder_bybodystyle_summary(o) {
  if(o != null) {
    var e = document.getElementById(o.id + "-summary");
    if(e != null) {
      var s = "";
      var s2 = "";
      if(o.style.display == "none") {
        s += car_finder_build_summary("car-finder-form", "input", "bsc_", car_finder_cb_checker, "summary");
        s2 = car_finder_build_summary("car-finder-form", "input", "bst_", car_finder_cb_checker, "summary");
        if(s2 != "") {
          if(s != "") s += ", ";
          s += s2;
        }
      }
      e.innerHTML = s;
      e.style.display = (o.style.display == 'none' ? "" : "none");
    }
  }
}

function car_finder_byyear_summary(o) {
  if(o != null) {
    var e = document.getElementById(o.id + "-summary");
    if(e != null) {
      if(o.style.display == "none")
        e.innerHTML = car_finder_build_summary("car-finder-form", "input", "y_", car_finder_cb_checker, "value");
      e.style.display = (o.style.display == 'none' ? "" : "none");
    }
  }
}



function car_finder_performance_toggle(o) {
  if(o != null) {
    var e = document.getElementById(o.id + "-summary");
    if(e != null) {
      if(o.style.display == "none") {
        e.innerHTML = car_finder_build_summary("car-finder-form", ["select", "input"], "o_", car_finder_checker, "summary");
      }
      if(isBlank(e.innerHTML)) {
        e.style.display = "none";
      }
      else {
        e.style.display = (o.style.display == 'none' ? "" : "none");
      }
    }
  }
}

function car_finder_options_toggle(o) {
  if(o != null) {
    var e = document.getElementById(o.id + "-summary");
    if(e != null) {
      if(o.style.display == "none") {
        e.innerHTML = car_finder_build_summary("car-finder-form", ["select", "input"], "oo_", car_finder_checker, "summary");
      }
      if(isBlank(e.innerHTML)) {
        e.style.display = "none";
      }
      else {
        e.style.display = (o.style.display == 'none' ? "" : "none");
      }
    }
  }
}

car_finder_timer = null;
car_finder_form = null;
car_finder_timer_delay = 2000;
function car_finder_trigger_delayed_submit(f) {
  if(car_finder_timer != null) {
    clearTimeout(car_finder_timer);
    car_finder_timer = null;
  }
  car_finder_form = f;
  car_finder_timer = setTimeout('car_finder_execute_form_submit()', car_finder_timer_delay);
}

function car_finder_execute_form_submit() {
  if(car_finder_timer != null) {
    clearTimeout(car_finder_timer);
    car_finder_timer = null;
  }
  if(car_finder_form != null) car_finder_form.submit();  
}

function car_finder_results_page(f, pg, url) {
  f.pg.value = pg.toString();
  car_finder_search(f, url)
  return false;
}

function toggleCheckbox(cbid) {
  var o = document.getElementById(cbid);
  if(o != null) {
    o.checked = !o.checked;
    car_finder_trigger_delayed_submit(o.form);
  }
  return false;
}

/* not used 20080325NH
function compare_start(f, lng) {
  if(f.carid.selectedIndex == -1 || f.carid.options[f.carid.selectedIndex].value == "") {
    alert(lng == 'fr' ? "Veuillez sélectionner une marque et un modèle parmi la liste et réessayer !" : "Please select a make and a model from the list and try again!");
    return false;
  }
  f.submit();
  return false;
}
*/

function select_option(select, text_or_value)  {
  for(var idx = 0; idx < select.options.length; ++idx)  {
    if(select.options[idx].value == text_or_value || select.options[idx].text == text_or_value)  {
      select.selectedIndex = idx;
      break;
    }
  }
}

function newcarquote_mycarselect(f, lng, make, model)  {
  select_option(f.make, make);
  ajax_updateModelsWithYearsAsCarID(f.make, f.carid, 1, 1, lng, model);
  return false;
}

function reviews_create_submit(f, lng) {
  if(f.make.selectedIndex > 0 && f.model.selectedIndex > 0 && f.year.selectedIndex > 0) {
    f.submit();
    return false;
  }
  
  if(lng == 'en')
    alert("Please select the vehicle's make, model and year!");
  else
    alert("Veuillez sélectionner la marque, le modèle et l'année du véhicule !");
  
  return false;
}

function rating_star_click(eid, sid, hover) {
  var idname = "star-" + eid.toString() + "-" + sid.toString();
  var e = document.getElementById(idname);
  var i;
  
  if(e != null) {
    var a = e.getAttribute("phase");
    var new_phase;
    a = 2;
    var s = document.getElementById("e" + eid.toString());
    
    if(a == null) a = "0";
    switch(a) {
      /*
      case '2':
        if(s != null && s.value != "" && !isNaN(s.value) && parseInt(s.value) > (sid * 2) + 2)
          new_phase = { id: 1, src: img_star_phase1.src };
        else
          new_phase = { id: 0, src: img_star_phase0.src };
        break;
      case '1':
        new_phase = { id: 2, src: img_star_phase2.src };
        break;
      default:
        new_phase = { id: 1, src: img_star_phase1.src };
        break;
      */
      
      case '2':
        if(s != null && s.value != "" && !isNaN(s.value) && parseInt(s.value) > (sid * 2) + 2)
          new_phase = { id: 2, src: img_star_phase2.src };
        else
          new_phase = { id: 1, src: img_star_phase1.src };
        break;
        break;
      case '1':
        new_phase = { id: 0, src: img_star_phase0.src };
        break;
      default:
        new_phase = { id: 2, src: img_star_phase2.src };
        break;
      
    }
    
    var score = (sid * 2) + new_phase.id;
    if(s != null) s.value = score.toString();
    
    for(i = 0; i < 5; i++) {
      var o = document.getElementById("star-" + eid.toString() + "-" + i.toString());
      if(o != null) {
        if(i < sid) {
          o.setAttribute("phase", "2");
          o.src = img_star_phase2.src;
        }
        else if(i == sid) {
          o.setAttribute("phase", new_phase.id.toString());
          o.src = new_phase.src;
        }
        else if(i > sid) {
          o.setAttribute("phase", "0");
          o.src = img_star_phase0.src;
        }
      }
    }    
  }
}

function checkVIN(o, im) {
  if(o.value != "" && o.value.length == 17) {
    if(validateVIN(o.value) == "") {
      im.src = "/site/img/perfectcar/dependency.gif";
    }
    else {
      im.src = "/site/img/perfectcar/exclusion.gif";
    }
  }
  else {
    im.src = "/site/img/spacer.gif";
  }
}

function trim_list_submit(f, carlist, url) {
  var i;
  var oname;
  var o;
  var _url;
  var s = [];
  var specialcase = null;
  
  for(i = 0; carlist != null && i < carlist.length; i++) {
    oname = "cmp" + carlist[i].toString();
    if(typeof(f[oname]) != "undefined") {
      o = f[oname];
      if(o.checked) {
        if(carlist[i] > 0) {
          s[s.length] = o.value;
        }
        else {
          specialcase = o.value;
        }
      }
    }
  }
  
  if(specialcase != null) {
    s[s.length] = specialcase;
  }
  
  if(s.length > 0) {
    _url = url + "?carid=" + s[0].toString();
    for(i = 1; i < s.length; i++) {
      _url += "&id" + (i + 1).toString() + "=" + s[i].toString();
    }
    
    document.location.href = _url;
  }
  
  return false;
}

function consumer_review_setpage(pg) {
  var basename = "create-review-step";
  var pg1 = document.getElementById(basename + "1");
  var pg2 = document.getElementById(basename + "2");
  var pg100=document.getElementById(basename + "100");
  
  var uri = null;
  if(typeof("pageTracker") != "undefined") {
    var uriIdx = document.location.href.indexOf("//");
    if(uriIdx != -1) {
      var uriD = document.location.href.substring(uriIdx + 2);
      uriIdx = uriD.indexOf("/");
      if(uriIdx != -1) {
        uri = uriD.substring(uriIdx);
        uriIdx = uri.indexOf("?");
        if(uriIdx != -1) {
          uri = uri.substring(1, uriIdx);
        }
      }
    }
  }
  
  if(pg1 != null && pg2 != null) {
    if(pg == 1) {
      pg1.style.display = 'block';
      pg2.style.display = 'none';
      pg100.style.display = 'none';
      document.location.href = "#pg1";
      if(uri != null && typeof("pageTracker") != "undefined") {
        pageTracker._trackPageview(uri + '-step2');
      }
    }
    else if(pg == 100) {
      if(validateReview(false)) {
        pg2.style.display = 'none';
        pg1.style.display = 'none';
        pg100.style.display = 'block';
        document.getElementById('top_04').src="/fr/site/img/contest/participate_top_04_off.gif";
        document.getElementById('top_05').src="/fr/site/img/contest/participate_top_05_on.gif";
        if(uri != null && typeof("pageTracker") != "undefined") {
          pageTracker._trackPageview(uri + '-step2');
        }
      }
    }
    else {
      if(validateReview(false)) {
        pg2.style.display = 'block';
        pg1.style.display = 'none';
        pg100.style.display = 'none';
        document.location.href = "#pg2";
        if(uri != null && typeof("pageTracker") != "undefined") {
          pageTracker._trackPageview(uri + '-step2');
        }
      }
    }
  }
  
  return false;
}

function newcars_hub_validate_get_quote(f) {
  if(f.make.selectedIndex <= 0) {
    return false;
  }
  
  if(f.carid.selectedIndex <= 0) {
    return false;
  }
  
  if(isBlank(f.PC.value)) {
    return false;
  }
  
  return true;
}

function newcars_hub_validate_find_dealer(f) {
  if(f.make.selectedIndex <= 0) {
    return false;
  }
  
  if(isBlank(f.PC.value)) {
    return false;
  }
  
  return true;
}

function newcars_bymake_popup(carid, idx, language, overview_url, build_url, compare_url) {
  if(language == null) language = 'en';
  var trimname = (language == 'en') ? 'trim' : 'version';  

  data = newcars_byprice_lineups[carid];
  if(typeof(data) != "undefined" && data != null) {
    if(idx == null)
      idx = "";
    
    var popup_container = document.getElementById("vpopup");
    var photo = document.getElementById("vpopup-photo");
    var modelname = document.getElementById("vpopup-modelname");
    var trims = document.getElementById("vpopup-trims");
    var msrp = document.getElementById("vpopup-msrp");
    var overview_link = document.getElementById("vpopup-link-overview");
    var build = document.getElementById("vpopup-build");
    var build_link = document.getElementById("vpopup-link-build");
    var compare_link = document.getElementById("vpopup-link-compare");
    
    if(popup_container != null) {
      if(photo != null) photo.src = data.p;
      if(modelname != null) modelname.innerHTML = data.v;
      if(trims != null) trims.innerHTML = data.c + " " + trimname + (data.c != 1 ? "s" : "");
      if(msrp != null) msrp.innerHTML = data.pr;
      if(overview_link) {
        //var url = overview_link.getAttribute("url");
        //overview_link.href = (url || "").replace("carid=0","carid=" + carid.toString());
        overview_link.href = overview_url;
      }
      if(build_link != null) {
        //var url = build_link.getAttribute("url");
        //build_link.href = (url || "").replace("carid=0","carid=" + carid.toString());
        build_link.href = build_url;
      }
      if(compare_link != null) {
        var url = compare_link.getAttribute("url");
        //compare_link.href = (url || "").replace("carid=0","carid=" + carid.toString());
        compare_link.href = compare_url;
      }
      
      if(idx != "") {
        var XY = YAHOO.util.Dom.getXY("vpopup-" + carid.toString());
        var XY = YAHOO.util.Dom.getXY("vpopup-" + carid.toString() + "-" + idx);
      }
      else
        var XY = YAHOO.util.Dom.getXY("vpopup-" + carid.toString());
      
      YAHOO.util.Dom.setStyle(popup_container.id, "display", "block")
      
      var cTop = YAHOO.util.Dom.getDocumentScrollTop();
      var cHeight = YAHOO.util.Dom.getViewportHeight();
      var bHeight = parseInt(YAHOO.util.Dom.getStyle(popup_container.id, "height"));
      
      if(XY[1] + bHeight >= (cTop + cHeight - 12)) {
        YAHOO.util.Dom.setXY(popup_container.id, [XY[0]-1,XY[1] - bHeight + 1]);
      }
      else {
        YAHOO.util.Dom.setXY(popup_container.id, [XY[0]-1,XY[1]-1]);
      }
    }
  }
  return false;
}

function change_location() {
  var o = document.getElementById("change-location");
  if(o != null) {
    o.style.display = o.style.display == "none" ? "" : "none";
  }
}

function newcars_build(f) {
  if(f.carid.selectedIndex > 0) return true;
  return false;
}

function review_rate(btn, f, respid, language) {
  btn.disabled = true;

  var responseNode = document.getElementById(respid);
  if(responseNode != null) {
    var cb = {
      success: review_rate_success,
      failure: review_rate_failure,
      argument: [responseNode, language, btn]
    };
  
    YAHOO.util.Connect.resetFormState();
    YAHOO.util.Connect.setForm(f);
    YAHOO.util.Connect.asyncRequest("GET", "/site/support/ajax_ratereview.spy", cb, null);
    YAHOO.util.Connect.resetFormState();
  }
}

function review_rate_success(o) {
  var responseNode = o.argument[0];
  var language = o.argument[1];
  
  eval("var r = (" + o.responseText + ")");
  if(typeof(r) != "object" || !r.success) {
    review_rate_failure(o, r);
    return;
  }
  
  if(language == 'en') {
    responseNode.innerHTML = "Your rating has been saved. Thank you for your input.";
  }
  else {
    responseNode.innerHTML = "Votre évaluation a été sauvegardée. Merci de votre collaboration.";
  }
}

function review_rate_failure(o, r) {
  var responseNode = o.argument[0];
  var language = o.argument[1];
  var btn = o.argument[2];
  
  btn.disabled = false;
  
  if(r != null && typeof(r) == 'object') {
    switch(r.reason) {
      case 'ERR_ALREADYRATED':
        if(language == 'en') alert("You have already rated this review or are the author of this review (authors may not rate their own reviews).")
        else alert("Vous avez déjà voté pour cette évaluation, ou bien celle-ci est votre évaluation (vous ne pouvez voter pour votre propre évaluation).");
        return;
      case 'ERR_NOREVIEWID':
        if(language == 'en') alert("Some important details about the review is missing. Please contact the administrator to let him know of this problem!");
        else alert("Des informations importantes sont manquantes. Veuillez en aviser l'administrateur du site!");
        return;
    }
  }
  else {
    if(language == 'en') {
      alert("An error occurred while trying to save your rating. Please try again.");
    }
    else {
      alert("Une erreur s'est produite lors de la sauvegarde de votre vote. Veuillez réessayer.");
    }
  }
}

function newcars_carfinder_compare(f) {
  
  var url = "";
  var inputs = f.getElementsByTagName("input");
  var cb = [];
  var params = "";
  for(var i = 0; i < inputs.length; i++) {
    var t = inputs[i].getAttribute("type");
    if(t != null && t.toLowerCase() == 'checkbox' && inputs[i].checked && inputs[i].name.substring(0, 3) == 'cmp') {      
      cb[cb.length] = 1;
      if(cb.length == 1) {
        var s6= 'link'+inputs[i].name.substring(3);
        url = document.getElementById('link'+inputs[i].name.substring(3)).value;
        params += "carid=" + inputs[i].value; // #20091217 ML Bugzilla #87:old way of building url
      } else // #20091217 ML Bugzilla #87:old way of building url
        params += "&id" + cb.length.toString() + "=" + inputs[i].value; // #20091217 ML Bugzilla #87:old way of building url
    }
  }
  // #20091217 ML Bugzilla #87: Using the array of cars to compare to build proper URL.
  if(typeof(G_selectedCars)!="undefined") {
    var _params="";
    var l=G_selectedCars.length;
    var _i = 0;
    var _j = 0;
    for(_i=0;_i<l;_i++) {
      if(G_selectedCars[_i]) {
        if(_j) {
          _params += "&id"  + (_j+1) + '=' + G_selectedCars[_i].toString();
        } else {
          _params += "carid="  + G_selectedCars[_i].toString();
        }    
        _j++;
      }
    }
    params=_params;
  }
  if((url != "") &&(params != ""))
    document.location.href = url + "?" + params;
  return false;
}



function switch_tab_load_content(tabcontentid) {
  var tab = document.getElementById(tabcontentid);
  if(tab != null) {
    var a = tab.getAttribute("loaded");
    if(a == null || a != "1") {
      var url = tab.getAttribute("url");
      if(url != null && url != "") {
        YAHOO.util.Connect.resetFormState();
        var callback = {
          success: switch_tab_load_content_success,
          failure: switch_tab_load_content_failure,
          argument: [tab]
        };
        var c = YAHOO.util.Connect.asyncRequest("GET", url, callback, null);
      }
    }
  }
  
  return false;
}

function switch_tab_load_content_success(o) {
  var tab = o.argument[0];
  tab.innerHTML = o.responseText;
  tab.setAttribute("loaded", "1");
}

function bookmarkPage(pageid, lng) {
  my123_save(31, { success: bookmarkPage_success, failure: bookmarkPage_failure, successArgs: lng, failureArgs: lng }, null, { title: _bookmark_page_title_, qs: _bookmark_page_qs_ }, pageid)  
}

function bookmarkPage_success(o, args) {
  var e = document.getElementById("bookmark-this-page-link");
  if(e != null) {
    e.href = "#";
    e.onclick = "return false;";
    
    if(args == null || args == 'en') {
      e.innerHTML = '<img src="/site/img/icon/16/savedone.gif" border="0" align="absmiddle">&nbsp;Bookmark This Page';
    }
    else {
      e.innerHTML = '<img src="/site/img/icon/16/savedone.gif" border="0" align="absmiddle">&nbsp;Sauvegarder cette page';
    }
  }
}

function bookmarkPage_failure(o, args) {
  if(args == null || args == 'en') {
    alert("An error occured while trying to save the page. Please try again later.");
  }
  else {
    alert("Une erreur s'est produite lors de la sauvegarde de cette page. Veuillez réessayer!");
  }
}

function my123_save_items(savetype, linkid, imgid) {
  /*
    Arguments follow the last arg listed above (id1 - id12)
    This should be used with a simple link that contains a "save" graphic...
  */
  
  cb = {
    success: function(o, args) {
      var e = document.getElementById(args.linkid);
      if(e != null) {
        e.onclick = "return false;";
        var e2 = document.getElementById(args.imgid);
        if(e2 != null) {
          var im = new Image();
          im.src = "/site/img/icon/16/savedone.gif";
          e2.src = im.src;
        }
        else {
          var basic = e.getAttribute("basic");
          if(basic != null && basic == "1") {
            basic = e.getAttribute("lang");
            if(basic != null && basic == "fr") {
              e.innerHTML = "Sauvegard&eacute;";
            }
            else {
              e.innerHTML = "Saved";
            }
            e.className = "gray";
          }
        }
      }
    },
    
    failure: function(o, args) {
      alert("failure");
    },
    
    successArgs: { linkid: linkid, imgid: imgid},
    
    failureArgs: { linkid: linkid }
  };
  
  var other_params = null;
  if(typeof(_my123_data) != "undefined") {
    other_params = {
      title: _my123_data.title,
      description: _my123_data.description,
      ispublic: _my123_data.ispublic == true ? 1 : 0
    };
    
    try {
      other_params.qs = document.location.toString().split("//")[1].substring(document.location.toString().split("//")[1].indexOf("/"));
    }
    catch(err) {
      
      }    
  }  
  
  var AVAILABLE_ARGS = 3;
  var params = [savetype, cb, linkid, other_params];
  for(var i = AVAILABLE_ARGS; i < arguments.length; i++) {
    params[params.length] = arguments[i];
  }
  return my123_save.apply(this, params);
}

_my123_data = {
  savetype_name: null,
  title: null,
  url: null,
  savetype: null,
  uniqueid: null,
  ids: [],
  description: null,
  ispublic: false,
  icon: null
}

function my123_popup_login(savetype_name, title, url, savetype, uniqueid, icon) {
  /*
  IMPORTANT: id1-id12 after the icon
  */
  
  var addbookmark_box = document.getElementById('confirm-addbookmark');
  if(addbookmark_box != null) addbookmark_box.style.display = "none";
  
  _my123_data.savetype_name = savetype_name;
  _my123_data.title = title;
  _my123_data.url = url;
  _my123_data.savetype = savetype;
  _my123_data.uniqueid = uniqueid;
  _my123_data.description = null;
  _my123_data.ispublic = false;
  _my123_data.icon = icon;
  
  for(var i = 6; i < arguments.length; i++) {
    if(arguments[i] != null) _my123_data.ids[_my123_data.ids.length] = arguments[i];
  }
  
  var login_box = document.getElementById('loginpopup');
  if(login_box != null) {
    var un = document.getElementById("agun");
    var pw = document.getElementById("agpw");
    
    if(un != null) un.value = "";
    if(pw != null) pw.value = "";
    
    
    var failbox = document.getElementById("loginpopup-failure");
    if(failbox != null) failbox.style.display = "none";
  
    var w = YAHOO.util.Dom.getViewportWidth();
    var h = YAHOO.util.Dom.getViewportHeight();
    var t = YAHOO.util.Dom.getDocumentScrollTop();
    login_box.style.left = (parseInt(w / 2) - 295).toString() + "px";
    login_box.style.top = (parseInt(h / 2) - 70 + t).toString() + "px";
    login_box.style.display = 'block';
    
    YAHOO.util.Dom.setStyle("fadeblock", "display", "block");
    YAHOO.util.Dom.setStyle("fadeblock", "opacity", 0);
    YAHOO.util.Dom.setStyle("fadeblock", "width", YAHOO.util.Dom.getDocumentWidth() + "px");
    YAHOO.util.Dom.setStyle("fadeblock", "height", YAHOO.util.Dom.getDocumentHeight() + "px");
    
    var a = new YAHOO.util.Anim("fadeblock", { opacity: { from: 0, to: 0.5 } }, 0.2, YAHOO.util.Easing.easeNone);
    a.animate();
    
    if(un != null) un.focus();
  }
  
  return false;
}

function my123_action_addbookmark(savetype_name, title, url, savetype, uniqueid, icon, nofade) {
  /*
  IMPORTANT: id1-id12 after the nofade
  */

  var login_box = document.getElementById('loginpopup');
  if(login_box != null) login_box.style.display = "none";
  
  _my123_data.savetype_name = savetype_name;
  _my123_data.title = title;
  _my123_data.url = url;
  _my123_data.savetype = savetype;
  _my123_data.uniqueid = uniqueid;
  _my123_data.description = null;
  _my123_data.ispublic = false;
  _my123_data.icon = icon
  
  for(var i = 7; i < arguments.length; i++) {
    if(arguments[i] != null) _my123_data.ids[_my123_data.ids.length] = arguments[i];
  }
  
  var addbookmark_box = document.getElementById('confirm-addbookmark');
  if(addbookmark_box != null) {
    var el_savename = document.getElementById("bkmtype");
    var el_title = document.getElementById("bkmitem");
    var el_icon = document.getElementById("bkmimg");
    
    if(el_icon != null) {
      var im = new Image();
      im.src = icon;
      el_icon.src = im.src;
    }
    
    if(el_savename != null) el_savename.innerHTML = _my123_data.savetype_name;
    if(el_title != null) {
      if(_my123_data.url != null && _my123_data.title == null) {
        // Fetch title by calling page with special params....
        var aj = ajax_fetch(_my123_data.url);
        var resp = aj.responseText;        
        while(resp != null && resp.length > 0 && resp.charAt(0) != '{') resp = resp.substring(1);
        while(resp != null && resp.length > 0 && resp.charAt(resp.length - 1) != '}') resp = resp.substring(0, resp.length - 1);        
        eval("var pagedata = (" + resp + ")");
        _my123_data.title = pagedata.pagetitle;
      }
      if(_my123_data.title != null) {
        el_title.innerHTML = _my123_data.title;
      }
    }
  
    var w = YAHOO.util.Dom.getViewportWidth();
    var h = YAHOO.util.Dom.getViewportHeight();
    var t = YAHOO.util.Dom.getDocumentScrollTop();
    addbookmark_box.style.left = (parseInt(w / 2) - 150).toString() + "px";
    addbookmark_box.style.top = (parseInt(h / 2) - 70 + t).toString() + "px";
    addbookmark_box.style.display = 'block';
    
    if(nofade == null || nofade != true) {
      YAHOO.util.Dom.setStyle("fadeblock", "display", "block");
      YAHOO.util.Dom.setStyle("fadeblock", "opacity", 0);
      YAHOO.util.Dom.setStyle("fadeblock", "width", YAHOO.util.Dom.getDocumentWidth() + "px");
      YAHOO.util.Dom.setStyle("fadeblock", "height", YAHOO.util.Dom.getDocumentHeight() + "px");      
      var a = new YAHOO.util.Anim("fadeblock", { opacity: { from: 0, to: 0.5 } }, 0.2, YAHOO.util.Easing.easeNone);
      a.animate();
    }
    
    var desc = document.getElementById("bkmdescription");
    if(desc != null) {
      desc.value = "";
      desc.focus();
    }
  }

  return false;
}

function login_ajax_success(o) {
  var resp1 = o.responseText;
  result = resp1.match(/{.*?success.*?}/gim);
  
  if(result.length > 0) {
    resp1 = result[0];
    eval("var resp = (" + resp1 + ")");
   
  }
  else {
   
    var resp = {success: false};
  }
  
  if(resp.success) {
    
    var params = [_my123_data.savetype_name, _my123_data.title, _my123_data.url, _my123_data.savetype, _my123_data.uniqueid, _my123_data.icon, true];
    for(var i = 0; i < _my123_data.ids.length; i++)
      params[params.length] = _my123_data.ids[i];
    return my123_action_addbookmark.apply(this, params);
  }
  else {
    var failbox = document.getElementById("loginpopup-failure");
    if(failbox != null) failbox.style.display = "";
  }
}

function login_ajax_failure(o) {
  var failbox = document.getElementById("loginpopup-failure");
  if(failbox != null) failbox.style.display = "";
}

function login_ajax(f, url) {
  var failbox = document.getElementById("loginpopup-failure");
  if(failbox != null) failbox.style.display = "none";

  var cb = {
    success: login_ajax_success,
    failure: login_ajax_failure
  };
  
  YAHOO.util.Connect.resetFormState();
  YAHOO.util.Connect.setForm(f.id);
 
  YAHOO.util.Connect.asyncRequest("POST", url, cb, null)
  YAHOO.util.Connect.resetFormState();
}

function centerBox(boxid, width, height) {
  var cBox = document.getElementById(boxid);  
  if(cBox != null) {
    var w = YAHOO.util.Dom.getViewportWidth();
    var h = YAHOO.util.Dom.getViewportHeight();
    var t = YAHOO.util.Dom.getDocumentScrollTop();
    cBox.style.left = (parseInt(w / 2) - (width / 2)).toString() + "px";
    cBox.style.top = (parseInt(h / 2) - (height / 2) + t).toString() + "px";
  }
  
  return cBox;
}

function fadeCenterBox(boxid, width, height, fadeOnly) {
  var cBox = centerBox(boxid, width, height);
  if(cBox != null || fadeOnly == true) {
    if(cBox != null) {
      cBox.style.display = 'block';
      YAHOO.util.Dom.setStyle("fadeblock", "display", "block");
      YAHOO.util.Dom.setStyle("fadeblock", "opacity", 0);
      YAHOO.util.Dom.setStyle("fadeblock", "width", YAHOO.util.Dom.getDocumentWidth() + "px");
      YAHOO.util.Dom.setStyle("fadeblock", "height", YAHOO.util.Dom.getDocumentHeight() + "px");
      var a = new YAHOO.util.Anim("fadeblock", { opacity: { from: 0, to: 0.5 } }, 0.2, YAHOO.util.Easing.easeNone);
      a.animate();
    }
  }
  return false;
}

function removePopupBlock(boxid) {
  var cBox = document.getElementById(boxid);
  if(cBox != null)
    cBox.style.display = 'none';
  YAHOO.util.Dom.setStyle("fadeblock", "display", "none");
  return false;
}

function swf360ready(video) {
  var so = new SWFObject(video.vl, video.idname, video.size_w, video.size_h, "8", "#ffffff");
  so.write(video.idname);
}

function mov360ready(video) {
  // Ready :)
}


hub_scroll_review_moved = 0;
function hub_scroll_review(direction) {
  var o = document.getElementById("home-reviews");
  var shiftWidth = 613;
  
  if(o != null) {
    switch(direction) {
      case 'right':
        if(hub_scroll_review_moved == 0) {
          attribs = {
            points:  {
              by: [ (shiftWidth * -1), 0 ],
              control: [[(shiftWidth * -1) - 150, 0]]
            }
          };
          var anim = new YAHOO.util.Motion(o, attribs, 0.7, YAHOO.util.Easing.EaseOut);
          anim.animate();
          hub_scroll_review_moved = 1;
        }
        break;
        
      case 'left':
        if(hub_scroll_review_moved != 0) {
          attribs = {
            points:  {
              by: [ shiftWidth, 0 ],
              control: [[shiftWidth + 150, 0]]
            }
          };
        
          var anim = new YAHOO.util.Motion(o, attribs, 0.7, YAHOO.util.Easing.EaseOut);
          anim.animate();
          hub_scroll_review_moved = 0;
        }
        break;
    }
    
    o.blur();
  }

  return false;
}

//transolio

function trfunc(s) {
  map1='éâäàåçêëèïîìÄÅÉÈÈÇæÆôöòûùÖÜáíóúñÑ';
  map2='eaaaaceeeiiiAAEEECaaooouuOUaiounN';    
  var w = '';
  for (var i = 0; i < s.length; i++) {
    var j=map1.indexOf(s.charAt(i));    
    w += (j>-1) ? map2.charAt(j) : s.charAt(i);
  }
  return w
}

function urlize(lowercase,params) {
  var s =  '';
  
  for (var i = 1; i < arguments.length; i++) {
    if(arguments[i]==null || (arguments[i])=='') {
      s+='/';
      continue;
    }
    if (s!='' && s.charAt(s.length-1) != '/')
      s+= ' ';
    
    var d = trfunc(arguments[i]);
    s+= d.replace(/[^a-zA-Z0-9_ -]/g,'')
  }  
    
  if ((lowercase==null) || lowercase)
    s = s.toLowerCase(); 
            
  s = s.replace(/ /g,'-');
  s = s.replace(/--+/g,'-');
  
  return s;
}

function appendToAction(f, params) {
  if(f != null) {
    for(var i = 1; i < arguments.length; i++) {
      s = arguments[i];
      if(s!=null){
        if (f.action.charAt(f.action.length-1) != '/') f.action += '/';
        if (typeof(s) == "string") {          
          f.action += urlize(true,s);           
        } else if(s.selectedIndex>0) {              
          f.action += urlize(true,s.options[s.selectedIndex].value); 
        }  
      }  
    }
  }
}

function appendTextToAction(f, params) {
  if(f != null) {
    for(var i = 1; i < arguments.length; i++) {
      s = arguments[i];
      if(s != null) {
        if (f.action.charAt(f.action.length-1) != '/') f.action += '/';
        if (typeof(s) == "string") {
          f.action += urlize(true,s);
        }
        else if(typeof(s.nodeName) != "undefined" && s.nodeName.toLowerCase() == 'select') {
          f.action += urlize(true, s.options[s.selectedIndex].text);
        }
      }
    }
  }
}


function  showElement(tdid){
   e=document.getElementById(tdid);       
   if (e.style.display=="none")
   {
   e.style.display=""; 
  }         
}      
function  hideElement(tdid){
   e=document.getElementById(tdid);       
   if (e.style.display=="")
   {
   e.style.display="none"; 
  }  
  
}

function updateRatingStars(rid,lng){
  
  var cb = {
    success: function(o) 
    { 
      eval("rc = " + o.responseText);           
      if (rc.success)  {                                                                                
        _rs = document.getElementById("ratingstars");

        if(_rs != null) {         
          _rs.innerHTML = rc.newscore ; 
         
        }     
      }
      
    },
    failure: function(o){}
  } 
         
  var url = "/"+lng+"/site/support/ajax_getratings.spy?" + "rid=" + rid ;  
  YAHOO.util.Connect.asyncRequest('GET', url, cb, null);

}


function  rateThis(rid,binding,bid,f){ 


  var raterid = document.getElementById("rateitrid"); 
  if(raterid != null && raterid.value!= '') {    
    rid = raterid.value;   
  }

  var cb = {
    success: function(o) 
    {
      eval("rc = " + o.responseText);
      if (rc.success)  {                                                                                
        _rs = document.getElementById("ratingstars");
        if(_rs != null)
          _rs.innerHTML = rc.newscore //s;  //o.responseText;
        setVisible("thanks", true); //showElement("thanks");
        setVisible("rate_this",false); //hideElement("rate_this");
        
        _rid = rc.rid;
        if(_rid != null && typeof(_rid) != "undefined") {
          delete photo_tags_cache[_rid]
        }
      }
      
      else  {           
        if (rc.reason=='ALREADY_RATED')
        {   setVisible("already_rated",true);}
        else {  setVisible("needlogin",true);}
        setVisible("rate_this",false);
      }

    },
    failure: function(o){}
  } 
         
  var url = "/site/support/ajax_rating.spy?" + "rid=" + rid + "&binding=" + binding + "&bid=" + bid + "&score=" + f.rating.value    
  YAHOO.util.Connect.asyncRequest('GET', url, cb, null);
}

function talkback_set_close_text(idx1, idx2) {
  var o1 = document.getElementById("tb" + idx1.toString() + "_" + idx2.toString());
  var o2 = document.getElementById("talkback-close-" + idx1.toString() + "-" + idx2.toString());
  if(o1 != null && o2 != null) {
    if(js_auto123_language == 'en') {
      o2.innerHTML = (o1.style.display == 'none') ? "Open" : "Close";
    }
    else {
      o2.innerHTML = (o1.style.display == 'none') ? "Ouvrir" : "Fermer";
    }
  }
  return false;
}

function a123addthis_sendto() {
  track_this_page('/clic/addthis');
  return addthis_sendto();
}

function a123addthis_open() {
  track_this_page('/mouseover/addthis');
  return addthis_open.apply(null, arguments);
}

function track_this_page(page_path) {
  var pth ='/'+js_auto123_language+(page_path!=null && page_path.length!=0?(page_path[0]=="/"?page_path:"/"+page_path):'');
  if(typeof(pageTracker)!="undefined" && pageTracker != null) {
    // FC 2009.01.06 Fixed: Originally there was only one line here... the one found in the else!
    if(page_path != null)
      pageTracker._trackPageview(pth);
    else 
      pageTracker._trackPageview('/'+js_auto123_language+'/newsletter/form');
  }
  return false;
}


mailing_subscription_anim = null;
mailing_subscription_motion = null;
mailing_subscription_timer = null;

function mailing_list_popup(elid, listname) {

  if(typeof(pageTracker)!="undefined" && pageTracker != null) {
    pageTracker._trackPageview('/'+js_auto123_language+'/newsletter/form');
  }
  
  if(mailing_subscription_anim != null) {
    mailing_subscription_anim.stop();
  }
  
  if(mailing_subscription_motion != null) {
    mailing_subscription_motion.stop();
  }
  
  if(mailing_subscription_timer != null) {
    clearTimeout(mailing_subscription_timer);
    mailing_subscription_timer = null;
  }
  
  var ln =  document.getElementById("mailing-subscription-listname");
  if(ln != null) {
    ln.value = listname != null ? listname : "";
  }
  
  var f1 = document.getElementById("mailing-subscription-step1");
  var f2 = document.getElementById("mailing-subscription-step2");
  
  if(f1 != null && f2 != null) {
    f2.style.display = "none";
    f1.style.display = "block";
  }

  fadeCenterBox(elid == null ? "mailingsubscription" : null, elid == null ? 300 : null, elid == null ? 240 : null, true);
  
  var msgbox = document.getElementById("mailing-subscription-messages");
  if(msgbox != null) {
    if(js_auto123_language == 'en') {
      msgbox.innerHTML = "Enter your details below and click <b>Sign Me Up</b>!"
    }
    else {
      msgbox.innerHTML = "Entrez votre information et cliquer sur <b>Inscrivez-moi</b>!"
    }
  }
  
  mailing_subscription_anim = new YAHOO.util.Anim("mailingsubscription", { opacity: { from: 0, to: 1 }}, 0, YAHOO.util.Easing.easeIn);
  mailing_subscription_anim.animate();
  
  var xy = YAHOO.util.Dom.getXY(elid);
  var o = document.getElementById("mailingsubscription");
  if(o != null && typeof(xy[1]) != "undefined") {
    o.style.top = (xy[1] - 195).toString() + "px";
    o.style.left = (xy[0] + 120).toString() + "px";
    o.style.display = "block";
  }
  
  return false;
}

function mailing_list_close() {
  var o = document.getElementById('mailingsubscription');
  if(o != null) {
    o.style.display = 'none';
  }
  removePopupBlock();
}

function mailing_list_subscribe(f) {
  //var fullname = f.mlfullname.value;***SD
  var email = f.mlemail.value;
  
  //if(isBlank(fullname) || isBlank(email)) {***SD
  if(isBlank(email)) {
    if(js_auto123_language == 'en') {
      //mailing_list_failure("You must list your name and email address in order to subscribe to the Auto123.com newsletter!");***SD
      mailing_list_failure("You must list email address in order to subscribe to the Auto123.com newsletter!");
    }
    else {
      //mailing_list_failure("Vous devez spécifier votre nom et adresse courriel afin de vous inscrire à l'Infolettre d'Auto123.com !");***SD
      mailing_list_failure("Vous devez spécifier votre adresse courriel afin de vous inscrire à l'Infolettre d'Auto123.com !");
    }
  }
  else {
    if(js_auto123_language == 'en') {
      mailing_list_failure("Sending your subscription... Please wait...", true);
    }
    else {
      mailing_list_failure("Inscription en cours... veuillez patienter...", true);
    }
    
    var url = "/site/support/ajax_mailing_add.spy";
    var cb = { success: mailing_list_subscribe_success, failure: mailing_list_subscribe_failure };
    YAHOO.util.Connect.resetFormState();
    YAHOO.util.Connect.setForm(f.id);
    YAHOO.util.Connect.asyncRequest('GET', url, cb, null);
    YAHOO.util.Connect.resetFormState();
  }
  
  return false;
}

function mailing_list_failure(msg, nocolor) {
  var m = document.getElementById("mailing-subscription-messages");
  if(m != null) {
    if(nocolor == true) {
      m.innerHTML = msg;
    }
    else {
      m.innerHTML = '<span style="color: red;">' + msg + '</span>';
    }
  }
}

function mailing_list_subscribe_success(o) {
  eval("var resp = (" + o.responseText + ")");
  if(resp.success) {     
    if(typeof(pageTracker)!="undefined" && pageTracker != null) {
      pageTracker._trackPageview('/'+js_auto123_language+'/newsletter/form');
    }
    mailing_list_close()
    
    if(js_auto123_language == 'en') {
      document.location = "/en/newsletter/thank-you/";
    }
    else {
      document.location = "/fr/infolettre/merci/";
    }
  }
  else {
    mailing_list_failure(resp.reason);
  }
}

function mailing_list_subscribe_success_fade() {
  mailing_subscription_anim = new YAHOO.util.Anim("mailingsubscription", { opacity: { from: 1, to: 0 }}, 3, YAHOO.util.Easing.easeIn);
  mailing_subscription_motion = new YAHOO.util.Motion("mailingsubscription", { point: { by: [0,0] }}, 3, YAHOO.util.Easing.easeNone);
  mailing_subscription_motion.onComplete.subscribe(mailing_list_close);
  mailing_subscription_motion.animate();
  mailing_subscription_anim.animate();
}

function mailing_list_subscribe_failure(o) {
  if(js_auto123_language == 'en') {
    mailing_list_failure("An error occured while trying to subscribe you.  Please try again!");
  }
  else {
    mailing_list_failure("Une erreur s'est produite lors de l'inscription.  Veuillez essayer à nouveau!");
  }
}

// ---------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------
// Create an instance of the XMLHttpRequest object
function createXMLHttpRequestObject()
{
  var http = null;

  if(window.XMLHttpRequest) {
    http = new XMLHttpRequest();
  }
  else if(window.ActiveXObject) {
    try {
      http = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        http = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
        http = null;
      }
    }
  }

  return http;
}

// GET, async (requires callback)
function get_xmlasync(http, url, callback_func)
{
  _xmlHttpRequest_sendRequest(http, true, "GET", url, callback_func, null);
}

// POST, async (requires callback)
function post_xmlasync(http, url, callback_func, postdata)
{
  _xmlHttpRequest_sendRequest(http, true, "POST", url, callback_func, postdata);
}

// GET, BLOCKING
function get_xmlwait(http, url)
{
  _xmlHttpRequest_sendRequest(http, false, "GET", url, null, null);
}

// POST, BLOCKING
function post_xmlwait(http, url, postdata)
{
  _xmlHttpRequest_sendRequest(http, false, "POST", url, null, postdata);
}


function _xmlHttpRequest_sendRequest(http, async, method, url, callback_func, postdata)
{
  methodOK = false;

  if(method == "GET") {
    methodOK = true;
    http.open(method, url, async);
  }
  else if(method == "POST") {
    methodOK = true;
    http.open(method, url, async);
    http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    http.setRequestHeader('Accept-Charset','ISO-8859-1');
  }

  if(methodOK) {
    if(async) {
      if(callback_func != null) {
        http.onreadystatechange = callback_func;
      }
    }

    if(method == "POST") {
      http.send(postdata);
    }
    else {
      http.send(null);
    }
  }
}

function display_glossary_popup(word, definition, lng, posX, posY)
{
  var elemBox = document.getElementById('glossary-box');
  var elemWord = document.getElementById('glossary-word');
  var elemDef = document.getElementById('glossary-def');
  var elemCloseLink = document.getElementById('glossary-close-link');
  
  if(elemBox != null)
  { 
    elemBox.style.left = posX;    
    elemBox.style.top = posY;
        
    elemWord.innerHTML = word;
    elemDef.innerHTML = definition;
    elemBox.style.display = "block";
    
    if (lng == 'en')
      elemCloseLink.innerHTML = 'Close <img style="position:absolute;top:1px; right:-16px" src="/site/img/perfectcar/exclusiond.gif"/>';
    else
      elemCloseLink.innerHTML = 'Fermer <img style="position:absolute;top:1px; right:-16px" src="/site/img/perfectcar/exclusiond.gif"/>';
  }  
}
      
function show_glossary_popup(word, definition, lng, e)
{    
  var elemBox = document.getElementById('glossary-box');  
  var region = { top: 0, left: 0 };
  
  if (YAHOO.env.ua.ie != 0) {
    region = YAHOO.util.Dom.getRegion(e.srcElement);
    e.srcElement.blur();
  }
  else {
    region = YAHOO.util.Dom.getRegion(e.currentTarget);
    e.currentTarget.blur();
  }
  
  posX = region.left - 1;
  posY = region.top + 14;
  
  /*
  if (YAHOO.env.ua.ie != 0)
  {   
    posX = event.clientX;
    posY = event.clientY;
  }
  else
  {
    posX = e.pageX;
    posY = e.pageY;
  }
  */
  
  if (elemBox == null)
  {        
    var cb = {
      success: function(o){
        var body = document.body;
        var d = document.createElement('div');
        d.innerHTML = o.responseText;        
        body.appendChild(d);                       
        display_glossary_popup(word, definition, lng, posX, posY);         
      }    
    };
    
    YAHOO.util.Connect.resetFormState();
    YAHOO.util.Connect.asyncRequest("GET", '/site/support/ajax_worddef.spy', cb, null);    
  }
  else
  {    
    display_glossary_popup(word, definition, lng, posX, posY);
  }  
}

function close_glossary_popup()
{
  var elemBox = document.getElementById('glossary-box');
  elemBox.style.display = "none";
  
}

// ---------------------------------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------------------------------










/* Added to serve new home page
 */
function validateCarSearch(o) {
  return o.make.selectedIndex>=1 && o.model.selectedIndex>=1;
  }


function resetModels(o){
  while(o.options.length > 1) o.options[1] = null;
  o.selectedIndex = 0;
}


function newcars_makemodel_validate(f, links) {
  if((f != null)&&(links != null)) { 
    if(links.selectedIndex > 0) {
      window.location.href = links.options[links.selectedIndex].value;
    }
    else {
      alert("Please select a make and a model from the list and try again!");      
    }
  }
  return false;
}


function newcars_carfinder_validate(f) {
  //alert('newcars_carfinder_validate');
  return newcars_makemodel_validate(f, f.model);
}


/**
The function will try to find all <a> tags with 'hidden_addr' attribute.
If found, the element will be formated as a 'mailto' link.

The goal is to reduce the chance of scraping emails off the pages.

example:
<a href="" hidden_addr="<spy=ctx.car.person.email.split('@')/>">&nbsp;</a>

To enable this on a page add this line to the handler:
page.setOnLoad('populate_emails()')
*/
function populate_emails(){
  try{
    var els = document.getElementsByTagName('a');
    var email_tockens = '';
    for(i in els){
      var el = YAHOO.util.Dom.get(els[i]);
      
      if(el.getAttribute){
        email_tockens = el.getAttribute('hidden_addr');
      }else{
        // For some reason 'getAttribute' is not working in IE
        email_tockens = el.hidden_addr;
      }
      if(!email_tockens){
        continue;
      }
      var email = eval(email_tockens).join('@');
      
      el.href = 'mailto:' + email;
      el.innerHTML = email;
    }
  }catch(e){}
}


function GA_PhotoView(cpt) {
  if(GACUSTOMEV){
    try {
      var h1 = GA_pagetitle;
      var loc = 'Photo Galleries';
      img_idx_map = new Object();
      img_idx_map['a'] = car_photo_imagesidx_all;
      img_idx_map['e'] = car_photo_imagesidx_exterior;
      img_idx_map['i'] = car_photo_imagesidx_interior;
      img_idx_map['o'] = car_photo_imagesidx_360;
      h1=h1.replace(/<\/?h1>/gi,'');
      cpt_2_idx = img_idx_map[cpt];
      main_idx = cpt_2_idx[car_photo_number-1];
      label = car_photos_all[main_idx].evox ?  'evox' : 'auto123';
      _gaq.push(['_trackEvent', loc, h1, label]);
    } catch(err) {
    }
  }
}

