var priceEffectiveStr = "2nd March, 2009";

// brochure stuff //

	function othercheck(obj)
	{
		if(obj.options[obj.selectedIndex].value == "other")
		{
			document.getElementById("othermake").style.visibility = "visible"; 
		}
		else
		{
			document.getElementById("othermake").style.visibility = "hidden";
		}
	}
	function switchit(obj,type)
	{
		if(type == "form"){ obj.name = "model";	}
		if(type == "gallery"){ obj.name = "model2";	}
	
		if(document.getElementById("brandlist").options[document.getElementById("brandlist").selectedIndex].value == "other")
		{ document.getElementById("make").value = document.getElementById("othermake").value; }
		else
		{ document.getElementById("make").value = document.getElementById("brandlist").options[document.getElementById("brandlist").selectedIndex].value; }
	}

	function fixPadding(objName,style, ie6, ie7, ff, mac)
	{
//		alert(objName + ":" + ie6 + ":" + ie7 + ":" + ff);
		if (window.XMLHttpRequest) {
			if(document.all){
				//IE7
				$(objName).setStyle(style,ie7);
			}else{
				if ($chk(mac) && navigator.platform.indexOf('Mac')>=0) {
					// browsers on a mac (differ due to fonts)
					$(objName).setStyle(style,mac);
				} else {
					//mozilla, safari, opera 9�etc
					$(objName).setStyle(style,ff);
				}
			}
		} else {
			// IE6, older browsers
			$(objName).setStyle(style,ie6);
		} 
	}

// end of brochure stuff //

function loadCSS(url_) {
  var _links = document.getElementsByTagName("link");
  if (_links.length > 0 && _links["href"] == url_) return;
  var _elstyle = document.createElement("link");
  _elstyle.setAttribute("rel", "stylesheet");
  _elstyle.setAttribute("type", "text/css");
  _elstyle.setAttribute("media", "all");
  _elstyle.setAttribute("href", url_);
  var _head = document.getElementsByTagName("head")[0];
  _head.appendChild(_elstyle);
}
		   

var ImageViewer = new Class({
	foldermap: function(path) {
		return path.replace('/small/','/large/');
	},
	initialize: function( imagelist , templateURL, foldermap) {
			if (foldermap) this.foldermap=foldermap;
			this.templateURL = templateURL;
			this.imagelist = imagelist;
			this.numImage=0;
			this.imagelist.getElements('img').each(function(item){
				item.addEvent('click', function(event){ this.clickImage(event, item); }.bind(this));
				this.numImage++;
			}.bind(this));
	},
	clickImage: function(event, img) {
            if( !img.getProperty ) {
                img.getProperty = function(key) {
                  return img[key];
                }
                img.setProperty = function(key, value) {
                  img[key] = value;
                }
            }
		var tg=img.getProperty('target');
		if (tg) {
			if (eval(tg)) return;
		}
		this.current=img;
		if (!this.container) {
			this.container = new Element('div').addClass("ImageViewer").injectTop(document.body);
			this.container.setStyle('visibility','hidden');
			this.container.makeDraggable();	
			//this.container.makeResizable();
		}
		var myAjax = new Ajax(this.templateURL, {method: 'get', update: this.container, evalScripts:true, onComplete: function() {
					this.container.getElementsBySelector('img,a').each(function(item){
					switch (item.id) {
						case 'placeholder': this.placeholder = item; return;
						break;
						case 'left': item.addEvent('click', function(event){ this.clickLeft(event, item); }.bind(this));
												this.left=item;
						break;
						case 'right': item.addEvent('click', function(event){ this.clickRight(event, item); }.bind(this));
												this.right=item;
						break;
						case 'close': item.addEvent('click', function(event){ this.clickClose(event, item); }.bind(this));												
						break;
					}
					item.addClass('active');
					with (this.container) 
					if (getStyle('visibility')!='visible') {
						var s=document.body.getSize();
						setStyle('left',(window.getScrollWidth()-850)/2);
						setStyle('top',200);
						setStyle('visibility','visible');
					}
				}.bind(this)); 
				this.updateButton();
				
			}.bind(this)}).request();
	},
	clickClose: function(event) {
		this.close();
	},
	imgIndex: function(img) {
		var count=0;
		this.imagelist.getElements('img').each(function(item){
			if (count>=0) count++;
			if (item==img) count=-count; 
		}.bind(this));	
		return -count;
	},
	updateButton: function() {
		var i=this.imgIndex(this.current);
		if (i<=1) {
			this.left.removeClass('active');
			this.left.addClass('inactive');
		} else {
			this.left.removeClass('inactive');
			this.left.addClass('active');
		}
		if (i>=this.numImage) {
			this.right.removeClass('active');
			this.right.addClass('inactive');
		} else {
			this.right.removeClass('inactive');
			this.right.addClass('active');
		}
		with (this.placeholder) 
			try {
				filters.blendTrans.Apply();
			  setProperty('src',this.foldermap(this.current.getProperty('src')));
				filters.blendTrans.Play();
			} catch (er) {
				setProperty('src',this.foldermap(this.current.getProperty('src')));			
			}
		this.container.getElementById("title").innerHTML=this.current.getProperty('title');

		// show disclaimer for particular models
		var disclaimer = '';
		var m = document.getElementById("model").options[document.getElementById("model").selectedIndex].value;
		if((m == 'rx450h' && (i == 6 || i == 1 || i == 2)) || (m == 'is250c' && (i == 2 || i == 5))) {
			disclaimer = 'Overseas model shown';
		} else if(m == 'rx450h' && (i == 3 || i == 4)) {
			disclaimer = 'Sports Luxury model shown';
		}
		document.getElementById("overseasmessage2").innerHTML = disclaimer; 
		if (disclaimer != '') {
			document.getElementById("overseasmessage2").style.fontSize = "11px";
			document.getElementById("overseasmessage2").style.color = "#666666";
		}
	},
	clickLeft: function(event, button) {
			var last = null;
			this.imagelist.getElements('img').each(function(item){
				if (item==this.current) {
					if (last) this.current = last;
				}				
				last=item;
			}.bind(this));
			this.updateButton();
	},
	clickRight: function(event, button) {
			var next = 0;
			this.imagelist.getElements('img').each(function(item){
				if (next==1) { this.current = item; next=2; }
				else if (item==this.current) {
					 next=1;
				}				
			}.bind(this));
			this.updateButton();
	},
	close: function() {
		if (this.container) {
			this.container.remove();
			this.container=null;
		}
		//this.imagelist.getElements('img').each(function(item){
		//		item.removeEvent('click');
		//	}.bind(this));
	}
});

