/*
 @Name: $RCSfile: global.js,v $
 @Version: $Revision: 1.43.10.7.2.26 $
 @Date: $Date: 2009/12/15 19:29:41 $

 Copyright (C) 2007 Copart, Inc. All rights reserved.
 */
var errorNotSupported = "error: not supported";
var navArray = new Array("nav2VirtualSales", "nav2SearchAndBid", "nav2CompanyInfo", "nav2IndustryLinks");
var origSetNav = "";
var otherThumbs____global = null;

var whoIsOn = null; // DO NOT MODIFY
var timerFunction = null; // DO NOT MODIFY
var milliseconds = 1000; // DO NOT MODIFY
var seconds = .25; // Modify this to change the nav delay time.
var navTimeoutInterval = milliseconds * seconds; // DO NOT MODIFY
var showDamageTypePopUp = true; // Set for checking the damage code div status
var AllowNewPopups = true; // Allow popup to happin

/*
 * This function will disable all the form elements on the page.
 */
function disableAll(){
    var formElem = document.getElementsByTagName("input");
    for (var i = 0; i < formElem.length; i++) {
        if (formElem[i].type != "hidden") {
            formElem[i].disabled = true;
        }
    }
}

/*
 This function enables all the form elements on a page
 and removes the error div from the body so that it can
 be used again.
 */
function enableAll(obj){
    var formElem = document.getElementsByTagName("input");
    for (var i = 0; i < formElem.length; i++) {
        if (formElem[i].type != "hidden") {
            formElem[i].disabled = false;
        }
    }
    document.body.removeChild(obj);
}

/**
 Show/Hide selects in IE.
 This allows the divs to be displayed above select elements.
 If 'hidden' is specified, the selects will be hidden.
 If 'visible' is specified, the selects will be visible.

 Default behavior is to toggle between visible and hidden.
 */
function toggleSelects(f){
    var f = f ? f : '';
    var action;

    if (navigator.userAgent.indexOf("MSIE") != -1) {
        for (var S = 0; S < document.forms.length; S++) {
            for (var R = 0; R < document.forms[S].length; R++) {
                if (document.forms[S].elements[R].options) {

                    if (f != '' && f == 'hidden') {
                        action = 'hidden';
                    }
                    if (f != '' && f == 'visible') {
                        action = 'visible';
                    }

                    if (f == '') {
                        if (document.forms[S].elements[R].style.visibility == 'visible' ||
                        document.forms[S].elements[R].style.visibility == '') {
                            action = 'hidden';
                        }
                        else {
                            action = 'visible';
                        }
                    }
                    document.forms[S].elements[R].style.visibility = action;
                }
            }
        }
    }
}


/**
 *  This function will remove any collection of elements from the page's DOM
 *  @param obj - is the array of object ids that will be removed
 *               from the current page's DOM
 */
function removeElementFromDOM(obj){
    if (obj.length > 0) {
        for (var i = 0; i < obj.length; i++) {
            if ($(obj[i]) != null) {
                document.body.removeChild($(obj[i]));
            }
        }
    }
    AllowNewPopups = true;
}

/**
 *  This function will remove a comma seperated collection of elements from the page's DOM
 *  @param obj - is the comma separated object ids that will be removed from DOM
 *
 */
function removeElement(objs){
    // Force selects visible.
    toggleSelects('visible');

    if (objs.length > 0) {
        var splitObj = objs.split(",");
        for (var i = 0; i < splitObj.length; i++) {
            if ($(splitObj[i]) != null) {
                document.body.removeChild($(splitObj[i]));
            }
        }
    }
    AllowNewPopups = true;
}

/**
 * This function will close the T&C div and redirect the user to homepage
 */
function declineTandC(objs){
    var declineURL = "virtualsales.html"
    redirect(objs, declineURL);
}

/**
 * This function will close the logoff div and redirect the user to the logoff
 * Copart.com page.
 */
function logoff(objs){
    var logoutURL = "securitylogout.html";
    redirect(objs, logoutURL);
}

function redirect(objs, url){
    //removeElement(objs);
    var logoutURL = url;
    var tempURL = window.location.href;
    var locationOfQueryString = tempURL.indexOf("?");

    if (locationOfQueryString > -1) {
        tempURL = tempURL.substring(0, locationOfQueryString);
    }
    var splitURL = tempURL.split("/");
    var urlLength = splitURL.length; // Split the URL cause we dont need the
    // page url
    splitURL[urlLength - 1] = logoutURL; // Set the last element to the
    // logout url
    var endURL = "";
    // Loop through the items in the split url array
    for (var i = 0; i < urlLength; i++) {
        // Rebuild the url
        endURL = endURL + splitURL[i];
        if (i == 0) // If we are at first element 'http' the add an additional /
        {
            endURL = endURL + "/";
        }
        else // Just add / to create a properly formed url
        {
            endURL = endURL + "/";
        }
    }
    //Trim off the last /
    var trimmedURL = endURL.substring(0, endURL.length - 1);
    // Set window url to logoff user
    window.location.href = trimmedURL;
}

/**
 * This function is to be used to create logoff div popup.
 */
function getInfoDivPageLogout(){
    var params = null;
    createInfoDivPopup(null, 'Divs/logoff', params, true);
}

/**
 * This function is used to display the damage code div on mouseover
 */
function getDamageCodePopup(){
    if (!AllowNewPopups) {
        return
    }
    showDamageTypePopUp = true;

    // If there is already a popup open, close it
    if ($("info-div-global") != null) {
        removeElement('info-div-global,msgDisabler');
    }

    // Hide selects for IE.
    toggleSelects('hidden');

    var msgBg = $E({
        tag: "div",
        id: "msgDisabler"
    });
    msgBg.setAttribute("onclick", "removeElement('info-div-global,msgDisabler');");
    msgBg.onclick = function(){
        removeElement('info-div-global,msgDisabler');
    };

    new Ajax.Request("aboutDamageTypeCodes.html", {
        method: "get",
        parameters: "view=Divs/getDamageTypeCodes",
        onSuccess: function(transport){
            if (showDamageTypePopUp) {
                var infoContainer = $E({
                    tag: "div",
                    id: "info-div-global"
                });
                document.body.appendChild(msgBg);
                document.body.appendChild(infoContainer);
                $("info-div-global").innerHTML = transport.responseText;
                var draggableMsg = new Draggable("information-div", {
                    handle: "information-div-titleBar"
                });
                Position.center(infoContainer);
                setDisablerHeight();
            }
        },
        onFailure: function(transport){
            redirectOnFailure(view);
        },
        onException: function(transport){
            redirectOnFailure(view);
        }
    });
}

/**
 * This function is used to hide the damage code div on mouseout
 */
function hideDamageCodePopup(){
    if (!AllowNewPopups) {
        return
    }
    showDamageTypePopUp = false;
    removeElement('info-div-global,msgDisabler');
}

/**
 *  This function is to be used to create informational/error message div/popups.
 * @param controller - passable url to a different controller, because some
 *                     div will need to do some processing and wont be able to
 *                     use the standard static controller.
 * @param view       - path and file name of the ftl to use as the view
 * @return           - none
 */
function getInfoDivPage(controller, view, method){
    method = method ? method : "get";
    var params = null;
    createInfoDivPopup(controller, view, params, false, method);
}

function getInfoDivPageGlossary(controller, view, method){
    method = method ? method : "get";
    var params = null;
    createInfoDivPopupGlossary(controller, view, params, false, method);
}

/**
 *  This function is a wrapper for the facility info div.
 *
 * @param yardNumber - The yard to show the facility info for.
 */
function getFacilityInfo(yardNumber){
    getInfoDivPage(message.facilityInfoAjax + '?yardnumber=' + yardNumber, 'Divs/facilityInfo');
    AllowNewPopups = false
}

/**
 *  This function is to be used to create the sale highlights div popup.
 * @param controller     - passable url to a different controller, because some
 *                         div will need to do some processing and wont be able to R
 *                         use the standard static controller.
 * @param view           - path and file name of the ftl to use as the view
 * @param facility       - Display value for Facility
 * @param saleHighlights - Display value for Sale Highlights
 * @return               - none
 */
function getInfoDivPageWithContent(controller, view, facility, saleHighlights){


    //var cleanSaleHighlights = removeCopartSingleQuote(saleHighlights);
    // cleanSaleHighlights = createPoundSignEntity(cleanSaleHighlights);
    var params = "facility=" + facility + "&saleHighlights=" + encodeURIComponent(saleHighlights);
    createInfoDivPopup(controller, view, params, false);
}

/**
 *  This function is responsible for creating the actual ajax divs.
 *  This function will create 2 divs in the DOM, the msgDisable that captures page
 *  clicks (not on the message div) and closes the dynamic divs, a info-div-global
 *  div that is a container that the AJAX (H) response will be placed into.
 */
function createInfoDivPopup(controller, view, params, isLogout, method, callBack){
    if (!AllowNewPopups) {
        return
    }
    method = method ? method : "get";
    // If there is already a popup open, close it
    if ($("info-div-global") != null) {
        removeElement('info-div-global,msgDisabler')
    }

    // Hide selects for IE.
    toggleSelects('hidden');

    if (controller == null) {
        controller = global.globalInfoDivUrl;
    }
    if (params == null) {
        params = "";
    }
    else {
        params = "&" + params;
    }

    var msgBg = $E({
        tag: "div",
        id: "msgDisabler"
    });
    if (isLogout) {
        msgBg.setAttribute("onclick", "logoff('info-div-global,msgDisabler');");
        msgBg.onclick = function(){
            logoff('info-div-global,msgDisabler');
        };
    }
    else {
        msgBg.setAttribute("onclick", "removeElement('info-div-global,msgDisabler');");
        msgBg.onclick = function(){
            removeElement('info-div-global,msgDisabler');
        };
    }
	var noCacheDate = new Date();
    new Ajax.Request(controller, {
        method: method,
        parameters: "noCache=" + noCacheDate + "&view=" + view + params,
        onSuccess: function(transport){
            var infoContainer = $E({
                tag: "div",
                id: "info-div-global"
            });
            document.body.appendChild(msgBg);
            document.body.appendChild(infoContainer);
            $("info-div-global").innerHTML = transport.responseText;
            var draggableMsg = new Draggable("information-div", {
                handle: "information-div-titleBar"
            });
            Position.center(infoContainer);
            setDisablerHeight();

            if (callBack) {
                callBack();
            }
        },
        onFailure: function(transport){
            redirectOnFailure(view);
        },
        onException: function(transport){
            redirectOnFailure(view);
        }
    });
}



