/* !getElementsByClassName replacement that works with IE */
/*
	Developed by Robert Nyman, http://www.robertnyman.com
	Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/	
var getElementsByClassName = function (className, tag, elm){
	if (document.getElementsByClassName) {
		getElementsByClassName = function (className, tag, elm) {
			elm = elm || document;
			var elements = elm.getElementsByClassName(className),
				nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
				returnElements = [],
				current;
			for(var i=0, il=elements.length; i<il; i+=1){
				current = elements[i];
				if(!nodeName || nodeName.test(current.nodeName)) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	else if (document.evaluate) {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = "",
				xhtmlNamespace = "http://www.w3.org/1999/xhtml",
				namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
				returnElements = [],
				elements,
				node;
			for(var j=0, jl=classes.length; j<jl; j+=1){
				classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
			}
			try	{
				elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
			}
			catch (e) {
				elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
			}
			while ((node = elements.iterateNext())) {
				returnElements.push(node);
			}
			return returnElements;
		};
	}
	else {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = [],
				elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
				current,
				returnElements = [],
				match;
			for(var k=0, kl=classes.length; k<kl; k+=1){
				classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
			}
			for(var l=0, ll=elements.length; l<ll; l+=1){
				current = elements[l];
				match = false;
				for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
					match = classesToCheck[m].test(current.className);
					if (!match) {
						break;
					}
				}
				if (match) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	return getElementsByClassName(className, tag, elm);
};


/* !Header Glider Code */
/**
 * @author Bruno Bornsztein <bruno@missingmethod.com>
 * @copyright 2007 Curbly LLC
 * @package Glider
 * @license MIT
 * @url http://www.missingmethod.com/projects/glider/
 * @version 0.0.4
 * @dependencies prototype.js 1.5.1+, effects.js
 */

/*  Thanks to Andrew Dupont for refactoring help and code cleanup - http://andrewdupont.net/  */

BGlider = Class.create();
Object.extend(Object.extend(BGlider.prototype, Abstract.prototype), {
	initialize: function(wrapper, options){
	    this.scrolling  = false;
	    this.wrapper    = $(wrapper);
	    this.scroller   = this.wrapper.down('div.scroller');
	    this.sections   = this.wrapper.getElementsBySelector('div.section');
	    this.options    = Object.extend({ controlsEvent:'click', duration: 1.0, frequency: 3 }, options || {});

	    this.sections.each( function(section, index) {
	      section._index = index;
	    });    

	    this.events = {
	      click: this.click.bind(this)
	    };

	    this.addObservers();
			if(this.options.initialSection) this.moveTo(this.options.initialSection, this.scroller, { duration:this.options.duration });
			if(this.options.autoGlide) this.start();
	  },
	
  addObservers: function() {
		this.controls = this.wrapper.getElementsBySelector('.controls a');
		this.controls.invoke('observe', this.options.controlsEvent, this.events.click);
  },	

  click: function(event) {
		this.stop();
    var element = Event.findElement(event, 'a');
    if (this.scrolling) this.scrolling.cancel();
    
		moveTo = this.wrapper.down('#'+element.href.split("#")[1])
    this.moveTo(moveTo, this.scroller, { duration:this.options.duration });     
    Event.stop(event);

		this.controls.each(function(control){
			if (control == element) {
				control.addClassName("active")
			}else{
				control.removeClassName("active")
			}			
		});
  },

	moveTo: function(element, container, options){
			this.current = $(element);

			Position.prepare();
	    var containerOffset = Position.cumulativeOffset(container),
	     elementOffset = Position.cumulativeOffset($(element));

		  this.scrolling 	= new Effect.SmoothScroll(container, 
				{duration:options.duration, x:(elementOffset[0]-containerOffset[0]), y:(elementOffset[1]-containerOffset[1])});
		  return false;
		},
		
  next: function(){
    if (this.current) {
      var currentIndex = this.current._index;
      var nextIndex = (currentIndex >= (this.sections.length - 6)) ? 0 : currentIndex + 6;   
    } else var nextIndex = 6;

    this.moveTo(this.sections[nextIndex], this.scroller, { 
      duration: this.options.duration
    });
  },	
  previous: function(){
    if (this.current) {
      var currentIndex = this.current._index;
      var prevIndex = (currentIndex <= 5) ? this.sections.length - 5 : currentIndex - 6;
    } else var prevIndex = 12;
    
    this.moveTo(this.sections[prevIndex], this.scroller, { 
      duration: this.options.duration
    });
  },

	stop: function()
	{
		clearTimeout(this.timer);
	},
	
	start: function()
	{
		this.periodicallyUpdate();
	},
		
	periodicallyUpdate: function()
	{ 
		if (this.timer != null) {
			clearTimeout(this.timer);
			this.next();
		}
		this.timer = setTimeout(this.periodicallyUpdate.bind(this), this.options.frequency*1000);
	}

});

