// return  null if no element is found.
function getPreviousTag(tag, currentElement)
{
	var result = currentElement;
	
	if (!currentElement)
		return (null);
	// if passed argument is already searched element, return this element.
	if (currentElement.tagName && currentElement.tagName.toLowerCase() == tag.toLowerCase())
		return (currentElement);
	while (result.previousSibling)
	{
		result = result.previousSibling;
		if (result.tagName && result.tagName.toLowerCase() == tag.toLowerCase())
			return (result);
	}
	return (null);
}

function centerElement(el, parent, ref)
{
	if (!parent)
		parent = el.parentNode
	if (!ref)
		ref = el;
	el.style.position = 'relative';
	el.style.top = Math.floor((parent.clientHeight - ref.offsetHeight) / 2) + 'px';
	el.style.left = Math.floor((parent.clientWidth - ref.offsetWidth) / 2) + 'px';
}

// return  null if no element is found.
function getNextTag(tag, currentElement)
{
	var result = currentElement;
	
	if (!currentElement)
		return (null);
	// if passed argument is already searched element, return this element.
	if (currentElement.tagName && currentElement.tagName.toLowerCase() == tag.toLowerCase())
		return (currentElement);
	while (result.nextSibling)
	{
		result = result.nextSibling;
		if (result.tagName && result.tagName.toLowerCase() == tag.toLowerCase())
			return (result);
	}
	return (null);
}

function positionAdvancedSearchLayerClose()
{
    var close = $('advanced_search_layer_close');
    var base = $('page');
    var rightPadding = 5;
    
    close.style.left = (base.clientWidth - close.clientWidth - rightPadding) + 'px';
    close.style.top = base.getTop();
}

function getAdvancedSearchLayerBlocksProperties()
{
    var blocksProperties = {};
    var base = $('page');
    
    blocksProperties.width = 150;
    blocksProperties.height = 150;
    blocksProperties.marginTop = $('advanced_search_layer_close').clientHeight + $('advanced_search_layer_close').getTop();
    blocksProperties.numberByWidth = Math.floor(base.clientWidth / blocksProperties.width);
    blocksProperties.numberByHeight = Math.floor((getWindowHeight() - blocksProperties.marginTop) / blocksProperties.height);
    blocksProperties.searchboxBlocksWidth = 2;
    blocksProperties.searchboxBlocksHeight = 1;
    blocksProperties.countBlocks = blocksProperties.numberByWidth * blocksProperties.numberByHeight;
    blocksProperties.countBlocks -= (blocksProperties.searchboxBlocksWidth * blocksProperties.searchboxBlocksHeight);
    return (blocksProperties);
}

function getAdvancedSearchLayerSearchboxProperties()
{
    var searchboxProperties = {};
    var blocksProperties = getAdvancedSearchLayerBlocksProperties();
    var top = Math.floor(blocksProperties.numberByHeight / 2);
    var left = Math.floor(blocksProperties.numberByWidth / 2);
    
    if (top == (blocksProperties.numberByHeight / 2))
        top -= 1;
    if (left == (blocksProperties.numberByWidth / 2))
        left -= 1;
    
    searchboxProperties.blockTop = top;
    searchboxProperties.blockLeft = left;
    searchboxProperties.y = blocksProperties.marginTop + (top * blocksProperties.height);
    searchboxProperties.x = left * blocksProperties.width;
    searchboxProperties.width = blocksProperties.width * blocksProperties.searchboxBlocksWidth;
    searchboxProperties.height = blocksProperties.height * blocksProperties.searchboxBlocksHeight;
    return (searchboxProperties);
}

function positionAdvancedSearchLayerSearchbox()
{
    var searchboxProperties = getAdvancedSearchLayerSearchboxProperties();
    var searchbox = $('advanced_search_layer_searchbox');
    
    searchbox.style.top = searchboxProperties.y + 'px';
    searchbox.style.left = searchboxProperties.x + 'px';
    searchbox.style.width = searchboxProperties.width + 'px';
    searchbox.style.height = searchboxProperties.height + 'px';
    
    getNextTag('form', searchbox.firstChild).style.top = Math.floor((searchbox.clientHeight - getNextTag('form', searchbox.firstChild).offsetHeight) / 2) + 'px';
}

