/***********pop in****************/
var d = document;
w = window;
var debug = null;
w.config = {
    debug : false,
    popin1 : {
        target : '.open',
        name : {
            popin   : 'popin',
            cache   : 'cache',
            close   : 'close',
            content : 'pop_content'//,
            // loadimg : 'load-indicator'
        },
        behaviours : {
            closeClick : true,
            hash   : 'pop',
            close  : f_get_txt('close'),         // 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.50,         // 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
        }
    },
    popin2 : {
        target : '.callbacks',
        name : {
            popin   : 'popin',
            cache   : 'cache',
            close   : 'close',
            content : 'pop_content'
        },
        behaviours : {
            closeClick : true,
            hash   : 'pop',
            close  : f_get_txt('close'),         // texte du bouton de fermeture (ou code html)
            anim   : true              // animation du masque (fadeIn/Out)
        },
        style : {
            marginMax : 50,           // marge autour de la popin quand elle est plus grande que la fenetre et redimensionnee
            opacity   : 0.50,         // 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,
            onunload : callUnload,
            onbeforeload  : callBeforeLoad,
            onreload : callReload
        }
    },
    externalPopin1 : {
        target : null,                // set it to null for external calls
        name : {
            popin   : 'popin',
            cache   : 'cache',
            close   : 'close',
            content : 'pop_content'
        },
        behaviours : {
            closeClick : true,
            hash   : 'pop',
            close  : f_get_txt('close'),         // texte du bouton de fermeture (ou code html)
            anim   : true              // animation du masque (fadeIn/Out)
        },
        style : {
            marginMax : 50,           // marge autour de la popin quand elle est plus grande que la fenetre et redimensionnee
            opacity   : 0.50,         // 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)
        }
    }
};

function callLoad() {
    //log('onload');
    // if(jQuery('#myContent').length) {
        // swfobject.embedSWF('swf/test.swf', 'myContent', '300', '120', '9.0.0', 'expressInstall.swf');
    // }

	// chargement du scroll
	/*if(jQuery('.scroll-bloc').length) {
		$('.scroll-bloc').addClass('scroll-bloc-1');
		$('.scroll-bloc').jScrollPane({showArrows:true});
	}*/
	if ($('.nes_bloc-degrade-pop span img').length)
	{
		if( $.browser.msie && ($.browser.version == "6.0") ) {
			DD_belatedPNG.fix(".nes_png, .nes_bloc-degrade-pop span img");
		}
	}	
	
	setTimeout(function ()
	{
		if(jQuery('.scroll-bloc').length) 
		{
			$('#popin .scroll-bloc').addClass('scroll-bloc-1');
			$('#popin .scroll-bloc-1').jScrollPane({showArrows:true});
			if ($.browser.msie && $.browser.version == "6.0"){
				$("#popin .scroll-bloc").find("shape").remove();
				$("#popin .scroll-bloc .nes_png").css("visibility", "visible")
										.css("behavior", "");
				DD_belatedPNG.fix(".nes_png");
			}
		}
		affQuantity($('#popin').find('.nes_select-quantity'), 'var');
		BagController.initPonctual('',$('#popin').find('.nes_linkAddToBag'),oPopin.closePopin);
	},200);
}
function callUnload() {
    //log('onunload');
}

function callBeforeLoad() {
    //log('onbeforeload');
}

function callReload() {
    // log('reload');
    // if(jQuery('#myContent').length) {
        // swfobject.embedSWF('swf/test.swf', 'myContent', '300', '120', '9.0.0', 'expressInstall.swf');
    // }
	setTimeout(function ()
	{
		if(jQuery('.scroll-bloc').length) 
		{
			$('#popin .scroll-bloc').addClass('scroll-bloc-1');
			$('#popin .scroll-bloc-1').jScrollPane({showArrows:true});
		}
		affQuantity($('#popin').find('.nes_select-quantity'), 'var');
		BagController.initPonctual('',$('#popin').find('.nes_linkAddToBag'),oPopin.closePopin);
	},10);
}



