/*
 * iziziCarousel - jQuery Plugin
 * ------------------------------------
 * v1.0 - 12-MAY-2011
 * Author: Nick Cousins
 * ------------------------------------
 * Derived from iziziCarousel plugin v1.0 - 13-FEB-2011 http://www.izizi.co.uk
 *
 * Initialising: $('#yourdiv').iziziCarousel({'images':$('.imageclass'),'width':'100','height':'80'});
 *
 * Options:
 *          images          - this is a jQuery object containing your images - e.g. $('.imageclass')
 *          width           - this is the width of the aperture
 *          height          - this is the height of the aperture
 *          circular        - when the last slide is shown, should the next button take you back to the start?
 *          autoRotate      - should the "next" event be fired automatically every n seconds until the nav is manually clicked?
 *          rotateFrequency - set the frequency in milliseconds for the autoRotate feature
 *
 */

   (function( $ ){

            var icc=null;
            var working=false;
            var circular=true;
            var autoRotate=false;
            var rotateFrequency=5000;
            var carouselID=null;
            var arID=null;
            var lcur = 0;
            var methods = {
                            init : function( options ) {
                            var settings = {
                              'images' : {},
                              'width' : 100,
                              'height' : 100,
                              'circular':true,
                              'autoRotate':false,
                              'rotateFrequency':5000
                            };
                            
                            icc=$(this);
                            return this.each(function(){
                                                /* Setup Settings */
                                                if ( options ) {
                                                        $.extend( settings, options );
                                                }

                                                circular=settings.circular;
                                                autoRotate=settings.autoRotate;
                                                rotateFrequency=settings.rotateFrequency;
                                                if (icc.attr('id')==''){
                                                var cid=null;
                                                var cck=null;
                                                while(icc.attr('id')==''){
                                                cid='iziziCarousel_'+Math.floor(Math.random()*100);
                                                cck=$('#'+cid);
                                                if (cck.length==0){icc.attr('id',cid);}
                                                }
                                                
                                                }
                                                carouselID=icc.attr('id');

                                                /* Build an array of Images (Sanitised) */

                                                var imglist=new Array();
                                                var imgurls = new Array();
                                                
                                                $.each(settings.images,function(index,value){
                                                   var uri = $(this).attr('src');
                                                   uri = uri.replace('http://www.telestack.com','');
                                                   uri = uri.replace('+','%2B');
                                                    imgurls.push(uri);
                                                    imglist.push('<img src="/wp-content/themes/telestack/imgscl.php?w='+settings.width+'&h='+settings.height+'&i='+imgurls[index]+'" class="'+$(this).attr('class')+'" alt="'+$(this).attr('alt')+'"/>');
                                                });

                                                
                                                /* Remove the Image objects from the page */
                                                settings.images.remove();

                                                /* Build the Aperture and Slider */
                                                icc.html('<div class="iziziCarousel_aperture"><div class="iziziCarousel_slider"></div><div class="iziziCarousel_caption"><p></p></div></div><div class="iziziCarousel_prev"/></div><div class="iziziCarousel_navAperture"><div class="iziziCarousel_navigator" style="width:9999px;"></div></div><div class="iziziCarousel_next"/></div></div>');


                                                /* Build Handles for objects  and values*/

                                                var iAperture = icc.children('.iziziCarousel_aperture');
                                                var iSlider = iAperture.children('.iziziCarousel_slider');
                                                var iNavigator = icc.children('.iziziCarousel_navAperture').children('.iziziCarousel_navigator');
                                                var iSlideCount = imglist.length;



                                                /* Add slides */
                                                $.each(imglist, function(index,value){
                                                    iSlider.append(value);
                                                });

                                                /* Populate Navigator */
                                                iNavigator.html('<div class="iziziCarousel_prev"/>');
                                                $.each(imglist,function(index,value){
                                                    var iPage = index+1;
                                                    iNavigator.append('<div style="background:url(/wp-content/themes/telestack/imgscl.php?w=90&h=60&i='+imgurls[index]+');background-size: cover" class="iziziCarousel_page" page="'+iPage +'"/>');
                                                    /* Listener for the Page button */
                                                    iNavigator.children('.iziziCarousel_page:last-child').click(function(){icc.iziziCarousel('page',iPage,false);});
                                                });
                                                iNavigator.append('<div class="iziziCarousel_next"/>');
                                                
                                                iNavigator.width=((iSlideCount*98)+100);

                                                var iPrev = iNavigator.children('.iziziCarousel_prev');
                                                var iNext = iNavigator.children('.iziziCarousel_next');
                                                var iPage = iNavigator.children('.iziziCarousel_page');

                                                /* Build Next and Prev Listeners */

                                                iPrev.click(function(){icc.iziziCarousel('prev');});
                                                iNext.click(function(){icc.iziziCarousel('next');});





                                                /* Setup alignment of slides and aperture */
                                                icc.css({'position':'relative'});
                                                iAperture.css({'position':'relative','width':settings.width+'px','height':settings.height+'px','overflow':'hidden'});
                                                iSlider.css({'position':'absolute','width':(settings.width * iSlideCount)+'px','height':settings.height+'px','left':'0','top':'0'});

                                                /* Set all images to be the size of the aperture */

                                                $.each(iSlider.children(),function(){
                                                    $(this).css({'width':iAperture.width()+'px','height':iAperture.height()+'px','display':'inline-block'});
                                                });

                                                /* Call page 1 for init */
                                                icc.iziziCarousel('page',1,false);

                                                /* Setup Auto-rotate */
                                                if (autoRotate==true)
                                                    {
                                                        arID=setInterval("$('#"+carouselID+"').iziziCarousel('next','circular');",rotateFrequency);
                                
                                                    }



                            });



                            },
                            next : function(circOr) {
                                if (circOr!='circular'){circOr=false;}
                                var iAperture = icc.children('.iziziCarousel_aperture');
                                var iSlider = iAperture.children('.iziziCarousel_slider');
                                var iNavigator = icc.children('.iziziCarousel_navAperture').children('.iziziCarousel_navigator');
                                var iSlideCount = iSlider.children().length;
                                

                            // Get the current page
                                var Position= iSlider.position();
                                if (Position.left==0){var CurPage=1;}else {
                                var CurPage = Math.round(Math.sqrt(Position.left * Position.left)/iAperture.width())+1;}
                                
                            // Is it the last? Go to Page 1
                                if (CurPage==iSlideCount){if (circular==true || circOr=='circular'){icc.iziziCarousel('page',1,circOr);}}
                                else
                                {

                            // If it's not go to the next
                                icc.iziziCarousel('page',CurPage+1,circOr);
                                }



                            },
                            prev : function( ) {

                                    var iAperture = icc.children('.iziziCarousel_aperture');
                                    var iSlider = iAperture.children('.iziziCarousel_slider');
                                    var iNavigator = icc.children('.iziziCarousel_navAperture').children('.iziziCarousel_navigator');
                                    var iSlideCount = iSlider.children().length;


                                // Get the current page
                                    var Position= iSlider.position();
                                    if (Position.left==0){var CurPage=1;}else {
                                    var CurPage = Math.round(Math.sqrt(Position.left * Position.left)/iAperture.width())+1;}

                                // Is it the First? Go to Last
                                    if (CurPage==1){if (circular==true){icc.iziziCarousel('page',iSlideCount,false);}}
                                    else
                                    {

                                // If it's not go to the previous
                                    icc.iziziCarousel('page',CurPage-1,false);
                                    }




                            },
                            page : function(index,circOr) {
                            if (circOr!='circular'){clearInterval(arID);}
                            if (working==false){
                            var iPage = index;
                                working=true;
                                var iAperture = icc.children('.iziziCarousel_aperture');
                                var iSlider = iAperture.children('.iziziCarousel_slider');
                                var iNavigator = icc.children('.iziziCarousel_navAperture').children('.iziziCarousel_navigator');
                                var iSlideCount = iSlider.children().length;
                                var iCaption = iAperture.children('.iziziCarousel_caption');
                                var imageObjects = iSlider.children('img');
                                var altText ='';
                                $.each(imageObjects,function(i,v){
                                    
                                    if (i+1 == iPage)
                                        {
                                            
                                            altText = $(v).attr('alt');
                                        }
                                });
                                
                                
                                var position = iAperture.width() - (iAperture.width() * iPage);
                                iCaption.children('p').fadeOut('fast',function(){
                                    iCaption.children('p').html(altText);
                                    iSlider.animate({left: position}, 500, function() {
                                        $.each(iNavigator.children(),function(index){
                                        $(this).removeClass('current');
                                        $(this).css('opacity','0.5');
                                        if (index==iPage){
                                            $(this).css('opacity','1');
                                            $(this).addClass('current');
                                            var pos = $(this).offset();
                                            var spos = iNavigator.parent().offset();
                                            if (pos.left > spos.left + 575)
                                                {
                                                    
                                                    var lleft=(lcur - $(this).width())-6;
                                                    lcur = lleft;
                                                    lleft=lleft+'px';
                                                    iNavigator.animate({left:lleft});
                                                }
                                                else{
                                                    lcur = 0;
                                                    iNavigator.animate({left:'0'});
                                                }
                                        }
                                        if (iPage==1 && circular==false){iNavigator.children('.iziziCarousel_prev').addClass('disabled');} else {iNavigator.children('.iziziCarousel_prev').removeClass('disabled');}
                                        if (iPage==iSlideCount && circular==false){iNavigator.children('.iziziCarousel_next').addClass('disabled');} else {iNavigator.children('.iziziCarousel_next').removeClass('disabled');}
                                        working=false;
                                       iCaption.children('p').fadeIn('fast');
                                        
                                     });
                                  });
                                });
                                 

                                  }
                            }
                          };

              $.fn.iziziCarousel = function( method ) {

                // Method calling logic
                if ( methods[method] ) {
                  return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
                } else if ( typeof method === 'object' || ! method ) {
                  return methods.init.apply( this, arguments );
                } else {
                  $.error( 'Method ' +  method + ' does not exist on jQuery.iziziCarousel' );
                }

              };

            })( jQuery );  
            