function createInfoDivPopupGlossary(controller, view, params, isLogout, method){
    if (!AllowNewPopups) {
        return
    }
    method = method ? method : "get";
    // If there is already a popup open, close it
    if ($("info-div-global") != null) {
        removeElement('info-div-global,msgDisabler')
    }

    // Hide selects for IE.
    toggleSelects('hidden');

    if (controller == null) {
        controller = "info.html";
    }
    if (params == null) {
        params = "";
    }
    else {
        params = "&" + params;
    }

    var msgBg = $E({
        tag: "div",
        id: "msgDisabler"
    });
    if (isLogout) {
        msgBg.setAttribute("onclick", "logoff('info-div-global,msgDisabler');");
        msgBg.onclick = function(){
            logoff('info-div-global,msgDisabler');
        };
    }
    else {
        msgBg.setAttribute("onclick", "removeElement('info-div-global,msgDisabler');");
        msgBg.onclick = function(){
            removeElement('info-div-global,msgDisabler');
        };
    }
    new Ajax.Request(controller, {
        method: method,
        parameters: "view=" + view + params,
        onSuccess: function(transport){
            var infoContainer = $E({
                tag: "div",
                id: "info-div-global"
            });
            document.body.appendChild(msgBg);
            document.body.appendChild(infoContainer);
            $("info-div-global").innerHTML = transport.responseText;
            var draggableMsg = new Draggable("information-div", {
                handle: "information-div-titleBar"
            });
            Position.centerGlossary(infoContainer);
            setDisablerHeight();
        },
        onFailure: function(transport){
            redirectOnFailure(view);
        },
        onException: function(transport){
            redirectOnFailure(view);
        }
    });
}

function redirectOnFailure(view){
    if (view == 'Divs/logoff') {
        logoff('info-div-global,msgDisabler');
    }
    else {
        redirect('info-div-global,msgDisabler', 'virtualsales.html');
    }
}

function createTandCDivPopup(){
    // If there is already a popup open, close it
    if ($("info-div-global") != null) {
        removeElement('info-div-global,msgDisabler')
    }

    var controller = "info.html";
    var view = "Divs/viewTandC";

    var msgBg = $E({
        tag: "div",
        id: "msgDisabler"
    });
    msgBg.setAttribute("onclick", "declineTandC('info-div-global,msgDisabler');");
    msgBg.onclick = function(){
        declineTandC('info-div-global,msgDisabler');
    };
    new Ajax.Request(controller, {
        method: "get",
        parameters: "view=" + view,
        onSuccess: function(transport){
            var infoContainer = $E({
                tag: "div",
                id: "info-div-global"
            });
            document.body.appendChild(msgBg);
            document.body.appendChild(infoContainer);
            $("info-div-global").innerHTML = transport.responseText;
            var draggableMsg = new Draggable("information-div", {
                handle: "information-div-titleBar"
            });
            Position.center(infoContainer);
            setDisablerHeight();
        }
    });
}

function confirmTAndC(){
    var controller = "acceptTAndC.ajax";
    new Ajax.Request(controller, {
        method: "get",
        parameters: "",
        onSuccess: function(transport){
            if (transport.responseText.indexOf("error") > -1) {
                $("inCaseOfError").innerHTML = transport.responseText;
            }
            // If there is already a popup open, close it
            else
                if ($("info-div-global") != null) {
                    removeElement('info-div-global,msgDisabler')
                }
        },
        onFailure: function(transport){
            createTandCDivPopup();
        }
    });
}

/**
 * This function will size the disabler div based on the window height and width
 */
function setDisablerHeight(){
    var yWithScroll;
    var xWithScroll;
    if (window.innerHeight && window.scrollMaxY) {
        // Firefox
        yWithScroll = window.innerHeight + window.scrollMaxY;
        xWithScroll = window.innerWidth + window.scrollMaxX;
    }
    else
        if (document.body.scrollHeight > document.body.offsetHeight) {
            // all but Explorer Mac
            yWithScroll = document.body.scrollHeight;
            xWithScroll = document.body.scrollWidth;
        }
        else {
            // works in Explorer 6 Strict, Mozilla (not FF) and Safari
            yWithScroll = (document.body.offsetHeight + document.body.offsetTop) - 20;
            xWithScroll = (document.body.offsetWidth + document.body.offsetLeft) - 20;
        }

    //    $("msgDisabler").style.height = yWithScroll + "px";
    //    $("msgDisabler").style.width = xWithScroll + "px";
}

/**
 * This function will size the disabler div based on the window height and width
 */
function setObjectHeightToMatchWindow(objId){
    var yWithScroll;
    var xWithScroll;
    if (window.innerHeight && window.scrollMaxY) {
        // Firefox
        yWithScroll = window.innerHeight + window.scrollMaxY;
        xWithScroll = window.innerWidth + window.scrollMaxX;
    }
    else
        if (document.body.scrollHeight > document.body.offsetHeight) {
            // all but Explorer Mac
            yWithScroll = document.body.scrollHeight;
            xWithScroll = document.body.scrollWidth;
        }
        else {
            // works in Explorer 6 Strict, Mozilla (not FF) and Safari
            yWithScroll = (document.body.offsetHeight + document.body.offsetTop) - 20;
            xWithScroll = (document.body.offsetWidth + document.body.offsetLeft) - 20;
        }

    $(objId).style.height = yWithScroll + "px";
    $(objId).style.width = xWithScroll + "px";
}

/**
 * This function was created to deal with the single quotes that we may have to
 * deal with in JavaScript. It is a 2 part fix, part one is in the ftl itself,
 * we have to use the function to replace ' with copartSingleQuote. Then this
 * function will replace copartSingleQuote with the JavaScript escaped single
 * quote.
 *
 * @param str - String that is going to have the copartSingleQuote replaced
 */
function removeCopartSingleQuote(str){
    var cleanStr;
    if (str.indexOf("copartSingleQuote") > -1) {
        cleanStr = str.replace("copartSingleQuote", "\'");
    }
    else {
        cleanStr = str;
    }
    return cleanStr;
}

/**
 * This function will replace the # and convert it to *CopartPound*. The reason this is
 * needed is because when we are using pound sign, in js it can be interperted as
 * part of a url instead of just a string. Then the *CopartPound* has to be replaced
 * in the FTL with a # for display.
 */
function createPoundSignEntity(str){
    var cleanStr;
    if (str.indexOf("#") > -1) {
        cleanStr = str.replace("#", "*CopartPound*");
    }
    else {
        cleanStr = str;
    }
    return cleanStr;
}

/*
 This function will remove DraggableImageViewer
 */
function hideDiv(child, parent){
    document.body.removeChild(child);
    document.body.removeChild(parent);
}

/**
 * document.createElement convenience wrapper
 *
 * The data parameter is an object that must have the "tag" key, containing
 * a string with the tagname of the element to create.  It can optionally have
 * a "children" key which can be: a string, "data" object, or an array of "data"
 * objects to append to this element as children.  Any other key is taken as an
 * attribute to be applied to this tag.
 *
 * Release homepage:
 * http://www.arantius.com/article/dollar+e
 *
 * Available under an MIT license:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * @param {Object} data The data representing the element to create
 * @return {Element} The element created.
 */
function $E(data){
    var el;
    if ('string' == typeof data) {
        el = document.createTextNode(data);
    }
    else {
        //create the element
        el = document.createElement(data.tag);
        delete (data.tag);

        // append the children
        if ('undefined' != typeof data.children) {
            if ('string' == typeof data.children ||
            'undefined' == typeof data.children.length) {
                //strings and single elements
                el.appendChild($E(data.children));
            }
            else {
                //arrays of elements
                for (var i = 0, child = null; 'undefined' != typeof(child = data.children[i]); i++) {
                    el.appendChild($E(child));
                }
            }
            delete (data.children);
        }

        //any other data is attributes
        for (attr in data) {
            el[attr] = data[attr];
        }
    }

    return el;
}

/**
 * View PDF Files in new Window
 */
function viewPdf(url){
    var winPdf = window.open(url, 'ViewPDF', "width=680, height=500, scrollbars=yes, menubar=no, location=no, status=no, resizable=yes, toolbars=no");
}

function watchASale(url){
    var watchASaleWindow = window.open(url, "WatchASale", "top=180, left=180, width=730, height=480, scrollbars=yes, menubar=no, location=no, status=no, resizable=no, toolbar=no");
}

/*Position.GetWindowSize = function(w){
    w = w ? w : window;
    var width = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
    var height = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
    return [width, height]
}*/


/**
 * This function allows the centering of objects based on where the client is viewing
 Position.center = function(element){
    var copartCenterX = 260; // Added to adjust what 'center' was
    var copartCenterY = 220;
    var options = Object.extend({
        zIndex: 999,
        update: false
    }, arguments[1] ||
    {});
    element = $(element)
    if (!element._centered) {
        Element.setStyle(element, {
            position: 'absolute',
            zIndex: options.zIndex
        });
        element._centered = true;
    }
    var dims = Element.getDimensions(element);
    Position.prepare();
    var winWidth = self.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0;
    var winHeight = self.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0;
    var offLeft = (Position.deltaX + Math.floor((winWidth - dims.width) / 2)) - copartCenterX;
    var offTop = (Position.deltaY + Math.floor((winHeight - dims.height) / 2) - copartCenterY);
    element.style.top = ((offTop != null && offTop > 0) ? offTop : '0') + 'px';
    element.style.left = ((offLeft != null && offLeft > 0) ? offLeft : '0') + 'px';
    if (options.update) {
        Event.observe(window, 'resize', function(evt){
            Position.center(element);
        }, false);
        Event.observe(window, 'scroll', function(evt){
            Position.center(element);
        }, false);
    }
}

Position.centerGlossary = function(element){
    var copartCenterX = 260; // Added to adjust what 'center' was
    var copartCenterY = 150;
    var options = Object.extend({
        zIndex: 999,
        update: false
    }, arguments[1] ||
    {});
    element = $(element)
    if (!element._centered) {
        Element.setStyle(element, {
            position: 'absolute',
            zIndex: options.zIndex
        });
        element._centered = true;
    }
    var dims = Element.getDimensions(element);
    Position.prepare();
    var winWidth = self.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0;
    var winHeight = self.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0;
    var offLeft = (Position.deltaX + Math.floor((winWidth - dims.width) / 2)) - copartCenterX;
    var offTop = (Position.deltaY + Math.floor((winHeight - dims.height) / 2) - copartCenterY);
    element.style.top = ((offTop != null && offTop > 0) ? offTop : '0') + 'px';
    element.style.left = ((offLeft != null && offLeft > 0) ? offLeft : '0') + 'px';
    if (options.update) {
        Event.observe(window, 'resize', function(evt){
            Position.center(element);
        }, false);
        Event.observe(window, 'scroll', function(evt){
            Position.center(element);
        }, false);
    }
}
*/
/* The following JS was taken from VB2 */

