/*------------------------------------------------------------------------------
    JS Document (https://developer.mozilla.org/en/JavaScript)

    project:    Le mans
    created:    2009-03-26
    author:     yvevan, sanjus

    summary:    CONSTANTES
                UTILITIES
                WINDOW.ONLOAD
                CAROUSEL
				TABS
				ACCORDEON
----------------------------------------------------------------------------- */

/*  =CONSTANTES
----------------------------------------------------------------------------- */
var d = document;
var w = window;
var debug = null;
window.config = {
    debug : false,
    carousel : {
        conf : {
            leftArrowSelector  : 'arrow-previous',
            rightArrowSelector : 'arrow-next',
            leftText : '',
            rightText : ''
        },
        classname : 'carousel',
        disable : 'arrow-previous-disabled'
    },
	popin1 : {
        target : '.open',
        name : {
            popin   : 'popin',
            cache   : 'cache',
            close   : 'close',
            content : 'pop_content'//,
            // loadimg : 'load-indicator'
        },
        behaviours : {
            closeClick : true,
            hash   : 'pop',
            close  : 'Fermer',				// texte du bouton de fermeture (ou code html)
            anim   : true,					
            resize : true//,             	// animation du masque (fadeIn/Out)
            // loadingImage : {
            //     src : 'img/data/ajax-loader.gif',
            //     alt : 'Loading ...'
            // }
        },
        style : {
            marginMax : 50,           		// marge autour de la popin quand elle est plus grande que la fenetre et redimensionnee
            opacity   : 0.70,         		// opacity du masque
            maxWidth  : 250,          		// width d'ecran max pour laquelle la popin est desactivee (mobiles))
            maxHeight : 250           		// height d'ecran max pour laquelle la popin est desactivee (mobiles)
        },
        callback : {                  		// events
            onload   : callLoad,
            onreload : callReload
        }
    },
	focus : "focus",
    tabs  : {
               tabs1 : {
                    id          : '#weather-box',
                    zones       : '.tabs1',
                    menu        : '#tabsMenu1',
                    active      : 'on',
					inactive    : 'disabled',
                    container   : '#tabs1',
                    linkParent  : 'li',
                    scrollToTop : true
                },
                tabs2 : {
                    id          : '#tabs2Container',
                    zones       : '.tabs2',
                    menu        : '#tabsMenu2',
                    active      : 'on',
					inactive    : 'disabled',
                    container   : '#tabs2',
                    linkParent  : 'li',
                    scrollToTop : true
        	}
    	}
};

function callLoad() {
	formSubmit();
    /*log('onload');
    if(jQuery('#myContent').length) {
        swfobject.embedSWF('swf/test.swf', 'myContent', '300', '120', '9.0.0', 'expressInstall.swf');
    }*/

}
function callUnload() {
    //log('onunload');
}

function callBeforeLoad() {
    //log('onbeforeload');
}

function callReload() {
	formSubmit()
    /*log('reload');
    if(jQuery('#myContent').length) {
        swfobject.embedSWF('swf/test.swf', 'myContent', '300', '120', '9.0.0', 'expressInstall.swf');
    }*/
}



/*  =UTILITIES
----------------------------------------------------------------------------- */
/* getElementsByClassName when not supported */
var matchAll = function() {
    var node = arguments[1] || document;
    var elms = node.getElementsByTagName('*');
    var className = arguments[0];
    if (d.getElementsByClassName) {
        return node.getElementsByClassName(className);
    }
    else {
        var regExp = new RegExp('\\b'+className+'\\b');
        var array = [];
        for (var i = 0; i < elms.length; i++) {
            var current = elms[i];
            if (current.className.match(regExp)) {
                array.push(current);
            }
        }
        return array;
    }
};

