/*
 * Piximedia 2010
 */
/*
 * Variables
 */
/*USED DIV ARRAY*/
var pixiContainer = new Array('pm300x250', 'pm728x90', 'pmFooterBody', 'pmFooterMain', 'pmHeaderMain');
var placementData = {
    '809': {
        domId: 'pm300x250',
        parentId: 'idpublicitepave',
        frameId: 'pmFrame300x250'
    },
    '792': {
        domId: 'pm728x90',
        parentId: 'idpublicitemegabanner',
        frameId: 'pmFrame728x90'
    }
};
var footerInc = 0;
var itemToBridge = new Array('dclk_hide_overlay', 'dclk_hide', 'dclk_show', 'dclk_div', 'setStage', 'pub_ist_collapse', 'pub_ist_hd', 'centerdiv');
var pubContent;
var pmDebugMode = false;
var pmDebugLevel = 1;
var browser_normal = !(getInternetExplorerVersion());
var pmIeVersion = getInternetExplorerVersion();
var isFirefox2 = false;
var customDebuger = false;

pmCustomLog = function (msg) {
    msg = msg.replace('<', '&lt;');
    msg = msg.replace('>', '&gt;');
    document.getElementById('pmDebug').innerHTML += msg.toString() + '<br/>';

};

if (/^Mozilla.*Gecko.*Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) {
    if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)) { //test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
        var ffversion = new Number(RegExp.$1); // capture x.x portion and store as a number
        if (ffversion >= 2 && ffversion < 3) isFirefox2 = true;
    };
};

var pubScript;
var sas_tmstp = Math.round(Math.random() * 10000000000);
var sas_masterflag = 1;

var piximediaGlobal = {
    actions: {}
};
piximediaGlobal.custom = {};
piximediaGlobal.custom.canal = function () {
    return {
        addEvent: function (eventName, callbackFunction, reset) {
            try {
                pmCanalLog("Add event >> " + eventName);
                var actions = piximediaGlobal.actions;
                if (!actions[eventName]) {
                    actions[eventName] = [callbackFunction];
                } else {
                    if (reset) {
                        actions[eventName] = null;
                        actions[eventName] = [callbackFunction];
                    }
                    actions[eventName][actions[eventName].length] = callbackFunction;
                }
            } catch (e) {
                pmCanalWarn(e);
            }
        },
        callEvent: function (eventName) {
            try {
                pmCanalLog("Call event >> " + eventName);
                var actions = piximediaGlobal.actions;
                if (!actions[eventName]) throw 'Event not found >> ' + eventName;
                for (callback in actions[eventName]) {
                    pmCanalLog('Event found');
                    actions[eventName][callback]();
                }
            } catch (e) {
                pmCanalWarn(e);
            }
        }
    };

}();

var piximedia = piximediaGlobal;

//GLOBAL FUNCTION
pmCanalError = function (logMessage) {
    try {
        pmLogToConsole(logMessage, 3);
    } catch (fberror) {}
};
pmCanalLog = function (logMessage) {
    try {
        pmLogToConsole(logMessage, 1);
    } catch (fberror) {}
};
pmCanalWarn = function (logMessage) {
    try {
        pmLogToConsole(logMessage, 2);
    } catch (fberror) {}
};
pmLogToConsole = function (msg, level) {
    try {
        if (typeof (window.pmDebugMode) != 'undefined' && typeof (window.pmDebugLevel) != 'undefined') {
            if (window.pmDebugMode && window.pmDebugLevel <= level) {
                if (level >= 3) console.error(msg);
                else if (level >= 2) console.warn(msg);
                else if (level >= 1) console.info(msg);
                else console.debug(msg);
            }
        }
    } catch (fberror) {
    }

};

function createIframe(targetId, parentId) {
    var parentElement = document.getElementById(parentId);
    if (parentElement) {
        try {
            var elem = document.createElement('iframe');
            elem.setAttribute('id', targetId);
            elem.setAttribute('scrolling', "no");
            elem.setAttribute('width', "300");
            elem.setAttribute('height', "250");
            elem.setAttribute('scrolling', "no");
            elem.setAttribute('frameBorder', "0");
            elem.setAttribute('marginwidth', "0");
            elem.setAttribute('marginheight', "0");
            elem.style.overflow = 'hidden';
            parentElement.appendChild(elem);
            return true;
        } catch (e) {
            return false;
        }
    }
    return false;
};

function delIframe(parent, child) {
    try {
        var obj = document.getElementById(parent);
        var old = document.getElementById(child);
        obj.removeChild(old);
    } catch (e) {
        return false;
    }
};

function getInternetExplorerVersion() {
    var rv = false;
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (re.exec(ua) != null) rv = parseFloat(RegExp.$1);
    }
    return rv;
};
var msie_version = getInternetExplorerVersion();
browser_normal = !(getInternetExplorerVersion());

