/* -- Cached as autos.js on -- 2010-07-02 04:35:58 */

// -----------------------------------------------------------------------------------

//
//	Animation Configuration (for overlays/lightbox)
//
var animate = true;
var resizeSpeed = 5 // Number 1-10 //
var overlayDuration = 0.2;	// shadow fade in/out duration

// THIS AFFECTS THE POPUP //
dojo.require("dojo.cookie");

function DisplayPopup(winURL,wWidth,wHeight,over) {
	var show = 1;
	if (popupUseCookie == true){
		if (!dojo.cookie('dhd[sitepopup]')){
			dojo.cookie('dhd[sitepopup]', 1, {expires: 1});
			var show = 1;
		} else {
			show = 0;
			console.log("not showing");
		}
	} else if (readCookie('dhd[sitepopup]')){
		dojo.cookie('dhd[sitepopup]', null, {expires: -1});
	}
	if (show){
		if (wWidth && wHeight) {
			if (over==2){
				window.open(winURL,'','width='+wWidth+',height='+wHeight).blur();
				window.focus();
			} else {
				window.open(winURL,'','width='+wWidth+',height='+wHeight);
			}
		}
	}
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

/*
MOVED
function removeCompare(label) {
	var thisForm = $('compareForm');
	var remove = document.createElement("input");
	remove.type = "checkbox";
	remove.name = "remove[]";
	remove.value = label;
	thisForm.appendChild(remove);
	remove.checked=true;
	thisForm.submit();
}
*/

function processContactForm(reqFields) {
	var args = PreProcessContactForm(reqFields);
    //do request
    if (args != ''){
    	var request = getRequest();
		//formButtonEnable(0);

	    request.onreadystatechange=function()
		{
		if(request.readyState==4)
		  {
		  	// Reset upon succesfull submission.
		  	if( dijit.byId( 'safeSubmit' ) ) {
				dijit.byId( 'safeSubmit' ).resetTimeout();
			}
		  	PostProcessContactForm(request.responseText, args);
		  }
		}

		clearFeedback('GOOD');
		clearFeedback('BAD');

		addFeedback("GOOD", "We are sending your information.")

		var address = "print_customOffer.php?verify=1&"+args;
		request.open("get", address, true);
    	request.send(null);
	} else {
		// Errors in form
		// Reset on unsuccesful submission
		if( dijit.byId( 'safeSubmit' ) ) {
			dijit.byId( 'safeSubmit' ).resetTimeout();
		}
	}
}

function getFItem(type){
	var fItem = "";
	if (type == "GOOD")	{
		fItem = document.getElementById("positiveFeedback");
	} else if (type == "BAD"){
		fItem = document.getElementById("negativeFeedback");
	}
	return fItem;
}

function getFormButton(){
	return document.getElementById("safeSubmit");
}

function addFeedback(type, info){
	var fItem = getFItem(type);
	if (fItem){
		if (fItem.innerHTML){
			fItem.innerHTML+="<br/>"+info;
		}else{
			fItem.innerHTML = info;
		}

		if (info){
			fItem.style.display = "block";

		}
	}
}

function clearFeedback(type){
	var fItem = getFItem(type);
	if (fItem){
		fItem.innerHTML = "";
	}
	fItem.style.display = "none";
}

function highlightMissingInfo(ele, force){
	if (ele){
		if (force == 1 || (ele.value == "" && force == "")){
			ele.style.backgroundColor = "#FF8888";
		} else {
			ele.style.backgroundColor = "#FFFFFF";
		}
	}
}


function formButtonEnable(en){
	/*if (en){
		getFormButton().disabled = "";
	} else {
		getFormButton().disabled = "disabled";
	}*/
}

function check_email(e) {
	var filter=/^.+@.+\..{2,3}$/

	if (filter.test(e)) return 1;
	return 0;
}

function PostProcessContactForm(res, args){
	clearFeedback('GOOD');
	clearFeedback('BAD');

	if (res == "OK"){
		addFeedback("GOOD", "Your information was successfully received.");
		addFeedback("GOOD", "If a new window does not open, please check your popup blocker settings. You might be missing out on a special offer!");
		window.open("print_customOffer.php?verify=0&"+args, "customResult");
		//formButtonEnable(1);
		//setTimeout("_gCustomOfferOverlay.hide()", 5000);
		return;
	} else {
		//formButtonEnable(1);
		if (res != ""){
			addFeedback("BAD", res)
		} else {
			addFeedback("BAD", "We are sorry, but the server could not be contacted. Please try again soon.")
		}
	}
}

function PreProcessContactForm(reqFields){
	clearFeedback('GOOD');
	clearFeedback('BAD');
	var args = '';
	var errors = 0;

	//----------
	//REQUIRED
	//first name
	if (dojo.indexOf(reqFields,"firstName") != -1){
		ele = document.getElementById("contact_form_firstName");
		highlightMissingInfo(ele, 0);
		var fnStr = ele.value;
		filter=/^[a-zA-Z\.' ]+$/
		if (!filter.test(fnStr)){
			addFeedback("BAD", "The first name field may only be letters and punctuation.")
			highlightMissingInfo(ele, 1);
			ele.onchange = PreProcessContactForm;
			errors++;
		} else {
			args += "firstName="+fnStr;
		}
	} else {
		args += "firstName="+fnStr;
	}

	//last name
	if (dojo.indexOf(reqFields,"lastName") != -1){
		ele = document.getElementById("contact_form_lastName");
		highlightMissingInfo(ele, 0);
		var lnStr = ele.value;
		filter=/^[a-zA-Z\.' ]+$/
		if (!filter.test(lnStr)){
			addFeedback("BAD", "The last name field may only be letters and punctuation.")
			highlightMissingInfo(ele, 1);
			ele.onchange = PreProcessContactForm;
			errors++;
		} else {
			args += "&lastName="+lnStr;
		}
	} else {
		args += "&lastName="+lnStr;
	}

	//daytime phone
	if (dojo.indexOf(reqFields,"phone_area") != -1){
		ele = document.getElementById("contact_form_phone_area");
		highlightMissingInfo(ele, 0);
		var pAreaStr = ele.value;
		var filter=/^\d{3,3}$/
		if (!filter.test(pAreaStr)){
			addFeedback("BAD", "The daytime area code may only contain 3 digits.")
			highlightMissingInfo(ele, 1);
			ele.onchange = PreProcessContactForm;
			errors++;
		} else {
			args += "&phone_area="+pAreaStr;
		}

		ele = document.getElementById("contact_form_phone_number1");
		highlightMissingInfo(ele, 0);
		var pP1Str = ele.value;
		var filter=/^\d{3,3}$/
		if (!filter.test(pP1Str)){
			addFeedback("BAD", "The daytime phone number 1 may only contain 3 digits.")
			highlightMissingInfo(ele, 1);
			ele.onchange = PreProcessContactForm;
			errors++;
		} else {
			args += "&phone_number1="+pP1Str;
		}

		ele = document.getElementById("contact_form_phone_number2");
		highlightMissingInfo(ele, 0);
		var pP2Str = ele.value;
		var filter=/^\d{4,4}$/
		if (!filter.test(pP2Str)){
			addFeedback("BAD", "The daytime phone number 2 may only contain 4 digits.")
			highlightMissingInfo(ele, 1);
			ele.onchange = PreProcessContactForm;
			errors++;
		} else {
			args += "&phone_number2="+pP2Str;
		}

		/*
		ele = document.getElementById("contact_form_phone_ext");
		highlightMissingInfo(ele);
		var pExtStr = ele.value;
		var filter=/^\d{0,6}$/
		if (!filter.test(pExtStr)){
			addFeedback("BAD", "The daytime phone extension may contain 0 to 6 digits.")
			highlightMissingInfo(ele, 1);
			errors++;
		} else {
			args += "&phone_ext="+pExtStr;
		}*/
	}

	//email
	if (dojo.indexOf(reqFields,"email") != -1){
		ele = document.getElementById("contact_form_email");
		highlightMissingInfo(ele, 0);
		var emailStr = ele.value;
		if (!check_email(emailStr)){
			addFeedback("BAD", "The email address is not valid.")
			highlightMissingInfo(ele, 1);
			ele.onchange = PreProcessContactForm;
			errors++;
		} else {
			args += "&email="+emailStr;
		}
	} else {
		args += "&email="+document.getElementById("contact_form_email").value;
	}


	////////Optional Items////////
	if (dojo.indexOf(reqFields,"street") != -1){
		//street
		ele = document.getElementById("contact_form_street");
		highlightMissingInfo(ele, 0);
		var streetStr = ele.value;
		filter=/^[0-9a-zA-Z\.,' ]+$/
		if (!filter.test(streetStr)){
			addFeedback("BAD", "You must specify a street.")
			highlightMissingInfo(ele, 1);
			errors++;
		} else {
			args += "&street="+streetStr;
		}
	} else {
		args += "&street="+document.getElementById("contact_form_street").value;
	}

	//city
	if (dojo.indexOf(reqFields,"city") != -1){
		ele = document.getElementById("contact_form_city");
		highlightMissingInfo(ele, 0);
		var cityStr = ele.value;
		filter=/^[0-9a-zA-Z\.,' ]+$/
		if (!filter.test(cityStr)){
			addFeedback("BAD", "You must specify a city.")
			highlightMissingInfo(ele, 1);
			errors++;
		} else {
			args += "&city="+cityStr;
		}
	} else {
		args += "&city="+document.getElementById("contact_form_city").value;
	}

	//state
	if (dojo.indexOf(reqFields,"state") != -1){
		ele = document.getElementById("contact_form_state");
		highlightMissingInfo(ele, 0);
		var stateStr = ele.options[ele.selectedIndex].value;
		if (!ele.selectedIndex || stateStr.value == ""){
			addFeedback("BAD", "You must specify a state.")
			highlightMissingInfo(ele, 1);
			errors++;
		} else {
			args += "&state="+stateStr;
		}
	} else {
		//state
		ele = document.getElementById("contact_form_state");
		var stateStr = ele.options[ele.selectedIndex].value;
		args += "&state="+stateStr;
	}

	//zip
	args += "&zip="+document.getElementById("contact_form_zip").value;
	args += "&zip2="+document.getElementById("contact_form_zip2").value;

	//make
	if (dojo.indexOf(reqFields,"make") != -1){
		ele = document.getElementById("contact_form_make");
		highlightMissingInfo(ele, 0);
		var streetStr = ele.value;
		filter=/^[0-9a-zA-Z\.,' ]+$/
		if (!filter.test(streetStr)){
			addFeedback("BAD", "You must specify a make.")
			highlightMissingInfo(ele, 1);
			errors++;
		} else {
			args += "&make="+document.getElementById("contact_form_make").value;
		}
	} else {
		args += "&make="+document.getElementById("contact_form_make").value;
	}

	//model
	if (dojo.indexOf(reqFields,"model") != -1){
		ele = document.getElementById("contact_form_model");
		highlightMissingInfo(ele, 0);
		var streetStr = ele.value;
		filter=/^[0-9a-zA-Z\.,' ]+$/
		if (!filter.test(streetStr)){
			addFeedback("BAD", "You must specify a model.")
			highlightMissingInfo(ele, 1);
			errors++;
		} else {
			args += "&model="+document.getElementById("contact_form_model").value;
		}
	} else {
		args += "&model="+document.getElementById("contact_form_model").value;
	}

	//comments
	if (dojo.indexOf(reqFields,"notes") != -1){
		ele = document.getElementById("contact_form_notes");
		highlightMissingInfo(ele, 0);
		if (ele.value == ""){
			addFeedback("BAD", "You must give some comments.")
			highlightMissingInfo(ele, 1);
			errors++;
		} else {
			args += "&notes="+ele.value;
		}
	} else {
		args += "&notes="+document.getElementById("contact_form_notes").value;
	}

	if (errors != 0){
		args = '';
	}
	return args;
}

function timecalculator(month1, day1, year1, month2, day2, year2, timeDifference)
{
month1 = document.getElementById(month1);
day1 = document.getElementById(day1);
year1 = document.getElementById(year1);
month2 = document.getElementById(month2);
day2 = document.getElementById(day2);
year2 = document.getElementById(year2);
timeDifference = document.getElementById(timeDifference);

var startdate;
var enddate;
var totaldays;
var monthsWorked;
var daysWorked;
var yearsWorked;

if ((month1.value != "") && (day1.value != "") && (year1.value != "") && (month2.value != "") && (day2.value != "") && (year2.value != ""))
	{
	startdate = new Date(year1.value, month1.value - 1, day1.value);
	enddate = new Date(year2.value, month2.value - 1, day2.value);
	totaldays = (enddate.getTime() - startdate.getTime());
	totaldays = new Date(totaldays);
	yearsWorked = Math.floor(totaldays / (365 * 24 * 60 * 60 * 1000));
	totaldays = totaldays - yearsWorked * (365 * 24 * 60 * 60 * 1000);
	monthsWorked = Math.floor(totaldays / (30.4167 * 24 * 60 * 60 * 1000));
	totaldays = totaldays - monthsWorked * (30.4167 * 24 * 60 * 60 * 1000);
	daysWorked = Math.ceil(totaldays / (24 * 60 * 60 * 1000));
	timeDifference.value = yearsWorked + " years, " + monthsWorked + " months, " + daysWorked + " days";
	}
else
	{
	timeDifference.value = "Please finish filling in the dates";
	}
}


// Wrapper function to handle event tracking.
function trackEvent( /*String*/ acct, /*String*/ category, /*String*/ action, /*String*/ label, /*Int*/ value ) {
	// Required.
	if(!acct||!category||!action) return;

	// Test to see if we have access to google's global variable
	if(typeof(_gat)!="undefined") {
		var t = _gat._getTracker(acct);	// Tracker variable.

		var ret = (value)	? (label)
							? t._trackEvent(category, action, label, value)
							: t._trackEvent(category, action, undefined, value)
						: (label)
							? t._trackEvent(category, action, label)
							: t._trackEvent(category, action);
		return ret;
	} else {
		// No access, deferr this callback.
		_gAnalyticDeferred.addCallback(dojo.hitch(this, function(){
			var t = _gat._getTracker(acct);	// Tracker variable.

			var ret = (value)	? (label)
								? t._trackEvent(category, action, label, value)
								: t._trackEvent(category, action, undefined, value)
							: (label)
								? t._trackEvent(category, action, label)
								: t._trackEvent(category, action);
			return ret;
		}));
	}
}

function appendStrings(/* All JS functions have the ability to take 1..n args via accessing "arguments". */) {
	var retStr = "";
	// Loop through each argument passed in.
	dojo.forEach( arguments, dojo.hitch( this, function( arg ) {
		if( dojo.isString( arg ) ) {
			// Check for the seperator prefix.
			if( arg.indexOf( "seperator:" ) != -1 ) {
				// Only use the seperator if we have length on this string already.
				if( retStr.length ) {
					retStr = retStr + " " + arg.replace( "seperator:", "" );
				}
			} else if( arg.length && retStr.length ) {
				// If our retStr has some content already, add a space before appending.
				retStr = retStr + " " + arg;
			} else if( arg.length ) {
				// This must be the first time we are adding content, ignore the leading space.
				retStr = arg;
			}
		}
	}));
	return retStr;
}
/*==================================================*
 $Id: slideshow.js,v 1.16 2003/10/14 12:39:00 pat Exp $
 Copyright 2000-2003 Patrick Fitzgerald
 http://slideshow.barelyfitz.com/

 This program is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation; either version 2 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *==================================================*/

// There are two objects defined in this file:
// "slide" - contains all the information for a single slide
// "slideshow" - consists of multiple slide objects and runs the slideshow

//==================================================
// slide object
//==================================================
function slide(src,link,text,target,attr) {
  // This is the constructor function for the slide object.
  // It is called automatically when you create a new slide object.
  // For example:
  // s = new slide();

  // Image URL
  this.src = src;

  // Link URL
  this.link = link;

  // Text to display
  this.text = text;

  // Name of the target window ("_blank")
  this.target = target;

  // Custom duration for the slide, in milliseconds.
  // This is an optional parameter.
  // this.timeout = 3000

  // Attributes for the target window:
  // width=n,height=n,resizable=yes or no,scrollbars=yes or no,
  // toolbar=yes or no,location=yes or no,directories=yes or no,
  // status=yes or no,menubar=yes or no,copyhistory=yes or no
  // Example: "width=200,height=300"
  this.attr = attr;

  // Create an image object for the slide
  if (document.images) {
    this.image = new Image();
  }

  // Flag to tell when load() has already been called
  this.loaded = false;

  //--------------------------------------------------
  this.load = function() {
    // This method loads the image for the slide
    if (!document.images) { return; }

    if (!this.loaded) {
      this.image.src = this.src;
      this.loaded = true;
    }
  }

  //--------------------------------------------------
  this.hotlink = function() {
    // This method jumps to the slide's link.
    // If a window was specified for the slide, then it opens a new window.
    var mywindow;

    // If this slide does not have a link, do nothing
    if (!this.link) return;

    // Open the link in a separate window?
    if (this.target) {
      // If window attributes are specified,
      // use them to open the new window
      if (this.attr) {
        mywindow = window.open(this.link, this.target, this.attr);
      } else {
        // If window attributes are not specified, do not use them
        // (this will copy the attributes from the originating window)
        mywindow = window.open(this.link, this.target);
      }

      // Pop the window to the front
      if (mywindow && mywindow.focus) mywindow.focus();
    } else {
      // Open the link in the current window
      location.href = this.link;
    }
  }
}

//==================================================
// slideshow object
//==================================================
function slideshow( slideshowname ) {
  // This is the constructor function for the slideshow object.
  // It is called automatically when you create a new object.
  // For example:
  // ss = new slideshow("ss");

  // Name of this object
  // (required if you want your slideshow to auto-play)
  // For example, "SLIDES1"
  this.name = slideshowname;

  // When we reach the last slide, should we loop around to start the
  // slideshow again?
  this.repeat = true;

  // Number of images to pre-fetch.
  // -1 = preload all images.
  //  0 = load each image is it is used.
  //  n = pre-fetch n images ahead of the current image.
  // I recommend preloading all images unless you have large
  // images, or a large amount of images.
  this.prefetch = -1;

  // IMAGE element on your HTML page.
  // For example, document.images.SLIDES1IMG
  this.image;

  // ID of a DIV element on your HTML page that will contain the text.
  // For example, "slides2text"
  // Note: after you set this variable, you should call
  // the update() method to update the slideshow display.
  this.textid;

  // TEXTAREA element on your HTML page.
  // For example, document.SLIDES1FORM.SLIDES1TEXT
  // This is a depracated method for displaying the text,
  // but you might want to supply it for older browsers.
  this.textarea;

  // Milliseconds to pause between slides.
  // Individual slides can override this.
  this.timeout = 3000;

  // Hook functions to be called before and after updating the slide
  // this.pre_update_hook = function() { }
  // this.post_update_hook = function() { }

  // These are private variables
  this.slides = new Array();
  this.current = 0;
  this.timeoutid = 0;

  //--------------------------------------------------
  // Public methods
  //--------------------------------------------------
  this.add_slide = function(slide) {
    // Add a slide to the slideshow.
    // For example:
    var i = this.slides.length;

    // Prefetch the slide image if necessary
    if (this.prefetch == -1) {
      slide.load();
    }

    this.slides[i] = slide;
  }

  //--------------------------------------------------
  this.play = function(timeout) {
    // This method implements the automatically running slideshow.
    // If you specify the "timeout" argument, then a new default
    // timeout will be set for the slideshow.

    // Make sure we're not already playing
    this.pause();

    // If the timeout argument was specified (optional)
    // then make it the new default
    if (timeout) {
      this.timeout = timeout;
    }

    // If the current slide has a custom timeout, use it;
    // otherwise use the default timeout
    if (typeof this.slides[ this.current ].timeout != 'undefined') {
      timeout = this.slides[ this.current ].timeout;
    } else {
      timeout = this.timeout;
    }

    // After the timeout, call this.loop()
    this.timeoutid = setTimeout( this.name + ".loop()", timeout);
  }

  //--------------------------------------------------
  this.pause = function() {
    // This method stops the slideshow if it is automatically running.

    if (this.timeoutid != 0) {

      clearTimeout(this.timeoutid);
      this.timeoutid = 0;

    }
  }

  //--------------------------------------------------
  this.update = function() {
    // This method updates the slideshow image on the page

    // Make sure the slideshow has been initialized correctly
    if (! this.valid_image()) { return; }

    // Call the pre-update hook function if one was specified
    if (typeof this.pre_update_hook == 'function') {
      this.pre_update_hook();
    }

    // Convenience variable for the current slide
    var slide = this.slides[ this.current ];

    // Determine if the browser supports filters
    var dofilter = false;
    if (this.image &&
        typeof this.image.filters != 'undefined' &&
        typeof this.image.filters[0] != 'undefined') {

      dofilter = true;

    }

    // Load the slide image if necessary
    slide.load();

    // Apply the filters for the image transition
    if (dofilter) {

      // If the user has specified a custom filter for this slide,
      // then set it now
      if (slide.filter &&
          this.image.style &&
          this.image.style.filter) {

        this.image.style.filter = slide.filter;

      }
      this.image.filters[0].Apply();
    }

    // Update the image.
    this.image.src = slide.image.src;

    // Play the image transition filters
    if (dofilter) {
      this.image.filters[0].Play();
    }

    // Update the text
    this.display_text();

    // Call the post-update hook function if one was specified
    if (typeof this.post_update_hook == 'function') {
      this.post_update_hook();
    }

    // Do we need to pre-fetch images?
    if (this.prefetch > 0) {

      var next, prev, count;

      // Pre-fetch the next slide image(s)
      next = this.current;
      prev = this.current;
      count = 0;
      do {

        // Get the next and previous slide number
        // Loop past the ends of the slideshow if necessary
        if (++next >= this.slides.length) next = 0;
        if (--prev < 0) prev = this.slides.length - 1;

        // Preload the slide image
        this.slides[next].load();
        this.slides[prev].load();

        // Keep going until we have fetched
        // the designated number of slides

      } while (++count < this.prefetch);
    }
  }

  //--------------------------------------------------
  this.goto_slide = function(n) {
    // This method jumpts to the slide number you specify.
    // If you use slide number -1, then it jumps to the last slide.
    // You can use this to make links that go to a specific slide,
    // or to go to the beginning or end of the slideshow.
    // Examples:
    // onClick="myslides.goto_slide(0)"
    // onClick="myslides.goto_slide(-1)"
    // onClick="myslides.goto_slide(5)"

    if (n == -1) {
      n = this.slides.length - 1;
    }

    if (n < this.slides.length && n >= 0) {
      this.current = n;
    }

    this.update();
  }


  //--------------------------------------------------
  this.goto_random_slide = function(include_current) {
    // Picks a random slide (other than the current slide) and
    // displays it.
    // If the include_current parameter is true,
    // then
    // See also: shuffle()

    var i;

    // Make sure there is more than one slide
    if (this.slides.length > 1) {

      // Generate a random slide number,
      // but make sure it is not the current slide
      do {
        i = Math.floor(Math.random()*this.slides.length);
      } while (i == this.current);

      // Display the slide
      this.goto_slide(i);
    }
  }

  //--------------------------------------------------
  this.specific = function(place) {
    // This method advances to the next slide.

    // Increment the image number
    this.current = place;

    this.update();
  }

  //--------------------------------------------------
  this.next = function() {
    // This method advances to the next slide.

    // Increment the image number
    if (this.current < this.slides.length - 1) {
      this.current++;
    } else if (this.repeat) {
      this.current = 0;
    }

    this.update();
  }


  //--------------------------------------------------
  this.previous = function() {
    // This method goes to the previous slide.

    // Decrement the image number
    if (this.current > 0) {
      this.current--;
    } else if (this.repeat) {
      this.current = this.slides.length - 1;
    }

    this.update();
  }


  //--------------------------------------------------
  this.shuffle = function() {
    // This method randomly shuffles the order of the slides.

    var i, i2, slides_copy, slides_randomized;

    // Create a copy of the array containing the slides
    // in sequential order
    slides_copy = new Array();
    for (i = 0; i < this.slides.length; i++) {
      slides_copy[i] = this.slides[i];
    }

    // Create a new array to contain the slides in random order
    slides_randomized = new Array();

    // To populate the new array of slides in random order,
    // loop through the existing slides, picking a random
    // slide, removing it from the ordered list and adding it to
    // the random list.

    do {

      // Pick a random slide from those that remain
      i = Math.floor(Math.random()*slides_copy.length);

      // Add the slide to the end of the randomized array
      slides_randomized[ slides_randomized.length ] =
        slides_copy[i];

      // Remove the slide from the sequential array,
      // so it cannot be chosen again
      for (i2 = i + 1; i2 < slides_copy.length; i2++) {
        slides_copy[i2 - 1] = slides_copy[i2];
      }
      slides_copy.length--;

      // Keep going until we have removed all the slides

    } while (slides_copy.length);

    // Now set the slides to the randomized array
    this.slides = slides_randomized;
  }


  //--------------------------------------------------
  this.get_text = function() {
    // This method returns the text of the current slide

    return(this.slides[ this.current ].text);
  }


  //--------------------------------------------------
  this.get_all_text = function(before_slide, after_slide) {
    // Return the text for all of the slides.
    // For the text of each slide, add "before_slide" in front of the
    // text, and "after_slide" after the text.
    // For example:
    // document.write("<ul>");
    // document.write(s.get_all_text("<li>","\n"));
    // document.write("<\/ul>");

    all_text = "";

    // Loop through all the slides in the slideshow
    for (i=0; i < this.slides.length; i++) {

      slide = this.slides[i];

      if (slide.text) {
        all_text += before_slide + slide.text + after_slide;
      }

    }

    return(all_text);
  }


  //--------------------------------------------------
  this.display_text = function(text) {
    // Display the text for the current slide

    // If the "text" arg was not supplied (usually it isn't),
    // get the text from the slideshow
    if (!text) {
      text = this.slides[ this.current ].text;
    }

    // If a textarea has been specified,
    // then change the text displayed in it
    if (this.textarea && typeof this.textarea.value != 'undefined') {
      this.textarea.value = text;
    }

    // If a text id has been specified,
    // then change the contents of the HTML element
    if (this.textid) {

      r = this.getElementById(this.textid);
      if (!r) { return false; }
      if (typeof r.innerHTML == 'undefined') { return false; }

      // Update the text
      r.innerHTML = text;
    }
  }


  //--------------------------------------------------
  this.hotlink = function() {
    // This method calls the hotlink() method for the current slide.

    this.slides[ this.current ].hotlink();
  }


  //--------------------------------------------------
  this.save_position = function(cookiename) {
    // Saves the position of the slideshow in a cookie,
    // so when you return to this page, the position in the slideshow
    // won't be lost.

    if (!cookiename) {
      cookiename = this.name + '_slideshow';
    }

    document.cookie = cookiename + '=' + this.current;
  }


  //--------------------------------------------------
  this.restore_position = function(cookiename) {
  // If you previously called slideshow_save_position(),
  // returns the slideshow to the previous state.

    //Get cookie code by Shelley Powers

    if (!cookiename) {
      cookiename = this.name + '_slideshow';
    }

    var search = cookiename + "=";

    if (document.cookie.length > 0) {
      offset = document.cookie.indexOf(search);
      // if cookie exists
      if (offset != -1) {
        offset += search.length;
        // set index of beginning of value
        end = document.cookie.indexOf(";", offset);
        // set index of end of cookie value
        if (end == -1) end = document.cookie.length;
        this.current = parseInt(unescape(document.cookie.substring(offset, end)));
        }
     }
  }


  //--------------------------------------------------
  this.noscript = function() {
    // This method is not for use as part of your slideshow,
    // but you can call it to get a plain HTML version of the slideshow
    // images and text.
    // You should copy the HTML and put it within a NOSCRIPT element, to
    // give non-javascript browsers access to your slideshow information.
    // This also ensures that your slideshow text and images are indexed
    // by search engines.

    $html = "\n";

    // Loop through all the slides in the slideshow
    for (i=0; i < this.slides.length; i++) {

      slide = this.slides[i];

      $html += '<P>';

      if (slide.link) {
        $html += '<a href="' + slide.link + '">';
      }

      $html += '<img src="' + slide.src + '" ALT="slideshow image">';

      if (slide.link) {
        $html += "<\/a>";
      }

      if (slide.text) {
        $html += "<BR>\n" + slide.text;
      }

      $html += "<\/P>" + "\n\n";
    }

    // Make the HTML browser-safe
    $html = $html.replace(/\&/g, "&amp;" );
    $html = $html.replace(/</g, "&lt;" );
    $html = $html.replace(/>/g, "&gt;" );

    return('<pre>' + $html + '</pre>');
  }


  //==================================================
  // Private methods
  //==================================================

  //--------------------------------------------------
  this.loop = function() {
    // This method is for internal use only.
    // This method gets called automatically by a JavaScript timeout.
    // It advances to the next slide, then sets the next timeout.
    // If the next slide image has not completed loading yet,
    // then do not advance to the next slide yet.

    // Make sure the next slide image has finished loading
    if (this.current < this.slides.length - 1) {
      next_slide = this.slides[this.current + 1];
      if (next_slide.image.complete == null || next_slide.image.complete) {
        this.next();
      }
    } else { // we're at the last slide
      this.next();
    }

    // Keep playing the slideshow
    this.play( );
  }


  //--------------------------------------------------
  this.valid_image = function() {
    // Returns 1 if a valid image has been set for the slideshow

    if (!this.image)
    {
      return false;
    }
    else {
      return true;
    }
  }

  //--------------------------------------------------
  this.getElementById = function(element_id) {
    // This method returns the element corresponding to the id

    if (document.getElementById) {
      return document.getElementById(element_id);
    }
    else if (document.all) {
      return document.all[element_id];
    }
    else if (document.layers) {
      return document.layers[element_id];
    } else {
      return undefined;
    }
  }


  //==================================================
  // Deprecated methods
  // I don't recommend the use of the following methods,
  // but they are included for backward compatibility.
  // You can delete them if you don't need them.
  //==================================================

  //--------------------------------------------------
  this.set_image = function(imageobject) {
    // This method is deprecated; you should use
    // the following code instead:
    // s.image = document.images.myimagename;
    // s.update();

    if (!document.images)
      return;
    this.image = imageobject;
  }

  //--------------------------------------------------
  this.set_textarea = function(textareaobject) {
    // This method is deprecated; you should use
    // the following code instead:
    // s.textarea = document.form.textareaname;
    // s.update();

    this.textarea = textareaobject;
    this.display_text();
  }

  //--------------------------------------------------
  this.set_textid = function(textidstr) {
    // This method is deprecated; you should use
    // the following code instead:
    // s.textid = "mytextid";
    // s.update();

    this.textid = textidstr;
    this.display_text();
  }
}
/**
 * SWFObject v1.4.2: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2006 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * **SWFObject is the SWF embed script formerly known as FlashObject. The name was changed for
 *   legal reasons.
 */
if(typeof deconcept=="undefined"){var deconcept=new Object();}
if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}
if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}
deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a,_b){
if(!document.getElementById){return;}
this.DETECT_KEY=_b?_b:"detectflash";
this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);
this.params=new Object();
this.variables=new Object();
this.attributes=new Array();
if(_1){this.setAttribute("swf",_1);}
if(id){this.setAttribute("id",id);}
if(w){this.setAttribute("width",w);}
if(h){this.setAttribute("height",h);}
if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}
this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();
if(c){this.addParam("bgcolor",c);}
var q=_8?_8:"high";
this.addParam("quality",q);
this.setAttribute("useExpressInstall",_7);
this.setAttribute("doExpressInstall",false);
var _d=(_9)?_9:window.location;
this.setAttribute("xiRedirectUrl",_d);
this.setAttribute("redirectUrl","");
if(_a){this.setAttribute("redirectUrl",_a);}};
deconcept.SWFObject.prototype={setAttribute:function(_e,_f){
this.attributes[_e]=_f;
},getAttribute:function(_10){
return this.attributes[_10];
},addParam:function(_11,_12){
this.params[_11]=_12;
},getParams:function(){
return this.params;
},addVariable:function(_13,_14){
this.variables[_13]=_14;
},getVariable:function(_15){
return this.variables[_15];
},getVariables:function(){
return this.variables;
},getVariablePairs:function(){
var _16=new Array();
var key;
var _18=this.getVariables();
for(key in _18){_16.push(key+"="+_18[key]);}
return _16;
},getSWFHTML:function(){
var _19="";
if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){
if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");}
_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\"";
_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";
var _1a=this.getParams();
for(var key in _1a){_19+=key+"=\""+_1a[key]+"\" ";}
var _1c=this.getVariablePairs().join("&");
if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}
_19+="/>";
}else{if(this.getAttribute("doExpressInstall")){
this.addVariable("MMplayerType","ActiveX");}
_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\">";
_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";
var _1d=this.getParams();
for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}
var _1f=this.getVariablePairs().join("&");
if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}
_19+="</object>";}
return _19;
},write:function(_20){
if(this.getAttribute("useExpressInstall")){
var _21=new deconcept.PlayerVersion([6,0,65]);
if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){
this.setAttribute("doExpressInstall",true);
this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));
document.title=document.title.slice(0,47)+" - Flash Player Installation";
this.addVariable("MMdoctitle",document.title);}}
if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){
var n=(typeof _20=="string")?document.getElementById(_20):_20;
n.innerHTML=this.getSWFHTML();
return true;
}else{
if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}
return false;}};
deconcept.SWFObjectUtil.getPlayerVersion=function(){
var _23=new deconcept.PlayerVersion([0,0,0]);
if(navigator.plugins&&navigator.mimeTypes.length){
var x=navigator.plugins["Shockwave Flash"];
if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}
}else{
try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}
catch(e){try{
var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
_23=new deconcept.PlayerVersion([6,0,21]);
axo.AllowScriptAccess="always";}
catch(e){
if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}
catch(e){}}
if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}
return _23;};
deconcept.PlayerVersion=function(_27){
this.major=_27[0]!=null?parseInt(_27[0]):0;
this.minor=_27[1]!=null?parseInt(_27[1]):0;
this.rev=_27[2]!=null?parseInt(_27[2]):0;
};
deconcept.PlayerVersion.prototype.versionIsValid=function(fv){
if(this.major<fv.major){return false;}
if(this.major>fv.major){return true;}
if(this.minor<fv.minor){return false;}
if(this.minor>fv.minor){return true;}
if(this.rev<fv.rev){return false;}
return true;
};
deconcept.util={getRequestParameter:function(_29){
var q=document.location.search||document.location.hash;
if(q){
var _2b=q.substring(1).split("&");
for(var i=0;i<_2b.length;i++){
if(_2b[i].substring(0,_2b[i].indexOf("="))==_29){
return _2b[i].substring((_2b[i].indexOf("=")+1));}}}
return "";}};
deconcept.SWFObjectUtil.cleanupSWFs=function(){
var _2d=document.getElementsByTagName("OBJECT");
for(var i=0;i<_2d.length;i++){
_2d[i].style.display="none";
for(var x in _2d[i]){if(typeof _2d[i][x]=="function"){_2d[i][x]=null;}}}};
if(typeof window.onunload=="function"){
var oldunload=window.onunload;
window.onunload=function(){
deconcept.SWFObjectUtil.cleanupSWFs();
oldunload();};
}else{window.onunload=deconcept.SWFObjectUtil.cleanupSWFs;}
if(Array.prototype.push==null){
Array.prototype.push=function(_30){
this[this.length]=_30;
return this.length;};}

