


/*MAIN*/



/* * *
	BACKGROUND IMAGE CACHE
* * */
Try.these(function(){
	document.execCommand("BackgroundImageCache", false, true);
});

/* * * 
	IE HOVER
* * */
var IEHover = {
	onId:function(id){
		IEHover._on(function(){
			return [$(id)];
		});
	},
	onTagName:function(tagName, self){
		IEHover._on(function(){
			return $(self || document).getElementsByTagName(tagName);
		});
	},
	_on:function(getFunc){
		$A(getFunc()).each(function(element){
			Event.observe(element, 'mouseover', IEHover.over.bind(element));
			Event.observe(element, 'mouseout', IEHover.out.bind(element));
		});
	},
	
	over:function(){
		Element.addClassName(this, IEHover.hoverClass(this));
	},
	
	out:function(){
		Element.removeClassName(this, IEHover.hoverClass(this));
	},
	
	hoverClass:function(element){
		if(!element.className || element.className == 'hover')
			return 'hover';
		else
			return element.className.split(/\s+/)[0]+'Hover';
	}
}

/* * *
	BUTTON
* * */
var button = {
	initialize: function(){
		if($('iBack'))
			Event.observe($('iBack'), 'click', button.back.bindAsEventListener(this));
	},
	back: function(event){
		Event.stop(event);
		history.back();
	}
}

/* * *
	EMAIL
* * */
var email = {
	decode: function(str){
		str = str.replace(/( \[arroba\] )/g, '@');
		str = str.replace(/( \[ponto\] )/g, '.');
		return str;
	}
}

/*-----------------------------------------------------------------------------------------------*/

Effect.Transitions.SwingFromTo = function(pos) {
	var s = 1.70158;
	if((pos/=0.5) < 1)
		return 0.5*(pos*pos*(((s*=(1.525))+1)*pos - s));
	return 0.5*((pos-=2)*pos*(((s*=(1.525))+1)*pos + s) + 2);
};

/* * *
	TEAM
* * */
team = {
	ready:true,
	current:-1,
	target:false,
	array:['gremio', 'palmeiras', 'flamengo', 'corinthians', 'atletico', 'bahia', 'botafogo', 'cruzeiro', 'fluminense', 'internacional', 'sao-paulo', 'santos', 'vitoria', 'vasco-da-gama', 'avai', 'figueirense', 'coritiba', 'atletico-paranaense', 'linha-brasil'],
	initialize: function(){
		Event.observe('team-next', 'click', (function(event){Event.stop(event); this.change(-1)}).bindAsEventListener(this));
		Event.observe('team-prev', 'click', (function(event){Event.stop(event); this.change(+1)}).bindAsEventListener(this));
		this.change(1);
	},
	get:function(alt){
		return $('team-image_'+(alt?this.target:!this.target));
	},	
	change:function(num){
		if(!this.ready) return;
		this.ready = false;
		// FADE
		if(this.current != -1){ // not first
			new Effect.Move(this.get(false), {
				duration:.3,
				transition:Effect.Transitions.sinoidal,
				y:num*-100
			});
		}else{
			this.current = Math.floor(Math.random()*this.array.length);
		}
		this.current += num;
		if(this.current < 0) 
			this.current = this.array.length-1;
		else if(this.current >= this.array.length) 
			this.current = 0;
		// APPER
		$('team-link').href = 'produtos-time/'+this.array[this.current];
		this.get(true).setStyle({left:(-this.current*90)+'px', top:num*150+'px'});
		new Effect.Move(this.get(true), {
			duration:.5,
			transition:Effect.Transitions.SwingFromTo,
			y:10+num*-150,
			afterFinishInternal:function(){this.ready=true}.bind(this)
		});
		this.target = !this.target;
	}
}

