var root_url = document.domain;
var cookie_url = root_url;


/* =onload functions
-------------------= */

function init() {
    // quit if this function has already been called
    if (arguments.callee.done) {
        return;
    }

    // flag this function so we don't do the same thing twice
    arguments.callee.done = true;

    // kill the timer
    if (_timer) {
        clearInterval(_timer);
        _timer = null;
    }

    if(typeof(Ninbar) != "undefined") {
          ninbar = new Ninbar();
        setTimeout("ninbar.headlineTicker.nextHeadline(1, 0)", 300 );
    }
    if(typeof(initScrollers) != "undefined") {
        initScrollers();
    }

    if(typeof(initOverLabels) != "undefined") {
        var access = window.setInterval(initOverLabels, 50);
    }

    if(typeof(formFocus) != "undefined") {
        formFocus();
    }

    if(typeof(Cyclo) != "undefined" && document.getElementById("image-thumbs") != null) {
        var cyclo = new Cyclo();
        cyclo.init();
    }
};

/* for Mozilla */
if (document.addEventListener) {
    document.addEventListener("DOMContentLoaded", init, null);
}

/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
    document.write("<script id=__ie_onload defer src=javascript:void(0)></script>");
    var script = document.getElementById("__ie_onload");
    script.onreadystatechange = function() {
        if (this.readyState == "complete") {
            init(); // call the onload handler
        }
    };
/*@end @*/

/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
    var _timer = setInterval(function() {
        if (/loaded|complete/.test(document.readyState)) {
            init(); // call the onload handler
        }
    }, 10);
}

/* for other browsers */
window.onload = function() {
init();
fullurl = window.location.href;
/*@cc_on @*/
/*@if (@_win32)
    /*@end @*/
}

function gallery_pop(vURL,vW,vH) {
    vW = parseInt(vW,10)+20;

    vParams =  "location=0,status=1,scrollbars=1,left=5,top=5,width="+vW+",height="+vH;
    mywindow = window.open (vURL, "gallery_window", vParams);
    mywindow.moveTo(0,0);
    return false;
}

function getElementsByClassName(searchClass, node, tag) {
  var classElements = new Array();
  if (node == null) node = document;
  if (tag == null) tag = '*';
  var els = node.getElementsByTagName(tag);
  var elsLen = els.length;
  var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
  for (var i = 0, j = 0; i < elsLen; i++) {
      if (pattern.test(els[i].className)) {
        classElements[j] = els[i];
        j++;
      }
  }
  return classElements;
}


function initOverLabels () {
  if (!document.getElementById) return;

  var labels, id, field;

  // Set focus and blur handlers to hide and show
  // LABELs with 'overlabel' class names.
  labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {

    if (labels[i].className == 'overlabel') {

      // Skip labels that do not have a named association
      // with another field.
      id = labels[i].htmlFor || labels[i].getAttribute('for');
      if (!id || !(field = document.getElementById(id))) {
        continue;
      }

      // Change the applied class to hover the label
      // over the form field.
      labels[i].className = 'overlabel-apply';

      // Hide any fields having an initial value.
      if (field.value !== '') {
        hideLabel(field.getAttribute('id'), true);
      }

      // Set handlers to show and hide labels.
      field.onfocus = function () {
        hideLabel(this.getAttribute('id'), true);
      };
      field.onblur = function () {
        if (this.value === '') {
          hideLabel(this.getAttribute('id'), false);
        }
      };

      // Handle clicks to LABEL elements (for Safari).
      labels[i].onclick = function () {
        var id, field;
        id = this.getAttribute('for');
        if (id && (field = document.getElementById(id))) {
          field.focus();
        }
      };

    }
  }
};

function hideLabel (field_id, hide) {
  var field_for;
  var labels = document.getElementsByTagName('label');
  for (var i = 0; i < labels.length; i++) {
    field_for = labels[i].htmlFor || labels[i].getAttribute('for');
    if (field_for == field_id) {
      labels[i].style.textIndent = (hide) ? '-3000px' : '0px';
      return true;
    }
  }
}