// Trims off all leading/trailing whitespace
function trimWS(strValue){
    var objRegExp = /^(\s*)$/;
    // check for all spaces
    if (objRegExp.test(strValue)) {
        strValue = strValue.replace(objRegExp, '');
        if (strValue.length == 0) {
            return strValue;
        }
    }
    //check for leading & trailing spaces
    objRegExp = /^(\s*)([\W\w]*)(\b\s*$)/;
    if (objRegExp.test(strValue)) {
        //remove leading and trailing whitespace characters
        strValue = strValue.replace(objRegExp, '$2');
    }
    return strValue;
}

function checkEmail(theField, msg, placementId){
    // Strip off leading/following whitespace
    theField.value = trimWS(theField.value);
    // Email check
    // pattern1 = beginning pattern of email, case insensitive
    // pattern2 = middle pattern of email, case insensitive
    // pattern3 = end pattern of email, case insensitive
    // pattern4 = only one @ allowed
    // pattern5 = no white space allowed

    var pattern1 = /^\w+/i;
    var pattern2 = /\w+\@\w+/i;
    var pattern3 = /[a-z|0-9]\.[a-z]{2,3}$/i;
    var pattern4 = /\@.+\@/;
    var pattern5 = /\s|\/|\\|\;|\:|\"|,/;

    if (theField.value == '' || theField.value.substr(0, 4) == 'www.') {
        theField.focus();
        if (placementId != null) {
            $(placementId).innerHTML = msg;
        }
        return false;
    }
    else
        if (!(pattern1.test(theField.value) && pattern2.test(theField.value) && pattern3.test(theField.value))) {
            theField.focus();
            if (placementId != null) {
                $(placementId).innerHTML = msg;
            }
            return false;
        }
        else
            if (pattern4.test(theField.value) || pattern5.test(theField.value)) {
                theField.focus();
                if (placementId != null) {
                    $(placementId).innerHTML = msg;
                }
                return false;
            }
    return true;
}

function checkNumber(theField, required, minLength, minValue, msg, placementId){
    // Strip off leading/following whitespace
    theField.value = trimWS(theField.value);

    // If NaN, return error
    if (isNaN(theField.value) && required) {
        theField.focus();
        $(placementId).innerHTML = msg;
        return false;
    }
    // If contains an 'e', return error
    else
        if (regex(theField.value, 'e')) {
            theField.focus();
            $(placementId).innerHTML = msg;
            return false;
        }
        // If value < 0, return error
        else
            if (theField.value < 0) {
                theField.focus();
                $(placementId).innerHTML = msg;
                return false;
            }
            // If not an int, return error
            else
                if (theField.value != Math.floor(theField.value)) {
                    theField.focus();
                    $(placementId).innerHTML = msg;
                    return false;
                }
                // If (required == 1 or length > 0) and length < minLength, return error
                else
                    if ((required || theField.value.length > 0) && theField.value.length < minLength) {
                        theField.focus();
                        $(placementId).innerHTML = msg;
                        return false;
                    }
                    // If (required == 1 or length > 0) and value < minValue, return error
                    else
                        if ((required || theField.value.length > 0) && theField.value < minValue) {
                            theField.focus();
                            $(placementId).innerHTML = msg;
                            return false;
                        }
    return true;
}

function checkAlphaNumeric(theField, required, minLength, strongFilter, msg, placementId){
    // Strip off leading/following whitespace
    theField.value = trimWS(theField.value);
    var myRegxp = /^([a-zA-Z0-9_-]+)$/;
    // Converting all strings to uppercase except password
    // if (theField.name != "oldpassword" || theField.name != "password1" ||
    // theField.name != "password2"){
    // theField.value=theField.value.toUpperCase();
    // }

    // If has illegal chars ("), return error
    if (regex(theField.value, '"')) {
        theField.focus();
        $(placementId).innerHTML = msg;
        return false;
    }
    // If (required == 1 or length > 0) and length <= minLength, return error
    else
        if ((required || theField.value.length > 0) && theField.value.length < minLength) {
            theField.focus();
            $(placementId).innerHTML = msg;
            return false;
        }
        // If strongFilter == 1 and contains (!@#$%^&* etc), return error
        else
            if (strongFilter && !myRegxp.test(theField.value)) {
                theField.focus();
                $(placementId).innerHTML = msg;
                return false;
            }
    return true;
}

function checkAlphaNumericStrict(theField, required, minLength, strongFilter, msg, placementId){
    // Strip off leading/following whitespace
    theField.value = trimWS(theField.value);
    var myRegxp = /^([a-zA-Z0-9]+)$/;
    // Converting all strings to uppercase except password
    // if (theField.name != "oldpassword" || theField.name != "password1" ||
    // theField.name != "password2"){
    // theField.value=theField.value.toUpperCase();
    // }

    // If has illegal chars ("), return error
    if (regex(theField.value, '"')) {
        theField.focus();
        $(placementId).innerHTML = msg;
        return false;
    }
    // If (required == 1 or length > 0) and length <= minLength, return error
    else
        if ((required || theField.value.length > 0) && theField.value.length < minLength) {
            theField.focus();
            $(placementId).innerHTML = msg;
            return false;
        }
        // If strongFilter == 1 and contains (!@#$%^&* etc), return error
        else
            if (strongFilter && !myRegxp.test(theField.value)) {
                theField.focus();
                $(placementId).innerHTML = msg;
                return false;
            }
    return true;
}

function regex(strValue, pattern){
    var objRegExp = new RegExp('[' + pattern + ']');

    if (objRegExp.test(strValue)) {
        return true;
    }
    else {
        return false;
    }
}

function isZipValid(zip){
    // strip leading trailing spaces
    var zip = trimWS(zip);
    var objRegExp;

    // check for US zipcode
    objRegExp = new RegExp("^[0-9]{5}$");
    if (objRegExp.test(zip)) {
        return true;
    }

    // check for canada zipcode short
    objRegExp = new RegExp("^[a-z]\\d[a-z]$", "i");
    if (objRegExp.test(zip)) {
        return true;
    }

    // check for canada zipcode long
    objRegExp = new RegExp("^[a-zA-Z]\\d[a-zA-Z]\\d[a-zA-Z]\\d$", "i");
    if (objRegExp.test(zip)) {
        return true;
    }

    // not us or canada zipcode
    return false;
}

/**
 * This function will take in the params to create the featured listings component.
 */
function getFeaturedCarList(url, params, outputDiv, loadingGif, errorMsg){
    var messageDivStart = '<div style="margin: 50px auto 50px auto;text-align: center;">';
    var messageDivEnd = '</div>';
    $(outputDiv).innerHTML = messageDivStart + loadingGif + messageDivEnd;
    new Ajax.Request(url, {
        method: "get",
        parameters: params,
        onSuccess: function(transport){
            $(outputDiv).innerHTML = transport.responseText;
        },
        onFailure: function(){
            $(outputDiv).innerHTML = messageDivStart + errorMsg + messageDivEnd;
        }
    });
}

function getDropdownValue(dropdown){
    var value = dropdown.options[dropdown.selectedIndex].value;
    return value;
}

/*
 *******************************
 About Title Type Codes - DIV
 *******************************
 */
function getStatesByCountry(countryDropdown, emptyListMsg, errMsg, defaultStateValue){
    var countryId = getDropdownValue(countryDropdown);
    if (countryId.length > 1) // Country selected is not 'Select a Country'
    {
        var controller = "aboutTitleTypeStates.ajax";
        var stateSplitter = "~";
        var setSplitter = "*";
        new Ajax.Request(controller, {
            method: "get",
            parameters: "countryId=" + countryId,
            onSuccess: function(transport){
                if (transport.responseText.indexOf("empty") > -1) {
                    $("listContent").innerHTML = "<div class=\"alertred\">" + emptyListMsg + "</div>";
                }
                else {
                    $("submitTitleType").disabled = false;
                    var returnValue = transport.responseText;
                    var states = returnValue.split(stateSplitter);
                    $("titleTypeState").options.length = 0;
                    for (var i = 0; i < states.length - 1; i++) {
                        var state = states[i].split(setSplitter);
                        $("titleTypeState").options[i] = new Option(state[1], state[0]);
                    }
                }
            },
            onFailure: function(transport){
                $("listContent").innerHTML = "<div class=\"alertred\">" + errMsg + "</div>";
            }
        });
    }
    else {
        $("submitTitleType").disabled = true;
        $("titleTypeState").options.length = 0;
        $("titleTypeState").options[0] = new Option(defaultStateValue, '');
    }
}

function getLossTypeCodes(errMsg){
    var stateId = getDropdownValue($("titleTypeState"));
    if (stateId.length > 0) {
        /*var loadingImg = "<img src=\"" + loadImg + "\" alt=\"" + loadImgAlt + "\"/>";*/
        var controller = "aboutTitleTypeCodesList.ajax";
        /*$("listContent").innerHTML = "<div class=\"centerobj\">" + loadingImg + "</div>";*/
        new Ajax.Request(controller, {
            method: "get",
            parameters: "stateId=" + trimWS(stateId),
            onSuccess: function(transport){
                $("listContent").innerHTML = transport.responseText;
            },
            onFailure: function(transport){
                $("listContent").innerHTML = "<div class=\"alertred\">" + errMsg + "</div>";
            }
        });
    }
}

/*
 *******************************
 Oklahoma Compliance - DIV
 *******************************
 */
function submitOKComplianceForm(errMsg){
    var lotId = $("okLotId").value;
    var controller = "oklahomaComplianceLotInfo.ajax";
    var formattedErrMsg = "<div class=\"alertneutral\">" + errMsg + "</div>";
    $("okComplianceResultTd").innerHTML = "<div style=\"text-align: center;\"><img src=\"" + $("loadingImgSrc").src + "\"></div>";
    if ((lotId.length < 1) || (isNaN(lotId))) {
        $("okComplianceResultTd").innerHTML = formattedErrMsg;
        return false;
    }
    new Ajax.Request(controller, {
        method: "get",
        parameters: "okLotId=" + lotId,
        onSuccess: function(transport){
            $("okComplianceResultTd").innerHTML = transport.responseText;
        },
        onFailure: function(transport){
            $("okComplianceResultTd").innerHTML = formattedErrMsg;
        }
    });
}

