var killerPoints;
var inScroller, slideshowNmb, slideshowLinks, cityDetails, cityDetailsTimer = 0, newlyCarouselFx = [], actualCarouselInt = [], carouselNavigation = [], switcherObjLeft = [], switcherObjRight = [], runningCarousel = [], hasRunCarousel = [], yearResults, priceResults, multiResults, todaysOffer, customSelects;
var searchTabs = null;
var modelLoaded = false;
var ie6 = Browser.Engine.trident && navigator.userAgent.indexOf('MSIE 6.0') > 0;
var ajaxRequest = false;
var ajaxRequestList = false;



function buildPromos(bgs){
	bgs.each(function(val){
		$(val.id).setStyle("background","url('"+val.src+"') bottom right no-repeat");
	});
}

function makeTheReady(){
	var aboutbox=document.getElementById('aboutbox');
	var aboutboxHead=document.getElementById('aboutbox-head');
	if(aboutbox && aboutboxHead){
		aboutbox.innerHTML = aboutboxHead.innerHTML;
		aboutboxHead.innerHTML="";
	}

   var listTabs = $$('ul.tab-menu li') || false;
   if(listTabs){
      listTabs.addEvent('mouseover', function(){
         var pos = $(this).getPosition();
         var title = $(this).getChildren('a').getProperty('title');
         if(title == '&#160;' || !title || title=="") return;
         var el = new Element('div', {'class':'tabTooltip','style':'top:'+pos.y+'px;left:'+pos.x+'px','html':title});
         el.inject($(document.body));
      }).addEvent('mouseout', function(){
         $$('.tabTooltip').dispose();
      });
   }

   var filterCars = $('filterCars') || false;
   var filterMenu = $('filterMenu') || false;
   if(filterCars && filterMenu){
    var ajaxTabs = new SimpleTabs(filterCars, {
        selector: '#filterMenu li a',
        skipLoadingFirst: true,
        firstContainerElement: $('carlistWrapper') || false,
        onSelect: function(toggle, container, index) {
            toggle.addClass('tab-selected');
            container.fade('show');
            container.addClass('container-selected');
        },
        onDeselect: function(toggle, container, index) {
            toggle.removeClass('tab-selected');
            container.fade('hide');
            container.removeClass('container-selected');
        }
    });
  }

  var container = $('searchtabs') || false;
  var buyout = $$('body.buyout') || false;

	if (container && (!buyout || !buyout.length) )  {

	  searchTabs = new SimpleTabs(container, {selector: 'h4'});
	  container.getElements('.hide').removeClass('hide');

	  container.getElements('.hide').removeClass('hide');

      $$('#searchtabs span.yellow').each(function(el){
         el.getParent().getParent().addClass("yellow");
      });

	}else if(container && buyout){

	  searchTabs = new SimpleTabs(container, {selector: 'h4'});
	  container.getElements('.hide').removeClass('hide');

    }

  var searchingType = $('searchingType') || false;
  if(searchingType){
     todaysOffer = $('searchingType').getElement('h5') || false;
     if (todaysOffer){
         todaysOffer = todaysOffer.get('text');
         $$('#searchingType a span').each(function(el){
             t = el.get('html');
             el.set('html',todaysOffer+' '+t);
         });
     }
  }
     
	var buildtabs = $('buildtabs') || false;
	if (buildtabs) {
	  new SimpleTabs(buildtabs, {selector: 'h4'});
	}

    var buildtabs2 = $('buildtabsCars') || false;
    if (buildtabs2) {
      new SimpleTabs(buildtabs2, {selector: 'h4', classMenu: 'tab-menu-cars'});
    }

	var newlycarousel = $('newlycarousel') || false;
	if (newlycarousel) {
	  new SimpleTabs(newlycarousel, {selector: 'h4'});
	}

  var resultsTableBig = $('tableimgs') || $('tablecars') || false;
  if (resultsTableBig) {
  	resultsTableBig.getElements('.one').each(function(one){
			one.addEvents({
	  		'mouseenter':function(){
	  			one.addClass('over');
				},
				'mouseleave':function(){
	  			one.removeClass('over');
				}
			});
		});
  	resultsTableBig.getElements('.oneL').addEvents({
  		'mouseenter':function(){
  			this.addClass('overL');
			},
			'mouseleave':function(){
  			this.removeClass('overL');
			}
		});
	}

	var fotoslides = $('fotoslides') || false;
	if (fotoslides) {
		slideshowLinks = fotoslides.getFirst().getElements('a[rel!=carGallery]');
		if (slideshowLinks.length > 0) {
			new Element('a',{'href':'#','class':'scrollBtn',html:'&#9668;'}).addClass('lft').addEvents({
				'mouseenter':function(){
					$clear(inScroller);
					inScroller = setInterval(function(){
						var oldScroll = this.getScroll().x;
						if(this.getScrollSize().x-this.getWidth() > (oldScroll-1)){
							this.scrollTo(oldScroll-5);
						}
						else $clear(inScroller);
					}.bind(this),25);
				}.bind(fotoslides),
				'mouseleave':function(){$clear(inScroller);},
				'click':function(e){e.stop();}
			}).inject(fotoslides,'before');
			new Element('a',{'href':'#','class':'scrollBtn',html:'&#9658;'}).addClass('rgt').addEvents({
				'mouseenter':function(){
					$clear(inScroller);
					inScroller = setInterval(function(){
						var oldScroll = this.getScroll().x;
						if(this.getScrollSize().x-this.getWidth() > (oldScroll+1)){
							this.scrollTo(oldScroll+5);
						}
						else $clear(inScroller);
					}.bind(this),25);
				}.bind(fotoslides),
				'mouseleave':function(){$clear(inScroller);},
				'click':function(e){e.stop();}
			}).inject(fotoslides,'after');

			slideshowNmb = 0;
			var cntR = slideshowLinks.length;
			slideshowLinks.each(function(ahref,inda){
				ahref.addEvent('mouseenter',function(e){
					e = new Event(e);
					e.stop();
					refreshSlideshow(false,inda,cntR);
					return false;
				});
                ahref.addEvent('click',function(e){
					e = new Event(e);
					e.stop();
					refreshSlideshow(false,inda,cntR);
					return false;
				});
			});

			slideshowLinks[0].addClass('selectedThumb');
			var elmNav = $('fotonavig').getElement('div');
			new Element('span',{'class':'counter'}).adopt(new Element('strong',{'text':'1'})).adopt(new Element('strong',{'text':' / '+cntR})).inject(elmNav);
			if (cntR > 1) {
				var arrow = new Element('a',{'class':'arrow','href':'#'});
				arrow.clone().addClass('prev').addEvent('click',function(e){
					e.stop();
					refreshSlideshow(true,-1,cntR);
				}).inject(elmNav,'top');
				arrow.clone().addClass('next').addEvent('click',function(e){
					e.stop();
					refreshSlideshow(true,1,cntR);
				}).inject(elmNav,'bottom');
			}
		}


	}

	setTimeout(function(){makeTheAfterReady();},20);

}

