/*------------------------------------------------------------------------------
    JS Document (https://developer.mozilla.org/en/JavaScript)

    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)
    summary:    CONFIG
                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
------------------------------------------------------------------------------*/
jQuery.noConflict();
var d = document;
var w = window;
pm = {};
majx.set({
    popin1 : {
        target : '.popin',              // target links with this class (CSS 3 Selectors)
        name : {
            popin   : 'popin',          // the popin id
            cache   : 'cache',          // the popin cache id
            close   : 'close',          // the close button id
            content : 'pop-content'     // the id where to extract the code in the target page.
        },
        behaviours : {
            closeClick : true,          // if true permits to click outside the popin to close it
            close  : '<img src="/wp-content/themes/pconsultants/images/master/picto-close.png" alt="Fermer" />',           // close button, you can also include HTML code
            anim   : true,              // true by default, false avoids fadeIn
            resize : false              // experimental to refit the popin when the window is resized
        },
        style : {
            marginMax : 50,             // minimum margin between the popin and the window
            opacity   : 1,           // cache final opacity
            maxWidth  : 250,            // minimal screen width to open popins
            maxHeight : 250             // minimal screen height to open popins
        }
    },
    popin2 : {
        target : '.popin2',              // target links with this class (CSS 3 Selectors)
        name : {
            popin   : 'popin',          // the popin id
            cache   : 'cache',          // the popin cache id
            close   : 'close',          // the close button id
            content : 'pop-content'     // the id where to extract the code in the target page.
        },
        behaviours : {
            closeClick : true,          // if true permits to click outside the popin to close it
            close  : '<img src="/wp-content/themes/pconsultants/images/master/picto-close.png" alt="Fermer" />',           // close button, you can also include HTML code
            anim   : true,              // true by default, false avoids fadeIn
            resize : false              // experimental to refit the popin when the window is resized
        },
        style : {
            marginMax : 50,             // minimum margin between the popin and the window
            opacity   : 1,           // cache final opacity
            maxWidth  : 250,            // minimal screen width to open popins
            maxHeight : 250             // minimal screen height to open popins
        },
        callback : {                    // events
            onload   : externFnLoad
        }
    }
});

function externFnLoad(){
    jQuery('.block-carousel').jcarousel({
    	wrap: 'circular',
    	scroll: 1
    });
    if (jQuery("#player-popin").length > 0 ) {
    	jwplayer("player-popin").setup({ flashplayer: "/wp-content/themes/pconsultants/swf/player.swf", file: "/wp-content/themes/pconsultants/uploads/video.mp4", height: 332, width: 591  });
	}
	if (jQuery("#player-popin-home-pernod").length > 0 ) {
		jwplayer("player-popin-home-pernod").setup({ flashplayer: "/wp-content/themes/pconsultants/swf/player.swf", file: "/wp-content/themes/pconsultants/uploads/pernod-ricard-ipad.flv", height: 332, width: 591  });
    }
	if (jQuery("#player-popin-cc-sg").length > 0 ) {
    	jwplayer("player-popin-cc-sg").setup({ flashplayer: "/wp-content/themes/pconsultants/swf/player.swf", file: "/wp-content/themes/pconsultants/uploads/YA_PAS_DE_MALAISE_DEF_VI_1.flv", height: 316, width: 591 });
    }
	if (jQuery("#player-popin-cc-arjel").length > 0 ) {
    	jwplayer("player-popin-cc-arjel").setup({ flashplayer: "/wp-content/themes/pconsultants/swf/player.swf", file: "/wp-content/themes/pconsultants/uploads/poney-v1_1-arjel.flv", height: 316, width: 591 });
    }
    if (jQuery("#player-popin-event-michelin").length > 0 ) {
        jwplayer("player-popin-event-michelin").setup({ flashplayer: "/wp-content/themes/pconsultants/swf/player.swf", file: "/wp-content/themes/pconsultants/uploads/Trophees-2011_IBF 2010-Michelin.flv", height: 316, width: 591 });
    }
    if (jQuery("#player-popin-cc-orsay").length > 0 ) {
        jwplayer("player-popin-cc-orsay").setup({ flashplayer: "/wp-content/themes/pconsultants/swf/player.swf", file: "/wp-content/themes/pconsultants/uploads/orsay_nouveau_regard_30s_110913.flv", height: 316, width: 591 });
    }
    if (jQuery("#player-popin-cc-carrefour-prod").length > 0 ) {
        jwplayer("player-popin-cc-carrefour-prod").setup({ flashplayer: "/wp-content/themes/pconsultants/swf/player.swf", file: "/wp-content/themes/pconsultants/uploads/boucles.flv", height: 316, width: 591 });
   }
   if (jQuery("#player-popin-betaworld").length > 0 ) {
        jwplayer("player-popin-betaworld").setup({ flashplayer: "/wp-content/themes/pconsultants/swf/player.swf", file: "/wp-content/themes/pconsultants/uploads/betaworld.flv", height: 316, width: 591 });
   }
   if (jQuery("#player-popin-ratp").length > 0 ) {
        jwplayer("player-popin-ratp").setup({ flashplayer: "/wp-content/themes/pconsultants/swf/player.swf", file: "/wp-content/themes/pconsultants/uploads/ratp.flv", height: 316, width: 591 });
   }
   if (jQuery("#player-popin-cc-womens-forum").length > 0 ) {
        jwplayer("player-popin-cc-womens-forum").setup({ flashplayer: "/wp-content/themes/pconsultants/swf/player.swf", file: "/wp-content/themes/pconsultants/uploads/womens-forum-2011.flv", height: 316, width: 591 });
   }
if (jQuery("#player-popin-p-couvry").length > 0 ) {
        jwplayer("player-popin-p-couvry").setup({ flashplayer: "/wp-content/themes/pconsultants/swf/player.swf", file: "/wp-content/themes/pconsultants/uploads/itw-p-couvry.flv", height: 316, width: 591 });
   }
}

/* =DOM.READY
------------------------------------------------------------------------------*/
jQuery(document).ready(function() {
    popin1 = new popin(majx.config.popin1);
    popin2 = new popin(majx.config.popin2);
});


/* =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 || 50;          // popin margin
    var marginIE6  = config.style.marginIE6 || 50;          // IE 6 fix
    var opacity    = config.style.opacity;
    var maxWidth   = config.style.maxWidth;
    var maxHeight  = config.style.maxHeight;
    var pop_hash   = config.behaviours.hash || 'pop';
    var closeStr   = config.behaviours.close;
    var innerLoad  = config.behaviours.innerLoad || true;
    var anim       = config.behaviours.anim   || true;
    var resize     = config.behaviours.resize || false;     // EXPERIMENTAL / 
    var anchor     = config.behaviours.anchor || false;     // EXPERIMENTAL / handling location hash
    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; // ugly!!!
    
    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;
            }
            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;
            }
        }();
                
        // 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 (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
                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);
            
            if (globs.callerElm && globs.callerElm.attr('action')) {
                var sentData = '';
                var getFormData = function() {
                    jQuery(elm).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  : eUrl,
                    data : sentData,
                    success : setPopin
                });
            }
            else {
                var param  = (url.indexOf("?") != -1) ? '&' : '?';
                var random = 'popincache='+Math.floor(1000000000*Math.random());
                popin.load(eUrl+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");
            jQuery('html, body' ).animate({ scrollTop: 0 }, 0 );
            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; // ugly!!!
        
            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;
        }
    };
}