/**
 * This function takes in either 2 xml strings or 2 xml documents. If strings
 * are passed in, they are converted into xml documents. Then the xsl is applied
 * to the xml and sent back to the caller
 */
function getFormattedXMLContent(xmlString, xslString){
    //If Moz/Opera
    if (document.implementation && document.implementation.createDocument) {
        var xmlDoc;
        var xslDoc;
        if ("string" == typeof xmlString) {
            xmlDoc = returnXMLDocument(xmlString);
        }
        else {
            xmlDoc = xmlString;
        }
        if ("string" == typeof xslString) {
            xslDoc = returnXMLDocument(xslString);
        }
        else {
            xslDoc = xslString;
        }
        if (isError(xmlDoc, xslDoc)) {
            return errorNotSupported;
        }
        var xsltProcessor = new XSLTProcessor();
        xsltProcessor.importStylesheet(xslDoc)
        return xsltProcessor.transformToFragment(xmlDoc, document);
    }
    //If IE
    else
        if (window.ActiveXObject) {
            var xmlDoc;
            var xslDoc;

            if ("string" == typeof xmlString) {
                xmlDoc = returnXMLDocument(xmlString);
            }
            else {
                xmlDoc = xmlString;
            }
            if ("string" == typeof xslString) {
                xslDoc = returnXMLDocument(xslString);
            }
            else {
                xslDoc = xslString;
            }
            if (isError(xmlDoc, xslDoc)) {
                return errorNotSupported;
            }
            return xmlDoc.transformNode(xslDoc)
        }
        else {
            return errorNotSupported;
        }

    function isError(xml, xsl){
        //Check that both items are objects
        if ((xml && "object" == typeof xml) &&
        (xsl && "object" == typeof xsl)) {
            return false;
        }
        return true;
    }
}

/**
 * This function takes a string and attempts to convert it to an xml document.
 */
function returnXMLDocument(strDocument){
    //If Mozilla/Opera
    if (document.implementation && document.implementation.createDocument) {
        var domParser = new DOMParser();
        var xmlDocument = domParser.parseFromString(strDocument, "text/xml");
        return xmlDocument;
    }
    //If IE
    else
        if (window.ActiveXObject) {
            var xmlDocument = new ActiveXObject("Microsoft.XMLDOM");
            xmlDocument.async = "false";
            xmlDocument.loadXML(strDocument);
            return xmlDocument;
        }
        //Not Supported
        else {
            return errorNotSupported;
        }
}


/**
 Replace the image tag with the replacement image.
 **/
function imageNotFound(image, imgName){
    var imgName = imgName || 'carImageNotFoundThumb.jpg';
    imageURL = global.contextRoot + 'images/global/' + imgName;
    imageWidth = image.width;
    imageHeight = image.height;
    image.parentNode.innerHTML = "<img alt='Image Not Found' src='" + imageURL + "' width='" + imageWidth + "' height='" + imageHeight + "' />";
}


function checkForBackForm(formName){
    if ($(formName) == null && $('backLink') != null) {
        $('backLink').innerHTML = '';
    }
}



/**
 * This method will validate that a field is present if another is as well.
 * @param dependentValue - value that needs to be present if parentValue is
 *        present
 * @param parentValue - value that when set makes the depenentValue required
 */
function requiredIf(dependentValue, parentValue){
    if (parentValue.length > 0 || parentValue != "") {
        if (dependentValue.length <= 0 || dependentValue == "") {
            return true;
        }
    }
    return false;

}

/**
 * This event is waiting for the window to resize, when the window is resized,
 * the function resizewindow() is called.
 */
//Event.observe(window, 'resize', resizewindow);

/**
 * This Function is used for Resizing the window and it will take cares to close
 * the DIV when Maximize.
 */
function resizewindow(){
    if ($('msgDisabler') != null) {
        setDisablerHeight();

    }
}

/**
 * This method checks that a field exists, if the field value is not empty or
 * null then it returns the field's vlaue, if the field
 * does not exist or is blank or null, it returns the defaultValue.
 * @param {Object} fieldName - field to get value from.
 * @param {Object} defaultValue - default value if field does not exist.
 */
function getHiddenFieldValue(fieldName, defaultValue){
    if ($(fieldName) != null) {
        if ($(fieldName).value != "" || $(fieldName).value != null) {
            return $(fieldName).value;
        }
        else {
            return defaultValue;
        }
    }
    return defaultValue;
}

/**
 * This function takes the number of minutes needed by the user and returns
 * milliseconds, since this is the default time interval for JavaScript.
 * @param {Object} minutes - this param can be an int, double or float.
 */
function getMinutesInMilliSeconds(minutes){
    return minutes * 60000;
}

function getLoadingImage(){
    return '<p class="ajaxLoadingImage"><img src="' + $("loadingImgSrc").src + '" width="16" height="16" /></p>';
}

/**
 * This method will make an AJAX call and get the featured listings compact list.
 * @param {Object} selectedValue - value selected for the criteria.
 * @param {Object} ajaxContentContainerName - container that we will write our content to.
 * @param {Object} failureMessage - message to present to the user if a failure happens.
 */
function getFeaturedListings(selectedValue, ajaxContentContainerName, failureMessage){
    var selectedLotType = selectedValue;
    $(ajaxContentContainerName).innerHTML = getLoadingImage();
    new Ajax.Request("featuredListingsCompact.ajax", {
        method: "get",
        parameters: "lotType=" + trimWS(selectedLotType),
        onSuccess: function(transport){
            $(ajaxContentContainerName).innerHTML = transport.responseText;
        },
        onFailure: function(transport){
            $(ajaxContentContainerName).innerHTML = failureMessage;
        }
    });
}

//Script in place that limits email to 1000 characters.
var ns6 = document.getElementById && !document.all

function restrictinput(maxlength, e, placeholder){
    if (window.event && event.srcElement.value.length >= maxlength)
        return false
    else
        if (e.target && e.target == eval(placeholder) && e.target.value.length >= maxlength) {
            var pressedkey = /[a-zA-Z0-9\.\,\/]/ // detect alphanumeric keys
            if (pressedkey.test(String.fromCharCode(e.which)))
                e.stopPropagation()
        }
}

function countlimit(maxlength, e, placeholder){
    var theform = eval(placeholder)
    var lengthleft = maxlength - theform.value.length
    var placeholderobj = document.all ? document.all[placeholder] : document.getElementById(placeholder)
    if (window.event || e.target && e.target == eval(placeholder)) {
        if (lengthleft < 0)
            theform.value = theform.value.substring(0, maxlength)
        placeholderobj.innerHTML = lengthleft
    }
}

function displaylimit(thename, theid, thelimit){
    var theform = theid != "" ? document.getElementById(theid) : thename
    var limit_text = '<b><span id="' + theform.toString() + '">' + thelimit + '</span></b> '
    if (document.all || ns6)
        document.write(limit_text)
    if (document.all) {
        eval(theform).onkeypress = function(){
            return restrictinput(thelimit, event, theform)
        }
        eval(theform).onkeyup = function(){
            countlimit(thelimit, event, theform)
        }
    }
    else
        if (ns6) {
            document.body.addEventListener('keypress', function(event){
                restrictinput(thelimit, event, theform)
            }, true);
            document.body.addEventListener('keyup', function(event){
                countlimit(thelimit, event, theform)
            }, true);
        }
}


function replayLot(lotSoldKey){
    var windowTarget = "replayWindow" + lotSoldKey;
    $("replayForm").target = windowTarget;
    $("soldLotKey").value = lotSoldKey;

    window.open("", windowTarget, "width=730, height=480, scrollbars=yes, menubar=no, location=no, status=no, resizable=no, toolbars=no");
    setTimeout("openReplayWindow()", 500);

}

function openReplayWindow(){
    $("replayForm").submit();
}


function backToPrevious(formName, eventId){
    $("_eventId").value = eventId;
    $(formName).method = "get";
    $(formName).submit();
}

function getLot(formName, eventId, lotId){
    $("lotId").value = lotId;
    $("_eventId").value = eventId;
    $(formName).submit();
}

/**
 * This function will perform validation on the Search By Type form on Home .
 */
function detailSearchValidateHome(doSubmit){
    var selectedMake = $F("make");
    var fromYear = $F("startYear");
    var toYear = $F("endYear");
    var zipPostalCode = $("zipPostalCode").value;
    var errors = "";

    if ($("detailedSearchError") != "") {
        $("detailedSearchError").innerHTML = "";
    }

    if (fromYear > toYear) {
        errors += message.detailSearch_error_yearRange;
    }

    if ($F("vehicleType") == message.validVehicleType) {
        if (selectedMake == "*" || selectedMake == "") {
            if (errors != "") {
                errors += "<br>";
            }
            errors += message.detailSearch_error_make;
        }
    }

    if (errors != "") {
        $("detailedSearchError").innerHTML = errors;
        return false;
    }

    if ($F("zip") == "zip") {
        if (zipPostalCode != null && zipPostalCode != "") {
            var isValid = checkAlphaNumericStrict($("zipPostalCode"), 0, 0, 1, message.detailSearch_zip_required, "detailedSearchError");
            // Corrected this IF condition to display the invalid zip code error
            // message -- Bug 5944
            if (!isValid) {
                if (errors != "") {
                    errors += "<br>";
                }
                errors += message.detailSearch_zip_required;
            }
            else {
                // zipcode is valid. if zip code length = 6 then
                // it is a full canadan zip we only use short
                //canada zips use only the first three charters
                if (zipPostalCode.length == 6) {
                    zipPostalCode = zipPostalCode.substr(0, 3);
                    $("zipPostalCode").value = zipPostalCode;
                }
                // rememberZip(zipPostalCode);
                searchParms.zip = zipPostalCode;
                searchParms.mileageRange = $F("mileageRange");
            }
        }
    }

    searchParms.zip = zipPostalCode
    if (errors != "") {
        $("detailedSearchError").innerHTML = errors;
        return false;
    }


    if (($F("state") == "state") || ($F("facility") == "facility")) {
        searchParms.stateFacility = $F("stateFacility")
    }

    if ($F("zip") == "zip") {
        searchParms.zip = zipPostalCode;
    }
    // if(  searchParms.zip > 0){
    //   $("zipPostalCode").value = zip;
    // }

    searchParms.vehicleType = $F("vehicleType");
    searchParms.make = selectedMake;
    searchParms.model = $F("model");
    searchParms.startYear = fromYear;
    searchParms.endYear = toYear;
    searchParms.make = selectedMake;
    searchParms.titleGroupCode = $F("titleGroupCode");

    var radioButton = $("facility").form.location;
    searchParms.location = get_radio_value(radioButton);

    saveSearchParms(searchParms);
    var filterLabel = $("vehicleType").options[$("vehicleType").selectedIndex].text +
    " " +
    $("make").options[$("make").selectedIndex].text;
    // alert(filterLabel);
    $("filterBaseLabelDetailSearch").value = filterLabel;

    if (doSubmit) {
        document.forms.searchByType.submit();
    }
    return true;



}


