﻿/*
	Copyright Nov 2011 - Bruno Torrinha (www.torrinha.com)

script:		site.js
descr:		Common site routines
requires:	MooTools Core: 1.3
Date:		- last Update Dec 2011.
			- First version May 2011.
*/

var site = {

	initialize: function(){

//		site.setup_search();

		site.winScroll = new Fx.SmoothScroll({ wheelStops: false });

		site.roar = new Roar({
			container: $('wrapper'),
			position: 'upperRight',
			duration: 4000,
			margin: {x: 0, y: 5}
		});

		if ($('sidebar').getElement('ul.lstGreen')) { site.setup_listGreen01(); }

		site.cart = new cart( $('carticon'), {
			roar: site.roar,
			onSubmit: function(wrap){
				if (wrap.kartPg){ window.location = '/carro-compras'; }
			}
		});

		$$('div.iCart').each(function(icart){ site.cart.attach('minicart', icart); }, this);
	},

	message_init: function(optDad){
		var dad = (optDad || $('container') );

		var m = site.msg = new Element('div', {
			id: 'msg',
			styles: {
				'display': 'block'
			}
		}).inject( dad, 'top' ).slide('hide');

		m.link = new Element('a', {
			'class': 'close',
			href: '#',
			html: 'fechar',
			events:{
				'click': function(e){
					e.stop();
					site.msg.slide('out').link.hide();
					return false;
				}			
			}
		}).hide();
		m.hd = new Element('span');
		m.text = new Element('span');
		m.adopt( m.link, m.hd, m.text );
	},

	message_send: function( mClass, mTitle, mText ){
		site.winScroll.toElement( site.msg );
		var m = site.msg.set('class', mClass);
		m.hd.set('html', mTitle);
		m.text.set('html', mText);
		m.slide('in').link.show();

		site.msg.link.removeEvent('click');
	},

	setup_search: function(){
		var xSearch = $('search');

		xSearch.getElement('.txt').addEvents({
			'focus': function(ev){
				xSearch.morph({'background-color': '#fff', 'width': '180'});
				this.tween('width', '155');
				ev.target.select();
			},
			'blur': function(ev){
				xSearch.morph({'background-color': '#EBF4E1', 'width': '130'});
				this.tween('width','105');
			}
		});
	},

	product_init: function(){
		var bSizes = ( $('prodSizes') || false );
		var bColors = ( $('prodColors') || false );
		var pCart = $(document.body).getElement('div.pCart');

		pCart = site.cart.attach('prdcart', pCart, {
				costUnit: $('costunit'),
				costTotal: $('costunit').getNext('span.total span'),
				cartClear: pCart.getParent().getNext('li.unitsclr a')
		});

		var newUrl = '';
		var prdUrl = '/produto/' + $('prdUrl').get('value') + '/';

		/*----------------------------------------------------------------------------------------------------------------------------------------  SIZES SETUP ----------- */
		if (bSizes) {
			var _sizeClick = function(e){
				e.stop();
				if(bSizes.selected !== e.target){
					bSizes.selected.removeClass('sizeOn');
					bSizes.selected = e.target.addClass('sizeOn');
					if (bColors) {
						bColors.empty();
						new Request.JSON({
							url: '/produto/changeoptions/',
							onFailure: function(){ site.roar.alert('<p>Ocorreu um erro.</p>'); },
							onSuccess: function(J) {
								var tmpUrl = prdUrl + ((bSizes) ? 'tamanho/' + bSizes.selected.get('text') + '/' : '')			// Set Product Colors
								J.colors.each(function(el){
									var elColor = new Element('a', {
										'id': 'color-' + el.id,
										'href': tmpUrl + 'cor/' + el.url,
										'alt': el.url,
										'title': el.name,
										events: { click: _colorClick.bind(this) }
									}).adopt(
										new Element('img', {
											'src': '/app/writables/cache/prodColors/' + el.filename, 
											'class': (el.selected)? 'imgOn':'', 
											'title': el.name
										})
									).set('opacity','0').inject( bColors ).fade('in');
									if (el.selected) { bColors.selected = elColor.getElement('img'); }
									new FloatingTips( elColor );		//»»» Floating Tips
								});
								site.cart._updateCart(false, J.id, pCart, J.pvp, J.units, (J.pvp * J.units).toFloat().round(2), 0, 0)
							}
						}).send('op=sizeClick&idProduct=' + site.cart.getProductID(pCart) + '&tamanho=' + bSizes.selected.get('text') + '&cor=0' + '&units=' + pCart.QTBox.qtvalue );
					}
				}
				return false;
			};
			bSizes.getElements('a').each(function(el){
				if (el.hasClass('sizeOn')) {
					bSizes.selected = el;
					newUrl = prdUrl + 'tamanho/' + el.get('text') + '/';
				}
				el.addEvent('click', _sizeClick.bind(this) );
			}, this);
		}

		/*----------------------------------------------------------------------------------------------------------------------------------------  COLORS SETUP ----------- */
		if (bColors) {
			var _setupColors = function(colors){
			}
			var _colorClick = function(e){
				e.stop();
				var xSizes = (!bSizes) ? '' : '&tamanho=' + bSizes.selected.get('text');
				if ( bColors.selected !== e.target ) {
					bColors.selected.removeClass('imgOn');
					bColors.selected = e.target.addClass('imgOn');
					new Request.JSON({
						url: '/produto/changeoptions/',
						onFailure: function(){ site.roar.alert('<p>Ocorreu um erro.</p>'); },
						onSuccess: function(J){
							site.cart._updateCart(false, J.id, pCart, J.pvp, J.units, (J.pvp * J.units).toFloat().round(2), 0, 0)
						}
					}).send('op=colorClick&idProduct=' + site.cart.getProductID(pCart) + '&units=' + pCart.QTBox.qtvalue + xSizes
						+ '&cor=' + bColors.selected.getParent().get('id').replace('color-','')
					);
				}
				return false;
			};
			bColors.getElements('a').each(function(el){
				new FloatingTips( el );		//»»» Floating Tips
				if (el.getElement('img').hasClass('imgOn')) {
					bColors.selected = el.getElement('img');
					newUrl = prdUrl + 'cor/' + el.get('alt') + '/';
				}
				el.addEvent('click', _colorClick.bind(this) );
			});
		}
/*
		//»»»»»»»»»»»»»»»»»»»»»»»»»»»»»
		//»»»» Discount per Units  »»»»
		//»»»»»»»»»»»»»»»»»»»»»»»»»»»»»
		var discountLink = ($('discountUnitsLink') || false);
		if (discountLink) {

			var _unitsPriceClick = function(e){							//---------   TODO   ---------
				pCart.def = J.units;									// Total units in cart
				inp.set('value', J.units );							// Set Product ID
				if( costUnit.get('html') != J.costUnit + ' €'){
					costUnit.set('html', J.costUnit + ' €').highlight('#fc3');	// Set new costUnit
				}
			}

			discountLink.addEvent('click', function(e){
				e.stop();

				new Request.JSON({
					url: '/produto/changeoptions/',
					onFailure: function() { 
						site.roar.alert('<p>Ocorreu um erro nos Preços por Quantidade.</p>');
					},
					onSuccess: function(J) {

						J.each(function(el){
							var elDescAgrav = new Element('a', {
								'id': 'units-' + el.units,
								'href': '#units/' + el.units,
								'alt': el.units,
								events: { click: _unitsPriceClick.bind(this) }
							}).adopt(
								new Element('div', {'html': el.costUnit})
							).inject( discountLink, 'after' );

							if (el.selected) { bColors.selected = elDescAgrav.getElement('img'); }
						});
					}
				}).send('op=discountUnitsClick&idProduct=' + inp.get('id').replace('rec-','') 
					+ '&tamanho=' + bSizes.selected.get('text') 
					+ '&cor=' + bColors.selected.getParent().get('id').replace('color-','')
					+ '&units=' + inp.get('value') );
			});
		}
*/

//		History.push( newUrl ); 		// Push the new URL

	},

	setup_listGreen01: function(){
		var vis_Itens = 5;
		var uls = $('sidebar').getElements('ul.lstGreen ul');

		var openedNode = $('sidebar').getElement('ul.lstGreen li a.rootOn') || false;

		uls.each(function(ul, i){
			var nRows = ul.getElements('li').length;

			var expandBtn = ul.getPrevious('a.expand');

			if ( expandBtn){
				ul.visHeight = ul.getElement('li').getSize().y * ( (nRows <= vis_Itens) ? nRows : vis_Itens);
				ul.totalHeight = ul.getSize().y;

				expandBtn.addEvent('click', function(e){
					e.stop();
					expandBtn.toggleClass('open');
					ul.tween('height', (ul.opened) ? ul.visHeight : ul.totalHeight);
					ul.opened = !ul.opened;
					return false;
				});

				if (openedNode) {
					ul.setStyle('height', 0 );
					expandBtn.opened = false;
				} else {
					ul.setStyle('height', ul.visHeight );
					expandBtn.opened = false;
				};
			}
		});
	}
};


var mooCheckbox = new Class({

	Implements: [Events],

	initialize: function(inpRadio) {
		this.sel = '';
		inpRadio.each(function(inp){
			var lbl = inp.getParent('label');
			inp.addEvent('change', function(){
				if (inp.checked){
					this.sel.removeClass('selected');
					this.sel = lbl.addClass('selected');
				}
			}.bind(this));
			if (inp.checked){ this.sel = lbl.addClass('selected'); }
		}.bind(this));
	}
});
