if ( typeof (amplafi) == "undefined") var amplafi={};
amplafi.isDebug=false;amplafi.mep_lookup_prefix="ampmep_";amplafi.csUrlKey="url";amplafi.providerLookup="AMPLAFI_BP_11";amplafi.dataloadUrl="http://amplafi.net/scripts";amplafi.siteUrl="http://amplafi.net/";amplafi.baseAnchor="";amplafi.yahooMapId="fRhpGYrV34GK7jK4fUydUIo772jtpaCd118z7.Hmrr.0X1LwBluGv9Y4oLbOwST74PQ-";amplafi.pasteFlowLink="http://amplafi.net/flow/Paste";amplafi.publicUri="publicUri";amplafi.scripts=["http://amplafi.net/js/dojo/dojo.js.uncompressed.js?38836","http://amplafi.net/js/amplafi/freemarker.js?38836","http://api.maps.yahoo.com/ajaxymap?v=3.7&appid=fRhpGYrV34GK7jK4fUydUIo772jtpaCd118z7.Hmrr.0X1LwBluGv9Y4oLbOwST74PQ-"];if ( typeof (djConfig) == "undefined") {
    var djConfig = { parseWidgets: false };
} else {
    // TODO do we need to worry about customers also using dojo? (probably)
    // probably as this might be the source of bugs!
    // also need to report back on these cases so that we can proactively make sure
    // everything is o.k.
}
djConfig.isDebug = amplafi.isDebug;

