var mi=(typeof mi=='undefined')?{'media_domain':''}:mi;if(window.miAppControler){mi.control=new miAppControler();}
mi.getArgs=function(){if(typeof mi.args=='undefined'){mi.args={};var query=location.search.substring(1);var pairs=query.split('&');for(var i=pairs.length-1;i>=0;i--){var pos=pairs[i].indexOf('=');if(pos==-1){continue;}
mi.args[pairs[i].substring(0,pos)]=unescape(pairs[i].substring(pos+1));}}
return mi.args;};mi._console=function(s){mi._console.log=(mi._console.log&&mi._console.log.length>0)?mi._console.log+'\n---------------------------------------------------\n'+s:s;};mi.fixConsole=function(){if(typeof window.console!="object"){window.console={};}
if(window.console.is_fixed){}
else{var firebugMethods=["log","debug","info","warn","error","assert","dir","dirxml","trace","group","groupEnd","time","timeEnd","profile","profileEnd","count"];var methodCount=firebugMethods.length;var args=mi.getArgs();var view=(args.viewlog&&args.viewlog=='1');for(var i=0;i<methodCount;i++){var methodName=firebugMethods[i];if(typeof window.console[methodName]!="function"){switch(methodName){case'log':if(view){window.console.log=mi._console;if(window.addEventListener){window.addEventListener("load",function(){alert(mi._console.log);},false);}else if(window.attachEvent){window.attachEvent("onload",function(){alert(mi._console.log);});}}else{window.console.log=function(){};}
break;default:eval("window.console[methodName] = function(s){window.console.log('"+methodName.toUpperCase()+": '+ s)};");}}}}
window.console.is_fixed=true;};mi.fixConsole();mi.cloneObject=function(sourceObj){if(sourceObj==null||typeof sourceObj!='object'){return sourceObj;}
var temp=new sourceObj.constructor();for(var key in sourceObj){temp[key]=mi.cloneObject(sourceObj[key]);}
return temp;};mi.App=function(){var _configs={};this._manageConf=function(prop,val){return val;};this.setConf=function(){switch(arguments.length){case 1:for(var prop in arguments[0]){_configs[prop]=this._manageConf(prop,arguments[0][prop]);}
break;case 2:_configs[arguments[0]]=this._manageConf(arguments[0],arguments[1]);break;default:console.warn('mi.App.setConf was passed an incorrect number of arguments, the method should be used with either a name-value pair or an object containing configuration settings.');}};this.getConf=function(prop){return _configs[prop];};this.viewConfs=function(){console.dir(_configs);};this.cache={};switch(arguments.length){case 1:this.setConf(arguments[0]);break;case 2:this.setConf(arguments[0],arguments[1]);break;}};mi.getEventSrc=function(e){if(!e){e=window.event;}
if(e.target){return e.target;}else if(e.srcElement){return e.srcElement;}};mi.templateVarPattern=/\@([^\@]+)\@/g;mi.templateParser=function(data,template){return template.replace(mi.templateVarPattern,function(){return data[arguments[1]];})};mi.makeHash=function(sourceData,firstDelimiter,secondDelimiter){if(sourceData&&firstDelimiter&&secondDelimiter){var hash={};var pairs=sourceData.split(firstDelimiter);var pos;for(var i=pairs.length-1;i>=0;i--){if(typeof(pairs[i+1])!='undefined'){pos=pairs[i].indexOf(secondDelimiter);if(pos==-1){continue;}
hash[pairs[i].substring(0,pos)]=pairs[i].substring(pos+1);}}
return hash;}
else{console.log('sourceData, firstDelimiter, & secondDelimiter must be defined. There are no default values.');}};mi.loadPageInfo=function(){if(window.pageInfo){var pi=window.pageInfo;if(this.pageInfo==undefined){this.pageInfo=this.cloneObject(pi);}else{for(var key in pi){if(key==='version'&&(parseFloat(pi[key])>parseFloat(this.pageInfo.version))){this.pageInfo.version=pi[key];}else if(this.pageInfo[key]==undefined){this.pageInfo[key]=this.cloneObject(pi[key]);}else if(typeof this.pageInfo[key]=='object'){for(var key2 in pi[key]){this.pageInfo[key][key2]=(this.pageInfo[key][key2])?this.pageInfo[key][key2]:this.cloneObject(pi[key][key2]);}}}}}
window.pageInfo=null;}
mi.wait_for_ready=function(time,target,callback){var checker,time_spent=0,interval=3000;_check_document=function(){if(null!==$(target)){clearInterval(checker);callback();}else{time_spent+=interval/1000;if(time_spent>=time){clearInterval(checker);}}};$(document).ready(function(){checker=setInterval(_check_document,interval);});};mi.Search=function(){mi.App.apply(this,arguments);mi.getArgs();this.kill;};mi.Search.prototype.submitForm=function(searchType){this.kill="false";switch(this.getConf("searchSelectorType")){case"option":searchType=document.miSearchForm.aff.value;break;case"radio":searchType=$('input:radio[name=aff]:checked').val();break;}
var queryInputField;if(document.miSearchForm.keywords){queryInputField=document.miSearchForm.keywords;}
else{queryInputField=document.miSearchForm.q;}
var searchText="";if($(queryInputField).attr("placeholder")){if(!(queryInputField.value==$(queryInputField).attr("placeholder"))){searchText=queryInputField.value;}}
else{searchText=queryInputField.value;}
if(searchType==parseInt(searchType)){return;}
else{this.searchParamConfig(searchType,searchText);this.buildForm(searchType);}
if(this.kill=="false"){document.miSearchForm.submit();}
else{return false;}};mi.Search.prototype.buildForm=function(search_type){var self=this;var searchInputContainer_div=document.getElementById("searchInputContainer").innerHTML;if(searchInputContainer_div){$("#searchInputContainer > input[type='hidden']").each(function(){$(this).remove();});}
$("#search_widget_form").attr('method',self.getConf("form_method"));try{jQuery.each(self.getConf("query_fields"),function(paramName,paramValue){paramName=paramName.replace(/(.*)_mihyphen_(.*)/,"$1-$2");$("<input type='hidden' name='"+paramName+"' value='"+paramValue+"' />").appendTo("#searchInputContainer");});}
catch(e){console.error("Script Caught Error - "+e);}
document.miSearchForm.action=self.getConf("form_action");};mi.Search.prototype.checkOption=function(){var self=this;if(typeof mi.args.collection!="undefined"){switch(self.getConf("searchSelectorType")){case"option":if(mi.args.collection=="WEB"){$("select#search_select option[value='web_search']").attr("selected",1);}else if(mi.args.collection=="ARCHIVES"){$("select#search_select option[value='archives']").attr("selected",1);}else{$("select#search_select option[value='h_archives']").attr("selected",1);}
break;case"radio":if(mi.args.collection=="WEB"){$("#search_web").attr("checked",1);}else if(mi.args.collection=="ARCHIVES"){$("#search_archives").attr("checked",1);}else{$("#search_history").attr("checked",1);}
break;}}};mi.Search.prototype.dropDownSelection=function(target){mi.search.cache.mi_search_type=target.children('a').attr("id");if(target.children('a').is('#site_search')){var this_image=target.find("img").attr("src");mi.search.getConf("mi_search_widget_icon").attr("src",this_image);}
else if(target.children('a').is('#web_search')){var this_image=target.find("img").attr("src");mi.search.getConf("mi_search_widget_icon").attr("src",this_image);}
else if(target.children('a').is('#archives')){var this_image=target.find("img").attr("src");mi.search.getConf("mi_search_widget_icon").attr("src",this_image);}
$("#search_keywords").focus();return false;}
mi.Search.prototype.configErrorReporter=function(){this.kill="true";alert("Option doesn't exist in your configuration. Please review your browsers error console.");console.error("Option doesn't exist in your configuration. Please submit a ticket to MI Support for assistance.");return false;}
mi.Search.prototype.setUp=function(){mi.search.searchParamConfig();mi.search.getConf("mi_search_dropdown_keys").hover(function(){mi.search.getConf("mi_search_drop_down").show();},function(){mi.search.getConf("mi_search_drop_down").hide();});mi.search.getConf("mi_search_drop_down_link").bind("click",function(e){mi.search.getConf("mi_search_drop_down").hide();});mi.search.getConf("mi_search_dropdown_input").focus(function(){mi.search.getConf("mi_search_drop_down").hide();});mi.search.getConf("mi_search_selected").click(function(){mi.search.dropDownSelection($(this));return false;});mi.search.checkOption();mi.search.cache.mi_search_type=mi.search.getConf("defaultSearchType");var mi_search_form=document.miSearchForm;mi_search_form.onsubmit=function(){return mi.search.submitForm(mi.search.cache.mi_search_type);}}