Effect.SmoothScroll = Class.create();
Object.extend(Object.extend(Effect.SmoothScroll.prototype, Effect.Base.prototype), {
  initialize: function(element) {
    this.element = $(element);
    var options = Object.extend({
      x:    0,
      y:    0,
      mode: 'absolute'
    } , arguments[1] || {}  );
    this.start(options);
  },
  setup: function() {
    if (this.options.continuous && !this.element._ext ) {
      this.element.cleanWhitespace();
      this.element._ext=true;
      this.element.appendChild(this.element.firstChild);
    }
   
    this.originalLeft=this.element.scrollLeft;
    this.originalTop=this.element.scrollTop;
   
    if(this.options.mode == 'absolute') {
      this.options.x -= this.originalLeft;
      this.options.y -= this.originalTop;
    } 
  },
  update: function(position) {   
    this.element.scrollLeft = this.options.x * position + this.originalLeft;
    this.element.scrollTop  = this.options.y * position + this.originalTop;
  }
});



/* !Navigation dropdown listeners */
/*
function addLoadEvent(func)
{
  var oldonload = window.onload;
  if (typeof window.onload != 'function')
  {
    window.onload = func;
  }
  else
  {
    window.onload = function()
    {
      oldonload();
      func();
    }
  }
}
*/


/* !Vehicle inventory filters */
/*
function prepSliders()
{
	var allSliders = getElementsByClassName("sliderHandle","div",$("inventory-filter"));
	for (var i=0; i<allSliders.length; i++)
	{
		allSliders[i].onmouseup = function()
		{
			document.getElementById("vsearch").submit();
		}
	}
}
addLoadEvent(prepSliders);
*/




/* !Drop-down menus */
/*
function prepDropdowns()
{
	var dropdowns = getElementsByClassName("navItem","li",$("header-nav"));
	for (var i=0; i<dropdowns.length; i++)
	{
		// activates when you mouse over any navigation list item
		dropdowns[i].onmouseover = function ()
		{	
			this.childNodes[0].className = "navLink hover";	// otherwise, just give it the hover class
			this.getElementsByClassName("navDrop")[0].style.display = "block"; // display the dropdown menu
		}
		
		// activates when you mouse out of any navigation list item
		dropdowns[i].onmouseout = function ()
		{
			this.childNodes[0].className = "navLink"; // otherwise, just drop the hover			
			this.getElementsByClassName("navDrop")[0].style.display = "none"; // hide the dropdown menu
		}
	}
}
addLoadEvent(prepDropdowns);
*/

/*
function showDropDown(thisNavDrop)
{	
	// this.childNodes[0].className = "navLink hover";
	var dropDownLink = document.getElementById(thisNavDrop+"-link");
	var dropDownDiv = document.getElementById(thisNavDrop+"-dropdown");
	dropDownLink.className = "navLink hover";
	dropDownDiv.style.display = "block";
}
function hideDropDown(thisNavDrop)
{
	//this.childNodes[0].className = "navLink";
	var dropDownLink = document.getElementById(thisNavDrop+"-link");
	var dropDownDiv = document.getElementById(thisNavDrop+"-dropdown");
	dropDownLink.className = "navLink";
	dropDownDiv.style.display = "none";
}
*/


