// JavaScript Document
sabana = {};
sabana.url = "http://" +  window.location.hostname;
sabana.gallery = {};
sabana.ajax = {};
sabana.ajax.form = Class.create({
	initialize:function(id,options){
		this.options = {
			lf:function(){sabana.ajax.loading(this.form,{bgColor:'blue',text:'Sending'})}
		};
		
		Object.extend(this.options, options || {});
		this.form = $(id);
		this.form.observe('submit',this.submit.bindAsEventListener(this));

	},
	submit:function(event){
		event.stop();
		
		this.form.request({onSuccess:this.success.bind(this),onCreate:this.options.lf.bind(this)});
	},
	success:function(transport){
		this.form.innerHTML = transport.responseText;
	}
});
sabana.ajax.loadImage = Class.create({
	initialize:function(elm, url){
		this.dl  = false;
		this.df  = false;
		this.elm = elm;
		this.img = new Image();
		
		this.img.src = url;
		this.img.onload = function(){
			this.dl = true;
			if(this.dl && this.df){
				this.fadeIn();
			}
		}.bind(this);
		
		Effect.Fade(this.elm,
			{duration:.25,
			 to:.1,
			 afterFinish:function(){
				    this.elm.setStyle({display:'block'});
					this.elm.setOpacity(0);
				 	this.df = true;
			 		if(this.dl && this.df){
						this.fadeIn();
					}else{
						this.elm.setOpacity(0);
					}
			 	}.bind(this)
			});
	},
	fadeIn:function(){
		this.elm.src    = this.img.src;
		this.elm.width  = this.img.width;
		this.elm.height = this.img.height;
		
		Effect.Fade(this.elm,
			{duration:.25,
			 from:.1,
			 to:1
			});
	}
});
sabana.ajax.loading = function(id, opt){
	options = {
		bgColor:'white',
		text:'Loading'
	}
	
	Object.extend(options, opt || {});
	
	ajaxLoader ='/images/common/loaders/white.gif';
	
	if(options.bgColor == 'blue')
		ajaxLoader = '/images/common/loaders/blue.gif';
	
	$(id).innerHTML = '<div class="loader"><img src="' + ajaxLoader +'" alt="Ajax Loader" /><span>' + options.text + '</span></div>';
}
sabana.Gallery = Class.create({
	initialize:function(){
			var frag = (window.location.pathname + "").split("/");
			if(window.location.hash != ""){
				var hash = (window.location.hash + "").split("#");
				window.location = "http://" +  window.location.hostname + "/" + frag[1] + hash[1];
			}
			
			
			this.cph   = null;
			this.imgs  = {};
			this.pop   = new askpop(null);
			this.GH    = $("ch");
			this.PGH   = $('productGroups');
			this.cache = "";
			this.GH.addClassName("js");
			this.RF0 = false;
			this.RFI = false;
			
			this.backSim = new sabana.BackButtonSim(this,
				function($this){
					var url = "";
					var frag = (window.location.pathname + "").split("/");
					if(window.location.hash != ""){
						var hash = (window.location.hash + "").split("#");
						url = "http://" +  window.location.hostname + "/" + frag[1] + hash[1];
					}
					
					if(url == "")
						url = window.location + "";
						
					$this._loadPage(url,$this.GH);
				}
			);
			
			sabana.Gallery.created = this;
			
			this.PGH.observe("click",
				function(event){
					event.stop();
					
					var e = event.findElement('a');
					
					if(e != document){
						this._loadPage(e.href, this.GH);
					}
				}.bind(this)
			);
	},
	load:function(gt){
		this.GH.stopObserving();
		switch(gt)
		{
			case 'product': 
				this._setUpProductHover();
			break;
			case 'estate': 
				setTimeout(function(){this._setUpEstate("estate")}.bind(this),10);
			break;
			case 'details': 
				this._setUpDetails();
			break;
		}
	},
	_setUpDetails:function(){
		this.GH.observe("click",function(event){
			var e = event.findElement('a');
			var p = e.up();
			
			if(p.hasClassName("enlarge")){
				event.stop();
				var pid = p.getAttribute('data-pid');
				if(this.imgs[pid] == null){
					new Ajax.Request(e.href + "&json&random=r" + Math.floor(1+ Math.random() * 1000), {
 						onSuccess: function(response) {
   							 this.imgs[pid] = response.responseJSON;
							 this.imgs[pid].current = e.href.split("?")[1].split("img=")[1];
							 this._showProductPop(pid);                  
							 
  						}.bind(this)
					});
				}else{
					this.imgs[pid].current = e.href.split("?")[1].split("img=")[1];
					this._showProductPop(pid);
				}
				
			}else if(e.hasClassName('close')){
				event.stop();
				this._loadPage(e.href, this.GH);
			}
		}.bind(this));
	},
	_setUpEstate:function(){		
		$('carousel-wrapper').addClassName('js');

		$('carousel-wrapper').up().innerHTML += '<a href="javascript:" id="cprv" class="carousel-control" rel="next">Next</a>';

		$('carousel-wrapper').up().innerHTML += '<a href="javascript:" id="cnxt" class="carousel-control" rel="prev">Previous</a>';

		new sabana.LazyLoader($('carousel-wrapper'),{
			calcTop    : function(e){return 500},
			calcOffset : function(){return 10000000000},
			mode       : 'click',
			triggers   : $$('a.carousel-control')
		});

		new Carousel('carousel-wrapper', 
			$$('#carousel-content .slide'), 
			$$('a.carousel-control'),
			{
				visibleSlides:4,
				duration:.33,
				wheel:false
			}
			 
		);
		
		var imgs = $$('#carousel-content .slide img');
		var urls = [];

		for(i = 0; i < imgs.length; i++){
			org =  imgs[i].readAttribute('data-orginal');
			src = ""
			if(org == "")
				src = imgs[i].src;
			else
				src = sabana.url + org;
				
			urls[i] = src.replace('s.jpg','l.jpg');
		}
			
		this.slideshow = new sabana.slideshow(urls,$('popImg'));
		
		this.GH.observe("click",
			function(event){
				var e = event.findElement('a');
				if(e.hasClassName("enlarge"))
				{
					event.stop();
					this.slideshow.goto(e.down().src.replace('s.jpg','l.jpg'));
				}
			}.bind(this)
		);
	},
	_setUpProductHover:function(){
		new sabana.LazyLoader($('scrollbox'),{height:800,calcTop: function(e){return e.up().up().positionedOffset().top}});
		this.GH.observe("click",function(event){
			
			var e = event.findElement('a');
			if(e.hasClassName("enlarge"))
			{
				event.stop();
				pid = event.findElement('.productTH').id;
				this.pop.urls=[];
				
				if(this.imgs[pid] == null){
					url = $$('#' + pid + ' a[class = next]');
					if(url != ""){
						new Ajax.Request($$('#' + pid + ' a[class = next]') + "?json", {
 							onSuccess: function(response) {
							 	this.imgs[pid] = response.responseJSON;
							 	this.imgs[pid].current = 0;
   								this._showProductPop(pid);					
  							}.bind(this)
						});
					}else{
						this.imgs[pid] = {
							current:0,
							photosPop:[e.href]
						}
						this._showProductPop(pid);
					}
				}else{
					this._showProductPop(pid);
				}				
			}
			else if (e.hasClassName("next"))
			{
				event.stop();
				pid = event.findElement('.productTH').id;
				if(this.imgs[pid] == null){
					new Ajax.Request(e.href + "?json", {
 						onSuccess: function(response) {
   							 this.imgs[pid] = response.responseJSON;
							 this.imgs[pid].current = 1;
							 this._swapProductImg(pid);                  
							 
  						}.bind(this)
					});
				}else{
					this.imgs[pid].current =  (++this.imgs[pid].current) % this.imgs[pid].photos.length;
					this._swapProductImg(pid);
				}
			}else if(e.hasClassName("details")){
				event.stop();
				this._loadPage(e.href, this.GH);
			}
		}.bind(this));
	},
	_loadPage:function(url, c){
		this._updateUrl(url);
		sabana.msg.body.show();
		new Ajax.Request(url + "?rand=" + Math.floor(Math.random() *10000), {
 			onSuccess: function(response) {
				sabana.msg.body.remove();
				r = response.responseJSON;
			 	if(r.error){
					alert(r.payload);
				}else{
					c.innerHTML = r.payload;
					document.title = r.pageTitle;
					
					switch(r.type)
					{
						case "gallery":
							setTimeout(function(){this.load("product")}.bind(this),10);
							 break;
						case "estate":
							setTimeout(function(){this.load("estate")}.bind(this),10);
							break;
						case "details":
							this.load("details");
							break;
						default:
							this.load();
					}
				}				
  			}.bind(this)
		});
	},
	_showProductPop:function(pid){
		this.pop.currentUrl = this.imgs[pid].current;
		this.pop.urls=this.imgs[pid].photosPop;
		this.pop.show();
	},
	_swapProductImg:function(pid){
		new sabana.ajax.loadImage($(pid + "img"),this.imgs[pid].photos[this.imgs[pid].current]);
	},
	_updateUrl:function(url)
	{
		if(url != window.location +""){
			url = url.split("http://" + window.location.hostname);
			url = url[1].split("/");
			str = "#/";
			
			for(i = 2; i < url.length; i++)
				str += url[i] + "/"
			
			str = str.substring(0,str.length-1);	
			window.location = ((window.location + "").split("#")[0]) + str;
			
			this.backSim.setCurrent();
		}
	
	}
});
sabana.slideshow =  Class.create({
	initialize:function(urls, img){
		this.current = 0;
		this.urls    = urls;
		this.running = null;
		this.timeout = 10000;
		this.img     = $(img);
		this.control = new Element('div', {'class': 'slControls'}).setStyle({'position':'absolute'});
		this.toggleC = new Element('div', {'class': 'slPause'}).observe('click',this.toggle.bind(this));
		
		this.control.insert(this.toggleC);
		this.control.insert(new Element('div', {'class': 'slNext'}).observe('click',this.next.bind(this)));
		this.control.insert(new Element('div', {'class': 'slPrev'}).observe('click',this.prev.bind(this)));
		
		this.img.up().insert(this.control);
		this.control.clonePosition(this.img);
		
		this.img.observe('load',function(event){
			event.stop();
			this.control.clonePosition(this.img);
		}.bind(this));
		
		setTimeout(this._preLoad.bind(this),100);
		this.start();
	},
	_preLoad:function(){
		
		if(this.current + 1 < this.urls.length){
			var img = new Image();
			img.src = this.urls[(this.current + 1)/1];
		}
		
	},
	_next:function(){
		this.current = (++this.current) % this.urls.length;
		new sabana.ajax.loadImage($(this.img), this.urls[this.current]);
		this.running = setTimeout(this._next.bind(this), this.timeout);
		setTimeout(this._preLoad.bind(this),100);
	},
	toggle:function(){
		if(this.running != null){
			this.stop();
		}else{
			this.start();
		}
	},
	goto:function(url){
		var c = 0;
				
		this.stop();
		for(i = 0; i < this.urls.length; i++){
			if(this.urls[i] == url){
				c = i;
				break;
			}
		}
		
		this.current = c;
		setTimeout(this._preLoad.bind(this),100);
		new sabana.ajax.loadImage($(this.img), this.urls[this.current]);
			
	},
	next:function(){
		this.stop();
		this.current = (++this.current) % this.urls.length;
		setTimeout(this._preLoad.bind(this),100);
		new sabana.ajax.loadImage($(this.img), this.urls[this.current]);
	},
	prev:function(){
		this.stop();
		this.current = this.current == 0 ? this.urls.length-1 : this.current-1 ;
		new sabana.ajax.loadImage($(this.img), this.urls[this.current]);
	},
	stop:function(){
		this.toggleC.removeClassName('slPause');
		this.toggleC.addClassName('slPlay');
		clearTimeout(this.running);
		this.running = null;
	},
	start:function(){
		this.toggleC.removeClassName('slPlay');
		this.toggleC.addClassName('slPause');
		this.running = setTimeout(this._next.bind(this), this.timeout);
	}
});
sabana.ajax.search = Class.create({
	initialize:function(sb, url, f){
		this.sb  = sb;
		this.url = url;
		this._f  = f;
		this._r  = null;
		this.of  = {width:14, height:0};
		this.po  = {top:1, left:-10};
		this.sbh =  new Element('div', {
				'class'    : 'searchHint'
			}).setStyle({
				'position' : 'absolute', 
				'display'  : 'none',
				'overflow' : 'hidden'
			});
		
		this.sb.observe("keyup",this._getHints.bind(this));
		this.sb.observe("focus",this._show.bind(this));
		this.sb.observe("blur" ,this._hide.bind(this));
		this.sb.observe("keyup",this._select.bind(this));
		this.sbh.observe("mousemove",this._clearFocus.bind(this));
		
		this.sbh.observe("mouseover",function(){this.over = true}.bind(this));
		this.sbh.observe("mouseout" ,function(){this.over = false; this._hide()}.bind(this));
		
		this._f.observe("submit",this._submit.bind(this));
		document.body.appendChild(this.sbh);
	},
	_clearFocus:function(event){
		if(this._r != null)
			this._r.getCurrent().removeClassName('focus');
	},
	_submit:function(event){
		if(this._r != null){
			event.stop();
			window.location = this._r.getCurrent().href;
		}
	},
	_select:function(event){
		event.stop();
		
		if(this._r == null && (event.keyCode == 38 || event.keyCode == 40))
		{
			this._r = new sabana.datastructure.ArrayList();
			this._r.setArray($$("#" + this.sbh.identify() + " a")); 
		}
		
		if(this._r.getCurrent().hasClassName('focus'))
			this._r.getCurrent().removeClassName('focus');
		else
			this._r.prev();
				
   		switch(event.keyCode){
			case 38://Arrow Up
				this._r.prev().addClassName('focus');
      			break;
 		    case 40://Arrow Down
				this._r.next().addClassName('focus');
      			break;					
   		}

	},
	_getHints:function(event){
		event.stop();
		
		if(!(event.keyCode == 38 || event.keyCode == 40 || event.keyCode == 13))
		{
			new Ajax.Request(this.url + this.sb.value, {
 				onSuccess: function(response) {
					r = response.responseJSON;
				 	if(r.error){
						alert(r.payload);
					}else{
						this._r = null;
						this.sbh.innerHTML = r.payload;
					}				
				}.bind(this)
			});
		}
	},
	_show:function(event){
		event.stop();
		this.over = false;
		var l = $('q').cumulativeOffset();
		this.sbh.setStyle({
			'width'   : (this.sb.getWidth() + this.of.width) + "px",
			'left'    : (l.left + this.po.left) + "px",
			'top'     : (l.top + this.sb.getHeight() + this.po.top) + "px",
			'display' : 'block'
		});
	},
	_hide:function(event){
		event.stop();
		if(!this.over)
			this.sbh.setStyle({
				'display':'none'
			});
	}
});
sabana.datastructure = {};
sabana.datastructure.ArrayList = Class.create({
	initialize:function(){
		this.array   = [];
		this.current = -1;
	},
	add:function(obj){
		this.array.push(obj);
	},
	setArray:function(array){
		this.current = -1;
		this.array = array;
	},
	getCurrent:function(){
		if(this.current < 0)
			this.current = 0;
		return this.array[this.current];
	},
	next:function(){
		this.current = (++this.current) % this.array.length;
		return this.array[this.current];
	},
	prev:function(){
		this.current = this.current <= 0 ? this.array.length-1 : this.current-1 ;
		return this.array[this.current];
	}
});
sabana.LazyLoader = Class.create({
	initialize:function(continer, options){
		this._a  = false;
		this.c   = continer;
		this.img = [];
		this.i   = 0;
		this.eventHandler = this.loadimg.bind(this);
		this.options = {
			calcTop    : function(e){return e.up().positionedOffset().top},
			calcOffset : function(){return this.c.viewportOffset().top * -1 + this.options.height},
			mode       : 'scroll',
			height     : 500,
			triggers   : []
		};
		
		Object.extend(this.options, options || {});		
		$$("img[data-orginal]").each(function(e){
			if(e.readAttribute('data-orginal') != "")
				this.img.push({elm:e, top:this.options.calcTop(e)});
		}.bind(this));

		switch(this.options.mode)
			{
			case 'scroll':
				this.c.observe("scroll",this.eventHandler);
				break;
			case 'click':
				this.options.triggers.each(function(e){
					e.observe("click",this.eventHandler);
				}.bind(this));
			break;
		}
		
		new PeriodicalExecuter(function(pe) {
			if(this._a){
				this._a = false;
				off = this.options.calcOffset.bind(this);
				var offset = off();
				
				for(i = this.i; i < this.img.length; i++)
				{
					var osrc = this.img[i].elm.readAttribute('data-orginal');
					if(this.img[i].top < offset && osrc != ""){
						this.img[i].elm.writeAttribute('src',osrc);
						this.i++;
					}else{
						break;
					}
				}
			
				if(this.img.length == this.i){
					switch(this.options.mode)
					{
						case 'scroll':
							this.c.stopObserving("scroll",this.eventHandler );
							break;
						case 'click':
							this.options.triggers.each(function(e){
								this.c.stopObserving("click",this.eventHandler);
							}.bind(this));
							break;
					}
				
					pe.stop();	
				}
			}
		}.bind(this), 1);

	},
	loadimg:function(event){
		this._a = true;
	}
});
sabana.BackButtonSim = Class.create({
	initialize:function($this, onchange){
		this.$this = $this;
		this.onchange = onchange;
		this.current = window.location + "";
		setInterval(this.check.bind(this), 333);
	},
	setCurrent:function(){
		this.current = window.location + "";
	},
	check:function(){
		if(this.current != (window.location + "")){
			this.current = window.location + "";
			this.onchange(this.$this);
		}
			
	}
});
sabana.msg = {};
sabana.msg.body = {
    displaying:false,
    show:function(msg){
        if(!sabana.msg.body.displaying){
        	sabana.msg.body.displaying = true;
			$('displayBox').toggleClassName('show');
			$('displayBox').toggleClassName('hidden');
		}
		
    },
    remove:function(){
        if(sabana.msg.body.displaying){
        	sabana.msg.body.displaying = false;
			$('displayBox').toggleClassName('show');
			$('displayBox').toggleClassName('hidden');
		}
    }
};

function quickscroll(){
	$('productGroups').stopObserving();
	$('productGroups').observe("click",function(event){
		event.stop();
		var e = event.findElement('a');
		var dest    = $(e.href.split("#")[1]).positionedOffset().top;
		var current = $('scrollbox').scrollTop;
		var step    = (dest - current)/8;

		var anim = {
			step:step,
			dest:dest,
			num:8,
			scroll:function(){
				var c = $('scrollbox').scrollTop;
				this.num--
				if((c + this.step) < 0){
					$('scrollbox').scrollTop = 0;
				}else if((c + this.step) > $('scrollbox').scrollHeight){
					$('scrollbox').scrollTop = $('scrollbox').scrollHeight;
				}else if(this.num == 1){
					$('scrollbox').scrollTop = this.dest;
				}else{				
					$('scrollbox').scrollTop = (c + this.step);
					setTimeout(this.scroll.bind(this),25)
				}
			}
		}
		
		anim.scroll();
	});
}