function Collapsable (options) {
    var obj = this;
    // parent node
    this.node = options.node;
    // style of transition
    this.style = options.style || 'backEaseIn';
    // speed of transition
    this.speed = options.speed || 0.6;
    // find trigger, has classname of 'trigger'
    this.trigger = (function(){
        var set = obj.node.getElementsByTagName('*');
        for (var i=0; i < set.length; i++) {
            var node = set[i];
            if (node.className.indexOf('trigger') !== -1)
                return node;
        }
    })();
    // used to get the id of the collapsable node
    var href = this.trigger.getAttribute('href');
    // collapsable node
    this.target = document.getElementById(href.substring(href.indexOf('#') + 1, href.length));
    // check to see if already collapsed
    this.collapsed = (this.node.className.indexOf('collapsed') !== -1) ? true : false;

    //add [show >>] or [<< hide] to collapsable menus
    var firstElem = getFirstChildElement(obj.target.parentNode);
    if (this.collapsed && firstElem.lastChild.className == "OpenOrClose")
        firstElem.lastChild.innerHTML = "[show &gt;&gt;]";
    else if(!this.collapsed && firstElem.lastChild.className == "OpenOrClose")
        firstElem.lastChild.innerHTML = "[&lt;&lt; hide]";
    // initiate
    this.init();
}

Collapsable.prototype.init = function() {
    var obj = this;
    // hide overflow on target
    this.target.style.overflow = 'hidden';
    // set initial height
    if (!this.collapsed)
        this.target.style.height = this.target.scrollHeight + 'px'
    // on click run manage method to determain if should be expanding or collapsing
    this.trigger.onclick = function() {
        obj.manage();
        // cancel default
        return false;
    }
}

Collapsable.prototype.manage = function() {
    // check if collapsed
    if (this.collapsed)
        // run extend method
        this.expand();
    // otherwise
    else
        // run collapse method
        this.collapse();
}


Collapsable.prototype.collapse = function() {
    var obj = this;
    var firstElem = getFirstChildElement(obj.target.parentNode);
    // check that tween library exists
    if (typeof(Tween) !== 'undefined') {
        // create tween instance
        var t = new Tween(this.target.style,'height',Tween[this.style],this.target.offsetHeight,1,this.speed,'px');
        // start tween
        t.start();
        // when finished
        t.onMotionFinished = function() {
            // add collapsed classname
            obj.node.className += ' collapsed';
            // set collapsed
            obj.collapsed = true;
            // if it was open show [show >>] at the end
            if (firstElem.lastChild.className == "OpenOrClose")
                firstElem.lastChild.innerHTML = "[show &gt;&gt;]";
            else if (firstElem.innerHTML == "Remove extra makes and models")
                firstElem.innerHTML = "Add extra makes and models";
        }
                        // update the session attribute "expanded" to exclude this dimension ENDECA
                        updateExpandedSet(obj.node.id, "0");

    }
}

Collapsable.prototype.expand = function() {
    var obj = this;
    var firstElem = getFirstChildElement(obj.target.parentNode);
    // check that tween library exists
    if (typeof(Tween) !== 'undefined') {
        // create tween instance
        var t = new Tween(this.target.style,'height',Tween.backEaseOut,1,this.target.scrollHeight,this.speed,'px');
        // start tween
        t.start();
        // when finished
        t.onMotionFinished = function() {
            // remove collapsed classname
            obj.node.className = obj.node.className.replace(' collapsed','');
            // set collapsed
            obj.collapsed = false;
            // if it was closed show [<< hide] at the end
            if (firstElem.lastChild.className == "OpenOrClose")
                firstElem.lastChild.innerHTML = "[&lt;&lt; hide]";
            else if (firstElem.innerHTML == "Add extra makes and models")
                firstElem.innerHTML = "Remove extra makes and models";
        }
        // update the session attribute "expanded" to include this expanded dimension ENDECA
        updateExpandedSet(obj.node.id, "1");

    }
}

ExpandAll = function() {

    // create array of all divs in the document

    var divs = document.getElementsByTagName('div');

    // loop through all divs in document.

    for (var i=0; i < divs.length; i++) {

        // check for classname & if function exists

        if (divs[i].className.indexOf('collapsed') !== -1) {
            obj = new Collapsable ({node : divs[i]});
            obj.expand();
        }
    }
}

CollapseAll = function() {

    // create array of all divs in the document

    var divs = document.getElementsByTagName('div');

    // loop through all divs in document.

    for (var i=0; i < divs.length; i++) {

        // check for classname & if function exists

        if (divs[i].className.indexOf('collapsable') !== -1) {
            obj = new Collapsable ({node : divs[i]});
            obj.collapse();
        }
    }
}