/* =========================================================

// jquery.innerfade.js

// Datum: 2008-02-14
// Firma: Medienfreunde Hofmann & Baldes GbR
// Author: Torsten Baldes
// Mail: t.baldes@medienfreunde.com
// Web: http://medienfreunde.com

// based on the work of Matt Oakes http://portfolio.gizone.co.uk/applications/slideshow/
// and Ralf S. Engelschall http://trainofthoughts.org/

 *
 *  <ul id="news"> 
 *      <li>content 1</li>
 *      <li>content 2</li>
 *      <li>content 3</li>
 *  </ul>
 *  
 *  $('#news').innerfade({ 
 *	  animationtype: Type of animation 'fade' or 'slide' (Default: 'fade'), 
 *	  speed: Fading-/Sliding-Speed in milliseconds or keywords (slow, normal or fast) (Default: 'normal'), 
 *	  timeout: Time between the fades in milliseconds (Default: '2000'), 
 *	  type: Type of slideshow: 'sequence', 'random' or 'random_start' (Default: 'sequence'), 
 * 		containerheight: Height of the containing element in any css-height-value (Default: 'auto'),
 *	  runningclass: CSS-Class which the container get’s applied (Default: 'innerfade'),
 *	  children: optional children selector (Default: null)
 *  }); 
 *

// ========================================================= */