function getWindowHeight()
{
    var result = 0;
    
    // !IE
    if (window.innerHeight != null)
        result = window.innerHeight
    // IE 6+
    else if (document.documentElement != null && document.documentElement.clientHeight != null)
        result = document.documentElement.clientHeight;
    else
        result = document.body.clientHeight;
    return (result);
}

function resizeImage(image)
{
    var blocksProperties = getAdvancedSearchLayerBlocksProperties();
	if (image.width >= (blocksProperties.width - 2) && image.width > image.height)
		image.setAttribute('width', blocksProperties.width - 2);
	else if (image.height >= (blocksProperties.height - 2) && image.height > image.width)
		image.setAttribute('height', blocksProperties.height - 2);
}

function initializeAdvancedSearchBlocks(datas)
{
    var advancedSearchLayerSearchboxProperties = getAdvancedSearchLayerSearchboxProperties();
    var blocksProperties = getAdvancedSearchLayerBlocksProperties();
    var blocks = new Array();
    
    if ($('advanced_search_layer').blocks != null)
    {
        for (i = 0; i < $('advanced_search_layer').blocks.length; i++)
        {
            $('advanced_search_layer').removeChild($('advanced_search_layer').blocks[i]);
        }
        $('advanced_search_layer').blocks = null;
        $('advanced_search_layer').datas = null;
        $('advanced_search_layer').style.width = $('page').clientWidth + 1;
        $('advanced_search_layer').style.width = $('page').clientWidth;
    }

    if (datas == null)
    	return;

    for (var y = 0, offset = 0; y < blocksProperties.numberByHeight && offset < datas.length; y++)
    {
        for (var x = 0; x < blocksProperties.numberByWidth && offset < datas.length; x++, offset++)
        {
            if (y >= advancedSearchLayerSearchboxProperties.blockTop &&
                y < (advancedSearchLayerSearchboxProperties.blockTop + blocksProperties.searchboxBlocksHeight) &&
                x >= advancedSearchLayerSearchboxProperties.blockLeft &&
                x < (advancedSearchLayerSearchboxProperties.blockLeft + blocksProperties.searchboxBlocksWidth))
                continue;
            var newElement = document.createElement('div');
            newElement.className = 'advanced_search_layer_block';
            newElement.style.left = (x * blocksProperties.width) + 'px';
            newElement.style.top = ((y * blocksProperties.height) + blocksProperties.marginTop) + 'px';
            newElement.style.width = blocksProperties.width + 'px';
            newElement.style.height = blocksProperties.height + 'px';
            $('advanced_search_layer').appendChild(newElement);
            
            var link = document.createElement('a');
            link.setAttribute('class', 'boutons');
            link.setAttribute('href', datas[offset].link);
            newElement.appendChild(link);
            
            var image = document.createElement('img');
            image.setAttribute('src', datas[offset].image_url);
            image.setAttribute('alt', datas[offset].title);
            image.setAttribute('title', datas[offset].link_title);
            image.setAttribute('border', '0');
            resizeImage(image);
            link.appendChild(image)
            centerElement(link, newElement, image);
            
            
            //newElement.innerHTML = '"'+ datas[offset] +'"';
            blocks.push(newElement);
        }
    }
    $('advanced_search_layer').blocks = blocks;
    $('advanced_search_layer').datas = datas;
    $('advanced_search_layer').style.width = $('page').clientWidth + 1;
    $('advanced_search_layer').style.width = $('page').clientWidth;
}

