﻿//****** Variable à modifier lors de l'intégration de l'IFrame ******/
/*** QLF ***/
var url_contenu_iframe = "http://courses-pql.mpxserv.fr";
/*** PROD ***/
//var url_contenu_iframe = "http://courses.monoprix.fr";

var iframe_widget_panier = "iframe_widget_panier";
var container_widget_panier = "container_widget_panier";

var widget_panier_key = "BasketElementAdded";

//var BasketElementAdded = false;

//Fonction permettant d'afficher sans erreurs le panier lors de l'ajout de produit
function ajoutPanier(ref_produit) {
    try {
        
        _CookieMgr.create(widget_panier_key, 'true', 10);
        window.open((url_contenu_iframe + "/widget/widget_panier.jsp?irefc=" + ref_produit), iframe_widget_panier);
    }
    catch (error) {
        alert("ajoutPanier : " + error.message);
    }
}

function chargePanier(ref_produit) {
    try {
        window.open((url_contenu_iframe + "/widget/widget_panier.jsp"), iframe_widget_panier);
    }
    catch (error) {
        alert("chargePanier : " + error.message);
    }
}


//http://courses-pql.mpxserv.fr/panier/componentPanier/remoteBasketManager.jsp?ajax-call=true


//Fonction permettant d'afficher/masquer l'IFrame pour lui laisser le tps de s'initialiser correctement
function affichePanier(aff) {

    try {

        var iframe = null;
        if (iframe = $(iframe_widget_panier)) {
            iframe.style.display = aff === true ? "block" : "none";
            iframe = null;
        }
    }
    catch (error) {
        alert("affichePanier : " + error.message);
    }
}

function testPanier() {

}

//*** Cookie Manager *********************************************************************************************//


CookieMgr = Class.create({
	
	initialize: function () {  },
	
	create: function (name, value, days) {
		var expires = "";
		if (days) {
			var d = new Date();
			d.setTime(d.getTime() + (days * 24 * 60 * 60 * 1000));
			expires = "; expires=" + d.toGMTString();
		}
		document.cookie = name + "=" + value + expires + "; path=/";
	},
	
	read: function (name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for (var i=0;i<ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0) == ' ') c = c.substring(1, c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
		}
		return null;
	},
	
	erase :function (name) {
		this.create(name, "", -1);
	}
		
});
var _CookieMgr = new CookieMgr();

//*** OBJECTScreenFixed *********************************************************************************************//

var Axis = {
    initialize: function() {
        this.each(function(k, r) { this.base[k] = this.base[k] || this.keys(k); } .bind(this));
    },
    base: { x: null, y: null },
    pos: { x: 'Left', y: 'Top' },
    scale: { x: 'Width', y: 'Height' },
    id: { x: 0, y: 1 },
    keys: function(key) {
        this[key] = this[key] ||
            {
                key: key,
                min: key + 'min',
                max: key + 'max',
                axis: key + 'axis',
                limit: key + 'limit',
                factor: key + 'factor',
                pos: this.pos[key].toLowerCase(),
                scale: this.scale[key].toLowerCase(),
                scrollpos: 'scroll' + this.pos[key],
                scrollscale: 'scroll' + this.scale[key],
                offsetpos: 'offset' + this.pos[key],
                offsetscale: 'offset' + this.scale[key],
                clientscale: 'client' + this.scale[key],
                innerscale: 'inner' + this.scale[key],
                mouse: key + 'mouse',
                pointer: 'pointer' + key.toUpperCase()
            };
        return this[key];
    },
    from: function(o) {
        return { x: o[0], y: o[1] };
    },
    each: function(iterator, memo) {
        for (var key in this.base)
            memo = iterator((this[key] || key), memo);
        return memo;
    }
}
Axis.initialize();

var PageTools = {

    _frame: null, _document: null, _documentLabel: null, _window: null,

    hasFrame: function() {
        this._frame = this._frame || top.frames.length > 0;
        return this.frame;
    },

    getDocument: function() {
        this._document = this._document ||
						 eval(this.getDocumentLabel() + (navigator.appVersion.indexOf('Safari') == -1 ? 'document.documentElement' : 'document.body'));
        return this._document;
    },

    getDocumentLabel: function() {
        this._documentLabel = this._documentLabel || this.hasFrame() ? 'top.' : '';
        return this._documentLabel;
    },

    getWindow: function() {
        this._window = this._window || this.hasFrame() ? top : window;
        return this._window;
    },

    getPageSize: function(k) {
        return this.getDocument()[k.scrollscale] < this.getWindowSize(k) ? this.getWindowSize(k) : this.getDocument()[k.scrollscale];
    },

    getWindowSize: function(k) {
        return window[k.innerscale] ? window[k.innerscale] : this.getDocument()[k.clientscale];
    }

};

