/*
* Copyright (c) 2006 Jonathan Weiss <jw@innerewut.de>
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/


/* tooltip-0.2.js - Small tooltip library on top of Prototype
* by Jonathan Weiss <jw@innerewut.de> distributed under the BSD license.
*
* This tooltip library works in two modes. If it gets a valid DOM element
* or DOM id as an argument it uses this element as the tooltip. This
* element will be placed (and shown) near the mouse pointer when a trigger-
* element is moused-over.
* If it gets only a text as an argument instead of a DOM id or DOM element
* it will create a div with the classname 'tooltip' that holds the given text.
* This newly created div will be used as the tooltip. This is usefull if you
* want to use tooltip.js to create popups out of title attributes.
*
*
* Usage:
*   <script src="/javascripts/prototype.js" type="text/javascript"></script>
*   <script src="/javascripts/tooltip.js" type="text/javascript"></script>
*   <script type="text/javascript">
*     // with valid DOM id
*     var my_tooltip = new Tooltip('id_of_trigger_element', 'id_of_tooltip_to_show_element')
*
*     // with text
*     var my_other_tooltip = new Tooltip('id_of_trigger_element', 'a nice description')
*
*     // create popups for each element with a title attribute
*    Event.observe(window,"load",function() {
*      $$("*").findAll(function(node){
*        return node.getAttribute('title');
*      }).each(function(node){
*        new Tooltip(node,node.title);
*        node.removeAttribute("title");
*      });
*    });
*
*   </script>
*
* Now whenever you trigger a mouseOver on the `trigger` element, the tooltip element will
* be shown. On o mouseOut the tooltip disappears.
*
* Example:
*
*   <script src="/javascripts/prototype.js" type="text/javascript"></script>
*   <script src="/javascripts/scriptaculous.js" type="text/javascript"></script>
*   <script src="/javascripts/tooltip.js" type="text/javascript"></script>
*
*   <div id='tooltip' style="display:none; margin: 5px; background-color: red;">
*     Detail infos on product 1....<br />
*   </div>
*
*   <div id='product_1'>
*     This is product 1
*   </div>
*
*   <script type="text/javascript">
*     var my_tooltip = new Tooltip('product_1', 'tooltip')
*   </script>
*
* You can use my_tooltip.destroy() to remove the event observers and thereby the tooltip.
*/

var Tooltip = Class.create();

