var lastHeight = 999999;
var isLoading = false;
var baseURL = "http://przeswietleni.com" + "/";
var myImg= new Array( );
//var baseURL = "";
var baseTitle = document.title;

var nowiPrzeswietleni = { };
var pictureHash = 1;

												
function doIt () {}

// Define corners and opposites arrays
var corners = [
   'bottomLeft', 'bottomRight', 'bottomMiddle',
      'topRight', 'topLeft', 'topMiddle',
         'leftMiddle', 'leftTop', 'leftBottom',
	    'rightMiddle', 'rightBottom', 'rightTop'
	    ];
var opposites = [
	       'topRight', 'topLeft', 'topMiddle',
	          'bottomLeft', 'bottomRight', 'bottomMiddle',
		     'rightMiddle', 'rightBottom', 'rightTop',
		        'leftMiddle', 'leftTop', 'leftBottom'
];
	

$( document ).ready ( function () {
		
		
		var formulkanawysokosc = Math.floor ( $(window).height() - 2*66 );
		$('#pictureGroup').css ( 'height' , formulkanawysokosc );
			
		var labels = $('a') 
		var i = 0;
		for ( i = 0; i< labels.length ; ++i ){
			initFormToolTip.call ( labels [ i ] ); 

		};
		
		
		
} );





function getOpposite ( val ){
		for ( i = 0 ; i < corners.length && corners [ i ] != val ; ++i );
		if ( i > corners.length )
				return null;
		var r = opposites [ i ];
		//alert ( val + " / " + r );
		return r;
}

function isChildOf ( tagName , el ){
		var elements = $( el ).parents ( tagName );
		return  ( elements.length > 0);
}

function initFormToolTip ( ) {
	var toolTip = 'topMiddle';
	var target = 'bottomMiddle';
        
	switch ( $(this).attr ('id') ){
		case "prev":
				toolTip = 'leftMiddle';
				target = getOpposite ( toolTip );
		break;
		
		case "next":
				toolTip = 'rightMiddle';
				target = getOpposite ( toolTip );
		break;
		
		case "up":
				toolTip = 'bottomMiddle';
				target = getOpposite ( toolTip );
		break;
		
	}
		
        if ( isChildOf ( 'tfoot' , this) ) {
		toolTip = 'bottomMiddle';
		target = getOpposite ( toolTip );
		
	}
	
	var className = $(this).attr ( 'class' );
	switch ( className ){
		case "noToolTip":
						return;
				break;
		case "dropDownToolTip":
						toolTip = 'leftMiddle';
						target = getOpposite ( toolTip );
				break;
		return;
	}
	if($(this).data("qtip")) $(this).qtip("destroy");
	$(this).qtip({
		content: "" + this.name, // Set the tooltip content to the current corner
		position: {
			corner: {
			
			tooltip: toolTip, // Use the corner...
			target: target // ...and opposite corner

			}
		},
		show:  {
			ready: false, // Show the tooltip when ready
			when: {
				target: false,
				event: 'mouseover'
			}
		},
		style: {
			border: {
				width: 0,
				radius: 0,
				color: '#ffffff'
			},
			padding: 50, 
			background: '#ffffff',
			color: '#000000',
			
			margin: 5,
			textAlign: 'center',
			tip: false, // Give it a speech bubble tip with automatic corner detection
			name: 'light' // Style it according to the preset 'cream' style
		}
	});
	

}

function setupThis(div) {
		if ( isLoading == true ){
			return;
		}
		if ( typeof ( myImg[nowiPrzeswietleni.indeksZdjecia] ) == "undefined" ) {
			$("#console").html ( "blad typeof ( myImg[i] ) == 'undefined' " );
			return;
		}
		var winH = $(window).height();
		var winW = $(window).width();
		
		if ( Math.abs ( lastHeight - winH ) > 50 ){
			
			show('loading');
			
			var centerImg = $('#' + div);
			var formulkanawysokosc = Math.floor ( winH - 2*66 );
			var formulkanaszerokosc = Math.floor ( winW - 2*66 );
			
			$('#pictureGroup').css ( 'height' , winH - 2*66);
			isLoading = true;
			
			dstURL = baseURL + "test.php?width=" + formulkanaszerokosc + "&height=" + formulkanawysokosc  + "&img=" + myImg[nowiPrzeswietleni.indeksZdjecia]  + "&gallery=" + myGallery;
			
			$("#console").html ( dstURL);
			$(centerImg).attr('src', dstURL  );
			
			lastHeight = winH;
		}
}

function onKeyDown ( event ){
                var code = window.event ? event.which : event.keyCode;
                //alert ( code );
		
		switch ( code ) {
				case 33:
						prevAlbum ( );
				break;
				case 34:
						nextAlbum ( );
				break;
		
		};
		
		if ( ( code < 37 ) || ( code  > 40 ) ){
				return;
		}
		var dy = ( 39 - code );
		var dx = ( 38 - code );
		
		//alert ( "dx " + dx + " \ndy " + dy );
		if ( Math.abs ( dx ) <= 1 ){
				if ( dx < 0 ) {
						next( );
				}else if ( dx > 0 ){
						prev( );
				}
		}
		if ( Math.abs ( dy ) <= 1 ){
				if ( dy < 0 ) {
						next( );
				}else if ( dy > 0 ){
						prev( );
				}
		}
}