var getQueryParamValue=deconcept.util.getRequestParameter;
var FlashObject=deconcept.SWFObject; // for legacy support
var SWFObject=deconcept.SWFObject;
/***************************************************/
/************** BEGIN AJAX FUNCTIONS ***************/
/***************************************************/
function dbpull(strURL, strSubmit, formName) {
	xmlhttpPost(strURL, strSubmit, "UpdateAJAX", formName);
}

/**
 * Handles special requirements for Inventory Searching
 */
function searchPull(strURL, strSubmit, formName) {
	dbpull(strURL, strSubmit, formName);
}

function searchAllow(docForm) {
	var selects = docForm.getElementsByTagName("select");
	var inputs = docForm.getElementsByTagName("input");

	for (var i=0;i<selects.length;i++) {
		if (selects[i].name=='type'|| selects[i].name=='invSearch_type') {selects[i].disabled = false;}
		else if (selects[i].multiple!=true || selects[i].name=='trim[]') {
			if (selects[i].length>1) {selects[i].disabled=false;}
//			if (docForm.type.value!='' && selects[i].length>1) {selects[i].disabled=false;}
			else {selects[i].disabled=true;}
		}
	}
	changeSearchSubmit(docForm, inputs);
}

function changeSearchSubmit(searchForm, inputs) {
	var searchStock = (searchForm.stock != null) ? 1 : 0;
	var searchType = 0;
	if (searchForm.type!=null) {
		if (searchForm.type.value!='') {searchType=1;}
	}else if (searchForm.invSearch_type!=null) {
		if (searchForm.invSearch_type.value!='') {searchType=1;}
	}

	for (i=0;i<inputs.length;i++) {
		if (inputs[i].name=='Search' || inputs[i].name=='All') {
			//if (searchType || searchStock) {inputs[i].disabled=false;}
			//if (searchForm.invSearch_type.value == '') {searchForm.invSearch_stock.disabled = false;}
			if (searchType || searchStock) {
				inputs[i].disabled=false;
				//if (searchForm.invSearch_type.value != '') {searchForm.invSearch_stock.disabled = true;}
			}
			else {inputs[i].disabled=true;}
		}
	}
}

//initiates the XMLHttpRequest object
function xmlhttpPost(strURL, strSubmit, strResultFunc, formName) {
	ShowLoading();
	var xmlHttpReq = false;

    // Mozilla/Safari
    if (window.XMLHttpRequest) {
            xmlHttpReq = new XMLHttpRequest();
            if (xmlHttpReq.overrideMimeType) xmlHttpReq.overrideMimeType('text/xml');
    }
    // IE
    else if (window.ActiveXObject) {
            xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }

  xmlHttpReq.open('POST', strURL+"?"+strSubmit, true);
        xmlHttpReq.setRequestHeader('Content-Type',
                     'application/x-www-form-urlencoded');
        xmlHttpReq.onreadystatechange = function() {
        		if (xmlHttpReq.readyState == 4) {
        			if (strResultFunc != ''){
                		eval(strResultFunc + '(xmlHttpReq.responseXML, formName);');
        			}
                }
        }
        xmlHttpReq.send(strSubmit);
}

function getRequest() {
    var xmlhttp=false;
    /*@cc_on @*/
    /*@if (@_jscript_version >= 5)
    // JScript gives us Conditional compilation, we can cope with old IE versions.
    // and security blocked creation of the objects.
     try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (e) {
      try {
       xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
       xmlhttp = false;
      }
     }
    @end @*/
    if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
        try {
            xmlhttp = new XMLHttpRequest();
        } catch (e) {
            xmlhttp=false;
        }
    }
    if (!xmlhttp && window.createRequest) {
        try {
            xmlhttp = window.createRequest();
        } catch (e) {
            xmlhttp=false;
        }
    }

    return xmlhttp;
}

/**
 * Function called after requested xml has been received, to update the page
 */
function UpdateAJAX(xmlObj, formName){
	if (xmlObj){
//		console.log(xmlObj);
//		alert("THERE IS AN XML OBJECT: "+xmlObj);
		if (xmlObj.documentElement){
//			alert("THERE IS AN XML OBJECT DOC ELEMENT");
			if(xmlObj.hasChildNodes()) {
//				alert("THERE ARE CHILD NODES");
				for (var i=0; i<xmlObj.childNodes.length;i++) {
					var tree = xmlObj.childNodes[i];
					if(tree.hasChildNodes()) {
						if (tree.getAttribute('newAction')) {
							formName.action = tree.getAttribute('newAction');
						}
						for (var j = 0; j < tree.childNodes.length; j++){
							var child = tree.childNodes[j];
							setFormObject(child, formName);
						}
					}
				}
			}
		}
//		else
//			alert("You are inferior.");
	}
//	else
//		alert("No XML Obj!");
	HideLoading();
}

/**
 * Change the form object with requested information from the xmlItem
 */
function setFormObject(xmlItem, docForm){
	var itemName = xmlItem.nodeName;
	if (!docForm) var docForm = document.editForm;
	var obj = '';

	//Search all Input tags
	var items = docForm.getElementsByTagName("input");
	for (var i = 0; i < items.length && obj == ''; i++){
		if (items[i].name == itemName){
			obj = items[i];
		}
	}
	if (obj != ''){
		obj.value = xmlItem.getAttribute('value');
		return;
	}

	//Search all Text Area tags
	items = docForm.getElementsByTagName("textarea");
	for (var i = 0; i < items.length && obj == ''; i++){
		if (items[i].name == itemName){
			obj = items[i];
		}
	}
	if (obj != ''){
		obj.value = xmlItem.getAttribute('value');
		return;
	}

	//Search all Select tags
	items = docForm.getElementsByTagName("select");
	for (var i = 0; i < items.length && obj == ''; i++){
		//Check for multiple selects too
		if ((items[i].name == itemName) || (items[i].name == itemName+'[]')){
			obj = items[i];
		}
	}
	if (obj){
		if (xmlItem.hasChildNodes()){
			while(obj.hasChildNodes()){
				obj.removeChild(obj.firstChild);
			}
			for (var k = 0; k < xmlItem.childNodes.length; k++){
				var child = xmlItem.childNodes[k];
				var shouldSelect = 0;
				if (child.getAttribute('selected')=='true') shouldSelect = 1;
				appendSelect(obj, child.getAttribute('value'), ((child.getAttribute('text')) ? child.getAttribute('text') : " "), shouldSelect);
			}
			// ENABLE SEARCH BUTTONS AND STORE SEARCH (IF AVAILABLE) IF TYPE CHANGES //
			searchAllow(docForm);
		}
		else{
			obj.value = xmlItem.getAttribute('value');
		}
		return;
	}
}

/**
 * Function to display the loading image
 */
function ShowLoading(){
	var key = document.getElementById("loading");
	if (key) key.style.display = "block";
}

/**
 * Function to hide the loading image
 */
function HideLoading(){
	var key = document.getElementById("loading");
	if (key) key.style.display = "none";
}



/* NOT FINISHED - CUYRRENTLY UNUSED */
function ajax_select_selectbox_update(sbox, domain, filters, valueField, displayField){
	 var request = getRequest();
	request.onreadystatechange=function()
    {
    if(request.readyState==4)
      {
      	var response = request.responseXML;
      	alert("here");
      	if (xmlObj){
			if (xmlObj.documentElement){
				if(xmlObj.hasChildNodes()) {
					for (var i=0; i<xmlObj.childNodes.length;i++) {
						var tree = xmlObj.childNodes[i];
						alert(tree);
						if(tree.hasChildNodes()) {
							/*
							for (var j = 0; j < tree.childNodes.length; j++){
								var child = tree.childNodes[j];
								for (var i = 0; i < items.length && obj == ''; i++){

								}
							}
							*/
						}
					}
				}
			}
		}
      }
    }
    request.open('get', '?cmd=Ajaxselect&domain='+domain+'&filters='+filters, true);
    request.send(null);
}


/***************************************************/
/*************** END AJAX FUNCTIONS ****************/
/***************************************************/
// GENERIC FUNCTIONS //
Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};

String.prototype.ucwords = function(){ //v1.0
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};

// CREATE A NEW OPTION BASED OFF VAL AND DISP AND APPEND IT TO SUPPLIED SELECT BOX //
function appendSelect(specialSelect, val, disp, doSelect) {
	var elOptNew = document.createElement('option');
	elOptNew.appendChild(document.createTextNode(disp));
	elOptNew.setAttribute('value', val);

	specialSelect.appendChild(elOptNew);
	if (doSelect) elOptNew.selected = "selected";
}

// REMOVE SELECTIONS FROM A SELECT BOX //
function removeSelected(selectID) {
	var selectBox = document.getElementById(selectID);
	var selected = selectBox.selectedIndex;

	// CREATE TEMP ARRAYS //
	var updatedInfo = new Array();
	var removed = new Array();

	var j=0;
	var k=0;
	for (var i=0;i<selectBox.length;i++) {
		if (!selectBox[i].selected) {
			updatedInfo.push(new Array(selectBox[i].value, selectBox[i].text));
		}else {
			removed.push(selectBox[i].value);
		}
	}

	// UPDATE THE SELECTBOX WITH THE REMAINING INFORMATION //
	selectBox.length = updatedInfo.length;
	for (i=0;i<updatedInfo.length;i++) {
		selectBox[i].value = updatedInfo[i][0];
		selectBox[i].text = updatedInfo[i][1];
		selectBox[i].selected = false;
	}

	return removed;
}

// REMOVE THE HIDDEN INPUT ELEMENT THAT MATCHES THOSE IN THE SUPPLIED REMOVEARR //
function removeHiddenInputs(removeArr, hiddenName) {
	// GET A LIST OF HIDDEN INPUTS THAT MATCH THE NAME SUPPLIED //
	if (hiddenName!=null) {var hiddenInputs = document.getElementsByName(hiddenName);}
	else {
		var formInputs = document.getElementsByTagName("input");
		var hiddenInputs = new Array();
		if (formInputs!=null) {
			for (var i=0;i<formInputs.length;i++) {
				if (formInputs[i].type=="hidden") {
					hiddenInputs.push(formInputs[i]);
				}
			}
		}
	}
	if (hiddenInputs!=null) {
		for (var i=0;i<hiddenInputs.length;i++) {
			for (var j in removeArr) {
				if (hiddenInputs[i].value == removeArr[j]) {
					hiddenInputs[i].parentNode.removeChild(hiddenInputs[i]);
				}
			}
		}
	}
}

// indexOf isn't globally used atm, so i created an InArray //
function InArray(haystack, needle) {
	for (var i=0;i<haystack.length;i++) {
		if (needle == haystack[i]) return true;
	}
	return false;
}

/**
 * Generic function to clear a form of all values, except a supplied array of field names (if applicable)
 */
function clearForm(objForm, saveFields) {
	if(objForm.elements[0]!=null) {
		var i;
		var max = objForm.length;
		if (saveFields == null) {saveFields = new Array();}

		for( i = 0; i < max; i++ ) {
//			if( objForm.elements[ i ].type != "submit" && saveFields.indexOf(objForm.elements[ i ].name)) {
			if( objForm.elements[ i ].type != "submit" && objForm.elements[ i ].type != "hidden" && !InArray(saveFields, objForm.elements[ i ].name)) {
				objForm.elements[ i ].value='';
			}
		}
	}
}