Tooltip.prototype = {
    initialize: function(element, tool_tip) {
        var options = Object.extend({
            default_css: false,
            margin: "0px",
            padding: "5px",
            backgroundColor: "#d6d6fc",
            min_distance_x: 15,
            min_distance_y: 15,
            delta_x: 0,
            delta_y: 0,
            zindex: 1000
        }, arguments[2] || {});

        this.element = $(element);

        this.options = options;

        this.tool_tip_contents = tool_tip;

        this.eventMouseOver = this.showTooltip.bindAsEventListener(this);
        this.eventMouseOut   = this.hideTooltip.bindAsEventListener(this);
        this.eventMouseMove  = this.moveTooltip.bindAsEventListener(this);

        this.registerEvents();
    },

    destroy: function() {
        Event.stopObserving(this.element, "mouseover", this.eventMouseOver);
        Event.stopObserving(this.element, "mouseout", this.eventMouseOut);
        Event.stopObserving(this.element, "mousemove", this.eventMouseMove);
    },

    registerEvents: function() {
        Event.observe(this.element, "mouseover", this.eventMouseOver);
        Event.observe(this.element, "mouseout", this.eventMouseOut);
        Event.observe(this.element, "mousemove", this.eventMouseMove);
    },

    moveTooltip: function(event){
        if (typeof(Event.stop) != 'function') {
            return;
        }

        if (!this.tool_tip) {
            return;
        }

        // get Mouse position
        var mouse_x = Event.pointerX(event);
        var mouse_y = Event.pointerY(event);

        // get the scroll position
        var scroll_y = 0;
        if (typeof(window.pageYOffset) == 'number') {
            scroll_y = window.pageYOffset;
        } else if (document.documentElement && document.documentElement.scrollTop) {
            scroll_y = document.documentElement.scrollTop;
        } else if (document.body && document.body.scrollTop) {
            scroll_y = document.body.scrollTop;
        }

        // decide if wee need to switch sides for the tooltip
        var dimensions = Element.getDimensions( this.tool_tip );
        var element_width = dimensions.width;
        var element_height = dimensions.height;

        if ((element_width + mouse_x) >= (this.getWindowWidth() - this.options.min_distance_x - 20)){ // too big for X
            mouse_x = mouse_x - element_width;
            // apply min_distance to make sure that the mouse is not on the tool-tip
            mouse_x = mouse_x - this.options.min_distance_x;
        } else {
            mouse_x = mouse_x + this.options.min_distance_x;
        }
//document.title = 'image h =' + element_height + ' mouse_y =' + mouse_y + ' scroll_y=' + scroll_y + ' screen =' + this.getWindowHeight();
        if ((element_height + mouse_y) >= (scroll_y + this.getWindowHeight() - this.options.min_distance_y)
            && (mouse_y - scroll_y - element_height + this.options.min_distance_y > 0)) {
            mouse_y = Math.min(mouse_y - element_height + this.options.min_distance_y, scroll_y + mouse_y - (element_height - (this.getWindowHeight() - mouse_y)) - this.options.min_distance_y);
        } else if ((element_height + mouse_y) >= (scroll_y + this.getWindowHeight() - this.options.min_distance_y)
            && (scroll_y + mouse_y - element_height + this.options.min_distance_y > 0)) {
            mouse_y = Math.min(scroll_y + mouse_y - element_height + this.options.min_distance_y, scroll_y + mouse_y - (element_height - (this.getWindowHeight() - mouse_y)) - this.options.min_distance_y);
        } else if ((element_height + mouse_y) >= (scroll_y + this.getWindowHeight() - this.options.min_distance_y)){ // bas
            mouse_y = scroll_y + mouse_y - (element_height - (this.getWindowHeight() - mouse_y)) - this.options.min_distance_y;
        } else if ((mouse_y < element_height) && (mouse_y + this.options.min_distance_y > scroll_y + this.getWindowHeight() - this.options.min_distance_y)) { // haut
            mouse_y = mouse_y + (element_height - (element_height + mouse_y)) + this.options.min_distance_y + scroll_y;
        } else {
            mouse_y = mouse_y + this.options.min_distance_y;
        }

        // now set the right styles
        this.setStyles(mouse_x, mouse_y);
    },

    showTooltip: function(event) {
        if (typeof(Event.stop) != 'function') {
            return;
        }

        // use the supplied tooltip element or create our own div
        if (!this.tool_tip) {
            this.tool_tip = $(document.createElement("div"));
            document.body.appendChild(this.tool_tip);

            if (this.options.classname) {
                this.tool_tip.addClassName(this.options.classname);
            } else {
                this.tool_tip.addClassName("tooltip");
            }

            if (this.options.html) {
                this.tool_tip.update(this.tool_tip_contents);
            } else {
                this.tool_tip.appendChild(document.createTextNode(this.tool_tip_contents));
            }

            this.tool_tip.hide();
        }

        Event.stop(event);
        this.moveTooltip(event);
        new Element.show(this.tool_tip);
    },

    setStyles: function(x, y){
        // set the right styles to position the tool tip
        Element.setStyle(this.tool_tip, { position:'absolute',
                top:y + this.options.delta_y + "px",
                left:x + this.options.delta_x + "px",
                zindex:this.options.zindex
        });

        // apply default theme if wanted
        if (this.options.default_css){
            Element.setStyle(this.tool_tip, { margin:this.options.margin,
                    padding:this.options.padding,
                    backgroundColor:this.options.backgroundColor,
                    zindex:this.options.zindex
            });
        }
    },

    hideTooltip: function(event){
        if (typeof(Element.hide) != 'function') {
            return;
        }

        new Element.hide(this.tool_tip);
    },

    getWindowHeight: function(){
        var innerHeight;

        if (typeof(window.innerHeight) == 'number') {
            innerHeight = window.innerHeight;
        } else if(document.documentElement && document.documentElement.clientHeight) {
            innerHeight = document.documentElement.clientHeight;
        } else if(document.body && document.body.clientHeight){
            innerHeight = document.body.clientHeight;
        }

        return innerHeight;
    },

    getWindowWidth: function(){
        var innerWidth;
        if (typeof(window.innerWidth) == 'number') {
            innerWidth = window.innerWidth;
        } else if(document.documentElement && document.documentElement.clientWidth) {
            innerWidth = document.documentElement.clientWidth;
        } else if(document.body && document.body.clientWidth){
            innerWidth = document.body.clientWidth;
        }

        return innerWidth;
    }

}