getSrcForIE = function (rs, pmIframeTarget, pmIframeDomId) { // IE FIX, SET IFRAME'S SRC AND document.close() DETECTION
	var rdm = "msie" + new Date().getTime();
    var s = '<head></head>\n<body topmargin="0" leftmargin="0">\n';
    s += '<scr' + 'ipt type="text/javascript">\nvar domWrapper = "' + pmIframeDomId + '";\nvar pmIframeTarget = "' + pmIframeTarget + '";\n</scr' + 'ipt>\n' + '<scr' + 'ipt type="text/javascript" src="'; 
    s += 'http://broadcast.piximedia.fr/streaming/canalplus/pmAdLib';
    
    if (window.location.href == "http://preprod.canalplus.fr/") {
    	s+= "";
    }
    
    s += '.js?' + rdm + '" onreadystatechange="startTimer();">';
    s += '</scr' + 'ipt>\n';
    s += '<scr' + 'ipt type="text/javascript">\nfunction startTimer()' + '{ \nif (event.srcElement.readyState == "complete") { \nwindow.setTimeout("document.close()", 2000);}\n}\n</scr' + 'ipt>\n';
    s += '</body>';
    return s;
};

function resetDom() {
    for (var p in pixiContainer) {
    	
        if (document.getElementById(pixiContainer[p])) document.getElementById(pixiContainer[p]).innerHTML = '';
    }
    try {
        delIframe('idpublicitepave', 'pmFrame300x250');
    } catch (e) {
        pmCanalWarn('Wrong Iframe 300x250 : ' + e);
    };
    try {
        delIframe('idpublicitemegabanner', 'pmFrame728x90');
    } catch (e) {
        pmCanalWarn('Wrong Iframe 728x90 : ' + e);
    };
};


function SmartAdServer(sas_pageid, sas_formatid, sas_target, timeStamp) {
    var placementExists = false;
    sas_target = sas_target || '';

    sas_tmstp = (timeStamp) ? sas_tmstp : Math.round(Math.random() * 10000000000); // Verification de l'existence du parametre timeStamp
    if (parent.sas_masterflag == 1) {
        parent.sas_masterflag = 0;
        sas_master = 'M';
    } else {
        sas_master = 'S';
    }
    //sas_master = 'M';
    if (placementData[sas_formatid] && document.getElementById(placementData[sas_formatid].frameId) == null) {
        placementExists = createIframe(placementData[sas_formatid].frameId, placementData[sas_formatid].parentId);
        if (!placementData[sas_formatid].called) {
            sas_target = 'ft';
        }
    } else if (placementData[sas_formatid] && document.getElementById(placementData[sas_formatid].parentId)) {
        placementExists = true;
    }

    if (placementExists) {
        placementData[sas_formatid].called = true;
        SmartAdServer_iframe(sas_pageid, sas_formatid, sas_target, placementData[sas_formatid].frameId, placementData[sas_formatid].domId);
    }
};

function SmartAdServer_iframe(sas_pageid, sas_formatid, sas_target, pmIframeTarget, pmIframeDomId) {
    var srcScript = ' ';

    pubScript = 'http://www3.smartadserver.com/call/pubj/' + sas_pageid + '/' + sas_formatid + '/' + sas_master + '/' + parent.sas_tmstp + '/' + escape(sas_target) + '?';
    pubContent = '<scr' + 'ipt type="text/javascript" src="' + pubScript + '"></scr' + 'ipt>';
    libContent = '<scr' + 'ipt type="text/javascript">var domWrapper = "' + pmIframeDomId + '";var pmIframeTarget = "' + pmIframeTarget + '";</scr' + 'ipt>';

    var rdm = new Date().getTime();

    if (window.location.href == "http://preprod.canalplus.fr/") libContent += '<scr' + 'ipt type="text/javascript" src="http://broadcast.piximedia.fr/streaming/canalplus/pmAdLib.js?' + rdm + '"></scr' + 'ipt>';
    else libContent += '<scr' + 'ipt type="text/javascript" src="http://broadcast.piximedia.fr/streaming/canalplus/pmAdLib.js?' + rdm + '"></scr' + 'ipt>';

    var ifrm = document.getElementById(pmIframeTarget);

    if (browser_normal) {
        ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument;
        ifrm.document.open();
        ifrm.document.write('<head></head><body>');
        ifrm.document.write(libContent);
        ifrm.document.write('</body>');
        if (!isFirefox2) ifrm.document.close();
        else setTimeout('closeDocument()', 3000);
    } else { // Internet Explorer
    	
        srcScript = getSrcForIE(pubScript, pmIframeTarget, pmIframeDomId);
        ifrm.src = "javascript:void(document.write('" + srcScript + "'));";
    }

};

function refreshSmartId() { //REFRESH TIMESTAMP
    resetDom();
    sas_tmstp = Math.round(Math.random() * 10000000000);
    sas_masterflag = 1;
}

function refresh_compagnon(PAGEID, TARGET, TIMESTAMP) {
    resetDom(); // Efface l'iframe deja presente et en reecrit une vierge
    sas_masterflag = 1;
    sas_master = 'M';
    sas_tmstp = TIMESTAMP;
    sas_pageid = '3574/' + PAGEID;
    sas_formatid = 809;
    sas_target = TARGET;
    SmartAdServer(sas_pageid, sas_formatid, sas_target, TIMESTAMP);
}
