/*
 * axiohm.js    1.0 2009-2-9
 *
 * Copyright 2009 Michal Petřík
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * Provede zmenu obrazku pri najeti mysi.
 *
 * @param name  Identifikace obrazku (element img).
 * @param state Definice stavu (true/false).
 */
function hoverImg(name, state) {
    // ziskej element
    element = document.getElementById(name);
    // ziskej cestu
    path = element.src;
    // pokud mame hover img, zmen ho zpet
    // pokud mame hover img, zmen ho zpet
    if(state=='true') {
        if(path.indexOf('_h.png')==-1) {
            element.src = path.substr(0,path.length-4) + '_h.png';
        }
    } else {
        if(path.indexOf('_h.png')!=-1) {
            element.src = path.substr(0,path.length-6) + '.png';
        }
    }
}

/**
 * Provadi plynuly prechod mezi zadanymi obrazky.
 *
 * @param imageId       Identifikace elementu obrazku, nad kterym jsou provadeny
 *                      zmeny.
 * @param imagesArray   Pole s cestami k obrazkum.
 */
function ImageTransition(imageId, imagesArray) {
    // zikej objekt elementu podle id
    this.img = document.getElementById(imageId);
    // zjisti si obrazky
    this.imgArray = imagesArray;
    // zatim nemame zadny index
    this.index = -1;
    // maximalni index obrazku
    this.maxImg = imagesArray.length;
    // prodleva pri prechodu obrazku
    this.DELAY = 75;

    /**
     * Nastavuje hodnotu pruhlednosti elementu.
     *
     * @param value Hodnota pro pruhlednost (0-1).
     */
    this.setOpacity = function(value) {
        // nastav styl pro Firefox, Krusader, Operu, ...
        this.img.style.opacity = value;
        // a taky IE ;-)
        this.img.style.filter = "alpha(opacity="+(value*100)+")";
    }

    /**
     * Provede prechod na dalsi obrazek.
     */
    this.nextImg = function() {
        // presun index (tocime se dokola)
        this.index = (this.index+1) % this.maxImg;
        // nastav obrazek
        this.img.src = this.imgArray[this.index];
	// zavolej dalsi upravu po definovane pouze
        this.waitOnLoad();
    }

    /** 
     * Ceka na najrani obrazku
     */
    this.waitOnLoad = function() {
        if(!this.img.complete){
           // hack pro pouziti ve funkci
           var _self = this; 

           setTimeout(function() {
                _self.waitOnLoad();
            }, 500);
        } else{
           this.showUp(0);
        }         
    }

    /**
     * Provede zobrazeni obrazku na danem indexu - plynuly prechod.
     *
     * @param value Hodnota alpha indexu.
     */
    this.showUp = function(value) {
        // hack pro pouziti ve funkci
        var _self = this;
        // pokud jeste nejsme v plne alphe, tak stale zvysuj sytost
        if(value<=1) {
            // nastav aktualni hodnotu
            this.setOpacity(value);
            // uprav alphu
            var v = value + 0.05;
            // zavolej dalsi upravu po definovane pouze
            setTimeout(function() {
                _self.showUp(v);
            }, this.DELAY);
        // uz v plne sytosti, nech obrazek svitit a pak ho zacni skryvat
        } else {
            setTimeout(function() {
                _self.hide(1);
            }, 8000);
        }
    }

    /**
     * Provede skryti obrazku na danem indexu - plynuly prechod.
     *
     * @param value Hodnota alpha indexu.
     */
    this.hide = function(value) {
        // uprav sytost
        var v = value - 0.05;
        // pokus nejsme na nule, tak skryvej dal
        if(v>0) {
            // uprav sytost
            this.setOpacity(v);
            // hack pro volani ve funkci
            var _self = this;
            // zavolej nas znova
            setTimeout(function() {
                _self.hide(v);
            }, this.DELAY);
        // zobraz dalsi obrazek
        } else {
	    this.setOpacity(0);

            this.nextImg();
        }
    }

    // po inicilizaci pust galerii
    this.nextImg();
}

/**
 * Poskytuje ovladani komponenty pro scollujici galerii.
 *
 * @param objId Identifikace objektu na kterem zachytavame udalosti.
 * @param strip Identifikace objektu ktery se posouva.
 */