if ( typeof (amplafi['bootstrap']) == "undefined") {
    amplafi.bootstrap = function() {
        if (amplafi.created) return; // already initialized        
        amplafi._init();        
        var nextScript;
        // runs while page is being loaded... no dojo nor DOM model available.
        for(var index = 0; index < amplafi.scripts.length; index++) {
            nextScript = amplafi.scripts[index];
            document.write('<script type="text/javascript" src="'+
            	nextScript+ '"></script>');
        }
        
        // remove parts of the url that are going to cause problems if embedded
	    var currentUrl = location.href;
	    var cutPoint = currentUrl.indexOf('#');
	    if ( cutPoint != -1 ) {
	        currentUrl = currentUrl.substring(0, cutPoint);
	    }
	    cutPoint = currentUrl.indexOf('?');
	    if ( cutPoint != -1 ) {
	        currentUrl = currentUrl.substring(0, cutPoint);
	    }
        amplafi.currentUrl = currentUrl;

        // for IE and Opera
        if (!amplafi.useEventListener){
            document.write('<sc'+'ri'+'pt' + ' type="text/javascript" defer="true">amplafi._bootstrapPostProcessing();</sc'+'r'+'ipt>');
        }
    };
    
    amplafi._init = function() {
        // initialization: Marks time, sets dom listeners, inits debug mode.
        if (!amplafi.created) {
            amplafi.created = new Date();
	    amplafi.useEventListener = false;//(document.addEventListener && !window.opera && !amplafi._khtml());
            if (amplafi.useEventListener){
                document.addEventListener('DOMNodeInserted', amplafi.handleNodeInsert, true);
            }

            if (location.href.indexOf('amplafi_debug=alert')>=0) {
                amplafi.debug = amplafi._debugAlert;
            } else if (location.href.indexOf('amplafi_debug=html')>=0) {
                amplafi.debug = amplafi._debugHtml;
            }  else if (location.href.indexOf('amplafi_debug=firebug')>=0) {
                amplafi.debug = console.debug;
            }
        }
    };

    // Message points will be searched after the page has loaded.
    // So, make sure that dojo is indeed available before going on.
    amplafi._bootstrapPostProcessing = function() {
        if (!window.dojo) {
            setTimeout(amplafi._bootstrapPostProcessing, 250);
            return;
        }
        /*dojo.addOnLoad(function(){*/amplafi.processPoints();//});
    };

    // Starting point for loading content.
    amplafi.loadData = function(data) {
        if (data.mep)
            amplafi.messagesLoad(data.mep);
        if (data.rss)
            amplafi.rssLinks(data.rss);
    };

    // data is key/value pairs
    // key = an html elementId,
    // value = a map that is used by StaticInlineMessages to insert the content.
    amplafi.messagesLoad = function(data) {
        // runs after the DOM tree is loaded.
	    // from dojo.hostenv.makeWidgets function:
	   			// we must do this on a delay to avoid:
				//	http://www.shaftek.org/blog/archives/000212.html
				// (IE bug)
	    for(var htmlId in data) {
	        var specificData = data[htmlId];
            specificData['messagePoint'] = htmlId;

            var messages = specificData.messages; 
            var mepId = htmlId.substring(htmlId.indexOf('_' + 1));
            var ctx = {messageEndPointLookupKey:mepId};
            var envelopes = [];
            for(var msg_index in messages){
                var msg = messages[msg_index];
                var env = {lookupKey:'ampbe_'+msg.envelopeId, messageLookupKey:'ampmsg_'+msg.messageId,
                    headline:msg.headline, updateDate:msg.lastUpdate, message:msg.fullText,
                    eventStart:msg.eventStart, eventLocation:msg.eventLocation};
                envelopes.push(env);
            }
            ctx.envelopes = envelopes;

            var element = document.getElementById(htmlId);
            if (element && (element.tagName=='A' || element.tagName=='a')) {
                element.innerHTML="";
                element.setAttribute('id', htmlId + "R");
                var newElement = document.createElement('div');
                newElement.setAttribute('id', htmlId);
		        element.parentNode.insertBefore(newElement, element);
                element = newElement;
            }
            if ( element ) {
                    amplafi.debug("Found and replacing id: " + htmlId);
                var engine = freemarker.create(specificData.messageTemplateString);
                element.innerHTML = freemarker.render(engine, ctx);
	            //dojo.widget.createWidget("amplafi:StaticInlineMessages", specificData, element);
	        }
	    }
            
            if (amplafi.shouldGatherTimings) {
                setTimeout(amplafi.gatherTimings, 2000);                                
            }
	};

    amplafi.rssLinks = function(data) {
        // runs while page is being loaded... no dojo nor DOM model available.
        // this is because firefox does not detect live bookmarks after dom is created.

        var head = document.getElementsByTagName("head")[0];
        var links = head.getElementsByTagName("link");
        var titles = [];
        for (var i=0; i<links.length; i++) {        
        	if (links[i].type=="application/rss+xml") {
        		titles.push(links[i].title);
       		}
        }

		for(var linkData in data) {
			var title = data[linkData].description;
			if (!amplafi._arrayContains(titles, title)) {
	            var linkElement = document.createElement('link');
	            linkElement.title = title;
	            linkElement.href = data[linkData].linkhref;
	            linkElement.rel="alternate";
	            linkElement.type="application/rss+xml";
	            head.appendChild(linkElement);
            }
        }
	};
	
	amplafi._arrayContains = function(arr, text) {
		for (var i = 0; i<arr.length; i++) {
			if (arr[i]==text) return true;
		}
		return false;
	}
    
    amplafi.processPoints = function() {
        // Runs after page has loaded... finds all meps and requests their data
        var tags = document.getElementsByTagName('p');
        var spans = document.getElementsByTagName('span');
        var divs = document.getElementsByTagName('div');
	    var links = document.getElementsByTagName('a');
        
        var res = [];
        amplafi._processElements(tags, res);
        amplafi._processElements(spans, res);
        amplafi._processElements(divs, res);        
	    amplafi._processElements(links, res);
        
        for (var i=0; i<res.length; i++) {
            var nextScript = amplafi.dataloadUrl
                + "/"+amplafi.providerLookup + '/' + res[i] + '.js?'
                + amplafi.csUrlKey + '=' + amplafi.currentUrl;
            amplafi.debug("Requesting: " + nextScript);
            var s = document.createElement('script');
            s.setAttribute('src', nextScript);
            document.body.appendChild(s);
        }

        return res;
    };

    amplafi._loadedUrls = {};

    amplafi._retryMep = function(id) {
        var byId = document.getElementById;
        if (byId(id) && byId(id).href && !amplafi._loadedUrls[id]) {
            amplafi._loadedUrls[id] = true;
            var href = byId(id).href.replace('.html','.js');
            href += '?' + amplafi.csUrlKey + '=' + amplafi.currentUrl;
            amplafi.debug("Re-requesting: " + href);
            var s = document.createElement('script');
            s.setAttribute('src', href);
            document.body.appendChild(s);
        }
    }

    amplafi._processElements = function(elms, res) {
        for (var i=0; i<elms.length; i++) {
            if (elms[i].id && elms[i].id.indexOf(amplafi.mep_lookup_prefix)==0) {
                res[res.length] = elms[i].id;
            }
        }
    };

    amplafi._khtml = function() {
        var dav = navigator.appVersion;
        return (dav.indexOf("Konqueror") >= 0)||(dav.indexOf("Safari") >= 0);
    };

    amplafi.handleNodeInsert = function(e) {
        // Runs when a node is inserted... if it's a mep node, requests its data.
        var node = e.target;
        if (node.id!=null && node.id.indexOf(amplafi.mep_lookup_prefix)==0) {
            // see if document already loaded - in which case we cant use this technique
            if (document.readyState=='complete') {
                //document.removeEventListener('DOMNodeInserted', amplafi.handleNodeInsert, false);
                amplafi.debug(e);
                amplafi.debug('Document already loaded - forwarding to processPoints');
                amplafi.processPoints();
                return;
            }
            var mep = node.id;
            var nextScript = amplafi.dataloadUrl+
                    "/"+amplafi.providerLookup+'/'+mep+'.js?'+amplafi.csUrlKey+'='+amplafi.currentUrl;
            amplafi.debug("Requesting (while DOMNodeInserted): " + nextScript);
            document.write('<sc'+'ri'+'pt' + ' type="text/javascript" src="'+nextScript+'"></sc'+'r'+'ipt>');
        }
    };

    amplafi.report = function() {
        // Reports what the current page contains, time taken to load and create
        // messages, their visibility, e.t.c.
        var meps = [];
        dojo.lang.forEach(dojo.widget.widgets, function(w) {
            if (w.declaredClass=='amplafi.widget.StaticInlineMessages') {
                var msgs = [];
                dojo.lang.forEach(w.children, function(kid) {
                    msgs[msgs.length] = {
                        id : kid.messageId,
                        time : kid.created - amplafi.created,
                        visible : true
                    };
                });
                meps[meps.length] = {
                    name : w.messagePoint,
                    time : w.created - amplafi.created,
                    visible : true,
                    messages : msgs
                };
            }
        });
        return {
            created : amplafi.created,
            points : meps
        };
    };
    
    amplafi.gatherTimings = function() {
        // sends timing (and mep display) data to server
        
    };
    
    amplafi.debugObject = function(obj, prefix) {
        // Debugs the given object and all its properties.
        if (!prefix)
            prefix = "";        
        for (prop in obj) {
            var val = obj[prop];
            amplafi.debug(prefix + prop + ' -> ' + val);
            if (typeof(val) == 'object') {
                amplafi.debugObject(val, prefix + prop + '.');
            }
        }
    };    
    
    amplafi.debug = function(msg) {};
    
    amplafi._debugAlert = function(msg) {
        alert(msg);        
    };
    
    amplafi._debugHtml = function(msg) {
        var htmlDebugNode = document.getElementById('amplafiHtmlDebugNode');
        if (!htmlDebugNode) {
            htmlDebugNode = document.createElement('div');
            htmlDebugNode.setAttribute('id','amplafiHtmlDebugNode');            
            document.body.appendChild(htmlDebugNode);
            
            htmlDebugNode.innerHTML += "<hr />Debug Output<br />";
        }
        htmlDebugNode.innerHTML += (msg + "<br />");
    };
    
    amplafi.copyThis = function(that) {
    	if (document.getElementById('pasteHereDiv')) {
    		document.getElementById('pasteHereDiv').style.display='block';
    		return;    		
    	}
		var myWidth = 0, myHeight = 0;
		if( typeof( window.innerWidth ) == 'number' ){
			//Non-IE
			myWidth = window.innerWidth;
			myHeight = window.innerHeight;
		} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ){
			//IE 6+ in 'standards compliant mode'
			myWidth = document.documentElement.clientWidth;
			myHeight = document.documentElement.clientHeight;
		} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ){
			//IE 4 compatible
			myWidth = document.body.clientWidth;
			myHeight = document.body.clientHeight;
		}
		var divHeight=50;
		var divWidth=320;	
		var parentNode=that.parentNode;
		var divLeft=Math.round((myWidth-divWidth)/2);
		var divTop=Math.round((myHeight-divHeight)/2);
		
		var div=document.createElement('div');
		div.setAttribute('id','pasteHereDiv');
		div.setAttribute('style','position:absolute;left:'+divLeft+'px;top:'+divTop+'px;width:'+divWidth+'px;height:'+divHeight+'px;border:2px solid #79b30b;background-color:#D2E4B5;text-align:center;line-height:50px;');
		div.innerHTML='Use ';
		var link=document.createElement('a');
		link.setAttribute('href',"javascript:(function(){var s=document.createElement('script');s.charset='UTF-8';s.src='"+amplafi.siteUrl+"scripts/paste-this.js';document.body.appendChild(s)})()");
		link.setAttribute('onClick', "alert('Drag this link to your bookmarks toolbar, or right-click and choose Bookmark This Link...');return false;");
		link.innerHTML='Paste here';
		div.appendChild(link);
		div.innerHTML+=' bookmarklet to move content';
		div.innerHTML+=" <a href='#' onClick='this.parentNode.style.display=\"none\";return false;'>[X]</a>";
		
		parentNode.appendChild(div);
		div.focus();
	}
}

amplafi.bootstrap();


