    /*------------------------------------------------------------------------------
    JS Document

    project:    majx JavaScript Library http://code.google.com/p/majx-js/
    license:    New BSD License http://www.opensource.org/licenses/bsd-license.php
    author:     Copyright (c) 2009
                Yves Van Goethem and Vincent Valentin
                All rights reserved.

    module:     customizable popins (modal boxes)
    version:    1.1
    summary:    CONFIG
                FUNCTIONS
                DOM.READY
                POPIN
----------------------------------------------------------------------------- */
    
/* =MAJX_CORE (http://code.google.com/p/majx-js/)
----------------------------------------------------------------------------- */
(function(){if(typeof majx=="undefined"){majx={};majx.init=function(){if(!majx.config){majx.config={};}}();}}());majx.set=function(){var e=arguments[0]||{};var b=null;var d=arguments.length;var c=1;if(d==c){e=majx.config;--c;}for(;c<d;c++){if((b=arguments[c])!=null){for(var a in b){var f=e[a];var g=b[a];if(e===g){continue;}else{if(g!==undefined){e[a]=g;}}}}}majx.config=e;};

	
/* =CONFIG
------------------------------------------------------------------------------*/
majx.set({
    popin1 : {
        target : '.popin',              // target links with this class (CSS 3 Selectors)
        behaviours : {
            close  : '<button type="button"><img src="/extension/poste_immo/design/poste_immo/images/skin/bt-popin-close.png" alt="fermer la fenêtre" /></button>', // close button, you can include HTML code
            loadingImage : {
                src : '/extension/poste_immo/design/poste_immo/images/data/ajax-loader.gif',
                alt : 'Chargement en cours ...',
                id  : 'pop-loading'
            }
        }
    }
});