/* * *
	LAUNCH
* * */
launch = {
	current:-1,
	target:false,
	array:[],
	initialize: function(array){
		this.array = array;
		var r = '';
		$('launch-image_true').style.width = $('launch-image_false').style.width = (210*array.length)+'px'
		array.each(function(value){
			r += '<img src="upload/launch/'+value[2]+'" width="210" height="142" />';
		});
		$('launch-image_true').innerHTML = $('launch-image_false').innerHTML = r;
		
		this.next();
	},
	get:function(alt){
		return $('launch-image_'+(alt?this.target:!this.target));
	},	
	next:function(){
		$('launch_title').innerHTML = '';
		
		// FADE
		if(this.current != -1){ // not first
			new Effect.Move(this.get(false), {
				duration:.3,
				transition:Effect.Transitions.sinoidal,
				y:-150
			});
		}else{
			this.current = Math.floor(Math.random()*this.array.length);
		}
		this.current++;
		if(this.current < 0) 
			this.current = this.array.length-1;
		else if(this.current >= this.array.length) 
			this.current = 0;
			
		// APPER
		$('launch-link').href = '/lancamentos';//this.array[this.current][1];
		var launchSWF = new SWFObject("swf/launch_title.swf", "launchSWF", "190", "34", "8", "#22211D");
		launchSWF.addVariable("title", this.array[this.current][0]);
		launchSWF.write("launch_title");
		
		this.get(true).setStyle({left:(-this.current*210)+'px', top:150+'px'});
		new Effect.Move(this.get(true), {
			duration:.5,
			transition:Effect.Transitions.SwingFromTo,
			y:-150
		});
		this.target = !this.target;
		
		setTimeout(this.next.bind(this), 8000);
	}
}



var Input = {
	get:function(event){
		if(event.shiftKey)
			return 999;
		if(window.event)
			return window.event.keyCode;
    else if(event)
    	return event.which;
	},
	keys:function(key){
		return [0, Event.KEY_BACKSPACE, Event.KEY_DELETE, Event.KEY_LEFT, Event.KEY_RIGHT, Event.KEY_TAB].include(key);
	},
	price_keys:function(event){
		if(!Input.number_keys(event, true) && Input.get(event) != 188 && Input.get(event) != 110)
			Event.stop(event);
	},	
	number_keys:function(event, stop){
		var key = Input.get(event);
		if(Input.keys(key) || (key > 47 && key < 58) || (key > 95 && key < 106))
			return true;	
		if(stop)
			return false;
		Event.stop(event);
	}
}

var Value = {
	float:function(value){
		value += '';
		if(value.indexOf('.') == -1)
			return value+',00';
		
		while(value.indexOf('.') >= value.length-2)
			value += '0';
		while(value.indexOf('.') < value.length-3)
			value = value.substr(0, value.length-1);
		return value.replace('.', ',');
	}	
}