/**
 * This function will perform validation on the Search By Type form.
 */
function detailSearchValidate(doSubmit){
    var selectedMake = $F("make");
    var fromYear = $F("startYear");
    var toYear = $F("endYear");
    var zipPostalCode = $("zipPostalCode").value;
    var errors = "";

    if ($("quickSearchError_lotVin") != "") {
        $("quickSearchError_lotVin").innerHTML = "";
    }

    if ($("quickSearchError") != "") {
        $("quickSearchError").innerHTML = "";
    }

    if ($("detailedSearchError") != "") {
        $("detailedSearchError").innerHTML = "";
    }

    if (fromYear > toYear) {
        errors += message.detailSearch_error_yearRange;
    }

    if ($F("vehicleType") == message.validVehicleType) {
        if (selectedMake == "*" || selectedMake == "") {
            if (errors != "") {
                errors += "<br>";
            }
            errors += message.detailSearch_error_make;
        }
    }

    if (errors != "") {
        $("detailedSearchError").innerHTML = errors;
        return false;
    }

    if ($F("zip") == "zip") {
        if (zipPostalCode != null && zipPostalCode != "") {
            var isValid = checkAlphaNumericStrict($("zipPostalCode"), 0, 0, 1, message.detailSearch_zip_required, "detailedSearchError");
            // Corrected this IF condition to display the invalid zip code error
            // message -- Bug 5944
            if (!isValid) {
                if (errors != "") {
                    errors += "<br>";
                }
                errors += message.detailSearch_zip_required;
            }
            else {
                // zipcode is valid. if zip code length = 6 then
                // it is a full canadan zip we only use short
                //canada zips use only the first three charters
                if (zipPostalCode.length == 6) {
                    zipPostalCode = zipPostalCode.substr(0, 3);
                    $("zipPostalCode").value = zipPostalCode;
                }
                // rememberZip(zipPostalCode);
                searchParms.zip = zipPostalCode;
                searchParms.mileageRange = $F("mileageRange");
            }
        }
    }

    searchParms.zip = zipPostalCode
    if (errors != "") {
        $("detailedSearchError").innerHTML = errors;
        return false;
    }


    if (($F("state") == "state") || ($F("facility") == "facility")) {
        searchParms.stateFacility = $F("stateFacility")
    }

    if ($F("zip") == "zip") {
        searchParms.zip = zipPostalCode;
    }
    // if(  searchParms.zip > 0){
    //   $("zipPostalCode").value = zip;
    // }

    searchParms.vehicleType = $F("vehicleType");
    searchParms.make = selectedMake;
    searchParms.model = $F("model");
    searchParms.startYear = fromYear;
    searchParms.endYear = toYear;
    searchParms.make = selectedMake;
    searchParms.titleGroupCode = $F("titleGroupCode");

    var radioButton = $("facility").form.location;
    searchParms.location = get_radio_value(radioButton);

    saveSearchParms(searchParms);

    var filterLabel = $("vehicleType").options[$("vehicleType").selectedIndex].text +
    " " +
    $("make").options[$("make").selectedIndex].text;
    // alert(filterLabel);
    $("filterBaseLabelDetailSearch").value = filterLabel;

    if (doSubmit) {
        document.forms.searchByType.submit();
    }
    return true;
}

/**
 * This function is used to update the State / Facility Drop down.
 * @param {Object} dropDownName - this is the drop down that triggers the onchange even.
 * @param {Object} contentContainer - this is the drop down that will be update with new content.
 */
function updateStateFacilityDropDown(dropDownName, contentContainer){
    var xmlNodeName = "state";
    var xmlNodeAttribute1 = "code";
    var xmlNodeAttribute2 = "description";
    var reqParam = "statefacility";

    if ($F(dropDownName) == "facility") {
        xmlNodeName = "yard";
        xmlNodeAttribute1 = "number";
        xmlNodeAttribute2 = "name";
    }


    if ($F(dropDownName) != "zip") {
        $("location-container").style.display = "block";
        $("zip-container").style.display = "none";
        if (xmlNodeName == "yard") {
            updateDropDown(dropDownName, contentContainer, xmlNodeName, xmlNodeAttribute1, xmlNodeAttribute2, reqParam, message.stateFacilityAjax, message.defaultFacilityDisplay, message.defaultFacilityValue);
        }
        else {
            updateDropDown(dropDownName, contentContainer, xmlNodeName, xmlNodeAttribute1, xmlNodeAttribute2, reqParam, message.stateFacilityAjax, message.defaultStateDisplay, message.defaultStateValue);
        }
        // clear zip if not used
        // $("zipPostalCode").value = "";
    }
    else {
        $("location-container").style.display = "none";
        $("zip-container").style.display = "block";

        // Set zip code
        // var zip = getZip();
        // if(zip == 0){
        // $("zipPostalCode").value = "";
        // }else{
        // $("zipPostalCode").value = zip;
        // }

    }
}

/**
 * This function is used to update the Models Drop down.
 * @param {Object} dropDownName - this is the drop down that triggers the onchange even.
 * @param {Object} contentContainer - this is the drop down that will be update with new content.
 */
function updateMakeDropDown(dropDownName, contentContainer){
    var reqParam = "vehicleType";
    var xmlNodeName = "make";
    var xmlNodeAttribute1 = "code";
    var xmlNodeAttribute2 = "description";

    if ($F(dropDownName) == message.validVehicleType) {
        $("model").disabled = false;
        updateDropDown(dropDownName, contentContainer, xmlNodeName, xmlNodeAttribute1, xmlNodeAttribute2, reqParam, message.makeAjax, message.defaultMakeDisplay, "*");
        setTimeout("timeoutForModel()", 1000000);
    }
    else {
        updateDropDown(dropDownName, contentContainer, xmlNodeName, xmlNodeAttribute1, xmlNodeAttribute2, reqParam, message.makeAjax, message.defaultMakeIfNotVehicle, message.defaultMakeIfNotVehicleValue);
        makeNotValidModelDropDown();
    }
}

function timeoutForModel(){
    updateModelDropDown('make', 'model');
}

function makeNotValidModelDropDown(){
    $("model").options.length = 0;
    var opt = $E({
        tag: "option"
    });
    opt.text = message.defaultModelDisplay;
    opt.value = message.defaultModelValue;
    $("model").options.add(opt);
    $("model").disabled = true;
}


/**
 * This function is used to update the Models Drop down.
 * @param {Object} dropDownName - this is the drop down that triggers the onchange even.
 * @param {Object} contentContainer - this is the drop down that will be update with new content.
 */
function updateModelDropDown(dropDownName, contentContainer){
    var reqParam = "selectedMake";
    var xmlNodeName = "model";
    var xmlNodeAttribute1 = "code";
    var xmlNodeAttribute2 = "description";

    if ($F(dropDownName) != "*") {
        updateDropDown(dropDownName, contentContainer, xmlNodeName, xmlNodeAttribute1, xmlNodeAttribute2, reqParam, message.modelAjax);
    }
}

function updateModelDropDown2(dropDownName, contentContainer){
    var reqParam = "selectedMake";
    var xmlNodeName = "model";
    var xmlNodeAttribute1 = "code";
    var xmlNodeAttribute2 = "description";

    if ($F(dropDownName) != "*") {
        updateDropDown(dropDownName, contentContainer, xmlNodeName, xmlNodeAttribute1, xmlNodeAttribute2, reqParam, message.modelAjax, message.defaultModelDisplay, message.defaultModelValue);
    }
}

/**
 * This function is used by both the model and State/Facility drop down update functions. This method makes
 * the ajax request for the the new collection, parses it and creates new options in the contentContainer.
 * @param {Object} dropDownName - the dropdown that triggered the function
 * @param {Object} contentContainer - the dropdown whose contents will be updated.
 * @param {Object} xmlNodeName - parent XML node name not root, ie: state
 * @param {Object} xmlNodeAttribute1 - attribute whose value we will use to display to the user, ie: description
 * @param {Object} xmlNodeAttribute2 - attribute whose value we will use as the value, ie: code
 * @param {Object} reqParam - request parameter that the controller is expecting.
 * @param {Object} ajaxURL - url to the controller for the ajax request.
 * @param {Object} defaultOptionValue - if a value is specified it is used as the first option in the drop down.
 */
function updateDropDown(dropDownName, contentContainer, xmlNodeName, xmlNodeAttribute1, xmlNodeAttribute2, reqParam, ajaxURL, defaultOption, defaultOptionValue){
    var selectedValue = $F(dropDownName);
    var xmlDoc;
    var nodeCounter = 0;
    var startCounterAt = 0;
    defaultOption = defaultOption ? defaultOption : "";
    defaultOptionValue = defaultOptionValue ? defaultOptionValue : "";
    if (defaultOption != "") {
        var firstOption = new Option(defaultOption, defaultOptionValue);
        startCounterAt = 1;
    }
    $(contentContainer).options.length = 0;

    new Ajax.Request(ajaxURL, {
        method: "get",
        parameters: reqParam + "=" + trimWS(selectedValue),
        onSuccess: function(transport){
            xmlDoc = returnXMLDocument(transport.responseText);
            nodeCounter = xmlDoc.getElementsByTagName(xmlNodeName).length;
            if (nodeCounter > 0) {
                if (startCounterAt > 0) {
                    $(contentContainer).options[0] = firstOption;
                }
                for (var i = 0; i < nodeCounter; i++) {
                    var desc = xmlDoc.getElementsByTagName(xmlNodeName)[i].attributes.getNamedItem(xmlNodeAttribute2).value;
                    var code = xmlDoc.getElementsByTagName(xmlNodeName)[i].attributes.getNamedItem(xmlNodeAttribute1).value;
                    var newOption = new Option(desc, code);
                    $(contentContainer).options[i + startCounterAt] = newOption;
                }
                if ($(contentContainer).options.length == 0) {
                    $(contentContainer).options[0] = firstOption;
                }
            }
            else {
                $(contentContainer).options[0] = firstOption;
            }
        },
        onFailure: function(){
            $(contentContainer).options[0] = firstOption;
        }
    });
}

