var has_console = (typeof console != "undefined");

var dbug = {
	log: function(str) {
		if (typeof console != "undefined") {
			console.log(str);
		} else {
			//alert(str);
		}		
	}
};

function get_obj_str(obj) {
	var res = "";
	for (var prop in obj) {
		res += prop.toString() + ": "+ obj[prop]+",";
	}
	return "{" + res + "}";
}

function hideLinkKeepingArea(el) {
	el.set('opacity', 0.01);
	el.setStyle("cursor", "default");
	el.setProperty("title", "");
}

/* http://davidwalsh.name/jquery-hover-mootools  */
Element.implement({
	'hover': function(fn1,fn2) {
		return this.addEvents({
			'mouseenter': function(e) {
				fn1.attempt(e,this);
			},
			'mouseleave': function(e) {
				fn2.attempt(e,this);
			}
		})
	}
});


var CCDCarrossel = new Class({
	Extends: SimpleSlideShow,
	Implements: [Class.ToElement],
	Binds: ['makeSlide'],
	options: {					
		sliderWidth: 999999,
		//clf
		dynamicLoad: false
	},
	initialize: function(container, options){
		dbug.log("initialize");
		this.setOptions(options);
		this.container = document.id(container);
		this.element = new Element('div').wraps(this.container).setStyles({
			width: this.container.getSize().x,
			overflow: 'hidden',
			position: 'relative'
		});
		this.container.setStyles({
			width: this.options.sliderWidth,
			position: 'relative'
		});
		
		
		//this.parent(options);
		var slides = this.options.slides;
		this.makeSlides(slides);
		this.setCounters();
		this.setUpNav();
		this.now = this.options.startIndex;
		
		dbug.log(this);
		dbug.log(document.id(this.options.prevLink));
		dbug.log(document.id(this.options.nextLink));
		
		//ccd clf
		carNavContainer = document.id(this.options.prevLink).getParent();
		if (carNavContainer) {
			if (this.slides.length <= 1) {
				carNavContainer.empty().set('html', '&nbsp;');
				carNavContainer.setStyle("display", "none");														
			} else {
				carNavContainer.setStyle("display", "block");										
			}
		}
		
		carParent = this.container.getParent().getParent();
		dbug.log("carParent");
		dbug.log(carParent);		
		if ((this.options.dynamicLoad) && (carParent)) {
			els = carParent.getElements("div.car_loading");
			if ($chk(els[0])) this.loadingDiv = els[0];
		}			
			
		//corrige bug (primeira transicao ocorre sem efeito em browsers nao gecko)
		if (!Browser.Engine.gecko) {
			if (this.slides.length > 1) {
				this.fx = this.fx || new Fx.Tween(this.container, {
					property: 'left'
				});
				this.fx.start(-this.slides[this.now].getPosition(this.container).x);			
			}
		}

		dbug.log("ini end " + this.now);
		if (this.slides.length > 0) this.show(this.now);

	},
	makeSlides: function(slides) {
		this.slides = [];
		slides.each(this.makeSlide);
		
		//clf - carrega slides vazios dinamicamente
		if (this.options.dynamicLoad) {
			this.slides_loaded = [];
			slides.each(function(s, idx) {
				this.slides_loaded[idx] = (s.getElements("div").length > 0);
			}.bind(this));
			dbug.log(this.slides_loaded);
		}
		
	},
	makeSlide: function(slide) {
		if (slide.retrieve('slideSetup')) return;
		slide.store('slideSetup', true);
		slide.show();
		var s = new Element('div', {
			styles: {
				'float': 'left',
				width: document.id(this).getSize().x
			}
		}).wraps(slide);
		this.parent(s);
		this.slides.erase(slide);
		this.setCounters();
		s.show();
		s.inject(this.container);
	},
	show: function(index) {
		dbug.log("show " + index);
		if (!this.container) return;
		this.fx = this.fx || new Fx.Tween(this.container, {
			property: 'left'
		});
		if (this.showing) return this.chain(this.show.bind(this, index));
		var now = this.now;

		var s = this.slides[index]; //saving bytes
		if (s) {
			dbug.log(this.now + " x  " + index);
			if (this.now != index) {
				dbug.log("fx start " + this.now + " " + -s.getPosition(this.container).x);
				this.fx.start(-s.getPosition(this.container).x).chain(function(){
					s.addClass(this.options.currentSlideClass);
					this.showing = false;
					this.disableLinks();
					this.callChain();
					this.ajaxLoad(index);					
				}.bind(this));
			}
			this.now = index;
			this.setCounters();
		}
	},
	//clf
	disableLinks: function(now){
		now = $pick(now, this.now);
		dbug.log("disable links " + now);
		var prev = document.id(this.options.prevLink);
		var next = document.id(this.options.nextLink);
		var dlc = this.options.disabledLinkClass;
		if (now > 0) {
			if (prev) prev.removeClass(dlc);
			if (now === this.slides.length-1 && next) next.addClass(dlc);
			else if (next) next.removeClass(dlc)
		}	else { //now is zero
			if (this.slides.length > 0 && next) next.removeClass(dlc);
			if (prev) prev.addClass(dlc);
		}
	},	
	ajaxLoad: function(index) {
		dbug.log("ajaxload " + index);
		if ((this.options.dynamicLoad) && (!this.slides_loaded[index])) {
			url = this.options.ajaxPageUrl + (index + 1);
			dbug.log(url);
			el_to_update =  $(this.slides[index].getElement("div"));
			
			var div_loading = new Element('div', {'class': "car_loading"});
			new Element(
				'img',
				{src: this.options.ajaxLoadingImg}
			).inject(div_loading);
			div_loading.inject(el_to_update)
			dbug.log(el_to_update.innerHTML);
			
			this.ajaxRequest = new Request.HTML({
				url: url,
				data: this.options.ajaxData,
			 	update: el_to_update,
			 	/*
			  	useWaiter: true,
			  	waiterOptions: {
			    	fxOptions: {duration: 400},
			    	baseHref: asset_path + "img/",
				  	useIframeShim: false,			    	
				  	injectWhere: 'inside',			    	
	    			img: {
						src: 'loading_barra3.gif',
						styles: {
							width: 24,
							height: 24
						},
						'class': 'waiterImg'
					}
			  	},*/
			  	onComplete: function() { 
			  		dbug.log("complete");
  					//this.loadingDiv.setStyle("display", "none");
  					//this.slides[index].setStyle("display", "block");
			  		this.slides[index].getElements("div.materia_resumida").each(hover_materia_resumida);
			  		this.slides_loaded[index] = true;
					this.fireEvent('onSlideDisplay', index);			  		
			  		//this.ajaxRequest.waiter.stop();				  		
			  	}.bind(this)				  	
			});
			this.ajaxRequest.send();
		} else {
			this.fireEvent('onSlideDisplay', index);
		}
	}
});


