function Intextad() {}

// ----------------------------------------------------------------------------
// Setup functions.
/**
 * Initialize stuff.  This function is called when the script is first included via the 'script' tag (it
 * is invoked at the end of this file.)
 */
Intextad.initOnInclude = function() {
    // Be sure to define these two first
    Intextad.i24server = Intextad.determineI24server("www.insight24.com"); // what server are we running on (default insight24.com)
    Intextad.i24BasePath = "/view/insight24/syndications/intextad/common/";
    
    Intextad.debug = (Intextad.i24server != "www.insight24.com") ;
    
    Intextad.include("keywordscanner.js");
    Intextad.include("layerpopup.js");
    Intextad.include("xml-utils.js");
    Intextad.include("query-string-utils.js");
    
    // Some settings such as paths to images & styles
    Intextad.feedLoaderURL = Intextad.i24URL("rss-feed-loader.html");
    Intextad.backgroundImg = Intextad.i24URL("frame.png");
    Intextad.closeButtonImg = Intextad.i24URL("close-btn_03.png");
    Intextad.logoImg = Intextad.i24URL("124-logo.png");
    Intextad.keywordMouseOutStyle = "cursor:pointer; text-decoration: none; border-bottom: 1px dotted red";
    Intextad.keywordMouseOverStyle = "background-color: #FFEBCC; cursor:pointer; text-decoration: none; border-bottom: 1px dotted red";
    Intextad.iframeWidth = 339;
    Intextad.iframeHeight = 365;
    Intextad.defaultWebcastCount = 5;
    Intextad.onMouseOver = "Intextad.keywordMouseOver('##KEYWORD_MATCH##')";
    Intextad.onMouseOut = "Intextad.keywordMouseOut('##KEYWORD_MATCH##')";
    Intextad.onClick = "Intextad.keywordClicked('##KEYWORD_MATCH##')";
    Intextad.popupShowDelay = 1200;
    Intextad.popupHideDelay = 600;
    Intextad.defaultStartTag = 'body';
    
    // State
    Intextad.keywordsXML;
    Intextad.startTag = null;
    Intextad.selectedKeyword = ""
}

/**
 * This does initialization that is needed after the page has loaded.
 */
Intextad.initOnPageLoad = function(startTagID) {
    Intextad.startTag = tryToFindTag(startTagID, Intextad.defaultStartTag);
    
    if (!Intextad.startTag) {
	Intextad.debugMsg("Can't locate the startTagID on this page (" + startTagID + ")");
	return false;
    }
    
    // These definitions allow keywordsXML to be used like: keywordsXML.getKeywordList(), etc
    Intextad.keywordsXML = new XMLObject();
    XMLObject.defineMultiValueExtractor(Intextad.keywordsXML, "getKeywordList", "//keyword/text()");
    XMLObject.defineMultiValueExtractor(Intextad.keywordsXML, "getTopicList", "//topic/text()");
    //XMLObject.defineMultiValueExtractor(Intextad.keywordsXML, "getTopicsForKeyword", "//topic[translate(ancestor::mapping/keyword, 'abcdefghijklmnopqrstuvwxyz ','ABCDEFGHIJKLMNOPQRSTUVWXYZ ') = translate('##PARAM_0##', 'abcdefghijklmnopqrstuvwxyz ','ABCDEFGHIJKLMNOPQRSTUVWXYZ ')]/text()");
    XMLObject.defineMultiValueExtractor(Intextad.keywordsXML, "getTopicsForKeyword", "//topic[ancestor::mapping/keyword = '##PARAM_0##']/text()");
    XMLObject.defineSingleValueExtractor(Intextad.keywordsXML, "getAltTopicForKeyword", "//alt-topic[ancestor::mapping/keyword = '##PARAM_0##']/text()");
    XMLObject.defineSingleValueExtractor(Intextad.keywordsXML, "getWebcastDisplayCount", "//webcast-display-count/text()", function(count) { return (count != '') ? count : Intextad.defaultWebcastCount; } );
    XMLObject.defineSingleValueExtractor(Intextad.keywordsXML, "getRssFeedURL", "//rss-feed-url/text()"); 
    XMLObject.defineSingleValueExtractor(Intextad.keywordsXML, "getPartnerRef", "//partner-ref/text()"); 
    XMLObject.defineSingleValueExtractor(Intextad.keywordsXML, "getWebcastURL", "//webcast-target-url/webcast/text()");
    XMLObject.defineSingleValueExtractor(Intextad.keywordsXML, "getRegistrationURL", "//webcast-target-url/registration/text()");	
    XMLObject.defineSingleValueExtractor(Intextad.keywordsXML, "getMaxHitsPerPage", "//max-hits-per-page/text()", function(maxHitsPerPage) { return maxHitsPerPage != '' ? maxHitsPerPage : -1; });

    // Initialize the LayerPopup code:
    LayerPopup.init();
    
    LayerPopup.default_window_border =
	'<div ' +
	'        style="background:url(\'' + Intextad.backgroundImg + '\'); ' +
	'            height: 472px; weight: 389px; ' +
	'            border-width: 0px; ' +
	'            padding: 0px; margin: 0px; ' +
	'            font-family: arial; font-weight: bold; font-size: 12pt; ' +
	'            ">' +
	'    <div style="text-align: left; padding-top: 15px; padding-left: 20px; padding-bottom: 5px"> ' +
	'        Related Content<a href="javascript:LayerPopup.hideAll();" style="position: absolute; right: 0; margin-right: 25px; padding-top: 0px"><img style="border: none;" src="' + Intextad.closeButtonImg + '" /></a> ' +
	'    </div> ' +
	'    <div style="margin-left: 21px; margin-right: 25px; margin-top: 1px; margin-bottom: 0px;"> ' +
	'        ##POPUP_CONTENT## ' +
	'    </div> ' +
	'    <div style="margin-top: 5px; margin-left: 20px; color: margin-bottom: 3px"> ' +
	'        <a href="http://www.insight24.com/"><img style="position: absolute; border: none; right: 0; padding-right: 25px; padding-top: 5px" src="' + Intextad.logoImg + '" /> ' +
	'    </div> ' +
	'</div>';
    
    return true;
}