/* logs into a textarea for IE and in the console for others */
var debuger = function() {
    if (window.config.debug && !debug && typeof console == 'undefined') {
        var parent = d.getElementsByTagName('div')[0];
        var body   = d.getElementsByTagName('body')[0];
        var debug  = d.createElement('textarea');
        debug.setAttribute('rows', 10);
        debug.setAttribute('cols', 80);
        debug.setAttribute('name', 'debug');
        body.insertBefore(debug, parent);
        window.debug = debug;
    }
    else if (window.config.debug && console) {
        log('Debug mode : on');        
    }
};
var log = function(x) {
    if (typeof console != 'undefined')
        console.log(x);
    else if (debug) {
        debug.value += x + '\n';
        debug.scrollTop = debug.scrollHeight;
    }
};


/*  =WINDOW.ONLOAD
----------------------------------------------------------------------------- */
jQuery(document).ready(function() {
    
    // Functions
    debuger();              						// build a log console for IE
    carousel();             						// set a carousel for photos
    printMe();									 	// print the page
	//calendarNav();									// calendar buttons
	formSubmit();
	searchToggle();
	
	var tabs1  = w.config.tabs.tabs1;
   	tabs(tabs1);                                   	// launches tabs1
	var tabs2  = w.config.tabs.tabs2;
    tabs(tabs2);                                   	// launches tabs2
	
	var popinConf1 = w.config.popin1;
    popin1 = new popin(popinConf1);
	
    // Classes
    
    
    // jQuery crappy stuff


    if (jQuery.browser.msie && jQuery.browser.version == 6) {
        // IE 6 FUNCTIONS ONLY
        
    }

});


/*  =CAROUSEL
----------------------------------------------------------------------------- */
function carousel() {
    // we had a strange behaviour on Safari, so we fixed it with a ugly Timeout
    setTimeout(function() {
        var config = w.config.carousel.conf;
        var name   = w.config.carousel.classname;
        var disable = w.config.carousel.disable;
        jQuery('.'+name).jac(config);
        jQuery('.'+config.leftArrowSelector).addClass(disable);
    },0);
}


/* TABS
------------------------------------------------------------------------------*/