// Automatic file, don't modify it


/* addEvent: simplified event attachment */
function addEvent( obj, type, fn ) {
	if (obj.addEventListener) {
		obj.addEventListener( type, fn, false );
		EventCache.add(obj, type, fn);
	}
	else if (obj.attachEvent) {
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
		EventCache.add(obj, type, fn);
	}
	else {
		obj["on"+type] = obj["e"+type+fn];
	}
}

var EventCache = function(){
	var listEvents = [];
	return {
		listEvents : listEvents,
		add : function(node, sEventName, fHandler){
			listEvents.push(arguments);
		},
		flush : function(){
			var i, item;
			for(i = listEvents.length - 1; i >= 0; i = i - 1){
				item = listEvents[i];
				if(item[0].removeEventListener){
					item[0].removeEventListener(item[1], item[2], item[3]);
				};
				if(item[1].substring(0, 2) != "on"){
					item[1] = "on" + item[1];
				};
				if(item[0].detachEvent){
					item[0].detachEvent(item[1], item[2]);
				};
				item[0][item[1]] = null;
			};
		}
	};
}();
addEvent(window,'unload',EventCache.flush);

/* window 'load' attachment */
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	}
	else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

/* grab Elements from the DOM by className */
function getElementsByClass(searchClass,node,tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

/* toggle an element's display */
function toggle(obj) {
	var el = document.getElementById(obj);
	if ( el.style.display != 'none' ) {
		el.style.display = 'none';
	}
	else {
		el.style.display = '';
	}
}

/* insert an element after a particular node */
function insertAfter(parent, node, referenceNode) {
	parent.insertBefore(node, referenceNode.nextSibling);
}

/* Array prototype, matches value in array: returns bool */
Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};

/* get, set, and delete cookies */
function getCookie( name ) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ";", len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}