// *****************************************************************************
// Function:	fetchKeywordUrlMap( 'myTargetSelector' )
// Arguments:	myKeywordUrlMap:  A string of URL to keyword mappings
//		myTargetSelector: JQuery style selector to inject keyword
//		mapping into.
// Purpose:	Based on keywords extrapolated from the current URL will compare
//		these keywords to a user generated mapping of URLs to Keywords
//		and if matched will output the URL link passed.
// Return:	NA
// *****************************************************************************
mi.Search.prototype.fetchKeywordUrlMap = function( myKeywordUrlMap, myTargetSelector ){

    // If 'myKeywordUrlMap' has a trailing '++' then we need to strip this, the
    //   '++' is replaced by Template Toolkit for every line break, and having
    //   a trailing '++' means the page element had a trailing line break with
    //   no data after it
    if( myKeywordUrlMap.match( /\++$/ ) )
	myKeywordUrlMap = myKeywordUrlMap.replace( /\+*$/, '' );
	
    // This will contain all the HTML to be injected into the selector passed
    //   above after processing.
    var formattedOutput		= '';
    // All the keywords extrapolated from the current URL, urlKeyword == Array
    var urlKeywords		= this.fetch404Keywords( );
    
    // This array will house all objects of class type keywordUrlMapClass
    var keywordUrlMapObjects	= [];
    
    // Now we have to parse the Keyword -> URL mappings so we can match on the
    //   404 keywords found.
    myKeywordUrlMap 	= myKeywordUrlMap.split( '++' );
    for( var i in myKeywordUrlMap ){
	// Example Map: Link Name 1||http://www.link1.com||link1, test1, keyword
	
	// Split the current keyword / url map by '||' and create new object
	var currentKeywordUrlMap	= myKeywordUrlMap[i].split( '||' );
	// Create the object and set the name and URL
	keywordUrlMapObjects[i]	= new this.keywordUrlMapClass( currentKeywordUrlMap[0], currentKeywordUrlMap[1] );
	
	// Now split the 3rd( [2] ) part of data by ',' and add to list of
	//   keywords for this object
	var currentKeywords		= currentKeywordUrlMap[2].split( ',' );
	for( var x in currentKeywords ){
	    keywordUrlMapObjects[i].addKeyword( currentKeywords[x] );
	}
    }
    
    
    // Finally loop through all the 404 keywords extrapolated, and call the
    //   keywordUrlMapClass objects 'matchKeyword' method to see if any of the
    //   objects keywords match the 404 keyword
    for( var i in urlKeywords ){	
	for( var x in keywordUrlMapObjects ){
	    if( keywordUrlMapObjects[x].matchKeyword( urlKeywords[i] ) ){
		// Then add the output code
		formattedOutput += "\
		    <li><a href='" + keywordUrlMapObjects[x].url + "'>" +
			    keywordUrlMapObjects[x].name + "</a>\
		    </li>";
	    }
	}
    }
    
    // Output the final HTML to the page
    $( myTargetSelector ).append( formattedOutput );
    
    
}