function ScrollView(objId, strip) {
    // element obalky
    this.elm = document.getElementById(objId);
    // element, co scrolluje
    this.strip = document.getElementById(strip);
    // inicializace mysi
    this.mouseX = 0;
    // zatim zadny pohyb
    this.scrolling = false;
    // smer doprava
    this.direction = 1;
    // zatim vychozi pozice
    this.left = 0;
    // zjisti delku obalky
    this.width = this.elm.offsetWidth;
    // zjisti delku stripu
    this.subWidth = this.strip.offsetWidth;
    // nasobek pro pohyb stripu
    this.mult = 1;
    // abychom mohli pracovat s touto tridou i ve funkcich
    var _self = this;

    /**
     * Vraci pozici obalky.
     */
    this.getPosition = function (){
        var left = 0;

        e = _self.elm;

        while (e.offsetParent){
            left += e.offsetLeft;
            e     = e.offsetParent;
        }

        left += e.offsetLeft;

        return left;
    }

    /**
     * Vraci pozici mysi na elementu.
     */
    this.objectMouseCoords = function(ev){
        if(ev.pageX){
            return {
                x:ev.pageX
            };
        }

        return {
            x:ev.clientX + document.body.scrollLeft - document.body.clientLeft
        };
    }

    /**
     * Zachycuje udalost pohybu mysi po objektu.
     */
    this.mouseMove = function(ev) {
        ev = ev || window.event;

        var mousePos = _self.objectMouseCoords(ev);
        // uprav mys pro nasi pozici
        _self.mouseX = mousePos.x - _self.getPosition();
        // pokud jsme za pulkou scrollujeme doleva (nechame 60px pro necinnost)
        if(Math.abs(_self.width/2 - _self.mouseX) > 30) {
            if(_self.mouseX >= _self.width/2) {
                _self.direction = -1;
                // uprav rychlost scrollingu
                _self.mult = (_self.width / 2) / ((_self.width / 2) -
                    (_self.mouseX - (_self.width / 2))) + 1;
            } else {
                // jedeme doprava
                _self.direction = 1;

                // hack pro nekonecno
                _self.mult = (_self.width / 2) / (_self.mouseX + 1);
            }

            // omezime maximalni a minimalni rychlost
            if(_self.mult > 5) {
                _self.mult = 5;
            }

            // pokud jeste nescrollujeme, tak zacni
            if(!_self.scrolling) {
                _self.scrolling = true;
                _self.scroll();
            }
        } else {
            _self.scrolling = false;
        }
    }

    /**
     * Provadi posouvani stripu.
     */
    this.scroll = function() {
        if(_self.subWidth >= _self.width) {
            if(_self.scrolling) {
                _self.left += 2*_self.direction*_self.mult;

                if(_self.left > 0) {
                    _self.left = 0;
                }

                if((_self.left+_self.subWidth) < _self.width) {
                    _self.left = _self.width - _self.subWidth;
                }

                _self.strip.style.left = Math.round(_self.left) +"px";

                setTimeout(function() {
                    _self.scroll();
                }, 50);
            }
        }
    }

    /**
     * Mys opustila nas element,
     */
    this.mouseOut = function(ev) {
        ev = ev || window.event;

        var trgt;

        if (ev.relatedTarget) {
            trgt = ev.relatedTarget;
        } else if(ev.toElement) {
            trgt = ev.toElement;
        }

        inside = false;
        // urci, zda je predek obalka -> jsme uvnitr
        while(trgt) {
            if(trgt.id == _self.elm.id) {
                inside = true;
                break;
            }
            trgt = trgt.parentNode;
        }

        if(!inside) {
            _self.scrolling = false;
        }
    }
    // zaregistruj udalosti mysi
    this.elm.onmousemove = this.mouseMove;

    this.elm.onmouseout = this.mouseOut;
}

/**
 * Vraci generovane elementy s nahledy obrazku.
 *
 * @param imgArray  Pole s obrazky.
 * @param relName   Nazev pro sdruzeni obrazku.
 */
function getImgElements(imgArray, relName) {
    str = "";

    for(var i=0;i<imgArray.length;i++) {
        str +="<a href='"+imgArray[i]+"' rel='lightbox["+relName+"]'><img src='"+imgArray[i]+"' /></a>";
    }

    return str;
}

/**
 * Vytvori objekt pro zajisteni scrollovaciho nahledu obrazku.
 *
 * @param objId     Element obalky.
 * @param stripId   Element s obrazky.
 * @param imgArray  Pole s URL obrazku.
 * @param relName   Nazev pro sdruzeni obrazku.
 */
function makeScrollView(objId, stripId, imgArray, relName) {
    strip = document.getElementById(stripId);

    strip.innerHTML = getImgElements(imgArray, relName);

    strip.style.width = (strip.childNodes.length*134)+'px';

    new ScrollView(objId,stripId);
}

