
//{{{ Emile

// emile.js (c) 2009 Thomas Fuchs
// Licensed under the terms of the MIT license.

(function(emile, container){
  var parseEl = document.createElement('div'),
    props = ('backgroundColor borderBottomColor borderBottomWidth borderLeftColor borderLeftWidth '+
    'borderRightColor borderRightWidth borderSpacing borderTopColor borderTopWidth bottom color fontSize '+
    'fontWeight height left letterSpacing lineHeight marginBottom marginLeft marginRight marginTop maxHeight '+
    'maxWidth minHeight minWidth opacity outlineColor outlineOffset outlineWidth paddingBottom paddingLeft '+
    'paddingRight paddingTop right textIndent top width wordSpacing zIndex').split(' '),
    supportsOpacity = typeof parseEl.style.opacity == 'string', 
    supportsFilters = typeof parseEl.style.filter == 'string',
    view = document.defaultView,
    supportsGCS = view && typeof view.getComputedStyle !== 'undefined',
    reOpacity = /alpha\s*\(\s*opacity\s*=\s*([^\)]+)\)/,
    setOpacity = function(){ }, 
    getOpacityFromComputed = function(){ return '1'; };
    
  if (supportsOpacity) {
    setOpacity = function(el, value){ el.style.opacity = value; };
    getOpacityFromComputed = function(computed) { return computed.opacity; };
  }
  else if (supportsFilters) {
    setOpacity = function(el, value){
      var es = el.style;
      if (el.currentStyle && !el.currentStyle.hasLayout) es.zoom = 1;
      if (reOpacity.test(es.filter)) {
        value = value >= 0.9999 ? '' : ('alpha(opacity=' + (value * 100) + ')');
        es.filter = es.filter.replace(reOpacity, value);
      }
      else {
        es.filter += ' alpha(opacity=' + (value * 100) + ')';
      }
    };
    getOpacityFromComputed = function(comp) {
      var m = comp.filter.match(reOpacity);
      return (m ? (m[1] / 100) : 1) + '';
    };
  }
    
  function interpolate(source,target,pos){ return (source+(target-source)*pos).toFixed(3); }
  function s(str, p, c){ return str.substr(p,c||1); }
  function color(source,target,pos){
    var i = 2, j, c, tmp, v = [], r = [];
    while(j=3,c=arguments[i-1],i--)
      if(s(c,0)=='r') { c = c.match(/\d+/g); while(j--) v.push(~~c[j]); } else {
        if(c.length==4) c='#'+s(c,1)+s(c,1)+s(c,2)+s(c,2)+s(c,3)+s(c,3);
        while(j--) v.push(parseInt(s(c,1+j*2,2), 16)); }
    while(j--) { tmp = ~~(v[j+3]+(v[j]-v[j+3])*pos); r.push(tmp<0?0:tmp>255?255:tmp); }
    return 'rgb('+r.join(',')+')';
  }
  
  function parse(prop){
    var p = parseFloat(prop), q = prop.replace(/^[\-\d\.]+/,'');
    return isNaN(p) ? { v: q, f: color, u: ''} : { v: p, f: interpolate, u: q };
  }
  
  function normalize(style){
    var css, rules = {}, i = props.length, v;
    parseEl.innerHTML = '<div style="'+style+'"></div>';
    css = parseEl.childNodes[0].style;
    while(i--) if(v = css[props[i]]) rules[props[i]] = parse(v);
    return rules;
  } 
  
  container[emile] = function(el, style, opts){
    el = typeof el == 'string' ? document.getElementById(el) : el;
    opts = opts || {};
    var target = normalize(style), comp = supportsGCS ? view.getComputedStyle(el, null) : el.currentStyle,
      prop, current = {}, start = +new Date, dur = opts.duration||200, finish = start+dur, interval,
      easing = opts.easing || function(pos){ return (-Math.cos(pos*Math.PI)/2) + 0.5; }, curValue;
    for(prop in target) current[prop] = parse(prop === 'opacity' ? getOpacityFromComputed(comp) : comp[prop]);
    interval = setInterval(function(){
      var time = +new Date, pos = time>finish ? 1 : (time-start)/dur;
      for(prop in target) {
        curValue = target[prop].f(current[prop].v,target[prop].v,easing(pos)) + target[prop].u;
        if (prop === 'opacity') setOpacity(el, curValue);
        else el.style[prop] = curValue;
      }
      if(time>finish) { clearInterval(interval); opts.after && opts.after(); }
    },10);
  }
})('emile', this);
//}}}

//{{{ initSIFR
function initSIFR() {
    var sackers = { src: '/swf/sackers.swf' };
    sIFR.activate(sackers);
    sIFR.replace(sackers, {
        selector: 'h2',
        transparent: true,
        forceSingleLine: true,
        css: {
            '.sIFR-root': { 'color': '#000000' }
        }
    });
}
//}}}

//{{{ Helper functions (_$, bind...)
function $(el) {
    return (typeof el == 'string') ? document.getElementById(el) : el;
}

