

function log() {}
if(typeof console != 'undefined')
    log = console.log;

function init() {
    initNavigation();
    initContact();
    initWorks();
}
$(document).observe('dom:loaded', init);



function initNavigation() {
    $('navigation').select('a').each(function(a) {
        if(a.className == document.body.className)
            return;
        a.observe('mouseover', navigationLinkMove.bindAsEventListener(a));
        a.observe('mouseout', navigationLinkOut.bindAsEventListener(a));
    });
}

function navigationLinkMove(e) {
    this.parentNode.parentNode.addClassName('hovered');
//     var as = this.parentNode.parentNode.select('li a');
//     var passedThis = false;
//     for(var i = 0; i < as.length; ++i) {
//         if(passedThis) {
//             $(as[i]).removeClassName('left').addClassName('left');
// //             effects.push(new Effect.Move(as[i], {sync: true, x: movement, mode: 'relative'}));
//         }
//         else {
//             if(as[i] == this) {
//                 passedThis = true;
//                 continue;
//             }
//             else {
//                 $(as[i]).removeClassName('left').addClassName('right');
//             }
// //                 effects.push(new Effect.Move(as[i], {sync: true, x: -movement, mode: 'relative'}));
//         }
//     }
}

function navigationLinkOut(e) {
    this.parentNode.parentNode.removeClassName('hovered');
//     var as = this.parentNode.parentNode.select('li a');
//     var passedThis = false;
//     for(var i = 0; i < as.length; ++i) {
//         $(as[i]).removeClassName('left').removeClassName('right');
//     }
}

// function navigationLinkOver(e) {
//     animateNavigationItems(this, 'over');
// }
// 
// 
// function animateNavigationItems(static, direction) {
//     var startOpacity, endOpacity, movement;
//     if(direction == 'over') {
//         startOpacity = 1;
//         endOpacity = 0.5;
//         movement = 20;
//     }
//     else if(direction == 'out') {
//         startOpacity = 0.5;
//         endOpacity = 1;
//         movement = -20;
//     }
//     var as = static.parentNode.parentNode.select('li a');
//     var effects = [];
//     var passedThis = false;
//     for(var i = 0; i < as.length; ++i) {
//         if(passedThis) {
//             effects.push(new Effect.Move(as[i], {sync: true, x: movement, mode: 'relative'}));
//         }
//         else {
//             if(as[i] == static) {
//                 passedThis = true;
//                 continue;
//             }
//             else
//                 effects.push(new Effect.Move(as[i], {sync: true, x: -movement, mode: 'relative'}));
//         }
// //         effects.push(new Effect.Opacity(as[i], {sync: true, from: startOpacity, to: endOpacity}));
//     }
//     new Effect.Parallel(effects, { 
//         duration: 0.2,
//         queue: {position: 'end', scope: 'navigation'}
// //         afterFinish: function() { log(Effect.Queues.get('navigation')); }
//     });
// //     ANIMATING_LINK = true;
// }
// 
// function navigationLinkOut(e) {
//     animateNavigationItems(this, 'out');
// }
// 
// function pruneNavigationQueue() {
// }



function initContact() {
    if(!$(document.body).hasClassName('contact'))
        return;
    
    // email address. Wonder if this paranoia is actually worth it.
    var me = R('cnhy@tvnaanebf.bet');
    $('my-email').innerHTML = me;
    $('my-email').href = R('znvygb:') + me;

    
    // message default text
    var m = $('message');
    if(!m)
        return;
    
    function focused() {
        m.removeClassName('unfilled');
        if(m.value == '' || m.value == m.defaultValue) {
            m.value = '';
        }
    }
    function unfocused() {
        if(m.value == '' || m.value == m.defaultValue) {
            m.value = m.defaultValue;
            m.addClassName('unfilled');
        }
        else
            m.removeClassName('unfilled');
    }
    m.observe('focus', focused);
    m.observe('blur', unfocused);
    unfocused();
    
    // submitting the message
    var p = $('post-message');
    p.observe('click', function() {
        alert('post');
    });
}



function initWorks() {
    if(!$(document.body).hasClassName('works'))
        return;
    var togglers = [];
    var stretchers = [];
    var hashes = [];
    var c = $A($('works-container').cleanWhitespace().childNodes);
    c.each(function(element, i) {
        if(i % 2 == 0) {
            togglers.push(element);
        }
        else {
            stretchers.push(element);
            hashes.push(element.id.split(/-/)[1]);
        }
    });
    
    new Accordion(togglers, stretchers, {
        initial: $('works-libraries'),
        hashes: hashes
    });
}



/////////////////////// Accordion /////////////////////////////
// Feel free to use this code if you like it, I place it in  //
// the public domain. /////////////////////////////////////////

