/**
 *  OneLineScroller using prototype.js
 *  Copyright © 2008 by GreenTech
 *
 *  $Id: dhtml.js 4584 2008-09-17 08:16:33Z jkromski $ 
 */

function ietruebody() {
    return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
}

function mouseX(evt) {
if (evt.pageX) return evt.pageX;
else if (evt.clientX)
   return evt.clientX + (document.documentElement.scrollLeft ?
   document.documentElement.scrollLeft :
   document.body.scrollLeft);
else return null;
}
function mouseY(evt) {
if (evt.pageY) return evt.pageY;
else if (evt.clientY)
   return evt.clientY + (document.documentElement.scrollTop ?
   document.documentElement.scrollTop :
   document.body.scrollTop);
else return null;
}

function randomIntInRange(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}


function GalleryLogos() {
    if ($('sponsors-logos-1')) {
        $('sponsors-logos-2').innerHTML= $('sponsors-logos-1').innerHTML;
        $('sponsors-logos-1').setStyle({'position':'absolute', 'top':'0px'});
        $('sponsors-logos-2').setStyle({'position':'absolute', 'top':'0px'});
        var _scrollers = [$('sponsors-logos-1'),$('sponsors-logos-2')];
        var _forcedReposition = true;
        var _box_width = $('sponsors-logos').getWidth();
        var _startdate = new Date();
        
        var _animStepString = function(scroller1,scroller2,xpos1,xpos2,forceRecalc) {
	    if (xpos1 < -scroller1.getWidth() || forceRecalc) {
	        xpos1 = 2+xpos2+Math.max(_box_width,scroller2.getWidth()+10);
	    }
	    scroller1.setStyle({'left': (xpos1-1)+'px'});
        }
        
        var animStep = function () {
            
	    var xpos0 = _scrollers[0].positionedOffset()[0];
	    var xpos1 = _scrollers[1].positionedOffset()[0];
            
	    if (xpos0 < -_scrollers[0].getWidth()) {
	        xpos0 = 2+xpos1+Math.max(_box_width,_scrollers[1].getWidth()+10);
	    }
	    _scrollers[0].setStyle({'left': (xpos0-1)+'px'});
            
	    if (xpos1 < -_scrollers[1].getWidth()) {
	        xpos1 = 2+xpos0+Math.max(_box_width,_scrollers[0].getWidth()+10);
	    }
	    _scrollers[1].setStyle({'left': (xpos1-1)+'px'});
        }
        
        var animStart = function () {
	    setInterval(animStep,50);
        }
        
        _animStepString(_scrollers[1],_scrollers[0],
		        _scrollers[1].positionedOffset()[0],_scrollers[0].positionedOffset()[0],
		        true);
        setTimeout(animStart,2000);
    }
}

function GalleryOnepicture () {
  var rootElem = $('c-gallery-onepicture');
  if (rootElem) {
    var picsCount = $('c-gallery-onepicture').getElementsBySelector('img.c-gallery-onepicture-img').length;
    var currPic = 0;
    if (currPic == 0 && picsCount > 0) {
      currPic = 1;
    }
    var next = function (e) {
      //confirm('coś?');
      if (picsCount > 0) {
        if (currPic == picsCount) {
          $('c-gallery-onepicture-pic-1').setStyle({'top': '0px', 'display': ''});
          $('c-gallery-onepicture-pic-' + currPic).setStyle({'display': 'none'});
          currPic = 1;
        }
        else {
          $('c-gallery-onepicture-pic-' + (currPic + 1)).setStyle({'top': '0px', 'display': ''});
          $('c-gallery-onepicture-pic-'+currPic).setStyle({'display': 'none'});
          currPic = currPic + 1;
        }
      }
    }
    
    var prev = function (e) {
      //confirm('coś?');
      if (picsCount > 0) {
        if (currPic == 1) {
          $('c-gallery-onepicture-pic-'+ picsCount).setStyle({'top': '0px', 'display': ''});
          $('c-gallery-onepicture-pic-1').setStyle({'display': 'none'});
          currPic = picsCount;
        }
        else {
          $('c-gallery-onepicture-pic-' + (currPic - 1)).setStyle({'top': '0px', 'display': ''});
          $('c-gallery-onepicture-pic-'+currPic).setStyle({'display': 'none'});
          currPic = currPic - 1;
        }
      }
    }
    var prevs = rootElem.getElementsBySelector('.c-gallery-onepicture-prev');
    var nexts = rootElem.getElementsBySelector('.c-gallery-onepicture-next');
    for (var i = 0; i < prevs.length; i++) {
      prevs[i].observe('click', prev);
    }
    for (var i = 0; i < nexts.length; i++) {
      nexts[i].observe('click', next);
    }
  }
}

