
var mochilaWidget = function(type, params, returnHTML) {
    // Set up badge counter to allow for use of duplicate badges.
    if(typeof mochilaWidgetBadgeCounter == 'undefined') {
        mochilaWidgetBadgeCounter = 0; // Needs to be global, so don't use var.
    }

    // this is the function that does some kinda token replacement within the template of params in the form "#{foobar}"
    var mochilaEval = function(template,params) {
        var match;var compiled = [];
        while (template.length > 0) {
            if (match = template.match(/(^|.|\r|\n)(#\{(.*?)\})/)) {
                compiled.push(template.slice(0, match.index));
                compiled.push(match[1] || '');
                var list = match[3].split(/\.|\[|\]\[|\]\.|\]/);
                if (!list[list.length-1]) list.pop();
                compiled.push(params[list]);
                template = template.slice(match.index + match[0].length);
            } else {
                compiled.push(template), template = '';
            }
        }
        return compiled.join("");
    };
    
    // look for the value of the given name in window's URL query params
    var gup = function( name ) {
        var results = (new RegExp("[\\?&]"+name+"=([^&#]*)")).exec(window.location.href);
        if ( results == null ) {return ""}
        else {return results[1]}
    };
    
    var getExtraParamsFromURL = function(urlParams) {
        var p = urlParams.split(',');
        var e = '';
        for (var i = 0; i < p.length; i++) {
            e+='&'+p[i]+'='+gup(p[i]); 
        };
        return e;
    };
    
    var toQueryString = function(queryObj) {
        var params=[];
        for (var property in queryObj){
            params.push(property+'='+queryObj[property]);
        };
        return params.join('&');
    };

    
    
    
    // default server url
    params.extraParams=params.extraParams||'';
    
    params.server='http://admatch-syndication.mochila.com';

    var codeTemplate = '';
    
    /*
      CASE BADGE :
      example usage :
      mochilaWidget('badge',{
          buid:1,
          templateid:10318,
          dest:214,
          buyerId:'MochilaShowCase',
          channelId:748
      });
    */
    
    if (type=='badge') {
        if (typeof params.txtSearch !='undefined') {
            var searchObj = {
                txtSearch      : params.txtSearch,
                types          : params.types || 'LTIV',
                license        : 'A',
                sort           : params.sort || 'D',
                collections    : params.collections || '',
                relateAsset    : params.relateAsset || '',
                category       : params.category || ''
            };
            params.channelId=9999;
            params.extraParams += toQueryString(searchObj);
        };
        params.badgeCounter = mochilaWidgetBadgeCounter;
        params.widgetClass = gup('widgetClass');

        // Check for existence of identical badge.
        var currentBadgeId = mochilaEval("mBC_mmm#{buid}_#{templateid}_#{dest}_#{channelId}", params);
        if(typeof document.getElementById(currentBadgeId) != 'undefined') {
            mochilaWidgetBadgeCounter++;
        }
        var codeTemplate ='<div><div id="mBC_mmm#{buid}_#{templateid}_#{dest}_#{channelId}_#{badgeCounter}"><span> ... </span></div>    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"              id="explorer_#{buid}_#{templateid}_#{dest}_#{channelId}_#{badgeCounter}" style="display:block; height:0; overflow:hidden" width="0" height="0" codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab"><param name="movie" value="#{server}/public/loader.swf" /><param name="flashVars" value="buid=#{buid}&tid=#{templateid}&dest=#{dest}&bid=#{buyerId}&chid=#{channelId}&articleTemplateId=#{articleTemplateId}&badgeTemplateId=#{badgeTemplateId}&widgetClass=#{widgetClass}&badgeCounter=#{badgeCounter}&poweredByProtected=true&#{extraParams}" /><param name="allowScriptAccess" value="always" /><embed src="#{server}/public/loader.swf"               width="0" height="0" name="explorer" flashVars="buid=#{buid}&tid=#{templateid}&dest=#{dest}&bid=#{buyerId}&chid=#{channelId}&articleTemplateId=#{articleTemplateId}&badgeTemplateId=#{badgeTemplateId}&widgetClass=#{widgetClass}&badgeCounter=#{badgeCounter}&poweredByProtected=true&#{extraParams}"               play="true"               allowScriptAccess="always"               type="application/x-shockwave-flash"               pluginspage="http://www.adobe.com/go/getflashplayer"></embed></object></div><div align="center" class="badgePower" style="width:150px;"><div style="margin-top: 2px; margin-bottom: 5px;"><a href="http://www.mochila.com" id="mmm#{buid}_#{templateid}_#{dest}_#{channelId}_#{badgeCounter}PoweredBy" target="_blank">Powered by Mochila</a></div></div>';
    };
    /*
    CASE SLIDESHOW (REGULAR)
    example usage:
    mochilaWidget('slideshow',{
        buid:1,
        templateid:10301,
        dest:214,
        buyerId:'SnapTimes',
        channelId:10217,
        width:300, height:250,
        slideshowHeightOuter:300,
        
        //OPTIONAL PARAMS :
        allowFullScreen:false, // or true
        intertistialAd:'on', // or 'off'
        initialCount:4, // start count
        photosPerAd:5, // photos per ad
        delay:2 // seconds per photo
    });
    */
    
    /*
    CASE SLIDESHOW ( SEARH DRIVEN )
    example usage :
    mochilaWidget('slideshow',{
        buid:1,
        templateid:1,
        dest:214,
        buyerId:'MochilaShowCase',
        channelId:10217, //channel id is ignored when a slideshow is search based (txtSearch param Exists)
        width:300,
        height:300,
        slideshowHeightOuter:600, //to fit the ad
        allowFullScreen:false,
        keyword:'obama' //the widget code library checks for this param to decide if it is channel driven or search driven
    });
    */
    var addP = function(paramStr){
        if (typeof params[paramStr]!='undefined' && params[paramStr]!='') {
            return paramStr+'='+params[paramStr]+'&';
        }else{return '';}
    }
    
    if (type == 'slideshow') {
        params.extra=params.extra||'';
        params.extra = addP('initialCount')+addP('photosPerAd')+addP('delay')+addP('showCarousel');
        
        if (typeof(params.keyword) != 'undefined') {
            params.channelId = 9999;
            params.extra += 'txtSearch=' + params.keyword + '&license=MRA&types=LI';
        } 
        
        if (typeof params.allowFullScreen!='undefined' && params.allowFullScreen) {
            params.extra+='&allowFullScreen=true';
        };
        
        if (typeof params.autoPlay!='undefined' && params.autoPlay) {
            params.extra+='&autoPlay=true';
        };
        
        if (params.templateid!=10301){
            params.slideshowWidthOuter = params.width + 14;
            //view is to prevent slideshowIntAd and slideshow both calling the same xsl file and messing up the layout
            params.view = '/viewer/channel/slideshowIntAd?';
        }else{
            // this is for 300px no padding slideshows.
            params.slideshowWidthOuter = params.width;
            // params.view = '/viewer/channel/badgex?asHtml=true&';
            params.view = '/public/slideshow/ssia300.html?';
        }
        
        if (typeof params.intertistialAd!='undefined' && params.intertistialAd=='off') {
            params.view = '/viewer/channel/slideshow?';
        };
        
        params.slideshowWidthInner = params.width;
        params.slideshowHeightInner = params.height;
        
        var codeTemplate ='<iframe name="mochilaSlideshow#{channelId}" id="mochilaSlideshow#{channelId}" allowtransparency="true" border="0" scrolling="no" FRAMEBORDER="0"  src="#{server}#{view}buyerId=#{buyerId}&channelId=#{channelId}&tid=#{templateid}&destination=#{dest}&buid=#{buid}&rd=1&width=#{slideshowWidthInner}&height=#{slideshowHeightInner}&#{extra}" style="width:#{slideshowWidthOuter}px;height:#{slideshowHeightOuter}px;"></iframe>'; 
    };
    
    /*
    CASE VIDEO CAROUSEL PLAYER ( TWISTAGE PLAYER)
    example usage:
    mochilaWidget('videoPlayer',{
        buid:4161,
        templateid:1,
        dest:214,
        buyerId:'topixcom',
        channelId:2876,
        width:320,   //maximum 400, minimum 250
        height:650   //height to accomedate the ad
    });
    */
    
    /*
    CASE VIDEO CAROUSEL PLAYER ( FLOW PLAYER)
    example usage:
    mochilaWidget('videoPlayer',{
        buid:4161,
        templateid:1,
        dest:214,
        buyerId:'topixcom',
        channelId:2876,
        randomize:'true',
        width:320,   //maximum 400, minimum 250
        height:650,   //height to accomedate the ad
        playerType:'flowplayer'
    });
    */
    if (type=='videoPlayer') {
        var codeTemplate ='<iframe name="mochilaVideo#{channelId}" id="mochilaVideo#{channelId}" allowtransparency="true" border="0" scrolling="no" FRAMEBORDER="0"  src="#{server}/viewer/channel/videoPlayer/flowplayer?buyerId=#{buyerId}&channelId=#{channelId}&tid=#{templateid}&destination=#{dest}&buid=#{buid}&rd=1&width=#{width}&flashHeight=#{flashHeight}&#{extraParams}" style="width:#{widthOuter}px;height:#{height}px;"></iframe>';
        if (typeof params.widthOuter == 'undefined') {
          params.widthOuter = params.width;//+18;
        }else{
          params.widthOuter = params.width + params.widthOuter;
        }
        
        if (params.playerType!='') {
            params.extraParams = '&playerType='+params.playerType;
        };
        if (typeof params.randomize!='undefined') {
            params.extraParams = '&randomize='+params.randomize;
        };
        if (typeof params.viral!='undefined') {
            params.extraParams = '&viral='+params.viral;
        };
        if (typeof params.sort!='undefined') {
            params.extraParams = '&sort='+params.sort;
        };
    };

    /*
    PHOTO WALL
    example usage:
    mochilaWidget('photoWall',{
        buid:3687,
        dest:1,
        buyerId:'TheFreeLibrary',
        channelId:10222,
        mode:'big',
        category:'financial',
        keyword:'gene'
    });
    */

    if (type=='wasphotoWall') {
        var codeTemplate ='<iframe style="width:302px;height:502px;" name="' + Math.random() + '" allowtransparency="true" frameborder="0" scrolling="no"  src="#{server}/viewer/channel/badgex?buyerId=#{buyerId}&channelId=#{channelId}&tid=10131&destination=1&randomize=false&asHtml=true&buid=#{buid}&rd=1&keyword=#{keyword}&category=#{category}&mode=#{mode}"></iframe>';
    };

    if (type=='photoWall') {
        var codeTemplate ='<iframe style="width:302px;height:502px;" name="' + Math.random() + '" allowtransparency="true" frameborder="0" scrolling="no"  src="#{server}/public/widget/photoWall.html?buyerId=#{buyerId}&channelId=#{channelId}&tid=10131&destination=1&randomize=false&asHtml=true&buid=#{buid}&rd=1&keyword=#{keyword}&category=#{category}&mode=#{mode}"></iframe>';
    };
    
    /*
    CASE ASSET - can be video, photo, or article, same syntax
    example article:
    mochilaWidget('asset',{
        buid:1,
        buyerId:'SnapTimes',
        assetId:26894874,
        templateId:575
    });
    
    example single video :
    mochilaWidget('asset',{
        buid:1,
        buyerId:'SnapTimes',
        assetId:26894928,
        templateId:575
    });
    
    
    */
    // loads all asset types, uses jsp loader
    if (type=='asset') {
        var codeTemplate = '<script type="text/javascript" src="#{server}/viewer/channel/loader?template=regularArticle&buyerId=#{buyerId}&tid=#{templateId}&articleId=#{assetId}" ></script><div align="center" class="badgePower" style="width:100%;"><p style="margin-top: 2px; margin-bottom: 5px;"><a href="http://www.mochila.com" target="_blank">Powered by Mochila</a></p></div>';
    };
    

    http://admatch-syndication.mochila.com/public/article/article.xrap?stdout=yes&renderMimeType=javascript&assetId=31735642&badgeTemplateId=3&badgeDestId=1&channelId=1&buyerId=MochilaShowCase&templateId=136&buid=1
    /*
    case iframe widget
    example (healthination widget)
    mochilaWidget('iframe',{
                        buid:4962,
                        templateId:10464,
                        dest:1,
                        buyerId:'HealthiNationcom',
                        channelId:10673,
                        
                        // URLParamsToPass:'articleId,channelId' <- optional comma seperated list of params that passed from the window url to the iframe widget src
                        // this can be useful for embedded widgets, or embedded articles inside skinned iframes
                        
                        width:300,
                        height:580
                    });
    */
    
    if (type=='iframe') {
        params.scrolling = (typeof(params.scrolling)!='undefined')?params.scrolling:'no';
        var codeTemplate = '<iframe style="width:#{width}px;height:#{height}px;" name="' + Math.random() + '" allowtransparency="true" frameborder="0" scrolling="#{scrolling}" src="#{server}/viewer/channel/badgex?asHtml=true&buyerId=#{buyerId}&channelId=#{channelId}&tid=#{templateId}&destination=#{dest}&randomize=false&buid=#{buid}&rd=1&#{extraParams}&cachebust=' + Math.random() +'"></iframe><div align="center" class="badgePower" style="width:100%;"><p style="margin-top: 2px; margin-bottom: 5px;"><a href="http://www.mochila.com" target="_blank">Powered by Mochila</a></p></div>';
        
        //bug fix to prevent articles from loading the wrong channel:
        
        if (typeof(params.URLParamsToPass) != 'undefined' && params.URLParamsToPass.match('channelId')) {
            params.channelId = gup('channelId');
        };
        
        if (typeof(params.URLParamsToPass) != 'undefined') {
            params.extraParams += getExtraParamsFromURL(params.URLParamsToPass);
        }
        
        // special code to hack the logic when we detect that its a knot article page
        
        if (params.templateId==10491) {
            params.dest=gup('destination');
            var codeTemplate = '<iframe style="width:#{width}px;height:#{height}px;" name="' + Math.random() + '" allowtransparency="true" frameborder="0" scrolling="#{scrolling}" src="#{server}/public/article/knot/knotArticle1.xrap?asHtml=true&buyerId=#{buyerId}&channelId=#{channelId}&tid=#{templateId}&destination=#{dest}&randomize=false&buid=#{buid}&rd=1&#{extraParams}&cachebust=' + Math.random() +'"></iframe><div align="center" class="badgePower" style="width:100%;"><p style="margin-top: 2px; margin-bottom: 5px;"><a href="http://www.mochila.com" target="_blank">Powered by Mochila</a></p></div>';
        };
        if (params.templateId==10493) {
            params.dest=gup('destination');
            var codeTemplate = '<iframe style="width:#{width}px;height:#{height}px;" name="' + Math.random() + '" allowtransparency="true" frameborder="0" scrolling="#{scrolling}" src="#{server}/public/article/knot/knotArticle2.xrap?asHtml=true&buyerId=#{buyerId}&channelId=#{channelId}&tid=#{templateId}&destination=#{dest}&randomize=false&buid=#{buid}&rd=1&#{extraParams}&cachebust=' + Math.random() +'"></iframe><div align="center" class="badgePower" style="width:100%;"><p style="margin-top: 2px; margin-bottom: 5px;"><a href="http://www.mochila.com" target="_blank">Powered by Mochila</a></p></div>';
        };
    };
    
    /*
        generic iframe
        example usage:
        mochilaWidget('genericIframe',{
            width:300,
            height:300,
            src:'http://mochila.com'
        })
    */
    
    if (type=='genericIframe') {
        var codeTemplate = '<iframe style="width:#{width}px;height:#{height}px;" name="'+Math.random()+'" allowtransparency="true" frameborder="0" scrolling="no" src="#{src}"></iframe>';
        if (typeof(params.URLParamsToPass)!='undefined') {
            params.extraParams+=getExtraParamsFromURL(params.URLParamsToPass);
        }
        
    };
    
    /*
        embedded loader - same as the asset / slideshow embedded loader
        
        mochilaWidget('embedded',{
            buid:1,
            buyerId:'SnapTimes',
            destination:1
        });
    */
    
    if (type == 'embedded') {
        params.articleId  = gup('articleId');
        params.channelId  = gup('channelId');
        params.assetClass = gup('assetClass');
        metas = document.getElementsByTagName('meta');
        for (i = 0; i < metas.length; i++) {
            if (metas[i].getAttribute('http-equiv') == 'Content-Type' || metas[i].getAttribute('httpequiv') == 'Content-Type') {
                var charset = metas[i].getAttribute('content');
                var charset2 = charset.substr(charset.search('charset='),charset.length - charset.search('charset='));
            }
        }
        // for backwards compatability with the mygirlyspace embedded slideshow hack.
        if(params.assetClass == "slideshow"){
            var codeTemplate = "<scr"+"ipt type=\"text/javascript\" src=\"http://twistage.mochila.com/api/script\"></scr"+"ipt><div id=\"mochila\" style='' align='center'><iframe width='330' height='567' scrolling='no' frameborder='0' src=\"#{server}/viewer/channel/slideshowIntAd?buid=#{buid}&tid=#{templateId}&destination=#{destination}&buyerId=#{buyerId}&channelId=#{channelId}&articleId=#{articleId}&mche="+Math.random()+"&"+charset2+"\">"+"</iframe></div>";
        }else{  
            var codeTemplate = "<scr"+"ipt type=\"text/javascript\" src=\"http://twistage.mochila.com/api/script\"></scr"+"ipt><div id=\"mochila\"><script type=\"text/javascript\" src=\"#{server}/viewer/article?buyerId=#{buyerId}&channelId=#{channelId}&tid=#{templateId}&articleId=#{articleId}&mche="+Math.random()+"&"+charset2+"\">"+"</script></div>";
        }
    }; 
    

    
    // this function checks if a param declared in the params obj, if it is, returns it
    // if not, it looks in the URL to see if its defined,
    // if not, it looks in a defaults object to see if its defined
    // if not, it returns a hard coded default value
    
    var detectParam = function(name,defaultValue) {
        if (typeof params[name]!='undefined') {
            // console.log(name+' found in params obj, value ='+params[name]);
            return params[name];
        }else{
            var value = gup(name);
            if (value!='') {
                // console.log(name+' found in URL, value ='+value);
                return value;
            }else{
                if (typeof params.defaults!='undefined' && typeof params.defaults[name]!='undefined') {
                    // console.log(name+' found in defaults obj, value ='+params.defaults[name]);
                    return params.defaults[name];
                }else{
                    // console.log(name+' not found anywhere, default value ='+defaultValue);
                    return defaultValue;
                }
            }
        }
    };
    
    /*
        EXAMPLE MOCHILA NEW EMBEDDED LOADER
        mochilaWidget('embeddedLoader',{
            buyerId:'SnapTImes'           // optional, overrides URL params
            defaults:{                    // optional params obj
                buyerId:'MochilaShowCase' // also optional - default fallback value if not found in URL
            }
        });
    */
    
    if (type=='embeddedLoader') {

        params.assetId         = detectParam('articleId'        ,31735642    );     // default is some article about Gustav
        params.badgeTemplateId = detectParam('badgeTemplateId'  ,10541       );     // generic grey badge
        params.badgeDestId     = detectParam('badgeDestId'      ,3           );     // 3 is poweredbymochila.com
        params.channelId       = detectParam('channelId'        ,2524        );     
        params.buyerId         = detectParam('buyerId'          ,'SnapTimes' );     
        params.templateId      = detectParam('templateId'       ,136         );     // default snaptimes style
        params.buid            = detectParam('buid'             ,1           );     // snaptimes
        
        var codeTemplate = (
            '<script type="text/javascript" src="'   +
            '#{server}/public/article/article.xrap?' +
            'stdout=yes&renderMimeType=javascript&'  +
            'assetId=#{assetId}&'                    +
            'badgeTemplateId=#{badgeTemplateId}&'    +
            'badgeDestId=#{badgeDestId}&'            +
            'channelId=#{channelId}&'                +
            'buyerId=#{buyerId}&'                    +
            'templateId=#{templateId}&'              +
            'buid=#{buid}" >'                        +
        '</script>');
        
        // powered by mochila
        
        // this commented out, because of IE script order bug
        
        // '<div align="center" class="badgePower" style="width:100%;">'+
        //     '<p style="margin-top: 2px; margin-bottom: 5px;">'+
        //         '<a href="http://www.mochila.com" target="_blank">Powered by Mochila</a>'+
        //     '</p>'+
        // '</div>'

    };
    

    /*
        EXAMPLE MOCHILA STAND ALONE AD
        mochilaWidget('mochilaAd',{
            buyerId : "SnapTimes",
	        assetId : "",
	        channelId: "1",
	        at: "11",
            otype: "xhtml",
            width:300,
            height:250
        });
    */

    if (type=='mochilaAd') {
                params.src = params.server+'/viewer/rad?buyerId='+params.buyerId+'&assetId='+params.assetId+'&channelId='+params.channelId+'&at='+params.at+'&otype='+params.otype;
                var codeTemplate = '<iframe style="width:#{width}px;height:#{height}px;" name="'+Math.random()+'" allowtransparency="true" frameborder="0" scrolling="no" src="#{src}"></iframe>';
    };

    /*
    EXAMPLE ADSENSE USAGE:
    (should work for any widget)
    mochilaWidget('badge',{
        buid:1,
        templateid:10318,
        dest:214,
        buyerId:'MochilaShowCase',
        channelId:748,
        
        // add the following section at the end of the params when loading a mochila widget
        
        useGoogleAdsense : true,                   //this tells the mochila widget loader to use adsense
        google_ad_client : 'pub-4266006243526887', //these are the params we pass to google
        google_ad_slot   : "2440944978",
        google_ad_width  : 234,
        google_ad_height : 60,
        
        // add the following section at the end of the params to make a pixel call
        
        makePixelCall : true,                   //this tells the mochila widget loader make a pixel call
        pixelSRC:'http://admatch-syndication.mochila.com/images/ad.gif?mtyp=logassetview&buyerId=1&assetId=&channelId=2&mche='+Math.random()
    }); 
    */
    
    /*
    EXAMPLE STAND ALONE GOOGLE AD -> adding to the end of the widget
    mochilaWidget('none',{ // notice the none
        useGoogleAdsense : true,                   //this tells the mochila widget loader to use adsense
        google_ad_client : 'pub-4266006243526887', //these are the params we pass to google
        google_ad_slot   : "2440944978",
        google_ad_width  : 234,
        google_ad_height : 60,

        // add the following section at the end of the params to make a pixel call
        makePixelCall : true,
        pixelSRC:       'http://admatch-syndication.mochila.com/images/ad.gif?mtyp=logassetview&buyerId=1&assetId=&channelId=2&mche='
    });
    
    */
    
    
    
    // checks if google adsense was requested, if it was, appends the google adsense code at the end of our mochila code,
    // and sets the variables for google to read
    if (typeof(params.useGoogleAdsense) != 'undefined' && params.useGoogleAdsense) {
        window.google_ad_client = params.google_ad_client ;
        window.google_ad_slot   = params.google_ad_slot   ;
        window.google_ad_width  = params.google_ad_width  ;
        window.google_ad_height = params.google_ad_height ;
        codeTemplate += '<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>';
    };
    
    
    if (typeof(params.makePixelCall) != 'undefined' && params.makePixelCall) {
        codeTemplate += '<img src="' + params.pixelSRC+ '"/>' ;
    };
    

    // console.log(params);
    //     console.log(codeTemplate);
    
    var widgetCode = mochilaEval(codeTemplate,params);
    
    if (typeof returnHTML!=undefined && returnHTML) {
        return widgetCode;
    }else{
        // SPECIAL CASE: Serve special IDG touts to Chicago Trib & LA Times
        var lhref = location.href;
        var OAS_rn = new String (Math.random());
        var OAS_rns = OAS_rn.substring (2, 11);

        if (params.channelId == 13132 && lhref.indexOf('http://www.chicagotribune.com/business') != -1){
            mbuyerId='ChicagoTribune323355';
            mchannelId = '13360';
            massetId = '0';
            document.write('<scr'+'ipt LANGUAGE="JavaScript1.1" SRC="http://oads.mochila.com/openx/www/delivery/ajs.php?source=mochila_live&zoneid=36&mmadsize=300_140&buyerId=ChicagoTribune323355&channelId=13360&category=9&at=57&adnw=0&cb='+OAS_rns+'"></scr'+'ipt>');
        }
        else  if (params.channelId == 13132 && lhref.indexOf('http://www.chicagotribune.com/') != -1) {
            mbuyerId='ChicagoTribune323355';
            mchannelId = '13361';
            massetId = '0';
            document.write('<scr'+'ipt LANGUAGE="JavaScript1.1" SRC="http://oads.mochila.com/openx/www/delivery/ajs.php?source=mochila_live&zoneid=37&mmadsize=300_140&buyerId=ChicagoTribune323355&channelId=13361&category=9&at=57&adnw=0&cb='+OAS_rns+'"></scr'+'ipt>');
        } // END SPECIAL CASE.
        else {
            document.write(widgetCode);
        }
    }
    
};

/*
    DOCUMENTATION FOR MOCHILA COMPOUND WIDGET :
    
    example horizontal 2 widget layout (one ad , one slideshow):
    
    new mochilaCompoundWidget({
        layout:'horizontal',width:600,
        widget1:{
            type:'badge',
            params:{
                buid:2591, 
                templateid:10505, 
                dest:1077, 
                buyerId:'MyGirlySpacecom', 
                channelId:2619
            }
        },widget2:{
            type:'slideshow',
            params:{
                buid:1,
                templateid:10301,
                dest:214,
                buyerId:'SnapTimes',
                channelId:10217,
                width:300, height:250,
                slideshowHeightOuter:300,

                //OPTIONAL PARAMS :
                allowFullScreen:false,
                intertistialAd:'on', // or 'off'
                initialCount:4,
                photosPerAd:5,
                delay:2
            }
        }
    });
    
    
    example vertical 2 widget layout (one badge one slideshow) :
    
    new mochilaCompoundWidget({
        layout:'horizontal',width:600,
        widget1:{
            type:'mochilaAd',
            params:{
                 buyerId:"SnapTimes",
                 assetId:"",
                 channelId: "1",
                 at: "11",
                 otype: "xhtml",
                 width:300,
                 height:250
            }
        },widget2:{
            type:'slideshow',
            params:{
                buid:1,
                templateid:10301,
                dest:214,
                buyerId:'SnapTimes',
                channelId:10217,
                width:300, height:300,
                slideshowHeightOuter:300,
                allowFullScreen:false,
                //these 3 params are optional
                initialCount:4,
                photosPerAd:5,
                delay:2
        }
    }});
*/

var mochilaCompoundWidget = function(obj) {
    this.initialize(obj);
    this.write();
    return this;
};

mochilaCompoundWidget.prototype = {
    initialize : function(obj) {
        var params = {
            width:obj.width
        };
        var layoutTemplate = '';
        if(obj.layout=='horizontal'){
            layoutTemplate = '<div style="position:relative;width:#{width}px" id="mochilaWrapH"><div style="float:left">#{widget1Code}</div><div style="float:left">#{widget2Code}</div></div>';
        }
        if(obj.layout=='vertical'){
            layoutTemplate = '<div style="position:relative;width:#{width}px" id="mochilaWrapV"><div>#{widget1Code}</div><br/><div>#{widget2Code}</div></div>';
        }
        if (obj.layout=='floatRight') {
            layoutTemplate = '<div><div style="float:right;padding:5px">#{widget2Code}</div>#{widget1Code}</div>';
        };
        if (obj.layout=='floatLeft') {
            layoutTemplate = '<div><div style="float:right;padding:5px">#{widget2Code}</div>#{widget1Code}</div>';
        };
        params.widget1Code = mochilaWidget(obj.widget1.type,obj.widget1.params,true);
        params.widget2Code = mochilaWidget(obj.widget2.type,obj.widget2.params,true);

        this.evaluatedCode = this.mochilaEval(layoutTemplate,params);
    },
    mochilaEval : function(template,params) {
        var match;var compiled = [];
        while (template.length > 0) {
            if (match = template.match(/(^|.|\r|\n)(#\{(.*?)\})/)) {
                compiled.push(template.slice(0, match.index));
                compiled.push(match[1] || '');
                var list = match[3].split(/\.|\[|\]\[|\]\.|\]/);
                if (!list[list.length-1]) list.pop();
                compiled.push(params[list]);
                template = template.slice(match.index + match[0].length);
            } else {
                compiled.push(template), template = '';
            }
        }
        return compiled.join("");
    },
    write : function() {
        document.write(this.evaluatedCode);
    },
    gup :  function( name ) {
        var results = (new RegExp("[\\?&]"+name+"=([^&#]*)")).exec(window.location.href);
        if ( results == null ) {return ""}
        else {return results[1]}
    }
};

/*
    DOCUMENTATION FOR MOCHILA AD:
    
    example with minimal parameters:
    
    mochilaAd({buyerId:"BLNZcom",at:"20"});
*/

var mochilaAdObj = function(obj){
    this.initialize(obj);
    this.write();
    return this;
};

var mochilaAd = function(obj){
new mochilaAdObj(obj);
};

mochilaAdObj.prototype = {
    initialize : function(obj) {
        var params = {
            buyerId:obj.buyerId,
		at:obj.at,
		channelId:obj.channelId,
		assetId:obj.assetId,
		server:'http://admatch-syndication.mochila.com'
        };
        var codeTemplate = (
            '<script type="text/javascript" src="'   	+
            '#{server}/viewer/rad?' 			+
            'buyerId=#{buyerId}&'  				+
            'at=#{at}&'                		    	+
            'assetId=#{assetId}&'                    	+
            'channelId=#{channelId}" >'			+
        '</script>');
        this.evaluatedCode = this.mochilaEval(codeTemplate,params);
    },
    mochilaEval : function(template,params) {
        var match;var compiled = [];
        while (template.length > 0) {
            if (match = template.match(/(^|.|\r|\n)(#\{(.*?)\})/)) {
                compiled.push(template.slice(0, match.index));
                compiled.push(match[1] || '');
                var list = match[3].split(/\.|\[|\]\[|\]\.|\]/);
                if (!list[list.length-1]) list.pop();
                compiled.push(params[list]);
                template = template.slice(match.index + match[0].length);
            } else {
                compiled.push(template), template = '';
            }
        }
        return compiled.join("");
    },
    write : function() {
        document.write(this.evaluatedCode);
    },
    gup :  function( name ) {
        var results = (new RegExp("[\\?&]"+name+"=([^&#]*)")).exec(window.location.href);
        if ( results == null ) {return ""}
        else {return results[1]}
    }
};