var TabPages = new Class({
	initialize: function(tab, content, inittab, tabsource) {
		this.tabsource = tabsource;
		this.tab = $(tab), this.current = this.tab.getElement('li');
		this.tab.getElements('li').each(function(item){
			item.addEvent('click', function(event){ this.clickItem(event, item); }.bind(this));
			if (item.id==inittab) { item.addClass('activetab'); }
			if (item.hasClass('activetab')) {
				this.current=item;
			}
		}.bind(this));
		this.content = content;
		//this.refresh();
	},
	refresh: function(tabid,tab) {
		var sel=$E('select','galleryHeader');
//		if(sel.options[sel.selectedIndex].value.toLowerCase() == "isf")
		if(this.current.id == "t-colours")
		{
/*
			if((sel.options[sel.selectedIndex].value.toLowerCase() == "gs300")||(sel.options[sel.selectedIndex].value.toLowerCase() == "gs460")||(sel.options[sel.selectedIndex].value.toLowerCase() == "gs450h"))
				this.clickItem(null, "t-photos"?this.getTab("t-photos"):"t-photos");
			else
*/
				this.clickItem(null, tabid?this.getTab(tabid):this.current);
		}
		else if(this.current.id == "t-accessories")
		{
			if(sel.options[sel.selectedIndex].value.toLowerCase() == "isf")
				this.clickItem(null, "t-photos"?this.getTab("t-photos"):"t-photos");
			else
				this.clickItem(null, tabid?this.getTab(tabid):this.current);
		}
		else
			this.clickItem(null, tabid?this.getTab(tabid):this.current);
/*
		switch(document.getElementById("model").options[document.getElementById("model").selectedIndex].value)
		{
			case "gs300":
				this.clickItem(null, "t-photos"?this.getTab("t-photos"):"t-photos");
				break;
			case "gs460":
				this.clickItem(null, "t-photos"?this.getTab("t-photos"):"t-photos");
				break;
			case "gs450h":
				this.clickItem(null, "t-photos"?this.getTab("t-photos"):"t-photos");
				break;
			default:
				this.clickItem(null, tabid?this.getTab(tabid):this.current);
		}
*/
	},
	getTab: function(tabid) {
		var mytab=null;
		this.tab.getElements('li').each(function(item){
			if (item.id==tabid) mytab=item; 
		});
		return mytab;
	},
	clickItem: function(event, item) {
		if (item.getStyle('cursor')=='text') return false;
		try { unloadTab(); } catch (er) {}
		if(this.current) {
			this.current.removeClass('activetab');
		}
		try { screen.updateInterval = 200; setTimeout( function() { screen.updateInterval = 0; }, 200); } catch (er) {}
		 
	var URL=this.tabsource(item);
		var myAjax = new Ajax(URL, {method: 'get', update: this.content, evalScripts:true, onComplete: function() {
				try { screen.updateInterval = 0; } catch (er) {}
			}}).request();
		item.addClass('activetab');	
		this.current = item;
	}
});

