var FormFocusCleaner = {};
(function(ffc){
	/**
	 * onFocus event.
	 * Checks if field has default value if true then clear it for fast field write.
	 * 
	 * @param e event data
	 */
	function on_focus(e) {
		//console.log(e.data);
		var el = e.data.el;
		if(el.attr('value') == e.data.inp.text) {
			el.attr('value', ''); 
		}
	}
	
	/**
	 * Checks if field is empty if yes put there default value.
	 * 
	 * @param e event data
	 */
	function on_blur(e) {
		var el = e.data.el;
		if(el.attr('value') == '') {
			el.attr('value', e.data.inp.text); 
		}
	}
	
	/**
	 * Register events focus and blur on given fields. Field can be text input or
	 * textarea (others not tested).
	 * 
	 * inputs is array variable with objects that defines field for script for
	 * 
	 * example:
	 * FormFocusCleaner.register([
	 *  {id:'elementdID_1', text:'defaultText_1'},
	 *  {id:'elementdID_2', text:'defaultText_2'}
	 * ]);
	 * 
	 * @param array inputs 
	 */
	function register_fields(inputs) {
		for(i in inputs) {
			var inp = inputs[i];
			var el = jQuery(document.getElementById(inp.id));
			if(el.size() > 0) {
				if(el.attr('value') == '') {
					el.attr('value', inp.text); 
				}
				el.bind('focus', {el: el, inp: inp}, on_focus);
				el.bind('blur', {el: el, inp: inp}, on_blur);
			}
		}
	}
	
	ffc.register = register_fields;
})(FormFocusCleaner);

/**
 *  Author: Łukasz Pietrek l.pietrek@e-bs.pl
 *  Company: e-Business Solutions http://www.e-bs.pl
 *
 *  Application: e-bs Rotator
 *  Description: Rotator
 *
 */