/**
 * Construct a keywordUrlMapClass
 * @class Basic class to house keyword to url mappings, and any helper methods
 * needed.
 * @constructor
 * @param {String} myName The human readable link name, used for innerHTML of
 * the anchor when outputting to the user.
 * @param {String} myUrl The actual href URL for the anchor
 * @return A new keywordUrlMapClass
 */
mi.Search.prototype.keywordUrlMapClass = function( myName, myUrl){
    this.name		= myName;		// Name of link to display
    this.url		= myUrl;		// Actual URL
    this.keywords	= [];			// An array of keywords match
    this.matchedKeyword = false;		// This is set to true when we
						// match a keyword to prevent dups
        
    
     /**
    * Adds a new keyword to the Array 'keywords' for the current instance of
    * this object, also lowercases the keyword
    * @type String
    */
    this.addKeyword 	= function( myKeyword ){
	this.keywords.push( myKeyword.toLowerCase() );
    }
    
    /**
     * Given a passed keyword, see if it matches any keywords in this object,
     * if so then return true, and set that object as matchedKeyword == true
     * to prevent duplicate outputs
     * @type String
     * @return 'true' if match found, 'false' otherwise
    */
    this.matchKeyword 	= function( myKeyword ){
	
	if( ( !this.matchedKeyword ) && ( this.getKeywords().match( myKeyword ) ) ){
		this.matchedKeyword 	= true;
		return( true );
	}
	return( false );
    }
    
    /**
     * Will return a list of this objects instance keywords, in comma delimited
     * format.
     * @return String of comma delimited keywords
     */
    this.getKeywords 	= function( ){
	
	return( this.keywords.join( ', ' ) );
    }
    
}
// *****************************************************************************