function refreshSlideshow(increase,intgr,cntr){
	var fotoactual = $('fotoactual');
	if (fotoactual.hasClass('loadingImg')) return;
	fotoactual.addClass('loadingImg');
	if (!increase && slideshowNmb == intgr) {
		fotoactual.removeClass('loadingImg');
		return;
	}
	if (increase) slideshowNmb += (intgr + cntr);
	else slideshowNmb = intgr;
	slideshowNmb %= cntr;
	fotoactual.empty();
	var gallery = $('fotoslides').getElement('a[rel=carGallery]') || false;
	if (gallery)
		$$('a.selectedThumb').getParent().getElement('a[rel=carGallery]').addClass('smoothbox');
	slideshowLinks.removeClass('selectedThumb');
	$('fotonavig').getElement('div').getElement('strong').set('text',(slideshowNmb+1));
	var elmP = $('fotonavig').getElement('p');
	if(killerPoints != undefined) elmP.innerHTML = select_slogan(slideshowNmb+1);

	var s=document.getElementById('overPhotoSticker');
	if(s)s.style.display=(slideshowNmb+1)==1?"block":"none";

	if (!gallery){
		new Asset.image(slideshowLinks[slideshowNmb].addClass('selectedThumb').get('href'),{onload:function(){this.inject($('fotoactual').removeClass('loadingImg'));}});
	}else{
		new Asset.image(slideshowLinks[slideshowNmb].addClass('selectedThumb').get('href'),{onload:function(){
					var d = new Element('div').adopt(slideshowLinks[slideshowNmb].getParent().getElements('a')[1].cloneNode(true));
					slideshowLinks[slideshowNmb].getParent().getElements('a')[1].removeClass('smoothbox');
					d.inject($('fotoactual'));
                    $$('#fotoactual a span').set("id", "zoom");
					$$('#fotoactual a').set("style", "display: inline");
					$('fotoactual').removeClass('loadingImg');
					TB_init();
			}
	});
	}
}