function $A(a) {
    if (!a) return [];
    if (a.toArray) return a.toArray();
    else {
        var r = [], i;
        for (i = 0, l = a.length; i < l; i++) r.push(a[i]);
        return r;
    }
}

Function.prototype.bind = function() {
    var __method = this, args = $A(arguments), object = args.shift();
    return function() {
        return __method.apply(object, args.concat($A(arguments)));
    }
}

Object.extend = function(destination, source) {
  for (var property in source) {
    destination[property] = source[property];
  }
  return destination;
}

function setStyle(element, styles) {
    for (var property in styles) {
        element.style[property] = styles[property];
    }
}

function hide(element) {
    element.style.display = 'none';
}

function show(element, inline) {
    element.style.display = (inline) ? 'inline' : 'block';
}

var getElementsByClassName = function (className, tag, elm){
	if (document.getElementsByClassName) {
		getElementsByClassName = function (className, tag, elm) {
			elm = elm || document;
			var elements = elm.getElementsByClassName(className),
				nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
				returnElements = [],
				current, i;
			for(i=0, il=elements.length; i<il; i+=1){
				current = elements[i];
				if(!nodeName || nodeName.test(current.nodeName)) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	else if (document.evaluate) {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = "",
				xhtmlNamespace = "http://www.w3.org/1999/xhtml",
				namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
				returnElements = [],
				elements,
				node, j;
			for(j=0, jl=classes.length; j<jl; j+=1){
				classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
			}
			try	{
				elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
			}
			catch (e) {
				elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
			}
			while ((node = elements.iterateNext())) {
				returnElements.push(node);
			}
			return returnElements;
		};
	}
	else {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = [],
				elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
				current,
				returnElements = [],
				match,
                k, l, m;
			for(k=0, kl=classes.length; k<kl; k+=1){
				classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
			}
			for(l=0, ll=elements.length; l<ll; l+=1){
				current = elements[l];
				match = false;
				for(m=0, ml=classesToCheck.length; m<ml; m+=1){
					match = classesToCheck[m].test(current.className);
					if (!match) {
						break;
					}
				}
				if (match) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	return getElementsByClassName(className, tag, elm);
};

//}}}

//{{{ PreHome
var PreHome = {
    init: function(wrapper_id, photos) {
        var me = this,
            wrapper = $(wrapper_id),
            img = wrapper.getElementsByTagName('img')[0];

        me.wrapper = wrapper;
        me.img = img;
        me.photos = photos;
        me.cur_photo = 0;

        hide(img);
        img.onload = me.photoLoaded.bind(me);
    },

    photoLoaded: function() {
        var me = this,
            img = me.img,
            new_img = new Image();

        new_img.onload = function() {
            me.ratio = new_img.height / new_img.width;
            window.onresize = me.resizePhoto.bind(me);
            me.resizePhoto();
            show(img);
        }

        new_img.src = img.src;
    },

    resizePhoto: function() {
        if (window.resize_IE6) {
            resize_IE6();
        }

        var me = this,
            img = me.img,
            wrapper = me.wrapper,
            ratio = me.ratio,
            max_w = wrapper.offsetWidth,
            max_h = wrapper.offsetHeight,
            h = Math.round(max_w * ratio),
            w = Math.round(max_h / ratio);

        if (w < max_w) {
            w = max_w;
            img.width = max_w;
            img.height = h;
        } else {
            h = max_h;
            img.width = w;
            img.height = max_h;
        }

        setStyle(img, {
            top: Math.min(0, (max_h - h) / 2) + 'px',
            left: Math.min(0, (max_w - w) / 2) + 'px'
        });
    }
};
//}}}

//{{{ Menu
var Menu = {
    init: function() {
        var me = this,
            menu = $('menu'),
            submenus = getElementsByClassName('submenu', 'div', menu),
            i, j, links;

        me.menu = menu;
        me.submenus = submenus;

        // Show thumbs preview on rollover
        for (i = 0; i < submenus.length; i++) {
            links = submenus[i].getElementsByTagName('a');
            for (j = 0; j < links.length; j++) {
                links[j].onmouseover = function() {
                    var preview = $(this.id.replace(/_link/, '') + '_preview');
                    if (preview) show(preview);
                }

                links[j].onmouseout = function() {
                    var preview = $(this.id.replace(/_link/, '') + '_preview');
                    if (preview) hide(preview);
                }
            }
        }
    }
};
//}}}

//{{{ Gallery

// FIX ME : some code (ie resize) is duplicated with PreHome

var Gallery = {
    init: function(wrapper_id, options) {
        var me = this,
            wrapper = $(wrapper_id),
            img = wrapper.getElementsByTagName('img')[0];

        me.options = Object.extend({
            x: 160,
            y: 0,
            margin_bottom: 50,
            photos: [],
            legends: [],
            cur_index: 0
        }, options || {});

        me.wrapper = $(wrapper_id);
        me.img = img;
        me.photos = me.options.photos;
        me.legends = me.options.legends;
        me.cur_photo = me.options.cur_index;

        setStyle(img, {
            display: 'none',
            position: 'absolute',
            height: 'auto',
            margin: 0
        });

        img.onload = me.photoLoaded.bind(me);

        me.setLoading(true);

        if (me.photos.length > 1) {
            $('next_link').onclick = me.showNextPhoto.bind(me);
            $('previous_link').onclick = me.showPreviousPhoto.bind(me);
        }
    },

    showPhoto: function(photo_index) {
        var me = this, img = me.img;
        emile(img, 'opacity:0', {
            duration: 250,
            after: function() {
                me.setLoading(true);
                img.src = '/photos/series/' + me.photos[photo_index] + '.jpg';
            }
        });
    },

    showNextPhoto: function() {
        var me = this, FALSE = false;
        if (me.loading) return FALSE;

        me.cur_photo++;
        if (me.cur_photo > me.photos.length - 1) me.cur_photo = 0;
        me.showPhoto(me.cur_photo);
        return FALSE;
    },

    showPreviousPhoto: function() {
        var me = this, FALSE = false;
        if (me.loading) return FALSE;

        me.cur_photo--;
        if (me.cur_photo < 0) me.cur_photo = me.photos.length - 1;
        me.showPhoto(me.cur_photo);
        return FALSE;
    },

    photoLoaded: function() {
        var me = this,
            img = me.img,
            new_img = new Image();

        new_img.onload = function() {
            me.ratio = new_img.height / new_img.width;
            me.realWidth = new_img.width;

            window.onresize = me.resizePhoto.bind(me);
            me.resizePhoto();

            me.setLoading();
            show(img);
            emile(img, 'opacity:1');
        }

        new_img.src = img.src;
    },

    setLoading: function(loading) {
        var me = this, legend = $('legend');
        me.loading = loading;
        if (loading) {
            show($('spinner'));
            if (legend) legend.innerHTML = '';
        } else {
            hide($('spinner'));
            if (legend) legend.innerHTML = me.legends[me.cur_photo];
        }
    },

    resizePhoto: function() {
        if (window.resize_IE6) {
            resize_IE6();
        }

        var me = this,
            img = me.img,
            wrapper = me.wrapper,
            wrap_w = wrapper.offsetWidth,
            wrap_h = wrapper.offsetHeight,
            x = me.options.x,
            y = me.options.y,
            max_w = wrap_w - (x * 2),
            max_h = wrap_h - (y * 2) - me.options.margin_bottom,
            w = Math.min(max_w, me.realWidth),
            h = Math.round(w * me.ratio),
            top, left;

        if (h > max_h) {
            h = max_h;
            w = Math.round(h / me.ratio);
        }

        img.width = w;
        img.height = h;

        left = x + Math.round((max_w - w) / 2);
        top = y + Math.round((max_h - h) / 2);
        setStyle(img, {
            top: top + 'px',
            left: left + 'px'
        });
    }
};
//}}}

//{{{ Thumbnails
var Thumbnails = {
    init: function(wrapper_id) {
        var me = this,
            wrapper = $(wrapper_id),
            parent = wrapper.parentNode,
            imgs = wrapper.getElementsByTagName('IMG'),
            total_thumbs = imgs.length,
            _setStyle = setStyle,
            i;

        me.wrapper = wrapper;
        me.parent = parent;

        _setStyle(wrapper, {
            width: (Math.ceil(total_thumbs / 3) * 140) + 'px'
        });

        _setStyle(parent, {
            overflow: 'hidden',
            left: '110px',
            right: '110px'
        });

        $('next_link').onclick = me.nextClicked.bind(me);
        $('previous_link').onclick = me.previousClicked.bind(me);

        for (i = 0; i < total_thumbs; i++) {
            hide(imgs[i]);
            imgs[i].onload = function() {
                _setStyle(this, {
                    paddingTop: ((120 - this.height) / 2) + 'px',
                    display: 'inline'
                });
            }
        }

        me.onResize();
        window.onresize = me.onResize.bind(me);
    },

    getCurX: function() {
        return parseInt(this.wrapper.style.left.replace(/px/, ''), 10);
    },

    getSlideOffset: function() {
        return Math.floor(this.parent.offsetWidth / 140) * 140;
    },

    slide: function(dir) {
        var me = this,
            wrapper = me.wrapper,
            next_x = me.getCurX() + me.getSlideOffset() * dir;

        if (dir == -1 && Math.abs(next_x) > wrapper.offsetWidth)
            return false;

        if (dir == 1 && next_x > 0)
            return false;

        emile(wrapper, 'left:' + next_x + 'px');
        return false;
    },

    previousClicked: function() {
        return this.slide(1);
    },

    nextClicked: function() {
        return this.slide(-1);
    },

    onResize: function() {
        var me = this,
            wrapper = me.wrapper,
            arrows = $('thumbnails_arrows');

        wrapper.style.paddingTop = (Math.max(0, (wrapper.parentNode.offsetHeight - 400) / 2)) + 'px';

        if (me.parent.offsetWidth > wrapper.offsetWidth) {
            hide(arrows);
            setStyle(wrapper, {
                position: 'static',
                left: 'auto'
            });
        } else {
            show(arrows);
            setStyle(wrapper, {
                position: 'absolute',
                left: '0px'
            });
        }
    }
}
//}}}