var CCDGaleria = new Class({
	Implements: [Options, Events, Chain],
	Binds: ["show"],
	options: {					
		showDuration: 3000,
		tbActiveClass: 'tb-active',
		createPlayButton: false,
		createCarroussel: true,
		tpp: 5, //thumbs por pagina
		forwardShadowboxClick: false,
		dynamicLoad: false,
		centerHorizontally: false,
		centerVertically: false,
		maxImgWidth: 800,
		maxImgHeight: 800,
		setWidth: true,
		tweenWidth: false, //faz twin de largura e permite crossFade
		crossFadeOptions: {},		
		useDeepLinks: true,		
		deepLinkPrefix: "foto-"
	},
	initialize: function(container, options){
		dbug.log("initialize ccd-galeria");
		this.setOptions(options);
		this.container = document.id(container);
		
		this.painel_container = this.container.getFirst('div').getFirst('.painel');
		this.car_container = this.container.getFirst('.ccd-galeria-carrossel');
		this.setupCarrossel();
		
		this.currentIndex = 0;
		this.currentPage = 1;
		this.interval = null;
		this.thumbs = this.car_container.getElements("img");
		this.imagensAmpliadas = this.painel_container.getElements("li");
		this.status = "play";
		
	
		//deepLinks?
		this.startedFromHash = false;
		if (this.options.useDeepLinks) {
			var hash = location.hash;
			if (hash) {
				var str = (hash.replace(/[\#0-9]/g, ''));	
				var idxHash = parseInt(hash.replace(/[^0-9]/g, ''));	
				dbug.log("str = " + str);
				dbug.log("idxHash = " + idxHash);

				if (str == this.options.deepLinkPrefix && (idxHash < this.thumbs.length)) {
					this.startedFromHash = true;
					this.currentIndex = idxHash;					
				}
			}				
		}		
		this.painel_container.set('morph', {duration: 300});
		
		this.imagensAmpliadas.each(function(img,i){
			img.set('morph', this.options.crossFadeOptions);
			img.set('opacity',0); 
			//if(i != this.currentIndex) { }
		}.bind(this));
		
		if (this.thumbs.length > 0) {
			this.thumbs[this.currentIndex].addClass(this.options.tbActiveClass);			
		}
		this.thumbs.each(function(_img, idx) {
			var _anch = _img.getParent();
			_img.set('tween');
			//_anch.setProperty("href", "#");			
			_anch.addEvent('click', function(evt) {			
				this.stop();
				this.show(idx);
				evt.preventDefault();			
				return false;
			}.bind(this));
		}.bind(this));
		
		if (this.options.forwardShadowboxClick) {
			/*
				problema: imagens do painel sobrepostas com pos:absolute e opacity=0 fazem click sempre na ultima img
				solucao: funcao a seguir repassa o click da img para o anchor, ativando o Shadowbox corretamente
			*/
			this.painel_container.addEvent('click', function() {
				this.stop();
				var anchor_atual = this.imagensAmpliadas[this.currentIndex].getFirst('a');
				anchor_atual.fireEvent("click");
			}.bind(this));
		}
		
		if (this.options.createPlayButton) {
			this.playButton = new Element('a',{
				'class': 'playButton'
			}).inject( this.car_container.getFirst(".carNav"), 'bottom' );
			this.playButton.addEvent('click', this.playButtonClick.bind(this));
		}

		window.addEvent('load',function(){			
			this.show(this.currentIndex);
			if (this.startedFromHash) {			
				this.changeCarPage();			
				this.stop();			
			} else {				
				this.start();				
			}			
		}.bind(this));		

	},
	setupCarrossel: function() {
		this.carObj = this.car_container.retrieve("carrossel");
		
		if (!this.carObj && true) {
			var car_body = this.car_container.getFirst('.car_body');
			this.carObj = new CCDCarrossel2(car_body,
				{
					slides: car_body.getElements("div.car_page"),
					currentIndexContainer: '',
			  		maxContainer: '',
			  		prevLink: this.car_container.getFirst('.car_ant'),
			  		nextLink: this.car_container.getFirst('.car_prox'),
					wrap: true,
					createNavContainer: true,
					createNavLinks: true,
					hideNavKeepingArea: true,
			  		dynamicLoad: false
				}
			);
		}		
	},
	playButtonClick: function() {
		if (this.status == "play") {
			this.stop();
		} else {
			this.show();
			this.start();
		}
	},
	stop: function() {
		this.status = "stop";
		dbug.log("stop"); 
		$clear(this.interval);
		if (this.options.createPlayButton) {
			this.playButton.addClass("playButtonPaused"); 
			this.playButton.setProperty("title", "iniciar slideshow");
		}
	},
	start: function() {
		dbug.log("start");
		//if (Browser.Engine.trident) this.show();
		if (!Shadowbox.isActive() && (this.imagensAmpliadas.length > 1)) {
			dbug.log("ccd-galeria start");			
			$clear(this.interval);  
			this.status = "play";
			this.changeCarPage();
			this.interval = this.show.periodical(this.options.showDuration); 
			if (this.options.createPlayButton) {
				this.playButton.removeClass("playButtonPaused"); 		
				this.playButton.setProperty("title", "pausar slideshow");
			}
		}
	},
	centerOnViewport: function(img, larg, alt) {
		larg = ($defined(larg))? larg : img.getWidth();
		alt  = ($defined(alt))?  alt  : img.getHeight();
		if (this.options.centerHorizontally) {
			dbug.log("-----------------");			
			dbug.log(larg);
			dbug.log(this.options.maxImgWidth);
			_left = Math.round(Math.abs(this.options.maxImgWidth - larg ) / 2);
			dbug.log(_left);
			img.setStyle('left', _left+"px");			
		}
		if (this.options.centerVertically) {		
			_top = Math.round(Math.abs(this.options.maxImgHeight - alt ) / 2);			
			dbug.log("_____top");
			dbug.log(_top);
			dbug.log(this.options.maxImgHeight);
			dbug.log(img);
			dbug.log(alt);
			img.setStyle('top', _top+"px");			
		}

	},
	show: function(idx) {
		dbug.log("show " + idx + " " + this.currentIndex);
		if (Shadowbox.isActive()) {
			this.stop();
			return;
		}
		if (this.showing) return this.chain(this.show.bind(this, idx));

		this.showing = true;
		if (this.options.tweenWidth) {
			this.imagensAmpliadas[this.currentIndex].get('morph').start({'opacity':[0]});	
		} else {
			this.imagensAmpliadas[this.currentIndex].set('opacity',0);			
		}
		
		this.thumbs[this.currentIndex].removeClass(this.options.tbActiveClass);
		this.currentIndex = ($defined(idx) ? idx : (this.currentIndex < this.imagensAmpliadas.length - 1 ? this.currentIndex+1 : 0));
		
		var img 	= this.imagensAmpliadas[this.currentIndex].getFirst("a img");
		var larg 	= img.getWidth();
		var alt 	= img.getHeight();
		if (larg > this.options.maxImgWidth) larg = this.options.maxImgWidth;
		if (this.options.tweenWidth) {
			this.painel_container.get('morph').start({'width': larg});
		} else {
			if (this.options.setWidth) {
				this.painel_container.setStyle('width', larg);			
				this.imagensAmpliadas[this.currentIndex].setStyle('width', larg);			
			}
		}
		
		this.centerOnViewport(img, larg, alt);
		if (larg > this.options.maxImgWidth) larg = this.options.maxImgWidth;
		this.changeCarPage();
		this.thumbs[this.currentIndex].addClass(this.options.tbActiveClass);

		//fade in imagem ampliada
		var mOptions = {'opacity':[1]};
		if (this.options.setWidth) {
			mOptions.width = larg;
		}
		this.imagensAmpliadas[this.currentIndex].get('morph').start(mOptions).chain(function(){
			if (this.options.useDeepLinks) location.hash = this.options.deepLinkPrefix + this.currentIndex;
			this.showing = false;
			this.callChain();
		}.bind(this));
		//this.imagensAmpliadas[this.currentIndex].fade('in');
	},
	changeCarPage: function() {
		if ($chk(this.carObj)) {
			var prevPage = this.carObj.now + 1;
			this.currentPage = parseInt(this.currentIndex / this.options.tpp) + 1;
			if (prevPage != this.currentPage) {
				//troca pagina do carrossel
				dbug.log("indo para pagina " + this.currentPage);
				this.carObj.show(this.currentPage-1);
			}
		}
	}
});

/*
Script: CCDCenterIcon.js
Shows an icon centered over a container with FX

container usually an <a> tag
container style must be { display: block;  position: relative; }
centerElement usually an <img> tag
ie6 has some issues yet

developed by claudio@castelcd.com.br
*/
var CCDCenterIcon = new Class({
	Implements: [Options],
	options: {
		width: 16,
		height: 16,		
		forceRelative: false,	
		useFX: false,
		fxOpacity: 0.8, //applied when useFx==true
		fxOptions: {
			transition:Fx.Transitions.Sine.easeInOut,
			duration: 500,
			wait: false
		},		
		centerElm: 'child', //[child,self,parent]
		resetPositionOnHover: false, //para conteudo que altera dimensao em tempo de execucao: evitar!
		hoverStyle: {
		    position: 'absolute',
		    zIndex: '1000',
		    opacity: 0.8 //applied when useFx==false
		}
	},
	getAbsolutePosition: function() {
		var imageSize = this.centerElm.getSize();
		return {
			left: Math.round(Math.abs(imageSize.x-this.options.width)/2),
			top: Math.round(Math.abs(imageSize.y-this.options.height)/2) 
		};
	},
	setHoverStyle: function() {
		var pos = this.getAbsolutePosition();
		dbug.log(pos);
		this.finalHoverStyle = $merge(
			this.options.hoverStyle, 
			{
				left: pos.left + 'px',
				top:  pos.top + 'px',
				width: this.options.width + 'px',
				height: this.options.height + 'px'
			}
		);		
		
		//fix for ie6 positioning bug
		if (Browser.Engine.trident4) {
			var cFloat = this.centerElm.getStyle("float");
			if (cFloat == "left" || cFloat == "right") {
				//this.options.hoverStyle.position = "relative";
				this.finalHoverStyle.marginLeft = "-" + (pos.left + this.options.width) + "px";
				this.finalHoverStyle.left = "0";
			}
		}		
		
		if (this.options.useFX) {
			this.finalHoverStyle.opacity = 0;
		} else {
			this.finalHoverStyle.display = "none";
		}
	},	
	setupHover: function() {
		//get the size again AFTER the image is loaded - for webkit and other browsers
		var event = (Browser.Engine.trident4)? "onload" : "load";
		this.centerElm.addEvent(event, function() { 
			if (this.hoverElm) {
				var pos = this.getAbsolutePosition();
				this.hoverElm.setStyles(pos);
			}
		}.bind(this));	
				
		this.setHoverStyle();
		
		//create the hover element
		this.hoverElm = new Element('span',	{styles: this.finalHoverStyle});
		this.container.grab(this.hoverElm, 'top');
		
		//if (Browser.Engine.trident4) Browser.fixPNG(this.hoverElm);		
		if (this.options.useFX) {
			this.hoverElm.set('morph', this.options.fxOptions);		
		}
		
		//hover
		this.container.hover(function(e) {
			//dbug.log("hover in");
			if (this.options.resetPositionOnHover) {
				var pos = this.getAbsolutePosition();
				this.hoverElm.setStyles(pos);
			}
			if (this.options.useFX) {
				this.hoverElm.morph({'opacity': [0, this.options.fxOpacity]});				
			} else {
				this.hoverElm.setStyle("display", "block");
			}
		}.bind(this), function(e) {
			//dbug.log("hover out");
			if (this.options.useFX) {
				this.hoverElm.morph({'opacity': [this.options.fxOpacity, 0]});				
			} else {
				this.hoverElm.setStyle("display", "none");
			}
		}.bind(this));	
	},
	initialize: function(container, options){
		dbug.log("CCDCenterIcon initialize");
		this.container = $(container);	
		this.setOptions(options);

		if (this.options.centerElm == "self") {
			this.centerElm = this.container;
		} else if (this.options.centerElm == "parent") {
			this.centerElm = this.container.getParent();	
		} else {
			//default = child
			this.centerElm = this.container.getFirst();
		}
		
		if (this.options.forceRelative) {
			//set the container to { display: block;  position: relative; }
			this.container.setStyles({ 
				display: 'block',  
				position: 'relative'
			});		
		}
		this.setupHover();	
	}
});


$extend(Browser, {
	fixPNG2: function(el) {
		try {
			if (Browser.Engine.trident4){
				el = document.id(el);
				if (!el) return el;
				alert(el);
				if (el.get('tag') == "img" && el.get('src').test(".png")) {
					var vis = el.isDisplayed();
					try { //safari sometimes crashes here, so catch it
						dim = el.getSize();
					}catch(e){}
					if (!vis){
						var before = {};
						//use this method instead of getStyles 
						['visibility', 'display', 'position'].each(function(style){
							before[style] = this.style[style]||'';
						}, this);
						//this.getStyles('visibility', 'display', 'position');
						this.setStyles({
							visibility: 'hidden',
							display: 'block',
							position:'absolute'
						});
						dim = el.getSize(); //works now, because the display isn't none
						this.setStyles(before); //put it back where it was
						el.hide();
					}
					var replacement = new Element('span', {
						id:(el.id)?el.id:'',
						'class':(el.className)?el.className:'',
						title:(el.title)?el.title:(el.alt)?el.alt:'',
						styles: {
							display: vis?'inline-block':'none',
							width: dim.x,
							height: dim.y,
							filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader (src='" 
								+ el.src + "', sizingMethod='scale');"
						},
						src: el.src
					});
					if (el.style.cssText) {
						try {
							var styles = {};
							var s = el.style.cssText.split(';');
							s.each(function(style){
								var n = style.split(':');
								styles[n[0]] = n[1];
							});
							replacement.setStyle(styles);
						} catch(e){ dbug.log('fixPNG1: ', e)}
					}
					if (replacement.cloneEvents) replacement.cloneEvents(el);
					replacement.replaces(el);
				} else if (el.get('tag') != "img") {
				 	var imgURL = el.getStyle('background-image');
					var img_url = imgURL.match(/\((.+)\)/)[1].replace('"', "'");								  					
				 	if (imgURL.test(/\((.+)\)/)){
						alert("progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true', sizingMethod='crop', src=" + img_url + ")");
				 		el.setStyles({
				 			background: '',
				 			filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true', sizingMethod='crop', src=" + img_url + ")"
				 		});
				 	};
				}
			}
		} catch(e) {dbug.log('fixPNG2: ', e)}
	},
  pngTest: /\.png$/, // saves recreating the regex repeatedly
  scanForPngs: function(el, className) {
    className = className||'fixPNG';
    //TODO: should this also be testing the css background-image property for pngs?
    //Q: should it return an array of all those it has tweaked?
    if (document.getElements){ // more efficient but requires 'selectors'
      el = document.id(el||document.body);
      el.getElements('img[src$=.png]').addClass(className);
    } else { // scan the whole page
      var els = $$('img').each(function(img) {
        if (Browser.pngTest(img.src)){
          img.addClass(className);
        }
      });
    }
  }
});



/*
 e24PNGFix
	- MooTools version required: 1.2.2
	Changelog:
		- 1.0: First release
		- added bg displacement code  by CLF july/2009
		- added float/absolute handling by CLF semptember/2009
*/
/*Based on the fixPNG module from MooTools, My Object Oriented Javascript Tools. Copyright (c) 2006-2007 Valerio Proietti, <http://mad4milk.net>, MIT Style License.||Clientcide Copyright (c) 2006-2008, http://www.clientcide.com/wiki/cnet-libraries#license*/
/* Copyright: equipo24 S.L.N.E <http://equipo24.com/> - Distributed under MIT License - Keep this message! */
$extend(Browser, {
	fixPNG: function(el) {
		if (Browser.Engine.trident){
			//el = document.id(el);
			//alert(el.outerHTML);
			var w = el.getStyle('width');
			var h = el.getStyle('height');

			var imgURL = el.getStyle('background');
			if (!imgURL) imgURL = el.getStyle('background-image');

			//bg displacement handling
			var posx = el.getStyle('background-position-x');
			var posy = el.getStyle('background-position-y');

			if (imgURL.test(/\((.+)\)/)){
				el.setStyle('background', '');
				var elFloat = el.getStyle('float');
				elFloat = (elFloat == "left" || elFloat == "right");
				if (elFloat) {
					el.setStyle('position', 'relative');						
				}

				var subEl = new Element('div', {
					'style': 'width: ' + w + ';' + 'height: ' + h + ';' + ' float: left; '+
					"filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true', sizingMethod='crop', src=" + imgURL.match(/\((.+)\)/)[1] + ");"
				});
				if (elFloat) {
					subEl.setStyle('position', "absolute");
					subEl.setStyle('left', "0");					
				}
				
				//bg displacement handling
				if( (Math.abs(parseInt(posx)) > 0) || (Math.abs(parseInt(posy)) > 0) ) {
					subEl.setStyle('position', "absolute");
					subEl.setStyle('width', "1000px");					
					subEl.setStyle('height', "1000px");					
					if (Math.abs(parseInt(posx)) > 0) {
						//alert("X: " + posx);
						subEl.setStyle('left', posx);
					}
					if (Math.abs(parseInt(posy)) > 0) {
						//alert("Y: " + posy);
						subEl.setStyle('top', posy);
					}					
				}
				el.grab(subEl);
			};
		}
	}
});