var Accordion = Class.create({
    initialize: function(togglers, stretchers, options) {
        this.togglers = togglers;
        this.stretchers = stretchers;
        this.hashes = $A(options.hashes || []);
        this.initial = options.initial || null;
        
        this.activeClassName = 'active';
        this.animating = false;
        this.transition = Effect.Transitions.sinoidal;
        
        this.activeStretcher = null;
        this.activeToggler = null;
        
        var toggle = this.toggle;
        // Set up the click handler for the togglers and initialise the
        // stretchers.
        for(var i = 0; i < this.togglers.length; ++i) {
            var t = $(this.togglers[i]);
            t.observe('click', this.togglerClicked.bindAsEventListener(this, t));
            t.observe('mousedown', this.togglerMouseDown.bindAsEventListener(this, t));
            var s = $(this.stretchers[i]);
            var dimensions = s.getDimensions();
            // Keeping track of the original size and telling scriptaculous
            // means that the animation will not jitter at the end when
            // expanding.
            s.originalSize = {
                originalHeight: dimensions.height,
                originalWidth: dimensions.width
            };
            // Stretchers are initially hidden
            s.setStyle({display: 'none'});
        }
        
        var hash = window.location.hash.substr(1);
        if(this.hashes.indexOf(hash) != -1)
            this.initial = this.stretchers[this.hashes.indexOf(hash)];
        if(this.initial) {
            // stop the hash from being set for the initial page
            var h = this.hashes;
            this.hashes = $A([]);
            log(this.initial);
            this.toggle(this.initial);
            this.hashes = h;
        }
    },
    
    
    togglerClicked: function(e, toggler) {
        this.toggle(toggler)
    },
    
    togglerMouseDown: function(e, toggler) {
        e.stop();
    },
    
    toggle: function(element) {
        log(this);
        var stretcher, toggler, index;
        if(this.togglers.indexOf(element) == -1) {
            stretcher = element;
            index = this.stretchers.indexOf(stretcher);
            toggler = this.togglers[index];
        }
        else {
            toggler = element;
            index = this.togglers.indexOf(toggler);
            stretcher = this.stretchers[index];
        }
        
        if(this.animating)
            return;
        this.animating = true;
        
        if(stretcher == this.activeStretcher) {
            stretcher = toggler = null;
        }
        
        if(stretcher) {
            toggler.addClassName(this.activeClassName);
            stretcher.addClassName(this.activeClassName);
        }
        if(this.activeStretcher) {
            this.activeToggler.removeClassName(this.activeClassName);
            this.activeStretcher.removeClassName(this.activeClassName);
        }
        
        var effects = [];
        if(stretcher) {
            effects.push(new Effect.BlindDown(stretcher, {sync: true, transition: this.transition, scaleContent: false, scaleMode: stretcher.originalSize}));
        }
        if(this.activeStretcher) {
            effects.push(new Effect.BlindUp(this.activeStretcher, {sync: true, transition: this.transition, scaleContent: false, scaleMode: this.activeStretcher.originalSize}));
        }
        this.activeStretcher = stretcher;
        this.activeToggler = toggler;
        
        new Effect.Parallel(effects, {
            duration: 0.6,
            fps: 40,
            afterFinish: function() { this.animating = false; }.bind(this)
        });
        
        if(this.hashes.length > index) {
            var l = stretcher ? this.hashes[index] : '';
            window.location.hash = '#' + l;
        }
    }
});



/////////////////////////// Darkview /////////////////////////////////
///  A little like Fancybox and Lightview for slideshows but free! ///
///                  Also in the public domain.                    ///
//////////////////////////////////////////////////////////////////////

