var dm_text_write = '';
var dm_write_position = '';

var DM_MassCast = 
{
    loaded: false,
    theaterAd: {},
    // Default reload ad value defined in the conf and
    // can be overwritten by the env
    reloadTime: 150,
    // By default, rotate add is disabled. One needs to do:
    // addEnv('DM_MassCast.doSecondCall, true); example on the player page
    doSecondCall: false,
    isPeriodicalExecuterStopped: false,
    crossFadeDuration: 1,
    enableCrossFade: true,
    isAdInIframe: false,
    // In seconds (900 = 15 min), stops the periodical executer at given duration
    reloadMaxDuration: 900,

    getSWF: function(url)
    {
        return DM_MassCast.hasTheaterAd() ? '/flash/dmtheater/dmtheater.swf' : url;
    },
    pushTheaterAd: function(data)
    {
        var match;

        // Trim spaces and remove '\n'
        data = data.replace(/^\s+|\s+$|\\n/g, '');

        if (match = data.match(/^(curtainPath|backgroundPath|clickTAG|clickTARGET|accountingPath)\s*=\s*(.*)?/))
        {
            DM_MassCast.theaterAd[match[1]] = match[2];
        }
    },
    loadTheaterAd: function(position)
    {
        try
        {
            if (!OAS_RICH)
            {
                return;
            }

            document.writeold = document.write;
            document.write = DM_MassCast.pushTheaterAd;
            try { OAS_RICH(position); } catch(e){};
            document.write = document.writeold;

            if (DM_MassCast.hasTheaterAd())
            {
                DM_MassCast.showTheaterAd();
            }
        }
        catch(e){}
    },
    setTheaterAd: function(obj)
    {
        if (!DM_MassCast.hasTheaterAd())
        {
            return;
        }

        for (param in DM_MassCast.theaterAd)
        {
            obj.addVariable(param, DM_MassCast.theaterAd[param]);
        }

        // Disable fullscreen
        obj.addVariable('hide', obj.getVariable('hide') + '%40fullscreen%40');
    },
    hasTheaterAd: function()
    {
        return (DM_MassCast.theaterAd['curtainPath'] && DM_MassCast.theaterAd['backgroundPath']);
    },
	showTheaterAd: function()
	{
		EventSelectors.start({ 'body': function(e) { e.addClassName('theater_video_page'); } });
	},
    write: function(text)
    {
        try
        {
            var regex = /<script.*?src="(.*?)".*?<\/script>/i;
            //dbg(text);
            if(regex.match(text))
            {
                //dbg('script avec src ' + RegExp.$1)
                $('mc_' + dm_write_position).insert(new Element("script", { src: RegExp.$1}));
            }
            else
            {
                //dbg('inline script (no src)');
                var vb_regex = /<script.*?language=vbscript.*?>/i;

                var complete_script_regex = /<script.*?>(.*?)<\/script>/gi;

                text = dm_text_write + text;

                text = text.gsub('\n', '{a}');

                if(vb_regex.match(text))
                {
                    //dbg('VBScript detected');

                    if(complete_script_regex.match(text))
                    {
                        //document.insert(script);
                        //dbg('VBScript completed');
                        //dbg('script ' + RegExp.$1.gsub('{a}', "\n"));
                        // var script = new Element("script", { language: "VBScript" });
                        // script.update(RegExp.$1.gsub('{a}', "\n"));
                        // $('mc_' + dm_write_position).insert({top: script});

                        //$('vb').update(RegExp.$1.gsub('{a}', "\n"));
                        
                        dm_text_write = ''; // just trash the VBScript, only useful on IE which is handle another way
                        
                        //dbg('global text to write (should be empty here) ' + dm_text_write);
                    }
                    else
                    {
                        dm_text_write = text;
                        //dbg('script accumulation ' + dm_text_write);
                    }
                }
                else
                {
                    //dbg('no script');
                    $('mc_' + dm_write_position).insert(text.gsub('{a}', "\n"));
                }
            }
        }
        catch(e)
        {
            dbg(e);
        }
    },
    rules: {
        'div#mc_close': function(element)
        {
            element.onclick = function()
            {
                // We are in the page
                if ($('iabIframe1'))
                {
                    while(!element.hasClassName('mc_container'))
                    {
                        element = $(element.parentNode);
                    }
                    $$('div.dm_widget_advert_iabrighttitle').first().setStyle({height: 0});
                    element.remove();
                    $('iabIframe1').remove();
                    $('iabIframe2').remove();
                }
                // We are in the iframe
                else
                {
                    var container = parent.window.$$('div.dm_widget_advert_iabrighttitle').first();
                    container.setStyle({height: 0});
                    container.childElements().each(function(el)
                    {
                        el.remove();
                    });
                }
            }
        }
    },
    render: function(title, param, url, target, play, pixel)
    {
        if(typeof(mcType) != 'string')
        {
            mcType = '';
        }
        if(typeof(mcContainer) != 'string')
        {
            mcContainer = '';
        }
        
        if(typeof pixel != 'string')
        {
            pixel = '';
        }
        
        var args = $H(
            {
                'title'     : title,
                'param'     : param,
                'url'       : url,
                'target'    : target,
                'play'      : play,
                'pixel'     : pixel,
                'container' : mcContainer,
                'type'      : mcType
            }
        );

        if(mcType != '' && mcContainer != '')
        {
            ajax_call('masscast', 'get_' + mcType, args.toJSON(), DM_MassCast.callback);
        }
    },
    transfer: function()
    {
        var html = window.frames["mc_frame"].document.body.innerHTML;
        $("mc_frame").remove();
        html = html.substr(1); // remove the 't' inserted at the top of the iframe, see below
        $('mc_' + dm_write_position).update(html);
    },
    renderFromPlayer: function(position, code)
    {
        if(code.substring(0, 11) != 'DM_MassCast')
        {
            timer = null;
            dm_write_position = position;
            var iframe = '<iframe name="mc_frame" id="mc_frame" scrolling="no" frameborder="0" width="0" height="0" style="visibility: hidden"></iframe>';

            $('mc_' + position).insert({top: iframe});

            if(!DM_MassCast.loaded)
            {
                Event.observe(window, 'load', function(e)
                {
                    document.writeold = document.write;
                    document.write = function(text)
                    {
                        clearTimeout(timer);
                        window.frames["mc_frame"].document.write(text);
                        timer = setTimeout(DM_MassCast.transfer, 500);
                    };
                    // write a character to activate the body in the iframe, doesn't work when only html tags are inserted, weird bug
                    document.write('t'); 
                    DM_MassCast.activateContent($('mc_' + position).parentNode.parentNode, true);
                    eval(code);
                });
            }
            else
            {
                document.writeold = document.write;
                document.write = function(text)
                {
                    clearTimeout(timer);
                    window.frames["mc_frame"].document.write(text);
                    timer = setTimeout(DM_MassCast.transfer, 500);
                };
                // write a character to activate the body in the iframe, doesn't work when only html tags are inserted, weird bug
                document.write('t');
                DM_MassCast.activateContent($('mc_' + position).parentNode.parentNode, true);
                eval(code);
            }
            return;
        }
        
        var tempCode = code.gsub(/document\.write\(\'(.*?)\'\);/, "#{1}");
        
        tempCode = tempCode.gsub(/'\s*\+\s*'/, '');

        var regex = /<script.*?src="(.*?)".*?<\/script>/i;

        if(regex.match(tempCode))
        {
            var script_source = RegExp.$1;
            
            if(!DM_MassCast.loaded)
            {
                Event.observe(window, 'load', function(e)
                {
                    document.writeold = document.write;
                    document.write = DM_MassCast.write;

                    dm_write_position = position;

                    $('mc_' + position).insert(new Element("script", { src: script_source }));
                    DM_MassCast.activateContent($('mc_' + position).parentNode.parentNode, true);
                });
            }
            else
            {
                document.writeold = document.write;
                document.write = DM_MassCast.write;

                dm_write_position = position;

                $('mc_' + position).insert(new Element("script", { src: script_source, type: "text/javascript", defer: "defer"}));
                DM_MassCast.activateContent($('mc_' + position).parentNode.parentNode, true);
            }

            return;
        }
        else
        {
            var transformedCode = "var mc_str = '';\n";

            var tempCode = code.gsub(/document\.write\(\'(.*?)\'\);/, "mc_str += '#{1}';\n");

            transformedCode += "\n" + tempCode;

            if(tempCode != code)
            {
                transformedCode += "\n" + "$('mc_" + position + "').update(mc_str);\n";
            }

            transformedCode = '<script>' + "mcType='video_player'; mcContainer='" + position + "';" + transformedCode + "</script>";

            $('mc_' + position).update(transformedCode);
            DM_MassCast.activateContent($('mc_' + position).parentNode.parentNode);
        }
    },
    callback : function(json)
    {
        var data = json.evalJSON();
        var content = data.content;

        $('mc_' + data.container).update(content);
        
        if(data.title && $('mc_title'))
        {
            var title = '';
            
            if($('mc_title').hasClassName('mc_vertical_title'))
            {
                for(var i = 0; i < data.title.length; i++)
                {
                    title += data.title.charAt(i) + '<br>';
                }
            }
            else
            {
                title = data.title;
            }
            $('mc_title').update(title);
        }

        $('mc_' + data.container).onclick = function()
        {
            if(data.url != '')
            {
                window.open(data.url, data.target);
            }
            return false;
        };

        var container = $('mc_' + data.container);

        while(!container.hasClassName('mc_container'))
        {
            container = $(container.parentNode);
        }

        DM_MassCast.activateContent(container);
    },
    loadSecondCall: function()
    {
        var container = $$('div.dm_widget_advert_iabrighttitle').first();
        var children = container.childElements();

        // We hit the "close ad" button, do nothing
        if (children.length == 0)
        {
            return;
        }

        container.setStyle({height: '258px'});

        if (DM_MassCast.isAdInIframe == false)
        {
            children[0].id = 'ad_to_be_removed';
            var elToFade = children[0];
            var elToAppear = children[1];
        }
        else
        {
            if(children[0].visible())
            {
                var elToFade = children[0];
                var elToAppear = children[1];
            }
            else
            {
                var elToFade = children[1];
                var elToAppear = children[0];
            }
        }

        elToAppear.src = '/middle?call=' + DM_MassCast.secondCall.gsub(
                '/[0-9]*@Middle',
                Math.floor(Math.random()*100000) + '@Middle');

        Event.observe(elToAppear, 'load', function()
        {
            if(DM_MassCast.enableCrossFade == true)
            {
                new Effect.Fade(elToFade, { duration: DM_MassCast.crossFadeDuration });
                new Effect.Appear(elToAppear, { duration: DM_MassCast.crossFadeDuration });
            }
            else
            {
                elToFade.setStyle({display: 'none'});
                elToAppear.setStyle({display: 'block'});
            }

            // We didn't yet remove the div,
            // let's do it and tell our application we did.
            if (DM_MassCast.isAdInIframe == false)
            {
                if(DM_MassCast.enableCrossFade == true)
                {
                    // After the cross fade has finished, remove the div element
                    setTimeout('$(\'ad_to_be_removed\').remove()',
                            DM_MassCast.crossFadeDuration * 1000);
                }
                else
                {
                    $('ad_to_be_removed').remove();
                }

                DM_MassCast.isAdInIframe = true;
            }
        });
    },
    setPeriodicalExecuterStopped: function(bool)
    {
        DM_MassCast.isPeriodicalExecuterStopped = bool;
    },
    initialize: function()
    {
        Event.observe(window, 'load', function()
            {
                $$('div.mc_container').each(
                    function(element)
                    {
                        DM_MassCast.activateContent(element);
                    }
                );

                // massCastDoSecondCall is defined in the ad server
                if(DM_MassCast.doSecondCall == true && DM_MassCast.reloadTime > 0 &&
                    (typeof massCastDoSecondCall == 'undefined' || massCastDoSecondCall == true))
                {
                    setTimeout('DM_MassCast.setPeriodicalExecuterStopped(true)',
                        DM_MassCast.reloadMaxDuration * 1000);

                    new PeriodicalExecuter
                    (
                        function(pe)
                        {
                            if(DM_MassCast.isPeriodicalExecuterStopped == true)
                            {
                                pe.stop();
                            }
                            DM_MassCast.loadSecondCall();
                        },
                        DM_MassCast.reloadTime
                    );
                }
            }
        );
    },
    activateContent: function(item, force)
    {
        force = (force | false);
        
        item = $(item);
        var found = false;

        if (item.id && (item.id == 'mc_Middle' || item.id == 'mc_Left' || item.id == 'mc_Right'))
        {
            $A(item.childNodes).each(
                function(child)
                {
                    if(force || (child.nodeType != 3 && child.tagName != "SCRIPT" && !(child.tagName == "DIV" && child.id == 'mc_title')))
                    {
                        $(item).setStyle({display: 'inline', visibility: 'visible'});
                        found = true;
                    }
                }
            );
        }
        else
        {
            item.descendants().each
            (
                function(element)
                {
                    if(element.id && (element.id == 'mc_Middle' || element.id == 'mc_Left' || element.id == 'mc_Right'))
                    {
                        $A(element.childNodes).each(
                            function(child)
                            {
                                if(force || (child.nodeType != 3 && child.tagName != "SCRIPT" && !(child.tagName == "DIV" && child.id == 'mc_title')))
                                {
                                    $(element).setStyle({display: 'inline', visibility: 'visible'});
                                    found = true;
                                }
                            }
                        );
                    }
                }
            );
        }
        if(found)
        {
            item.setStyle({display: 'inline', visibility: 'visible'});
        }
/*        else
        {
            if($(item.parentNode) && $(item.parentNode).hasClassName('removable'))
            {
                $(item.parentNode).setStyle({display:'none'});
            }
        }*/
        EventSelectors.start(DM_MassCast.rules);
    },
    
    renderYAHOO: function(container)
    {
        function escapeDoubleQuotes(s)
        {
            var str = String(s);

            return str.replace(/"/g, '&quot;');
        }
        if(typeof(zSr)!="undefined" && zSr != null)
        {
            var k;
            var html = '<div class="advert_yahoo background">';

            for(k=6; (k < zSr.length); k += 6)
            {
                html += ('<div class="yahoo_block_ad"><a class="label" href="'+zSr[k+2]+'" target="_blank" class="advert" title="'+escapeDoubleQuotes(zSr[k] + ' - ' + zSr[k+4])+'">'+zSr[k+3]+'</a><br>' );

                array_tmp = zSr[k].split(' ');
                nb_words = array_tmp.length;    

                if(nb_words > 15)
                {
                    html += ('<div class="foreground ad_desc"><a href="'+zSr[k+2]+'" target="_blank">');
                    i_tmp=0;

                    array_tmp.each(function(item)
                    {
                        if(i_tmp<15) html += (item+" ");
                        i_tmp++;
                    });

                    html += ('...</a></div>' );
                }
                else
                {
                    html += ('<div class="foreground ad_desc"><a href="'+zSr[k+2]+'" target="_blank">'+ zSr[k] + '</a></div>' );
                }
                html += ( '<a href="'+zSr[k+2]+'" target="_blank" class="tag">' + zSr[k+4] + '</a></div>' );
            }
            html += '</div>';
            $('mc_' + container).innerHTML = html;
        }
    },

    loadScript: function(url, callback) {
    	var script = document.createElement('script');
    	script.type = 'text/javascript';
    	if (callback)
    		script.onload = script.onreadystatechange = function() {
    			if (script.readyState && script.readyState != 'loaded' && script.readyState != 'complete')
    				return;
    			script.onreadystatechange = script.onload = null;
    			callback();
    		};
    	script.src = url;
    	document.getElementsByTagName('head')[0].appendChild(script);
    }
};
DM_MassCast.initialize();

Event.observe(window, 'load', function(){ DM_MassCast.loaded = true;});
var yahoo_source = "";
var yahoo_maxCount = "";
var yahoo_type = "";
var yahoo_ctxtId = "";
var yahoo_ctxtUrl = "";
var yahoo_ctxtKeywords= "";

var banner_yahoo_source = "";
var banner_yahoo_maxCount = "";
var banner_yahoo_type = "";
var banner_yahoo_ctxtId = "";
var banner_yahoo_ctxtUrl = "";
var banner_yahoo_ctxtKeywords= "";