/* * *
	PURCHASES
* * */
var purchases = {
	count:0,
	initialize:function(){
		Event.observe('purchase-add', 'click', this.add_field.bindAsEventListener(this));
		$('purchase').cleanWhitespace();
		Event.observe('search', 'click', this.search.bindAsEventListener(this));
		Event.observe('discount', 'keydown', Input.price_keys);
		Event.observe('discount', 'blur', this.check_total.bind(this));
		
		Event.observe('deadline', 'focus', function(){
			var target = $('deadline');
			if(target.value == '00/00/00') target.value = '';				
		});
		Event.observe('deadline', 'blur', function(){
			var target = $('deadline');
			if(!target.value) target.value = '00/00/00';				
		});
		
		//Event.observe('restricted_form', 'submit', this.send.bindAsEventListener(this));
		$('restricted_form').getInputs('text').each(function(input){
			Event.observe(input, 'keypress', function(e){
				if(e.keyCode==13){
					Event.stop(e);
					var inputs = $('restricted_form').getInputs('text');
					var idx = inputs.indexOf(this);

					if(idx == inputs.length - 1){
						inputs[0].select();
					}else{
						inputs[idx + 1].focus(); // handles submit buttons  
						inputs[idx + 1].select();
					} 
					return false;
				}  
			});
		});
		Xaprb.InputMask.setupElementMasks();
		
		this.init_field();
	},
	init_field:function(){
		var element = $('purchase').lastChild;
		$A(element.getElementsByTagName('input')).each(function(input){
			input.value = '';
		});
		Event.observe(Element.down(element, 'a'), 'click', this.delete_field.bindAsEventListener(this));
		$('product_'+this.count).innerHTML = 'Entre com a referência';
		Element.addClassName('product_'+this.count, 'alert');
		Event.observe('amount_'+this.count, 'keydown', Input.number_keys);
		Event.observe('amount_'+this.count, 'blur', this.check_field.bind(this, this.count));
		Event.observe('reference_'+this.count, 'keydown', Input.number_keys);
		Event.observe('reference_'+this.count, 'blur', this.check_product.bind(this, this.count));
		Event.observe('price_'+this.count, 'keydown', Input.price_keys);
		Event.observe('price_'+this.count, 'blur', this.check_field.bind(this, this.count));
		Event.observe('refresh_'+this.count, 'click', function(event){Event.stop(event);}.bindAsEventListener(this));

		this.check_field(this.count);
		this.count++;
	},
	add_field:function(event){
		Event.stop(event);
		new Insertion.Bottom($('purchase'), '<div class="seconds">'+$('purchase-field').innerHTML.replace(/_0/g, '_'+this.count)+'</div>');
		this.init_field();
	},
	delete_field:function(event){
		Event.stop(event);
		Event.element(event).parentNode.remove();
		this.check_total();
	},
	check_field:function(num){
		var amount = $('amount_'+num);
		var price = $('price_'+num);
		var price_total = $('price_total_'+num);
		if(!price.value.match(/^([0-9]{1,})(\,[0-9]{0,2})?$/i))
			price.value = '0,00';
		if(isNaN(amount.value) || amount.value < 1)
			amount.value = 1;
			
		var priceUS = price.value.replace(',', '.');
		var price_totalUS = priceUS*amount.value;
		price.value = Value.float(priceUS);
		price_total.innerHTML = $('price_total_'+num+'_hidden').value = Value.float(price_totalUS);
		if(price_totalUS) Element.removeClassName(price_total, 'alert');
		else              Element.addClassName(price_total, 'alert');
		this.check_total();
	},
	check_total:function(){
		var subtotalUS = 0;
		document.getElementsByClassName('price_total_field', 'purchase').each(function(element){
			subtotalUS += parseFloat(element.innerHTML.replace(',', '.'));
		});
		$('subtotal').innerHTML = $('subtotal_hidden').value = Value.float(subtotalUS);
		
		if(!$F('discount').match(/^([0-9]{1,})(\,[0-9]{0,2})?$/i))
			$('discount').value = '0,00';
		var discountUS = $F('discount').replace(',', '.');
		if(discountUS > 100) discountUS = 100;
		$('discount').value = Value.float(discountUS);
		$('total').innerHTML = $('total_hidden').value = Value.float(subtotalUS-(subtotalUS*discountUS/100));
	},
	check_product:function(num){
		if($F('reference_'+num).length==3)
			$('reference_'+num).value = '0'+$F('reference_'+num);
		new Ajax.Request( 
			'area-restrita/ajax/produto/'+$F('reference_'+num), {
				method: 'get',
				onComplete: this.check_product_complete.bind(this, num),
				onFailure: this.failure.bind(this)
			}
		);
		Element.addClassName('product_'+num, 'alert')
		$('product_'+num).innerHTML = '...';
	},
	check_product_complete:function(num, ret){
		ret = ret.responseText.split('|CURE|');
		$('product_'+num).innerHTML = $('product_'+num+'_hidden').value = ret[1];
		$('idproduct_'+num).value = ret[2];
		if(ret[0]=='1') Element.removeClassName('product_'+num, 'alert');
	},
	search:function(event){
		Event.stop(event);
		if(!$F('description')){
			alert('Informe a Razão Social!');
		}else{
			new Ajax.Request( 
				'area-restrita/ajax/cliente/'+encodeURI($F('description')), {
					method: 'get',
					onComplete: this.search_complete.bind(this),
					onFailure: this.failure.bind(this)
				}
			);
			$('search').hide();
		}
	},
	search_complete:function(ret){
		if(ret.responseText){
			ret = ret.responseText.split('|CURE|');
			fields = ['description', 'phone', 'contact', 'cnpj'];
			for(var i=0; i<fields.length; i++)
				$(fields[i]).value = ret[i];
		}else{
			alert('Cliente não encontrado!');
		}
		$('search').show();
	},	
	send:function(){
		if(document.getElementsByClassName('alert', 'purchase')[0]){
			alert('Algo está errado na escolha dos produtos!');
			document.location.hash = '#ie';
		}else if(parseFloat($('total').innerHTML.replace(',', '.')) < 350){
			alert('Pedido mínimo de R$ 350,00!');
		}else{
			$('restricted_form').submit();
		}
		return false;
	},
	failure:function(transport){
		alert('Problemas com a aplicação.\n\nFalha na requisiçao AJAX.\n\nOcorrência: '+transport.status);
	}
}