//Returns the first child that is an element (type 1)
getFirstChildElement = function (node) {
    for (i=0; i<node.childNodes.length; i++){
            if (node.childNodes[i].nodeType == 1)
                return node.childNodes[i];
    }
    return null;
}

hideshow = function () {

    // create array of all divs in the document

    var divs = document.getElementsByTagName('div');

    // array of all the a in the document
    var links = document.getElementsByTagName('a');
    // loop through all divs in document.

    for (var i=0; i < divs.length; i++) {

        // check for classname & if function exists

        if (divs[i].className.indexOf('collapsable') !== -1 && typeof(Collapsable) !== 'undefined') {

            // create collapsable instance
            new Collapsable ({node : divs[i]});

        }

    }
    // check fot those links with an OpenOrClose class and make them clickable
    for(i=0; i<links.length; i++){
        if  (links[i].className=="OpenOrClose"){
                links[i].onclick = function() {
                    openclose (this);
                    return false;
                }
        }
        else if (links[i].className=="hideAll"){
                links[i].onclick = function() {
                        CollapseAll();
                        return false;
                }
        }
        else if (links[i].className=="showAll"){
                links[i].onclick = function() {
                        ExpandAll();
                        return false;
                }
        }
    }
}


openclose = function(node){

    var parent = node.parentNode.parentNode;
    obj = new Collapsable ({node : parent});
    obj.manage();

}

//rollover effect for IE
setIEHoverState = function () {
    el = getElementsByClassName("dealer_result");
    resTable = document.getElementById("results");
    resForm = getElementsByClassName("results");
    if(el) {
        for(i=0;i<el.length;i++){
            el[i].onmouseover= function(){
                this.className += ' over';
            }
            el[i].onmouseout = function(){
                this.className = 'dealer_result';
            }
        }
    }
    if(resTable) {
        resRow = resTable.getElementsByTagName("tr");
            for(i=1;i<resRow.length;i++){
                if (resRow[i].className != "adspace-strip" && resRow[i].getElementsByTagName("th").length == 0){
                    resRow[i].onmouseover= function(){
                        this.className=='priority' ? this.className='priorityOver' : this.className='Tover';
                    }
                    resRow[i].onmouseout = function(){
                        this.className == 'priorityOver' ? this.className = 'priority' : this.className = '';
                    }
                }
            }
    }
    if (resForm){
        for (i=0 ; i<resForm.length; i++){
            if (resForm[i].tagName == 'LABEL'){
                resForm[i].onmouseover= function(){
                    this.className=='priority' ? this.className='priorityOver' : this.className='Tover';
                }
                resForm[i].onmouseout = function(){
                    this.className == 'priorityOver' ? this.className = 'priority' : this.className = '';
                }
            }

        }
    }
}

if (window.attachEvent) window.attachEvent("onload", setIEHoverState); //use only in IE