(function($) {

    $.fn.innerfade = function(options) {
        return this.each(function() {   
            $.innerfade(this, options);
        });
    };

    $.innerfade = function(container, options) {
        var settings = {
        		'animationtype':    'fade',
            'speed':            'normal',
            'type':             'sequence',
            'timeout':          2000,
            'containerheight':  'auto',
            'runningclass':     'innerfade',
            'children':         null
        };
        if (options)
            $.extend(settings, options);
        if (settings.children === null)
            var elements = $(container).children();
        else
            var elements = $(container).children(settings.children);
        if (elements.length > 1) {
            $(container).css('position', 'relative').css('height', settings.containerheight).addClass(settings.runningclass);
            for (var i = 0; i < elements.length; i++) {
                $(elements[i]).css('z-index', String(elements.length-i)).css('position', 'absolute').hide();
            };
            if (settings.type == "sequence") {
                setTimeout(function() {
                    $.innerfade.next(elements, settings, 1, 0);
                }, settings.timeout);
                $(elements[0]).show();
            } else if (settings.type == "random") {
            		var last = Math.floor ( Math.random () * ( elements.length ) );
                setTimeout(function() {
                    do { 
												current = Math.floor ( Math.random ( ) * ( elements.length ) );
										} while (last == current );             
										$.innerfade.next(elements, settings, current, last);
                }, settings.timeout);
                $(elements[last]).show();
						} else if ( settings.type == 'random_start' ) {
								settings.type = 'sequence';
								var current = Math.floor ( Math.random () * ( elements.length ) );
								setTimeout(function(){
									$.innerfade.next(elements, settings, (current + 1) %  elements.length, current);
								}, settings.timeout);
								$(elements[current]).show();
						}	else {
							alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');
						}
				}
    };

    $.innerfade.next = function(elements, settings, current, last) {
        if (settings.animationtype == 'slide') {
            $(elements[last]).slideUp(settings.speed);
            $(elements[current]).slideDown(settings.speed);
        } else if (settings.animationtype == 'fade') {
            $(elements[last]).fadeOut(settings.speed);
            $(elements[current]).fadeIn(settings.speed, function() {
							removeFilter($(this)[0]);
						});
        } else
            alert('Innerfade-animationtype must either be \'slide\' or \'fade\'');
        if (settings.type == "sequence") {
            if ((current + 1) < elements.length) {
                current = current + 1;
                last = current - 1;
            } else {
                current = 0;
                last = elements.length - 1;
            }
        } else if (settings.type == "random") {
            last = current;
            while (current == last)
                current = Math.floor(Math.random() * elements.length);
        } else
            alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');
        setTimeout((function() {
            $.innerfade.next(elements, settings, current, last);
        }), settings.timeout);
    };

})(jQuery);