TabPages.implement(new Options);


var ScrollViewer = new Class({
	initialize: function( wrapperid, linkid, topdivid, transit ) {
			if (topdivid) {
				var crd=$(wrapperid).getCoordinates();
				$(topdivid).setStyles({ left: crd.left, top: crd.top, width: crd.width, height: crd.height } );
			}		
			var scroll = new Fx.Scroll(wrapperid,transit);
			this.scroll=scroll;
			var rx=0;
			$(linkid).getElements("a").each(function(item) {
				
				var conid='content-'+item.id;
				$(conid).setStyles({ left: rx });
				var c=$(conid).getCoordinates();
				rx+=c.width;					
				if (item.hasClass('active')) {
					this.activelink=item;
					this.scrollto(conid);
				}
				if (!item.onclick)
				item.addEvent('click', function(event) {
					//event = new Event(event).stop();
					if (this.activelink)
					this.activelink.removeClass('active');
					this.activelink=item;
					item.addClass('active');					
					this.scrollto(conid);
				}.bind(this,conid));
			}.bind(this));
	},
	refresh: function() {
		this.scrollto(this.lastid);
	},
	scrollto: function(conid) {
		this.lastid=conid;
		this.scroll.toElement(conid);	
	},
	gotolink: function(delta,notme) { 
		var nextitem=this.activelink;
		var lastitem=nextitem;
		do {
			nextitem=delta>0?nextitem.getNext():nextitem.getPrevious();
			if ((!nextitem)||(nextitem==notme)) {
				nextitem=lastitem;
				return false;				
			}
			if (nextitem.tagName) { lastitem=nextitem; }
		} while (!lastitem.tagName);	
		if (this.activelink) this.activelink.removeClass('active');
		this.activelink=lastitem;
		lastitem.addClass('active');					
		this.scrollto('content-'+lastitem.id);
	}
	
});	
	

// Primary Global Navigation - Class
var SlideList = new Class({
	initialize: function(menu, options) {
		this.setOptions(options);
		var defaultitem=document.body.id;
		this.menu = $(menu);	
		
		$ES('ul li', this.menu).each(function(item){
			if ((!this.current)||(item.firstChild.href.indexOf(defaultitem)>=0))	this.current = item;
			item.addEvent('mouseover', function(){ clearTimeout(this.delayHideId); this.moveBg(item); }.bind(this));
			item.addEvent('mouseout', function(){ this.moveBg(this.current); this.hideContent(); }.bind(this));			 
		}.bind(this));
		this.back = new Element('div').addClass('SlideContent').injectInside(document.body);
		this.back.setProperty("id",this.menu.getProperty("id"));
		this.back.addEvent('mouseover', function() { clearTimeout(this.delayHideId); }.bind(this));
		this.back.addEvent('mouseout', function() { this.hideContent(); }.bind(this));
		this.back.fx = this.back.effects(this.options);
		var p=this.current.getPosition();
		this.back.setStyles( 'left: '+p.x+'px ; top: '+(p.y+this.current.getSize().size.y)+'px' );
		
		var myAjax = new Ajax('/common/menucontent.html', {method: 'get', update: this.back, evalScripts:true, onComplete: function() {	
					this.back.getElements("a").each(function(item) {
		  			item.addEvent('click', function() {
		  			this.hideContent(100);
		  		}.bind(this));
		  	}.bind(this));			
			}.bind(this)}).request();		
		
	},
	
	hideContent: function(delay) {
		clearTimeout(this.delayHideId); 
		this.delayHideId=setTimeout(function() {
			this.back.style.visibility='hidden';
			if (this.current)	this.current.removeClass("active"); 
			this.current=null; 
		}.bind(this),delay?delay:150);	 
	},
	
	setCurrent: function(el, effect){
		if(this.current) this.current.removeClass("active"); 
		this.current = el;
		el.addClass("active");
	},


	moveBg: function(to) {
		if ((to!=this.current)||(this.current&&!this.current.hasClass('active'))) {
		  var extcontent=this.back.getElement('#'+to.id+'div');
		  
		  if (extcontent) {		  
		  	this.back.style.visibility='visible';
		  	this.back.getElements('div[class=mNav]').each(function(item){
		  		item.setStyle('display',item==extcontent?'':'none');
		  	}.bind(extcontent));
		  	
				var pos=to.getPosition();
				var old=this.back.getPosition();
		  	this.setCurrent(to, true);
		  	this.back.fx.custom({
						left: [old.x, pos.x],
						top: [old.y, pos.y+to.getSize().size.y]
				});
			} else {
				this.hideContent();
			}
			
		}			
	}
});