function GalleryView () {
  var rootElem = $('c-gallery-view');
  if (rootElem) {
    var picsCount = $('c-gallery-view').getElementsBySelector('img.c-gallery-view-img').length;
    var currPic = 0;
    if (currPic == 0 && picsCount > 0) {
      currPic = 1;
    }
    var next = function (e) {
      //confirm('coś?');
      if (picsCount > 0) {
        if (currPic == picsCount) {
          $('c-gallery-view-pic-1').setStyle({'top': '0px', 'display': ''});
          $('c-gallery-view-pic-' + currPic).setStyle({'display': 'none'});
          currPic = 1;
        }
        else {
          $('c-gallery-view-pic-' + (currPic + 1)).setStyle({'top': '0px', 'display': ''});
          $('c-gallery-view-pic-'+currPic).setStyle({'display': 'none'});
          currPic = currPic + 1;
        }
      }
    }
    
    var prev = function (e) {
      //confirm('coś?');
      if (picsCount > 0) {
        if (currPic == 1) {
          $('c-gallery-view-pic-'+ picsCount).setStyle({'top': '0px', 'display': ''});
          $('c-gallery-view-pic-1').setStyle({'display': 'none'});
          currPic = picsCount;
        }
        else {
          $('c-gallery-view-pic-' + (currPic - 1)).setStyle({'top': '0px', 'display': ''});
          $('c-gallery-view-pic-'+currPic).setStyle({'display': 'none'});
          currPic = currPic - 1;
        }
      }
    }
    var prevs = rootElem.getElementsBySelector('.c-gallery-view-prev');
    var nexts = rootElem.getElementsBySelector('.c-gallery-view-next');
    for (var i = 0; i < prevs.length; i++) {
      prevs[i].observe('click', prev);
    }
    for (var i = 0; i < nexts.length; i++) {
      nexts[i].observe('click', next);
    }
  }
}


var fillUpID;
bubblesCount = 0;

function BubbleCache(holderDivId) {

    var _holderDiv = $(holderDivId);
    var _bubble_types = [];
    var _bubble_types_total_weight = 0;
    this._bubbles = [];
    var that = this;

    var _generateRandomBubble = function() {
        
        var _select = randomIntInRange(0,_bubble_types_total_weight);
        
        for (var _key=0; _key< _bubble_types.length; _key++) {
            if ( _select < _bubble_types[_key][1]) {
                var b = Object.clone(bubble_types[_key][0]);
                b.id = ++bubblesCount;
                b.createHTML(holderDivId);
                return b;
            }
            else {
                _select -= _bubble_types[_key][1];
            }
        }
        return undefined;
    }

    this.registerBubbleGenerator = function(bubblePrototype,weight) {
        _bubble_types.push([bubblePrototype,weight])
        _bubble_types_total_weight += weight;
    }

    this.fetchBubble = function() {
        if (that._bubbles.length) {
            return that._bubbles.pop();
        }
        else {
            return _generateRandomBubble();
        }
    }

    this.recycleBubble = function(bubble) {
        that._bubbles.push(bubble);
    }

    this.recycleBubbles = function(bubblelist) {
        for (var _key in bubblelist) {
            that.recycleBubble(bubblelist[_key])
        }
    }
}