/**
 * Scans and highlights keywords on a page.  Call this on page load
 * The keywordsXMLURL parameter should be a URL to an XML file containing
 * keywords and topics.  The startTagID should be the ID of the tag where
 * scanning should start.  If startTagID is not provided, the entire
 * document will be scanned starting at the 'body' tag.
 *
 * E.g.: <body onload="scanInsightKeywords('insight24.xml', 'mainContentDivID')>
 */
function scanInsight24Keywords(keywordsXMLURL, startTagID) {
    var ok = Intextad.initOnPageLoad(startTagID);
    
    if (!ok) {
	return;
    }
    
    if (!browserSupportsXSLT()) {
	//Intextad.debugMsg("Browser does not support client-side XSL transform.");
	return;
    }
    
    // Load list of keywords and topics from 'insight24.xml'.  Once loaded, execution continues
    // with the keywordsLoaded() function.
    loadXML(keywordsXMLURL, Intextad.keywordsLoaded);
}

/**
 * After the keywords and topics are loaded from 'insight24.xml', set things up and scan the page for keywords.
 */
Intextad.keywordsLoaded = function(keywordsXML) {
    if (keywordsXML == null || keywordsXML.responseXML == null) {
	Intextad.debugMsg("Can't load keywords xml file");
	return;
    }
    
    Intextad.keywordsXML.setXMLDoc(keywordsXML);
    var keywords = Intextad.keywordsXML.getKeywordList();
    if (!keywords) {
        Intextad.debugMsg("Keyword list was loaded but can't be initialized");
        return;
    }
    
    // Keywords already inside of an existing anchor tag will be skipped:
    var tagsToExclude = ['a'];

    // Keep track of keywords that were already matched.
    var matchedKeywords = [];


    // Whenever a keyword is encountered in 'walkDOM' this function will be called to
    // do the actualy DOM mangling to format the keyword and add popup interactivity.
    var replacementTextCallback = function(keywordMatch) {
        var lcKeywordMatch = keywordMatch.toLowerCase();

        if (!matchedKeywords[lcKeywordMatch]) {
            matchedKeywords[lcKeywordMatch] = true;

	    var replacement = DOMElement.createElement('span');
	    replacement.setAttribute('style', 'white-space: nowrap;'); 
        
	    replacement.setAttribute('onmouseover', Intextad.onMouseOver.replace('##KEYWORD_MATCH##', keywordMatch));
	    replacement.setAttribute('onmouseout', Intextad.onMouseOut.replace('##KEYWORD_MATCH##', keywordMatch));
	    replacement.setAttribute('onclick', Intextad.onClick.replace('##KEYWORD_MATCH##', keywordMatch));
            
	    var keywordEl = DOMElement.createElement('span');
	    keywordEl.setAttribute('id', Intextad.i24KeywordID(keywordMatch));
	    keywordEl.setAttribute('style', Intextad.keywordMouseOutStyle);
        
	    var magImg = DOMElement.createElement('img');
	    magImg.setAttribute('src', Intextad.i24URL('mag.png'));
	    magImg.setAttribute('style', 'border: none; float: none; padding: 0; margin: 0; cursor: pointer;');
        
	    replacement.appendChild(keywordEl);
            keywordEl.appendChild(DOMElement.createTextNode(keywordMatch));
            keywordEl.appendChild(DOMElement.createTextNode(" "));
	    replacement.appendChild(magImg);
        
            return replacement.toDOMTree();
        }
    };

    walkDOM(Intextad.startTag, keywordScanner(keywords, replacementTextCallback, tagsToExclude, Intextad.keywordsXML.getMaxHitsPerPage()));
}



// ----------------------------------------------------------------------------
// Mouse event callbacks on keywords.
/**
 * If a keyword is clicked, toggle the popup (show it if it is not visible; hide it if it is.)
 */
Intextad.keywordClicked = function(keyword) {
    Intextad.selectedKeyword = keyword;
    LayerPopup.toggle(("insight24KeywordPopup-" + keyword), Intextad.feedLoaderURL, renderPopupContent, Intextad.popupHideDelay);
} 