function loadModels(parentEl, destination, simple, shortTitle){
	if(!Browser.Engine.webkit)
       destination.loader();
    else if(destination.id == "modelspan"){
       destination.selectedOption.set('html', 'Model');
    }
    
	new Request.JSON({
      url: '/cs/ajax/model',
      onComplete: function(resp) {
          destination.populate(resp);

          if(typeof setModelValue == 'function')
             setModelValue();
      }
  }).get({'simple': simple ? 1 : 0, 'short': shortTitle ? 1 : 0, 'make' : parentEl.selectElement.get('value')});
}


function makeTheAfterReady(){

$$(".aab").addEvent("click",function(){
var aab=Cookie.read("aab");
if(!aab)aab="";
aab=aab.replace(new RegExp($(this).id+":\d+?;"),"");
Cookie.write("aab",aab+$(this).id+":"+((new Date()).getTime())+";",{path:'/',duration:30});
});

	var topmenu = $('dropmenu');
	if (topmenu) {
		topmenu.getElements('li.menu').each( function( elem ){
			var list = elem.getElement('ul.links') || false;
			if (list){
				new Element('li',{'class':'submenuTop'}).inject(list,'top');
				new Element('li',{'class':'submenuBottom'}).inject(list,'bottom');
				var sizes = list.getSize();
				listN = new Element('div',{'class':'hide'}).addClass('inMenu').adopt(list.clone().setStyle('visibility','visible'));
				list = listN.replaces(list);

				if (Browser.Engine.trident) new Element('div',{'class':'bgIframe'}).inject(list,'bottom').setStyles({'width':sizes.x,'height':sizes.y}).set({'html':'<iframe width="'+sizes.x+'" height="'+sizes.y+'" frameborder="0" scrolling="no" src=""></iframe>'}).set('opacity',0.01).getFirst().set('opacity',0.01);

				elem.addEvents({
					'mouseenter' : function(){
						list.removeClass('hide');
					},
					'mouseleave' : function(){
						list.addClass('hide');
					}
				});
			}
		})
	}

    var carDetailSelects = $$('.carDetailSelect');
    if(carDetailSelects.length > 0){
		customSelects = [];
		carDetailSelects.each(function(el,ind){
			customSelects[ind] = new CustomSelect(el,el.getProperty('class').replace('carDetailSelect','').clean(),false,3,false);
			if (el.get('id') == 'makespan')
               customSelects[ind].addEvent('change', function(){loadModels(this, customSelects[1], true, true);});
            if(el.get('id') == 'modelspan'){
               customSelects[ind].addEvent('change', function(e){
                  if((typeof(e)=='string' || typeof(e)=='number')){
                     if($$('#imodelh').length > 0)
                        $('imodelh').set('value', e);
                  }
               });
            }
		});
		if($('imake').get('value') != ''){
			loadModels(customSelects[0], customSelects[1], true, false);
		}
    }


}

function buildCarousel(el,childs,cnt,prop,val,nav) {
	var newlyCarouselArea = $(el) || false;
	if (newlyCarouselArea) {
		var newlyCarousels = newlyCarouselArea.getElements(childs) || false;
		actualCarouselInt[cnt] = -1;
		newlyCarouselFx[cnt] = new Fx.Elements(newlyCarousels,{'onComplete':function(){runningCarousel[cnt]=false;},transition:'quad:out',duration:500});
		actualCarouselInt[cnt] -= 1;

		hasRunCarousel[cnt] = false;
		runningCarousel[cnt] = false;

		var strLeft = [];
		var strRight = [];
	  for(var ix = 0; ix < newlyCarousels.length; ix++) {
	  	strLeft[ix] = ix+":{'"+prop+"':"+val+",'zIndex':30}";
	  	strRight[ix] = ix+":{'"+prop+"':"+(-val)+",'zIndex':30}";
		}

	  carouselNavigation[cnt] = nav;
	  spanka = new Element('span',{'class':'circle','text':' '});
	  spanka.clone().removeClass('circle').addClass('circleArrowPrev').addEvent('mouseup',function(e){
	  	runCarousel((actualCarouselInt[cnt]-1),cnt,newlyCarousels.length);
			e.stop();
			return false;
		}).inject(carouselNavigation[cnt]);
		switcherObjLeft[cnt] = [];
		switcherObjRight[cnt] = [];
	  newlyCarousels.each(function(el,ind){
	  	var strLeftX = new Array().extend(strLeft);
	  	var strRightX = new Array().extend(strRight);
	  	strLeftX[ind] = ind+":{'"+prop+"':["+(-val)+",0],'zIndex':40}";
	  	strRightX[ind] = ind+":{'"+prop+"':["+val+",0],'zIndex':40}";
	  	switcherObjLeft[cnt][ind] = JSON.decode("{"+strLeftX.join(",")+"}");
	  	switcherObjRight[cnt][ind] = JSON.decode("{"+strRightX.join(",")+"}");
		  spanka.clone().addEvent('click',function(e){runCarousel(ind,cnt,newlyCarousels.length);e.stop();return false;}).inject(carouselNavigation[cnt]);
		});
	  spanka.clone().removeClass('circle').addClass('circleArrowNext').addEvent('click',function(e){
			runCarousel((actualCarouselInt[cnt]+1),cnt,newlyCarousels.length);
			e.stop();
			return false;
		}).inject(carouselNavigation[cnt]);
	  carouselNavigation[cnt] = carouselNavigation[cnt].getElements('span.circle');
		runCarousel(0,cnt,newlyCarousels.length);
	}
}