/********************************************************************/
/*******************************************************************************
 * The function in this section that end with "With" These functions are the
 * same as the the ones with out the "With" exect the functions that have "With"
 * are passed a value ensted of the field that contains the value for loading
 * the dropdown box. /
 ******************************************************************************/
/** ***************************************************************** */
/**
 * This function is used to update the Make Drop down.
 *
 * @param {Object}
 *            vehicleType - The vehicle type group that is to load the dropdown
 *            box.
 * @param {Object}
 *            defaultValue - The value that is to be selected.
 */
function updateMakeDropDownWith(vehicleType, defaultValue){
    var reqParam = "vehicleType";
    var xmlNodeName = "make";
    var xmlNodeAttribute1 = "code";
    var xmlNodeAttribute2 = "description";

    if ((vehicleType == undefined)) {
        return
    }

    if (vehicleType == message.validVehicleType) {
        $("model").disabled = false;
        updateDropDownWith(vehicleType, 'make', xmlNodeName, xmlNodeAttribute1, xmlNodeAttribute2, reqParam, message.makeAjax, message.defaultMakeDisplay, "*", defaultValue);
        // setTimeout("timeoutForModel()", 10000);
    }
    else {
        updateDropDownWith(vehicleType, 'make', xmlNodeName, xmlNodeAttribute1, xmlNodeAttribute2, reqParam, message.makeAjax, message.defaultMakeIfNotVehicle, message.defaultMakeIfNotVehicleValue, defaultValue);
        makeNotValidModelDropDown();
    }
}


/**
 * This function is used to update the Models Drop down.
 * @param {Object} makeType - The make type group that is to load the dropdown box.
 * @param {Object} defaultValue - The value that is to be selected.
 */
function updateModelDropDownWith(makeType, defaultValue){
    var reqParam = "selectedMake";
    var xmlNodeName = "model";
    var xmlNodeAttribute1 = "code";
    var xmlNodeAttribute2 = "description";

    updateDropDownWith(makeType, 'model', xmlNodeName, xmlNodeAttribute1, xmlNodeAttribute2, reqParam, message.modelAjax, message.defaultModelDisplay, message.defaultModelValue, defaultValue);
    // updateDropDownWith(makeType, 'model', xmlNodeName, xmlNodeAttribute1,
    // xmlNodeAttribute2, reqParam, message.modelAjax,
    // message.defaultModelDisplay, message.defaultModelValue, defaultValue);

}

/**
 * This function is used to update the State / Facility Drop down.
 * @param {Object} locationType - The location type group that is to load the dropdown box.
 * @param {Object} defaultValue - The value that is to be selected.
 */
function updateStateFacilityDropDownWith(locationType, defaultValue){
    var xmlNodeName = "state";
    var xmlNodeAttribute1 = "code";
    var xmlNodeAttribute2 = "description";
    var reqParam = "statefacility";

    if (locationType == "facility") {
        xmlNodeName = "yard";
        xmlNodeAttribute1 = "number";
        xmlNodeAttribute2 = "name";
    }


    if (locationType != "zip") {
        $("location-container").style.display = "block";
        $("zip-container").style.display = "none";
        if (xmlNodeName == "yard") {
            updateDropDownWith(locationType, 'stateFacility', xmlNodeName, xmlNodeAttribute1, xmlNodeAttribute2, reqParam, message.stateFacilityAjax, message.defaultFacilityDisplay, message.defaultFacilityValue, defaultValue);
        }
        else {
            updateDropDownWith(locationType, 'stateFacility', xmlNodeName, xmlNodeAttribute1, xmlNodeAttribute2, reqParam, message.stateFacilityAjax, message.defaultStateDisplay, message.defaultStateValue, defaultValue);
        }
    }
    else {
        $("location-container").style.display = "none";
        $("zip-container").style.display = "block";

    }
}

/**
 * This function is used by both the model and State/Facility drop down update functions. This method makes
 * the ajax request for the the new collection, parses it and creates new options in the contentContainer.
 * @param {Object} dropDownType - the type value that is to be loaded
 * @param {Object} contentContainer - the dropdown whose contents will be updated.
 * @param {Object} xmlNodeName - parent XML node name not root, ie: state
 * @param {Object} xmlNodeAttribute1 - attribute whose value we will use to display to the user, ie: description
 * @param {Object} xmlNodeAttribute2 - attribute whose value we will use as the value, ie: code
 * @param {Object} reqParam - request parameter that the controller is expecting.
 * @param {Object} ajaxURL - url to the controller for the ajax request.
 * @param {Object} firstValue - if a value is specified it is used as the first option in the drop down.
 * @param {Object} firstDescription - the description displayed if firstValue is specified.
 * @param {Object} defaultValue - the value that is to be selected.
 */
function updateDropDownWith(dropDownType, contentContainer, xmlNodeName, xmlNodeAttribute1, xmlNodeAttribute2, reqParam, ajaxURL, firstDescription, firstValue, defaultValue){
    if (dropDownType == undefined) {
        return;
    }
    var xmlDoc;
    var nodeCounter = 0;
    var startCounterAt = 0;
    firstDescription = firstDescription ? firstDescription : "";
    firstValue = firstValue ? firstValue : "";

    if (firstDescription != "") {
        var firstOption = new Option(firstDescription, firstValue);
        startCounterAt = 1;
    }
    $(contentContainer).options.length = 0;

    new Ajax.Request(ajaxURL, {
        method: "get",
        parameters: reqParam + "=" + trimWS(dropDownType),
        onSuccess: function(transport){
            xmlDoc = returnXMLDocument(transport.responseText);
            nodeCounter = xmlDoc.getElementsByTagName(xmlNodeName).length;
            if (nodeCounter > 0) {
                $(contentContainer).options.length = 0;
                if (startCounterAt > 0) {
                    $(contentContainer).options[0] = firstOption;
                }
                for (var i = 0; i < nodeCounter; i++) {
                    var desc = xmlDoc.getElementsByTagName(xmlNodeName)[i].attributes.getNamedItem(xmlNodeAttribute2).value;
                    var code = xmlDoc.getElementsByTagName(xmlNodeName)[i].attributes.getNamedItem(xmlNodeAttribute1).value;
                    var newOption = new Option(desc, code);
                    $(contentContainer).options[i + startCounterAt] = newOption;
                }
                if ($(contentContainer).options.length == 0) {
                    $(contentContainer).options[0] = firstOption;
                }
            }
            else {
                $(contentContainer).options[0] = firstOption;
            }
            if (defaultValue != undefined) {
                setSelectValue(contentContainer, defaultValue)
            }
        },
        onFailure: function(){
            $(contentContainer).options.length = 0;
            $(contentContainer).options[0] = firstOption;
        }
    });
}

/********************************************************************/
/*******************************************************************************
 * End of functions with "With" /
 ******************************************************************************/
/** ***************************************************************** */

function saveSearchParms(parms){
    var cookieTxt = new String();

    for (parmName in parms) {
        if ((escape(parms[parmName]) != null) && (escape(parms[parmName]) != '')) {
            cookieTxt += parmName + "=" + escape(parms[parmName]) + "|"
        }
    }

    if (cookieTxt.length > 1) {
        if (cookieTxt.substr((cookieTxt.length - 1), 1) == "|") {
            // strip off trailing  "|"
            cookieTxt = cookieTxt.substr(0, cookieTxt.length - 1);
        }
    }

    setCookie("searchParms", cookieTxt, null, "/", "copart.com");
}

function getSearchParms(){
    var parmObj = new Object();
    var cookieTxt = getCookie("searchParms");
    var parms = cookieTxt.split("|");

    // set default values for parms
    parmObj.zip = "";

    for (var i = 0; i < parms.length; i++) {
        var parm = parms[i].split("=");
        if ((parm[1] != "null") && (parm[1] != "undefined")) {
            parmObj[unescape(parm[0])] = unescape(parm[1]);
        }
    }

    return parmObj
}

function setCookie(name, value, expires, path, domain, secure){
    var today = new Date();
    today.setTime(today.getTime());

    if (expires) {
        expires = expires * 1000 * 60 * 60 * 24;
    }
    var expires_date = new Date(today.getTime() + (expires));

    document.cookie = name + "=" + escape(value) +
    ((expires) ? ";expires=" + expires_date.toGMTString() : "") +
    ((path) ? ";path=" + path : "") +
    ((domain) ? ";domain=" + domain : "") +
    ((secure) ? ";secure" : "");

}


function getCookie(c_name){
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1)
                c_end = document.cookie.length;
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

searchParms = getSearchParms();

function getZip(){
    zip = getCookie("user_zip");
    if (zip == '') {
        return 0;
    }
    else {
        return zip;
    }
}


function setSelectValue(SelectName, value){
    var selectObj = $(SelectName);
    if ((selectObj.selectedIndex > -1) && (selectObj[selectObj.selectedIndex].value == value)) {
        return false;
    }
    for (var i = 0; i < selectObj.length; i++) {
        var m = selectObj[i].value;
        if (selectObj[i].value == value) {
            selectObj.selectedIndex = i;
            return true;
        }
    }
    return false;
}

function getSelectedValue(SelectName){
    var selectObj = $(SelectName);
    var returnValue = "";
	for (i = 0; i < selectObj.length; i++) {
		try {
			if (selectObj.options[i].selected == true) {
				returnValue += selectObj.options[i].value + "|";
			}
		}
		catch (err) {
		}
	}
	if (returnValue.length > 0) {
		returnValue = returnValue.substr(0, returnValue.length - 1);
	}
    return returnValue;
}





function getStateForCountry(countryDropdownId, stateDropdownId, state){

    var selectedCountry = $F(countryDropdownId);
    var setState = state ? state : "";

    var requestURL = "stateCountry.ajax";
    var requestParameters = $H({
        country: selectedCountry
    });

    var stateCodeDisplay = "";
    var xmlDoc;
    var nodeCounter = 0;

    if (selectedCountry != "") {

        // Perform an AJAX request to fill the States for the given Country.
        new Ajax.Request(requestURL, {
            method: "get",
            parameters: requestParameters,
            onComplete: function(transport){
                xmlDoc = returnXMLDocument(transport.responseText);
                nodeCounter = xmlDoc.getElementsByTagName("state").length;

                if (nodeCounter > 0) {
                    $(stateDropdownId).options.length = 0;
                    $(stateDropdownId).options[0] = new Option(message.selectAState, "");
                    for (var i = 0; i < nodeCounter; i++) {
                        var desc = xmlDoc.getElementsByTagName("state")[i].attributes.getNamedItem("description").value;
                        var code = xmlDoc.getElementsByTagName("state")[i].attributes.getNamedItem("code").value;
                        var stateCodeDisplay = "";

                        if (selectedCountry != "USA") {
                            stateCodeDisplay = " (" + code + ")";
                        }

                        var newOption = new Option(desc + stateCodeDisplay, code);
                        $(stateDropdownId).options[i + 1] = newOption;

                        if (($(stateDropdownId).options[i + 1].value == setState) && setState != "") {
                            $(stateDropdownId).options.selectedIndex = i + 1;
                        }

                    }
                }

            },
            onFailure: function(){
            }
        });
    }
}