/**
 * If a keyword is moused over, highlight the keyword and show the popup in a few milliseconds
 */
Intextad.keywordMouseOver = function(keyword) {
    Intextad.selectedKeyword = keyword;
    XmlUtils.setElementAttribute(Intextad.i24KeywordID(keyword), 'style', Intextad.keywordMouseOverStyle);
    LayerPopup.startShowTimer(("insight24KeywordPopup-" + keyword), Intextad.feedLoaderURL, renderPopupContent, Intextad.popupShowDelay);
}

/**
 * After mouse out of a keyword, un-highlight the keyword and hide in a few seconds.
 * If the show timer was started on mouse over but the popup was not displayed yet,
 * cancel the show timer.
 */
Intextad.keywordMouseOut = function(keyword) {
    LayerPopup.stopShowTimer(("insight24KeywordPopup-" + keyword));
    XmlUtils.setElementAttribute(Intextad.i24KeywordID(keyword), 'style', Intextad.keywordMouseOutStyle);
    LayerPopup.startHideTimer(("insight24KeywordPopup-" + keyword), Intextad.popupHideDelay);
}

/**
 * This is a callback that is invoked by the LayerPopup code at the time when the
 * popup should be displayed.
 *
 * E.g.:
 * LayerPopup.toggle(("insight24KeywordPopup-" + keyword), Intextad.feedLoaderURL, renderPopupContent, 1200);
 */
function renderPopupContent(popupContentDiv, contentURL) {
    if (Intextad.selectedKeyword == null) {
	Intextad.debugMsg('keyword is null');
        return;
    }
    
    // Construct a URL to pass information to the iframe:
    var topics = Intextad.keywordsXML.getTopicsForKeyword(Intextad.selectedKeyword.toLowerCase());
    contentURL += ('?' + constructQueryString('topic', topics) 
		   + constructQueryString('count', Intextad.keywordsXML.getWebcastDisplayCount())
		   + constructQueryString('rssfeed', Intextad.keywordsXML.getRssFeedURL())
		   + constructQueryString('webcastURL', Intextad.keywordsXML.getWebcastURL())
		   + constructQueryString('registrationURL', Intextad.keywordsXML.getRegistrationURL())
                   + constructQueryString('altTopic', Intextad.keywordsXML.getAltTopicForKeyword(Intextad.selectedKeyword.toLowerCase()))
                   + constructQueryString('partnerRef', Intextad.keywordsXML.getPartnerRef()));
    
    var popupContent = document.createElement('iframe');
    popupContent.setAttribute('src', contentURL);
    popupContent.setAttribute('width', Intextad.iframeWidth);
    popupContent.setAttribute('height', Intextad.iframeHeight);
    popupContent.setAttribute('border', "0");
    popupContent.setAttribute('frameborder', "0");
    popupContent.setAttribute('style', 'width: ' + Intextad.iframeWidth + ' px; height: ' + Intextad.iframeHeight + ' px; padding: 0; margin: 0;');
    popupContentDiv.appendChild(popupContent);
}


// ----------------------------------------------------------------------------
// Some utility functions
/**
 * Makes a unique ID for a keyword that can be used to tag the keyword for future reference.
 */
Intextad.i24KeywordID = function(keyword) {
    return 'i24Keyword-' + keyword;
}

/**
 * This grabs the insight24 server from the <script> tag that includes this file if that
 * tag is labeled with the ID 'i24intextad'.  Otherwise the server is set to production
 * 'www.insight24.com'
 */
Intextad.determineI24server = function(defaultServer) {
    var i24server = null;
    var i24ScriptIncludeTag = document.getElementById('i24intextad');
    if (i24ScriptIncludeTag) {
	var scriptSrc = i24ScriptIncludeTag.getAttribute("src");
	if (scriptSrc != null && scriptSrc.indexOf("/intextad/") != -1) {
	    i24server = Intextad.parseServerFromURL(scriptSrc, defaultServer);
	}
    }
    return (i24server) ? i24server : defaultServer;
}

/**
 * Takes 'file' and returns "http://<i24server>/<i24BasePath>/<file>"
 */
Intextad.i24URL = function(file) { 
    return "http://" + Intextad.i24server + Intextad.i24BasePath + file; 
}

/**
 * Imports a .js file.
 */
Intextad.include = function(file) { 
    document.write('<script type="text/javascript" src="' + Intextad.i24URL(file) + '"></script>');
}

/**
 * Checks whether Intextad.debug is true, and if so displays 'msg' in an alert box.
 */
Intextad.debugMsg = function(msg) {
    if (Intextad.debug) {
	alert(msg);
    }
}

/**
 * Takes a url and grabs the server part of it
 */
Intextad.parseServerFromURL = function(url, defaultServer) {
    var regex = new RegExp(/^http\:\/\/([^\/]*)[\/:].*$/);
    var parts = regex.exec(url);
    if (parts != null && parts.length > 0) {
	return parts[1];
    }
    return defaultServer;
}

// This is at the end so that all function definitions can be loaded first.
Intextad.initOnInclude();