// *****************************************************************************
// Function:	fetchSearchResults( 'myTargetSelector' )
// Arguments:	myTargetSelector: JQuery style selector to inject SOLR results in
// Purpose:	Based on keywords extrapolated from the current URL, will inject
// 		SOLR search results into the passed JQuery selector
// Return:	NA
// *****************************************************************************
mi.Search.prototype.fetchSearchResults = function( myTargetSelector ){
    
    // 'keywordList' is a space separated list of keywords found in the URL
    var keywordList 	= '';
    
    // Get the URL and send to function to get keywords, will return an array
    //   of keywords.
    var keywords 		= this.fetch404Keywords( );
    
    // Here we loop through the keywords, and assemble into a space separated
    //   string that SOLR can parse
    for( var i in keywords ){
	keywordList += ' ' + keywords[i];
    }
    
    // Now inject the search results into the passed selector
    $( myTargetSelector ).load( '/search/ #search', { q: keywordList } );

}
// *****************************************************************************


// *****************************************************************************
// Function:	fetch404Keywords( )
// Purpose:	Will parse for all words between forward slashes after the
// 		domain name and return this list of words as an array
// Return:	An array of keywords found in the url after the domain name
// *****************************************************************************
mi.Search.prototype.fetch404Keywords = function( ){
    
    // This will be the array that holds the unedited version of all 404 keywords
    var keywordsArray 		= [];
    // This will be the array returned by this function containing all keywords
    //   after filtering out the 'bad' keywords as defined by the regex below
    var returnKeywordsList 	= [];
    
    // Get the list of 404 keywords from the current URL
    keywordsArray = window.location.pathname.toLowerCase().slice(1).split('/');
    
    // Go through all the keywords and filter out for 'invalid' keywords
    //   based on the regex in the loop.
    for( var x in keywordsArray ){	

	// If the current keyword doesn't match the regex then assign on the
	//   returned keyword array
	if(  ( keywordsArray[x].match( /story/ ) ) || ( keywordsArray[x].match( /[0-9]+/ ) ) ){
	    //console.log( 'INVALID KEYWORD FOUND: ' + keywordsArray[x] );
	} else {
	    //console.log( 'VALID KEYWORD FOUND: ' + keywordsArray[x] ); 
	    returnKeywordsList.push( keywordsArray[x] );
	}
    }
	
    return( returnKeywordsList );

}

mi.Search.prototype.searchParamConfig=function(search_type,search_text){this.setConf("searchSelectorType","option");if(search_type){switch(search_type){case"web_search":this.setConf("form_action","http://theolathenews.com/search-bin/search.pl.cgi");this.setConf("query_fields",{sf_Keywords:search_text,product:"Yahoo,Overture",collection:"WEB",live_template:"http://www.theolathenews.com/searchresults/v-ysr/index.html",error_template:"http://www.theolathenews.com/searchresults/v-yerr/index.html",preview_template:"http://preview.theolathenews.com/searchresults/v-ysr/index.html",results_per_page:"10",preview:"0",prop_related:"1",prop_dym:"1"});break;case"archives":this.setConf("form_action","http://www.newslibrary.com/nlsearch.asp?");this.setConf("query_fields",{search_mode:"all",date_mode:"year",year:"last+180+days",sort:"d%3Ah",nitems:"10",region:"ODNB",dbquery:search_text,collection:"ARCHIVES"});break;default:this.configErrorReporter();}}};
