/**
* skrypt do swapu flashy
* @uses SWFObject, jQuery
*/

if( typeof _auDebug != 'function' ){
    /**
    * @param mixed mixData in - dane do debugu
    */
   var _auDebug = function(mixData)
   {
      if(typeof console == 'function' || typeof console == 'object')
         console.log(mixData);
      
      return true;
   }
}

function getFlashMovieObject(movieName)
{
  if (window.document[movieName]) 
  {
    return window.document[movieName];
  }
  if (navigator.appName.indexOf("Microsoft Internet")==-1)
  {
    if (document.embeds && document.embeds[movieName])
      return document.embeds[movieName]; 
  }
  else // if (navigator.appName.indexOf("Microsoft Internet")!=-1)
  {
    return document.getElementById(movieName);
  }
}

var g_test = null;
var swfSwapper_clientIsIe = navigator.appName.indexOf('Microsoft') != -1;

/**
 * @param string strWrapperSelector in - selektor jQuery do wrappera
 * @param array aSwfList in - tablica flashy ktore chcemy odgrywac
 * 
 */
function auSwfSwapper(strWrapperSelector, aSwfList, pConfig){

try{
    // jesli wrapper nie zostal odnaleziony zwracamy false i wychodzimy z konstruktora
    if( $(strWrapperSelector).length < 1 )
        return false;
    
    if( typeof swfobject != 'object' ){
        alert('Nie zainicjalizowano biblioteki SWFObject, wymaganej do prawidłowego działania komponentu.');
        return false;
    }
	
	if( aSwfList.length < 1 ){
		alert('brak elementow do wyswietlenia');
		return false;
	}
    
    // alias kontekstu
    var that = this;
    
    /**
     * @type jQuery
     */
    this.pWrapper = $(strWrapperSelector);
    
    /**
     * @type jQuery
     */
    this.pCurtain = null;
    
    /**
     * @type array
     */
    this.aSwfList = aSwfList;
    
    /**
     * indeks tablicy aSwfList, ktory wskazuje na aktualnie ogladana pozycje
     * @type int
     */
    this.iCurPos = 0;
    
    /**
     * jesli flash wykonuje jakies animacje, za pomoca tej wartosci mozemy powstrzymywac wykonywanie kolejnych animacji
     * @type bool
     */
    this.bAnimationBusy = false;
    
    /**
     * true jesli animacja wczytuje glownego flasha
     *
     * @type bool
     */
    this.bAnimationLoading = false;
    
    /**
     * obiekt z nazwami klass przypisywanymi elementom kurtyny itp
     */
    this.pConfig =
    {
		iHeight: '260', // wysokosc w pikselach, bez 'px'
		iWidth: '100%',// szerokosc, moze byc podana w proc
                curtainClassName: 'flashCurtain', // nazwa klasy html kurtyny
                flashWrapperId: 'flashcontainer', // htmlowy id wrappera flasha
                iEffectDuration: 800,
                iOutroFrame: 55, // ramka odgrywana po przejsciu do kolejnej animacji
                bInstantClose: false,
		iAnimationDisplayTime: 9, // czas w sekundach, po ktorym zmienia sie slajd animacji
		bAddActor: true //  czy w kurtynie umiescic wezel div o klasie 'curtainActor' - moze byc bool lub int, jesli int to mowi ile ma byc aktorow, w tym przypadku aktorzy otrzymaja po dwie klasy html: 'curtainActor' oraz 'curtainActor<offset>' gdzie offset bedzie liczony od 1
    };
    
    var loadConfigFromObject = function(pObj){
            if( typeof pObj != 'object' ){
                    return false;
            }
            
            for( var i in pObj ){
                    that.pConfig[i] = pObj[i];
            }
            
            return true;
    }
    
    var setLoadingState = function( newVal ){
        
        that.bAnimationLoading = Boolean( newVal );
        
        // reakcja timera
        if( that.bAnimationLoading ){
            that.stopTimer();
        }else{
            that.startTimer();
        }
        
    }
    
    /**
     * podpina kod html kurtyny itp itp do wrappera
     */
    var appendHtml = function(){
        
        that.pWrapper.append( $('<div id="'+that.pConfig.flashWrapperId+'" />') );
        that.pCurtain = $('<div class="'+that.pConfig.curtainClassName+'" />');
        that.pWrapper.append( that.pCurtain );
        
        // opcjonalnie dodanie aktora
        if( typeof that.pConfig.bAddActor == 'boolean' && that.pConfig.bAddActor == true ){
                
                var newActor = $('<div class="curtainActor" />');
                that.pCurtain.append( newActor );
                newActor.append( $('<b />') );
                
        }else if( typeof that.pConfig.bAddActor == 'number' ){
                for( var i = 1; i <= that.pConfig.bAddActor; i++){
                        that.pCurtain.append( $('<div class="curtainActor curtainActor'+i+'" />') );
                }
        }
    }
    
    /**
     * funkcja czysci caly obiekt wrappera, oraz wstawia ponownie elementy takie jak wrapper flasha oraz kurtynke
     */
    var renewHtml = function()
    {
        that.pWrapper.empty();
        appendHtml();
    }
    
    /**
     * renew pod html flasha
     */
    var renewFlashHtml = function()
    {
        that.pWrapper.find('#'+that.pConfig.flashWrapperId).remove();
        that.pWrapper.prepend('<div id="'+that.pConfig.flashWrapperId+'" />');
    }
    
    
    /**
     * ponownie odpala swfObject, pod dane znajdujace sie w elemencie na parametrze o wskazanym offsecie
     * @param int iToIndex in - [OPT] index z tablicy aSwfList, na podstawie ktorego wpisu ma byc wyswietlony flash
     *                          jesli prametr nie zostnaie podany, to przyjmuje wartosc this.iCurPos
     * 
     */
    var reloadSwfObject = function( iToIndex ){
        
        // czyszczenie calego wrappera
        //renewHtml();
        fadeIn(
            function()
            {
                renewFlashHtml();
        
                if( typeof iToIndex == 'undefined' )
                    iToIndex = that.iCurPos;
                
                var flashVars = {};
                var flashParams = { 
                        allowfullscreen: "false", 
                        allowscriptaccess: "always",
                        wmode: 'transparent'
                        //wmode: "opaque" 
                    };
				
                        var embedHandler = function (e){ 
                            var hUchwyt = (e.success) ? e.ref : false; 
                             
                             _auDebug( 'mam uchwyt: ');
                             //_auDebug( typeof hUchwyt['play'] );
                             
                            }; // embed handler
                            
                _auDebug('callback przekazany');

                var ret = swfobject.embedSWF( aSwfList[iToIndex], that.pConfig.flashWrapperId, that.pConfig.iWidth, that.pConfig.iHeight, '9.0.0', 'expressInstall.swf', flashVars, flashParams, {}, embedHandler );
                
                // rozpoczynamy wczytywanie flasha
                    setLoadingState( true );
                
                that.appendFlashLoadListener();
        
            });
    }
    
    this.flashOnload = function(hFlashElement)
    {
        fadeOut();
        hFlashElement.GotoFrame( 0 );
        hFlashElement.Play();
    }
    
    this.appendFlashLoadListener = function( ){
        this.appendAsyncFlashCallback(
                function(hFlash, tInterval){
                    
                    if( hFlash.PercentLoaded() >= 100 ){
                        that.flashOnload(hFlash);
                        clearInterval( tInterval );
                    }
                },
                2,
                30
            );
    }
    
    var hFlashObject = null; // uchwyt tymczasowy do obiektu flasha
    
    /**
     * @param function
     * funkcja przyjmuje parametry:
     *      hFlash - uchwyt obiektu flasha
     * @param int iCallMethod - sposob wywolywania calla, dostepne wartosci
     *      0 - wywoluje raz
     *      1 - wywoluje po uplywie czasu podanego jako kolejny parametr
     *      2 - wywoluje co ilosc milisekund podanych w nastepnym parametrze
     * @param int iCallDelay - ilosc czasu dla callow timerowych
     */
    this.appendAsyncFlashCallback = function( callback, iCallMethod, iCallDelay ){
        
        if( !iCallMethod ) iCallMethod = 0;
        if( !iCallDelay ) iCallDelay = 30;
        
        var tFlashHandlerInterval = setInterval(
            function(){
				//window.document
				//g_test = window[that.pConfig.flashWrapperId];
				
				
				
                //if(  typeof document.getElementById(that.pConfig.flashWrapperId).StopPlay == 'function'){
                if(  isValidFlashHandle( document.getElementById(that.pConfig.flashWrapperId) ) ){
                    // odnaleziono flasha
                    hFlashObject = document.getElementById(that.pConfig.flashWrapperId);
                    
                    //var tInnerInterval = setInterval( function(){ callback( hFlashObject ); }, 30);
                    switch(iCallMethod)
                    {
                        case 0:
                            callback(hFlashObject);
                        break;
                        case 1:
                            setTimeout( function(){ callback(hFlashObject); }, iCallDelay );
                        break;
                        case 2:
                            var tTimer = null;
                            tTimer = setInterval( function(){ callback(hFlashObject, tTimer); }, iCallDelay );
                        break;
                    }
                    
                    clearTimeout( tFlashHandlerInterval );
                }
            }, 50 );
    }
    
    /**
     *
     * @returns int - zwraca ilosc slajdow
     */
    this.getLength = function(){
        return this.aSwfList.length;
    }
    
    /**
     * wyswietla kolejny obrazek
     */
    this.displayNext = function(){
        
        if( this.getLength() <= 1 ){
            return false;
        }
        
        switchIncrementation(true);
        reloadSwfObject();
        
        return true;
    }
    
    this.displayPrev = function(){
        
        if( this.getLength() <= 1 ){
            return false;
        }
        
        switchIncrementation(false);
        reloadSwfObject();
        
        return true;
    }
    
    /**
     * @param bool bPositive in - czy podbijac dodanie, czy cofamy
     */
    var switchIncrementation = function( bPositive )
    {
        // jesli w tablicy jest mniej niz 2 elementow to nie ma sensu przewijac
        if( that.aSwfList.length <= 1)
            return false;
        
        if( that.bAnimationBusy == true )
            return false;
        
        if(bPositive){
            pushIteration();
        }else{
            decrIteration();
        }
        
        return true;
    }
    
    /**
     * sprawdza czy zasob jest poprawnym uchwytem flasha
     */
    var isValidFlashHandle = function( hFlash ){
        
        if( swfSwapper_clientIsIe == true){
			return getFlashMovieObject( that.pConfig.flashWrapperId );
            return false;
        }
        
        return (
                (typeof hFlash == 'object' || typeof hFlash == 'function' )
                    &&
                ( hFlash['StopPlay'] && typeof hFlash['StopPlay'] == 'function' )
            );
        //return ( (typeof hFlash == 'object' || typeof hFlash == 'function' ) && typeof hFlash['StopPlay'] == 'function' );
    }
    
    /**
     * nakladki efektowe, ukrycie kurtyny oraz jej ukazanie
     */
    var fadeIn = function(onComplete){
        
    
    if( that.pConfig.iOutroFrame )
    {
        var tFlashHandlerInterval = setInterval(
            function(){
                
                var flashObj = document.getElementById( that.pConfig.flashWrapperId );
                var altFlash = getFlashMovieObject(that.pConfig.flashWrapperId);
                
                //dump( flashObj );
                
                if( isValidFlashHandle( flashObj ) )
                {
                    clearInterval( tFlashHandlerInterval );
                    flashObj.GotoFrame( that.pConfig.iOutroFrame );
                    flashObj.Play();
                }// _auDebug('tick');
                
                //console.log( typeof flashObj['StopPlay'] );
				
            }, 50 );
            
            
            if( typeof onComplete == 'function')
                that.pCurtain.fadeIn(that.pConfig.iEffectDuration, onComplete);
            else
                that.pCurtain.fadeIn(that.pConfig.iEffectDuration);
                //window.setTimeout( onComplete, that.pConfig.iEffectDuration);
        }
    } // function fadeIn
    
    /**
     * pokazuje kurtyne
     *
     */
    var fadeOut = function(){
      
        if( !that.pConfig.bInstantClose )
        {
            // fade wersja
            that.pCurtain.fadeOut(
                             that.pConfig.iEffectDuration,
                             function(){ that.bAnimationBusy = false; setLoadingState( false ); } // nakazujemy skryptowi przyjmowac animacje
                        );
        }else{   
            // instantowa wersja
            that.pCurtain.hide();
        }
    }
    
    /**
     * przesuwa iteracje o 1 punkt do przodu sprawdzajac przy tym czy nie natrafiono na koniec, jesli tak wraca do poczatku
     */
    var pushIteration = function(){
        
        that.iCurPos++;
        
        // jesli licznik jest za duzy - przewiniecie do startu
        if( that.iCurPos >= that.aSwfList.length ){
            that.iCurPos = 0;
        }
        
        return true;
    }
    
    var decrIteration = function(){
        
        that.iCurPos--;
        
        // jesli mniej niz 0 wracamy na sam koniec listy
        if( that.iCurPos < 0 ){
            that.iCurPos = ( that.aSwfList.length - 1 );
        }
        
        return true;
    }
    
    var appendUtilities = function(){
        
        // timer
        that.startTimer();
        if( isTimerActive() ){
            // bindujemy eventy dla timera
            that.pWrapper.mouseenter(function(){
                
                    if( !that.bAnimationLoading ){
                        that.stopTimer();
                    }
                    
                });
            that.pWrapper.mouseleave(function(){
                
                    if( !that.bAnimationLoading ){
                        that.startTimer();
                    }
                
                });
        }
        
        // koniec appendUtilities
    }
    
    // ------------------------ timer -------------------------------
    
    /**
    * uchwyt do timera, -1 jeśli nie jest włączony
    */
    this.hTimer = -1;
    
    var isTimerActive = function(){ return ( that.hTimer != -1 ); }
    
    /**
     * funkcja odpalana przy "wybiciu" timera
     *
     */
    this.timerTick = function( ){
        that.displayNext();
    }
    
    /**
     * wlacza zegar, jesli zegar jest juz odpalony funkcja zwroci false
     * @returns bool
     */
    this.startTimer = function(){
        
        if( isTimerActive() == true ){
            return false;
        }
        
        if( !this.pConfig.iAnimationDisplayTime ){
            if( typeof this.pConfig.iAnimationDisplayTime == 'undefined' ){
                _auDebug( 'startTimer(): brak wartosci pConfig.iAnimationDisplayTime' );
            }
            
            return false;
        }
        
        this.hTimer = window.setInterval( this.timerTick, this.pConfig.iAnimationDisplayTime * 1000 );
        
        return true;
    }
    
    this.stopTimer = function(){
        
        if( !isTimerActive ){
            return false;
        }
        
        window.clearInterval( this.hTimer );
        this.hTimer = -1;
        
        return true;
    }


    // strumien sterowania konstruktora:
    loadConfigFromObject( pConfig );
    renewHtml();
    appendUtilities();
    reloadSwfObject( 0 );
    
    // przypisujemy eventy dla klawiszy (przewijanie)
    $(document).bind('keyup', function(e){
        // 39 prawo, 37 lewo
            if(
               (e.keyCode == 39 || e.keyCode == 37) && e.shiftKey == true && e.altKey == false
               ){
                that['display'+(e.keyCode == 37 ? 'Prev' : 'Next')]();
            }
         })
		 
	}catch(e){ return false; }
}

var g_flashSwapper = null;
var g_defaultFlashList = ['media/flash/grodzisk.swf', 'media/flash/cowparade.swf', 'media/flash/iasio.swf', 'media/flash/kaldicoffee.swf', 'media/flash/alterman.swf', 'media/flash/epoka.swf'];

$(window).ready( function(){
    
    if( typeof g_preventFlashHeader == 'undefined' || g_preventFlashHeader == false ){

        if( typeof g_customFlashList == 'object' ){
            g_flashSwapper = new auSwfSwapper('div#flashWrapper', g_customFlashList, { iWidth: '100%', iHeight: '140px' } );
        }else{
            g_flashSwapper = new auSwfSwapper('div#flashWrapper', g_defaultFlashList );
        }
    
    }
})