function BubbleGroup(_pdiv,_bid,_type, _width, _height,_xpos) {
    var _parentDiv = $(_pdiv);
    var _bgPositionY = 0;
    var _bgWidth = _width;
    var _bgHeight = _height;
    var _id = 'blanker-bubble-group-' + _bid;
    var _bgType = _type;
    var _leftOffset = _xpos;
    var _bubbleGroupHandleId = undefined;
    var _animStep = 4;
    var that = this;
    
    this.start = function() {
        that.stop();
        _bgPositionY =  bgroupBox.getHeight();
        bgroupBox.setStyle({backgroundRepeat: 'repeat-y', top: '0px', left: _leftOffset + 'px', height: parentDiv.getHeight() + 'px'});
        bgroupBox.show();
        _bubbleGroupHandleId = window.setInterval(that.animStep, 100);
    };
    
    this.prepareStart = function() {
        that.stop();
        //_bgPositionY =  bgroupBox.getHeight();
        bgroupBox.setStyle({top: (_parentDiv.getHeight() - 20) + 'px',
                            left: _leftOffset + 'px',
                            height: (_parentDiv.getHeight() - 20) + 'px',
                            backgroundPosition: 'center 0px'});
        bgroupBox.show();
        //_bubbleGroupHandleId = window.setInterval(that.animStep, 100);
    };
    
    this.stop = function () {
        if (_bubbleGroupHandleId != undefined) {
            window.clearInterval(_bubbleGroupHandleId);
        }
        bgroupBox.hide();
    }
    
    this.moveTo = function(_ypos) {
        bgroupBox.setStyle({top: _ypos +'px'});
    };
    this.setHeight = function(height) {
        bgroupBox.setStyle({height: parseInt(height) + 'px'});
    };
    
    this.animStep = function(){
        var fromTop = parseInt(bgroupBox.getStyle('top'));
        if (fromTop > 20) {
            bgroupBox.setStyle({top: (fromTop - _animStep) + 'px'});
        }
        else {
            if (_bgPositionY <  -_bgHeight ) {
                _bgPositionY = 0;
            }
            else {
                _bgPositionY -= _animStep;
            }
            bgroupBox.setStyle({backgroundPosition: 'center ' + _bgPositionY + 'px'});
        }
    }

    /** real constructor */
    var bgroupBox = undefined;
    bgroupBox = document.createElement('div');
    bgroupBox.setAttribute('id','blanker-bubble-group-'+_bid);
    _parentDiv.appendChild(bgroupBox);
    bgroupBox = $('blanker-bubble-group-'+_bid);
    //var img = new Element('img');
    //img.setAttribute('src', '/_gfx/blanker/bubblegroup1.gif');
    //bgroupBox.appendChild(img);
    bgroupBox.setStyle({width: _bgWidth+'px', height: _bgHeight+'px', left: _leftOffset +'px'});

    //setTimeout(function() {
        bgroupBox.addClassName(_type+'-box');
        bgroupBox.setStyle({left: _xpos +'px'});
    //},1000);

}

function Bubble(bid) {
    this.id = bid;
    this.className = '';
    this.areaWeight = 0; // in px^2
    //this.probability = 0; // int (for creation of bubbles)
    this.activationProbality = 0; // int (for move start)
    this.gifUrl = 'somegif.gif';
    this.blowGifUrl = 'someblow.gif';
    this.animationSpeed = 5;
    this.elem = undefined;
    var that = this;

    this.moveTo = function(_x,_y) {
        if (that.elem) {
            that.elem.setStyle({top:  _y + 'px', left:  _x + 'px'});
            that.elem.setStyle({display: 'block'})
        }
    }
    
    this.createHTML = function(parentDivId) {
        var pdiv = $(parentDivId);
        var bhtml = new Element('div');
        bhtml.addClassName(that.className);
        bhtml.setAttribute('id', 'ss-bubble-'+ that.id);
        bhtml.appendChild(new Element('img', {alt: '', src: that.gifUrl}));
        bhtml.setStyle({
            position: 'absolute',
            top: pdiv.getHeight() + 'px'
            });
        pdiv.appendChild(bhtml);
        that.elem = bhtml;
    }
    
    this.resetPosition = function(_x, _y) {
        that.moveTo(_x, _y);
    }
}


/**
 * @returns bool true if buble didn't blew yet
 */
Bubble.prototype.animationStep = function () {
    
    if (this.id && this.elem.getStyle('display') != 'none') {
        var fromTop = parseInt(this.elem.getStyle('top'));
        if (fromTop > 0) {
            this.elem.setStyle({top: --fromTop + 'px'})
            return true;
        }
        else {
            // do BOOM
            return false;
        }
    }
    return false;
}