function FormatNumberBy3(num, decpoint, sep) {
  if (arguments.length == 2) sep = ",";
	if (arguments.length == 1) {
    sep = ",";
    decpoint = ".";
  }
  num = num.toString();
  a = num.split(decpoint);
  x = a[0];
  y = a[1];
  z = "";
  if (typeof(x) != "undefined") {
    for (i=x.length-1;i>=0;i--) z += x.charAt(i);
    z = z.replace(/(\d{3})/g, "$1" + sep);
    if (z.slice(-sep.length) == sep) z = z.slice(0, -sep.length);
    x = "";
    for (i=z.length-1;i>=0;i--) x += z.charAt(i);
    if (typeof(y) != "undefined" && y.length > 0) x += decpoint + y;
  }
  return x;
}

var newWindow = null;
function closeWin(){if (newWindow != null){if(!newWindow.closed)newWindow.close();}}
function popUpWin(url, type, strWidth, strHeight){closeWin();if (type == "fullScreen"){var strWidth = screen.availWidth - 10;var strHeight = screen.availHeight - 160;}var leftVal = (screen.width - strWidth ) / 2;var topVal = (screen.height - strHeight) / 2;var tools="";if (type == "standard" || type == "fullScreen") tools = "resizable,toolbar=yes,location=yes,scrollbars=yes,menubar=yes,width="+strWidth+",height="+strHeight+",top=0,left=0";if (type == "console") tools = "resizable,toolbar=no,location=no,scrollbars=no,width="+strWidth+",height="+strHeight+",left="+leftVal+",top="+topVal+"";if (type == "scroll") tools = "resizable,toolbar=no,location=no,scrollbars=yes,width="+strWidth+",height="+strHeight+",left="+leftVal+",top="+topVal+"";newWindow = window.open(url, 'newWin', tools);newWindow.focus();}
function runCarousel(ix,c,counter){if (runningCarousel[c]) return false;runningCarousel[c] = true;var switcherObj = [];if (ix>actualCarouselInt[c]) switcherObj = switcherObjRight[c];else switcherObj = switcherObjLeft[c];ix = Math.abs((ix + counter)%counter);if (ix === actualCarouselInt[c]) return;runningCarousel[c] = true;if (hasRunCarousel[c]) carouselNavigation[c][actualCarouselInt[c]].removeClass('selectedSpan');actualCarouselInt[c] = ix;hasRunCarousel[c] = true;carouselNavigation[c][ix].addClass('selectedSpan');newlyCarouselFx[c].start(switcherObj[ix]);}
function login(lang){new Request.JSON({url: '/ajax/login.php?lang=' + lang,onComplete: function(resp) {if(resp.ok){TB_remove();document.location.reload();}else{$('loginError').innerHTML = '<span style="color:red">'+ resp.msg +'</span>';}}}).get({'login': $('loginInput').value, 'pass' : $('passInput').value});$('loginError').innerHTML = '<img src="/images/ajax-loader.gif" style="margin:0px; border:0px"/>';}

function getCookie(c){if(document.cookie.length>0){d=document.cookie;s=d.indexOf(c+"=");if(s!=-1){s=s+c.length+1;e=d.indexOf(";",s);if(e==-1)e=d.length;return unescape(d.substring(s,e));}}return "";}