// -----------------------------------------------------------------------------------

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.com
// Edit for Firefox by pHaez
//
function getPageSize(){

	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth;
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}

//	console.log("xScroll " + xScroll)
//	console.log("windowWidth " + windowWidth)

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = xScroll;
	} else {
		pageWidth = windowWidth;
	}
//	console.log("pageWidth " + pageWidth)

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
	return arrayPageSize;
}

// -----------------------------------------------------------------------------------

//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.com
//
function getPageScroll(){

	var xScroll, yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;
	}

	arrayPageScroll = new Array(xScroll,yScroll)
	return arrayPageScroll;
}

// ---------------------------------------------------

function showFlash(){
	var flashObjects = document.getElementsByTagName("object");
	for (i = 0; i < flashObjects.length; i++) {
		flashObjects[i].style.visibility = "visible";
	}

	var flashEmbeds = document.getElementsByTagName("embed");
	for (i = 0; i < flashEmbeds.length; i++) {
		flashEmbeds[i].style.visibility = "visible";
	}
}

// ---------------------------------------------------

function hideFlash(){
	var flashObjects = document.getElementsByTagName("object");
	for (i = 0; i < flashObjects.length; i++) {
		flashObjects[i].style.visibility = "hidden";
	}

	var flashEmbeds = document.getElementsByTagName("embed");
	for (i = 0; i < flashEmbeds.length; i++) {
		flashEmbeds[i].style.visibility = "hidden";
	}

}

function ShowSelects(show){
	var sels = document.getElementsByTagName("select");
	for (var i = 0; i < sels.length; i++){
		if (show == 0){
			sels[i].style.visibility ='hidden';
		} else {
			sels[i].style.visibility ='visible';
		}
	}
}

function twirly(itemName, image, tclass, iclass)
{
	var item = document.getElementById(itemName);
	if (item.className == tclass){
		item.className = tclass+"Hidden";
		image.className = iclass+"Hidden";
	} else {
		item.className = tclass;
		image.className = iclass;
	}
}
var weekend = [0,6];

var gNow = new Date();
var ggWinContent;
var ggNavContent;
var ggPosX = -1;
var ggPosY = -1;

Calendar.Months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];

// Non-Leap year Month days..
Calendar.DOMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// Leap year Month days..
Calendar.lDOMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

function Calendar(p_item, p_number, p_month, p_year, p_format) {
	if ((p_month == null) && (p_year == null))	return;

	if (p_month == null) {
		this.gMonthName = null;
		this.gMonth = null;
		this.gYearly = true;
	} else {
		this.gMonthName = Calendar.get_month(p_month);
		this.gMonth = new Number(p_month);
		this.gYearly = false;
	}

	this.gYear = p_year;

	this.gFormat = p_format;
	this.gBGColor = "white";
	this.gFGColor = "black";
	this.gTextColor = "black";
	this.gHeaderColor = "black";
	this.gReturnItem = p_item;
	this.gReturnNumber = p_number;

	this.gReturnMonth = p_item+"Month";
	this.gReturnDay = p_item+"Day";
	this.gReturnYear = p_item+"Year";

	if (p_number!="") {
		this.gReturnMonth += "_"+p_number;
		this.gReturnDay += "_"+p_number;
		this.gReturnYear += "_"+p_number;
	}
}

Calendar.get_month = Calendar_get_month;
Calendar.get_daysofmonth = Calendar_get_daysofmonth;
Calendar.calc_month_year = Calendar_calc_month_year;

function Calendar_get_month(monthNo) {
	return Calendar.Months[monthNo];
}

function Calendar_get_daysofmonth(monthNo, p_year) {
	/*
	Check for leap year ..
	1.Years evenly divisible by four are normally leap years, except for...
	2.Years also evenly divisible by 100 are not leap years, except for...
	3.Years also evenly divisible by 400 are leap years.
	*/
	if ((p_year % 4) == 0) {
		if ((p_year % 100) == 0 && (p_year % 400) != 0)
			return Calendar.DOMonth[monthNo];

		return Calendar.lDOMonth[monthNo];
	} else
		return Calendar.DOMonth[monthNo];
}

function Calendar_calc_month_year(p_Month, p_Year, incr) {
	/*
	Will return an 1-D array with 1st element being the calculated month
	and second being the calculated year
	after applying the month increment/decrement as specified by 'incr' parameter.
	'incr' will normally have 1/-1 to navigate thru the months.
	*/
	var ret_arr = new Array();

	if (incr == -1) {
		// B A C K W A R D
		if (p_Month == 0) {
			ret_arr[0] = 11;
			ret_arr[1] = parseInt(p_Year) - 1;
		}
		else {
			ret_arr[0] = parseInt(p_Month) - 1;
			ret_arr[1] = parseInt(p_Year);
		}
	} else if (incr == 1) {
		// F O R W A R D
		if (p_Month == 11) {
			ret_arr[0] = 0;
			ret_arr[1] = parseInt(p_Year) + 1;
		}
		else {
			ret_arr[0] = parseInt(p_Month) + 1;
			ret_arr[1] = parseInt(p_Year);
		}
	}

	return ret_arr;
}

// This is for compatibility with Navigator 3, we have to create and discard one object before the prototype object exists.
new Calendar();

Calendar.prototype.getMonthlyCalendarCode = function() {
	var vCode = "";
	var vHeader_Code = "";
	var vData_Code = "";

	// Begin Table Drawing code here..
	vCode += ("<div id=\"jsCalDisplay\"><table cellspacing=\"0\" cellpadding=\"0\">");

	vHeader_Code = this.cal_header();
	vData_Code = this.cal_data();
	vCode += (vHeader_Code + vData_Code);

	vCode += "</div></div>";

	return vCode;
}

Calendar.prototype.show = function() {
	var vCode = "";

	// build content into global var ggWinContent
	ggWinContent += ("<div class=\"jsCalCurrentMonth\">");
	ggWinContent += (this.gMonthName + " " + this.gYear);
	ggWinContent += ("</div>");

	// Show navigation buttons
	var prevMMYYYY = Calendar.calc_month_year(this.gMonth, this.gYear, -1);
	var prevMM = prevMMYYYY[0];
	var prevYYYY = prevMMYYYY[1];

	var nextMMYYYY = Calendar.calc_month_year(this.gMonth, this.gYear, 1);
	var nextMM = nextMMYYYY[0];
	var nextYYYY = nextMMYYYY[1];

	// Get the complete calendar code for the month, and add it to the
	//	content var
	vCode = this.getMonthlyCalendarCode();
	ggWinContent += vCode;

	ggNavContent = "";
	this.cal_nav(prevMM, prevYYYY, nextMM, nextYYYY);
}

Calendar.prototype.cal_nav = function (prevMonth, prevYear, nextMonth, nextYear) {
	ggNavContent += ("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\"><tr>");
	ggNavContent += ("<td><span class=\"jsCalPrev\" " +
		"onclick=\"Build(" +
		"'" + this.gReturnItem + "', '" + this.gReturnNumber + "', '" + this.gMonth + "', '" + (parseInt(this.gYear)-1) + "', '" + this.gFormat + "'" +
		");" +
		"\">&nbsp;</span>");
	ggNavContent += ("<span class=\"jsCalNext\" " +
		"onclick=\"Build(" +
		"'" + this.gReturnItem + "', '"  + this.gReturnNumber + "', '" + this.gMonth + "', '" + (parseInt(this.gYear)+1) + "', '" + this.gFormat + "'" +
		");" +
		"\">&nbsp;</span>");
	ggNavContent += ("<span>Year</span>");
	ggNavContent += ("<div class=\"clearer\">&nbsp;</div>");
	ggNavContent += ("</td>");
	ggNavContent += ("<td><span class=\"jsCalPrev\" " +
		"onclick=\"Build(" +
		"'" + this.gReturnItem + "', '"  + this.gReturnNumber + "', '" + prevMonth + "', '" + prevYear + "', '" + this.gFormat + "'" +
		");" +
		"\">&nbsp;</span>");
	ggNavContent += ("<span class=\"jsCalNext\" " +
		"onclick=\"Build(" +
		"'" + this.gReturnItem + "', '"  + this.gReturnNumber + "', '" + nextMonth + "', '" + nextYear + "', '" + this.gFormat + "'" +
		");" +
		"\">&nbsp;</span>");
	ggNavContent += ("<span>Month</span>");
	ggNavContent += ("<div class=\"clearer\">&nbsp;</div>");
	ggNavContent += ("</td>");
	ggNavContent += ("</tr></table>");
}

Calendar.prototype.cal_header = function() {
	var vCode = "";

	vCode = vCode + "<tr>";
	vCode = vCode + "<th>Sun</th>";
	vCode = vCode + "<th>Mon</th>";
	vCode = vCode + "<th>Tue</th>";
	vCode = vCode + "<th>Wed</th>";
	vCode = vCode + "<th>Thu</th>";
	vCode = vCode + "<th>Fri</th>";
	vCode = vCode + "<th>Sat</th>";
	vCode = vCode + "</tr>";

	return vCode;
}

Calendar.prototype.cal_data = function() {
	var vDate = new Date();
	vDate.setDate(1);
	vDate.setMonth(this.gMonth);
	vDate.setFullYear(this.gYear);

	var vFirstDay=vDate.getDay();
	var vDay=1;
	var vLastDay=Calendar.get_daysofmonth(this.gMonth, this.gYear);
	var vOnLastDay=0;
	var vCode = "";

	/*
	Get day for the 1st of the requested month/year..
	Place as many blank cells before the 1st day of the month as necessary.
	*/
	vCode = vCode + "<tr>";
	for (i=0; i<vFirstDay; i++) {
		vCode += "<td " + this.write_weekend_string(i) + "></td>";
	}

	// Write rest of the 1st week
	for (j=vFirstDay; j<7; j++) {
		vCode = vCode + "<td " + this.write_weekend_string(j) +
				"onclick=\"setDateForm(document." + this.gReturnMonth + ", document." + this.gReturnDay + ", document." + this.gReturnYear + ", '"
				+ this.format_data(vDay, "D")+"', '" + this.format_data(vDay, "M")+"', '" + this.format_data(vDay, "YYYY")+"');"
				+ "cClick();ggPosX=-1;ggPosY=-1;\">" +
				this.format_day(vDay) +
			"</td>";
		vDay++;
	}
	vCode += "</tr>";

	// Write the rest of the weeks
	for (k=2; k<7; k++) {
		vCode += "<tr>";

		for (j=0; j<7; j++) {
			vCode = vCode + "<td " + this.write_weekend_string(j) +
				"onclick=\"setDateForm(document." + this.gReturnMonth + ", document." + this.gReturnDay + ", document." + this.gReturnYear + ", '"
				+ this.format_data(vDay, "D")+"', '" + this.format_data(vDay, "M")+"', '" + this.format_data(vDay, "YYYY")+"');"
				+ "cClick();ggPosX=-1;ggPosY=-1;\">" +
				this.format_day(vDay) +
				"</td>";
			vDay++;

			if (vDay > vLastDay) {
				vOnLastDay = 1;
				break;
			}
		}

		if (j == 6)
			vCode = vCode + "</tr>";
		if (vOnLastDay == 1)
			break;
	}

	// Fill up the rest of last week with proper blanks, so that we get proper square blocks
	for (m=1; m<(7-j); m++) {
		vCode += "<td " + this.write_weekend_string(j+m) + " style=\"color: gray;\">";
		if (!this.gYearly)
			vCode += m;
		vCode += "</td>";
	}

	return vCode;
}
function setDateForm(monthField, dayField, yearField, day, month, year) {
	monthField.value = month;
	dayField.value = day;
	yearField.value = year;
	if (monthField.onchange) monthField.onchange();
	if (dayField.onchange) dayField.onchange();
	if (yearField.onchange) yearField.onchange();
}

Calendar.prototype.format_day = function(vday) {
	var vNowDay = gNow.getDate();
	var vNowMonth = gNow.getMonth();
	var vNowYear = gNow.getFullYear();

	if (vday == vNowDay && this.gMonth == vNowMonth && this.gYear == vNowYear)
		return ("<span class=\"jsCalCurDay\">" + vday + "</span>");
	else
		return (vday);
}

Calendar.prototype.write_weekend_string = function(vday) {
	var i;

	// Return special formatting for the weekend day.
	for (i=0; i<weekend.length; i++) {
		if (vday == weekend[i])
			return ("class=\"jsCalWeekend\"");
	}
	return ("class=\"jsCalWeekday\"");
}

Calendar.prototype.format_data = function(p_day, format) {
	var vData;
	var vMonth = 1 + this.gMonth;
	vM = vMonth;
	vMonth = (vMonth.toString().length < 2) ? "0" + vMonth : vMonth;

	var vY4 = new String(this.gYear);
	var vDD = (p_day.toString().length < 2) ? "0" + p_day : p_day;
	var vD = p_day;
	switch (format) {
		case "DD":
			vData = vDD;
			break;
		case "D":
			vData = vD;
			break;
		case "MM":
			vData = vMonth;
			break;
		case "M":
			vData = vM;
			break;
		case "YYYY":
			vData = vY4;
			break;
		case "YYYY-MM-DD" :
			vData = vY4 + "-" + vMonth + "-" + vDD;
			break;
		default :
			vData = vMonth + "/" + vDD + "/" + vY4;
	}

	return vData;
}

function Build(p_item, p_number, p_month, p_year, p_format) {
	gCal = new Calendar(p_item, p_number, p_month, p_year, p_format);

	// Customize your Calendar here..
	gCal.gBGColor="white";
	gCal.gLinkColor="black";
	gCal.gTextColor="black";
	gCal.gHeaderColor="darkgreen";

	// initialize the content string
	ggWinContent = "";

	gCal.show();
	// if this is the first calendar popup, use autopositioning with an offset
	if (ggPosX == -1 && ggPosY == -1) {
		overlib(ggWinContent, AUTOSTATUSCAP, STICKY, CLOSECLICK, CSSSTYLE,
			CAPTION, ggNavContent, OFFSETX, 20, OFFSETY, -20);
		// save where the 'over' div ended up; we want to stay in the same place if the user
		//	clicks on one of the year or month navigation links
		if ( (ns4) || (ie4) ) {
		 	ggPosX = parseInt(over.left);
	        ggPosY = parseInt(over.top);
		} else if (ns6) {
			ggPosX = parseInt(over.style.left);
			ggPosY = parseInt(over.style.top);
		}
	}
	else {
		// we have a saved X & Y position, so use those with the FIXX and FIXY options
		overlib(ggWinContent, AUTOSTATUSCAP, STICKY, CLOSECLICK, CSSSTYLE,
			CAPTION, ggNavContent, FIXX, ggPosX, FIXY, ggPosY);
	}
	if (ie5) enableAlphaImages();
}

function show_calendar() {
	/*
		p_month : 0-11 for Jan-Dec; 12 for All Months.
		p_year	: 4-digit year
		p_format: Date format (mm/dd/yyyy, dd/mm/yy, ...)
		p_item	: Return Item.
	*/

	p_item = arguments[0];
	p_number = arguments[1];

	// SET DATE FROM FORM IF IT EXISTS //
	var itemArray = explodeArray(p_item, '.');
	var formMonth = itemArray[1]+'Month';
	var formDay = itemArray[1]+'Day';
	var formYear = itemArray[1]+'Year';
	// ADD IDENTIFIER TO END OF FORM ELEMENTS IF IT EXISTS //
	if (p_number!="") {
		formMonth += "_"+p_number;
		formDay += "_"+p_number;
		formYear += "_"+p_number;
	}
	var formDate = document.getElementsByName(formDay);
	if (formDate[0].value != null && formDate[0].value!='') {
		gNow.setDate(formDate[0].value);
	}
	// SET MONTH FROM FORM IF IT EXISTS, ELSE THIS MONTH //
	formDate = document.getElementsByName(formMonth);
	if (formDate[0].value != null && formDate[0].value!='') {
		p_month = formDate[0].value-1;
		gNow.setMonth(formDate[0].value-1);
	} else {
		p_month = new String(gNow.getMonth());
	}
	// SET YEAR FROM FORM IF IT EXISTS, ELSE THIS YEAR //
	formDate = document.getElementsByName(formYear);
	if (formDate[0].value != null && formDate[0].value!='') {
		p_year = formDate[0].value;
		gNow.setYear(formDate[0].value);
	} else {
		p_year = new String(gNow.getFullYear().toString());
	}
	if (arguments[4] == null)
		p_format = "YYYY-MM-DD";
	else
		p_format = arguments[4];

	Build(p_item, p_number, p_month, p_year, p_format);
}

function explodeArray(item,delimiter) {
  tempArray=new Array(1);
  var Count=0;
  var tempString=new String(item);

  while (tempString.indexOf(delimiter)>0) {
    tempArray[Count]=tempString.substr(0,tempString.indexOf(delimiter));
    tempString=tempString.substr(tempString.indexOf(delimiter)+1,tempString.length-tempString.indexOf(delimiter)+1);
    Count=Count+1
  }

  tempArray[Count]=tempString;
  return tempArray;
}
//\//////////////////////////////////////////////////////////////////////////////////
//\  overLIB 3.50  --  This notice must remain untouched at all times.
//\  Copyright Erik Bosrup 1998-2001. All rights reserved.
//\  THIS IS A VERY MODIFIED VERSION. DO NOT EDIT OR PUBLISH. GET THE ORIGINAL!

/* THIS IS THE VARIABLE CONFIGURATION FILE FOR THE DIV CONTAINING THE CALENDAR */
var STICKY=1;
var CAPTION=2;
var OFFSETX=3;
var OFFSETY=4;
var AUTOSTATUSCAP=5;
var FIXX=6;
var FIXY=7;
var CLOSECLICK=8;
var CSSSTYLE=9;
if(typeof ol_width=='undefined'){var ol_width="200";}
if(typeof ol_offsetx=='undefined'){var ol_offsetx=10;}
if(typeof ol_offsety=='undefined'){var ol_offsety=10;}
if(typeof ol_text=='undefined'){var ol_text="Default Text";}
if(typeof ol_cap=='undefined'){var ol_cap="";}
if(typeof ol_sticky=='undefined'){var ol_sticky=0;}
if(typeof ol_background=='undefined'){var ol_background="";}
if(typeof ol_close=='undefined'){var ol_close="&nbsp;";}
if(typeof ol_hpos=='undefined'){var ol_hpos=8;}
if(typeof ol_status=='undefined'){var ol_status="";}
if(typeof ol_autostatus=='undefined'){var ol_autostatus=0;}
if(typeof ol_height=='undefined'){var ol_height=-1;}
if(typeof ol_snapx=='undefined'){var ol_snapx=0;}
if(typeof ol_snapy=='undefined'){var ol_snapy=0;}
if(typeof ol_fixx=='undefined'){var ol_fixx=-1;}
if(typeof ol_fixy=='undefined'){var ol_fixy=-1;}
if(typeof ol_fgbackground=='undefined'){var ol_fgbackground="";}
if(typeof ol_bgbackground=='undefined'){var ol_bgbackground="";}
if(typeof ol_padxl=='undefined'){var ol_padxl=1;}
if(typeof ol_padxr=='undefined'){var ol_padxr=1;}
if(typeof ol_padyt=='undefined'){var ol_padyt=1;}
if(typeof ol_padyb=='undefined'){var ol_padyb=1;}
if(typeof ol_fullhtml=='undefined'){var ol_fullhtml=0;}
if(typeof ol_vpos=='undefined'){var ol_vpos=36;}
if(typeof ol_aboveheight=='undefined'){var ol_aboveheight=0;}
if(typeof ol_caption=='undefined'){var ol_capicon="";}
if(typeof ol_frame=='undefined'){var ol_frame=self;}
if(typeof ol_timeout=='undefined'){var ol_timeout=0;}
if(typeof ol_function=='undefined'){var ol_function=Function();}
if(typeof ol_delay=='undefined'){var ol_delay=0;}
if(typeof ol_hauto=='undefined'){var ol_hauto=0;}
if(typeof ol_vauto=='undefined'){var ol_vauto=0;}
if(typeof ol_closeclick=='undefined'){var ol_closeclick=0;}
if(typeof ol_css=='undefined'){var ol_css=51;}
if(typeof ol_fgclass=='undefined'){var ol_fgclass="";}
if(typeof ol_bgclass=='undefined'){var ol_bgclass="";}
if(typeof ol_textfontclass=='undefined'){var ol_textfontclass="";}
if(typeof ol_captionfontclass=='undefined'){var ol_captionfontclass="";}
if(typeof ol_closefontclass=='undefined'){var ol_closefontclass="";}
if(typeof ol_padunit=='undefined'){var ol_padunit="px";}
if(typeof ol_heightunit=='undefined'){var ol_heightunit="px";}
if(typeof ol_widthunit=='undefined'){var ol_widthunit="px";}
if(typeof ol_textsizeunit=='undefined'){var ol_textsizeunit="px";}
if(typeof ol_textdecoration=='undefined'){var ol_textdecoration="none";}
if(typeof ol_textstyle=='undefined'){var ol_textstyle="normal";}
if(typeof ol_textweight=='undefined'){var ol_textweight="normal";}
if(typeof ol_captionsizeunit=='undefined'){var ol_captionsizeunit="px";}
if(typeof ol_captiondecoration=='undefined'){var ol_captiondecoration="none";}
if(typeof ol_captionstyle=='undefined'){var ol_captionstyle="normal";}
if(typeof ol_captionweight=='undefined'){var ol_captionweight="bold";}
if(typeof ol_closesizeunit=='undefined'){var ol_closesizeunit="px";}
if(typeof ol_closedecoration=='undefined'){var ol_closedecoration="none";}
if(typeof ol_closestyle=='undefined'){var ol_closestyle="normal";}
if(typeof ol_closeweight=='undefined'){var ol_closeweight="normal";}
if(typeof ol_texts=='undefined'){var ol_texts=new Array("Text 0", "Text 1");}
if(typeof ol_caps=='undefined'){var ol_caps=new Array("Caption 0", "Caption 1");}
var otext="";
var ocap="";
var osticky=0;
var obackground="";
var oclose="Close";
var ohpos=8;
var ooffsetx=2;
var ooffsety=2;
var ofgcolor="";
var obgcolor="";
var otextcolor="";
var ocapcolor="";
var oclosecolor="";
var owidth=100;
var ostatus="";
var oautostatus=0;
var oheight=-1;
var osnapx=0;
var osnapy=0;
var ofixx=-1;
var ofixy=-1;
var ofgbackground="";
var obgbackground="";
var opadxl=0;
var opadxr=0;
var opadyt=0;
var opadyb=0;
var ofullhtml=0;
var ovpos=36;
var oaboveheight=0;
var ocapicon="";
var oframe=self;
var otimeout=0;
var otimerid=0;
var oallowmove=0;
var ofunction=Function();
var odelay=0;
var odelayid=0;
var ohauto=0;
var ovauto=0;
var ocloseclick=0;
var ocss=51;
var ox=0;
var oy=0;
var oallow=0;
var oshowingsticky=0;
var oremovecounter=0;
var over=null;
var ns4=(document.layers)? true:false;
var ns6=(document.getElementById)? true:false;
var ie4=(document.all)? true:false;
var ie5=false;
var ie7=false;
if(ie4){
if((navigator.userAgent.indexOf('MSIE 5')> 0)||(navigator.userAgent.indexOf('MSIE 6')> 0)){
ie5=true;
}
if((navigator.userAgent.indexOf('MSIE 7')> 0)){
ie7=true;
}
if(ns6){
ns6=false;
}
}
if((ns4)||(ie4)||(ns6)){
document.onmousemove=mouseMove
if(ns4)document.captureEvents(Event.MOUSEMOVE)
}else{
overlib=no_overlib;
nd=no_overlib;
ver3fix=true;
}
function no_overlib(){
	return ver3fix;
}
function overlib(){
	otext=ol_text;
	ocap=ol_cap;
	osticky=ol_sticky;
	oclose=ol_close;
	ohpos=ol_hpos;
	ooffsetx=ol_offsetx;
	ooffsety=ol_offsety;
	owidth=ol_width;
	ostatus=ol_status;
	oautostatus=ol_autostatus;
	oheight=ol_height;
	osnapx=ol_snapx;
	osnapy=ol_snapy;
	ofixx=ol_fixx;
	ofixy=ol_fixy;
	opadxl=ol_padxl;
	opadxr=ol_padxr;
	opadyt=ol_padyt;
	opadyb=ol_padyb;
	ofullhtml=ol_fullhtml;
	ovpos=ol_vpos;
	oaboveheight=ol_aboveheight;
	ocapicon=ol_capicon;
	otimeout=ol_timeout;
	ofunction=ol_function;
	odelay=ol_delay;
	ohauto=ol_hauto;
	ovauto=ol_vauto;
	ocloseclick=ol_closeclick;
	ocss=ol_css;
	ofgclass=ol_fgclass;
	obgclass=ol_bgclass;
	opadunit=ol_padunit;
	oheightunit=ol_heightunit;
	owidthunit=ol_widthunit;
	oclosesizeunit=ol_closesizeunit;
	oclosedecoration=ol_closedecoration;
	oclosestyle=ol_closestyle;
	ocloseweight=ol_closeweight;
	if((ns4)||(ie4)||(ns6)){
		oframe=ol_frame;
		if(ns4)over=oframe.document.jsCal
		if(ie4)over=oframe.jsCal.style
		if(ns6)over=oframe.document.getElementById("jsCal");
	}
	var c=-1;
	var ar=arguments;
	for(i=0;i < ar.length;i++){
		if(c < 0){
			if(ar[i]==1){
				otext=ol_texts[ar[++i]];
			}else{
				otext=ar[i];
			}
			c=0;
		}else{
			if(ar[i]==STICKY){osticky=1;continue;}
			if(ar[i]==CAPTION){ocap=ar[++i];continue;}
			if(ar[i]==OFFSETX){ooffsetx=ar[++i];continue;}
			if(ar[i]==OFFSETY){ooffsety=ar[++i];continue;}
			if(ar[i]==AUTOSTATUSCAP){oautostatus=2;continue;}
			if(ar[i]==FIXX){ofixx=ar[++i];continue;}
			if(ar[i]==FIXY){ofixy=ar[++i];continue;}
			if(ar[i]==CLOSECLICK){ocloseclick=(ocloseclick==0)? 1 : 0;continue;}
			if(ar[i]==CSSSTYLE){ocss=ar[i];continue;}
		}
	}
	if(odelay==0){
		return overlib350();
	}else{
		odelayid=setTimeout("overlib350()", odelay);
		if(osticky){
			return false;
		}else{
			return true;
		}
	}
}