Fx.Morph = Fx.Styles.extend({
 
	start: function(className, modifs){

		var to = {};
 
		$each(document.styleSheets, function(style){
			var rules = style.rules || style.cssRules;
			$each(rules, function(rule){
				if (!rule.selectorText.test('\.' + className + '$')) return;
				Fx.CSS.Styles.each(function(style){
					if (!rule.style || !rule.style[style]) return;
					var ruleStyle = rule.style[style];
					to[style] = (style.test(/color/i) && ruleStyle.test(/^rgb/)) ? ruleStyle.rgbToHex() : ruleStyle;
					if (modifs && modifs[style])
					    to[style] = modifs[style];
				});
			});
		});
		return this.parent(to);
	}
 
});
 
Fx.CSS.Styles = ["backgroundColor", "backgroundPosition", "color", "width", "height", "left", "top", "bottom", "right", "fontSize", "letterSpacing", "lineHeight", "textIndent", "opacity"];
 
Fx.CSS.Styles.extend(Element.Styles.padding);
Fx.CSS.Styles.extend(Element.Styles.margin);
 
Element.Styles.border.each(function(border){
	['Width', 'Color'].each(function(property){
		Fx.CSS.Styles.push(border + property);
	});
});

function advancedSearchLayerSearchboxFormSubmit(event)
{
	new Event(event).stop();
	$(this);
	
	this.send({onFailure: function()
		{
			alert('script don\'t exists.');
		},
		onComplete: function()
		{
			var form = getNextTag('form', $('advanced_search_layer_searchbox').firstChild)
			var datas = Json.evaluate(this.response.text, true);

			if (getNextTag('a', form.firstChild) != null)
			{
				form.removeChild(getNextTag('br', form.firstChild));
				form.removeChild(getNextTag('a', form.firstChild));
				centerElement(form);
			}

			if (datas === false || datas == null)
			{
				initializeAdvancedSearchBlocks(null);
				return;
			}

			if (datas.length == 0)
			{
				var error = document.createElement('a');
				error.setAttribute('class', 'delete');
				error.innerHTML = 'Aucun r&eacute;sultat';
				
				form.insertBefore(error, getNextTag('input', form.firstChild));
				form.insertBefore(document.createElement('br'), getNextTag('input', form.firstChild));
				centerElement(form);
			}
			initializeAdvancedSearchBlocks(datas);
		}
	});
}

function morph_out(e)
{
    e = new Event(e).stop();
    $('advanced_search_link').myMorph.start('advanced_search_layer_hide', {width: $('page').clientWidth, left: $('page').getLeft()});
}

function morph_in(e)
{
    e = new Event(e).stop();
    positionAdvancedSearchLayerClose();
    positionAdvancedSearchLayerSearchbox();
    this.myMorph.start('advanced_search_layer_show', {height: getWindowHeight(), width: $('page').clientWidth, left: $('page').getLeft()});
}

function init()
{
    $('advanced_search_link').myMorph = new Fx.Morph('advanced_search_layer', {wait: false});
    $('advanced_search_link').addEvent('click', morph_in);
    $('advanced_search_layer_close').addEvent('click', morph_out);
    $('advanced_search_layer').style.left = $('page').getLeft() + 'px';
    $('advanced_search_layer').style.width = $('page').clientWidth + 'px';
    getNextTag('form', $('advanced_search_layer_searchbox').firstChild).onsubmit =advancedSearchLayerSearchboxFormSubmit;
    
    var Test = new Tips($$('.Tips'),{ fixed:true });
    
    var myGallery = new gallery($('myGallery'), {timed: true, showArrows: true, showCarousel: false, embedLinks: false});
    
    var accordion = new Accordion('h3.atStart', 'div.atStart', {
	opacity: false,
	alwaysHide: true,
	show: 0,
	display: 0,
	onActive: function(toggler, element){
	toggler.setStyle('color', '#F01662');
	},
	
	onBackground: function(toggler, element){
	toggler.setStyle('color', '#222');
	}
	}, $('accordion'));
}

window.addEvent('domready', init);