function tabs(config) {
    var elements   = null;
    var active     = config.active;
	var inactive     = config.inactive;
    var linkParent = config.linkParent;
    var scroll     = config.scrollToTop;
    var id         = jQuery(config.id);
    var zones      = id.find(config.zones);
    var menu       = id.find(config.menu);
    var container  = id.find(config.container);
    function launch() {
        var setStyles = function() {
            var containerHeight = container.css("height");
            var focus           = jQuery("." + w.config.focus).length;
            zones.css('height', containerHeight);
            zones.css('overflow','auto');
            container.css('overflow','hidden');
			zones.addClass(inactive)
            //zones.hide();
            if(!focus) {
                id.addClass(w.config.focus);
            }
        }();
        var handleBehaviours = function() {
            var idExists = id.find(w.location.hash);
            var isActive   = menu.find('.' + active);
            var zoneActive = jQuery(isActive.find('a').attr('href'));
            if (w.location.hash && idExists.length) {
                menu.find(linkParent).removeClass(active);
                //idExists.show();
				idExists.removeClass(inactive);
                idExists.attr("tabindex","-1");
                idExists.focus();
                idExists.removeAttr("tabindex");
                jQuery('a[href='+ w.location.hash +']').parents(linkParent).addClass(active);
                if (scroll) {
                    w.scrollTo(0,0);
                }
            }
            else if (isActive.length) {
                //zoneActive.show();
				zoneActive.removeClass(inactive);
            }
            else {
				zones.eq(0).removeClass(inactive);
                //zones.eq(0).show();
                menu.find(linkParent).eq(0).addClass(active);
            }
        }();
        var handleEvents = function() {
            var tabs = menu.find(linkParent).find('a');
            tabs.click(function(){
                jQuery("." + w.config.focus).removeClass(w.config.focus);
                id.addClass(w.config.focus);
                var zoneActive = jQuery(jQuery(this).attr("href"));
                menu.find(linkParent).removeClass(active);
                jQuery(this).parents(linkParent).addClass(active);
				zones.addClass(inactive)
                //zones.hide();
                //zoneActive.show();
				zoneActive.removeClass(inactive);
                zoneActive.attr("tabindex","-1");
                zoneActive.focus();
                zoneActive.removeAttr("tabindex");
                return false;
            });
            tabs.focus(function(e) {
                jQuery("." + w.config.focus).removeClass(w.config.focus);
                id.addClass(w.config.focus);
            });
        }();
        var handleKeyboard = function() {
            jQuery(d).keyup(function(e) {
                var isActive = jQuery(config.id + '.' + w.config.focus).find(config.menu).find('.' + active);
                if (isActive.length) {
                    var zoneActive = jQuery(isActive.find('a').attr('href'));
                    if (e.keyCode == 39 || e.keyCode == 37) {
                        var position  = null;
                        var afterZone = null;
                        var action = function(position,move) {
                             if (isActive[move]().length) {
                                afterZone = jQuery(isActive[move]().children("a").attr("href"));
                                isActive[move]().addClass(active);
                            }
                            else {
                                afterZone = zones.eq(position);
                                menu.children(linkParent).eq(position).addClass(active);
                            }
                        };
						zones.addClass(inactive)
                        //zones.hide();
                        switch(e.keyCode)
                        {
                            case 39: // right arrow
                                var position = 0;
                                action(position,"next")
                                break;
                            case 37: //  left arrow 
                                var position = zones.length - 1;
                                action(position,"prev")
                                break;                        
                        }
                        isActive.removeClass(active);
                        //afterZone.show();
						afterZone.removeClass(inactive);
                        afterZone.attr("tabindex","-1");
                        afterZone.focus();
                        afterZone.removeAttr("tabindex");
                    }
                }
            });
        }();
    }
    var init = function() {
        function verifyHTMLStruct() {
            var error   = false;
            var message = '\n## Erreur(s) sur `' + config.id + '`\n\n';
            if (zones.length != menu.find('a').length) {
                if (error == false && w.config.debug == true) {
                    log(message);
                }
                error = true;
                if (w.config.debug == true) {
                    log(' - `' + config.id + '` ne comporte pas autant d\'onglets que de zones ; ');
                }
            }
            if (menu.find('.' + active).length > 1) {
                if (error == false && w.config.debug == true) {
                    log(message);
                }
                error = true;
                if (w.config.debug == true) {
                    log(' - `' + config.id + '` comporte plus d\'un onglet actif ; ');
                }
            }
            for(var i=0 ; i<zones.length ; i++) {
                if(jQuery((menu.find('a').eq(i).attr("href"))).length != 1) {
                    if (error == false && w.config.debug == true) {
                        log(message);
                    }
                    error = true;
                    if (w.config.debug == true) {
                        log(' - `' + config.id + '` n\'associe pas correctement les onglets et les zones ; ');
                    }
                }
            }
            if(error) {
                menu.find(linkParent).removeClass(active);
                if (w.config.debug == true) {
                    log('\nMerci de corriger le HTML et/ou le JS sur `' + config.id + '`.');
                }
                return(false);
            }
            else {
                return(true);
            }
        }
        if (verifyHTMLStruct()) {
            launch();
        }
    }(); 
}

/*  =ACCORDEON
----------------------------------------------------------------------------- */
<!--
    jQuery(document).ready( function () {
        // On cache les sous-menus
        // sauf celui qui porte la classe "open_at_load" :
        jQuery("ul.subMenu:not('.open_at_load')").hide();
        // On selectionne tous les items de liste portant la classe "toggleSubMenu"
    
        // et on remplace l'element span qu'ils contiennent par un lien :
        jQuery("li.toggleSubMenu span").each( function () {
            // On stocke le contenu du span :
            var TexteSpan = jQuery(this).text();
            jQuery(this).replaceWith('<a href="" title="Afficher le sous-menu">' + TexteSpan + '</a>') ;
        } ) ;
    
        // On modifie l'evenement "click" sur les liens dans les items de liste
        // qui portent la classe "toggleSubMenu" :
        jQuery("li.toggleSubMenu > a").click( function () {
            // Si le sous-menu etait deja ouvert, on le referme :
            if (jQuery(this).next("ul.subMenu:visible").length != 0) {
                jQuery(this).next("ul.subMenu").slideUp("normal", function () { jQuery(this).parent().removeClass("open") } );
            }
            // Si le sous-menu est cache, on ferme les autres et on l'affiche :
            else {
                jQuery("ul.subMenu").slideUp("normal", function () { jQuery(this).parent().removeClass("open") } );
                jQuery(this).next("ul.subMenu").slideDown("normal", function () { jQuery(this).parent().addClass("open") } );
            }
            // On emp�che le navigateur de suivre le lien :
            return false;
        });
        if (!jQuery('#mailformcodepostal').hasClass('tiny')) {
        	jQuery('#mailformcodepostal').addClass('tiny');
        }
    
    } ) ;
    // -->