var ObjectScreenFixed = Class.create({

	initialize: function(o) {
		this._target = o.target;
		this._axis = {};
		Axis.each(function(k) {
			this._axis[k.key + 'align'] = o.axis[k.key + 'align'];
			this._axis[k.min] = o.axis[k.min];
			this._axis[k.max] = o.axis[k.max];
		} .bind(this));
		this._setAlign();
		this._setEvents();
	},

	_setEvents: function() {
		this._mouseWheel = document.all ? 'mousewheel' : 'DOMMouseScroll';
		this._onWindowEVENT = this._setAlign.bindAsEventListener(this);
		Event.observe(PageTools.getWindow(), this._mouseWheel, this._onWindowEVENT);
		Event.observe(PageTools.getWindow(), 'scroll', this._onWindowEVENT);
		Event.observe(PageTools.getWindow(), 'resize', this._onWindowEVENT);
	},

	_killEvents: function() {
		Event.stopObserving(PageTools.getWindow(), 'resize', this._onWindowResizeEVENT);
		Event.stopObserving(PageTools.getWindow(), 'scroll', this._onWindowMouseWheelEVENT);
	},

	_setAlign: function() {
		Axis.each(function(k) {
			var align = this._axis[k.key + 'align'];
			var pos = 0;
			var scrollpos = PageTools.getDocument()[k.scrollpos];
			if (/*align == 'left' ||*/align == 'top') {
				pos = (this._axis[k.min] && this._target[k.offsetpos] < this._axis[k.min] || scrollpos < this._axis[k.min]) ? this._axis[k.min] : scrollpos;
			}
			else if (/*align == 'right' ||*/align == 'bottom') {
				var posTest = PageTools.getWindowSize(k) - this._target[k.offsetscale] + scrollpos;
				pos = (this._axis[k.max] && this._axis[k.max] < posTest) ? this._axis[k.max] : posTest;
			}

			if(k.pos != "left") {
				this._target.style[k.pos] = pos + 'px';
			}
		} .bind(this));
	}

});


//*** Main Init Panier ***//
Event.observe(window, 'load', function() {

    if (!$(container_widget_panier))
        return;

    /// Main Activity condition..
    if( !(HasContentAddBasketLink||false))
        return;

    new ObjectScreenFixed({
        target: $(container_widget_panier),
        axis: {
            xalign: 'right', xmin: null, xmax: null,
            yalign: 'top', ymin: 160, ymax: null
        }
    });

    // todo : push conditions...
    /// if must not be visible : return... 

    /// Add onmouseout handler
    Event.observe($(iframe_widget_panier), 'mouseout',
        function() {
            
            var BasketElementAdded = (_CookieMgr.read(widget_panier_key)!=null);
            if( BasketElementAdded )
            {
                $(iframe_widget_panier).removeClassName('widget_panier_closed');
                $(iframe_widget_panier).addClassName('widget_panier_opened');

            }
            else
            {
                $(iframe_widget_panier).addClassName('widget_panier_closed');
                $(iframe_widget_panier).removeClassName('widget_panier_opened');
            }
        }
        );

    Event.observe($(iframe_widget_panier), 'load',
        function() {
        
            affichePanier(true);
            
            /// auto reload open...
            var BasketElementAdded = (_CookieMgr.read(widget_panier_key)!=null);
            if( BasketElementAdded )
            {
                $(iframe_widget_panier).removeClassName('widget_panier_closed');
                $(iframe_widget_panier).addClassName('widget_panier_opened');

            }
            else
            {
                $(iframe_widget_panier).addClassName('widget_panier_closed');
                $(iframe_widget_panier).removeClassName('widget_panier_opened');
            }
        }
        );
   
    Event.observe($(iframe_widget_panier), 'mouseover',
        function() {
        

        }
    );
    
    chargePanier();

});