/* =POPIN
------------------------------------------------------------------------------*/
majx.popin = function(config) {
    
    this.about = {
        version: 1.1,
        memorize : {
            activeLink : null
        }
    };
    
    var memorize = this.memorize = this.about.memorize;
    var w = window;
    var d = document;

    if (!config.name) {
        config.name = {};
    }
    if (!config.style) {
        config.style = {};
    }
    if (!config.behaviours) {
        config.behaviours = {};
    }
    if (!config.callback) {
        config.callback = {};
    }

    var targetLink = config.target;

    var id_popin   = config.name.popin   || 'popin';
    var id_cache   = config.name.cache   || 'cache';
    var id_close   = config.name.close   || 'close';
    var id_content = config.name.content || 'pop-content';

    var marginMax  = config.style.marginMax || 50;          // popin margin
    var marginIE6  = config.style.marginIE6 || 50;          // IE 6 fix
    var opacity    = config.style.opacity   || 0.5;
    var maxWidth   = config.style.maxWidth  || 250;
    var maxHeight  = config.style.maxHeight || 250;

    var pop_hash   = config.behaviours.hash || 'pop';
    var innerLoad  = config.behaviours.innerLoad || true;
    var anim       = config.behaviours.anim   || true;
    var resize     = config.behaviours.resize || false;     // EXPERIMENTAL / handling popin resize
    var anchor     = config.behaviours.anchor || false;     // EXPERIMENTAL / handling location hash
    var closeClick = config.behaviours.closeClick || false;

    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 statusCodes = config.statusCodes;

    var loadImage = 'Loading ...';
    if (config.behaviours.loadingImage) {
        loadImage = new Image();
        // should we include an image in base64 as fallback for modern browsers ?
        loadImage.src = config.behaviours.loadingImage.src || null;
        loadImage.alt = config.behaviours.loadingImage.alt || 'Loading ...';
        loadImage.id = config.behaviours.loadingImage.id;
    }
    loadImage = jQuery(loadImage);
    
    // jQuery Objects
    var popin      = null;
    var popinCache = null;
    var body    = jQuery('body');
    var jWindow = jQuery(window, document.body);
    
    // variables for hash handling
    var url, parametres, paramets, params, iparam = null; // ugly!!!
    
    var globs = {
        callerElm : null,
        popinLoaded : 0,
        closeHTML : '<span id="'+id_close+'">'+config.behaviours.close+'</span>',
        xhr1 : null,
        xhr2 : null,
        resizeMem : [0,0],
        dontPreventDefault : false
    };
    
    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
                result = w['inner'+dimension] - marginMax;
            }
            else if (d.documentElement && d.documentElement['client'+dimension]) {
                // IE 6+ in standard mode
                result = d.documentElement['client'+dimension] - marginMax;
            }
            return result;
        },
        fixDimensions : function(speed, auto, callback) {
            if (!popin) {
                return;
            }
            
            if (typeof params['width'] == 'undefined') {
                params['width'] = 800;
            }
            if (typeof params['height'] == 'undefined') {
                params['height'] = 450;
            }
            
            if (auto && params['width'] == 'auto') {
                params['width']  = auto[0].scrollWidth;
            }

            if (auto && params['height'] == 'auto') {
                params['height'] = auto[0].scrollHeight;
            }
            
            if (utils.getWindowDimensions('height') < params['height']) {
                params['height'] = utils.getWindowDimensions('height');
            }
            // else if ((utils.getWindowDimensions('height') > parseInt(popin.css('height'),10)) && (parseInt(popin.css('height'),10) < globs.resizeMem[1])) {
            //     params['height'] = utils.getWindowDimensions('height');
            //     if (params['height'] > globs.resizeMem[1]) {
            //         params['height'] = globs.resizeMem[1];
            //     }
            // }
            if (utils.getWindowDimensions('width') < params['width']) {
                params['width'] = utils.getWindowDimensions('width');
            }
            // else if ((utils.getWindowDimensions('width') > parseInt(popin.css('width'),10)) && (parseInt(popin.css('width'),10) < globs.resizeMem[0])) {
            //     params['width'] = utils.getWindowDimensions('width');
            //     if (params['width'] > globs.resizeMem[0]) {
            //         params['width'] = globs.resizeMem[0];
            //     }
            // }

            // if (!globs.resizeMem[0]) {
            //     globs.resizeMem = [params['width'],params['height']];
            // }
            
            if (!isNaN(params['height']) && !isNaN(params['width'])) {
                popin.animate({
                    width : params['width'] + 'px',
                    marginLeft : '-' + Math.round(((params['width'])/2)) + 'px',
                    height : params['height'] + 'px',
                    marginTop : '-' + Math.round(((params['height'])/2)) + 'px'
                }, speed, callback);
            }
            else if (callback) {
                callback;
            }
        },
        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) {
            if (!((utils.getWindowDimensions('width') < maxWidth)
            || (utils.getWindowDimensions('height') < maxHeight))) {
                if (!popin && typeof callOnBeforeLoad == 'function') {
                    callOnBeforeLoad();
                }
                var options = {
                    inner : inner
                };
                openPopin(jQuery(elm), options);
            }
        },
        bubbleSort : function(inputArray) {
            var start = 0;
            var rest  = inputArray.length - 1;
            for (var i = rest - 1; i >= start;  i--) {
                for (var j = start; j <= i; j++) {
                    if (inputArray[j+1].getAttribute('tabindex') < inputArray[j].getAttribute('tabindex')) {
                        var tempValue = inputArray[j];
                        inputArray[j] = inputArray[j+1];
                        inputArray[j+1] = tempValue;
                    }
                }
            }
            return inputArray;
        }
    };
    
    var liveEvents = function(){
        
        function eventClosePopin(e) {
            globs.dontPreventDefault = false;
            if (e.keyCode == 27 && popin) {
                closePopin();
            }
        }
        
        jQuery('#' + id_close).live('click',function(){
            closePopin();
        });
        
        jQuery(document.body, '#' + id_popin).bind('keyup',function(e) {
            eventClosePopin(e);
        });
        jQuery(window).bind('keyup',function(e) {
            eventClosePopin(e);
        });
        
        jWindow.bind('keydown',function(e) {
            if (e.shiftKey || e.ctrlKey || e.altKey || e.metaKey || e.keyCode == 9) {
                globs.dontPreventDefault = true;
            }
        });
        if (resize) {
            jWindow.resize(function(){
                utils.fixDimensions(0);
            });
        }
    }();
    
    function openPopin(elm, options) {
        var inner = false; // if true permits inner reloads

        if (memorize.activeLink == null) {
            var focusElm = null;  // a DOM element where the focus is applied on close
        }
        else {
            focusElm = memorize.activeLink;
        }
        if (options) {
            if (options.focusElm) {
                focusElm = options.focusElm;
            }
            if (options.inner) {
                inner = true;
            }
        }

        url = null;

        var setUrl = function(){
            if (typeof elm == 'string') {
                memorize.activeLink = jQuery(focusElm) || body;
                url = elm;
            }
            else if (typeof elm == 'object') {
                if (elm[0] && (elm[0].href || elm[0].action)) { // if elm is in DOM and has action
                    if (!document.getElementById(id_popin)) {
                        memorize.activeLink = elm;
                    }
                    url = elm.attr('href') || elm.attr('action');
                    globs.callerElm = elm;
                }
                else {
                    throw('Popin : openPopin() Argument Type Error : Can\'t found href or action attribut');
                }
            }
            else {
                throw('Popin : openPopin() Argument Type Error : Not a String or Object');
            }
        }();
        
        // ugly!!!
        parametres = (url.slice(url.indexOf('?') + 1)).split('&');
        paramets   = [];
        params     = [];
        iparam     = 0;
        
        var handleWindowLocation = function() {
            // ugly!!!
            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 (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();
                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;
            }
            if (closeClick) {
                if (popinCache && !popinCache.popinBinded) {
                    popinCache.bind('click', 'popin', function(e){
                        this.popinBinded = true;
                        closePopin();
                        e.preventDefault();
                    });
                }
            }
        }();
        
        
        var setPreStyles = function() {
            if (typeof inner != 'undefined' && inner == true) {
                return;
            }
            
            popinCache.css('opacity', opacity);
            
            if (anim) {
                popinCache.fadeIn('fast');
            }
            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');
                
                popinCache.css('height',(body.height() + marginIE6) + 'px');
                if (body.height() < utils.getWindowDimensions('height')) {
                    popinCache.css('height',utils.getWindowDimensions('height') + 'px');
                }
            }
            
        }();
        
        var loadContent = function() {
            var eUrl = encodeURI(url);
            var sentData = '';
            
            if (globs.callerElm && globs.callerElm.attr('action')) {
                var getFormData = function() {
                    jQuery(elm).find('input, select, textarea').each(function(){
                        if (!((this.type == 'checkbox' || this.type == 'radio') && !this.checked)) {
                            var current = jQuery(this);
                            var val  = encodeURIComponent(current.val());
                            var name = current.attr('name');
                            sentData += name+'='+val+'&';
                        }
                    });
                }();
            }
            
            globs.xhr1 = jQuery.ajax({
                type : 'POST',  // should we POST that ?
                url  : eUrl,
                data : sentData,
                cache : false,
                success : setPopin,
                error : function(XHR){
                    var statusURL = null;
                    for (var item in statusCodes) {
                        if (item == XHR.status) {
                            statusURL = statusCodes[item];
                            break;
                        }
                    }
                    globs.xhr2 = jQuery.ajax({
                        type : 'POST',
                        url  : statusURL || eUrl,
                        error : function(XHR){
                            if (popin) {
                                popin.empty();
                                popin.append('<div id="' + id_content + '">'+
                                                '<p>An error has occurred</p>' +
                                                '<p>ReadyState : '+ XHR.readyState + '</p>' +
                                                '<p>Status : '+ XHR.status + '</p>' +
                                             '</div>'+globs.closeHTML);
                
                                popin.attr('tabindex','-1');
                                popin.focus();
                            }
                        },
                        success : setPopin
                    });
                }
            });
        }();

        popin.append(loadImage[0]);
        popin.append(globs.closeHTML);
        popin.show();
    
        // alert('allo');
        
        // alert(!(params['width'] == 'auto' || params['height'] == 'auto'));
        
        var setDimensions = function() {
            if (globs.popinLoaded == 1) {
                utils.fixDimensions('normal'); //animate if there is a popin already open
            }
            else {
                if (!(params['width'] == 'auto' || params['height'] == 'auto')) {
                    // don't animate by opening first time
                    utils.fixDimensions(0);
                }
            }
        }();
    } // end openPopin
    
    function setPopin() {
        if (arguments[1] == 'error') {
            var XHR = arguments[0];
            var textStatus = responseText = arguments[1];
        }
        else {
            var responseText = arguments[0];
            textStatus = arguments[1];
            XHR = arguments[2];
        }
        
        var setContent = function(){
            if (popin) {
                
                var insertContent = function() {
                    popin.empty();
                    getContent.clone(true).appendTo(popin);
                    popin.append(globs.closeHTML);
                    popin.attr('tabindex','-1');
                    popin.focus();
                };
                
                var getContent = jQuery(responseText).find('#' + id_content);
                if (params['width'] == 'auto' || params['height'] == 'auto') {
                    var tmpClone = getContent.clone(true).appendTo(document.body);
                    tmpClone = jQuery(tmpClone);
                    tmpClone.css('visibility','hidden');
                    tmpClone.css('position','absolute');
                    tmpClone.css('left','-9999999px');
                    insertContent();
                    utils.fixDimensions('normal', tmpClone, function(){
                        tmpClone.remove();
                        delete tmpClone;
                    });
                }
                else {
                    insertContent();
                }
            }
        }();
                
        var verifyBehaviours = function() {
            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 tabFocus = function() {
            
            var focusPos = null;
            var elmsTabsIndex = [];
            
            var getElements = function(){
                
                // what about HTML5 elements : output, command ?
                // still browser dependent bugs CANTFIX (video, iframe, safari, IE, ..)
                
                var insertLabel = '';
                var doctype = new String(document.doctype).toUpperCase();
                if (doctype == '<!DOCTYPE HTML>') {
                    insertLabel = ', label';
                }
                
                // add only input when checked for radio and checkboxes
                var tabElms = 'a, area, audio[controls], button, details, embed, iframe, img[usemap], input:not([type=hidden]), keygen'+insertLabel+', menu[type=toolbar], object[usemap], select, video[controls], textarea';

                var elmsTabsNative = jQuery.makeArray(popin.find(tabElms).filter(function(){
                    if ((parseInt(jQuery(this).attr('tabindex') ,10) > 0) ||
                        ((this.offsetHeight == 0 && this.offsetWidth == 0) || this.style.visibility == 'hidden')) {
                        return false;
                    }
                    else {
                        return true;
                    }
                }));
                
                popin.find('*[tabindex]').filter(function(){
                    if (parseInt(jQuery(this).attr('tabindex') ,10) > 0) {
                        elmsTabsIndex.push(this);
                    }
                });
                
                elmsTabsIndex = utils.bubbleSort(elmsTabsIndex);
                elmsTabsIndex = [].concat(elmsTabsIndex, elmsTabsNative);
                
            }();
            
            var keyBoardEvents = function(){
                
                focusPos = -1; // init position
                
                var setFocus = function(e){
                    if (e.keyCode == 9) {
                        var nextElm = null;
                        if (focusPos == elmsTabsIndex.length-1 && !e.shiftKey) {
                            focusPos = -1;  // arrived at the last -> re-init
                        }
                        if (focusPos <= 0 && e.shiftKey) {
                            focusPos = elmsTabsIndex.length-1; // arrived at the start
                        }
                        else if (e.shiftKey) {
                            focusPos = focusPos - 1;
                        }
                        else {
                            focusPos = focusPos + 1;
                        }
                        nextElm = elmsTabsIndex[focusPos];
                        
                        // we have to try/catch because of IE
                        try { 
                            nextElm.focus();
                            e.preventDefault();
                        } catch(e) {}
                    }
                };
                
                if (jQuery.browser.mozilla || jQuery.browser.opera) {
                    jQuery(popin).bind('keypress',function(e){
                        setFocus(e);
                    });
                }
                else {
                    jQuery(popin).bind('keydown',function(e){
                        setFocus(e);
                    });
                }
            }();
            
        }();
        
        var modalEvents = function() {
            if (innerLoad) {
                jQuery(popin).find(targetLink).not('form').click(function(e){
                    if (!globs.dontPreventDefault) {
                        utils.setLinks(this, true);
                        e.preventDefault();
                    }
                });
                jQuery(popin).find('form'+targetLink).submit(function(e) {
                    if (!globs.dontPreventDefault) {
                        utils.setLinks(this, true);
                        e.preventDefault();
                    }
                });
            }
            
            if (popin && globs.popinLoaded > 0 && typeof callReload == 'function') {
                callReload();
            }
            else if (popin && typeof callOnload == 'function') {
                callOnload();
            }

        }();
        
        var handleStatus = function() {
            if (typeof inner != 'undefined' && inner == true) {
                return;
            }
            
            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;
        
        if (globs.xhr2) {
            globs.xhr2.abort();
        }
                
        var handleEvents = function() {
            if (!onload && tmpPopin && 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) {
                    memorize.activeLink = jQuery(options.focusElm);
                }
            }
        
            if (!onload && memorize.activeLink) {
                memorize.activeLink.attr('tabindex','-1');
                memorize.activeLink.focus();
                memorize.activeLink.removeAttr('tabindex');
                memorize.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;
        
            var url = parametres = iparam = null; // ugly!!!
            var paramets = params = [];
            
            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').bind('click',function(e) {
                    if (!globs.dontPreventDefault) {
                        utils.setLinks(this, false);
                        e.preventDefault();
                    }
            });
            jQuery('form'+targetLink).bind('submit',function(e) {
                    if (!globs.dontPreventDefault) {
                        utils.setLinks(this, false);
                        e.preventDefault();
                    }

            });
        }
    }();
    
    return {
        openPopin : function(url, options) {
            // options can be <focusElm> (DOM) and <inner> (true/false)
            if (!options) {
                options = {};
            }
            openPopin(url, options);
        },
        closePopin : function(focusElm) {
            if (!options) {
                options = {};
            }
            closePopin(null, options);
        },
        about : function(arg){
            return arg;
        }(this.about)
    };
};

/* EOF
------------------------------------------------------------------------------*/