/*  =PRINT
----------------------------------------------------------------------------- */
var printMe = function(){

	if(document.getElementById('printLink')) document.getElementById('printLink').onclick = function(){
		window.print();
		this.blur();
		return false;
	}
	
}

/*  =CALENDAR
----------------------------------------------------------------------------- */

var calendarNav = function(){
	
	var myLinks = jQuery('#agendaCal th a');
	var myMonthes = jQuery('#agendaCal div');

	myLinks.click(function(){
		
		myMonthes.hide();
		document.getElementById(jQuery(this).attr('href').split('#')[1]).style.display = 'block';
		return false;
		
	});
	
}

/* =POPIN
------------------------------------------------------------------------------*/
var popinMemorize = {
    activeLink : null
};
function popin(config) {
    var targetLink = config.target;
    var id_popin   = config.name.popin;
    var id_cache   = config.name.cache;
    var id_close   = config.name.close;
    var id_content = config.name.content;
    var marginMax  = config.style.marginMax;
    var marginIE6  = config.style.marginIE6 || 50;          // correctif IE6
    var opacity    = config.style.opacity;
    var maxWidth   = config.style.maxWidth;
    var maxHeight  = config.style.maxHeight;
    var pop_hash   = config.behaviours.hash;
    var closeStr   = config.behaviours.close;
    var innerLoad  = config.behaviours.innerLoad || true;
    var anim       = config.behaviours.anim   || true;
    var resize     = config.behaviours.resize || false;     // EXPERIMENTAL / quand on change la taille de la fenetre et que la popin devient trop grande
    var anchor     = config.behaviours.anchor || false;     // EXPERIMENTAL / gestion des ancres
    var closeClick = config.behaviours.closeClick || false;
    // var loadImage  = new Image();
    // if (config.behaviours.loadingImage) {
    //     loadImage.src = config.behaviours.loadingImage.src || null;
    //     loadImage.alt = config.behaviours.loadingImage.alt || null;
    //     loadImage.id  = config.name.loadimg || null;
    // }
    if (config.callback) {
        var callOnunload = config.callback.onunload || null;
        var callOnload   = config.callback.onload   || null;
        var callReload   = config.callback.onreload || null;
        var callOnBeforeLoad = config.callback.onbeforeload  || null;
    }
    
    var popin      = null;
    var popinCache = null;
    var body = jQuery('body');
    
    var url, parametres, paramets, params, iparam = null; // crados
    
    var globs = {
        callerElm : null,
        popinLoaded : 0
    };
    
    var utils = {
        getWindowDimensions : function(dimension) {
            var dimension = dimension.substr(0, 1).toUpperCase() + dimension.substr(1);
            var result = 0;
            if (typeof(w['inner'+dimension]) == "number") {
                // Standard Browsers
                var result = w['inner'+dimension];
            }
            else if (d.documentElement && d.documentElement['client'+dimension]) {
                // IE 6+ in standard mode
                var result = d.documentElement['client'+dimension];
            }
            return result;
        },
        fixDimensions : function(dimension, direction) {
            if (utils.getWindowDimensions(dimension) <  popin[dimension]()) {
                popin.css(dimension,(utils.getWindowDimensions(dimension) - marginMax) + "px");
                popin.css("margin-"+direction,"-" + Math.round((utils.getWindowDimensions(dimension) - marginMax)/2) + "px");
            }
        },
        getScrollPositions : function(axis) {
            var axis = axis.toUpperCase();
            var axis2 = (axis == 'Y') ? 'Top' : 'Left';
            var result = 0;
            if (typeof w['page'+axis+'Offset'] == "number") {
                result = w['page'+axis+'Offset'];
            }
            else if (d.body && d.body['scroll'+axis2]) {
                result = d.body['scroll'+axis2];
            }
            else if (d.documentElement && d.documentElement['scroll'+axis2]) {
                result = d.documentElement['scroll'+axis2];
            }
            return result;
        },
        setLinks : function(elm, inner) {
            // update this to a resolution check, rather than to a window size check ?
            if (!((utils.getWindowDimensions('width') < maxWidth)
            || (utils.getWindowDimensions('height') < maxHeight))) {
                if (!popin && typeof callOnBeforeLoad == 'function') {
                    callOnBeforeLoad();
                }
                var options = {
                    inner : inner
                };
                openPopin(jQuery(elm), options);
            }
        }
    };
    
    function openPopin(elm, options) {
        var focusElm = null;  // a DOM element where the focus is applied on close
        var inner    = false; // if true permits inner reloads
        if (options) {
            if (options.focusElm) {
                focusElm = options.focusElm;
            }
            if (options.inner) {
                inner = true;
            }
        }

        url = null;

        var setUrl = function(){
            if (typeof elm == 'string') {
                popinMemorize.activeLink = jQuery(focusElm) || body;
                url = elm;
				globs.callerElm = jQuery(popin).find('form:first');
            }
            else if (typeof elm == 'object') {
                if (elm[0] && elm[0].action) { // if elm is in DOM and has action
                    if (!document.getElementById(id_popin)) {
                        popinMemorize.activeLink = elm;
                    }
                    url = elm.attr('action');
                    globs.callerElm = elm;
                }
                else if (elm[0] && elm[0].href) { // if elm is in DOM and has href
                    if (!document.getElementById(id_popin)) {
                        popinMemorize.activeLink = elm;
                    }
                    url = elm.attr('href');
                    globs.callerElm = elm;
                }
                else {
                    throw('Popin : openPopin() Argument Type Error');
                    return;
                }
            }
            else {
                throw('Popin : openPopin() Argument Type Error');
                return;
            }
        }();
                
        // total crados
        parametres = (url.slice(url.indexOf("?") + 1)).split("&");
        paramets   = [];
        params     = [];
        iparam     = 0;
        
        var handleWindowLocation = function() {
            // crados
            for (var i = 0, n = parametres.length; i < n; i++) {
                paramets[iparam] = parametres[i].split("=")[0];
                iparam++;
                paramets[iparam] = parametres[i].split("=")[1];
                iparam++;
            }
            for (var i = 0, n = paramets.length; i < n; i++) {
                var chaine = paramets[i];
                i++;
                params[chaine] = paramets[i];
            }
        }();
        
        var setBehaviours = function() {
            if (typeof inner != 'undefined' && inner == true) {
                var oContent = jQuery('#'+id_content);
                oContent.empty();
                // oContent.append(loadImage); // breaks focus on Jaws
                // oContent.show(); // breaks focus on Jaws
                return;
            }
            if (popin && popinCache) {
                closePopin(true);
            }
        }();
        
        var buildHTML = function() {
            if (typeof inner != 'undefined' && inner == true) {
                return;
            }
            body.append('<div id="' + id_cache + '"></div><div id="' + id_popin + '"></div>');
            popinCache = jQuery('#' + id_cache);
            popin = jQuery("#" + id_popin);
            if (typeof callOnunload == 'function') {
                popin[0].setUnload = callOnunload;
            }
        }();
        
        var setPreStyles = function() {
            if (typeof inner != 'undefined' && inner == true) {
                return;
            }
            popinCache.css("opacity", opacity);
            
            if (anim) {
                popinCache.fadeIn();
            }
            else {
                popinCache.show();
            }
            
            // IE 6 hacks
            if ((jQuery.browser.msie) && (jQuery.browser.version < 7)) {
                // hide selects
                jQuery('select').css('visibility', 'hidden');
                popin.find('select').css('visibility', 'visible');
                
                // position:fixed
                popin.css('position','absolute');
                popinCache.css('position','absolute');
                popinCache.css('height',(body.height() + marginIE6) + 'px');
                if (body.height() < utils.getWindowDimensions('height')) {
                    popinCache.css('height',utils.getWindowDimensions('height') + 'px');
                }
            }
            
        }();
        
        var loadContent = function() {
			if (globs.callerElm && globs.callerElm.attr('action')) {
				var sentData = '';
                var getFormData = function() {
                    globs.callerElm.find('input, select, textarea').each(function(){
                        var current = jQuery(this);
                        var val  = encodeURIComponent(current.val());
                        var name = current.attr('name');
                        sentData += name+"="+val+"&";
                    });
                }();
                jQuery.ajax({
                    type : 'POST',
                    url  : url,
                    data : sentData,
                    success : setPopin
                });
            }
            else {
                var param  = (url.indexOf("?") != -1) ? '&' : '?';
                var random = 'popincache='+Math.floor(1000000000*Math.random());
                popin.load(url+param+random+" #" + id_content, setPopin);
            }
        }();
    
    } // end openPopin
    
    function setPopin() {
        var responseText = arguments[0];
        var textStatus   = arguments[1];
        var XHR = arguments[2];
        var closeHTML = '<ul id="' + id_close + '"><li><a href="#">' + closeStr +'</a></li></ul>';
        
        var setDimensions = function() {
            if (globs.popinLoaded == 1) {
                popin.animate({
                    width : params["width"] + "px",
                    marginLeft : "-" + Math.round(((params["width"])/2)) + "px",
                    height : params["height"] + "px",
                    marginTop : "-" + Math.round(((params["height"])/2)) + "px"
                });
            }
            else {
                if (typeof params["width"] != 'undefined') {
                    popin.css("width",params["width"] + "px");
                    popin.css("margin-left","-" + Math.round(((params["width"])/2)) + "px");
                }
                if (typeof params["height"] != 'undefined') {
                    popin.css("height",params["height"] + "px");
                    popin.css("margin-top","-" + Math.round(((params["height"])/2)) + "px");
                }
            }
            utils.fixDimensions('width','left');
            utils.fixDimensions('height','top');
        }();
        
        var verifyBehaviours = function() {
            if (resize) {
                jQuery(window).resize(function(){
                    utils.fixDimensions('width','left');
                    utils.fixDimensions('height','top');
                });
            }
            if (anchor) {
                var position_x = utils.getScrollPositions("x");
                var position_y = utils.getScrollPositions("y");
                w.location.hash = pop_hash + "=" + url;
                window.scrollTo(position_x,position_y);
            }
            
            if ((jQuery.browser.msie) && (jQuery.browser.version < 7)) {
                if (utils.getScrollPositions("y") != 0) {
                    popin.css("top",utils.getScrollPositions("y") + (utils.getWindowDimensions("height")/2));
                }
            }
        }();
        
        var handleVisitedLinks = function() {
            if (typeof inner != 'undefined' && inner == true) {
                return;
            }
            // only works on Firefox/Gecko
            popin.append('<iframe src="' + url + '" id="popin-iframe"></iframe>');
            popin.children("#popin-iframe").css("display","none");
        }();
        
        
        var handleEvents = function() {
            if (globs.callerElm && globs.callerElm.attr('action')) {
                var content = jQuery(responseText).find('#' + id_content);
                content.clone(true).appendTo(popin);
                popin.children('#' + id_content).append(closeHTML);
            }
            else {
                jQuery('#' + id_content).append(closeHTML);
            }
            
            jQuery('#' + id_close +' a').bind('click',function(){
                closePopin();
                return false;
            });
            
            body.bind('keyup',function(e) {
                if (e.keyCode == 27 && popin) {
                    closePopin();
                    jQuery(this).unbind('keyup');
                }
            });
            
            if (closeClick) {
                popinCache.bind('click',function(){
                    closePopin();
                    return false;
                });
            }
            
            if (innerLoad) {
                jQuery(popin).find(targetLink).not('form').click(function(){
                    utils.setLinks(this, true);
                    return false;
                });
                jQuery(popin).find('form'+targetLink).submit(function() {
                    utils.setLinks(this, true);
                    return false;
                });
            }
            
            if (globs.popinLoaded > 0 && typeof callReload == "function") {
                callReload();
            }
            else if (typeof callOnload == "function") {
                callOnload();
            }

        }();
        
        var handleStatus = function() {
            if (typeof inner != 'undefined' && inner == true) {
                return;
            }
            if (textStatus != 'success') {
                popin.append('<div id="' + id_content + '">'+
                                '<p>Message : '+ textStatus + '</p>' +
                                '<p>ReadyState : '+ XHR.readyState + '</p>' +
                                '<p>Status : '+ XHR.status + '</p>' +
                             '</div>'+closeHTML);
                jQuery('#' + id_close +' a').bind('click',function(){
                    closePopin();
                    return false;
                });
            }
            popin.show();
            popin.attr("tabindex","-1");
            popin.focus();
                        
            globs.popinLoaded = 1;
        }();
        
        
    } // end setPopin
        
    function closePopin(onload, options) {
        // we need this if we use the external interface
        popinCache = popinCache || jQuery('#' + id_cache);
        popin = popin || jQuery('#' + id_popin);
        var tmpPopin = document.getElementById(id_popin);
        
        globs.popinLoaded = 0;
        
        var handleEvents = function() {
            if (!onload && typeof tmpPopin.setUnload == 'function') {
                tmpPopin.setUnload();
                tmpPopin.setUnload = null;
                delete tmpPopin;
            }
            if (anchor) {
                var position_x = utils.getScrollPositions('x');
                var position_y = utils.getScrollPositions('y');
                w.location.hash = '#';
                w.scrollTo(position_x,position_y);
            }
        }();

        var setFocusBack = function() {
            if (options) {
                if (options.focusElm) {
                    popinMemorize.activeLink = jQuery(options.focusElm);
                }
            }
        
            if (!onload && popinMemorize.activeLink) {
                popinMemorize.activeLink.attr('tabindex','-1');
                popinMemorize.activeLink.focus();
                popinMemorize.activeLink.removeAttr('tabindex');
                popinMemorize.activeLink = null;
            }
        }();

        var removePopin = function() {
            if (anim) {
                var tmpCache = popinCache;
                popinCache.fadeOut(function(){
                    tmpCache.remove();
                    delete tmpCache;
                });
            }
            else {
                popinCache.remove();
            }
            popin.remove();
        }();
        
        var resetVars = function() {
            popin = null;
            popinCache = null;
        
            url, parametres, paramets, params, iparam = null; // crados
			if (!onload) globs.callerElm = null;
        }();
        
        if (jQuery.browser.msie && jQuery.browser.version < 7) {
            jQuery('select').css('visibility','visible');
        }
    } // end closePopin
    
    var init = function() {
        if (anchor && w.location.hash
        && (w.location.hash.indexOf(pop_hash + "=") != -1)) {
            var wHash = w.location.hash;
            var options = {};
            openPopin(wHash.slice(wHash.indexOf(pop_hash + "=") + pop_hash.length + 1) ,options);
        }
        
        if (targetLink) { // if null just works on external calls
            jQuery(targetLink).not('form').click(function() {
                utils.setLinks(this, false);
                return false;
            });
            jQuery('form'+targetLink).submit(function() {
                utils.setLinks(this, false);
                return false;
            });
        }
    }();
    
    return {
        openPopin : function(url, focusElm) {
            var options = {
                focusElm : focusElm
            };
            openPopin(url, options);
            return false;
        },
        closePopin : function(focusElm) {
            var options = {
                focusElm : focusElm
            };
            closePopin(null, options);
            return false;
        }
    };
}


