/*
----------------------------------------------------------------------------------
    AJAXGallery v.1
    by Radek N.
----------------------------------------------------------------------------------
*/

var debugVar;

// kolekcja galerii
function Galleries(galleries)
{
    addLoadEvent(initGallery);
    
    // tworzenie obiektow Gallery zgodnie z obiektem konfiguracyjnym
    var arrGalleries = galleries;   
    function initGallery() { 
        for (var i = 0; i < arrGalleries.length; i++) {
            new Gallery(arrGalleries[i]);
        }
    }
}

// galeria
function Gallery(options)
{
    this.ajaxHelper = new net.ContentLoader( 
        this, 
        options.url, 
        "GET", 
        [] 
    );
		
    this.flagBusy = false; // zabezpiecza przed klinkaniem podczas ladowania
    
    var that = this;
    var startElem = options.startElem; // element poczatkowy
	var offsetId = 0; // offset ID dla zapytania do bazy
    var numOfElem = options.numOfElem; // calkowita liczba elementow galerii 
    var container = document.getElementById(options.container); // kontener
    var listItems = null; // elementy LI zawierajace opisy i obrazki
	var numVisibleElem = null; // ilosc widocznych elementow
	var descriptions = Array(); // element z opisem
	var all = container.getElementsByTagName('*'); 
	for (var i = 0; i < all.length; i++) {
		if (all[i].className.indexOf('description') != -1) {
			descriptions.push(all[i]);
		}
	}
    var images = container.getElementsByTagName('img'); // obrazki
	var anchors = container.getElementsByTagName('a'); // linki
    var loaders = Array(); // warstwy z animowanym loaderem
    var prev; // przycisk
    var next; // przycisk
	var canvasArr = Array(); // canvas (obroty w przegladarkach)
    this.elements = Array(); // tablica elementow
	
	if (container) initialize();
		
	function initialize()
	{
		// utworzenie tablicy elementow na podstawie elementów z kodu HTML
		listItems = container.getElementsByTagName('li');		
		numVisibleElem = listItems.length;
		for (var i = 0; i < startElem; i++) {
			that.elements[i] = true;
		}
		
		for (var i = 0; i < listItems.length; i++) {
			var src = listItems[i].getElementsByTagName('img')[0].getAttribute('src');
			if (src.indexOf('/') != -1) { // pobranie nazwy pliku
            	var match = src.split('/');
            	src = match[match.length-1];			
			}
			that.elements[startElem + i] = new Object();
			that.elements[startElem + i].mini = listItems[i].getElementsByTagName('img')[0].getAttribute('src');
			that.elements[startElem + i].full = listItems[i].getElementsByTagName('a')[0].getAttribute('href');		
			that.elements[startElem + i].alt = listItems[i].getElementsByTagName('img')[0].getAttribute('alt');
			that.elements[startElem + i].description = null;
            
            // added detection of original orientation
            if(hasClass(listItems[i].getElementsByTagName('a')[0],'photoHorizontal')) {
                that.elements[startElem + i].orientation = 'photoHorizontal';
            }
            else if(hasClass(listItems[i].getElementsByTagName('a')[0],'photoVertical')) {
                that.elements[startElem + i].orientation = 'photoVertical';
            }
			
			// description jest opcjonalne
			var allDesc = listItems[i].getElementsByTagName('*');			
			for (var j = 0; j < allDesc.length; j++) {
				if (allDesc[j].className.indexOf('description') != -1) {					
					that.elements[startElem + i].description = allDesc[j].lastChild.nodeValue;
				}
			}
		}
		
		for (var i = startElem + numVisibleElem; i < numOfElem; i++) {
			that.elements[i] = true;
		}
		
	
		debugVar = that.elements;
	
		// utworz nawigacje
		createNavigation();
		initRotation(container);
	}
    
            
    function createNavigation() 
    {
        // utworzenie warstw z loaderami
        for (var i = 0; i < listItems.length; i++) {
            var layer = document.createElement('div');
            layer.className = 'loaderLayer';
            listItems[i].appendChild(layer);
            loaders.push(layer);
            layer.style.display = 'none';
        }
    
        // utworzenie nawigacji
        prev = document.createElement('a');
        prev.className = options.buttonPrevClassName;
        var txt = document.createTextNode('Poprzednie');
        prev.appendChild(txt);
        container.appendChild(prev);
        next = document.createElement('a');
        next.className = options.buttonNextClassName;
        var txt = document.createTextNode('Nastepne');
        next.appendChild(txt);
        container.appendChild(next);
        	
		// ukryj jesli nie sa potrzebne
		if (numOfElem <= numVisibleElem) { 
			next.style.display = 'none';
			prev.style.display = 'none';
		}
		if (startElem == 0) prev.style.display = 'none';
				
		if ((startElem + numVisibleElem) >= numOfElem) next.style.display = 'none';
				
        next.onclick = function() {
			if (!that.flagBusy) { 
				startElem = startElem + numVisibleElem; 
				var startFrom = startElem; 
				var howMany = numVisibleElem; 
				if (startElem + numVisibleElem > numOfElem) { 
					// sprawdz czy jest to wielokrotnosc numVisibleElem
					// jesli nie to modyfikuj parametry dla getElements oraz startElem
					//howMany = startElem + (numVisibleElem - numOfElem) + 1;
					howMany = numVisibleElem - (numVisibleElem - (numOfElem - startElem));
					startFrom = startElem; 
					startElem = startElem - (startElem + numVisibleElem - numOfElem); 
				} 
				// pobierz nowe elementy lub update widoku jesli sa juz w buforze
				var needRequest = false;
				for (var i = 0; i < numVisibleElem; i++) {
					if (that.elements[startElem + i] == true) {
						needRequest = true;
					}
				}
				if (needRequest) {
					getElements(startFrom, howMany);
				} else {
					updateView();
				}				
            } else {
                if (window.console && console.firebug && debug) console.log('max');
            }
            return false;
        }
        
        prev.onclick = function() {
            if (!that.flagBusy) {
				startElem = startElem - numVisibleElem;
				var startFrom = startElem;
				var howMany = numVisibleElem;
				if (startElem < 0) {
					// modyfikuj parametry dla getElements oraz startElem
					// jesli brakuje elementow do pobrania
					startElem = 0;
					startFrom = startElem;
				}
				// pobierz nowe elementy lub update widoku jesli sa juz w buforze
				var needRequest = false;
				for (var i = 0; i < numVisibleElem; i++) {
					if (that.elements[startElem + i] == true) {
						needRequest = true;
					}
				}
				if (needRequest) {
					getElements(startFrom, howMany);
				} else {
					updateView();
				}
            } else {
                if (window.console && console.firebug && debug) console.log('min');    
            }
            return false;   
        }
    }
    
    // pobranie elementow
    function getElements(startFrom, howMany)
    { 
            loadersVisibility(true);
            that.flagBusy = true; 
            var startId = startFrom + offsetId;
			that.ajaxHelper.sendRequest('limit=' + howMany + '&offset=' + startId); 
    }

	// wlacza i wylacza warstwy z animowanym loaderem
    function loadersVisibility(option) 
    {
        if (option) {
            for (var i = 0; i < loaders.length; i++) {
                loaders[i].style.display = 'block';
            }      
        } else {
            for (var i = 0; i < loaders.length; i++) {
                loaders[i].style.display = 'none';
            }   
        }
    }
    
    // warstwa widoku
    function updateView()
    {        
					
		 // update opisow
         for (var i = 0; i < descriptions.length; i++) {
            descriptions[i].innerHTML = that.elements[startElem+i].description;
         }
				 
		// update obrazkow i altow
		 for (var i = 0; i < images.length; i++) {
		 	images[i].src = that.elements[startElem+i].mini;
            images[i].alt = that.elements[startElem+i].alt;
		 }
         
         // update linkow
         for (var i = 0; i < images.length; i++) {
			anchors[i].href = that.elements[startElem+i].full;
            anchors[i].title = that.elements[startElem+i].alt;
            
            //uwaga - poprawka do narzucania odpowiedniej klasy do obrazka pionowego/poziomego
            if(that.elements[startElem+i].orientation) {
                remClass(anchors[i],"photoHorizontal");
                remClass(anchors[i],"photoVertical");
                
                addClass(anchors[i],that.elements[startElem+i].orientation);
            }
         }
		 
		 // wlacz/wylacz przyciski
         if (startElem <= 0) {
            prev.style.display = 'none'; 
         } else {
            prev.style.display = 'block';
         }
         if (startElem >= numOfElem - numVisibleElem) {
            next.style.display = 'none'; 
         } else {
            next.style.display = 'block';
         }
		 
		 //update canvas
		 if (canvasArr.length > 0) {
			for (var j = 0; j < canvasArr.length; j++) {
				var canvasContext = canvasArr[j].getContext('2d');
				var imagePreload = new Image();	
				imagePreload.context = canvasContext;
				imagePreload.onload = function() {
					this.context.clearRect(0,0,300,300);
					this.context.drawImage(this, 10, 20);	
				}
				imagePreload.src = that.elements[startElem+j].mini;  	
         	}			
		 } 
		 
    }
    
    // akcje wykonywane po odebraniu requesta
    this.ajaxUpdate = function(request)
    {
        var obj = eval('(' + request.responseText + ')');
		// dodanie nowych elementow do tablicy
		var key = startElem + (numVisibleElem - obj.length); // przesuniecie, gdy nie jest pobierana calosc numVisibleElem
			
		if (window.console && console.firebug && debug) console.log(key); 
		for (var i = 0; i < obj.length; i++) {
			this.elements[key + i] = obj[i]; 
        }
        if (window.console && console.firebug && debug) console.log('pobralem'); 
        loadersVisibility(false);
        this.flagBusy = false;
		// update widoku
        updateView();
    }
    
    this.handleError = function(request)
    {
        // do nothing
    }
	
	function rotation(elem, deg) 
	{    
		var rad = deg*Math.PI*2/360;
		elem.filters.item(0).M11 = Math.cos(rad);;
		elem.filters.item(0).M12 = - Math.sin(rad);
		elem.filters.item(0).M21 = Math.sin(rad);
		elem.filters.item(0).M22 = Math.cos(rad);
	}
	
	function initRotation(container) 
	{
		var images = container.getElementsByTagName('img');
	
		for (var i = 0; i < images.length; i++) {
			if (images[i].className.indexOf('rotate') != -1) {
				var image = images[i];	
				var match = image.className.split('_');
				var rotate = match[match.length-1];
		
				// ie
				image.style.filter = "progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand');" 
					
				
				// browsers	
				canvas = document.createElement('canvas');
				if (canvas.getContext) {				
					var id = 'canvas' + image.getAttribute('id');
					canvas.setAttribute('id', id);
					var canvasContext = canvas.getContext('2d');
					var dagona = Math.floor(Math.sqrt((Math.pow(image.width,2)) + (Math.pow(image.height,2))));
					canvas.setAttribute('width', dagona);
					canvas.setAttribute('height', dagona);
					canvasContext.rotate(rotate * Math.PI/180);
					canvasContext.drawImage(image, 10, 20);						
					var imageParent = image.parentNode;
					imageParent.insertBefore(canvas, image);
					canvasArr.push(canvas);
					image.style.display = 'none';
				} else {
					rotation(image,rotate); // ie				
				}
				
				// onclick action 
				if (!canvas.getContext) {
					var parentLi = image.parentNode.parentNode;
					parentLi.onclick = function() {
						var as = this.getElementsByTagName('a');
						if (as) {
							var href = as[0].href;
							window.location = href;
						}
					}
				}
				
			}
		}   
	}	    	
}

/* end */