function BubblesManager() {
    
    var activeBubbles = [];
    this.inactiveBubbles = [];
    var bubbleCache = new BubbleCache('ss-water');
    var _bubblesArea = {width: 0, height: 0};
    var _bubblesFactor = 0.5;
    var that = this;
    
    // bubbles types creation
    var bubble = new Bubble();
    bubble.gifUrl = '/_gfx/blanker/bubble1.gif';
    bubble.areaWeight = 131*125;
    bubbleCache.registerBubbleGenerator(bubble, bubble.areaWeight);
    bubble = new Bubble();
    bubble.gifUrl = '/_gfx/blanker/bubble2.gif';
    bubble.areaWeight = 115*117;
    bubbleCache.registerBubbleGenerator(bubble, bubble.areaWeight);
    bubble = new Bubble();
    bubble.gifUrl = '/_gfx/blanker/bubble3.gif';
    bubble.areaWeight = 100*98;
    bubbleCache.registerBubbleGenerator(bubble, bubble.areaWeight);
    //end
    
    this.setBubblesFactor = function (factor) {
        _bubblesFactor = factor;
    }
    
    var startNewBubble = function () {
        var sum = activeBubbles.length + inactiveBubbles.length;
        var factor = 1;
        var index = randomIntInRange(0,sum*factor);
        if (index < inactiveBubbles.length) {
            var offset = randomIntInRange(0,document.viewport.getWidth());
            var b = inactiveBubbles[index];
            offset -= Math.floor(b.elem.getWidth() / 2);
            inactiveBubbles[index] = inactiveBubbles[inactiveBubbles.length -1];
            inactiveBubbles.pop();
            b.moveTo($('ss-water').getHeight(),offset);
            activeBubbles.push(b);
        }
    }
    
    this.animationStep = function() {
        startNewBubble();
        for (var b=0; b<activeBubbles.length; b++) {
            if (!activeBubbles[b].animationStep()) {
                inactiveBubbles.push(activeBubbles[b]);
                activeBubbles[b] = activeBubbles[activeBubbles.length-1];
                activeBubbles.pop();
            }
        }
    }
    /**
     * prepares bubbles before animations start - generate them 
     * @param parentDivId {string} id of the parent div
     */
    this.prepareStart = function(parentDivId) {
        that.stopAnimation();
        var pdiv = $(parentDivId);
        if (pdiv){
            _bubblesArea.width = pdiv.getWidth();
            _bubblesArea.height = pdiv.getHeight();
        }
        var area = parseInt(_bubblesArea.width * _bubblesArea.height * _bubblesFactor);
        var takenArea = 0;
        var b;
        var con = (takenArea < area);
        while (con) {
            confirm('1');
            b = bubbleCache.fetchBubble();
            confirm('2');
            takenArea += b.areaWeight;
            confirm('3');
            that.inactiveBubbles[that.inactiveBubbles.length] = b;
            confirm('4');
            con = (takenArea < area);
        }
    }
    
    /**
     * stop all bubble animations
     */
    this.stopAnimation = function() {
        bubbleCache.recycleBubbles(that.inactiveBubbles);
        bubbleCache.recycleBubbles(activeBubbles);
    }
    
    // real contrusctor
    
}