var Darkview = Class.create({
    initialize: function(imgs) {
        this.shadowSize = 17;
        this.scaleEffect = null;
        this.screen = new Element('div').hide().setStyle({
            backgroundColor: '#000',
            position: 'fixed', left: 0, top: 0,
            width: '100%', height: '100%'
        });
        this.box = new Element('table').setStyle({
            position: 'fixed', left: '50%', top: '50%',
            marginLeft: -(5 + this.shadowSize) + 'px',
            marginTop: -(5 + this.shadowSize) + 'px'
        }).addClassName('darkview').insert(new Element('tbody')).hide();
        var tbody = this.box.firstChild;
        var classNames = [['nw', 'n', 'ne'], ['w', 'c', 'e'], ['sw', 's', 'se']];
        for(var i = 0; i < 3; ++i) {
            var tr = new Element('tr');
            for(var j = 0; j < 3; ++j) {
                tr.appendChild(new Element('td').addClassName(classNames[i][j]));
            }
            tbody.appendChild(tr);
        }
        
        this.panel = new Element('table').setStyle({
            position: 'fixed', left: '50%', bottom: '2px',
            height: '47px', width: '200px',
            marginLeft: '-100px'
        }).addClassName('darkview-control').insert(new Element('tbody'));
       
        var panelItems = [
            ['number', null],
            ['previous', this.showPrevious],
            ['next', this.showNext],
            ['close', this.close]
        ];
        var tr = new Element('tr');
        this.panel.firstChild.appendChild(tr)
        for(var i = 0; i < panelItems.length; ++i) {
            var td = new Element('td').addClassName(panelItems[i][0]);
            if(panelItems[i][1]) {
                td.observe('click', panelItems[i][1].bindAsEventListener(this));
            }
            tr.appendChild(td);
            this[panelItems[i][0] + 'Cell'] = td;
        }
        this.previousCell.addClassName('disabled');
        if(imgs.length == 1)
            this.nextCell.addClassName('disabled');
        
        document.body.appendChild(this.screen);
        document.body.appendChild(this.box);
        
        this.imageContainer = $(tbody.childNodes[1].childNodes[1]);
        
        this.currentImage = 0;
        this.images = imgs;
        
        this.showScreen(function() {
            this.setImage(imgs[0]);
            document.body.appendChild(this.panel);
            this.updateNumberLabel();
        }.bind(this));
    },
    
//     Lobsanov
    showScreen: function(afterFinish) {
        this.screen.appear({duration: 0.3, from: 0, to: 0.6, afterFinish: function() {
            this.box.show();
            if(afterFinish)
                afterFinish();
        }.bind(this)});
    },
    
    setImage: function(img) {
        if(typeof img == 'string') {
            var src = img;
            img = new Image();
            img.src = src;
        }
        img = $(img);
        this.imageContainer.update();
        if(!img.complete) {
            // if it hasn't loaded, wait.
            setTimeout(this.setImage.bind(this, img), 250);
            return;
        }
//         var currentImage = this.currentImage;
        log(img.width, img.height, img.src);
//         .complete
        this.setSize(img.width, img.height, function() {
            
            img.hide();
            this.imageContainer.appendChild(img);
            img.appear({duration: 0.3});
        }.bind(this));
    },
    
    setSize: function(width, height, afterFinish) {
        if(this.scaleEffect)
            this.scaleEffect.cancel();
        var effects = [];
        var newSize = {
            width: width + 'px',
            height: height + 'px'
        };
        var newMargins = {
            marginLeft: -parseInt(width / 2 + this.shadowSize) + 'px',
            marginTop: -parseInt(height / 2 + this.shadowSize) + 'px'
        };
        this.scaleEffect = new Effect.Parallel([
            new Effect.Morph(this.imageContainer, {style: newSize, sync: true}),
            new Effect.Morph(this.box, {style: newMargins, sync: true})
        ], {duration: 0.8, afterFinish: afterFinish});
    },
    
    hideScreen: function(afterFinish) {
        this.screen.fade({duration: 0.3, from: 0.6, to: 0, afterFinish: afterFinish});
    },
    
    showPrevious: function() {
        if(this.currentImage == 0)
            return;
        this.nextCell.removeClassName('disabled');
        this.setImage(this.images[--this.currentImage]);
        if(this.currentImage == 0)
            this.previousCell.addClassName('disabled');
        this.updateNumberLabel();
    },
    
    showNext: function() {
        if(this.currentImage == (this.images.length - 1))
            return;
        this.previousCell.removeClassName('disabled');
        this.setImage(this.images[++this.currentImage]);
        if(this.currentImage == (this.images.length - 1))
            this.nextCell.addClassName('disabled');
        this.updateNumberLabel();
    },
    
    updateNumberLabel: function() {
        var s = (this.currentImage + 1) + ' / ' + this.images.length;
        this.numberCell.update(s);
    },
    
    close: function() {
        this.box.remove();
        this.panel.remove();
        this.hideScreen(function() {
            this.screen.remove();
        }.bind(this));
    }
});




/////////////////////// ROT13

function rot( t, u, v ) {  return String.fromCharCode( ( ( t - u + v ) % ( v * 2 ) ) + u ); }
function R( s ) {  var b = [], c, i = s.length,   a = 'a'.charCodeAt(), z = a + 26,   A = 'A'.charCodeAt(), Z = A + 26;  while(i--) {   c = s.charCodeAt( i );   if( c>=a && c<z ) { b[i] = rot( c, a, 13 ); }   else if( c>=A && c<Z ) { b[i] = rot( c, A, 13 ); }   else { b[i] = s.charAt( i ); }  }  return b.join( '' ); } 
function rot5( s ) {  var b = [], c, i = s.length,   a = '0'.charCodeAt(), z = a + 10;  while(i--) {   c = s.charCodeAt( i );   if( c>=a && c<z ) { b[i] = rot( c, a, 5 ); }   else { b[i] = s.charAt( i ); }  }  return b.join( '' ); } 
function rot135( s ) {  return R( rot5( s ) ); }