SlideList.implement(new Options);


	
// Primary Global Navigation - Implementation
window.addEvent('domready', function() {
	// QuickTips  - Implementation
	var QT = new Tips($$('.QT'), {
		maxTitleChars: 150,
		className: 'q'			
	});
		
	if($('galleryHeader'))
		__tabNav = new TabPages($E('ul', 'gallery'), $('galleryContent'), function(tab) { 
//				return "/index.jsp?url="+tab.id+"/"+val;
				//return "/"+tab.id+"/"+val;
				return "/gallery/"+tab.id+"/"+val+".htm";
			});

	if($('modelNav'))
		__modelNav = new SlideList($E('ul#modelNav'), {transition: Fx.Transitions.Quad.easeOut, duration: window.ie6?0:200, wait:false, onClick: function(ev, item) { /*ev.stop();*/ }});

	if ($('accordion'))	setupAccordion('accordion','h3.atStart', 'div.atStart');
	
	/* 
		Set up the following hover effects using Javascript because li:hover is not supported on IE6:
	
		ul#modelNav li#n-sedans:hover { background: url(../img/topnav.gif) no-repeat -213px -61px; }
		ul#modelNav li#n-convertibles:hover { background: url(../img/topnav.gif) no-repeat -304px -61px; }
		ul#modelNav li#n-suvs:hover { background: url(../img/topnav.gif) no-repeat -434px -61px; }
		ul#modelNav li#n-hybrids:hover { background: url(../img/topnav.gif) no-repeat -502px -61px; }
		ul#modelNav li#n-fperformance:hover { background: url(../img/topnav.gif) no-repeat -596px -61px; }
	*/
	var navs = {sedans : -213, convertibles : -304, suvs : -434, hybrids : -502, fperformance : -596 };
	$each(navs, function(x, id) {
		$E('ul#modelNav li#n-' + id).addEvent('mouseover', function(event) {
			$each(navs, function(x, id) {
				var li = $E('ul#modelNav li#n-' + id);
				if (!li.hasClass('navActive')) {
					li.setStyle('background', 'none');
				}
			});
			this.setStyle('background', 'url(/img/topnav.gif) no-repeat ' + x + 'px -61px');
		}).addEvent('mouseout', topNavMouseOut);
	});
});

function topNavMouseOut(event) {
	if (!this.hasClass('navActive')) {
		var event = new Event(event);
		var p = this.getCoordinates();
		if (event.client.x <= p.left || event.client.y <= p.top || 
				event.client.x >= p.right || event.client.y >= p.bottom) {
			this.setStyle('background', 'none');
		}
	}
}



function setupAccordion(aId, hPath, divPath) {
	var accnode=$(aId);
	if (accnode) {
		var showindex=location.href.split("#");
		var i=0; try { i=parseInt(showindex[1]); } catch (er) { i=-1; } 
		
		//alert(showindex[1]?showindex[1]:'none');
		var accordion = new Accordion(hPath, divPath, {
			opacity: false,
			show: i<0?'none':i,
			display: i, 
			alwaysHide: true,
			onActive: function(toggler, element){
				toggler.addClass('active');
			},
			onBackground: function(toggler, element){
				toggler.removeClass('active');
			}
		}, accnode);
	}
}



var numselectReplacement=0;
var this_li;

