/*global define*/ define(['jquery', 'json3.min'], function ($, JSON) { var ifr = function () { var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent", eventer = window[eventMethod], messageEvent = eventMethod === "attachEvent" ? "onmessage" : "message", callbackFunctions = [], followingType = {}; return { init : function () { eventer(messageEvent, $.proxy(this.listenMessage, this)); }, /** * Run callbacks following message * @returns {boolean} */ listenMessage : function (e) { try { var donnee = JSON.parse(e.data); if (followingType.length === 0) { return false; } var functionsIndexToCall = [], keyState = donnee.type; for (var kf in followingType[keyState]) { // Test if function isn't allready in queue if ($.inArray(followingType[keyState][kf], functionsIndexToCall) == -1) { // Add function in queue functionsIndexToCall.push(followingType[keyState][kf]); } } // Parsing all functions and run it for (var k in functionsIndexToCall) { if (typeof(callbackFunctions[functionsIndexToCall[k]]) !== 'undefined') { callbackFunctions[functionsIndexToCall[k]](donnee); } } } catch (error) {} }, /** * Add a callback on segment passing in settings * @param settings * @param callback */ add : function (settings, callback) { var index = callbackFunctions.push(callback); index += -1; for (var k in settings) { var keyState = settings[k]; if (typeof(followingType[keyState]) === 'undefined') { followingType[keyState] = []; } followingType[keyState].push(index); } }, /** * Remove the callback * @param callback */ remove: function(callback) { var index = callbackFunctions.indexOf(callback); if (index > -1) { callbackFunctions.splice(index, 1); } }, send: function (functionName, functionParams) { window.parent.postMessage(JSON.stringify({ 'js': 'tC.privacy.' + functionName + '(' + functionParams + ')', 'functionName': functionName, 'params': functionParams }), "*"); }, sendReady: function () { window.parent.postMessage(JSON.stringify({type:'ready'}), "*"); }, callbackSync: function(nb, fn){ var count = 0; return function(){ count++; if(count === nb){ fn(); } } } }; }; return ifr(); });