;jQuery.lpplRotator || (function($) {


var instance_counter = 0;

var instances = [];

var _defaults = {
                use_left_right_bt   : true,
                rotate              : true,     
                time                : { out : 0 , interval : 2000 , animation : 1000 },
                html                : {
                                        wrapper     : '<div id="-ebs-rotator-wrapper-[+instance_counter+]" class="-ebs-rotator-wrapper"><div class="-ebs-rotator-content-screen"> </div></div>',
                                        bt_prev     : '<div class="-ebs-rotator-bt-prev"> Poprzedni </div>',
                                        bt_next     : '<div class="-ebs-rotator-bt-next"> Następny </div>'
                                      },
                rotateDir           : 'next'
                };

function __animate ( data ) {
    var tmp, i, stop;
    if( ! ( tmp = instances[ data.instance ] ) ) {
        return false;
    }
    tmp.jqo.contener.animate( { left : '-' + tmp.positionLeft + 'px' }, instances[ data.instance ].conf.time.animation );
}

// @todo funkcja przesuwajšca do wybranego elementu, napisać
function __moveTo ( data ) {
    var tmp, i, stop;
    if( ! ( tmp = instances[ data.instance ] ) ) {
        return false;
    }
}

function __movePrev ( data ) {
    var tmp, i, stop;
    if( ! ( tmp = instances[ data.instance ] ) ) {
        return false;
    }
    if( tmp.positionLeft == 0 ) {
        tmp.positionLeft = tmp.widths.l[ tmp.widths.l.length - 1 ] - tmp.visibleWidth;
        return __animate( data );
    }
    for( i = tmp.widths.l.length, stop = tmp.positionLeft; i > 0; i-- ) {
        if( tmp.widths.l[i] < stop ) {
            tmp.positionLeft = tmp.widths.l[i];
            return __animate( data );
            break;
        }
    }
    tmp.positionLeft = 0;
    return __animate( data ); 
}

// kończy rotację 
function __stopRotation( data ) {
    var tmp, i, stop;
    if( ! ( tmp = instances[ data.instance ] ) ) {
        return false;
    }
    if( tmp.timeids.interval ) {
        clearInterval ( tmp.timeids.interval );
        tmp.timeids.interval = 0;
    }
}

function __moveNext ( data ) { 
    var tmp, i, stop;
    if( ! ( tmp = instances[ data.instance ] ) ) {
        return false;
    }
    for( i = 0, stop = tmp.positionLeft + tmp.visibleWidth; i < tmp.widths.l.length; i++ ) {
        if( tmp.widths.l[i] > stop ) {
            tmp.positionLeft = tmp.widths.l[i] - tmp.visibleWidth;
            return __animate( data );
            break;
        }
    }
    tmp.positionLeft = 0;
    return __animate( data ); 
}

var actions = {
                next        : __moveNext,
                prev        : __movePrev,
                goto        : __moveTo
              };

/**
 *  Dla każdego dodanego rotatora wykonaj inicjację:
 *      - zapisuje jego konfigurację
 *      - zapisuje szerokości jego potomków, to ich będziemy rotować
 *  
 *	@todo: obecnie funkcja pracuje w dwóch trybach
 *		1. podano i action i data: wtedy wywoływana jest akcja z podanymi danymi
 *		2. w przewnym wypadku inicjujemy rotator
 *		Należy rozdzielić te funkcjonalności do różnych funkcji!!! Inaczej wraz z rozwojem aplikacji zrobi się
 *		tutaj bajzel.
 */
function __initRotator ( action, data ) {
    if( typeof( action ) == 'string' && typeof( actions[ action ] ) == 'function' ) {
        data.action = action;
        return actions[ action ]( data );
    }else{
        userConfiguration = action;
    }
    // inicjujemy każdy wybrany element
    $(this).each( function( i, contener ) {

        // każdy nowy element potrzebuje swojego id
        instance_counter++;

        // rozszerzamy konfigurację
        var conf = {}
        $.extend( conf, _defaults);
        $.extend( conf, userConfiguration);

        // generujemy tablicę szerokoci
        var widths  = {l: [] , r: []};
        var tmp = 0;
        var jqo = {};
        jqo.contener = $(contener);
        jqo.contener.children().addClass('-ebs-rotator-item').each(function( index, item ){
            tmp = tmp + $(item).width();
            widths.l.push( tmp );    
            });
        for( i = widths.lenght - 1, j = 0; i >= 0; i--, j++) {
            widths.r[i] = widths.l[j];
        }
        jqo.contener.width( tmp );
		
        // okładamy rotowany element wrapperem
        jqo.wrapper = $( conf.html.wrapper.replace( '[+instance_counter+]',  instance_counter ) );
        jqo.screen = $(jqo.wrapper.children()[0]);
        jqo.contener.addClass('-ebs-rotator-contener').wrap( jqo.wrapper );
        
        // dodajemy przyciski left right
        if( conf.use_left_right_bt ) {
            var ddd = {instance : instance_counter} ;
            jqo.bt_prev = $( conf.html.bt_prev );               // tworzenie obiektu dom
            jqo.contener.parent().before( jqo.bt_prev );        // umiejscowienie przycisku w drzewie strony
            jqo.bt_prev.click( function() { __stopRotation( ddd ); __movePrev( ddd ); } );  // dopięcie eventu do przycisku

            jqo.bt_next = $( conf.html.bt_next );               // tworzenie obiektu dom
            jqo.contener.parent().before( jqo.bt_next );        // umiejscowienie przycisku w drzewie strony
            jqo.bt_next.click( function() { __stopRotation( ddd ); __moveNext( ddd ); } );  // dopięcie eventu do przycisku
        }

        // dodajemy automatyczne rotowanie
        var timeids = { interval: 0 , out: 0 };
        if( conf.rotate ) {
            timeids.interval = setInterval( 
                    'jQuery(document).lpplRotator( "[+dir+]", { instance : [+id+] } );'.
                        replace( '[+id+]', instance_counter ).
                        replace( '[+dir+]', conf.rotateDir ), 
                    conf.time.interval 
                    );
        }

        // przypisujemy konfigurację naszego do dwóch miejsc
        //  - wrappera, skrypty zewnętrze i fastfixy będš miały do niej dojcie
        //    trzeba tylko pamiętać o szybkich ich implementacjach do ciała
        //    pluginu
        //  - do wewnętrznego magazynu instancji
        instances[ instance_counter ] = { 
                        conf :          conf,               // konfiguracja def + user
                        widths :        widths,             // obiekt z zsumowanymi szerokociami w obie strony liczšc
                        maxwidth:       tmp,                // szerokość wszystkich przewijanych elementów
                        visibleWidth:   jqo.contener.parent().width(), // szerokoć widocznych elementów @todo znaleć sposób na pobieranie parametru z jqo.screen.width()
                        instance :      instance_counter,   // id instancji
                        positionLeft :  0,                  // obecne przesunięcie 
                        contener :      jqo.contener,       // obiekt jquery kontenera
                        timeids :       timeids,            // zbiór id produkowanych przez akcje funkcji czasowych
                        jqo :           jqo                 // dowišzania do elementów instancji: sš to obiekty jquery
                        }
        jqo.contener.parent().data( instances[ instance_counter ] );        
        });

    $(this).each( function( i, contener ) {
        //console.dir( $(contener).parent().data() );
        });
}

// extend jquery 
$.fn.extend({ lpplRotator : __initRotator });

})(jQuery);


