<%@ page import="java.util.*, com.opencms.flex.jsp.*,com.opencms.file.CmsObject, com.opencms.file.CmsFile" %>
<%
/*
 * @author mbutcher@grcomputing
 * @license GPL v2
 *
 * This script provides ad placement services. It may either 
 * be seeded with a particular
 * ad, or it may use a random ad.
 * 
 * PARAMETERS:
 * ad_dir: the directory in which the ads are stored. Set it
 * by passing params in from template. Example:
 * <cms:include file="../elements/ad_placement.jsp">
 *  <cms:param name="ad_dir">/matt_test/ads</cms:param>
 * </cms:include>
 *
 * PROPERTIES:
 * ad_file: the particular file that contains the ad (if this
 * is set, then ad_placement will
 *  use a particular ad instead of a random one.)
 */
CmsJspActionElement cms = new CmsJspActionElement(pageContext, request, response);

String ad_dir = request.getParameter("ad_dir");
String ad_file = cms.property("ad_file");

// test w/ hardcoded dir
//ad_dir = "/matt-test/ads/";

if (ad_dir != null && !"".equals(ad_dir)) {
    if(ad_file != null && !"".equals(ad_file) && !"null".equals(ad_file)) {
        cms.include(ad_dir + ad_file);
    } else {
        CmsObject cmso = cms.getCmsObject();
        try {
            // We have to use Cms* objects to get files that are not Pages.
            Vector fileList = cmso.getFilesInFolder(ad_dir);
            int fileListSize = fileList.size();
            if(fileListSize == 0) {
                out.println("No ads found in " + ad_dir +".<br>");
            } else {
                int rand = (int)(Math.random() * 100000);
                CmsFile f = (CmsFile)fileList.get(rand % fileListSize);
                String fname = f.getName();
                // If image, put in image tags, else include in page.
                if(fname.indexOf(".jpg") > 0 || fname.indexOf(".gif") > 0) {
                    String link = cms.link(ad_dir + fname);
                    out.println("<img src='"+link+"'><br>");
                } else cms.include(ad_dir + fname);
            }
        } catch (Exception e) {
            out.println(e.toString());
        }
    }
}

%>