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);

function redir(href) {
    window.location = href;
}

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:100}, 500, "swing");
		}
		
		function portfolio_click_handler() {
			$this = jQuery(this);
			$this.stop();
			$vcard.animate({opacity:0}, 500, "swing", show);
		}
		$items.click(portfolio_click_handler);
		$items.first().click();
	}
});

// var dupa = 1;
// function goRotator() {
	// var l = parseInt(jQuery("#Rot ul").css('marginLeft')) || 0;
	// console.log(l);
	
	// var margin = -110; 
	// var i = new Image();
	// i.src = jQuery("#Rot ul li:first img").attr('src');
	// var margin = -i.width+20 ;
	// var time = parseInt(margin) * 20;

	// if(time < 0) time = time * -1;
	

	// jQuery('#Rot ul').animate({marginLeft: margin+'px'},time, 'linear', function(){
		// .remove();
		// jQuery('#Rot ul').append(jQuery('#Rot ul li:first'));
		// jQuery('#Rot ul').attr('style','');
		// goRotator();
	// });
	
	// jQuery('#Rot ul').hover(
		// function() { jQuery(this).stop(false, false); },
		// function() { 
			// var u = jQuery("#Rot ul");
			// var l = parseInt(u.css('marginLeft'));  
			// var f = jQuery('#Rot ul li:first');
			
			// u.animate({marginLeft: (f.width()-l)*-1}, -1*(f.width()-l), 'linear', function(){
				// jQuery('#Rot ul').append(jQuery('#Rot ul li:first'));
				// jQuery('#Rot ul').attr('style','');
				// goRotator();
			// })
			// console.log(jQuery('#Rot ul li:first').width());
		// }
	// );
	
// }
// jQuery().ready(function() {
	// goRotator();
// });


// var FlodRotator = {
	
	// start	: function() { 
		// FlodRotator.rots = jQuery('#FooterRotators').children('.rotator_body');
		// FlodRotator.active = -1;
		// FlodRotator.counter = 0;
		// FlodRotator.perPixelTime = 40;
		// FlodRotator.showNextRotator();
		// FlodRotator.rots.hover(
			// FlodRotator.onMouseOver,
			// FlodRotator.onMouseOut
		// );
	// },
	
	// showNextRotator: function() {
		// FlodRotator.active++;
		// if(FlodRotator.active >= FlodRotator.rots.size()) {
			// FlodRotator.active = 0;
		// }
		// console.log('active == ' + FlodRotator.active);
		// console.log('rots.size() == ' + FlodRotator.rots.size());
		// FlodRotator.ul = jQuery(FlodRotator.rots[FlodRotator.active]).children('div').children('ul');
		// console.log(FlodRotator.ul);
		// FlodRotator.rots.fadeOut(FlodRotator.perPixelTime * 10, function(){
			// FlodRotator.ul.parent().parent().fadeIn(FlodRotator.perPixelTime * 10);
			// FlodRotator.goToNext();
		// });
	// },
	
	// goToNext : function() {
		// FlodRotator.first = FlodRotator.ul.children().first();
		// console.log(FlodRotator.first);
		// console.log(FlodRotator.first.width());
		// return '';
		// 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.stop(true, true);
		// FlodRotator.ul.append(FlodRotator.first);
		// console.log(FlodRotator.ul.position().left);
		// FlodRotator.ul.css('left', 0);
		// FlodRotator.ul.attr('style', '');
		// console.log(FlodRotator.ul.position().left);
		// FlodRotator.counter++;
		// return '';
		// if(FlodRotator.ul.children().size() <= FlodRotator.counter) {
			// FlodRotator.counter = 0;
			// FlodRotator.showNextRotator();
		// } else {
			// 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
		// );
	// }
// }

var FlodRotator = {
	
	start	: function() { 
		FlodRotator.ul = jQuery('.rotator_screen 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(document).ready(function(){
	jQuery('#SiteMenu li').hover(
		function(){jQuery(this).prev().addClass('remove_border_right');},
		function(){jQuery(this).prev().removeClass('remove_border_right');}
	);
});