function FishAnim(_pdiv) {
    var animHandle;
    var fishBox;
    var fishBox_x;
    var fishBox_y;
    var fishBowlBox = {t: 0, l: 0, b: 0, r: 0}
    var that = this;
    var fish_x_dir = 0;
    var fish_y_dir = 0;
    var fishBox_x_timeout = 10;
    var fishBox_y_timeout = 10;
    

    this.startSwimming = function() {
        if (!animHandle) {
            var fish_x_dir = 0;
            var fish_y_dir = 0;
            var fishBox_x_timeout = 10;
            var fishBox_y_timeout = 10;
            //animHandle = setInterval(function() {
                fishBox_x_timeout--;
                fishBox_y_timeout--;
                if (fishBox_x_timeout == 0) {
                    fishBox_x_timeout = randomIntInRange(1,100);
                    fish_x_dir = Math.random()*10-5;
                }
                if (fishBox_y_timeout == 0) {
                    fishBox_y_timeout = randomIntInRange(1,100);
                    fish_y_dir = Math.random()*4-2;
                }
                fishBox.setStyle({position: 'absolute', left: fishBox_x + 'px', top: fishBox_y +'px'});
                fishBox_x = Math.max(fishBowlBox.l,Math.min(fishBowlBox.r,fish_x_dir+fishBox_x));
                fishBox_y = Math.max(fishBowlBox.t,Math.min(fishBowlBox.b,fish_y_dir+fishBox_y));
            //},100);
        }
    }
    
    this.prepareStart = function() {
        fishBox.setStyle({position: 'absolute', top: fishBox_y +'px', left: fishBox_x+'px'});
        fish_x_dir = 0;
        fish_y_dir = 0;
        fishBox_x_timeout = 10;
        fishBox_y_timeout = 10;
    }
    
    this.animStep = function() {
        fishBox_x_timeout--;
        fishBox_y_timeout--;
        if (fishBox_x_timeout == 0) {
            fishBox_x_timeout = randomIntInRange(1,100);
            fish_x_dir = Math.random()*10-5;
        }
        if (fishBox_y_timeout == 0) {
            fishBox_y_timeout = randomIntInRange(1,100);
            fish_y_dir = Math.random()*4-2;
        }
        fishBox.setStyle({position: 'absolute', left: fishBox_x + 'px', top: fishBox_y +'px'});
        fishBox_x = Math.max(fishBowlBox.l,Math.min(fishBowlBox.r,fish_x_dir+fishBox_x));
        fishBox_y = Math.max(fishBowlBox.t,Math.min(fishBowlBox.b,fish_y_dir+fishBox_y));
    }

    this.setBowlSize = function(_top,_right,_bottom,_left) {
        fishBowlBox = {t: _top, l: _left, b: _bottom, r: _right};
    }
    
    this.stopSwimming = function() {
        //clearInterval(animHandle);
        //animHandle = undefined;
        fishBox.setStyle({display: 'none'});
        that.moveTo($('ss-holder').getWidth()/2 - 100,$('ss-holder').getHeight()+Math.max(100,$('ss-holder').getHeight()/4-50),false);
    }
    
    this.moveTo = function(_x,_y,show_me) {
        fishBox_x = _x;
        fishBox_y = _y;
        fishBox.setStyle({position: 'absolute', left: fishBox_x + 'px', top: fishBox_y +'px'});
        if (show_me) {
            that.show();
        }
    }

    this.show = function() {
        fishBox.setStyle({display: 'block'});
    }

    this.hide = function() {
        fishBox.setStyle({display: 'none'});
    }

    /** real constructor */
    fishBox = document.createElement('div');
    fishBox.setAttribute('id','blanker-fishBox');
    $(_pdiv).appendChild(fishBox);
    fishBox = $('blanker-fishBox');
    fishBox.setStyle({display: 'none'});

    setTimeout(function() {
        var fishParts = 
            ['/_gfx/blanker/fish/body.gif',
             '/_gfx/blanker/fish/oczy.gif',
             '/_gfx/blanker/fish/pletwy.gif'];
        for (var i = 0; i < fishParts.length; i++) {
            var fishImg = document.createElement('img');
            fishImg.setAttribute('src',fishParts[i]);
            fishBox.appendChild(fishImg);
        }
    },1000);
}