function menuoff()
{
	try
	{ 
		//var sel=$E('select','galleryHeader');
//		this_li.className='selected';
		this_li.parentNode.className = this_li.parentNode.className.replace(new RegExp(" selectOpen\\b"), '');
		this_li.onclick = function() {
			this_li.parentNode.className += ' selectOpen';
			//this_li.onclick = function() {
				  //this_li = this_li;
				  //selectMe(sel.options[sel.selectedIndex]); //.selected = true;
				  //selectMe(this_li);
			//	}
		}
	}
	catch(e)
	{
		//alert("error");
		alert(e);
	  //setVal("something", 5);
	}
	if(document.getElementById("player"))
	{
		document.getElementById("player").style.display = "block";  
		document.getElementById("t-instructions").style.display = "block";
		document.getElementById("overseamessage").style.display = "block";
	}
}

function selectReplacement(obj) {
	var t;
	var opts = obj.options;
		
	if ((!opts)||(opts.length<=0)) return;
	numSelectReplacement++;
	obj.addClass('replaced');
  var ul = document.createElement('ul');
  ul.className = 'selectReplacement';
  
  ul.onmouseout = function(){
	t=setTimeout("menuoff()",500);
  }
  ul.onmouseover = function(){
	  clearTimeout(t);
	  
  ul.onmousedown = function() {
	if(document.getElementById("player"))
	{
		document.getElementById("player").style.display = "none";
		document.getElementById("t-instructions").style.display = "none";
		document.getElementById("overseamessage").style.display = "none";
	}
  }

//	exampleFx = new Fx.Style("player", "opacity", 
//	{
//	  duration: 100,
//	  transition: Fx.Transitions.quartInOut
//	});
//	
//	exampleFx.start(1,0); /*fade it out*/

  }

  for (var i=0; i<opts.length; i++) {
    var selectedOpt;
    if (opts[i].selected) {
      selectedOpt = i;
      break;
    } else {
      selectedOpt = 0;
    }
  }
  for (var i=0; i<opts.length; i++) {
    var li = document.createElement('li');
    var txt = document.createTextNode(opts[i].text);
    li.appendChild(txt);
    li.selIndex = opts[i].index;
    li.selectID = obj.id;
    li.onclick = function() {
  	  this_li = this;
      selectMe(this);
    }
    if (i == selectedOpt) {
      li.className = 'selected';
      li.onclick = function() {
       this.parentNode.className += ' selectOpen';
        this.onclick = function() {
	  	  this_li = this;
          selectMe(this);
        }
      }
    }
    if (window.attachEvent) {
      li.onmouseover = function() {
        this.className += ' hover';
      }
      li.onmouseout = function() {
        this.className = 
          this.className.replace(new RegExp(" hover\\b"), '');
      }
    }
    ul.appendChild(li);
	if(i==0){ this_li = li; }
  }
  obj.parentNode.insertBefore(ul,obj);
}

function selectMeByIndex(obj,index) {
  var lis = obj.parentNode.getElementsByTagName('li');
  this_li = lis[index];
  selectMe(lis[index]);
}
function selectMe(obj) 
{
	var lis = obj.parentNode.getElementsByTagName('li');
	for (var i=0; i<lis.length; i++) {
		if (lis[i] != obj) {
		  lis[i].className='';
		  lis[i].onclick = function() {
	  	    this_li = this;
			selectMe(this);
		  }
		} 
		else {
		  setVal(obj.selectID, obj.selIndex);
		  //prompt("test",obj.parentNode.parentNode.innerHTML);
		  obj.className='selected';
		  obj.parentNode.className = 
		  obj.parentNode.className.replace(new RegExp(" selectOpen\\b"), '');
		  obj.onclick = function() {
			  obj.parentNode.className += ' selectOpen';
			  this.onclick = function() {
				  this_li = this;
				  selectMe(this);
			  }
			}
		}	

		if(document.getElementById("t-photos"))
		{
			reposition(document.getElementById("model").options[obj.selIndex].value);
		}
	}
}

function setVal(objID, selIndex) {
  var obj = document.getElementById(objID);
  obj.selectedIndex = selIndex;
  obj.fireEvent('change');
}

function replaceAllSelect(fromNode, again) {
	if (!again) numSelectReplacement=0;
     fromNode.getElements('select[class=replaced]').each(function(item) { selectReplacement(item); });
    
     if (numSelectReplacement==0) {
    		setTimeout( function() { replaceAllSelect(fromNode,true); }.bind(fromNode), 300);
    	}
}
