/*
* Slides, A Slideshow Plugin for jQuery
* Intructions: http://slidesjs.com
* By: Nathan Searles, http://nathansearles.com
* Version: 1.1.3
* Updated: February 21th, 2011
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.

* Update: August 3rd, 2011
* By: Fabiana Pires
- Dynamic loading of the pictures
- Allow user to set height, width
- Allows only 1 banner without breaking the script
*/

(function($){
$.fn.slides=function(option){
	option=$.extend({},$.fn.slides.option,option),
	$this = this;
	
	$this.append("<div class='slides_container'></div>");	
	
	$.get("uploads/banner.php", { dominio: option.dominio },
		function(xml){
			// retrieve XML data
			var xsUrl,xsLink,xsTitle,xsUrl_swf,xsDesc,i=0;
						
			$(xml).find('info').each(function(){
				xsUrl  =  $(this).find('img').text();
				xsLink  =  $(this).find('link').text();
				xsTitle  =  $(this).find('title').text();
				xsDesc =  $(this).find('desc').text();
				
				//banners frame
				$('.slides_container').append("<div id='banner"+i+"' class='slide'></div>");				
				
				// if NOT swf
				if (xsUrl.search(/swf/i) == -1)
				{
					if ((xsLink != undefined) && (xsLink != ' '))
						$("#banner"+i).append("<a href='"+xsLink+"'><img src='"+xsUrl+"' alt='"+xsTitle+"' /></a>");			
					else
						$("#banner"+i).append("<img src='"+xsUrl+"' alt='"+xsTitle+"' />");		
				}
				else
				{
					xsUrl_swf = xsUrl;	// detection for preloading
					
					if ((xsLink != undefined) && (xsLink != ' '))
						$("#banner"+i).append("<div style=\"height:"+option.height+";position:absolute;width:"+option.width+";\"><a href='"+xsLink+"' target='_blank'><img src=\"css/images/transparente.gif\" border=\"0\" height=\""+option.height+"\" width=\""+option.width+"\" /></a></div><object id=\"FlashID\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+option.width+"\" height=\""+option.height+"\"><param name=\"movie\" value=\""+xsUrl+"\" /><param name=\"quality\" value=\"high\" /><param name=\"wmode\" value=\"transparent\" /><param name=\"swfversion\" value=\"6.0.65.0\" /><embed src=\""+xsUrl+"\" quality=\"high\" wmode=\"transparent\" type=\"application/x-shockwave-flash\" width=\""+option.width+"\" height=\""+option.height+"\"></embed><!--[if !IE]>--><object type=\"application/x-shockwave-flash\" data=\""+xsUrl+"\" width=\""+option.width+"\" height=\""+option.height+"\"><!--<![endif]--><param name=\"quality\" value=\"high\" /><param name=\"swfversion\" value=\"6.0.65.0\" /><!--[if !IE]>--></object><!--<![endif]--></object>");			
					else
						$("#banner"+i).append("<div style=\"height:"+option.height+";position:absolute;width:"+option.width+";\"><img src=\"css/images/transparente.gif\" border=\"0\" height=\""+option.height+"\" width=\""+option.width+"\" /></div><object id=\"FlashID\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+option.width+"\" height=\""+option.height+"\"><param name=\"movie\" value=\""+xsUrl+"\" /><param name=\"quality\" value=\"high\" /><param name=\"wmode\" value=\"transparent\" /><param name=\"swfversion\" value=\"6.0.65.0\" /><embed src=\""+xsUrl+"\" quality=\"high\" wmode=\"transparent\" type=\"application/x-shockwave-flash\" width=\""+option.width+"\" height=\""+option.height+"\"></embed><!--[if !IE]>--><object type=\"application/x-shockwave-flash\" data=\""+xsUrl+"\" width=\""+option.width+"\" height=\""+option.height+"\"><!--<![endif]--><param name=\"quality\" value=\"high\" /><param name=\"swfversion\" value=\"6.0.65.0\" /><!--[if !IE]>--></object><!--<![endif]--></object>");						
				}

				if ((xsTitle != undefined) && (xsTitle != ''))
					$("#banner"+i).append("<div class='caption' style='bottom:0'><p><h1>"+xsTitle+"</h1>"+xsDesc+"</p></div>");	
				i++;
			});	
			
			// determina altura/largura do frame principal
			$('.slides_container').css({'width':option.width});
			
			// determina altura/largura do frame das imagens
			$('.slide').css({'width':option.width,'height':option.height});
			
			// determina largura dos captions
			var cap_width = option.width - 30;
			$('.caption').css({'width':cap_width});

			// determina posição do navigation
			var nav_left = option.width - 53, nav_top = option.height - 45;
			$('#nav').css({'left':nav_left, 'top':nav_top});	
			
			// determina posição do pagination
			var pag_right = - option.width + 120;
			$('.pagination').css({'right': pag_right+'px'});

			return $this.each(function(){
				$('.'+option.container,$(this)).children().wrapAll('<div class="slides_control"/>');
				var elem=$(this),control=$('.slides_control',elem),total=control.children().size(),width=control.children().outerWidth(),height=control.children().outerHeight(),start=option.start-1,effect=option.effect.indexOf(',')<0?option.effect:option.effect.replace(' ','').split(',')[0],paginationEffect=option.effect.indexOf(',')<0?effect:option.effect.replace(' ','').split(',')[1],next=0,prev=0,number=0,current=0,loaded,active,clicked,position,direction,imageParent,pauseTimeout,playInterval;
				
				// se tiver somente 1 banner
				if (total <= 1){
					// habilita o frame da imagem com caption se tiver
					$('.'+option.container,elem).css({display:'block'});
					// desabilita os botoes de prox/ant
					$('.'+option.prev+' img',elem).css({display:'none'});
					$('.'+option.next+' img',elem).css({display:'none'});
					return false;
				}
				
				function animate(direction,effect,clicked){
					if(!active&&loaded){
						active=true;
						switch(direction){
							case'next':
								prev=current;
								next=current+1;
								next=total===next?0:next;
								position=width*2;
								direction=-width*2;
								current=next;
							break;
							case'prev':
								prev=current;
								next=current-1;
								next=next===-1?total-1:next;
								position=0;
								direction=0;
								current=next;
							break;
							case'pagination':
								next=parseInt(clicked,10);
								prev=$('.'+option.paginationClass+' li.current a',elem).attr('href').match('[^#/]+$');
								if(next>prev){position=width*2;direction=-width*2;}
								else{position=0;direction=0;}
								current=next;
							break;
						}
						if(effect==='fade'){option.animationStart();if(option.crossfade){control.children(':eq('+next+')',elem).css({zIndex:10}).fadeIn(option.fadeSpeed,option.fadeEasing,function(){if(option.autoHeight){control.animate({height:control.children(':eq('+next+')',elem).outerHeight()},option.autoHeightSpeed,function(){control.children(':eq('+prev+')',elem).css({display:'none',zIndex:0});control.children(':eq('+next+')',elem).css({zIndex:0});option.animationComplete(next+1);active=false;});}else{control.children(':eq('+prev+')',elem).css({display:'none',zIndex:0});control.children(':eq('+next+')',elem).css({zIndex:0});option.animationComplete(next+1);active=false;}});}else{option.animationStart();control.children(':eq('+prev+')',elem).fadeOut(option.fadeSpeed,option.fadeEasing,function(){if(option.autoHeight){control.animate({height:control.children(':eq('+next+')',elem).outerHeight()},option.autoHeightSpeed,function(){control.children(':eq('+next+')',elem).fadeIn(option.fadeSpeed,option.fadeEasing);});}else{control.children(':eq('+next+')',elem).fadeIn(option.fadeSpeed,option.fadeEasing,function(){if($.browser.msie){$(this).get(0).style.removeAttribute('filter');}});}
		option.animationComplete(next+1);active=false;});}}else{control.children(':eq('+next+')').css({left:position,display:'block'});if(option.autoHeight){option.animationStart();control.animate({left:direction,height:control.children(':eq('+next+')').outerHeight()},option.slideSpeed,option.slideEasing,function(){control.css({left:-width});control.children(':eq('+next+')').css({left:width,zIndex:5});control.children(':eq('+prev+')').css({left:width,display:'none',zIndex:0});option.animationComplete(next+1);active=false;});}else{option.animationStart();control.animate({left:direction},option.slideSpeed,option.slideEasing,function(){control.css({left:-width});control.children(':eq('+next+')').css({left:width,zIndex:5});control.children(':eq('+prev+')').css({left:width,display:'none',zIndex:0});option.animationComplete(next+1);active=false;});}}
		if(option.pagination){$('.'+option.paginationClass+' li.current',elem).removeClass('current');$('.'+option.paginationClass+' li:eq('+next+')',elem).addClass('current');}
					}
				}
				
				function stop(){clearInterval(elem.data('interval'));}
				
				function pause(){if(option.pause){clearTimeout(elem.data('pause'));clearInterval(elem.data('interval'));pauseTimeout=setTimeout(function(){clearTimeout(elem.data('pause'));playInterval=setInterval(function(){animate("next",effect);},option.play);elem.data('interval',playInterval);},option.pause);elem.data('pause',pauseTimeout);}else{stop();}}
				
				if(total<2){return;}
				if(start<0){start=0;}
				if(start>total){start=total-1;}
				if(option.start){current=start;}
				if(option.randomize){control.randomize();}
				
				$('.'+option.container,elem).css({overflow:'hidden',position:'relative'});
				control.children().css({position:'absolute',top:0,left:control.children().outerWidth(),zIndex:0,display:'none'});
				control.css({position:'relative',width:(width*3),height:height,left:-width});
				$('.'+option.container,elem).css({display:'block'});
				if(option.autoHeight){
					control.children().css({height:'auto'});
					control.animate({height:control.children(':eq('+start+')').outerHeight()},option.autoHeightSpeed);
				}

				if(option.preload&&control.find('img').length){
					$('.'+option.container,elem).css({background:'url('+option.preloadImage+') no-repeat 50% 50%'});
					var img=control.find('img:eq('+start+')').attr('src')+'?'+(new Date()).getTime();
					if($('img',elem).parent().attr('class')!='slides_control'){
						imageParent=control.children(':eq(0)')[0].tagName.toLowerCase();
					}
					else{
						imageParent=control.find('img:eq('+start+')');
					}
					
					// for SWF preloading
					if (img.search(/transparente/i) == -1) // if 1st != SWF
					{
						control.find('img:eq('+start+')').attr('src',img).load(function(){
							control.find(imageParent+':eq('+start+')').fadeIn(option.fadeSpeed,option.fadeEasing,function(){
								$(this).css({zIndex:5});
								elem.css({background:''});
								loaded=true;
							});
						});
					}
					else // if 1st == SWF
					{
						$($this).delay(6000);
						loaded=true;
					}
				}
				else{
					control.children(':eq('+start+')').fadeIn(option.fadeSpeed,option.fadeEasing,function(){loaded=true;});
				}				
				
				if(option.bigTarget){control.children().css({cursor:'pointer'});control.children().click(function(){animate('next',effect);return false;});}
				if(option.hoverPause&&option.play){control.bind('mouseover',function(){stop();});control.bind('mouseleave',function(){pause();});}
				if(option.generateNextPrev){
					$('.'+option.container,elem).after('<a href="#" class="'+option.prev+'">Anterior</a>');
					$('.'+option.prev,elem).after('<a href="#" class="'+option.next+'">Próximo</a>');
				}
				
				$('.'+option.next,elem).click(function(e){e.preventDefault();if(option.play){pause();}
				animate('next',effect);});$('.'+option.prev,elem).click(function(e){e.preventDefault();if(option.play){pause();}
				animate('prev',effect);});if(option.generatePagination){elem.append('<ul class='+option.paginationClass+'></ul>');control.children().each(function(){$('.'+option.paginationClass,elem).append('<li><a href="#'+number+'">'+(number+1)+'</a></li>');number++;});}else{$('.'+option.paginationClass+' li a',elem).each(function(){$(this).attr('href','#'+number);number++;});}

				$('.'+option.paginationClass+' li:eq('+start+')',elem).addClass('current');
				$('.'+option.paginationClass+' li a',elem).click(function(){
					if(option.play){
						pause();
					}
					clicked=$(this).attr('href').match('[^#/]+$');
					if(current!=clicked){
						animate('pagination',paginationEffect,clicked);
					}
					return false;
				});
				
				$('a.link',elem).click(function(){
					if(option.play){
						pause();
					}
					clicked=$(this).attr('href').match('[^#/]+$')-1;
					if(current!=clicked){
						animate('pagination',paginationEffect,clicked);
					}
					return false;
				});
				
				if(option.play){
					playInterval=setInterval(function(){
						animate('next',effect);
					},option.play);
					elem.data('interval',playInterval);
				}
			});
	
		}, "xml"
	 );	
	}; // fim da função slider

	$.fn.slides.option={
		dominio:'',
		width: 570,
		height: 270,
		preload:false,
		preloadImage:'/img/loading.gif',
		container:'slides_container',
		generateNextPrev:false,
		next:'next',
		prev:'prev',
		pagination:true,
		generatePagination:true,
		paginationClass:'pagination',
		fadeSpeed:350,
		fadeEasing:'',
		slideSpeed:350,
		slideEasing:'',
		start:1,
		effect:'slide',
		crossfade:false,
		randomize:false,
		play:0,
		pause:0,
		hoverPause:false,
		autoHeight:false,
		autoHeightSpeed:350,
		bigTarget:false,
		animationStart:function(){},animationComplete:function(){}
	};

	$.fn.randomize=function(callback){
		function randomizeOrder(){
			return(Math.round(Math.random())-0.5);
		}
		return($(this).each(function(){var $this=$(this);var $children=$this.children();var childCount=$children.length;if(childCount>1){$children.hide();var indices=[];for(i=0;i<childCount;i++){indices[indices.length]=i;}
	indices=indices.sort(randomizeOrder);$.each(indices,function(j,k){var $child=$children.eq(k);var $clone=$child.clone(true);$clone.show().appendTo($this);if(callback!==undefined){callback($child,$clone);}
	$child.remove();});}}));};	
	
})(jQuery);

(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery);