function setCookie( name, value, expires, path, domain, secure ) {
	var today = new Date();
	today.setTime( today.getTime() );
	if ( expires ) {
		expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date( today.getTime() + (expires) );
	document.cookie = name+"="+escape( value ) +
    ( ( expires ) ? ";expires="+expires_date.toGMTString() : "" ) + //expires.toGMTString()
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

function deleteCookie( name, path, domain ) {
	if ( getCookie( name ) ) document.cookie = name + "=" +
        ( ( path ) ? ";path=" + path : "") +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

function getEventSrc(e) {
	if (!e) e = window.event;

	if (e.originalTarget)
        return e.originalTarget;
	else if (e.srcElement)
        return e.srcElement;
}


function setActiveStyleSheet(href) {
    var c = document.getElementsByTagName("link")
    var i, a, main;
    for (i = 0; a = c[i]; i++) {
        if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("href")) {
            a.disabled = true;
            if (a.getAttribute("href") == href) {
                a.disabled = false;
            }
        }
    }
}





var Ahnenposter_OpenSearch = {
    addOpenSearch: function(name) {
        if (
            (typeof window.external == 'object') &&
            ((typeof window.external.AddSearchProvider == 'unknown') || (typeof window.external.AddSearchProvider == 'function'))
        ) {
            if (((typeof window.external.AddSearchProvider == 'unknown') || (window.navigator.vendor == 'Camino'))) {
                alert(_('This plugin uses POST which is not currently supported by your browser\'s implementation of OpenSearch.'));
            } else {
               // window.external.AddSearchProvider('http://static.fotolia.com/xml/search-plugin/' + name + '_search_plugin.xml');
            }
        } else {
            alert(_('You will need a browser which supports OpenSearch to install this plugin.'));
        }
    }
}

// domready
// http://www.cherny.com/webdev/26/domloaded-object-literal-updated

Object.extend(Event, {
  _domReady : function() {
    if (arguments.callee.done) return;
    arguments.callee.done = true;

    if (this._timer)  clearInterval(this._timer);

    this._readyCallbacks.each(function(f) { f() });
    this._readyCallbacks = null;
},
  onDOMReady : function(f) {
    if (!this._readyCallbacks) {
      var domReady = this._domReady.bind(this);

      if (document.addEventListener)
        document.addEventListener("DOMContentLoaded", domReady, false);

        /*@cc_on @*/
        /*@if (@_win32)
            var proto = "src='javascript:void(0)'";
            //if (location.protocol == "https:") proto = "src='https://sstatic.fotolia.com/js/ie_onload.js'";
            document.write("<scr"+"ipt id=__ie_onload defer " + proto + "><\/scr"+"ipt>");
            var script = document.getElementById("__ie_onload");
            script.onreadystatechange = function() {
                if (this.readyState == "complete") {
                    domReady();
                }
            };
        /*@end @*/

        if (/WebKit/i.test(navigator.userAgent)) {
          this._timer = setInterval(function() {
            if (/loaded|complete/.test(document.readyState)) domReady();
          }, 10);
        }

        Event.observe(window, 'load', domReady);
        Event._readyCallbacks =  [];
    }
    Event._readyCallbacks.push(f);
  }
});


var AhnenposterAjaxActions = {
    obj: Object,

    init: function() {
        if (
            !document.getElementById ||
            !document.createElement ||
            !document.getElementsByTagName
        ) {
            return;
        }

        var i,j;

        // add events to Ajax links
        var current = document.getElementsByTagName('a');
        var curLen = current.length;


        for (j = 0; j < curLen; j++) {
            // must redefine regexp because of reuse
            var regexp = new RegExp('^https?://[A-Za-z0-9_\\.]+/Ajax/([A-Za-z0-9]+)', 'gi');
            var results = regexp.exec(current[j].href);
            if (!results) {
                continue;
            }

            // replace onclick
            current[j].onclick = AhnenposterAjaxActions.basicClick;
        }
    },

    basicClick: function(e) {
        url = this.href;

        var pars = '';
        var myAjax = new Ajax.Request();

        myAjax.setOptions(
            {
                method: 'get',
                parameters: pars,
                onComplete: AhnenposterAjaxActions.XHRResponseTextCallback
            }
        );

        // reference to source
        myAjax.sourceObject = this;

        myAjax.request(url);

        return false;
    },

    radioClick: function(e) {

        url = this.href;

        var pars = '';
        var myAjax = new Ajax.Request();
        myAjax.setOptions(
            {
                method: 'get',
                parameters: pars,
                onComplete: AhnenposterAjaxActions.XHRResponseTextCallback
            }
        );

        // reference to source
        myAjax.sourceObject = this;

        myAjax.request(url);

        return true;
    },

    XHRResponseTextCallback: function(XHR, eJSON, origin) {
        try {
            eval(XHR.responseText);
        } catch (e) {
            var s = '';
            for (i in e) {
                s += i + ' = ' + e[i] + "\n";
            }
        }
    }
}


/*
Zoom on 400px images

based on http://valid.tjp.hu/zoom2/index_en.html + events and crop on server
create several AhnenposterZoom object on onload events
*/
var AhnenposterZooms = {
    containers: new Array(),

    init: function() {

        if (
            !document.getElementById ||
            !document.createElement ||
            !document.getElementsByTagName
        ) {
            return;
        }

        var current = document.getElementsByTagName('img');
        var curLen = current.length;


		var ele = document.getElementById('zoom');

		if(!ele) {
			 return;
		}
		
		AhnenposterZooms.createNewZoom(ele);
		addEvent(window.document, 'click', function() { AhnenposterZooms.reinit(); });
        
    },

    createNewZoom: function(img)
    {
        // zoom ratio for each new click
        if (zoom_ratio = img.getAttribute('zoom_ratio')) {
            zoom_ratio = Number(zoom_ratio);
            if (zoom_ratio == 0) {
                return;
            }
        } else {
            return;
        }

        if (zoom_depth_max = img.getAttribute('zoom_depth_max')) {
            zoom_depth_max = Number(zoom_depth_max);
        } else {
            return;
        }

        var zoom = new AhnenposterZoom(img, zoom_ratio, zoom_depth_max);
        zoom.create();
    },

    reinit: function()
    {
        for (var i = 0, l = AhnenposterZooms.containers.length; i < l; i++) {
            var container = AhnenposterZooms.containers[i];

            // reinit
            if (typeof(container.originalSrc) == 'undefined') {
                continue;
            }

            container.img.src = container.originalSrc;

            container.img.style.left = '0px';
            container.img.style.top = '0px';
            container.img.width = container.w;
            container.img.height = container.h;

            container.AhnenposterZoom.zoomDepth = 1;

            container.baseX = 0;
            container.baseY = 0;

            container.baseLeft = 0;
            container.baseTop = 0;

            container.AhnenposterZoom.zoomDepth = 1;
        }
    }
}


function AhnenposterZoom(img, zoom_ratio, zoom_depth_max)
{


    this.img = img;

    // zoom ratio for each new click
    this.zoomRatio = zoom_ratio
    this.zoomDepthMax = zoom_depth_max + 1;

    // clip border
    this.bordersize = 1;

    // clip border
    this.outbordersize = 1;

    // ratio of the clip box
    this.ratio = 1 / this.zoomRatio;

    this.zoomDepth = 0;

    this.loading = false;
}

AhnenposterZoom.prototype.create = function()
{
    // add events, only on jpg
    //var regexp_tb = new RegExp('\/(jpg|photos_mini)\/.+\/(300|400)_F_');

    //if (!this.img.src.match(regexp_tb)) {
    //    return;
    //}


    // create container
    var div = document.createElement('div');
    div.id = 'AhnenposterZoom:' + this.img.src;

    div.style.width = this.img.width + 'px';
    div.style.height = this.img.height + 'px';

    var newImage = this.img.cloneNode(false);
    newImage.originalSrc = newImage.src;
    newImage.id = 'img:' + this.img.src;
    newImage.setAttribute('title', '');

    // create clip
    var divClip = document.createElement('div');

    Element.setStyle(
        div,
        {
            position: 'relative',
            overflow: 'hidden'
        }
    );
	

    Element.setStyle(
        divClip,
        {
            position: 'absolute',
            width: Math.round(this.img.width * this.ratio) + 'px',
            height: Math.round(this.img.height * this.ratio) + 'px',
            border: '1px solid #777777',
            borderWidth: Math.round(this.bordersize) + 'px'
        }
    );
    
    

    Element.hide(divClip);

    // append child
    div.appendChild(newImage);
    div.appendChild(divClip);

    // replace original image
    this.img.parentNode.replaceChild(div, this.img);

    Element.addClassName(div, 'AhnenposterZoom');
    Element.addClassName(divClip, 'AhnenposterZoomClip');

    // name references
    this.container = div;
    this.container.img = newImage;
    this.container.clip = divClip;

    this.container.AhnenposterZoom = this;

    addEvent(this.container, 'mouseover', this.onmouseover);
    addEvent(this.container, 'mousemove', this.onmousemove);
    addEvent(this.container, 'mouseout', this.onmouseout);
    addEvent(this.container, 'click', this.onclick);

    AhnenposterZooms.containers.push(this.container);
}

// for these functions, 'this' is the container
AhnenposterZoom.prototype.onmousemove = function(e)
{
    var xCord;
    var yCord;

    if (document.captureEvents) {
        xCord = e.pageX;
        yCord = e.pageY;
    } else if (window.event.clientX) {
        xCord = window.event.clientX + document.documentElement.scrollLeft;
        yCord = window.event.clientY + document.documentElement.scrollTop;
    }

    // reference to clip
    var clip = this.clip;

    var left = Math.ceil(xCord - this.xCord - clip.w / 2);
    var top = Math.ceil(yCord - this.yCord - clip.h / 2);

    if (left < 0) {
        left = 0;
    } else if (left >= (this.w - clip.w)) {
        left = this.w - clip.w - this.AhnenposterZoom.bordersize * 2;
    }

    if (top < 0) {
        top = 0;
    } else if (top >= (this.h - clip.h)) {
        top = this.h - clip.h - this.AhnenposterZoom.bordersize * 2;
    }

    if (isNaN(top)) {
        top = 0;
    }

    if (isNaN(left)) {
        left = 0;
    }

    Element.setStyle(
        clip,
        {
            top: top + 'px',
            left: left + 'px'
        }
    );
}

AhnenposterZoom.prototype.onmouseover = function(e)
{
    if (this.AhnenposterZoom.hideClipTimeout) {
        window.clearTimeout(this.AhnenposterZoom.hideClipTimeout);
    }

    if (this.AhnenposterZoom.zoomDepth >= this.AhnenposterZoom.zoomDepthMax) {
        return;
    } else if (this.loading) {
        return;
    } else {
        if (Element.visible(this.clip)) {
            return;
        }

        this.AhnenposterZoom.showClip(this);
    }
}

AhnenposterZoom.prototype.showClip = function(container)
{
    var clip = container.clip;


    if (typeof(container.xCord) == 'undefined' || container.xCord == 0) {
        var pos = Position.cumulativeOffset(container);
        container.xCord = pos[0];
        container.yCord = pos[1];

        var dims = Element.getDimensions(container);
        container.w = dims['width'];
        container.h = dims['height'];

        var clipDims = Element.getDimensions(clip);
        clip.w = clipDims['width'];
        clip.h = clipDims['height'];
    }

    if (container.AhnenposterZoom.hideClipTimeout) {
        window.clearTimeout(container.AhnenposterZoom.hideClipTimeout);
    }

    Element.show(clip);
}

AhnenposterZoom.prototype.onmouseout = function(e)
{
    if (this.AhnenposterZoom.hideClipTimeout) {
        window.clearTimeout(this.AhnenposterZoom.hideClipTimeout);   
    }
    this.AhnenposterZoom.hideClipTimeout = window.setTimeout('var container = $("' + this.id + '"); container.AhnenposterZoom.hideClip(container);', 100);
    
    
}

AhnenposterZoom.prototype.hideClip = function(container)
{
    Element.hide(container.clip);
}

AhnenposterZoom.prototype.reinit = function(container)
{
    // reinit
    if (typeof(container.originalSrc) == 'undefined') {
        return;
    }

    container.img.src = container.originalSrc;

    container.img.style.left = '0px';
    container.img.style.top = '0px';
    container.img.width = container.w;
    container.img.height = container.h;

    container.baseX = 0;
    container.baseY = 0;

    container.baseLeft = 0;
    container.baseTop = 0;

    container.AhnenposterZoom.zoomDepth = 1;
    container.loading = false;
}

AhnenposterZoom.prototype.onloadZoomImage = function(container)
{
    var img = container.img;

    Element.hideExt(img);

    window.setTimeout(
        function() {
            img.width = img.zoomImage.width;
            img.height = img.zoomImage.height;
            img.style.left = 0;
            img.style.top = 0;

            img.src = img.zoomImage.src;
            Element.showExt(img);
        },
        0);

    container.loading = false;

    if (container.AhnenposterZoom.zoomDepth < container.AhnenposterZoom.zoomDepthMax) {
        container.AhnenposterZoom.showClip(container);
    }
}

AhnenposterZoom.prototype.onclick = function(e)
{
    if (this.loading) {
        Event.stop(e);
        return;
    }

    if (this.AhnenposterZoom.zoomDepth == 0) {
        // first call

        this.originalSrc = this.img.src;

        this.baseX = 0;
        this.baseY = 0;

        this.baseLeft = 0;
        this.baseTop = 0;

        this.AhnenposterZoom.zoomDepth = 1;
    }

    if (this.onloadZoomImageTimeout) {
        window.clearTimeout(this.onloadZoomImageTimeout);
    }

    if (this.AhnenposterZoom.zoomDepth >= this.AhnenposterZoom.zoomDepthMax) {
        this.AhnenposterZoom.reinit(this);
        this.AhnenposterZoom.showClip(this);
    } else {
        var pos = Position.positionedOffset(this.img);
        var clipPos = Position.positionedOffset(this.clip);
        var dims = Element.getDimensions(this.img);

		

        var currentZoomRatio = Math.pow(this.AhnenposterZoom.zoomRatio, this.AhnenposterZoom.zoomDepth - 1);

        // we must remember where we are this.based on orginal image

        this.baseX = ((0 - this.baseLeft) + clipPos[0] + this.AhnenposterZoom.bordersize + this.clip.w / 2) / currentZoomRatio;
        this.baseY = ((0 - this.baseTop) + clipPos[1] + this.AhnenposterZoom.bordersize + this.clip.h / 2) / currentZoomRatio;

        this.baseLeft = (this.w / 2) - (this.baseX * this.AhnenposterZoom.zoomRatio * currentZoomRatio);
        this.baseTop = (this.h / 2) - (this.baseY * this.AhnenposterZoom.zoomRatio * currentZoomRatio);


        // request new image (zoom + crop) and display it
        var zoomImage = new Image();
		var ratio = (this.w / this.h)
      
        zoomImage.src = HOME_URL + 'Zoom?ratio=' + ratio + '&zoom=' + (this.AhnenposterZoom.zoomRatio * currentZoomRatio) + '&x=' + this.baseX + '&y=' + this.baseY + '&path=' + escape(this.originalSrc);
        
        zoomImage.targetImg = this.img;
        zoomImage.container = this;

		document.getElementById("infoLoad").innerHTML = '<img src="'+HOME_URL+'img/loadingAnimation.gif" />';

        this.img.zoomImage = zoomImage;

        this.loading = true;

        zoomImage.onload = function (e) {
            this.container.onloadZoomImageTimeout = window.setTimeout('var container = $("' + this.container.id + '"); container.AhnenposterZoom.onloadZoomImage(container);', 10);
            document.getElementById("infoLoad").innerHTML = '';
        };

        // and now we compute for browser zoom

        if (pos[0] == 0 && dims['width'] == this.w) {
            // no zoom for the current image
            currentZoomRatio = 1;
        }

        // dot position which will be the new center (based on current image displayed, dynamix src)
        var x = ((0 - pos[0]) + clipPos[0] + this.AhnenposterZoom.bordersize + this.clip.w / 2) / currentZoomRatio;
        var y = ((0 - pos[1]) + clipPos[1] + this.AhnenposterZoom.bordersize + this.clip.h / 2) / currentZoomRatio;

        // multiply dims
        var w = this.w * this.AhnenposterZoom.zoomRatio * currentZoomRatio;
        var h = this.h * this.AhnenposterZoom.zoomRatio * currentZoomRatio;

        // translate origin: x,y must be on the center
        var l = (this.w / 2) - (x * this.AhnenposterZoom.zoomRatio * currentZoomRatio);
        var t = (this.h / 2) - (y * this.AhnenposterZoom.zoomRatio * currentZoomRatio);

        // bound origins
        if (l > 0) {
            l = 0;
        } else if (l + w < this.w) {
            l = this.w - w;
        }

        if (t > 0) {
            t = 0;
        } else if (t + h < this.h) {
            t = this.h - h;
        }

        // browser zoom
        Element.setStyle(
            this.img,
            {
                position: 'absolute',
                left: Math.round(l) + 'px',
                top: Math.round(t) + 'px'
            }
        );



        // zoom with current image (browser zoom)
        this.img.width = w;
        this.img.height = h;

        this.AhnenposterZoom.zoomDepth++;

        this.AhnenposterZoom.hideClip(this);
    }

    Event.stop(e);
}


var AhnenposterTooltip = {
    init: function() {
        if (
            !document.getElementById ||
            !document.createElement ||
            !document.getElementsByTagName
        ) {
            return;
        }

        var current = document.getElementsByClassName('image_tooltip');
        var curLen = current.length;

        for (var j = 0; j < curLen; j++) {

            var regexp = new RegExp('cache.*cache');
            var largeSrc = current[j].src.replace(regexp, 'cache');
			
            current[j].setAttribute('largeSrc', largeSrc);

            var title = current[j].getAttribute('title');
            // remove title
            current[j].setAttribute('title', '');

            var tip = '<div class="tool"><img src="' + largeSrc + '" /></div>';
            new Tooltip(current[j], tip, {'html': true, 'classname': 'AhnenposterTooltipObject'});
        }
    }
}

var Ahnenposter = {

    init: function()
    {
        // init all objects
        AhnenposterZooms.init();
        AhnenposterTooltip.init();
        
        
    }
    
}

Event.onDOMReady(function() {
    Ahnenposter.init();
});


Element.AhnenposterMethods = {
    visibleExt: function(element) {
        var dyn = $(element).style.display;
        var css = $(element).getStyle('display');

        switch (dyn) {
            case 'none':
                return false;
            case '':
                return (css != 'none');

            default:
                return true;
        }
    },

    toggleExt: function() {
        for (var i = 0; i < arguments.length; i++) {
            var element = $(arguments[i]);
            Element[Element.visibleExt(element) ? 'hideExt' : 'showExt'](element);
        }
    },

    hideExt: function() {
        for (var i = 0; i < arguments.length; i++) {
            var element = $(arguments[i]);
            element.style.display = 'none';
        }
    },

    showExt: function() {
        for (var i = 0; i < arguments.length; i++) {
            var element = $(arguments[i]);
            element.style.display = 'block';
        }
    },

    visibleInline: function(element) {
        var dyn = $(element).style.display;
        var css = $(element).getStyle('display');

        switch (dyn) {
            case 'none':
                return false;
            case '':
                return (css != 'none');

            default:
                return true;
        }
    },

    toggleInline: function() {
        for (var i = 0; i < arguments.length; i++) {
            var element = $(arguments[i]);
            Element[Element.visibleInline(element) ? 'hideInline' : 'showInline'](element);
        }
    },

    hideInline: function() {
        for (var i = 0; i < arguments.length; i++) {
            var element = $(arguments[i]);
            element.style.display = 'none';
        }
    },

    showInline: function() {
        for (var i = 0; i < arguments.length; i++) {
            var element = $(arguments[i]);
            element.style.display = 'inline';
        }
    },

    showTr: function() {
        for (var i = 0; i < arguments.length; i++) {
            var element = $(arguments[i]);
            try {
                element.style.display = 'table-row';
            } catch (e) {
                // IE bug
                element.style.display = '';
            }
        }
    },

    fastUpdate: function(element, html) {
        $(element).innerHTML = html;
    },

    fastReplace: function(element, html) {
        element = $(element);
        if (element.outerHTML) {
            element.outerHTML = html;
        } else {
            var range = element.ownerDocument.createRange();
            range.selectNodeContents(element);
            element.parentNode.replaceChild(
                range.createContextualFragment(html),
                element
            );
        }
    },

    firstParentByTagName: function(element, tagName) {
        tagName = tagName.toUpperCase();
        element = $(element);
        while (element = element.parentNode) {
            if (element.tagName.toUpperCase() == tagName) {
                return element;
            }
        }

        return false;
    },

    insertLastSibling: function(element, type, label, attrs) {
        var node;

        element = $(element);
        if (!element || !element.parentNode) {
            return ;
        }

        node = null;
        if (element.parentNode.lastChild.nodeName.toUpperCase() == type.toUpperCase()) {
            if (attrs.className && element.parentNode.lastChild.className == attrs.className) {
                node = element.parentNode.lastChild;
                node.removeChild(node.firstChild);
                node.appendChild(document.createTextNode(label));
            }
        }
        if (!node) {
            node = document.createElement(type);
            node.appendChild(document.createTextNode(label));
            if (attrs.className) {
                node.className = attrs.className;
            }

            element.parentNode.appendChild(node);
        }
    },

    removeLastSibling: function(element, type) {
        element = $(element);
        if (!element || !element.parentNode) {
            return ;
        }

        if (!type || type.toUpperCase() == element.parentNode.lastChild.nodeName.toUpperCase()) {
            element.parentNode.removeChild(element.parentNode.lastChild);
        }
    }
}

Object.extend(Element, Element.AhnenposterMethods);
Element.addMethods(Element.AhnenposterMethods);