/**
 * This function is initially called by a mouseover event in our navigation.
 * The variables for these function are defined at the top of the file.
 * @param myId - ID of the nav item mousedOver which will set the sub nav to active
 * @return - N/A
 */
function mousedOver(myId){
    //If a function is active
    if (timerFunction != undefined) {
        //Stop function
        clearTimeout(timerFunction);
    }
    //Set the active id to the one passed in
    whoIsOn = myId;
    // Set function timer with the id that was passed in.
    timerFunction = setTimeout("showSubNav(" + myId + ")", navTimeoutInterval);
}

/**
 * This function will update the sub nav, by hiding inactive elements and
 * activating the most current.
 * @param myId - id of current nav element
 * @return - N/A
 */
function showSubNav(myId){
    // Clear the sub nav
    clearSubNav(myId);
    // If the ID passed in is who we are still on
    if (myId == whoIsOn) {
        // If the ID passed in exists in the nav collection
        if ($(navArray[myId]) != undefined) {
            // Show the sub nav element.
            $(navArray[myId]).style.display = "block";
        }
    }
    // Loop through all the nav elements
    for (var i = 0; i < navArray.length; i++) {
        // If the element is not the selected one
        if (i != myId) {
            // Hide the sub nav element
            $(navArray[i]).style.display = "none";
        }
    }
}

/**
 * This function is initially called on mouseout to hide any sub
 * navs that might be visible.
 * @param myId - id of the nav element that last mouseout of.
 * @return - N/A
 */
function hideSubNav(myId){
    // If a function is active
    if (timerFunction != undefined) {
        // Stop the function
        clearTimeout(timerFunction);
    }
    // Set function timer with the id of the nav item that was passed in.
    timerFunction = setTimeout("clearSubNav(" + myId + ")", navTimeoutInterval);
}

/**
 * This function will hide the sub nav item that was just mouseout of.
 * @param myId - id of sub nav item.
 * @return - N/A
 */
function clearSubNav(myId){
    // If the id exists in the nav collection
    if ($(navArray[myId]) != undefined) {
        // Hide it.
        $(navArray[myId]).style.display = "none";
    }
}


function setPageSubNav(){
    for (var i = 0; i < navArray.length; i++) {
        if ($(navArray[i]) != null && $(navArray[i]) !== undefined) {
            if ($(navArray[i]).style.display == "block") {
                origSetNav = navArray[i];
                break;
            }
        }
    }
}

function get_radio_value(radioButton){
    for (var i = 0; i < radioButton.length; i++) {
        if (radioButton[i].checked) {
            return radioButton[i].value;
        }
    }
}

function showIconPopup(code, url, iconURL, e){
    if (!AllowNewPopups) {
        return
    }
    if (code == 'PD') {
        showIconPopupDiv(url, iconURL, e);
    } else if (code == 'CN' && url != '') {
		// For the condition report icon, see if the div URL is available to display the div.
        showIconPopupDiv(url, iconURL, e);
    }
}

/**
 * This function is used to hide the icon div on mouseout
 */
function hideIconPopup(){
    if (!AllowNewPopups) {
        return
    }
    openIconPopupDiv = false;
    removeElement('info-div-global,msgDisabler');
}

var openIconPopupDiv = false;

function showIconPopupDiv(url, iconURL, e){

    if (iconURL != null && iconURL !== undefined && iconURL.length > 0) {
        iconURL = "&iconURL=" + iconURL;
    }
    else {
        iconURL = "";
    }

    openIconPopupDiv = true;
    // If there is already a popup open, close it
    if ($("info-div-global") != null) {
        removeElement('info-div-global,msgDisabler');
    }

    // Hide selects for IE.
    toggleSelects('hidden');

    var msgBg = $E({
        tag: "div",
        id: "msgDisabler"
    });
    msgBg.setAttribute("onclick", "removeElement('info-div-global,msgDisabler');");
    msgBg.onclick = function(){
        removeElement('info-div-global,msgDisabler');
    };

    new Ajax.Request("iconInfo.html", {
        method: "get",
        parameters: "view=" + url + iconURL,
        onSuccess: function(transport){
            if (openIconPopupDiv) {
                var infoContainer = $E({
                    tag: "div",
                    id: "info-div-global"
                });
                document.body.appendChild(msgBg);
                document.body.appendChild(infoContainer);
                $("info-div-global").innerHTML = transport.responseText;

				var mousedOverItemTop = findPos(e); //Icon mouseover top location
			    var mousedOverItemLeft = findLeftPos(e); //Icon mouseover left location
			    var divWidth = 330; //From CSS
			    var windowSize = Position.getWindowSize();
				mousedOverItemTop = mousedOverItemTop - (e.offsetHeight * 2);
				mousedOverItemLeft = mousedOverItemLeft + (e.offsetWidth + 10);

                Position.center(infoContainer);

				if((mousedOverItemLeft + divWidth) > windowSize.width)
				{
					mousedOverItemLeft -= ((divWidth + (e.offsetWidth * 2) + 20));
				}
                infoContainer.style.left = parseInt(mousedOverItemLeft) + "px";
//                infoContainer.style.top = parseInt(mousedOverItemTop) + "px";

                setDisablerHeight();
            }
        },
        onFailure: function(transport){
            redirectOnFailure(view);
        },
        onException: function(transport){
            redirectOnFailure(view);
        }
    });
}

function imageNotFoundShowNothing(image, imgName){
    /*var imgName = imgName || 'transparent.gif';
    imageURL = global.contextRoot + 'images/global/' + imgName;
    imageWidth = image.width;
    imageHeight = image.height;
    image.parentNode.innerHTML = "<img alt='Image Not Found' src='" + imageURL + "' width='1' height='1' />";
    */
}

//Effect.Scroll = Class.create();
//Object.extend(Object.extend(Effect.Scroll.prototype, Effect.Base.prototype), {
//    initialize: function(element){
//        this.element = $(element);
//        if (!this.element)
//            throw (Effect._elementDoesNotExistError);
//        this.start(Object.extend({
//            x: 0,
//            y: 0
//        }, arguments[1] ||
//        {}));
//    },
//    setup: function(){
//        /*var scrollOffsets = (this.element == window)
//         ? document.viewport.getScrollOffsets()
//         : Element._returnOffset(this.element.scrollLeft, this.element.scrollTop) ;*/
//        this.originalScrollLeft = 0;//scrollOffsets.left;
//        this.originalScrollTop = 0;//scrollOffsets.top;
//    },
//    update: function(pos){
//        this.element.scrollTop = Math.round(this.options.y * pos + this.originalScrollTop);
//        this.element.scrollLeft = Math.round(this.options.x * pos + this.originalScrollLeft);
//        //this.element.scrollTo(Math.round(this.options.x * pos + this.originalScrollLeft), Math.round(this.options.y * pos + this.originalScrollTop));
//    }
//});
//




function showGlossary(subsection){

    // If there is already a popup open, close it
    if ($("info-div-global") != null) {
        removeElement('info-div-global,msgDisabler');
    }

    infoDivSubSection = subsection;
    getInfoDivPageGlossary('glossaryOfTerms.html', 'Divs/aboutSaleInformationAndDefinitions');
    setTimeout('glossaryScrollTo()', 500);
}

function glossaryScrollTo(){
    var isIE = navigator.appName.indexOf("Explorer") > -1 ? true : false;

    if ($('info-div-global') != null && $('info-div-global') !== undefined) {
        var parent_y = $('info-div-global').offsetTop;
        var glossarySubsections = $('glossText').getElementsByTagName('th');
        var _y = 0;

        if (isIE) {
            var parentChromeOffset = 60;
        }
        else {
            var parentChromeOffset = 55;
        }

        for (var i = 0; i < glossarySubsections.length; i++) {
            if (glossarySubsections[i].id == infoDivSubSection) {
                _y = findPos(glossarySubsections[i]);
                break;
            }
        }
        new Effect.Scroll('glossText', {
            y: _y - (parent_y + parentChromeOffset)
        });
    }
    else {
        setTimeout('glossaryScrollTo()', 100);
    }
}
//
function findPos(obj){
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
            // curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        }
        while (obj = obj.offsetParent);
    }
    return curtop;
}
function findLeftPos(obj){
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            // curtop += obj.offsetTop;
        }
        while (obj = obj.offsetParent);
    }
    return curleft;
}

/**
 * This function will auto tab from the 'original' to the 'destination'.
 * @param {Object} original - string name of the current field
 * @param {Object} destination - string name of the field to go to.
 */
function autoTab(original, destination){
    if ($(original).getAttribute && ($(original).value.length == $(original).getAttribute("maxlength"))) {
        $(destination).focus();
    }
}

function serviceLevelCheck(){
    if ($('leftNavLoginSection') != null && $('leftNavLoginSection') !== undefined) {
        var date = new Date();
        new Ajax.Request('serviceLevelCheck.ajax?nocache=' + date.getMilliseconds, {
            method: 'get',
            onSuccess: function(transport){
                if (transport.responseText == 'ROLL_SWAP') { //C2_BUYER_DOWN, ROLL_SWAP
                    $('leftNavLoginSection').hide();
                    $('leftNavLoginSectionNotAvail').show();
                }
                else {
                    $('leftNavLoginSection').show();
                    $('leftNavLoginSectionNotAvail').hide();
                    if (transport.responseText == 'C2_BUYER_DOWN') {
                        $('btnLeftNavBuyerLogin').href = globalLoginUrls.prevBuyerLogin;
                    }
                    else {
                        $('btnLeftNavBuyerLogin').href = globalLoginUrls.c2BuyerLogin;
                    }
                }
            },
            onFailure: function(transport){
                $('leftNavLoginSection').show();
                $('leftNavLoginSectionNotAvail').hide();
            },
            onException: function(transport){
                $('leftNavLoginSection').show();
                $('leftNavLoginSectionNotAvail').hide();
            }
        });
    }
}