function onKeyUp ( event ){
		
}

	$(document).ready(function () {
		
		//jkoutlinemenu.definemenu("projekty", "mymenu1", "mouseover", 180)
		$(document).keydown ( onKeyDown );
		$(document).keyup ( onKeyUp );
		$("#next").click ( function () {
				next();
				show('loading');		
		});
		$("#prev").click ( function () {
				prev();
				show('loading');		
		});
		
		var loading = $('#loading');	
		nowiPrzeswietleni.indeksZdjecia = 0;
		$('#imgSrc').load(function () {
					//$(this).css('display', 'none'); // .hide() doesn't work in Safari when the element isn't on the DOM already
					$(this).fadeIn();
					hide('loading');
					isLoading = false;
					
		}).error(function () {
					isLoading = false;
					// notify the user that the image could not be loaded
		});
		dataLoadStart ( );
		
	}); 
	
	function getFolderName ( ){
		var s =  ( document.location.href );
		
		
		s = s.split ( "//" )[1].split ( "/" );
		s = ( s [ s.length - 1 ] + "" );
		
		if ( s.length <= 0 ){
				s = "title";
		}
		
		s = s.split ("#");
		
		
		s = s[0];
		
		myGallery = s;
		nowiPrzeswietleni.folderName = s;
		
		
		//alert ( s );
		return s;
		
		
	}
	
	function markCurrentFolder ( val){
		var menuItems = getMainMenuLinks ( );
		var i;
		var it3m;
		for ( i = 0 ; i < menuItems.length ; ++ i ){
			it3m = $( menuItems [ i ] );
			if ( it3m.attr ( 'href' ) == val){
				it3m.addClass ( 'current' );
			}
			
		}
		
	
	}
	
	function firstRunSplash ( ) {
		var toolTip = 'bottomMiddle';
		var target = getOpposite ( toolTip );
		
		
		$('#help').qtip({
				content: $('#help').attr ( 'name' ),
				position: {
						corner: {
						
						tooltip: toolTip, // Use the corner...
						target: target // ...and opposite corner
			
						}
				},
				show:  {
					ready: true
				},
				
				hide: {
						fixed: false,
						delay: 500,
						when: {
								target: false,
								event: 'unfocus'
						}
				},
				style: {
					border: {
						width: 1
					},
					padding: 5, 
					background: '#D71574',
					color: '#ffffff',
					margin: 5,
					textAlign: 'center',
					tip: true, // Give it a speech bubble tip with automatic corner detection
					name: 'light' // Style it according to the preset 'cream' style
				}
	        })	
	}
	
	function mySetCookie ( k , v ){
		//$(document).attr ( 'cookie' , k + "=" + v );
		return setCookie ( k , v );
	}
	
	function myGetCookie ( k ){
		return getCookie ( k );
	}
	
	function firstRunCheck ( ){
		//$.aqCookie.domain = 'przeswietleni.com';
		
		var cookieName = "wewew";
		var targetValue = "X";
		var cookieVal;
		
		if ( ( cookieVal = myGetCookie ( cookieName ) ) !=  targetValue   ) {
				firstRunSplash ( );
				mySetCookie ( cookieName , targetValue );		
		} else {
				
		}
		//alert ( cookieVal );
		//alert ( $(document).attr ( 'cookie' ));
		
	}
	
	function dataLoadStart ( ){
		folder = getFolderName ( );
		collection = 'portfolio';
		markCurrentFolder ( folder );
		
		firstRunCheck ( );
		$.getJSON ( baseURL + "/listing.php?folder=" + folder + "&collection=" + collection ,  onDataLoaded );

	}
	
	function onDataLoaded ( data ){
		//alert ( data );
	  	var i = 0;
		var it3m = null;
		
		//sczytac po # przzypiasac do nowiPrzeswietleni.indeksZdjecia
		
		
		var s =  ( document.location.href );
		s = s.split ("#");
		
		if ( typeof( s[ 1 ] ) != 'undefined' ) {
			pictureHash = parseInt ( s[ 1 ] );
		} else {
			pictureHash = 1;				
		}
		nowiPrzeswietleni.indeksZdjecia = pictureHash - 1;
		
		myImg = new Array ( );
		for ( i = 0 ; i < data.length ; ++i ){
			it3m = data [ i ];
			if ( ( it3m.indexOf ( "." ) < 1 ) ) {
				continue;
			} 
			//alert ( it3m  + " " + it3m.indexOf ( "." ) );
			myImg.push ( it3m + "" );
		}
		
		fixButtonsToolTips ( );
		setupThis('imgSrc');
		
		setInterval ( myTimer , 1000 );
	}
	
	function  myTimer ( ) {
		if ( isLoading == true ){
			return;
		}
		setupThis('imgSrc');
	}


	


	/* This script and many more are available free online at
	The JavaScript Source :: http://javascript.internet.com
	Created by: Solomon, the Sleuth :: http://www.freewebs.com/thesleuth/scripts/ */
	
	// List image names without extension
	
	
	// Tell browser the type of file
	
	
	function prevAlbum ( ){
		//alert ( "prev album");
		jump2Folder ( { name: getPreviousFolderName ( nowiPrzeswietleni.folderName ) } );
		
		
	}
	function nextAlbum ( ){
		//alert ( "next album");
		jump2Folder ( { name: getNextFolderName ( nowiPrzeswietleni.folderName ) } );
		
	}
	function jump2Folder ( p ){
		if ( typeof ( p ) != "object" ){
				return;
		}
		if ( typeof ( p.name ) == "string" ){
				document.location.href = p.name;
		}
	}
	function getFolderIndex ( s ){
		var elements = getMainMenuLinks ( );
		var it3m;
		var i = 0;
		if ( s == "title" ){
				return -1;
		}
		for ( i = 0 ; i < elements.length && $( elements [ i ] ).attr ('href').indexOf ( s ) < 0; ++i ){
				
		}
		return i;
	}
		
	
	function getPreviousFolderName ( s ) {
		var i = getFolderIndex ( s );
		i = i > 0 ? i - 1 : i;
		return getFolderNameByIndex ( i );
	}
	function getFolderNameByIndex ( idx ) {
		var elements = getMainMenuLinks ( );
		var idx = Math.max ( 0 , idx ) % elements.length;
		var it3m = elements [ idx ];
		var s = $( it3m ).attr ( 'href' );
		s = s.split ( "/" ).pop ( );
		//alert ( s );
		return s;
	}
	function getMainMenuLinks ( ) {
		return $('th#menu a');
	}
	function getNextFolderName ( s ) {
		var elements = getMainMenuLinks ( );
		var it3m;
		var i = getFolderIndex ( s );
		i = i < elements.length ? i + 1 : i;
		return getFolderNameByIndex ( i );
	}
	function prev( ) {
		if( nowiPrzeswietleni.indeksZdjecia < 1 ){
			var l = nowiPrzeswietleni.indeksZdjecia
		} else {
			var l = nowiPrzeswietleni.indeksZdjecia-=1;
		}
		
		fixButtonsToolTips ( );
		lastHeight = 999999;
		setupThis('imgSrc');
	}
	
	function fixButtonsToolTips ( ){
		$('#next').attr ( 'name' , "Dalej jest <br /><strong>" + ( myImg.length - nowiPrzeswietleni.indeksZdjecia - 1 ) + "</strong> obraz/ów." );
		initFormToolTip.call ( $('#next')[ 0 ] );
		
		$('#prev').attr ( 'name' , "Wstecz jest <br /><strong>" + ( nowiPrzeswietleni.indeksZdjecia ) + "</strong> obraz/ów." );
		initFormToolTip.call ( $('#prev')[ 0 ] );
		
		
		
		document.location.href = baseURL + nowiPrzeswietleni.folderName + "#" + ( nowiPrzeswietleni.indeksZdjecia + 1 );
		$('#pictureHash').html ( "<br /><a href='" + document.location.href + "' title='Kliknij prawym klawiszem myszy by skopiować link do tego zdjęcia: " + document.location.href + "'>" + ( nowiPrzeswietleni.indeksZdjecia + 1 ) + "</a><sub>" + myImg.length +"</sub>" ); //inkrementacja licznika klatek (bottom, right)
		
		
		
		//document.title = "(" + ( nowiPrzeswietleni.indeksZdjecia + 1 ) + " / " + myImg.length + ") | " + nowiPrzeswietleni.folderName + " | " + baseTitle;
	}
	
	
	function next( ) {			
		if( nowiPrzeswietleni.indeksZdjecia > myImg.length - 2 ){
			var l = nowiPrzeswietleni.indeksZdjecia
		} else {
			var l = nowiPrzeswietleni.indeksZdjecia+=1;
		}
		
		fixButtonsToolTips ( );
		
		lastHeight = 999999;
		setupThis('imgSrc');
	}

var state = 'none';
	function show(layer_ref){
		state = 'block';
		
		if(document.all){ //IS IE 4 or 5 (or 6 beta)
			eval("document.all." +layer_ref+ ".style.display = state");
		}
		if (document.layers) { //IS NETSCAPE 4 or below
			document.layers[layer_ref].display = state;
		}
		if (document.getElementById &&!document.all) {
			hza = document.getElementById(layer_ref);
			hza.style.display = state;
		}
	} 
	
	
	function hide(layer_ref){
		state = 'none';
		
		if(document.all){ //IS IE 4 or 5 (or 6 beta)
			eval("document.all." +layer_ref+ ".style.display = state");
		}
		if (document.layers) { //IS NETSCAPE 4 or below
			document.layers[layer_ref].display = state;
		}
		if (document.getElementById &&!document.all) {
			hza = document.getElementById(layer_ref);
			hza.style.display = state;
		}
	} 