function overlib350(){
	var layerhtml;
	if(ocap!=""){
		if(osticky){
			layerhtml=ol_content_caption(otext, ocap, oclose);
		}else{
			layerhtml=ol_content_caption(otext, ocap, "");
		}
	}
	if(osticky){
		oshowingsticky=1;
		oremovecounter=0;
	}
	layerWrite(layerhtml);
	if(oautostatus > 0){
		ostatus=otext;
		if(oautostatus > 1){
			ostatus=ocap;
		}
	}
	oallowmove=0;
	if(otimeout > 0){
		if(otimerid > 0)clearTimeout(otimerid);
		otimerid=setTimeout("cClick()", otimeout);
	}
	disp(ostatus);
	if(osticky){
		oallowmove=0;
		return false;
	}else{
		return true;
	}
}

function ol_content_caption(text, title, close){
	closing="";
	if(ocloseclick==1) closeevent="onclick";
	if(close !=""){
		closing="<div class=\"jsCalClose\" "+closeevent+"=\"return cClick();\">"+close+"</div>";
	}
	txt="<div id=\"jsCalHeader\"> <div id=\"jsCalCaption\">"+ocapicon+title+"</div> "+closing+"<div class=\"clearer\">&nbsp;</div></div>";
	txt+=text;
	set_background("");
	return txt;
}

function set_background(pic){
	if(pic==""){
		if(ie4)over.backgroundImage="none";
		if(ns6)over.style.backgroundImage="none";
	}else{
		if(ns4){
			over.background.src=pic;
		}else if(ie4){
			over.backgroundImage="url("+pic+")";
		}else if(ns6){
			over.style.backgroundImage="url("+pic+")";
		}
	}
}
function disp(statustext){
if((ns4)||(ie4)||(ns6)){
if(oallowmove==0){
placeLayer();
showObject(over);
oallowmove=1;
}
}
if(statustext !=""){
self.status=statustext;
}
}
function placeLayer(){
	var placeX, placeY;
	if(ofixx > -1){
		placeX=ofixx;
	}else{
		winoffset=(ie4)? oframe.document.body.scrollLeft : oframe.pageXOffset;
		if(ie4)iwidth=oframe.document.body.clientWidth;
		if(ns4)iwidth=oframe.innerWidth;// was screwed in mozilla, fixed now?
		if(ns6)iwidth=oframe.outerWidth;

		if(ohauto==1){
			if((ox - winoffset)>((eval(iwidth))/ 2)){
				ohpos=7;
			}else{
			ohpos=8;
			}
		}
		if(ohpos==9){// Center
			placeX=ox+ooffsetx-(owidth/2);
		}
		if(ohpos==8){// Right
			placeX=ox+ooffsetx;
			if((eval(placeX)+ eval(owidth))>(winoffset + iwidth)){
				placeX=iwidth + winoffset - owidth;
				if(placeX < 0)placeX=0;
			}
		}
		if(ohpos==7){// Left
			placeX=ox-ooffsetx-owidth;
			if(placeX < winoffset)placeX=winoffset;
		}
		if(osnapx > 1){
			var snapping=placeX % osnapx;
			if(ohpos==7){
				placeX=placeX -(osnapx + snapping);
			}else{
				placeX=placeX +(osnapx - snapping);
			}
			if(placeX < winoffset)placeX=winoffset;
		}
	}
	if(ofixy > -1){
		placeY=ofixy;
	}else{
		scrolloffset=(ie4)? oframe.document.body.offsetHeight : oframe.pageYOffset;

		if(ovauto==1){
			if(ie4)iheight=oframe.document.body.clientHeight;
			if(ns4)iheight=oframe.innerHeight;
			if(ns6)iheight=oframe.outerHeight;
			iheight=(eval(iheight))/ 2;
			if((oy - scrolloffset)> iheight){
				ovpos=35;
			}else{
				ovpos=36;
			}
		}
		if(ovpos==35){
			if(oaboveheight==0){
				var divref=(ie4)? oframe.document.all['jsCal'] : over;
				oaboveheight=(ns4)? divref.clip.height : divref.offsetHeight;
			}
			placeY=oy -(oaboveheight + ooffsety);
			if(placeY < scrolloffset)placeY=scrolloffset;
		}else{
			placeY=oy + ooffsety;
		}
		if(osnapy > 1){
			var snapping=placeY % osnapy;
			if(oaboveheight > 0 && ovpos==35){
				placeY=placeY -(osnapy + snapping);
			}else{
				placeY=placeY +(osnapy - snapping);
			}
			if(placeY < scrolloffset)placeY=scrolloffset;
		}
	}
	repositionTo(over, placeX, placeY);
}
// This function was tossing mad errors whenever the mouse was moved prior the page finshed being loaded.
// I don't know exactly what this condition checks, but it does seem to prevent errors while allowing the
// functionality we need with our websites. The check is if(oallowmove==1) wich wraps the entire contents
// of the function, if we ever run into weird JS errors down the line, remove this and try again. - JM

// Update Nov 4, 2008 - Ryan
// We ran into those weird issues. In firefox and safari it would display the calendar in the corner
// Going to try specifying the issue oallowmove for IE only
// So far that seems to be working in my IE 7 and Mac browsers

// Nope, that doesn't work, it was just cached

// Updated! Fixed, body doesnt exist until the page is finished loading
function mouseMove(e){
//if(oallowmove==1){
if((ns4)||(ns6)){ox=e.pageX;oy=e.pageY;}
if(ie4){ox=event.x;oy=event.y;}
//if(ie5 || ie7){ox=event.x+oframe.document.body.scrollLeft;oy=event.y+oframe.document.documentElement.scrollTop;}
if((ie5 || ie7) && oframe.document.body) {
		ox=event.x+oframe.document.body.scrollLeft;
		oy=event.y+oframe.document.documentElement.scrollTop;
}
//if(oallowmove==1 && (ie5 || ie7)){ox=event.x+oframe.document.body.scrollLeft;oy=event.y+oframe.document.documentElement.scrollTop;}
if(oallowmove==1){
placeLayer();
}
//}
}
function cClick(){
hideObject(over);
oshowingsticky=0;
return false;
}
function compatibleframe(frameid){
if(ns4){
if(typeof frameid.document.jsCal=='undefined')return false;
}else if(ie4){
if(typeof frameid.document.all["jsCal"]=='undefined')return false;
}else if(ns6){
if(frameid.document.getElementById('jsCal')==null)return false;
}
return true;
}
function layerWrite(txt){
txt +="\n";
if(ns4){
var lyr=oframe.document.jsCal.document
lyr.write(txt)
lyr.close()
}else if(ie4){
oframe.document.all["jsCal"].innerHTML=txt
}else if(ns6){
range=oframe.document.createRange();
range.setStartBefore(over);
domfrag=range.createContextualFragment(txt);
while(over.hasChildNodes()){
over.removeChild(over.lastChild);
}
over.appendChild(domfrag);
}
}
function showObject(obj){
if(ns4)obj.visibility="show";
else if(ie4)obj.visibility="visible";
else if(ns6)obj.style.visibility="visible";
}
function hideObject(obj){
if(ns4)obj.visibility="hide";
else if(ie4)obj.visibility="hidden";
else if(ns6)obj.style.visibility="hidden";
if(otimerid > 0)clearTimeout(otimerid);
if(odelayid > 0)clearTimeout(odelayid);
otimerid=0;
odelayid=0;
self.status="";
}
function repositionTo(obj,xL,yL){
if((ns4)||(ie4)){
obj.left=xL;
obj.top=yL;
}else if(ns6){
obj.style.left=xL + "px";
obj.style.top=yL+ "px";
}
}
function opt_FRAME(frm){
oframe=compatibleframe(frm)? frm : ol_frame;
if((ns4)||(ie4 ||(ns6))){
if(ns4)over=oframe.document.jsCal;
if(ie4)over=oframe.jsCal.style;
if(ns6)over=oframe.document.getElementById("jsCal");
}
return 0;
}
function opt_FUNCTION(callme){
otext=callme()
return 0;
}
var replacementItems = new Array();

function com_stewartspeak_replacement() {
/*
	Dynamic Heading Generator
    By Stewart Rosenberger
    http://www.stewartspeak.com/headings/

	This script searches through a web page for specific or general elements
	and replaces them with dynamically generated images, in conjunction with
	a server-side script.
*/

for (var i = 0; i < replacementItems.length; i++){
	replaceSelector(replacementItems[i][0],JS_WEBROOT+"/ajax.php?q=getImageHeaders&ffont="+replacementItems[i][1]+"&fsize="+replacementItems[i][2]+"&fcolor=%23"+replacementItems[i][3]+"&bgcolor=%23"+replacementItems[i][4],true);
}
var testURL = JS_RIMS_WEB+"/test.jpg" ;

var doNotPrintImages = false;
var printerCSS = "replacement-print.css";

var hideFlicker = false;
var hideFlickerCSS = "replacement-screen.css";
var hideFlickerTimeout = 1000;




/* ---------------------------------------------------------------------------
    For basic usage, you should not need to edit anything below this comment.
    If you need to further customize this script's abilities, make sure
	you're familiar with Javascript. And grab a soda or something.
*/

var items;
var imageLoaded = false;
var documentLoaded = false;

function replaceSelector(selector,url,wordwrap)
{
	if(typeof items == "undefined")
		items = new Array();
	items[items.length] = {selector: selector, url: url, wordwrap: wordwrap};
}

if(hideFlicker)
{
	document.write('<link id="hide-flicker" rel="stylesheet" media="screen" href="' + hideFlickerCSS + '" />');
	window.flickerCheck = function()
	{
		if(!imageLoaded)
			setStyleSheetState('hide-flicker',false);
	};
	setTimeout('window.flickerCheck();',hideFlickerTimeout)
}

if(doNotPrintImages)
	document.write('<link id="print-text" rel="stylesheet" media="print" href="' + printerCSS + '" />');

var test = new Image();
test.onload = function() { imageLoaded = true; if(documentLoaded) replacement(); };
test.src = testURL + "?date=" + (new Date()).getTime();

addLoadHandler(function(){ documentLoaded = true; if(imageLoaded) replacement(); });


function documentLoad()
{
	documentLoaded = true;
	if(imageLoaded)
		replacement();
}

function replacement()
{
	if (items) {
		for(var i=0;i<items.length;i++)
		{
			var elements = getElementsBySelector(items[i].selector);
			if(elements.length > 0) for(var j=0;j<elements.length;j++)
			{
				if(!elements[j])
					continue ;

				var text = extractText(elements[j]);
	    		while(elements[j].hasChildNodes())
					elements[j].removeChild(elements[j].firstChild);

				var tokens = items[i].wordwrap ? text.split(' ') : [text] ;
				for(var k=0;k<tokens.length;k++)
				{
					var tokenText = tokens[k];
					if (k + 1 < tokens.length){
						tokenText += ' ';
					}
					var url = items[i].url + "&text="+escape(tokenText)+"&selector="+escape(items[i].selector);
					var image = document.createElement("img");
					image.className = "replacement";
					image.alt = tokens[k] ;
					image.src = url;
					elements[j].appendChild(image);
				}

				if(doNotPrintImages)
				{
					var span = document.createElement("span");
					span.style.display = 'none';
					span.className = "print-text";
					span.appendChild(document.createTextNode(text));
					elements[j].appendChild(span);
				}
			}
		}
	}
	if(hideFlicker)
		setStyleSheetState('hide-flicker',false);
}

function addLoadHandler(handler)
{
	if(window.addEventListener)
	{
		window.addEventListener("load",handler,false);
	}
	else if(window.attachEvent)
	{
		window.attachEvent("onload",handler);
	}
	else if(window.onload)
	{
		var oldHandler = window.onload;
		window.onload = function piggyback()
		{
			oldHandler();
			handler();
		};
	}
	else
	{
		window.onload = handler;
	}
}

function setStyleSheetState(id,enabled)
{
	var sheet = document.getElementById(id);
	if(sheet)
		sheet.disabled = (!enabled);
}

function extractText(element)
{
	if(typeof element == "string")
		return element;
	else if(typeof element == "undefined")
		return element;
	else if(element.innerText)
		return element.innerText;

	var text = "";
	var kids = element.childNodes;
	for(var i=0;i<kids.length;i++)
	{
		if(kids[i].nodeType == 1)
		text += extractText(kids[i]);
		else if(kids[i].nodeType == 3)
		text += kids[i].nodeValue;
	}

	return text;
}

/*
	Finds elements on page that match a given CSS selector rule. Some
	complicated rules are not compatible.
	Based on Simon Willison's excellent "getElementsBySelector" function.
	Original code (with comments and description):
		http://simon.incutio.com/archive/2003/03/25/getElementsBySelector
*/
function getElementsBySelector(selector)
{
	var tokens = selector.split(' ');
	var currentContext = new Array(document);
	for(var i=0;i<tokens.length;i++)
	{
		token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');
		if(token.indexOf('#') > -1)
		{
			var bits = token.split('#');
			var tagName = bits[0];
			var id = bits[1];
			var element = document.getElementById(id);
			if(tagName && element.nodeName.toLowerCase() != tagName)
				return new Array();
			currentContext = new Array(element);
			continue;
		}

		if(token.indexOf('.') > -1)
		{
			var bits = token.split('.');
			var tagName = bits[0];
			var className = bits[1];
			if(!tagName)
				tagName = '*';

			var found = new Array;
			var foundCount = 0;
			for(var h=0;h<currentContext.length;h++)
			{
				var elements;
				if(tagName == '*')
					elements = currentContext[h].all ? currentContext[h].all : currentContext[h].getElementsByTagName('*');
				else
					elements = currentContext[h].getElementsByTagName(tagName);

				for(var j=0;j<elements.length;j++)
					found[foundCount++] = elements[j];
			}

			currentContext = new Array;
			var currentContextIndex = 0;
			for(var k=0;k<found.length;k++)
			{
				if(found[k].className && found[k].className.match(new RegExp('\\b'+className+'\\b')))
					currentContext[currentContextIndex++] = found[k];
			}

			continue;
	    }

		if(token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/))
		{
			var tagName = RegExp.$1;
			var attrName = RegExp.$2;
			var attrOperator = RegExp.$3;
			var attrValue = RegExp.$4;
			if(!tagName)
				tagName = '*';

			var found = new Array;
			var foundCount = 0;
			for(var h=0;h<currentContext.length;h++)
			{
				var elements;
	        	if(tagName == '*')
					elements = currentContext[h].all ? currentContext[h].all : currentContext[h].getElementsByTagName('*');
				else
					elements = currentContext[h].getElementsByTagName(tagName);

				for(var j=0;j<elements.length;j++)
					found[foundCount++] = elements[j];
			}

			currentContext = new Array;
			var currentContextIndex = 0;
			var checkFunction;
			switch(attrOperator)
			{
				case '=':
					checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue); };
					break;
				case '~':
					checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('\\b'+attrValue+'\\b'))); };
					break;
				case '|':
					checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))); };
					break;
				case '^':
					checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0); };
					break;
				case '$':
					checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length); };
					break;
				case '*':
					checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1); };
					break;
				default :
					checkFunction = function(e) { return e.getAttribute(attrName); };
			}

			currentContext = new Array;
			var currentContextIndex = 0;
			for(var k=0;k<found.length;k++)
			{
				if(checkFunction(found[k]))
					currentContext[currentContextIndex++] = found[k];
			}

			continue;
		}

		tagName = token;
		var found = new Array;
		var foundCount = 0;
		for(var h=0;h<currentContext.length;h++)
		{
			//var elements = currentContext[h].getElementsByTagName(tagName);
			var elements = currentContext[h].getElementsByClassName(tagName);
			for(var j=0;j<elements.length; j++)
				found[foundCount++] = elements[j];
		}

		currentContext = found;
	}

	return currentContext;
}


}// end of scope, execute code

if(document.createElement && document.getElementsByTagName && !navigator.userAgent.match(/opera\/?6/i))
	com_stewartspeak_replacement();
/***************************************************/
/************** START FORM FUNCTIONS ***************/
/***************************************************/

function setFormValue( objForm, strValue ) {
 	objForm.value = strValue;
}

/**
 * Generic function to submit a form
 */
function submitForm(objForm, strURL, strTG)	{
//	alert(strURL);
	objForm.action = strURL;
	objForm.target = strTG;
	objForm.submit();
}

/**
 * Set the field focus on the first form type that is not a: hidden, select (single), disabled or read-only
 */
function f_setfocus( aForm ){
	if(aForm.elements[0]!=null) {
		var i;
		var max = aForm.length;
		for( i = 0; i < max; i++ ) {
			if( aForm.elements[ i ].type != "hidden" && aForm.elements[ i ].type != "select-one" && !aForm.elements[ i ].disabled && !aForm.elements[ i ].readOnly ) {
				aForm.elements[ i ].focus();
				break;
			}
		}
	}
}

/**
 * Change the value of a form field
 */
function changeVal (thisValue, thisForm, toLocation, toTarget) {
	var empNum = thisForm.employeeNum;
	var oldValue = empNum.value
	var newValue = "";
	switch (thisValue) {
		case '11':
			for (i=0; i<(oldValue.length-1); i++) {
				newValue += oldValue[i];
			}
			empNum.value = newValue;
			break;
		case '12':
			submitForm(thisForm, toLocation, toTarget)
			break;
		default:
			empNum.value += thisValue;
	}
}

/**
 *	Change a button source
 *  (used for rollovers and is probably way outdated)
 */
function changeButton(button, newSrc) {
	button.src = newSrc;
}

/***************************************************/
/*************** END FORM FUNCTIONS ****************/
/***************************************************/

/* GLOBAL ARRAY OF CONTAINERS  */
var hiddenContainers = ["contact", "work", "vacation", "sick", "personal"]
function displayContainer(displayContainer) {
	var i;
	var max = hiddenContainers.length;
	var selectedContainer = displayContainer.value;

	for (i=0;i<max;i++) {
		if (document.getElementById(hiddenContainers[i])!=null) {
			if (hiddenContainers[i]==selectedContainer) {
				document.getElementById(hiddenContainers[i]).style.display="block";

			} else {
				document.getElementById(hiddenContainers[i]).style.display="none";
			}
		}
	}
}

//function MM_preloadImages() { //v3.0
//  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
//    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
//    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
//}
//
/**
 * Function to swap an image (auto-generated from dreamweaver)
 */
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

/**
 * Function to restore an image after it has initially been swapped (auto-generated from dreamweaver)
 */
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
//
//function MM_findObj(n, d) { //v4.01
//  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
//    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
//  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
//  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
//  if(!x && d.getElementById) x=d.getElementById(n); return x;
//}
//

// Clock Script Generated By Maxx Blade's Clock v2.0
// http://www.maxxblade.co.uk/clock

function tS(){ x=new Date(); x.setTime(x.getTime()+dS()); return x; }
function tN(){ return new Date(); }
function dS(){ return ((tN().getTime()>fD(0,3,1,1).getTime())&&(tN().getTime()<fD(0,9,1,-1).getTime()))?3600000:0; }
function fD(d,m,h,p){ var week=(p<0)?7*(p+1):7*(p-1),nm=(p<0)?m+1:m,x=new Date(tN().getUTCFullYear(),nm,1,h,0,0),dOff=0; if(p<0){ x.setTime(x.getTime()-86400000); } if(x.getDay()!=d){ dOff=(x.getDay()<d)?(d-x.getDay()):0-(x.getDay()-d); if(p<0&&dOff>0){ week-=7; } if(p>0&&dOff<0){ week+=7; } x.setTime(x.getTime()+((dOff+week)*86400000)); } return x; }
function lZ(x){ return (x>9)?x:'0'+x; }
function tH(x){ if(x==0){ x=12; } return (x>12)?x-=12:x; }
function dT(){ if(fr==0){ fr=1; document.write('<div id="clock_date">'+eval(oT1)+'</div><div id="clock_time">'+eval(oT2)+'</div>'); } document.getElementById('clock_date').innerHTML=eval(oT1); document.getElementById('clock_time').innerHTML=eval(oT2); setTimeout('dT()',1000); }
function aP(x){ return (x>11)?'pm':'am'; }
function y4(x){ return (x<500)?x+1900:x; }
var dN=new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat'),
mN=new Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'),
fr=0,
oT1="dN[tS().getDay()]+' '+tS().getDate()+' '+mN[tS().getMonth()]+' '+y4(tS().getYear())",
//oT2="tH(tS().getHours())+':'+lZ(tS().getMinutes())+':'+lZ(tS().getSeconds())+' '+aP(tS().getHours())";
oT2="tH(tS().getHours())+':'+lZ(tS().getMinutes())+' '+aP(tS().getHours())";