function Gallery(htmlObjectId, galleryId, moveBy){
    function moveToPrevious(){
        if (this.galleryPosition > 0) {
            new Effect.Move(this.htmlObjectId, {
                x: this.galleryMoveBy,
                y: 0,
                transition: Effect.Transitions.sinoidal
            });
            this.galleryPosition -= this.galleryMoveBy;
        }
    }

    function moveToNext(){
        if ((this.galleryPosition + this.galleryMoveBy) <= getMaxScrollTo(this.galleryWidth)) {
            new Effect.Move(this.htmlObjectId, {
                x: -(this.galleryMoveBy),
                y: 0,
                transition: Effect.Transitions.sinoidal
            });
            this.galleryPosition += this.galleryMoveBy;
        }
    }

    function getMaxScrollTo(galleryWidthDefault){
        var maxScrollPos = 0;
        if (navigator.appName.indexOf('Explorer') >= 0) {
            maxScrollPos = galleryWidthDefault - 250;
            return maxScrollPos;
        }
        else {
            maxScrollPos = galleryWidthDefault + 225;
            return maxScrollPos;
        }
    }

    this.htmlObjectId = htmlObjectId; //Ojbect in page containing images
    this.galleryId = galleryId; //gallery id to pass to load gallery
    this.moveToPrevious = moveToPrevious;
    this.moveToNext = moveToNext;
    this.galleryPosition = 0;
    this.galleryWidth = $(htmlObjectId).offsetWidth;
    this.galleryMoveBy = moveBy ? moveBy : 75; //This value can be passed in or default will be used
}
/*Event.observe(window, 'load', function(){
    setPageSubNav();
});*/

function formSubmit(formName, dropDownName){
    if ($F(dropDownName) != "") {
        $(formName).submit();
    }
}

function homeVideo(){
	$('flashVideo').style.background = 'url(images/global/transparent.gif)';
	var so2 = new SWFObject(message.copartVideoURL, 'copartVideo', '350', '260', '8.0.23', "#FFFFFF");
	so2.addParam("wmode", "transparent");
	so2.write("flashVideo");
}

function goTo(url)
{
	window.location.href = url;
}

/*Position.getWindowSize = function(w) {
	var array = [];

	w = w ? w : window;
	array.width = array[0] = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
	array.height = array[1] = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);

    return array;
}
*/
function getWifiDefinitionDiv()
{
	createInfoDivPopup('aboutWiFi.html', '', null, false, null, null);
}

/**
 * This function will perform validation on the Quick Search form.
 */
function validateQuickSearch(){
    var selectedQuickSearch = $F("categorySearchType");
    var errors = "";

    // clear out error old messages
    $("quickSearchError").innerHTML = ""


    if (selectedQuickSearch == null) {
        errors += message.quickSearch_error;
        $("quickSearchError").innerHTML = message.quickSearch_error;
    }

    if (errors != "") {
        $("quickSearchError").innerHTML = errors;
    }

    searchParms.mileageRange = $F("mileageRange");
    searchParms.zip = zipPostalCode
    saveSearchParms(searchParms);

    return true;
}

function quickSearchSubmit(){
    // clear out error old messages
	if ($("quickSearchError_lotVin") != null && $("quickSearchError_lotVin") !== undefined) {
		$("quickSearchError_lotVin").innerHTML = "";
	}
	if ($("quickSearchError") != null && $("quickSearchError") !== undefined) {
		$("quickSearchError").innerHTML = "";
	}
	if ($("detailedSearchError") != null && $("detailedSearchError") !== undefined) {
		$("detailedSearchError").innerHTML = "";
	}

	if(document.quickSearch.filterCode.value.length <= 0) {
		$("quickSearchError").innerHTML = message.quickSearch_error;
		return false;
	}

    //quick search
    var errors = "";
    var zipPostalCode;
    var selectedQuickSearch = document.quickSearch.filterCode.options[document.quickSearch.filterCode.options.selectedIndex].value;

    // validate search type
    if (selectedQuickSearch == null) {
        errors += message.quickSearch_error;
    }

    if (errors != "") {
        $("quickSearchError").innerHTML = errors;
        return false;
    }




    var uncleanLabel = document.quickSearch.filterCode.options[document.quickSearch.filterCode.options.selectedIndex].text;
    var closeParenPos = uncleanLabel.lastIndexOf(")");
    var openParenPos = uncleanLabel.lastIndexOf("(");
    var cleanLabel = "";

    if (closeParenPos > -1 && openParenPos > -1) {
        cleanLabel = uncleanLabel.substring(0, openParenPos - 1);
    }
    else {
        cleanLabel = uncleanLabel;
    }

    $("filterBaseLabelQuick").value = cleanLabel;

    //Submit form
    $('quickSearch').submit();
}


function createLoginDivPopup(controller){

    // If there is already a popup open, close it
    if ($("info-div-global") != null) {
        removeElement('info-div-global,msgDisabler')
    }

    // Hide selects for IE.
    toggleSelects('hidden');

    var msgBg = $E({
        tag: "div",
        id: "msgDisabler"
    });

	msgBg.setAttribute("onclick", "removeElement('info-div-global,msgDisabler');");
    msgBg.onclick = function(){
        removeElement('info-div-global,msgDisabler');
    };
	var noCacheDate = new Date();
    new Ajax.Request(controller, {
        method: "get",
        parameters: "noCache=" + noCacheDate,
        onSuccess: function(transport){
            var infoContainer = $E({
                tag: "div",
                id: "info-div-global"
            });
            document.body.appendChild(msgBg);
            document.body.appendChild(infoContainer);
            $("info-div-global").innerHTML = transport.responseText;
			var mousedOverItemTop = findPos($('globalUnifiedLogin')); // find top loc of login button
			var mousedOverItemLeft = findLeftPos($('globalUnifiedLogin')); // find left loc of login buttoni
			Position.center(infoContainer);
            infoContainer.style.left = (parseInt(mousedOverItemLeft) - 5) + "px";
			infoContainer.style.top = (parseInt(mousedOverItemTop) + 45) + "px";
            setDisablerHeight();
        },
        onFailure: function(transport){
            redirectOnFailure(view);
        },
        onException: function(transport){
            redirectOnFailure(view);
        }
    });
}

function setFilterBaseLabel(label)
{
	document.specialSearchForm.filterBaseLabel.value = label;
	// $('specialSearchForm').submit();
	//$('filterBaseLabel').value=label;
	return false;
}
function validateSpecialSearch(){
    if (true) {

        //rememberZip($("enteredZip").value);
        //searchParms.zip = 94534;
        //saveSearchParms(searchParms);
        //$("specialZipPostalCode").value = 94534;
        $("errorSpan").innerHTML = "&nbsp;";
        submitForm = true;
    }
    return true;
}

function setPickup(){
    // Clears the error message in zip/postal code div If the user clicks on other image.
    //clearErrorCode();
    setSpecialSearchValues("9");
}

function setSUV(){
    // Clears the error message in zip/postal code div If the user clicks on other image.
    //clearErrorCode();
    setSpecialSearchValues("8");
}

function setCars(){
    // Clears the error message in zip/postal code div If the user clicks on other image.
    //clearErrorCode();
    setSpecialSearchValues("A");
}

function setMarine(){
    // Clears the error message in zip/postal code div If the user clicks on other image.
   // clearErrorCode();
    setSpecialSearchValues("G");
}

function setClassics(){
    // Clears the error message in zip/postal code div If the user clicks on other image.
    //clearErrorCode();
    setSpecialSearchValues("J");
}

function setRecreational(){
    // Clears the error message in zip/postal code div If the user clicks on other image.
    //clearErrorCode();
    setSpecialSearchValues("C");
}

function setIndustrialEquipment(){
    // Clears the error message in zip/postal code div If the user clicks on other image.
    //clearErrorCode();
    setSpecialSearchValues("D");
}

function setMotorcycles(){
    // Clears the error message in zip/postal code div If the user clicks on other image.
    //clearErrorCode();
    setSpecialSearchValues("B");
}

function setJetSkis(){
    // Clears the error message in zip/postal code div If the user clicks on other image.
    //clearErrorCode();
    setSpecialSearchValues("F");
}

function setSnowMobiles(){
    // Clears the error message in zip/postal code div If the user clicks on other image.
    //clearErrorCode();
    setSpecialSearchValues("E");
}// Modified for bug 5785 - Invalid zip code returns results by Phani

function setSpecialSearchValues(filterCode){

	$("ssFilterCode").value = filterCode;
    $("specialSearchForm").submit();

    //showZip();
}

/** BEGIN: Challenge of Champions **/
function loadSoldInSeconds(){
    toggleSelects('hidden');
	var date = new Date();
    var msgBg = $E({
        tag: 'div',
        id: 'soldInSecondsBg'
    });

    new Ajax.Request(globalLoginUrls.c2SoldInSeconds, {
        method: 'get',
        onSuccess: function(transport){
            var infoContainer = $E({
                tag: "div",
                id: "soldInSeconds"
            });
			document.body.appendChild(msgBg);
            document.body.appendChild(infoContainer);
            $("soldInSeconds").innerHTML = transport.responseText;
			Position.center(infoContainer);
            setObjectHeightToMatchWindow('soldInSeconds');
        },
        onFailure: function(transport){

        },
        onException: function(transport){

        }
    });
}

function closeSoldInSeconds() {
	removeElement('soldInSeconds,soldInSecondsBg');
}

function videoSoldInSeconds() {
	var so2 = new SWFObject(globalLoginUrls.c2SoldInSecondsVideo, 'sisVideo', '324', '220', '8.0.23', "#000000");
	so2.addParam("wmode", "transparent");
	so2.write("soldInSecondsVideoLocation");
}

/*
Event.observe(window, "load", function(){

    Event.observe('searchCars', 'click', setCars);
    Event.observe('searchClassics', 'click', setClassics);
    Event.observe('searchSUV', 'click', setSUV);
    Event.observe('searchMarine', 'click', setMarine);
    Event.observe('searchRecreational', 'click', setRecreational);
    Event.observe('searchPickupTruck', 'click', setPickup);
    Event.observe('searchMotorcycles', 'click', setMotorcycles);
    Event.observe('searchJetSkis', 'click', setJetSkis);
    Event.observe('searchIndustrialEquipment', 'click', setIndustrialEquipment);
    Event.observe('searchSnowMobiles', 'click', setSnowMobiles);
});
        */