/* DEBUG
------------------------------------------------------------------------------*/
var debuger = function() {
    if (w.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");
        debug.setAttribute("id",   "debug");
        body.insertBefore(debug, parent);
        w.debug = debug;
    }
    //log('Debug on\n\n');
};
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() {
    //debuger();
    
    // configs
    var popin1 = w.config.popin1;
    var popin2 = w.config.popin2;
	var emptyVarOk = typeof isShoppingBagEmpty != 'undefined' ? isShoppingBagEmpty : "false";

    // functions
	if (emptyVarOk == "true") {
		$('#nes_colLeft > div.nes_orderHistryContent > div.nes_orderDetailsContent > div.nes_colTopOrder > ul.nes_add-block > li.nes_yellow-bg-middle > a.nes_linkAddToBag_').removeClass('open').attr('href', urlReorder);
	}else{
		oPopin=popin(popin1);
	}
    oPopin=popin(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;
    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;
            }
            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('slow');
            }
            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() {
            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) {
				if (typeof params["width"] != 'undefined' && typeof params["height"] != 'undefined') 
				{
					popin.animate({
						width : params["width"] + "px",
						//marginLeft : "-" + Math.round(((params["width"])/2)) + "px",
						marginLeft : Math.round(((params["width"])/2)) + "px",
						height : params["height"] + "px",
						//marginTop : "-" + Math.round(((params["height"])/2)) + "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");
                }
            }

			//200 a remplacer par la hauteur du popin
			popin.css('top',Math.round( utils.getWindowDimensions('height')/2 - 200 + utils.getScrollPositions("y"))+"px")
			
            utils.fixDimensions('width','left');
            utils.fixDimensions('height','top');
        }();
        
		InstallationInfoBulle();
		
		$('.nes_fct-bulle li .info-bulle-css img').hover(
			function(){
				 $(this).parent('.info-bulle-css').parent('li').css('position','relative');
				 
			 }, function(){
				$(this).parent('.info-bulle-css').parent('li').css('position','static');
			
		});
		$('.nes_img-cup li .info-bulle-css').hover(
			function(){
				 $(this).parent('li').addClass('nes_li_relpop');
				$(this).parent('li').parents('ul').css('z-index','1');
				
			 }, function(){
				  $(this).parent('li').removeClass('nes_li_relpop');
				$(this).parent('li').parents('ul').css('z-index','0');
			
		});
		$('.nes_img-cup li .info-bulle-css span').hover(
			function(){
				 $(this).parent('.info-bulle-css').parent('li').addClass('nes_li_relpop');
				$(this).parent('.info-bulle-css').parent('li').parents('ul').css('z-index','1');
				
			 }, function(){
				  $(this).parent('.info-bulle-css').parent('li').removeClass('nes_li_relpop');
				$(this).parent('.info-bulle-css').parent('li').parents('ul').css('z-index','0');
			
		});	
		$('.nes_img-cup li .info-bulle-css img').hover(
			function(){
				 $(this).parent('.info-bulle-css').parent('li').addClass('nes_li_relpop');
				$(this).parent('.info-bulle-css').parent('li').parents('ul').css('z-index','1');
				
			 }, function(){
				  $(this).parent('.info-bulle-css').parent('li').removeClass('nes_li_relpop');
				$(this).parent('.info-bulle-css').parent('li').parents('ul').css('z-index','0');
			
		});	

		$('.nes_block-choices input').click(function(){
			$('.nes_block-choices').removeClass('nes_block-choice-selected');
			$(this).parents('.nes_block-choices').addClass('nes_block-choice-selected');
		});

        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);
				// Modifié par : Abdelkader RHOAUTI
				// date : 04/03/2010
                // Description : Modifier pour mettre le lien Close en début de popin
				// popin.children('#' + id_content).append(closeHTML);
				popin.children('#' + id_content).prepend(closeHTML);
            }
            else {
				// Modifié par : Abdelkader RHOAUTI
				// date : 04/03/2010
                // Description : Modifier pour mettre le lien Close en début de popin
				// Modifier pour mettre le lien Close en debut de popin
				// jQuery('#' + id_content).append(closeHTML);
                jQuery('#' + id_content).prepend(closeHTML);
            }
            
            jQuery('#' + id_close +' a').bind('click',function(){
                closePopin();
				$(".nes_popin-content .info-bulle-contenu").css('display','none');
                return false;
            });
            jQuery('#nes_order-close').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 && tmpPopin != null && 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.stop().fadeOut('fast', function(){
                    tmpCache.remove();
                    delete tmpCache;
                });
				popin.remove();
            }
            else {
                popinCache.remove();
				popin.remove();
            }
            //popin.remove();
        }();
        
        var resetVars = function() {
            popin = null;
            popinCache = null;
        
            url, parametres, paramets, params, iparam = null; // crados
        
            globs.callerElm = null;
        }();
        
        if (jQuery.browser.msie && jQuery.browser.version < 7) {
            jQuery('select').css('visibility','visible');
        }
		
		if(contextPage == "aboutUs" || contextPage == "customerService")
		{
			popinClosing();
		}
    } // 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;
        }
    };
}