/* !Header search box value */
function clearSearchBox(targetInput,defaultText)
{
	if (document.getElementById(targetInput).value == defaultText)
	{
		document.getElementById(targetInput).value = "";
	}
}



/* !Email obfuscator */
function sendTo(username)
{
	var hostname = "bergerchevy.com";
	var linktext = username + "@" + hostname;
	document.write("<a href=" + "mail" + "to:" + username + "@" + hostname + ">" + linktext + "</a>");
}



/* !Vehicle Photo Slider */
/*

// NOT USED ANYMORE

function showVehiclePhotos(numPhotos)
{
	if ($("photo-slider").className == 'button lite more')
	{
		//new Effect.Morph('other-photos', {style: 'display:block;' });
		new Effect.Morph('other-photos', {style: 'width:685px', duration: 0.4 });
		new Effect.Opacity('other-photos-ul', {from: 0.0, to: 1.0, duration: 0.4, delay: 0.5 });
		$("photo-slider").innerHTML = 'Hide More Photos ('+numPhotos+') &laquo;';
		$("photo-slider").className = 'button lite less';
		$("main-photo").className = 'active';
	}
	else
	{
		new Effect.Opacity('other-photos-ul', {from: 1.0, to: 0.0, duration: 0.4 });
		new Effect.Morph('other-photos', {style: 'width:1px', duration: 0.4, delay: 0.5 });
		//new Effect.Morph('other-photos', {style: 'display:none;', delay: 0.5 });
		$("photo-slider").innerHTML = 'View More Photos ('+numPhotos+') &raquo;';
		$("photo-slider").className = 'button lite more';
		$("main-photo").className = 'more';
	}
}
*/



/* !Ajax Scripts for Forms */
function createRequestObject()
{
	var ro;
	var browser = navigator.appName;
	if(browser == "Microsoft Internet Explorer")
	{
		ro = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else
	{
		ro = new XMLHttpRequest();
	}
	return ro;
}

var http = createRequestObject();

function sendemail(form) {
	//var msg = document.contactform.msg.value;
	//var name = document.contactform.name.value;
	//var email = document.contactform.email.value;
	//var subject = document.contactform.subject.value;
	//document.contactform.send.disabled=true; 
	//document.contactform.send.value='Sending....';
	var processer = '/email/'+form;
  http.open('get', '/email/contact');
  http.onreadystatechange = handleResponse;
  http.send(null);
}

function handleResponse()
{
	if(http.readyState == 4)
	{
		var response = http.responseText;
		var update = new Array();
		if(response.indexOf('|' != -1))
		{
			update = response.split('|');
			document.getElementById(update[0]).innerHTML = update[1];
		}
	}
}


/* !vehicle invetory page script */
function searchVehicles(selected_item) {
	document.getElementById('vsearch').orderby.value = selected_item;
	document.getElementById('vsearch').submit();
}


/* !Toggle advanced filter options on the vehicle inventory pages */
function showAdvanced()
{
	if (document.getElementById('show-advanced-search').className != 'moreOptions')
	{
		document.getElementById('advanced-search-options').style.display = 'none';
		document.getElementById('show-advanced-search').className = 'moreOptions';
		document.getElementById('vsearch').advs.value = 0;
	}
	else
	{
		document.getElementById('advanced-search-options').style.display = 'block';
		document.getElementById('show-advanced-search').className = 'lessOptions';
		document.getElementById('vsearch').advs.value = 1;
	}
}

function sendSearchToFriend(show)
{
	if(show == false)
	{
		document.getElementById('send-search').style.display = 'none';
	}
	else {
		document.getElementById('send-search').style.display = 'block';
	}
}

/* !pop-up window code */
function popUpWindow(uri, thisWindow, height, width)
{
	window.open(uri, thisWindow, 'height='+height+', width='+width+', menubars=no, scrollbars=yes, resizeable=0');
}

// assign this window a name of 'main' so that popup windows can reference it
window.name = "main";