var FlodRotator = {
    
    start   : function() { 
        FlodRotator.ul = jQuery('#OurClientsRotator ul');
        FlodRotator.perPixelTime = 40;
        FlodRotator.goToNext();
        FlodRotator.ul.hover(
            FlodRotator.onMouseOver,
            FlodRotator.onMouseOut
        );
    },
    
    goToNext : function() {
        FlodRotator.first = FlodRotator.ul.children().first();
        FlodRotator.left = FlodRotator.first.width();
        if(FlodRotator.left < 0) FlodRotator.left = FlodRotator.left * -1;
        FlodRotator.ul.animate(
            {left: (-1*FlodRotator.left)},
            FlodRotator.left*FlodRotator.perPixelTime,
            'linear',
            FlodRotator.switchEls
        )
    },
    
    switchEls : function() {
        FlodRotator.ul.append(FlodRotator.first);
        FlodRotator.ul.attr('style', '');
        FlodRotator.ul.css('left', 0);
        FlodRotator.goToNext();
    },
    
    onMouseOver: function () {
        FlodRotator.ul.stop(true, false);
    },
    
    onMouseOut: function () {
        var tmp = FlodRotator.ul.position().left;
        FlodRotator.ul.animate(
            {left: -1 * FlodRotator.left},
            (FlodRotator.left + tmp)*FlodRotator.perPixelTime,
            'linear',
            FlodRotator.switchEls
        );
    }
    
}

jQuery(document).ready(function(){
    FlodRotator.start();
});

jQuery('#OurServicesBox').ready(function(){
	var $sbBox = jQuery('#OurServicesBox');
	var $items = jQuery('#OurServicesBox .item');
	var half = Math.ceil($items.size() / 2);
	$sbBox.append('<div class="column"> </div><div class="column"> </div>');
	var $columns = jQuery('#OurServicesBox .column');
	$columns
		.first()
		.append($items.slice(0, half))
		.next()
		.append($items.slice(half));
	
});

jQuery(document).ready(function(){
	var $items = jQuery("#PortfolioPage .item");
	var $vcard = jQuery("#PortfolioVCard");
	var $this;
	if($items.size() > 0) {
		function show() {
			$vcard.html($this.children(".hide").first().html());
			$vcard.animate({opacity:1}, 600, "linear");
			var $gal = jQuery("#PortfolioVCard .img_big_wrap a").colorbox({opacity: 0.70, current: "{current} z {total}", photo:true});
		}
		
		function portfolio_click_handler() {
			$this = jQuery(this);
			$this.stop();
			$vcard.animate({opacity:0}, 400, "linear", show);
		}
		
		function init_rels() {
			jQuery("#Rot .item .img_big_wrap").each(function(k, v){
				var $this = jQuery(this);
				if($this.children().size() > 1) {
					$this.children().each(function(i, j){
						jQuery(this).attr("rel", "gallery-" + k);
					});
				}
			});
		}
		
		init_rels();
		
		$items.click(portfolio_click_handler);
		$items.first().click();
		// $vcard.html($items.first().children(".hide").html());
	}
}); 