function ShowTab(item, name, alltabs, tabContainer){
	if (item){
		//Set tab class
		if (tabContainer == null) tabContainer = "tabs";
		var tabCont = document.getElementById(tabContainer);
		if (tabCont){
			var tabs  = tabCont.getElementsByTagName("div");
			if (!tabs.length) tabs = tabCont.getElementsByTagName("li");
			for (var i = 0; i < tabs.length; i++){
				if (tabs[i].className == "tabActive"){
					tabs[i].className = "tabNormal";
				}
			}
		}
		item.className = "tabActive";
		//Display tab data
	}
	if (name){
		var tab;
		for (var i = 0; i < alltabs.length; i++){
			tab = document.getElementById(alltabs[i]);
			if (tab){
				tab.style.height = "0";
				tab.style.visibility = "hidden";
				tab.style.overflow = "hidden";
			}
		}
		tab = document.getElementById(name);
		if (tab){
			tab.style.height = "";
			tab.style.visibility = "visible";
			tab.style.overflow = "";
		}
	}
}

/*
MOVED
function Scroll(direction, tabClass, containerClass) {
	var tabs,				// The HTMLEntity Objects of the tabs.
		tabsContent,		// The HTMLEntity Objects of the tabs content.
		tabContentWidth,	// The width of the container we are scrolling.
		tabCount,			// The number of tabs, and containers.
		tabCurrent,			// The 0..n value of the current tab.
		tabIntended,		// The 0..n value of the intended tab.
		tabClassArr,		// The array of class names for the tabs.
		slideDistance;		// The distance our content will need to slide over for the effect.

	// Store the tab elements for later use, we typically can have a div or li setup.
	if( tabClass == null ) tabClass = 'mediaButton';
	tabs = $$( 'div.' + tabClass );
	if( !tabs.length ) tabs = $$( 'li.' + tabClass );

	// Store the tab content elements for later use, we typically can have a div or li setup.
	if( containerClass == null ) containerClass = 'media_section';
	tabsContent = $$( 'div.' + containerClass );
	if( !tabsContent.length ) tabsContent = $$( 'li.' + containerClass );

	// All tabs should be the same width.
	tabContentWidth = tabsContent[ 0 ].getWidth();
	tabCount = tabs.size();

	// Loop through the tabs
	tabs.each( function( iter, ndx ) {
		if( iter.hasClassName( 'tabActive' ) ) {
			// We have found the current active tab.
			tabCurrent = ndx;

			// Save class names on active tab.
			tabClassArr = $A( iter.className.split( ' ' ) ).without( 'tabActive', 'tabNormal', 'tabInactive' );

			// Set current active tab, as normal.
			iter.removeClassName( 'tabActive' );
			iter.addClassName( 'tabNormal' );

			// Break out, we don't need to iterate any more.
			throw $break;
		}
	});

	// If direction is positive, we are going "next", if it is negative, we are going "prev".
	// Find the intended tab.
	tabIntended = tabCurrent + direction;
	// Did we wrap around on the left?
	if( tabIntended < 0 ) {
		// tabCount should be 1..n, so subtract 1 to shift to 0..n
		tabIntended = tabCount - 1;
	// Did we wrap around on the right?
	} else if ( tabIntended + 1 > tabCount ) {
		tabIntended = 0;
	}

	// Reset the class name(s).
	tabs[ tabIntended ].className = '';
	tabClassArr.each( function( iter ) {
		tabs[ tabIntended ].addClassName( iter );
	});
	// Set the intended tab, as active.
	tabs[ tabIntended ].addClassName( 'tabActive' );

	var scaler = 1;
	if( tabCurrent - tabIntended < 0 ) {
		scaler = -1;
	}
	// Find the total distance we need to slide our main div over by.
	slideDistance = scaler * ( tabCurrent - tabIntended ).abs() * tabContentWidth;

	// Move the content over.
	new Effect.Move('media_content', { x: slideDistance, y: 0, mode: 'relative', queue: 'end' });
}

function ScrollTab(item, name, alltabs, tabContainer){
	var curActiveTab = 1;

	// Set the default tab class value, if it isn't set already.
	if( tabContainer == null ) tabContainer = 'media_buttonArea';

	// Tab container element.
	var tabCont = $( tabContainer );

	// Typically we deal with either DIVs, or LIs, so lets get em.
	var tabs = $$( '#' + tabContainer + ' div');
	if( !tabs.length ) tabs = $$( '#' + tabContainer + ' li');

	if( item ) {
		// Save the tab's class names if any exist, and remove the ones we append.
		var classArr = $A( item.className.split( ' ' ) ).without( 'tabActive', 'tabNormal', 'tabInactive' );

		// Loop through all the tabs.
		tabs.each(function(iter, ndx) {
			if( iter.hasClassName( 'tabActive' ) ) {
				iter.removeClassName( 'tabActive' );
				iter.addClassName( 'tabNormal' );
				curActiveTab = ndx + 1;
				throw $break;
			}
		});

		// Reset the class name(s).
		item.className = '';
		classArr.each(function(iter) {
			item.addClassName( iter );
		});
		// Set the active tab.
		item.addClassName( 'tabActive' );
	}

	//
	// Handle Transition, or the scroll.
	//
	if( name ) {
		var clickedTab;
		tabs.each( function( iter, ndx ) {
			if( $( iter ).hasClassName( 'tabActive' ) ) {
				clickedTab = ndx + 1;
			}
		});

		var moveDistance = ( curActiveTab - clickedTab ) * $( name ).getWidth();
		new Effect.Move('media_content', { x: moveDistance, y: 0, mode: 'relative', queue: 'end' });
	}
}
*/

var currentShown = '';
function ShowHours(divID) {
	var showDiv = document.getElementById('hours_'+divID);
	if (currentShown!='') {
//		alert(currentShown.style.display);
		currentShown.style.display = "none";
	}
	if (showDiv!=currentShown) {
		showDiv.style.display = "block";
		currentShown = showDiv;
	} else {
		currentShown = '';
	}
}

var advancedSearchText = '';
function showAdvancedSearch(advancedText) {
 	var showDiv = document.getElementById("advancedSearch");

 	if (advancedText.innerHTML.indexOf("Hide") == -1) {
 		showDiv.style.display = "block";
 		advancedSearchText = advancedText.innerHTML;
 		advancedText.innerHTML = "Hide "+advancedSearchText;
 	} else {
 		showDiv.style.display = "none";
 		advancedText.innerHTML = advancedSearchText;
 	}
}

var SelectSearch = 1;
function CheckSearchSelect(stockVal, formFields, changeURL) {
	if (SelectSearch == 1) {
		for(var i=0;i<formFields.length;i++) {
			if (formFields.elements[i].type == "select-one" && (formFields.elements[i].name!="type" || formFields.elements[i].name!="invSearch_type")) {
				formFields.elements[i].disabled = true;
				formFields.elements[i].value = '';
			}
		}
		SelectSearch = 0;
		changeSearchSubmit(formFields, formFields.getElementsByTagName("input"));
		document.getElementById("Search").disabled = false;
		document.getElementById("All").disabled = false;
	} else if (SelectSearch == 0) {
		enableInventorySearch(formFields);
		if (document.getElementById("invSearch_stock").value != '') {document.getElementById("Search").disabled = false;}
		if (document.getElementById("invSearch_stock").value != '') {document.getElementById("All").disabled = false;}
		eval(changeURL);
		SelectSearch = 1;
	}
}
/* STOPPING POINT */

function enableInventorySearch(docForm) {
	var selects = docForm.getElementsByTagName("select");
	var inputs = docForm.getElementsByTagName("input");

	for (var i=0;i<selects.length;i++) {
		if (selects[i].name=='type' || selects[i].name=='invSearch_type') {var typeIndex=i;selects[i].disabled = false;}
		else if (selects[typeIndex].value!='' && (selects[i].multiple!=true || selects[i].name=='trim[]')) {
			if (selects[i].length>1) {selects[i].disabled=false;}
			else {selects[i].disabled=true;}
		}
	}
	changeSearchSubmit(docForm, inputs);
}

/*
MOVED
function checkCarfax(vin, openLocation) {
	if (vin.length!=17) {
		$$('.badResponse').invoke("update", "You have entered an invalid VIN");
	}
	else {window.open(openLocation+vin);}
}
*/

/*
MOVED
function IP_Click(page, max, total) {
	if(page <= -1) {
		page = (total / max) - 1;	// zero based
	} else if(page >= (total / max)) {
		page = 0;
	}
	// Hide all elements
	var parent = $('similarVehicles');
	var children = parent.childNodes;
	var vehicleData = [];

	//alert('>' + (page * max) + ' && <' + ((page * max) + max + 1))
	var j=0;
	for(var i = 0; i < children.length; i++) {
		if(children[i].className == "likeVehicle") {
			if(page == 0 && j < max) {
				vehicleData.push(children[i]);
			} else if(page != 0 && j >= (page * max) && j < (page * max) + max) {
				vehicleData.push(children[i]);
			}
			if(children[i].style.setAttribute) {
				children[i].style.setAttribute("cssText", "display: none");
			} else {
				children[i].setAttribute("style", "display: none");
			}
			j++;
		}
	}
	// Show elements from (page * max) up to ((page * max) + max);
	for(i = 0; i < vehicleData.length; i++) {
		if(vehicleData[i].style.setAttribute) {
			vehicleData[i].style.setAttribute("cssText", "");
		} else {
			vehicleData[i].setAttribute("style", "");
		}
	}

	// Make all pagination tags of class 'otherPage'
	parent = $('pHandle');
	children = parent.childNodes;
	var paginationData = [];
	for(i = 0; i < children.length; i++) {
		if(children[i].className == 'pageDisplay' || children[i].className == 'currentPage') {
			paginationData.push(children[i]);
			children[i].className = 'pageDisplay';
		}
	}
	// Make the 'page' tag of class 'currentPage'
	paginationData[page].className = 'currentPage';
}
*/

/*
MOVED
function IP_Next(max) {
	var count = 0;
	var pageCount = 0;
	var parent = $('pHandle');
	var children = parent.childNodes;
	for(i = 0; i < children.length; i++) {
		if(children[i].className == 'pageDisplay' || children[i].className == 'currentPage') {
			pageCount++;
			count++;
			if(children[i].className == 'currentPage') {
				var currentPage = count;
			}
		}
	}
	IP_Click(currentPage, max, (pageCount * max));
}
*/

/*
MOVED
function IP_Prev(max) {
	var count = 0;
	var pageCount = 0;
	var parent = $('pHandle');
	var children = parent.childNodes;
	for(i = 0; i < children.length; i++) {
		if(children[i].className == 'pageDisplay' || children[i].className == 'currentPage') {
			pageCount++;
			if(children[i].className == 'currentPage') {
				var currentPage = count;
			}
			count++;
		}
	}
	IP_Click((currentPage - 1), max, (pageCount * max));
}
*/

/*
MOVED
function dynamicDay( dayID ) {
	// Get the three drop down elements.
	var eDay = $( dayID );
	var eMonth = $( dayID.sub( 'Day', 'Month' ) );
	var eYear = $( dayID.sub( 'Day', 'Year' ) );

	// If the three drop down elements are present and accounted for...
	if( eDay && eMonth && eYear ) {
		var totalDays = new Date(eYear.value, eMonth.value, 0).getDate();
		var eDays = eDay.childElements();
		var eDaysCount = eDays.length - 1;
		if( eDaysCount > totalDays ) {
			for( var i = eDaysCount; i > totalDays; i-- ) {
				// remove
				eDays[ i ].remove();
			}
		} else if( eDaysCount < totalDays ) {
			for( var i = eDaysCount + 1; i <= totalDays; i++ ) {
				// append
				var attrs = {
					value	: i
				};

	            var link = new Element('option', attrs);
	            link.update(i);
	            eDay.insert(link);
			}
		}
	}
}
*/

/*
MOVED
function toggleVehicleHistory( vh_ID, tab_ID, instant ) {
	if( instant == null ) { instant = 0; }
	// Only proceed if we have an ID.
	if( vh_ID ) {
		var vh = $( vh_ID );
		var tab = $( tab_ID );

		// Toggle the class name.
		var active = 1;
		if( vh.hasClassName( 'vh_active' ) ) {
			vh.removeClassName( 'vh_active' );
			vh.addClassName( 'vh_inactive' );
			active = -1;
		} else if( vh.hasClassName( 'vh_inactive' ) ) {
			vh.removeClassName( 'vh_inactive' );
			vh.addClassName( 'vh_active' );
		} else {
			vh.addClassName( 'vh_active' );
		}

		// Handle Transition, or the scroll.
		var moveDistance = -1 * active * ( vh.getWidth() - tab.getWidth() );
		new Effect.Move( vh_ID, { x: moveDistance, y: 0, mode: 'relative', duration: 1.0, transition: Effect.Transitions.spring, queue: 'end' } );

		new Ajax.Request( 'ajax.php?q=storeVehicleHistoryState', {
			method: 'get',
			parameters: { 'vh_state': -1 * active }
		});
	}
}
*/
function getRequest() {
    var xmlhttp=false;
    /*@cc_on @*/
    /*@if (@_jscript_version >= 5)
    // JScript gives us Conditional compilation, we can cope with old IE versions.
    // and security blocked creation of the objects.
     try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (e) {
      try {
       xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
       xmlhttp = false;
      }
     }
    @end @*/
    if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
        try {
            xmlhttp = new XMLHttpRequest();
        } catch (e) {
            xmlhttp=false;
        }
    }
    if (!xmlhttp && window.createRequest) {
        try {
            xmlhttp = window.createRequest();
        } catch (e) {
            xmlhttp=false;
        }
    }

    return xmlhttp;
}

function check_email(e) {
	var filter=/^.+@.+\..{2,3}$/

	if (filter.test(e)) return 1;
	return 0;
}


function isArray(obj) {
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}


function clearTable(tableElm) {
	var rows = tableElm.rows;
	for( var i = rows.length - 1; i >= 0; --i )
  		tableElm.deleteRow( i );
}

function clearSelect(selectElm) {
	if (selectElm.options != null) {
		//alert ("clearing: "+selectElm.name);
        selectElm.options.length = 0;
    }
    selectElm.disabled = true;
}

function fillSelect(selectElm, responseText, restrict) {
    selectElm.options.length = 0;
    selectElm.options[0] = new Option("", "0", true, true);
    var response = responseText.split(";;");
    for (var i = 0; i < response.length; i++) {
        var style = response[i].split("~~");
        if (restrict && restrict != ''){
        	if (restrict.inArray(style[1])){
        		selectElm.options[selectElm.options.length] = new Option(style[1], style[0], false, false);
        	}
        } else {
       		selectElm.options[selectElm.options.length] = new Option(style[1], style[0], false, false);
        }
    }
    selectElm.disabled = false;
}

//This is only used while testing
function fillTestData(txt){
	var td = document.getElementById("testdata");
	if (td){
		td.innerHTML = txt;
	}
}

function doError(err){
	alert(err);
}

function setElementText( elementName, value )
{
    var element = document.getElementById( elementName );
    if( element )
        element.innerHTML = value;
}

function getFloatValue( floatValue )
{
    var value;
    if( floatValue.length > 0 )
    {
        // strip out non-numeric characters
        floatValue = floatValue.replace( NUMERIC_REGEXP, "" );

        value = parseFloat( floatValue );
        if( isNaN( value ) )
            value = null;
    }
    return value;
}

function selectSelectboxItem(sel, id){
	if (sel){
		for (var i=0; i < sel.options.length; i++){
			if (sel.options[i].value == id){
				sel.selectedIndex = i;
				return sel.options[i].value;
			}
		}
		for (var i=0; i < sel.options.length; i++){
			if (sel.options[i].innerHTML == id){
				sel.selectedIndex = i;
				return sel.options[i].value;
			}
		}
	} else {
		alert("FAIL");
	}
	return 0;
}


function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

//////////////////////////////////// xml2array() ////////////////////////////////////////
//See http://www.openjs.com/scripts/xml_parser/
var not_whitespace = new RegExp(/[^\s]/);//This can be given inside the funciton - I made it a global variable to make the scipt a little bit faster.
var parent_count;
//Process the xml data
function xml2array(xmlDoc,parent_count) {
	var arr;
	var parent = "";
	parent_count = parent_count || new Object;

	var attribute_inside = 0; /*:CONFIG: Value - 1 or 0
	*	If 1, Value and Attribute will be shown inside the tag - like this...
	*	For the XML string...
	*	<guid isPermaLink="true">http://www.bin-co.com/</guid>
	*	The resulting array will be...
	*	array['guid']['value'] = "http://www.bin-co.com/";
	*	array['guid']['attribute_isPermaLink'] = "true";
	*
	*	If 0, the value will be inside the tag but the attribute will be outside - like this...
	*	For the same XML String the resulting array will be...
	*	array['guid'] = "http://www.bin-co.com/";
	*	array['attribute_guid_isPermaLink'] = "true";
	*/

	if(xmlDoc.nodeName && xmlDoc.nodeName.charAt(0) != "#") {
		if(xmlDoc.childNodes.length > 1) { //If its a parent
			arr = new Object;
			parent = xmlDoc.nodeName;

		}
	}
	var value = xmlDoc.nodeValue;
	if(xmlDoc.parentNode && xmlDoc.parentNode.nodeName && value) {
		if(not_whitespace.test(value)) {//If its a child
			arr = new Object;
			arr[xmlDoc.parentNode.nodeName] = value;
		}
	}

	if(xmlDoc.childNodes.length) {
		if(xmlDoc.childNodes.length == 1) { //Just one item in this tag.
			arr = xml2array(xmlDoc.childNodes[0],parent_count); //:RECURSION:
		} else { //If there is more than one childNodes, go thru them one by one and get their results.
			var index = 0;

			for(var i=0; i<xmlDoc.childNodes.length; i++) {//Go thru all the child nodes.
				var temp = xml2array(xmlDoc.childNodes[i],parent_count); //:RECURSION:
				if(temp) {
					var assoc = false;
					var arr_count = 0;
					for(key in temp) {
						if(isNaN(key)) assoc = true;
						arr_count++;
						if(arr_count>2) break;//We just need to know wether it is a single value array or not
					}

					if(assoc && arr_count == 1) {
						if(arr[key]) { 	//If another element exists with the same tag name before,
										//		put it in a numeric array.
							//Find out how many time this parent made its appearance
							if(!parent_count || !parent_count[key]) {
								parent_count[key] = 0;

								var temp_arr = arr[key];
								arr[key] = new Object;
								arr[key][0] = temp_arr;
							}
							parent_count[key]++;
							arr[key][parent_count[key]] = temp[key]; //Members of of a numeric array
						} else {
							parent_count[key] = 0;
							arr[key] = temp[key];
							if(xmlDoc.childNodes[i].attributes.length) {
								for(var j=0; j<xmlDoc.childNodes[i].attributes.length; j++) {
									var nname = xmlDoc.childNodes[i].attributes[j].nodeName;
									if(nname) {
										/* Value and Attribute inside the tag */
										if(attribute_inside) {
											var temp_arr = arr[key];
											arr[key] = new Object;
											arr[key]['value'] = temp_arr;
											arr[key]['attribute_'+nname] = xmlDoc.childNodes[i].attributes[j].nodeValue;
										} else {
										/* Value in the tag and Attribute otside the tag(in parent) */
											arr['attribute_' + key + '_' + nname] = xmlDoc.childNodes[i].attributes[j].nodeValue;
										}
									}
								} //End of 'for(var j=0; j<xmlDoc. ...'
							} //End of 'if(xmlDoc.childNodes[i] ...'
						}
					} else {
						arr[index] = temp;
						index++;
					}
				} //End of 'if(temp) {'
			} //End of 'for(var i=0; i<xmlDoc. ...'
		}
	}

	if(parent && arr) {
		var temp = arr;
		arr = new Object;

		arr[parent] = temp;
	}
	return arr;
}

/**
* Function : dump()
* Arguments: The data - array,hash(associative array),object
*    The level - OPTIONAL
* Returns  : The textual representation of the array.
* This function was inspired by the print_r function of PHP.
* This will accept some data as the argument and return a
* text that will be a more readable version of the
* array/hash/object that is given.
*/
function dump(arr,level) {
var dumped_text = "";
if(!level) level = 0;

//The padding given at the beginning of the line.
var level_padding = "";
for(var j=0;j<level+1;j++) level_padding += "    ";

if(typeof(arr) == 'object') { //Array/Hashes/Objects
 for(var item in arr) {
  var value = arr[item];

  if(typeof(value) == 'object') { //If it is an array,
   dumped_text += level_padding + "'" + item + "' ...\n";
   dumped_text += dump(value,level+1);
  } else {
   dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
  }
 }
} else { //Stings/Chars/Numbers etc.
 dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
}
return dumped_text;
}

function removeChildrenFromNode(node)
{
   if(node !== undefined && node !== null)
   {
		var len = node.childNodes.length;
		while (node.hasChildNodes())
		{
			node.removeChild(node.firstChild);
		}
   }
}

function getChildNodeByName(obj, name){
	var i = 0;
	if (obj.childNodes){
		while(i < obj.childNodes.length && obj.childNodes[i].name != name ){
			i++;
		}
		if (i < obj.childNodes.length){
			return obj.childNodes[i];
		}
	}
	return null;
}

function setChildNodeByName(obj, name, attr, value){
	var item = getChildNodeByName(obj, name);
	if (item != null){
		if (item.setAttribute){
			item.setAttribute(attr, value);
		} else {
			alert("Not possible! "+name+ " "+attr);
		}
	}
}

function urlencode(str) {
str = escape(str);
str = str.replace('+', '%2B');
str = str.replace('%20', '+');
str = str.replace('*', '%2A');
str = str.replace('/', '%2F');
str = str.replace('@', '%40');
return str;
}

function urldecode(str) {
str = str.replace('+', ' ');
str = unescape(str);
return str;
}

var cbtnDest = "";
function continueButtonFunction(val){
	cbtnDest = val;
}

function continueButtonEnable(val){
	var cbtn = document.getElementById("continue_button_img");
	if (cbtn){
		if (val == 1){
			cbtn.onclick = cbtnDest;
			cbtn.className="continue_button_img";
			cbtn.style.cursor = "pointer";
		} else {
			cbtn.onclick = function() {}
			cbtn.className="continue_button_img_off";
			cbtn.style.cursor = "default";
		}
	}
}