function popup(url, Width, Height){
    window.open(url, "null", 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=660,height=600,left = 340,top = 112');
}


function AC_validateForm(){
var errors='';
    if((document.subscr_form.firstname.value=="")) {
            errors+='\n Please enter your first name.   ';
    }
    if(!validEmail(document.subscr_form.email.value)) {
                errors+='\n Please enter a valid email Address.   ';
    }

    if(!(document.subscr_form.mobile.value=="")) {
        if(!isNum(document.subscr_form.mobile.value)) {
                errors+='\n Your mobile number must contain numbers only.   ';
        }else{
            if(validSize(document.subscr_form.mobile.value)) {
                errors+='\n Your mobile number must be 10 digits or more.   ';
            }
        }
    }

    genderOption = -1;
    for(i=0; i<document.subscr_form.gender.length; i++){
        if(document.subscr_form.gender[i].checked)
          genderOption=i
        }
    if (genderOption == -1){
        errors+='\n Please enter your gender.   ';
    }

    if((document.subscr_form.postcode.value=="")) {
                errors+='\n Please enter your postcode.   ';
    }
    if((document.subscr_form.dob.value=="0")) {
                errors+='\n Please enter your year of birth.   ';
    }

    if(errors){
        alert('The following error(s) occurred:\n'+errors);
    }else{
        document.subscr_form.submit();
    }
}

function validate_required(field,alerttxt){
    with (field){
    if (value==null||value==""){
    alert(alerttxt);
    return false;
    var yyy=1;
    }
    else
    return true;
    }
}

function validate_form(thisform){
    with (thisform)
    {

    if (validate_required(firstname,"First name must be filled out")==false)
      {firstname.focus();return false;}

    if (validate_required(postcode,"Postcode must be filled out")==false)
      {postcode.focus();return false;}

    if (validate_radio("gender","Please choose your gender")==false)
      {return false;}

    if (validate_email(email, "Please enter a valid email address")==false)
      {email.focus();return false;}
    }
}

function validate_email(field,alerttxt){
    with (field)
    {
    var apos=value.indexOf("@");
    var dotpos=value.lastIndexOf(".");
    if (apos<1||dotpos-apos<2)
      {alert(alerttxt);return false;}
    else {return true;}
    }
}

function validate_radio(radioName,alerttxt){
    var radioOpts = $("input[name='"+radioName+"']:checked");
    if(radioOpts.length === 0){
        alert(alerttxt);
        return false;
    }else{
        return true;
    }
}


submitForm = function (bodytype, formtype){
    if (formtype == "type")
     var el = document.getElementById("cg_car_type");
    else if(formtype == "make")
     var el = document.getElementById("cg_car_make");
    el.value = bodytype;
    if (formtype == "type")
     document.bodytypeForm.submit();
    else if(formtype == "make")
     document.makeForm.submit();
}

/* font size change
------------------- */
var curFontSize = 1;
var fontModifier = 0.1;

function fontSize(act) {
    if (document.getElementById) {
        storyBody = document.getElementById("boxcontent");
        if (storyBody == null)
          storyBody = document.getElementById("article-corpus");
        if (act === 1) {
            curFontSize += fontModifier;
            curFontSize = Math.min(curFontSize, 1.4);
        } else if (act === 0) {
            curFontSize -= fontModifier;
            curFontSize = Math.max(curFontSize, 1);
        }
        storyBody.style.fontSize = curFontSize + "em";
    }
}


/* ENDECA */
function updateExpandedSet(dimval, status) {
    var httpRequest;

    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
        httpRequest = new XMLHttpRequest();

        if (httpRequest.overrideMimeType) {
            httpRequest.overrideMimeType('text/xml');
            // See note below about this line
        }
    }
    else if (window.ActiveXObject) { // IE
        try {
            httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!httpRequest) {
        alert('Giving up :( Cannot create an XMLHTTP instance');
        return false;
    }

    httpRequest.open('GET', "w6.0-search-results-maintain-expanded.jsp?dim=" + dimval + "&status=" + status, true);
    httpRequest.send(null);
}

function initTwisties() {
    // create array of all divs in the document
    var divs = document.getElementsByTagName('div');

    // loop through all divs in document.
    for (var i=0; i < divs.length; i++) {
        // check for classname & if function exists
        if ((divs[i].id.indexOf('panel-left') == -1) && (divs[i].className.indexOf('collapsable') != -1) && (typeof(Collapsable) != 'undefined')) {
            // create collapsable instance
            new Collapsable ({node : divs[i]});
        }
    }
}

/* NINBAR HBX tracking code */

var getEventTarget = function(e) {
    var ev = e || window.event;
    if (typeof ev === "undefined") {
        return false;
    }
    var targ = ev.target || ev.srcElement;
    if (targ.nodeType === 3) {
        // defeat Safari bug
        targ = targ.parentNode;
    }
    return targ;
};

var relListener = function() {
    var old = document.onmouseup || function() {};
    document.onmouseup = function(e) {
        var targ = getEventTarget(e);
        if (targ.nodeType === 1) {
            var rel = targ.getAttribute("rel");
            var url = targ.getAttribute("href");
            if (/track/.test(rel)) {
                var s = rel.match(/track-([a-zA-Z0-9-]*)/gi, "$1")[0] + "|" + encodeURI(window.location) + "-" + encodeURI(url);
                s = s.replace(/,/gi, "&#44;").replace(/track-/gi, "");
                _hbSet("cv.c9", s);
                _hbSend();
            }
        }
        old(e);
    };
};

hideContactForm= function(){
    document.getElementById("email-the-dealer").display="none";
}