function webPageScreenSaver() {
    var standstillTime = 0;
    var screenSaver = undefined;
    var bubblesManager = new BubblesManager();
    var fish = new FishAnim('ss-holder');
    //_pdiv,_bid,_type, _width, _height,_xpos
    var bubbleGroups = [new BubbleGroup('ss-holder','1','blanker-bubblegroup1',109,332, 200),
                        new BubbleGroup('ss-holder','2','blanker-bubblegroup1',109,332, 400)];
    var intervalFunctions = [];
    
    var resetTime = function (e) {
        standstillTime = 0;
        if (screenSaver != undefined) {
            window.clearTimeout(screenSaver);
            window.clearInterval(fillUpID);
            screenSaver = undefined;
            $('ss-holder').hide();
            bubblesManager.stopAnimation();
            fish.stopSwimming();
            for (var i = 0; i < bubbleGroups.length; i++) {
                bubbleGroups[i].stop();
            }
        }
    }
    
    var timeOutObserver = function () {
        timeOut = 3; // in seconds
        if (standstillTime < timeOut) {
            standstillTime += 1;
        } 
        else if (screenSaver == undefined) {
            screenSaver = window.setTimeout(startScreenSaver, 500);
        }
    }
    
    var startScreenSaver = function () {
        waterFillUp();
    }
    
    window.setInterval(timeOutObserver,1000);
  
    //  Event.observe(window, 'mousemove', resetTime);
    //  Event.observe(window, 'keydown', resetTime);
    Event.observe(window, 'keypress', resetTime);
    Event.observe(window, 'click', resetTime);
    //  Event.observe(window, 'scroll', resetTime);
    //  Event.observe(window, 'resize', resetTime);
    
    var waterFillUp = function() {
        initScreenSaverBoxes();
        $('ss-holder').setStyle({display: 'block'});
        $('ss-water-holder').setStyle({top: '100%'});
        var toTop = $('ss-holder').getHeight();
        fillUpID = window.setInterval(function (){
            var ssHolder = $('ss-holder');
            var ssWaterHolder = $('ss-water-holder');
            toTop -= 5;
            fish.moveTo($('ss-holder').getWidth()/2 - 100,toTop+Math.max(100,$('ss-holder').getHeight()/4-50),true);
            /*for (var i = 0; i < bubbleGroups.length; i++) {
                bubbleGroups[i].moveTo(toTop+10);
            }*/
            
            if (toTop < 1) {
                window.clearInterval(fillUpID);
                toTop = 0;
                intervalFunctions.clear();
                bubblesManager.prepareStart('ss-water');
                intervalFunctions.push(bubblesManager.animationStep);
                
                var waterHeight = $('ss-water-holder').getHeight();
                for (var i = 0; i < bubbleGroups.length; i++) {
                    bubbleGroups[i].setHeight(waterHeight + 40);
                    bubbleGroups[i].moveTo(20);
                    bubbleGroups[i].prepareStart();
                    intervalFunctions.push(bubbleGroups[i].animStep);
                }
                fish.setBowlSize(20,$('ss-holder').getWidth(),$('ss-holder').getHeight(),0);
                fish.prepareStart();
                intervalFunctions.push(fish.animStep);
                fillUpID = window.setInterval(function (){
                    for (var i = 0; i < intervalFunctions.length; i++) {
                        intervalFunctions[i]();
                    }
                }, 100);
                ///var waterHeight = $('ss-water-holder').getHeight();
                //for (var i = 0; i < bubbleGroups.length; i++) {
                    //bubbleGroups[i].setHeight(waterHeight);
                    //bubbleGroups[i].start();
                //}
                //fish.startSwimming();
            }
            ssWaterHolder.setStyle({top: (toTop) + 'px'});
            //$('navigator').update(toTop);
        }, 100);
    }
    
    //var singleBubleCount = 2;
    
    var singleBuble = function() {
        var template = '<div >';
        alert ('not implemented');
    }
}

function initWebPageScreenSaver() {
    var ss = new webPageScreenSaver();
    var rt = ss.resetTime;
}


function initScreenSaverBoxes() {
    var ssholder = $('ss-holder');
    var sshheight = (document.viewport.getHeight() * 70) / 100;
    if (sshheight < 200) {
        sshheight = 200;
    }
    ssholder.setStyle({height: (sshheight) + 'px'});
    ssholder.setStyle({top: (document.viewport.getHeight() - ssholder.getHeight()) + window.scrollY + 'px'});
    $('ss-surface').setStyle({height: '60px'});
    $('ss-water').setStyle({height: (ssholder.getHeight() - $('ss-surface').getHeight()) + 'px'});
}

function initLogosBar() { gallery_logos = new GalleryLogos(); }
function initGalleryOnepicture() {gallery_onepicture = new GalleryOnepicture();}
Event.observe(window, 'load', initGalleryOnepicture, false);
function initGalleryView() {gallery_view = new GalleryView();}
Event.observe(window, 'load', initGalleryView, false);
Event.observe(window, 'load', initLogosBar, false);
//Event.observe(window, 'load', initScreenSaverBoxes, false);
//Event.observe(window, 'load', initWebPageScreenSaver, false);