function php_serialize(obj)
{
var string = '';

if (typeof(obj) == 'object') {
if (obj instanceof Array) {
string = 'a:';
tmpstring = '';
count = 0;
for (var key in obj) {
tmpstring += php_serialize(key);
tmpstring += php_serialize(obj[key]);
count++;
}
string += count + ':{';
string += tmpstring;
string += '}';
} else if (obj instanceof Object) {
classname = obj.toString();

if (classname == '[object Object]') {
classname = 'StdClass';
}

string = 'O:' + classname.length + ':"' + classname + '":';
tmpstring = '';
count = 0;
for (var key in obj) {
tmpstring += php_serialize(key);
if (obj[key]) {
tmpstring += php_serialize(obj[key]);
} else {
tmpstring += php_serialize('');
}
count++;
}
string += count + ':{' + tmpstring + '}';
}
} else {
switch (typeof(obj)) {
case 'number':
if (obj - Math.floor(obj) != 0) {
string += 'd:' + obj + ';';
} else {
string += 'i:' + obj + ';';
}
break;
case 'string':
string += 's:' + obj.length + ':"' + obj + '";';
break;
case 'boolean':
if (obj) {
string += 'b:1;';
} else {
string += 'b:0;';
}
break;
}
}

return string;
}
// *****************************************************
function js_array_to_php_array (a)	{
// This converts a javascript array to a string in PHP serialized format.
// This is useful for passing arrays to PHP. On the PHP side you can
// unserialize this string from a cookie or request variable. For example,
// assuming you used javascript to set a cookie called "php_array"
// to the value of a javascript array then you can restore the cookie
// from PHP like this:
// // This automatically converts both keys and values to strings.
// The return string is not URL escaped, so you must call the
// Javascript "escape()" function before you pass this string to PHP.
var a_php = "";
var total = 0;
for (var key in a)
{
++ total;
a_php = a_php + "s:" +
String(key).length + ":\"" + String(key) + "\";s:" +
String(a[key]).length + ":\"" + String(a[key]) + "\";";
}
a_php = "a:" + total + ":{" + a_php + "}";
return a_php;
}

function Track(type, data, system){
	//do request
    var request = getRequest();
    request.open("get", "ajax/carbuilder/track.php?type=" + type + "&system=" + system + "&data=" + php_serialize( (data) ), true);
    request.send(null);
}

function CarbuilderPreloader(show){
	if (show == 1){
		dojo.require( 'dhd.site.overlay.Loading' );
		_gLoadingOverlay.display();
	}
}

function capitalizeMe(obj) {
        val = obj.value;
        newVal = '';
        val = val.split(' ');
        for(var c=0; c < val.length; c++) {
        	newVal += val[c].substring(0,1).toUpperCase() +
				val[c].substring(1,val[c].length) + ' ';
        }
        obj.value = newVal;
}

function lowercaseAllOfMe(obj){
	val = obj.value;
    obj.value = val.toLowerCase();
}
var make_restriction_list = '';


function selectMode(mode, cy, cm, cmod) {
	if (mode == ""){
		//get mode
    	var modeElm = document.getElementById("system_mode");
    	var mode = modeElm.options[modeElm.selectedIndex].value;
	}

    //do request
    var request = getRequest();

    request.onreadystatechange=function()
	{
	if(request.readyState==4)
	  {
	    //clear dropdowns
	    clearSelect(document.getElementById("car_make_select"));
	    clearSelect(document.getElementById("car_model_select"));

	    loadYears(cy, cm, cmod);
	  }
	}

    request.open("get", "ajax/carbuilder/system_mode.php?orderAvailability=" + mode, true);
    request.send(null);
}


function loadYears(cy, cm, cmod) {
	//do request
    var request = getRequest();
    request.onreadystatechange=function()
	{
	if(request.readyState==4)
	  {
	  	//populate year dropdown and disable division and model
	  	clearSelect(document.getElementById("car_make_select"));
	    clearSelect(document.getElementById("car_model_select"));
	    fillSelect(document.getElementById("car_year_select"), request.responseText);

	    if (cy) {
	    	selectSelectboxItem(document.getElementById("car_year_select"), cy);
	    	selectYear(cy, cm, cmod);
	    }
	  }
	}

    request.open("get", "ajax/carbuilder/car_years.php", true);
    request.send(null);
}

function selectYear(cy, cm, cmod) {
	//do request
	var request = getRequest();


    request.onreadystatechange=function()
	{
		if(request.readyState==4)
	  	{
	  		//populate division dropdown and clear model dropdown
    		clearSelect(document.getElementById("car_model_select"));
    		fillSelect(document.getElementById("car_make_select"), request.responseText, make_restriction_list);
    		if (cm){
    			cm = selectSelectboxItem(document.getElementById("car_make_select"), cm);
    			selectMake(cm, cmod);
    		}
	  	}
	}
    request.open("get", "ajax/carbuilder/car_make.php?modelYear=" + cy, true);
    request.send(null);



}

function selectMake(makeId, cmod) {
	//get year
    var modelYear = document.getElementById("car_year_select").value;

    //do request
    var request = getRequest();
    request.onreadystatechange=function()
	{
		if(request.readyState==4)
	  	{
	  		//sort models
		    var models = request.responseText.split(";;");
		    var modelsArray = [];
		    for (var i = 0; i < models.length; i++) {
		   		modelsArray[i] = models[i];
			}
			modelsArray.sort();

		    //populate model dropdown
		    fillModelsSelect(document.getElementById("car_model_select"), modelsArray);
		    if (cmod){
		    	cmod = selectSelectboxItem(document.getElementById("car_model_select"), cmod);
		    	continueButtonEnable(1);
		    } else {
		    	continueButtonEnable(0);
		    }
	  	}
	}

    request.open("get", "ajax/carbuilder/car_model.php?modelYear=" + modelYear + "&makeId=" + makeId, true);
    request.send(null);


}

function fillModelsSelect(selectElm, modelsArray) {
    selectElm.options.length = 0;
    selectElm.options[0] = new Option("", "0", true, true);
    for (var i = 0; i < modelsArray.length; i++) {
        var style = modelsArray[i].split("~~");
       	selectElm.options[selectElm.options.length] = new Option(style[0], style[1], false, false);
    }
    selectElm.disabled = false;
}


/* Advanced Search */
//Convert known criterion to something readable.
var ca = new Array();
ca["hasAirbagDriver"] = "A Driver Side Airbag";
ca["hasAirbagPassenger"] = "A Passenger Side Airbag";

function criteria_to_sentence(crit)
{
	if (ca[crit]){
		return ca[crit];
	}
	return crit;
}

function criteria_to_fullsentence(crit, imp, sv, so, nmin, nmax, mmin, mmax, tmin, tmax)
{
	var sent = "";
	crit = criteria_to_sentence(crit);
	if (imp == "false"){
		sent = "Does Not Have "+crit;
	} else {
		sent = "Has "+crit;
	}

	if (sv){
		sent += " of type "+so;
	} else if (so){

	} else if (nmin){
		sent += " between "+nmin+" and "+nmax;
	} else if (mmin){
		sent += " between $"+nmin+" and $"+nmax;
	} else if (tmin){
		sent += " between "+tmin+" and "+tmax;
	}

	return sent+".";
}

var selectedCriterionCount = 0;
var addedCriterionCount = 0;
function AddCriterionSelector(){
	p = null;
	i = 0;
	while (!p){
		var p = document.getElementById("caroption_"+i);
		i++;
	}
	var newdiv = p;
	if (selectedCriterionCount == 0){
		p.style.display = "block";
	} else {
		newdiv = document.createElement('div');
		var divIdName = p.id;
		divIdName = divIdName.substr(0, divIdName.length-1)+(selectedCriterionCount);
		newdiv.setAttribute('id',divIdName);
		newdiv.innerHTML = p.innerHTML;
		p.parentNode.appendChild(newdiv);
		nlist = document.getElementsByName("adv_search_select_name");
		if (nlist){
			criterionSelected(nlist[selectedCriterionCount], newdiv);
		}
	}
	selectedCriterionCount++;
	addedCriterionCount++;

	return newdiv;
}

function RemoveCriterionSelector(elem){
	selectedCriterionCount--;
	if (selectedCriterionCount > 0){
		var p = elem.parentNode;
		p.removeChild(elem);
	} else if (selectedCriterionCount == 0){
		elem.style.display = "none";
	}
	//Reset ID's
	for (var i = 0; i < selectedCriterionCount; i++){
		var n = p.childNodes[i];
		if (n.setAttribute){
			n.setAttribute('id',"caroption_"+i);
		}
	}
}


var NUMERIC_REGEXP = /[^\-\d\.]/g;
var stringArray = new Array();
var booleanArray = new Array();
var numberRangeArray = new Array();
var moneyRangeArray = new Array();
var techSpecArray = new Array();
var selectArray = [ "locale", "mode", "criterion" ];
var currentRow = null;

var currentCriteria = new Array();
var currentCompositeCriteria = new Array();

var FORMAT_BOLD = 0;
var FORMAT_ITALIC = 1;

var ACTION_DELETE = 0;
var ACTION_GENERAL_CRITERIA = 1;
var ACTION_AND_CRITERIA = 2;
var ACTION_OR_CRITERIA = 3;

var CRIT_LIST_ROW    = "critListRow_";
var CRIT_LIST_CHECK  = "critListCheck_";
var CRIT_LIST_CHECKS  = "critListChecks";
var CRIT_EFFECT_ROW    = "critEffectRow_";
var CRIT_EFFECT_BTN    = "critEffectBtn_";

var TYPE_GENERAL_CRITERION = "general";
var TYPE_AND_CRITERION = "and";
var TYPE_OR_CRITERION = "or";

// represents a search criterion object which is used to build a search request
SearchCriterion.index = 0;
function SearchCriterion( name, type )
{
    this.name = name;
    this.type = type;
    this.mustHave = true;
    this.value = null;
    this.min = null;
    this.max = null;
    this.id = SearchCriterion.index++;
}

SearchCriterion.prototype.getSummary = function()
{
    var valueDesc = "";

    switch( this.type )
    {
        case "Boolean":
            valueDesc = " = " + getFormattedString( this.value, FORMAT_BOLD );
            break;
        case "String":
            valueDesc = " = " + getFormattedString( this.value, FORMAT_BOLD );
            break;
        // fall through for all these cases
        case "NumberRange":
        case "MoneyRange":
        case "TechnicalSpecificationRange":
            valueDesc = (this.min.length > 0 ? " >= " + getFormattedString( this.min, FORMAT_BOLD ) : "" )
            valueDesc += (this.max.length > 0 ? (valueDesc.length > 0 ? " and " : "" ) + " <= " + getFormattedString( this.max, FORMAT_BOLD ) : "" );
            break;
        default:
            break;
    }

    return (this.mustHave ? "Must have " : "Must not have ") + getFormattedString( this.name, FORMAT_BOLD ) + valueDesc;
}

SearchCriterion.prototype.getSearchString = function()
{
    // construct search string based on params
    var searchString = "&name=" + this.name;
    searchString += "&type=" + this.type;
    searchString += "&mustHave=" + this.mustHave;
    searchString += "&value=" + (this.value != null ? this.value : "" );
    searchString += "&min=" + (this.min != null ? this.min : "" );
    searchString += "&max=" + (this.max != null ? this.max : "" );

    return searchString;
}


function getSearchCriteria(sbox, home)
{
	if (sbox){

	    var request = getRequest();
	    request.onreadystatechange=function()
		{
			if(request.readyState==4)
		  	{
		  		// clear out old data
			    currentCriteria.length = 0;
			    currentCompositeCriteria.length = 0;

			    var childNodes = sbox.childNodes; // clear out old list of criteria
			    for( var i = childNodes.length -1; i >= 0; --i )
			        sbox.removeChild( childNodes[ i ] );

			    // divide the criteria based on type
			    stringArray.length = 0;
			    booleanArray.length = 0;
			    numberRangeArray.length = 0;
			    moneyRangeArray.length = 0;
			    techSpecArray.length = 0;

			    // iterate through all search criteria
			    var response = request.responseText.split(";;");
			    for (var i = 0; i < response.length; i++)
			    {
			        var criterionParams = response[i].split("~~");
			        var name = criterionParams[ 0 ];
			        var type = criterionParams[ 1 ];
			        var min = criterionParams[ 2 ];
			        var max = criterionParams[ 3 ];
			        var unit = criterionParams[ 4 ];

			        var criterion = new SearchCriterion( name, type );
			        criterion.min = min;
			        criterion.max = max;
			        criterion.unit = unit;

			        // add the criterion to the appropriate array
			        var array = null;
			        switch( type )
			        {
			            case "String":
			                array = stringArray;
			                break;
			            case "Boolean":
			                array = booleanArray;
			                break;
			            case "NumberRange":
			                array = numberRangeArray;
			                break;
			            case "MoneyRange":
			                array = moneyRangeArray;
			                break;
			            case "TechnicalSpecificationRange":
			                array = techSpecArray;
			                break;
			        }
			        if( array != null )
			            array.push( criterion );
			    }

			    // add the criteria to the sbox
			    addCriteriaToSelect( sbox, "Yes/No Criteria", booleanArray );
			    addCriteriaToSelect( sbox, "String Criteria", stringArray );
			    addCriteriaToSelect( sbox, "Number Range Criteria", numberRangeArray );
			    addCriteriaToSelect( sbox, "Money Range Criteria", moneyRangeArray );
			    addCriteriaToSelect( sbox, "Technical Specification Criteria", techSpecArray );

			    // enable the sbox and sbox first element by default
			    sbox.disabled = false;
			    if( sbox.options.length > 0 )
			    {
			        sbox.options.sboxedIndex = 0;
			        criterionSelected(sbox, home);
			    }
		  	}
		}


	    request.open("get", "ajax/carbuilder/adv_search_criteria.php", false);
	    request.send(null);
	}
}

function addCriteriaToSelect( select, groupName, array )
{
    if( array.length > 0 )
    {
        array.sort
        (
            function( a, b )
            {
                var aLower = a.name.toLowerCase();
                var bLower = b.name.toLowerCase();

                if( aLower < bLower )
                    return -1;
                else if( aLower > bLower )
                    return 1;
                else
                    return 0;
            }
        );

        var optGroup = document.createElement( "OPTGROUP" );
        optGroup.label = groupName;
        for( var i = 0; i < array.length; ++i )
        {
            var option = document.createElement( "OPTION" );
            option.value = array[ i ].name;
            option.innerHTML = criteria_to_sentence(array[ i ].name);
            option.setAttribute( "criterion", array[ i ].type + "~~" + i );
            optGroup.appendChild( option );
        }
        select.appendChild( optGroup );
    }
}



function criterionSelected(sbox, home){
	var descriptor = findCriterion(sbox);
	var positionString = home.id;
	var position = positionString.substr(10, positionString.length-10);

    var select = sbox;
    var tokenName = select.options[ select.options.selectedIndex ].value;

    if( descriptor )
    {
        var type = descriptor.type;
        setElementText( "criterionType", type );
        var targetRow = type + "Row";

        var minField = "";
        var maxField = "";
        var minValueField = "";
        var maxValueField = "";

        if (currentRow){
        	currentRow.style.display = "none";
        	currentRow = null;
        }

        switch( type )
        {
        	case "String":
                var stringFieldItem = document.getElementsByName("adv_search_stringValue");
            	stringFieldItem[position].value = "";
                currentRow = "adv_search_StringRow";
                break;
            case "NumberRange":
                minField = "adv_search_numMin";
                maxField = "adv_search_numMax";
                minValueField = "adv_search_numMinValue";
                maxValueField = "adv_search_numMaxValue";
                currentRow = "adv_search_NumberRangeRow";
                break;
            case "MoneyRange":
                minField = "adv_search_moneyMin";
                maxField = "adv_search_moneyMax";
                minValueField = "adv_search_moneyMinValue";
                maxValueField = "adv_search_moneyMaxValue";
                currentRow = "adv_search_MoneyRangeRow";
                break;
            case "TechnicalSpecificationRange":
                minField = "adv_search_techSpecMin";
                maxField = "adv_search_techSpecMax";
                minValueField = "adv_search_techSpecMinValue";
                maxValueField = "adv_search_techSpecMaxValue";
                currentRow = "adv_search_TechnicalSpecificationRangeRow";
                break;
            default:
                break;
        }


        if( type == "NumberRange" || type == "MoneyRange" || type == "TechnicalSpecificationRange" ){
            var minFieldItem = document.getElementsByName(minField);
            minFieldItem[position].innerHTML = descriptor.min;
            var maxFieldItem = document.getElementsByName(maxField);
            maxFieldItem[position].innerHTML = descriptor.max;
            var minItem = document.getElementsByName(minValueField);
            minItem[position].value = "";
            var maxItem = document.getElementsByName(maxValueField);
            maxItem[position].value = "";
        } else if ( type == "String" ){
	     	var optionalValues = getOptionalValues( tokenName );
	     	if( optionalValues.length > 0 ){
		     	currentRow = "adv_search_StringRowWithOptions";
		     	var optionsItems = document.getElementsByName("adv_search_stringOptionValues");
            	var optionsSelect = optionsItems[position];

		     	optionsSelect.length = 0;
		     	for( var i=0; i < optionalValues.length; i++ ){
                     var optionalValue = optionalValues[i].split("~~");
                     var option = document.createElement( "OPTION" );
		             option.value = optionalValue[0];
		             option.innerHTML = optionalValue[1];
		             optionsSelect.appendChild( option );
			    }
		    }
	    }
	    if (currentRow){
	    	currentRow = document.getElementsByName(currentRow);
        	currentRow = currentRow[position];
        	currentRow.style.display = "block";
	    }
    }
}

function findCriterion(sbox){

    var descriptor = null;

    if (sbox){
	    var item = sbox.options[ sbox.options.selectedIndex ].getAttribute( "criterion" );
	    var params = item.split( "~~" );

	    var array = null;
	    switch( params[0] )
	    {
	        case "String":
	            array = stringArray;
	            break;
	        case "Boolean":
	            array = booleanArray;
	            break;
	        case "NumberRange":
	            array = numberRangeArray;
	            break;
	        case "MoneyRange":
	            array = moneyRangeArray;
	            break;
	        case "TechnicalSpecificationRange":
	            array = techSpecArray;
	            break;
	    }

	    var index = parseInt( params[ 1 ] );
	    if( array != null && index < array.length )
	        descriptor = array[ index ];
    }
	return descriptor;
}

function getOptionalValues( stringTokenName ){

	var values = new Array();

    var request = getRequest();
    request.open("get", "ajax/carbuilder/adv_search_string_options.php?tokenName=" + stringTokenName, false);
    request.send(null);

    if( request.responseText.length > 0 ){
	    var optionalValues = request.responseText.split(";;");
	    for( var i=0; i < optionalValues.length; i++ ){
            if( optionalValues[i].length > 0 ){
			    values[values.length] = optionalValues[i];
			}
		}
	}

	return values;

}

function finalizeSearch(url){
	CarbuilderPreloader(1);

	var yearElm = document.getElementById("car_year_select");
	if (!yearElm.selectedIndex){
		doError("You did not set the year.");
		return 0;
	}
	var year = yearElm.options[yearElm.selectedIndex].value;
	if (!year){
		doError("You did not set the year.");
		return 0;
	}

	var makeElm = document.getElementById("car_make_select");
	if (!makeElm.selectedIndex){
		doError("You did not set the make.");
		return 0;
	}
	var make = makeElm.options[makeElm.selectedIndex].value;
	if (!make){
		doError("You did not set the make.");
		return 0;
	}

	var modelElm = document.getElementById("car_model_select");
	var model = modelElm.options[modelElm.selectedIndex].value;
	/*if (!model){
		doError("You did not set the model.");
		return 0;
	}*/

	var address = "ajax/carbuilder/search_finalize.php?car_year=" + year +"&car_make=" + make +"&car_model=" + model;

	/* ADVANCED OPTIONS */
	var optionsel = document.getElementById("caroption_0");
	if (optionsel){
		if (optionsel.style.display=="block"){
			var fieldList =
				new Array(
					"adv_search_select_name", 0,
					"adv_search_select_imp", 0,
					"adv_search_stringValue", 1,
					"adv_search_stringOptionValues", 0,
					"adv_search_numMinValue", 1,
					"adv_search_numMaxValue", 1,
					"adv_search_moneyMinValue", 1,
					"adv_search_moneyMaxValue", 1,
					"adv_search_techSpecMinValue", 1,
					"adv_search_techSpecMaxValue", 1
				)
			for(var j = 0; j < fieldList.length; j+=2){
				var nlist = document.getElementsByName(fieldList[j]);
				if (nlist){
					for(var i = 0; i < nlist.length; i++){
						var sel = nlist[i];
						address += "&"+fieldList[j]+"_"+i+"=";
						if (fieldList[j+1] == 0 && sel.options.length) address += sel.options[sel.selectedIndex].value;
						else if (fieldList[j+1] == 1) address += sel.value;
					}
				}
			}
		}
	}

	var request = getRequest();
	request.onreadystatechange=function()
	{
	if(request.readyState==4)
	  {
	  	console.log(request.responseText);
	  	if (request.responseText == "NONE"){
	  		alert("We could not find any matches for your selection.");
	  		CarbuilderPreloader(0);
	  	} else if (request.responseText){
	  		finalizeRefine(url.replace("step=2", "step=3"), request.responseText, 0);
	  	} else {
	  		window.location = url;
	  	}
	  }
	}
	console.log(url);
	  	
	request.open("get", address, true);
	request.send(null);
}

function PopulateCriterion(id, name, imp, sv, so, nmin, nmax, mmin, mmax, tmin, tmax){
	var nlist = null;

	nlist = document.getElementsByName("adv_search_select_imp");
	if (nlist){
		selectSelectboxItem(nlist[id], imp);
	}

	if (nlist){
		nlist = document.getElementsByName("adv_search_select_name");
		selectSelectboxItem(nlist[id], name);
		criterionSelected(nlist[id], document.getElementById("caroption_"+id));
	}

	nlist = document.getElementsByName("adv_search_stringValue");
	if (nlist){
		nlist[id].value = sv;
	}

	nlist = document.getElementsByName("adv_search_stringOptionValues");
	if (nlist){
		selectSelectboxItem(nlist[id], so);
	}

	nlist = document.getElementsByName("adv_search_numMinValue");
	if (nlist){
		nlist[id].value = nmin;
	}

	nlist = document.getElementsByName("adv_search_numMaxValue");
	if (nlist){
		nlist[id].value = nmax;
	}

	nlist = document.getElementsByName("adv_search_moneyMinValue");
	if (nlist){
		nlist[id].value = mmin;
	}

	nlist = document.getElementsByName("adv_search_moneyMaxValue");
	if (nlist){
		nlist[id].value = mmax;
	}

	nlist = document.getElementsByName("adv_search_techSpecMinValue");
	if (nlist){
		nlist[id].value = tmin;
	}

	nlist = document.getElementsByName("adv_search_techSpecMaxValue");
	if (nlist){
		nlist[id].value = tmax;
	}
}

function showItem(base, itemID, title){
	var item = document.getElementById(itemID);
	if (item.style.display != "block"){
		item.style.display = "block";
		base.innerHTML = "Hide "+title;
	} else {
		item.style.display = "none";
		base.innerHTML = "Show "+title;
	}
}
var selectedVehicle1 = "";
var selectedVehicle2 = "";
var loading = 0;

function refine_cell_select(obj, id){
	var item = document.getElementById(id);
	
	if (loading == 1){
		addFeedback('BAD', "Please wait until your current comparison is loaded.");
		return;
	}
	
	if (item.checked == 1){
		obj.className = "vehicleInfo";
		item.checked = 0;
	} else {
		obj.className = "vehicleInfoSelected";		
		item.checked = 1;
	}
	
	refine_select(item);
}