/*  =FORM CHECK ON SUBMIT
----------------------------------------------------------------------------- */
var formSubmit = function(){
	
	jQuery('form').submit(function(){
		
		var hasError = false;
		var myAction = jQuery(this).attr('action');
		var myId = jQuery(this).attr('id');
		
		jQuery('p').removeClass('error');
		// text inputs
	
		jQuery('#'+myId+' .mandatory').each(function(i){
			
			
			var myVal = jQuery(this).val();
			
			//take the id of every element
			
			//
			if ((myVal == '')||(myVal == jQuery(this).attr('title'))){
				
				jQuery(this).parent('p').addClass('error');
				hasError = true;
				
			}
			
			// email
			
			else if(jQuery(this).hasClass('mandatoryEmail')){
				
				var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
				
				if (!emailReg.test(myVal)){ 
					
					jQuery(this).parent('p').addClass('error'); 
					hasError = true;
					
				}
			}
			
			// emails collection
			
			else if(jQuery(this).hasClass('mandatoryEmailCollection')){
				
				var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
				var myValCollection = myVal.split(',');
				
				for (x in myValCollection){
					
					myValCollection[x] = myValCollection[x].replace(/^\s+/g,'').replace(/\s+$/g,'').replace(/^\n+/g,'').replace(/\n+$/g,'');	// clean spaces

					if (!emailReg.test(myValCollection[x])){ 
					
						jQuery(this).parent('p').addClass('error'); 
						hasError = true;
						
					}		
				}
			}
			
			// format date
			
			else if(jQuery(this).hasClass('mandatoryDate')){
				
				var dateReg = /^\d\d\/\d\d\/\d\d\d\d$/;
				
				if (!dateReg.test(myVal)){ 
					
					jQuery(this).parent('p').addClass('error'); 
					hasError = true;
					
				}
			}
		});
		
		// radio buttons
		
		var myRadioCollection = [];
		
		jQuery('.mandatoryRadio').each(function(i){
			
			var marked = false;
			
			for (j=0; j<=myRadioCollection.length; j++){
				
				if (myRadioCollection[j] == jQuery(this).attr('name')) marked = true;
				
			}
			
			if (marked == false) myRadioCollection.push(jQuery(this).attr('name'));

		});
		
		for (j=0; j<=myRadioCollection.length; j++){
			
			var checked = false;
			
			jQuery('.mandatoryRadio[name='+myRadioCollection[j]+']').each(function(j){
				
				if (jQuery(this).attr('checked') == true) checked = true;
				
			});
			
			if (checked == false) jQuery('.mandatoryRadio[name='+myRadioCollection[j]+']').parent().parent('p').addClass('error');
			
		}
		
		// checkboxes
		
		jQuery('.mandatoryCheck').each(function(i){
			
			if (jQuery(this).attr('checked') == false) jQuery(this).parent('p').addClass('error');
			
		});
				
		if (hasError) {
			
			jQuery('#'+myId+' #responseArea').fadeIn();
			jQuery('#'+myId+' #responseArea2').fadeIn();
			return false;
		}
		
		else{
			
			// submit - put ajax stuff here if needed
			
			// for the forms inside a popin
			if (myId == 'insidePopinForm'){
				popin1.openPopin(myAction)
			}
		}
	});
}

/*  =FORM CHECK ON SUBMIT
----------------------------------------------------------------------------- */
var searchToggle = function(){
	var checked = false;
	
	if (jQuery('.advancedSearch h3').hasClass('show')) {
		jQuery('#advancedSearchCore').show();
		jQuery('.advancedSearch h3').addClass('on');
		jQuery('.advancedSearch h3').removeClass('show');
		
		checked = true;
	} else {
		jQuery('#advancedSearchCore').hide();
		jQuery('.advancedSearch h3').removeClass('on');
	}
	
	
	jQuery('.advancedSearch h3').toggle(
		
		function () {	
			jQuery('.advancedSearch h3').addClass('on');
			jQuery("#advancedSearchCore").show("slow");	
			jQuery("#simpleSearch").attr('value', 0);		
		},
		function () {
			jQuery('.advancedSearch h3').removeClass('on');
			jQuery("#advancedSearchCore").hide("slow");
			jQuery("#simpleSearch").attr('value', 1);
		}
		
	);

}
