var behaviors = new Object();
window.onload = AttachBehaviors;

function AttachBehavior(behaviorName){
	if(behaviors == null)
		 behaviors = new Object();
	if(behaviorName == "OpenLinksInNewWindow"){
		behaviors[behaviorName] = AttachOpenLinksInNewWindow;
	}
	else if(behaviorName == "EmbeddedFiles"){
		behaviors[behaviorName] = AttachEmbeddedFiles;
	}
}

function AttachBehaviors(){
	for(name in behaviors){
		attachOp = behaviors[name];
		attachOp();
	}
}

//
// Attaches open links in new window behavior to all anchor elements.
//
function AttachOpenLinksInNewWindow() { 
 if (!document.getElementsByTagName) return; 
 var anchors = document.getElementsByTagName("a"); 
 for (var i=0; i<anchors.length; i++) { 
   var anchor = anchors[i]; 
   if (anchor.getAttribute("href")) 
     anchor.target = "_blank"; 
 } 
} 

//
// Attaches behavior to embedded files to control how links respond
// when a user clicks them.
//
function AttachEmbeddedFiles(){
	var anchors = document.getElementsByTagName("a"); 
	for (var i=0; i<anchors.length; i++) { 
		var anchor = anchors[i]; 
		var mhtURL = /^mhtml:/;
		var href = anchor.getAttribute("href");
		var webExts = /\.(htm|html|gif|jpg|jpeg|png)$/;
		var officeExts = /\.(doc|xls|ppt|pdf)$/;
		
		if(officeExts.test(href)){ //open office docs in separate window
			anchor.target = "_blank";
		}
		
		if(href != null && href.toString()!=""){
			href = href.toString().toLowerCase();
			if(mhtURL.test(href)){ //only attach alert logic for MHT URLs
				if(!webExts.test(href)){ //display download instructions for non-web files
					anchor.onclick = viewFileAlert;
				}
			}
		}
	}
}

//
// Pops up an alert dialog telling the user how to save an embedded file locally
//
function viewFileAlert(){
	var href = event.srcElement.href.toString();
	var paths = href.split(".");
	var fileName = paths[paths.length-1];
	alert('To view this file you will need to: \n\n 1. Right-click the link and choose the "Save Target As..." menu \n 2. Enter a filename with a .' + fileName + ' extension\n 3. Double-click the saved file' );
	var href = event.srcElement.href;	
	event.cancelBubble = true;
	return false;
}


function dump(obj)
{
	var str = "";
	var i = 1;
	var ch = '\t';
	for(k in obj){
	if(i%10 == 0) ch = '/n';
	else ch = '\t';
	str = str + '[' + k + '=' + obj[k] + ']' + ch;
	i = i+1;
	}
	alert(str);
}