/* * *
	ZOOMER
* * 
var Zoomer = Class.create();
Zoomer.prototype = {
	initialize: function(element, large, preload){
		this.element = $(element);
		this.image = this.element.down('img');
		if(!preload){
			var image = new Image();
			image.onload = this.initialize.bind(this, element, large, true);
			image.src = this.image.src;
		}else{
			this.position = Position.cumulativeOffset(this.image);
			this.scaleX = 1;
			this.scaleY = 1;
	
			// Large image preloading
			this.preload = new Image();
			this.preload.onload = this.loaded.bind(this);
			this.preload.src = large;
	
			this.image_zoom = Builder.node('img', {src:large});
			this.scroller = Builder.node('div', {className:'zoom-inner'}, [this.image_zoom, Builder.node('div')]);
			this.zoom = Builder.node('div', {className:'zoom'}, [this.scroller]);
			Element.hide(this.zoom);
			Element.hide(this.image_zoom);
			this.element.appendChild(this.zoom);
			this.image.observe('mouseover', this.over.bindAsEventListener(this));
			this.image.observe('mouseout', Element.hide.bind(this, this.zoom));
			this.image.observe('mousemove', this.move.bindAsEventListener(this));
		}
	},
	
	over: function(event){
		Element.show(this.zoom);                    
		this.move(event);
	},
	
	move: function(event){
		var x = Event.pointerX(event) - this.position[0];
		var y = Event.pointerY(event) - this.position[1];
		
		this.scroller.scrollLeft = x * this.scaleX - x;
		this.scroller.scrollTop  = y * this.scaleY - y;
	},
	//()
	loaded: function(){
		Element.show(this.image_zoom);
		this.scaleX = this.preload.width / this.image.getWidth() - (362-194)/194;
		this.scaleY = this.preload.height / this.image.getHeight();
	}
};*/

/* * *
	CATALOG
* * */
var catalog = {
	current: null,

	/* INITIALIZE */
	initialize: function(){
		$$('#catalog-images li.main').each(function(element){
			element.cleanWhitespace();
			Event.observe(element.childNodes[0], 'click', this.click.bindAsEventListener(this));	
		}.bind(this));
	},
	
	/* CLICK */
	click: function(event){
		Event.stop(event);
		var element = Event.element(event);
		if(this.current)
			this._close(element);
		else
			this._open(element);
	},
	
	/* _OPEN */
	_open: function(element){
		element.setStyle({fontSize:'18px'});
		Effect.BlindDown(element.nextSibling, {duration:0.4, transition:Effect.Transitions.sinoidal});
		this.current = element;
	},
	
	/* _CLOSE */
	_close: function (element){
		this.current.setStyle({fontSize:''});
		Effect.BlindUp(this.current.nextSibling, {duration:0.4, transition:Effect.Transitions.sinoidal});
		
		if(this.current == element)
			this.current = null
		else
			this._open(element);
	}
};

/*-----------------------------------------------------------------------------------------------*/

ContentLoaded(window, function(){
	button.initialize();
	IEHover.onTagName('button');
});


/*
 * Copyright (C) 2006 Baron Schwartz <baron at xaprb dot com>
 * http://www.xaprb.com/html-input-mask/html-form-input-mask.html
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by the
 * Free Software Foundation, version 2.1.
 *
 * 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 Lesser General Public License for more
 * details.
 *
 * $Id: html-form-input-mask.js,v 1.6 2006-11-03 04:04:29 baron Exp $
 */

if(typeof(Xaprb) === 'undefined')
	Xaprb = new Object();