function refine_select(obj){
	if (loading == 1){
		addFeedback('BAD', "Please wait until your current comparison is loaded.");
		return;
	}
	
	if (obj.checked){
		if (selectedVehicle1 == "" && selectedVehicle2 == ""){
			selectedVehicle1 = obj;
		} else if(selectedVehicle2 == "" && selectedVehicle1 != obj){
			selectedVehicle2 = obj;
		} else if (selectedVehicle2 != obj){
			selectedVehicle1 = selectedVehicle2;
			selectedVehicle2 = obj;
		}
	} else {
		if(selectedVehicle1 == obj){
			selectedVehicle1 = selectedVehicle2;
			selectedVehicle2 = "";
		} else if (selectedVehicle2 == obj){
			selectedVehicle2 = "";
		}
	}
	
	
	if((selectedVehicle1 != "" || selectedVehicle2 != "") 
		&& !(selectedVehicle1 != "" && selectedVehicle2 != "")){
		refine_sendSelect(selectedVehicle1);
		clearFeedback('GOOD');
		clearFeedback('BAD');
		addFeedback('GOOD', "Click Continue to configure this vehicle or select another car to compare.");
		continueButtonEnable(1);
	} else if (selectedVehicle1 != "" && selectedVehicle2 != ""){
		continueButtonEnable(0);
		loading = 1;
		var address = "ajax/carbuilder/refine_compare.php?car_style1=" + selectedVehicle1.value +"&car_style2="+selectedVehicle2.value;
		var temp = "";
		var request = getRequest();
		clearFeedback('GOOD');
		addFeedback('BAD', "We are loading your comparison information...");
		request.onreadystatechange=function()
		{
		if(request.readyState==4)
		  {
			var arr = xml2array(request.responseXML.documentElement);
			var cdata = new Array();
			var cstyle = new Array();
			var i = 0;
			for (var c in arr['pmtcarbuilder']['comparison']){
				cdata[i] = arr['pmtcarbuilder']['comparison'][c]['comparisonItems'];
		   		cstyle[i] = arr['pmtcarbuilder']['comparison'][c]['comparisonConfiguration']['style'];
		   		i++;
			}
			
			
			var vimg = document.getElementById("refine_v1_image");
			var vhead = document.getElementById("refine_v1_header");
			var vlist = document.getElementById("refine_v1_list");
			var vcbx = document.getElementById("refine_v1_data");
		
			var vlistentry = "";
			
			vimg.src = cstyle[1]['stockPhotoUrl'];
			//vimg.width = 320;
			//vimg.height = 240;
			vimg.alt = cstyle[1]['modelYear']+" "+cstyle[1]['divisionName']+" "+cstyle[1]['consumerFriendlyModelName']+" "+cstyle[1]['consumerFriendlyStyleName'];
			vhead.innerHTML = "Advantages for the "+cstyle[1]['modelYear']+" "+cstyle[1]['divisionName']+" "+cstyle[1]['consumerFriendlyModelName']+" "+cstyle[1]['consumerFriendlyStyleName'];			
			temp = selectedVehicle1.id;
			vcbx.value = temp.substr(8);
			
			if (cdata[0]){
				refine_compare_AddList(vlist, cdata[0]['entry1']);
			} else {
				refine_compare_AddList(vlist, new Array());
			}

			
			vimg = document.getElementById("refine_v2_image");
			vhead = document.getElementById("refine_v2_header");
			vlist = document.getElementById("refine_v2_list");
			vcbx = document.getElementById("refine_v2_data");
			
			vimg.src = cstyle[0]['stockPhotoUrl'];
			//vimg.width = 320;
			//vimg.height = 240;
			vimg.alt = cstyle[0]['modelYear']+" "+cstyle[0]['divisionName']+" "+cstyle[0]['consumerFriendlyModelName']+" "+cstyle[0]['consumerFriendlyStyleName'];
			vhead.innerHTML = "Advantages for the "+cstyle[0]['modelYear']+" "+cstyle[0]['divisionName']+" "+cstyle[0]['consumerFriendlyModelName']+" "+cstyle[0]['consumerFriendlyStyleName'];			
			temp = selectedVehicle2.id;
			vcbx.value = temp.substr(8);
			
			if (cdata[1]){
				refine_compare_AddList(vlist, cdata[1]['entry1']);
			} else {
				refine_compare_AddList(vlist, new Array());
			}
			refine_showCompare(selectedVehicle1, selectedVehicle2);
			clearFeedback('BAD');
			loading = 0;
		  }
		}
		
		request.open("get", address, true);
		request.send("");
		
	} else {
		refine_sendSelect("");
		continueButtonEnable(0);
		clearFeedback('GOOD');
		clearFeedback('BAD');
		addFeedback('BAD', 'Select a vehicle to proceed.');
	}	
}

function refine_sendSelect(obj){
	if (obj != ""){
		var ind = obj.id;
		var address = "ajax/carbuilder/refine_selected.php?sind=" + ind.substr(8) + "&sid=" + obj.value;
	} else {
		var address = "ajax/carbuilder/refine_selected.php?sind=&sid=";
	}
	var request = getRequest();
	request.open("get", address, true);
	request.send("");
}

function refine_compare_AddList(listEle, listData){
	removeChildrenFromNode(listEle);
	var i = 0;
	for (e in listData){
		if (listData[e]['comparisonResultType'] == "Advantage"){
			var vlistentrydata = listData[e]['naturalLanguageDescription'];
			var newentry = document.createElement('li');
			if (i%2 == 0){
				newentry.setAttribute('class', "normal");
			} else {
				newentry.setAttribute('class', "alt");
			}
			newentry.innerHTML = vlistentrydata;
			listEle.appendChild(newentry);
			i++;
		}
	}
	if (i == 0){
		var vlistentrydata = "We're sorry, this vehicle has no noticeable comparables. Only the available options are different.";
		var newentry = document.createElement('li');
		newentry.setAttribute('class', "normal");
		newentry.innerHTML = vlistentrydata;
		listEle.appendChild(newentry);		
	}
}

function refine_showCompare(sV1, sV2){
	var compEle = document.getElementById("refine_compare_overlay");
	if (sV1 != "" && sV2 != ""){
		compEle.style.display = "block";
		//TODO set return paramters
	} else {
		compEle.style.display = "none";
	}
}

function refine_hideCompare(ind){
	if (ind == 0){
		var v1 = selectedVehicle1.parentNode;
		refine_cell_select(v1, selectedVehicle1.id);		
		//sv1 again because cell_select will swap it
		var v2 = selectedVehicle1.parentNode;
		refine_cell_select(v2, selectedVehicle1.id);
	} else {
		//Unset ind car
		var cbx = document.getElementById("refine_v"+ind+"_data");
		var truIND = cbx.value;		
		var uncheck = document.getElementById("vehicle_"+truIND);		
		refine_cell_select(uncheck.parentNode, "vehicle_"+truIND);
	}
	
	var compEle = document.getElementById("refine_compare_overlay");
	compEle.style.display = "none";
}

function finalizeRefine(url, styleID, ind){
	//CarbuilderPreloader(1);
	
	var address = "ajax/carbuilder/refine_finalize.php?car_style=" + styleID+"&style_index="+ind;
	
	console.log(address);
	
	//clearFeedback('GOOD');
	//clearFeedback('BAD');
	//addFeedback('GOOD', "Submitting your information...");
	
	var request = getRequest();
	request.onreadystatechange=function()
	{
	if(request.readyState==4)
	  {
	  	window.location = url;
	  }
	}
	request.open("get", address, true);
	request.send("");
}



/* This is for dynamically creating the table, unused atm */

function getStyles(modelYear, makeId, modelName){
	var request = getRequest();
    request.open("get", "ajax/carbuilder/car_styles.php?modelYear=" + modelYear + "&makeId=" + makeId + "&modelName="+modelName, false);
    request.send("");	
    
    var arr = xml2array(request.responseXML.documentElement);
    var car_styles = arr['pmtcarbuilder']['carstyle'];
    return car_styles;    
}


function refine_AddStyles(styles){
	for (var style in styles){
		var info = styles[style];
		refine_AddStyleToHeader(info);
	}
	refine_AddStyleToTable();
}

var refine_style_count = 0;
function refine_AddStyleToHeader(style){
	var trow = document.getElementById("refine_tableheaderRow");
	var ymm = style['modelYear']+" "+style['divisionName']+" "+style['consumerFriendlyModelName']+" "+style['consumerFriendlyStyleName'];
		
	newth = document.createElement('th');
	newth.setAttribute('class', "vehicleInfo");
	
	newimg = document.createElement('img');
	if (style['stockPhotoUrl']){
		newimg.setAttribute('src', style['stockPhotoUrl']);
	} else {
		newimg.setAttribute('src', "images/default100x75.jpg");
	}
	newimg.setAttribute('width', 100);
	newimg.setAttribute('height', 75);
	newimg.setAttribute('alt', ymm);
	newimg.setAttribute('title', ymm);
	
	newh4 = document.createElement('h4');
	newh4.innerHTML = ymm;
	
	newth.appendChild(newimg);
	newth.appendChild(newh4);
		
	trow.appendChild(newth);
	
	refine_style_count = 1;
}

function refine_AddStyleToTable(){
	var request = getRequest();
    request.open("get", "ajax/carbuilder/refine_sbs.php", false);
    request.send("");	
    
    var arr = xml2array(request.responseXML.documentElement);
    var groups = arr['pmtcarbuilder']['group'];
    
    var thumbs = document.getElementById("thumbsUpHolder");
    thumbs.setAttribute("rowspan", "1");
    
    for (var g in groups){
    	refine_AddCategory(groups[g]);
    }
}

function refine_AddCategory(category){
	var tb = document.getElementById("refine_styles_tbody");
	
	//Create the new category row
	var newtr = document.createElement('tr');
	newtr.setAttribute('class',"category");
	
	//create the data element for the new row
	var newtd = document.createElement('td');
	
	//create the blank element for the new row
	var newtd2 = document.createElement('td');
	newtd2.setAttribute('rowspan',"1");
	
	//create the h4 element for inside the new data element
	newh4 = document.createElement('h4');
	newh4.innerHTML = category['groupName'];
	
	newtd.appendChild(newh4);
	newtr.appendChild(newtd);
	newtr.appendChild(newtd2);
	tb.appendChild(newtr);
	
	var thumbs = document.getElementById("thumbsUpHolder");
    thumbs.setAttribute("rowspan",  thumbs.getAttribute("rowspan")+1);
    
    var items = category['comparisonItems'];
    var entries = items['entry1'];
           
    for (e in entries){
		refine_AddFeature(entries[e]);
		thumbs.setAttribute("rowspan",  thumbs.getAttribute("rowspan")+1);
	}
}

function refine_AddFeature(item){
	var tb = document.getElementById("refine_styles_tbody");
	
	//Create the new feature row
	var newtr = document.createElement('tr');
	newtr.setAttribute('class',"vehicleData");
	
	//create the data element for the new row
	var newtd = document.createElement('td');
	newtd.innerHTML = item['featureDescription'];
	
	newtr.appendChild(newtd);
	
	if (item['comparisonValues']){
		var compItems = item['comparisonValues']['entry3'];
		
		
		for(e in compItems){
			//create the data element for the new row
			newtd = document.createElement('td');
			if (compItems[e] != ""){
				newtd.innerHTML = compItems[e];
			} else {
				newtd.innerHTML = "&nbsp;";
			}
			newtr.appendChild(newtd);
		}
	}
	
	tb.appendChild(newtr);
}


function vehicleCatExpand(grp, ind){
	var grpDiv = document.getElementById(grp+ind);
	var listUl = document.getElementById(grp+ind+"_list");
	var btnImg = document.getElementById(grp+ind+"_button");
	var btnStr = btnImg.className;
	var btnSpan = "";
	var btnWords = "";
	
	
	for (var i = 0; i < btnImg.childNodes; i++){
		if (btnImg.childNodes[i].tagName == "SPAN" || btnImg.childNodes[i].tagName == "span"){
			btnSpan = btnImg.childNodes[i];
		}
	}
	if (btnStr.indexOf("_open") == -1){
		listUl.style.display = "block";
		btnImg.className = "veh_opt_cat_button_open";
		btnWords = "Press to hide the details";
	} else {
		listUl.style.display = "none";
		btnImg.className = "veh_opt_cat_button";
		btnWords = "Press to expand the details";
	}
	btnSpan.innerHTML = btnWords;
}

function optionSelect(opt, catID, doCheck){
	if (opt.disabled=="disabled" || opt.disabled==true ){
		return;
	}
	if (doCheck){
		if (opt.type!="radio"){
			opt.checked = !opt.checked;
		} else {
			if (opt.checked == 1) return;
			opt.checked = 1;
		}
	}
	
	
	var address = "ajax/carbuilder/options_poll.php?optionCode="+opt.value;
	clearFeedback("BAD");
	addFeedback("BAD", "Loading new option information...");
	
	var request = getRequest();
	request.onreadystatechange=function()
	{
	if(request.readyState==4)
	  {
	  	var arr = xml2array(request.responseXML.documentElement);
	
	
		var status = arr['pmtcarbuilder']['status'];
		var config = arr['pmtcarbuilder']['configuration'];
		var style = config['style'];
		var state = style['configurationState'];
		
		var orig = arr['pmtcarbuilder']['originatingChromeOptionCode'];
		var oadd = arr['pmtcarbuilder']['originatingOptionAnAddition'];
		var addaff = arr['pmtcarbuilder']['additionAffectedChromeOptionCodes'];
		var delaff = arr['pmtcarbuilder']['deletionAffectedChromeOptionCodes'];
		var clic = arr['pmtcarbuilder']['conflictResolvingChromeOptionCodes'];
		var rtog = arr['pmtcarbuilder']['requiresToggleToResolve'];
		
		if (status == "None"){
			UpdateOptionTable(config['options']['entry2']);
			UpdateOptionPrices(catID, config);			
			clearFeedback("BAD");				
		} else if (status == "UserConfirmationNeeded"){
			//fillTestData(dump(arr));
			
			var uadd = "";
			var udel = "";
			
			
			if (addaff){
				uadd = "\nYou must also select the following options: \n";
				if (addaff['entry1']){
					for(i in addaff['entry1']){
						uadd += findOptionName(addaff['entry1'][i])+"\n";
					}
				} else {
					uadd += findOptionName(addaff)+"\n";
				}
			}
			if (delaff){
				udel = "\nYou must also remove the following options: \n";
				if (delaff['entry1']){
					for(i in delaff['entry1']){
						udel += findOptionName(delaff['entry1'][i])+"\n";
					}
				} else {
					udel += findOptionName(delaff)+"\n";
				}
			}
			var confirmed = confirm("In order to choose this option;\n"+uadd+udel+"\nDo you wish to accept?")
			if (confirmed == 0){
				restoreOptions();
				clearFeedback("BAD");
				return;
			}
			UpdateOptionTable(config['options']['entry2']);
			clearFeedback("BAD");
			
			/*
			if (addaff){
				if (addaff['entry1']){
					for(i in addaff['entry1']){
						opt = findOption(addaff['entry1'][i]);
						addOption(opt);
					}					
				} else {
					opt = findOption(addaff);
					addOption(opt);
				}
			}
			
			if (delaff){
				if (delaff['entry1']){
					for(i in delaff['entry1']){
						opt = findOption(delaff['entry1'][i]);
						removeOption(opt);
					}					
				} else {
					opt = findOption(delaff);
					removeOption(opt);
				}
			}
			*/
						
			
		} else if (status == "UserChoiceNeeded"){
			alert("Contact the sys admin please. - Choice Needed");
			return;
			
			fillTestData(dump(arr));
			
			var clist = "";
			for(i in clic['entry1']){
				clist += findOptionName(clic['entry1'][i])+"\n";
			}
			alert(clist);
		} else {
			alert("Contact the sys admin please. - "+status);
		}			
	  }
	}
	
	request.open("get", address, true);
	request.send(null);
}

function UpdateOptionTable(oarr){
	for (i in oarr) {
		var opt = oarr[i];
		var box = findOption(opt['chromeOptionCode']);
		
		if (opt['selectionState']=="Selected"||
			opt['selectionState']=="Required"||
			opt['selectionState']=="Included"){
				
			box.checked = 1;
		} else {
			box.checked = 0;
		}
		if ((box.type!="radio" && opt['selectionState']=="Excluded")||
			opt['selectionState']=="Upgraded"){
			box.disabled = "disabled";
		} else {
			box.disabled = "";
		}
	}
}

function restoreOptions(){
	var address = "ajax/carbuilder/options_restore.php";
	var request = getRequest();
	request.onreadystatechange=function()
	{
		if(request.readyState==4)
		{
			var arr = xml2array(request.responseXML.documentElement);
			var config = arr['pmtcarbuilder']['configuration'];
	  	  	UpdateOptionTable(config['options']['entry2']);
		}
	}
	request.open("get", address, true);
	request.send(null);	 
}

function findOptionName(val){
	return findOption(val).title;
}

function findOption(val){
	var tbody = document.getElementById("option_list_table_body");
	var inputs = tbody.getElementsByTagName('input');
	
	for (var i = 0; i < inputs.length; i++){
		if (inputs[i].value == val){
			return inputs[i];
		}
	}
}

/*
function addOption(opt){
	alert("Added: "+opt.title+" "+opt.type);
	var isRadio = (opt.type=="radio");
	if (!isRadio){
		opt.checked = !opt.checked;
	} else {
		opt.checked = 1;
	}
}

function removeOption(opt){
	alert("Removed: "+opt.title+" "+opt.type);
	var isRadio = (opt.type=="radio");
	if (!isRadio){
		opt.checked = !opt.checked;
	} else {
		opt.checked = 0;
	}
}*/

function UpdateOptionPrices(catID, config){
	var catItem = document.getElementById("category_total_"+catID);
	
	//Process New Option
	//Update Vehicle Pricing
	//MSRP
	var optionsTotalData = parseFloat(config['configuredOptionsMsrp']);
	var optionsTotal = document.getElementById("optionsTotal_data");
	optionsTotal.innerHTML = addCommas(optionsTotalData.toFixed(2));
	
	var msrpDiff = optionsTotalData - parseFloat(optionsTotal.innerHTML);
	if (catItem){
		var oldCatData = catItem.innerHTML;
		var newCatData = parseFloat(oldCatData) + msrpDiff;
		catItem.innerHTML = addCommas(newCatData.toFixed(2));
	}
	
	//MSRP Grand Total
	var grandTotalData = parseFloat(config['configuredTotalMsrp']);			
	var grandTotal = document.getElementById("grandTotal_data");
	if (grandTotal){
		grandTotal.innerHTML = addCommas(grandTotalData.toFixed(2));
	}
	
	
	//Invoice
	if (OPTIONS_SHOW_INVOICE_PRICE){
		var catItemInvoice = document.getElementById("category_total_invoice_"+catID);
		var optionsTotalDataInvoice = parseFloat(config['configuredOptionsInvoice']);
		var optionsTotalInvoice = document.getElementById("optionsTotal_data_invoice");
		optionsTotalInvoice.innerHTML = addCommas(optionsTotalData.toFixed(2));
		
		var invoiceDiff = optionsTotalDataInvoice - parseFloat(optionsTotalInvoice.innerHTML);
		if (catItemInvoice){
			var oldCatDataInvoice = catItemInvoice.innerHTML;
			var newCatDataInvoice = parseFloat(oldCatDataInvoice) + invoiceDiff;
			catItemInvoice.innerHTML = addCommas(newCatDataInvoice.toFixed(2));
		}
		
		//Invoice Grand Total
		var grandTotalDataInvoice = parseFloat(config['configuredTotalInvoice']);	
		var grandTotalInvoice = document.getElementById("grandTotal_data_invoice");
		if (grandTotalInvoice){
			grandTotalInvoice.innerHTML = addCommas(grandTotalDataInvoice.toFixed(2));
		}
	}
}

function finalizeOptions(url){
	var address = "ajax/carbuilder/options_finalize.php";
	var request = getRequest();
	
	request.onreadystatechange=function()
	{
	if(request.readyState==4)
	  {
	  	window.location = url;
	  }
	}
	request.open("get", address, true);
	request.send(null);
}

function showOptionRows(category, btnID){
	var btnImg = document.getElementById(btnID);
	var btnStr = btnImg.className;
	var btnSpan = "";
	var btnWords = "";
	for (var i = 0; i < btnImg.childNodes; i++){
		if (btnImg.childNodes[i].tagName == "SPAN" || btnImg.childNodes[i].tagName == "span"){
			btnSpan = btnImg.childNodes[i];
		}
	}
	if (btnStr.indexOf("_open") == -1){
		btnImg.className = "list_opt_cat_button_open";
		btnWords = "Press to hide the details";
	} else {
		btnImg.className = "list_opt_cat_button";
		btnWords = "Press to expand the details";
	}
	btnSpan.innerHTML = btnWords;
	
	var hiding = 0;
	var tbody = document.getElementById("option_list_table_body");
	for (var r = 0; r < tbody.childNodes.length; r++){
		var child = tbody.childNodes[r];
		if (child.tagName == "tr" || child.tagName == "TR"){
			if (child.className == "category"){
				if (hiding == 1){
					return;
				} else if (child == category){
					hiding = 1;
				}
			} else if (hiding == 1){
				if (child.style.display == "none"){
					child.style.display = child.od;
				} else {
					child.od = child.style.display;
					child.style.display = "none";
				}
			}
		}
	}
}
var styleId = "";

var selectedInteriorColor = "";
var selectedExteriorColor = "";

var selectedInteriorColorCode = "";
var selectedExteriorColorCode = "";

function interiorColorSelect(col, doCheck, mcode){
	if (col.disabled == true){
		return;
	}
	if (doCheck){
		col.checked = 1;
	}
	clearFeedback("GOOD");
	addFeedback("GOOD", "Saving interior color choice...");
	
	selectedInteriorColor = col.value;
	selectedInteriorColorCode = mcode;
	
	var intItem = document.getElementById("color_interior");
	intItem.innerHTML = selectedInteriorColor+" is the chosen interior color.";
	
	colorSelect(selectedInteriorColor, selectedExteriorColor, 0);
	continueButtonEnable(1);
}

function exteriorColorSelect(col, doCheck, mcode){
	if (col.disabled == true){
		return;
	}
	if (doCheck){
		col.checked = 1;
	}
	clearFeedback("GOOD");
	addFeedback("GOOD", "Saving exterior color choice...");
	addFeedback("GOOD", "Loading interior color matches...");
	
	selectedExteriorColor = col.value;
	selectedExteriorColorCode = mcode;
	
	colorSelect(selectedInteriorColor, selectedExteriorColor, 1);
}

function colorSelect(intc, extc, update){
	continueButtonEnable(0);
	var address = "ajax/carbuilder/color_select.php?interior="+intc+"&exterior="+extc;
	
	var request = getRequest();
	request.onreadystatechange=function()
	{
	if(request.readyState==4)
	  {
	  	if (update){
	  		var results =request.responseText;
	  		updateSelectableColors(results.split(";;"));
	  		UpdateColorPicture(selectedInteriorColor, selectedExteriorColor, selectedInteriorColorCode, selectedExteriorColorCode); 		
	  	}
	  	clearFeedback("GOOD");
		addFeedback("GOOD", "Click continue to proceed.");	
	  }
	}
	request.open("get", address, true);
	request.send(null);
}

