/* jQuery.preloader - v0.95 - K Reeve aka BinaryKitten
*
* v0.95
* 	# Note - keeping below v1 as really not sure that I consider it public usable.
* 	# But it saying that it does the job it was intended to do.
* 	Added Completion of loading callback.
* 	Main Reworking With Thanks to Remy Sharp of jQuery for Designers
*
*
* v0.9
* 	Fixed .toString being .toSteing
*
* v0.8
*		Fixed sheet.href being null error (was causing issues in FF3RC1)
*
* v0.7
*		Remade the preLoadImages from jQuery to DOM
*
* v0.6
* 		Fixed IE6 Compatability!
*		Moved from jQuery to DOM
*
* v0.5
* 		Shifted the additionalimages loader in the preLoadAllImages so it wasn't called multiple times
* 		Created secondary .preLoadImages to handle additionalimages and so it can be called on itself
*/
(function( $ ){
    
    $.preLoadImages = function(imageList,callback) {
		var pic = [], i, total, loaded = 0;
		if (typeof imageList != 'undefined') {
			if ($.isArray(imageList)) {
				total = imageList.length; // used later
					for (i=0; i < total; i++) {
						pic[i] = new Image();
						pic[i].onload = function() {
							loaded++; // should never hit a race condition due to JS's non-threaded nature
							if (loaded == total) {
								if ($.isFunction(callback)) {
									callback();
								}
							}
						};
						pic[i].src = imageList[i];
					}
			}
			else {
				pic[0] = new Image();
				pic[0].onload = function() {
					if ($.isFunction(callback)) {
						callback();
					}
				}
				pic[0].src = imageList;
			}
		}
		pic = undefined;
	};

	$.preLoadCSSImages = function(callback) {
		var pic = [], i, imageList = [], loaded = 0, total, regex = new RegExp("url\((.*)\)",'i'),spl;
		var cssSheets = document.styleSheets, path,myRules,Rule,match,txt,img,sheetIdx,ruleIdx;
		for (sheetIdx=0;sheetIdx < cssSheets.length;sheetIdx++){
			var sheet = cssSheets[sheetIdx];
			if (typeof sheet.href == 'string' && sheet.href.length > 0) {
				spl = sheet.href.split('/');spl.pop();path = spl.join('/')+'/';
			}
			else {
				path = './';
			}
			myRules = sheet.cssRules ? sheet.cssRules : sheet.rules;
			for (ruleIdx=0;ruleIdx < myRules.length;ruleIdx++) {
				Rule = myRules[ruleIdx];
				txt = Rule.cssText ? Rule.cssText : Rule.style.cssText;
				match = regex.exec(txt);
				if (match != null) {
					img = match[1].substring(1,match[1].indexOf(')',1));
					if (img.substring(0,4) == 'http') {
						imageList[imageList.length] = img;
					}
					else if ( match[1].substring(1,2) == '/') {
						var p2 = path.split('/');p2.pop();p2.pop();p2x = p2.join("/");
						imageList[imageList.length] = p2x+img;
					}
					else {
						imageList[imageList.length] = path+img;
					}
				}
			}
		}

		total = imageList.length; // used later
		for (i=0; i < total; i++) {
			pic[i] = new Image();
			pic[i].onload = function() {
				loaded++; // should never hit a race condition due to JS's non-threaded nature
				if (loaded == total) {
					if ($.isFunction(callback)) {
						callback();
					}
				}
			};
			pic[i].src = imageList[i];
		}

	};
	$.preLoadAllImages = function(imageList,callback) {
		if (typeof imageList != 'undefined') {
			if ($.isFunction(imageList)) {
				callback = imageList;
			}
			else if (!$.isArray(imageList)) {
				imageList = [imageList];
			}
		}
		$.preLoadCSSImages(function(){
			if (imageList.length > 0) {
				$.preLoadImages(imageList,function(){
					callback();
				});
			}
			else {
				callback();
			}
		});
	}

    $.fn.intro = function (options)  {

       var settings = {
          'asLoader'    : true,                     // dodaje biale tlo pod wrapperem
          'background' : 'bckg.jpg',           // ustawia obrazek jako tło
          'enterLinkClass': 'enterLink',       // ustawia klase linkow, ktore w zalozeniu maja sluzyc za przechodzenie do wlasciwej strony
          'fadeDelay'   : 500,                     // odstep pomiedzy kolejnymi fadeami obrazkow
          'fadeTime'    : 1000,                   // czas fadeow
          'howMany'     : 5,                        // ile obrazkow jest do zfadeowania (nie liczac tla 'background')
          'howManyLinks' : 2,
          'linkLang' : ['pl','en'],                  // skroty jezykow dla linkow 'wejdz', skroty te beda poszukiwane w tagu BODY do ew. przeladowania lub nie strony, po kliknieciu "wejdz"
          'imagesCat'   : './images/',          // katalog w ktorym znajduja sie obrazki, wzgledem pliku html
          'imgClass'    : 'introImage',         // zawartosc atrybutu "class" w dodawanych obrazkach
          'tmpCourtain': 'introBckgHide',  // temporary div rozciągniety na szerokosc i wysokosc widocznej strony, zeby przyslonic ladowanie obrazkow, usuwany po utworzeniu rozciagnietego wrappera
          'wrapperHeight' : 430,               // wysokosc calego wrappera obrazkow (przewaznie najwiekszego z elementow, robiacego za tlo)
          'wrapperWidth' : 315                 // szerokosc calego wrappera obrazkow, j.w.
       };

       var opt = $.extend( settings, options );
       var me, pos_top, pos_left;

       return this.each(function() {

           if ( !$('body').hasClass('no-intro') ) { 

           var wrappHeight = $(window).height();

           if ( wrappHeight < $('body').height() ) {
                wrappHeight = $('body').height();
           }

           $('.'+opt.tmpCourtain).remove();

            if (opt.asLoader) {
                $('body').append('<div id=\"introWrapperBckg\"><div id=\"introWrapper\"></div></div>');
                $('#introWrapperBckg').css({
                    'background-color'   :'#fff',
                    'position' : 'absolute',
                    'left': 0,
                    'top' : 0,
                    'height' : wrappHeight+'px',
                    'width' : $(window).width()+'px',
                    'z-index' : 1500
                });
                me = $('#introWrapper');

                me.height(opt.wrapperHeight).width(opt.wrapperWidth);

                pos_top = parseInt( parseInt($(window).height()) / 2 ) - parseInt( opt.wrapperHeight / 2 );
                pos_left = parseInt( parseInt($(window).width()) / 2 ) - parseInt( opt.wrapperWidth / 2 );
            } else {
                me = $(this);
                pos_top = parseInt( parseInt($(window).height()) / 2 ) - parseInt( parseInt(me.height()) / 2 );
                pos_left = parseInt( parseInt($(window).width()) / 2 ) - parseInt( parseInt(me.width()) / 2 );
            }

            if (pos_top < 0 ) {pos_top = 0;}
            if (pos_left < 0 ) {pos_left = 0;}
            var i,j;

            var cacheStr = new Array();

            for (i = 0; i < opt.howMany; i++ ){
                        cacheStr [i] = opt.imagesCat+(i+1)+".png";
                    }

            $.preLoadImages(
                    cacheStr,
                    function() {
                         me.css({
                            'position' : 'absolute',
                            'left' : pos_left,
                            'top' : pos_top
                        }).append("<img src=\""+opt.imagesCat+opt.background+"\" class=\""+opt.imgClass+"\" />" ).hide().fadeIn(opt.fadeTime);



                        for (i = 0; i < opt.howMany; i++ ){
                            me.append("<img src=\""+opt.imagesCat+(i+1)+".png\" class=\""+opt.imgClass+"\" style=\"z-index: "+(100+i)+";\"/>");
                            if ($.browser.msie) {
                                me.find('.'+opt.imgClass+':last').hide().delay((i+1)*opt.fadeDelay).fadeIn(200);
                            }else {
                                me.find('.'+opt.imgClass+':last').hide().delay((i+1)*opt.fadeDelay).fadeIn(opt.fadeTime);
                            }

                        }

                        for (j = 0; j < opt.howManyLinks; j++) {
                            me.append(
                                '<div class=\"'+ opt.enterLinkClass +' '+opt.enterLinkClass + j +'\" rel=\"'+ opt.linkLang[j] +'\" style=\"z-index: '+(100+i+j)+';\"><a href=\"#\"></a></div>'
                            ).find('.'+opt.enterLinkClass+j).hide().delay((j+i+1)*opt.fadeDelay).fadeIn(opt.fadeTime/2);
                            if ( $('body').attr('rel') == opt.linkLang[j] ) {
                                $('.'+opt.enterLinkClass+j).addClass('defLink');
                            }
                        }

//                        $('.'+ opt.enterLinkClass + ' a' ).click(function(e) {
                        $('.'+opt.enterLinkClass ).click(function(e) {
                            e.preventDefault();
                            if ( $(this).hasClass('defLink') ) {
                                $('#introWrapperBckg').fadeOut(opt.fadeDelay).delay(opt.fadeDelay).queue(function() {$(this).remove();} );
//                                $('#introWrapperBckg').hide().delay(opt.fadeDelay).queue(function() {$(this).remove();} );
                            } else {
                                window.location = './?lang=' + $(this).attr('rel');
                            }
                            
                        });

                    }
            )
            
           
         }
       });

       
    };
    
})( jQuery );