Xaprb.InputMask = {
   masks: {
      date_iso: {
         format: '    -  -  ',
         regex:  /\d/
      },
      date_us: {
         format: '  /  /    ',
         regex:  /\d/
      },
			deadline: {
         format: '  /  /  ',
         regex:  /\d/
			},
      time: {
         format: '  :  :  ',
         regex:  /\d/
      },
      phone: {
         format: '(   )   -    ',
         regex:  /\d/
      },
      ssn: {
         format: '   -  -    ',
         regex:  /\d/
      },
      visa: {
         format: '    -    -    -    ',
         regex:  /\d/
      }
   },

   /* Finds every element with class input_mask and applies masks to them.
    */
   setupElementMasks: function() {
      if ( document.getElementsByClassName ) { // Requires the Prototype library
         document.getElementsByClassName('input_mask').each(function(item) {
            Event.observe(item, 'keypress',
               Xaprb.InputMask.applyMask.bindAsEventListener(item), true);
         });
      }
   },


   /* This is triggered when the key is pressed in the form input.  It is
    * bound to the element, so 'this' is the input element.
    */
   applyMask: function(event) {
      var match = /mask_(\w+)/.exec(this.className);
      if ( match.length == 2 && Xaprb.InputMask.masks[match[1]] ) {
         var mask = Xaprb.InputMask.masks[match[1]];
         var key  = Xaprb.InputMask.getKey(event);

         if ( Xaprb.InputMask.isPrintable(key) ) {
            var ch      = String.fromCharCode(key);
            var str     = this.value + ch;
            var pos     = str.length;
            if ( mask.regex.test(ch) && pos <= mask.format.length ) {
               if ( mask.format.charAt(pos - 1) != ' ' ) {
                  str = this.value + mask.format.charAt(pos - 1) + ch;
               }
               this.value = str;
            }
            Event.stop(event);
         }
      }
   },

   /* Returns true if the key is a printable character.
    */
   isPrintable: function(key) {
      return ( key >= 32 && key < 127 );
   },

   /* Returns the key code associated with the event.
    */
   getKey: function(e) {
      return window.event ? window.event.keyCode
           : e            ? e.which
           :                0;
   }
};



/*LIGHTBOX*/