function UpdateColorPicture(intc, extc, icode, ecode){
	var address = "ajax/carbuilder/color_sill.php?styleId="+styleId+"&ecode="+ecode+"&icode="+icode+"&stockPhotoUrl="+urlencode(stockImage);
	var request = getRequest();
	request.onreadystatechange=function()
	{
	if(request.readyState==4)
	  {	
	  	var results =request.responseText;
	  	results = results.split(";;");
	  	var sill_type = results[0];
	  	var sill_file = results[1];
	  	
	  	if (sill_type == 0){
	  		addFeedback("BAD", "Sorry, we could not find a matching picture for your color choice.");	
	  	} /*
	  	//We do not intend to match interior colors.
	  	else if (sill_type == 1){
	  		addFeedback("BAD", "Sorry, we could not find a matching picture for your interior color choice.");	
	  	}  	*/
	  	
		var intItem = document.getElementById("color_interior");
		intItem.innerHTML = intc+" is the chosen interior color.";
	
		var extItem = document.getElementById("color_exterior");
		if (sill_type == 0){
			extItem.innerHTML = "Shown with default exterior color. <br />"+extc+" is the chosen exterior color.";;
		} else {
			extItem.innerHTML = "Shown with "+extc+" exterior color.";
		}
		
		var colorimage = document.getElementById("vehicle_photo");
		colorimage.src = sill_file;
	  }
	}
	request.open("get", address, true);
	request.send(null);
}

function updateSelectableColors(colors){
	clearFeedback("BAD");
	var proceed = 1;
	var selected = 0;
	var options = document.getElementsByTagName('input');
	for(var i = 0; i < options.length; i++){
		var marked = 0;
		if (options[i].name == "interiorColor"){
			for(var j = 0; j < colors.length && marked == 0; j++){
				if (options[i].value == colors[j]){
					marked = 1;
				}
			}
			if (marked == 0){
				addFeedback("BAD", "You cannot choose the interior color "+options[i].value+" with this exterior color.");
				options[i].disabled = true;
				GrayOutOption(options[i].parentNode, 1);
				if (options[i].checked == true){
					proceed = 0;
				}
			} else {
				options[i].disabled = false;
				GrayOutOption(options[i].parentNode, 0);
			}
			if (options[i].checked == true){
				selected = 1;
			}
		}
	}
	continueButtonEnable(proceed && selected);
}

function GrayOutOption(node, val){
	var label;
	for(var i=0; i < node.childNodes.length; i++){
		label = node.childNodes[i];
		if (label.tagName == "label" || label.tagName == "LABEL"){
			if (val){
				label.className = "color_option_grey_true";
			} else {
				label.className = "color_option_grey_false";
			}
		}
	}
}


function finalizeColors(url){
	var address = "ajax/carbuilder/color_finalize.php";
	var request = getRequest();
	
	request.onreadystatechange=function()
	{
	if(request.readyState==4)
	  {
	  	window.location = url;
	  }
	}
	request.open("get", address, true);
	request.send(null);
}
var attemptedSubmit = 0;

function cb_validateFinalizeInfo(post){
	if (post == 1 && attemptedSubmit == 0){
		return;
	}
	clearFeedback("BAD");
	clearFeedback("GOOD");
	
	var errors = 0;
	var ele = "";
	
	ele = document.getElementById("price");
	var nStr = ele.value;	
	filter=/^[\d\.,]+$/
	if (!filter.test(nStr)){
		addFeedback("BAD", "The Name Your Price field must only be digits.")
		highlightMissingInfo(ele, 1);
		errors++;
	}
	
	ele = document.getElementById("firstName");
	var fStr = ele.value;	
	filter=/^[a-zA-Z\.' ]+$/
	if (!filter.test(fStr)){
		addFeedback("BAD", "The first name field may only be letters and punctuation.")
		highlightMissingInfo(ele, 1);
		errors++;
	} else {
		lowercaseAllOfMe(ele);
		capitalizeMe(ele);
	}
	
	ele = document.getElementById("lastName");
	var lStr = ele.value;	
	filter=/^[a-zA-Z\.' ]+$/
	if (!filter.test(lStr)){
		addFeedback("BAD", "The last name field may only be letters and punctuation.")
		highlightMissingInfo(ele, 1);
		errors++;
	} else {
		lowercaseAllOfMe(ele);
		capitalizeMe(ele);
	}
	
	ele = document.getElementById("emailAddress");
	var emailStr = ele.value;
	if (!check_email(emailStr)){
		addFeedback("BAD", "The email address is not valid.")
		highlightMissingInfo(ele, 1);
		errors++;
	}
	
	//Test zipcode
	ele = document.getElementById("zipCode");
	var zipStr = ele.value;	
	var filter=/^\d{5}$/
	if (!filter.test(zipStr)){
		addFeedback("BAD", "The zipcode may only contain 5 digits.")
		highlightMissingInfo(ele, 1);
		errors++;
	}
		
	/*
	var reqTxtFields = new Array("price", "firstName", "lastName");
	var reqTxtFieldsMsg = new Array(
		"You need to fill out the Name Your Price field.", 
		"You need to fill out the First Name field.", 
		"You need to fill out the Last Name field."
	);
	for(var i = 0; i < reqTxtFields.length; i++){
		ele = document.getElementById(reqTxtFields[i]);
		if (ele.value == ""){
			highlightMissingInfo(ele, 1);
			addFeedback("BAD", reqTxtFieldsMsg[i])
			errors++;
		}
	}*/
	
	if (errors > 0){
		return 0;	
	}
	
	return 1;
}

function finalizeInfo(url){
	attemptedSubmit = 1;
	
	if (!cb_validateFinalizeInfo()){
		return 0;
	}
	
	var finalString = "ajax/carbuilder/info_finalize.php?";
	var txtFields = new Array("price", "firstName", "lastName", "emailAddress", 
							"streetAddress01", "streetAddress02", "city", "zipCode",
							"phoneArea", "phoneNumber1", "phoneNumber2", "phoneExt",
							"phone2Area", "phone2Number1", "phone2Number2", "phone2Ext");
	
							 
	for(var i = 0; i < txtFields.length; i++){
		var ele = document.getElementById(txtFields[i]);
		if (ele){
			finalString += txtFields[i]+"="+urlencode(ele.value)+"&";
		} else {
			alert(txtFields[i]);
		}
	}
	
	var stateEle = document.getElementById("state");
	finalString += "state="+urlencode(stateEle.options[stateEle.options.selectedIndex].value)+"&";
	
	var commentsEle = document.getElementById("comments");
	finalString += "comments="+urlencode(commentsEle.value)+"&";
	
	var ratingEle = document.getElementById("rating");
	finalString += "rating="+urlencode(ratingEle.value)+"&";
	
	var maillistEle = document.getElementById("info_mail_yes");
	if (maillistEle.checked){
		finalString += "mailinglist=1";	
	} else {
		finalString += "mailinglist=0"
	}
	
	
	addFeedback("GOOD", "Submitting your information...")
	
	var request = getRequest();
    request.onreadystatechange=function()
	{
	if(request.readyState==4)
	  {
	 	if (request.responseText){
	    	clearFeedback("GOOD");
	    	addFeedback("BAD", request.responseText);
	    } else {
	    	window.location = url;
	    }
	  }
	}
    request.open("get", finalString, true);
    request.send(null);	    
    return 1;
}

function highlightMissingInfo(ele, force){
	if (ele.value == "" || force == 1){
		ele.style.backgroundColor = "#FF8888";
	} else {
		ele.style.backgroundColor = "#FFFFFF";
	}
}


function selectStars(star, num){
	var rating = document.getElementById("rating");
	rating.value = num;
	
	var starholder = star.parentNode;
	for (var i = 4; i >= 0; i--){
		var cstar = starholder.childNodes[i];
		if (i >= num){
			cstar.className = "star";
		} else {
			cstar.className = "starOn";
		}
	}
}
/*
	NOTE: As these become in the process of being converted,
		  please comment out the functions from '_site_reviewed_js.js'
		  so they do not clash with this file.

	Files:	includes/js/config.js
			includes/replaceables.php

			pmt/js/sites.js
			pmt/js/slideshow.js
			pmt/js/swfobject.js
			pmt/js/ajax.js
			pmt/js/generic.js
			pmt/js/chooseDate.js
			pmt/js/overlib_mini.js
			pmt/js/financing.js
			pmt/js/replacement.js
			pmt/js/inventory.js
			pmt/js/PageOverlay.js
			pmt/js/carbuilder/util.js
			pmt/js/carbuilder/search.js
			pmt/js/carbuilder/refine.js
			pmt/js/carbuilder/options.js
			pmt/js/carbuilder/color.js
			pmt/js/carbuilder/info.js

	*Special Case* 2 Files are local to the website, I can't imagine any of
		them use prototype or script.aculo.us code.  I am not sure
		how to handle them.
*/

/********************************************************************************
| pmt/js/sites.js 																|
********************************************************************************/
// NOTE: There are some more functions in this file that A) Could be converted from
//	tradition javascript to it's dojo variant and B) Looks as it a majority of the code
//	is no longer used and can be removed altogether.
function removeCompare(label) {
	var form = dojo.byId( 'compareForm' );
	dojo.create( 'input', { type: 'checkbox', name: 'remove[]', value: label, checked: true }, form );
	form.submit();
}
/*E*N*D**O*F**B*L*O*C*K*********************************************************/


/********************************************************************************
| pmt/js/slideshow.js 															|
********************************************************************************/

/*E*N*D**O*F**B*L*O*C*K*********************************************************/


/********************************************************************************
| pmt/js/swfobject.js 															|
********************************************************************************/

/*E*N*D**O*F**B*L*O*C*K*********************************************************/


/********************************************************************************
| pmt/js/ajax.js 																|
********************************************************************************/

/*E*N*D**O*F**B*L*O*C*K*********************************************************/


/********************************************************************************
| pmt/js/generic.js 															|
********************************************************************************/

/*E*N*D**O*F**B*L*O*C*K*********************************************************/


/********************************************************************************
| pmt/js/chooseDate.js 															|
********************************************************************************/

/*E*N*D**O*F**B*L*O*C*K*********************************************************/


/********************************************************************************
| pmt/js/overlib_mini.js 														|
********************************************************************************/

/*E*N*D**O*F**B*L*O*C*K*********************************************************/


/********************************************************************************
| pmt/js/financing.js 															|
********************************************************************************/
// NOTE CONVERTED CODE IS LOCATED AT: pmt/js/dhd/site/Calculator.js
// NOTE CONVERTED CODE IS LOCATED AT: pmt/js/dhd/site/Calculator.js
// NOTE CONVERTED CODE IS LOCATED AT: pmt/js/dhd/site/Calculator.js
// NOTE CONVERTED CODE IS LOCATED AT: pmt/js/dhd/site/Calculator.js
// NOTE CONVERTED CODE IS LOCATED AT: pmt/js/dhd/site/Calculator.js
/*E*N*D**O*F**B*L*O*C*K*********************************************************/


/********************************************************************************
| pmt/js/replacement.js 														|
********************************************************************************/

/*E*N*D**O*F**B*L*O*C*K*********************************************************/


/********************************************************************************
| pmt/js/inventory.js 															|
********************************************************************************/
function Scroll(direction, tabClass, containerClass) {
	var tabs,				// The HTMLEntity Objects of the tabs.
		tabsContent,		// The HTMLEntity Objects of the tabs content.
		tabContentWidth,	// The width of the container we are scrolling.
		tabCount,			// The number of tabs, and containers.
		tabCurrent,			// The 0..n value of the current tab.
		tabIntended,		// The 0..n value of the intended tab.
		tabClassArr,		// The array of class names for the tabs.
		slideDistance;		// The distance our content will need to slide over for the effect.

	// Store the tab elements for later use, we typically can have a div or li setup.
	if( tabClass == null ) tabClass = 'mediaButton';
	tabs = dojo.query( 'div.' + tabClass );
	if( !tabs.length ) tabs = dojo.query( 'li.' + tabClass );

	// Store the tab content elements for later use, we typically can have a div or li setup.
	if( containerClass == null ) containerClass = 'media_section';
	tabsContent = dojo.query( 'div.' + containerClass );
	if( !tabsContent.length ) tabsContent = dojo.query( 'li.' + containerClass );

	// All tabs should be the same width.
	var tabsCoords = dojo.coords( tabsContent[ 0 ] );
	tabContentWidth = tabsCoords.w;
	tabCount = tabs.length;

	// Loop through the tabs
	dojo.forEach( tabs, function( data, ndx ) {
		if( dojo.hasClass( data, 'tabActive' ) ) {
			// We have found the current active tab.
			tabCurrent = ndx;

			// Set current active tab, as normal.
			dojo.removeClass( data, 'tabActive' );
			dojo.addClass( data, 'tabNormal' );
		}
	});

	// If direction is positive, we are going "next", if it is negative, we are going "prev".
	// Find the intended tab.
	tabIntended = tabCurrent + direction;
	// Did we wrap around on the left?
	if( tabIntended < 0 ) {
		// tabCount should be 1..n, so subtract 1 to shift to 0..n
		tabIntended = tabCount - 1;
	// Did we wrap around on the right?
	} else if ( tabIntended + 1 > tabCount ) {
		tabIntended = 0;
	}

	// Set the intended tab, as active.
	dojo.removeClass( tabs[ tabIntended ], ["tabActive", "tabNormal", "tabInactive"] );
	dojo.addClass( tabs[ tabIntended ], 'tabActive' );

	var scaler = 1;
	if( tabCurrent - tabIntended < 0 ) {
		scaler = -1;
	}
	// Find the total distance we need to slide our main div over by.
	slideDistance = scaler * ( Math.abs( tabCurrent - tabIntended ) * tabContentWidth );
	var mcNode = dojo.byId( 'media_content' );
	var mcCoords = dojo.coords( mcNode );
	var toLeft = mcCoords.l + slideDistance;
	// Move the content over.
	dojo.fx.slideTo({node: 'media_content', left: toLeft }).play();
}

function ScrollTab(item, name, alltabs, tabContainer){
	var curActiveTab = 1;

	// Set the default tab class value, if it isn't set already.
	if( tabContainer == null ) tabContainer = 'media_buttonArea';

	// Tab container element.
	var tabCont = dojo.byId( tabContainer );

	// Typically we deal with either DIVs, or LIs, so lets get em.
	//var tabs = $$( '#' + tabContainer + ' div');
	//if( !tabs.length ) tabs = $$( '#' + tabContainer + ' li');
	var tabs = dojo.query( '#' + tabContainer + ' div' );
	if( !tabs.length ) tabs = dojo.query( '#' + tabContainer + ' li' );

	if( item ) {
		// Loop through all the tabs.
		dojo.forEach( tabs, function( data, ndx ) {
			if( dojo.hasClass( data, 'tabActive' ) ) {
				dojo.removeClass( data, 'tabActive' );
				dojo.addClass( data, 'tabNormal' );
				curActiveTab = ndx + 1;
			}
		});

		// Set the active tab.
		dojo.removeClass( item, ["tabActive", "tabNormal", "tabInactive"] );
		dojo.addClass( item, 'tabActive' );
	}

	//
	// Handle Transition, or the scroll.
	//
	if( name ) {
		var clickedTab;
		dojo.forEach( tabs, function( data, ndx ) {
			if( dojo.hasClass( data, 'tabActive' ) ) {
				clickedTab = ndx + 1;
			}
		});

		var scaler = 1;
		if( curActiveTab - clickedTab < 0 ) {
			scaler = -1;
		}

		var slideDistance = scaler * Math.abs( curActiveTab - clickedTab ) * dojo.coords( name ).w;
		var mcNode = dojo.byId( 'media_content' );
		var mcCoords = dojo.coords( mcNode );
		var toLeft = mcCoords.l + slideDistance;
		dojo.fx.slideTo({node: 'media_content', left: toLeft }).play();
	}
}

function checkCarfax(vin, openLocation) {
	if (vin.length!=17) {
		dojo.query( '.badResponse' ).forEach( function( node ) { node.innerHTML = 'You have entered an invalid VIN.'; } );
	} else { window.open( openLocation + vin ); }
}

// TODO: This can be updated more elegantly to use dojo, I'm skipping that becuase this should work currently.
function dynamicDay( dayID ) {
	// Get the three drop down elements.
	var eDay = dojo.byId( dayID );
	var eMonth = dojo.byId( dayID.replace( 'Day', 'Month' ) );
	var eYear = dojo.byId( dayID.replace( 'Day', 'Year' ) );

	// If the three drop down elements are present and accounted for...
	if( eDay && eMonth && eYear ) {
		var totalDays = new Date(eYear.value, eMonth.value, 0).getDate();
		var eDays = dojo.query( '#' + dayID + '> *' );
		var eDaysCount = eDays.length - 1;
		if( eDaysCount > totalDays ) {
			for( var i = eDaysCount; i > totalDays; i-- ) {
				// remove
				eDays[ i ].remove();
			}
		} else if( eDaysCount < totalDays ) {
			for( var i = eDaysCount + 1; i <= totalDays; i++ ) {
				// append
				var attrs = {
					value	: i
				};

	            var link = new Element( 'option', attrs );
	            link.update(i);
	            eDay.insert(link);
			}
		}
	}
}
/*E*N*D**O*F**B*L*O*C*K*********************************************************/


/********************************************************************************
| pmt/js/PageOverlay.js 														|
********************************************************************************/
// NOTE CONVERTED CODE IS LOCATED AT: pmt/js/dhd/site/PageOverlay.js
// NOTE CONVERTED CODE IS LOCATED AT: pmt/js/dhd/site/PageOverlay.js
// NOTE CONVERTED CODE IS LOCATED AT: pmt/js/dhd/site/PageOverlay.js
// NOTE CONVERTED CODE IS LOCATED AT: pmt/js/dhd/site/PageOverlay.js
// NOTE CONVERTED CODE IS LOCATED AT: pmt/js/dhd/site/PageOverlay.js
/*E*N*D**O*F**B*L*O*C*K*********************************************************/


/********************************************************************************
| pmt/js/carbuilder/util.js														|
********************************************************************************/

/*E*N*D**O*F**B*L*O*C*K*********************************************************/


/********************************************************************************
| pmt/js/carbuilder/search.js													|
********************************************************************************/

/*E*N*D**O*F**B*L*O*C*K*********************************************************/


/********************************************************************************
| pmt/js/carbuilder/refine.js													|
********************************************************************************/

/*E*N*D**O*F**B*L*O*C*K*********************************************************/


/********************************************************************************
| pmt/js/carbuilder/options.js													|
********************************************************************************/

/*E*N*D**O*F**B*L*O*C*K*********************************************************/


/********************************************************************************
| pmt/js/carbuilder/color.js													|
********************************************************************************/

/*E*N*D**O*F**B*L*O*C*K*********************************************************/


/********************************************************************************
| pmt/js/carbuilder/info.js														|
********************************************************************************/

/*E*N*D**O*F**B*L*O*C*K*********************************************************/
function LoadTabCache( webID, carID, tabName, loader ) {
	var xhrArgs = {
		url: JS_WEBROOT + '/ajax.php?q=LoadTabCache',
		content: { websiteID: webID, carID: carID, tab: tabName },
		load: dojo.hitch( this, function( data ) {
			dojo.byId( tabName ).innerHTML = data;
			var scripts = dojo.query("script", tabName );
			scripts.forEach(function(scriptItem){
				dojo.eval(scriptItem.text);
				dojo.destroy(scriptItem);
			});
		})
	};
	dojo.xhrPost( xhrArgs );
}

function ServiceFade( toggleButton ) {
	dojo.require( 'dojo.fx' );
	if( toggleButton.checked ) {
		dojo.fadeIn( { node: 'serviceInfoOther' } ).play();
	} else {
		dojo.fadeOut( { node: 'serviceInfoOther' } ).play();
	}
}

function toggleShareThis( bookmarkStr ) {
	dojo.require( 'dojo.fx' );
	if( dojo.byId( bookmarkStr ) ) {
		var bkmrk = dojo.byId( bookmarkStr );
		if( dojo.style( bkmrk, 'display' ) == 'none' ) {
			dojo.fadeIn( { node: bkmrk, duration: 500, onBegin: function() { dojo.style( bkmrk, 'display', 'block' ) } } ).play();
		} else {
			dojo.fadeOut( { node: bkmrk, duration: 500, onEnd: function() { dojo.style( bkmrk, 'display', 'none' ) } } ).play();
		}
	}
}

function toggleAdvancedSearch( advSearchStr ) {
	dojo.require( 'dojo.fx' );
	var xhrArgs = {
		url: JS_WEBROOT + '/ajax.php?q=storeAdvSearchState'
	};
	if( dojo.byId( advSearchStr ) ) {
		var advSearch = dojo.byId( advSearchStr );
		if( dojo.style( advSearch, 'display' ) == 'none' ) {
			dojo.fadeIn( { node: advSearch, duration: 500, onBegin: function() { dojo.style( advSearch, 'display', 'block' ) } } ).play();
			dojo.mixin( xhrArgs, { content: { advSearch_state: 1 } } );
			dojo.xhrPost( xhrArgs );
		} else {
			dojo.fadeOut( { node: advSearch, duration: 500, onEnd: function() { dojo.style( advSearch, 'display', 'none' ) } } ).play();
			dojo.mixin( xhrArgs, { content: { advSearch_state: 0 } } );
			dojo.xhrPost( xhrArgs );
		}
	}
}

function toggleOverview( overviewStr, overviewArr ) {
	var _cont = 'DetailsContainer';	// Append to get container
	var _list = 'DetailsList';		// Append to get list button

	if( dojo.byId( overviewStr + _list ) && dojo.byId( overviewStr + _cont ) ) {
		if( dojo.isArray( overviewArr ) ) {
			dojo.forEach( overviewArr, dojo.hitch( this, function( data ) {
				var list = dojo.byId( data + _list );
				var cont = dojo.byId( data + _cont );
				if( list && cont && ( data != overviewStr ) ) {
					dojo.style( cont, 'display', 'none' );
					dojo.removeClass( list, 'activeCategory' );
				}
			}));
		}
		var list = dojo.byId( overviewStr + _list );
		var cont = dojo.byId( overviewStr + _cont );

		dojo.fadeIn( { node: cont, duration: 500, onBegin: function() { dojo.style( cont, 'display', 'block' ) } } ).play();
		dojo.addClass( list, 'activeCategory' );
	}
}


function toggleItem(item, force) {
	if (!dojo.byId(item)){
		return;
	}
	if (dojo.style(item, 'display') == "block" || force == "false") {
		dojo.fadeOut({ node:item, onEnd: function(){ dojo.style(item, 'display', 'none'); } }).play();
	} else if (dojo.style(item, 'display') == "none" || force == "true") {
		dojo.fadeIn({ node:item, onBegin: function(){ dojo.style(item, 'display', 'block'); } }).play();
	}
}

function openzView(commandUrl, div_id, invID, videoID) {
	var xhrArgs = {
		url: JS_WEBROOT + commandUrl + '&invID=' + invID + '&videoID=' + videoID,
		load: function( data ) {
			dojo.byId( div_id ).innerHTML = data;
		}
	};
	dojo.xhrPost( xhrArgs );
}