var LightboxOptions = {
	overlayOpacity: 0.9,
	resizeSpeed: 7,
	borderSize: 2,
	transition: Effect.Transitions.SwingFromTo
};
Object.extend(Element, {
	getRelJS: function(link){
		if(link.getAttribute('rel')){
			var m = link.getAttribute('rel').match(/:([^\[\(]+)/im);
			if(m) return m[1];
		}
	},
	getRelGalery: function(link){
		if(link.getAttribute('rel')){
			var m = link.getAttribute('rel').match(/\[[^\]]+\]/im);
			if(m) return m[0];
		}
	},
	getRelDimensions: function(link){
		if(link.getAttribute('rel')){
			var m = link.getAttribute('rel').match(/\((.*?),(.*?)\)/im);
			if(m) return {w:parseInt(m[1]), h:parseInt(m[2])};	
		}
	}
});

function SelectBoxes(v){
	v = v ? 'visible' : 'hidden';
	$A(document.getElementsByTagName("select")).each(function(select){
		select.style.visibility = v;																												
	});
}

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

var Lightbox = Class.create();

Lightbox.prototype = {
	array: [],
	js: undefined,
	image_array: [],
	image_current: undefined,
	details:false,
	
	initialize: function(){	
		this.resizeDuration = (11 - LightboxOptions.resizeSpeed) * 0.15;
		this.overlayDuration = 1;
		this.list();
		//	<div id="overlay" style="display:none"></div>
		//	<div id="lightbox_loading">
		//		<img src="images/loading.gif">
		//	</div>
		//	<div id="lightbox_limit">
		//		<div id="lightbox">
		//			<div id="lightbox_top">
		//				<a href="#" id="iClose" class="icon"></a>
		//			</div>
		//			<div id="lightbox_content">
		//				<div class="top"><div></div></div>
		//				<div id="lightbox_image">
		//					<img id="lightbox_img">
		//				</div>
		//				<div class="bottom"><div></div></div>
		//			</div>
		//			<div id="lightbox_data">
		//				<div class="caption"></div>
		//			</div>
		//		</div>
		//	</div>
		var objBody = document.getElementsByTagName("body")[0];
		objBody.appendChild(Builder.node('div', {id:'overlay'}));
    objBody.appendChild(Builder.node('div', {id:'lightbox_loading'}, [
			//Builder.node('img', {src:'images/loading.gif'})
		]));		
		objBody.appendChild(
			Builder.node('div', {id:'lightbox_limit', style:'display:none'}, [
				Builder.node('div', {id:'lightbox'}, [
					Builder.node('div', {id:'lightbox_top'}, [
						Builder.node('a', {href:'#', id:'lightbox_iClose', className:'icon iClose'}, 'Fechar')
					]),
					Builder.node('div', {id:'lightbox_content'}, [
						Builder.node('div', {className:'top'}, [Builder.node('div', {className:'top'})]),
						Builder.node('div', {id:'lightbox_image'}, [
							Builder.node('img', {id:'lightbox_img', style:'display:none'})	
						]),
						Builder.node('div', {className:'bottom'}, [Builder.node('div', {className:'bottom'})])
					]),
					Builder.node('div', {id:'lightbox_data'}, [
						Builder.node('div', {className:'caption'})
					])
				])
			])
		);

		Element.hide('overlay');		
		Event.observe('overlay', 'click', (function(event){Event.stop(event); this.end();}).bindAsEventListener(this));						
		Element.hide('lightbox_loading');
		Element.hide('lightbox_limit');			
		Event.observe('lightbox_limit', 'click', (function(event){
			var e = Event.element(event);
			if(e.id == 'lightbox' || e.id == 'lightbox_limit' || Element.hasClassName(e, 'iClose')){
				Event.stop(event);
				this.end()
			}
		}).bindAsEventListener(this));						
	},
	
	/* * *
		LIST
	* * */
	list:function(element){
		this.array = [];
		$A((element || document).getElementsByTagName('a')).each(function(a){
			var rel = String(a.getAttribute('rel'));
			if(a.getAttribute('href') && rel.toLowerCase().match('lightbox')){
				Event.observe(a, 'click', (function(event){Event.stop(event); this.start(a);}).bindAsEventListener(this));
				this.array.push(a);
			}
		}.bind(this));
	},

	/* * *
		START
	* * */
	start: function(link){
		SelectBoxes(false);

		var arrayPageSize = getPageSize();
		var arrayPageScroll = getPageScroll();
		Element.setStyle('overlay', {width:arrayPageSize[0]+'px', height:arrayPageSize[1]+'px'});
		Element.setStyle('lightbox_limit', {width:arrayPageSize[0]+'px', height:arrayPageSize[1]+'px'});
		
		var top = (arrayPageScroll[1] + ((arrayPageSize[3]-44) / 2));
		Element.setStyle('lightbox_loading', {top:top+'px', left:arrayPageScroll[0]+'px'});
		/* ATENTION */Element.setStyle('lightbox', {top:arrayPageSize[1]+'px', left:-getPageSize()[0]+'px'});
		Element.hide('lightbox_loading');

		new Effect.Appear('overlay', {duration:this.overlayDuration, from: 0.0, to: LightboxOptions.overlayOpacity});

		this.js = eval(Element.getRelJS(link));
		if(this.js){ // js
			this.js_change(Element.getRelDimensions(link));
		}else{ // image
			this.image_array = [];
			this.image_current = 0;
			var galery = Element.getRelGalery(link);
			if(!galery){
				this.image_array.push([link.getAttribute('href'), link.getAttribute('title'), Element.getRelDimensions(link)]);
			}else{
				this.image_array = this.array.inject([], function(array, a, index){
					if(a.getAttribute('href') == link.getAttribute('href'))
						this.image_current = index;
					if(a.getAttribute('href') && Element.getRelGalery(a) == galery)
						array.push([a.getAttribute('href'), a.getAttribute('title'), Element.getRelDimensions(a)]);
					return array;
				}).uniq();
				
				while(this.image_array[this.image_current][0] != link.getAttribute('href'))
					this.image_current++;
			}
			this.image_change();
		}
	},
	
	/* * *
		RESIZE CONTAINER
	* * */
	resizeContainer: function(wNew, hNew, animate){
		var arrayPageSize = getPageSize();
		var arrayPageScroll = getPageScroll();
		var lightboxTop = arrayPageScroll[1] + ((arrayPageSize[3]-hNew) / 2);

		Element.setWidth('lightbox_top', wNew);
		Element.setWidth('lightbox_data', wNew);

		//Element.setStyle('lightbox', {top:lightboxTop+'px'});
		Element.setStyle('lightbox_image', {width:wNew+'px', height:hNew+'px'});
		/* ATENTION */ 
		if($('product')){
			hNew += 44;
			lightboxTop -= 22;
		}
		/* ATENTION */ 
		Element.setStyle('lightbox_content', {width:wNew+'px', height:hNew+'px'});
		if(animate)
			new Effect.Move('lightbox', {y:lightboxTop, transition:LightboxOptions.transition, mode:'absolute', duration:this.resizeDuration*1.5});
		else
			new Effect.Appear('lightbox', {duration:this.resizeDuration});
	},
	
	/* * *
		CHANGE
	* * */
	_change: function(){
		$('lightbox_top').hide();
		//$('lightbox_img').hide();
		$('lightbox_data').hide();
	},
	// JS
	js_change: function(dimensions){
		/*Element.hide('lightbox_image');
		this._change();
		
		this.resizeContainer(dimensions.w, dimensions.h, false);
		this.js.initialize.call(this.js);*/
	},
	// IMAGE
	image_change: function(){
		$('lightbox_limit').show();
		$('lightbox_loading').show();
		$('lightbox_img').hide();
		this._change();

		var imgPreloader = new Image();
		imgPreloader.onload = function(){
			Element.hide('lightbox_loading');
			Element.show('lightbox_image');

			var img = this.image_array[this.image_current];
			Element.setSrc('lightbox_img', img[0]);
			
			var w = [imgPreloader.width], h = [imgPreloader.height];				
			if(img[2]){
				w.push(img[2].w);
				h.push(img[2].h);
			}
			this.resizeContainer(w.max(), h.max(), true);
			
			new Effect.Appear('lightbox_img', {
				duration: this.resizeDuration,
				queue:'end', 
				afterFinish: this.image_details.bind(this)
			});
			this.image_preload();
			
		}.bind(this);
		imgPreloader.src = this.image_array[this.image_current][0];
	},
	
	image_change_nav: function(event, num){
		Event.stop(event); 
		this.end_lightbox(num>0?'left':'right');
		this.image_current += num;
		(function(){
			Element.setStyle('lightbox', {left:(num>0?getPageSize()[0]:-1000)+'px'});
			this.image_change();
		}).bind(this).delay(1050);
	},

	/* * *
		IMAGE DETAILS
	* * */
	image_details: function(){
		this.details = true;
		
		// data
		var objCaption = document.getElementsByClassName('caption', $('lightbox_data'))[0];
		Element.setInnerHTML(objCaption, this.image_array[this.image_current][1]);
		new Effect.BlindDown('lightbox_data', {
			duration:this.resizeDuration,
			afterFinish: function() {
				var arrayPageSize = getPageSize();
				Element.setHeight('overlay', arrayPageSize[1]);
			}
		});
		// top
		new Effect.Parallel([
			new Effect.Move('lightbox', {sync:true, y:-44, duration:this.resizeDuration}),
			new Effect.BlindDown('lightbox_top', {sync:true, duration:this.resizeDuration})
		],{duration:this.resizeDuration});
	},

	/* * *
		IMAGE PRELOAD
	* * */
	image_preload: function(){
		var preloadNextImage, preloadPrevImage;
		if(this.image_array.length > this.image_current + 1){
			preloadNextImage = new Image();
			preloadNextImage.src = this.image_array[this.image_current + 1][0];
		}
		if(this.image_current > 0){
			preloadPrevImage = new Image();
			preloadPrevImage.src = this.image_array[this.image_current - 1][0];
		}
	},

	/* * *
		END
	* * */
	end: function(){
		Effect.Queue.each(function(effect){
			Effect.Queue.remove(effect);
		});
		if(this.js){ // js
			this.js.end();
		}else{ // image
			Element.setStyle('lightbox_top', {height: 'auto'});
			Element.setStyle('lightbox_data', {height: 'auto'});
		}
		Element.hide('lightbox_loading');
		this.end_lightbox('right');
		new Effect.Fade('overlay', {duration: this.overlayDuration});
		SelectBoxes(true);
	},
	
	end_lightbox: function(pos){
		this._change(); /* ?? IE HACK */
		if(this.details)
			Element.setStyle('lightbox', {top:parseFloat(Element.getStyle('lightbox','top'))+44+'px'});
		new Effect.Move('lightbox', {y:getPageSize()[1], x:pos=='right'?getPageSize()[0]:-getPageSize()[0], transition:LightboxOptions.transition, mode:'absolute', duration:this.overlayDuration, beforeFinish:function(){Element.hide('lightbox_limit')}});
		this.details = false
	}	
}

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

var box;
ContentLoaded(window, function(){
	box = new Lightbox();											 
});