// sets the focus of the cursor to our search box and call auth string on page load

function init() {
    if( typeof(document.searchform.w)!='undefined'){
        document.searchform.w.focus();
    }
    loadAuthString();
    // 
    //if($('mpHead')) {
    //    new Asset.javascript('http://www.nejm.org/most-popular/accordion-data.aspx?numItems=10');
    //}
    getCurrentDates();
    // don't show survey
    //showSurvey();
}


/* AUTH STRING CODE */

serviceUrl = 'http://www.nejm.org/auth/auth-string.aspx?returnUrl=';
function loadAuthString() {
    //Create a script tag to call the auth string service
    authScript = document.createElement('script')
    authScript.type = 'text/javascript'
    authScript.src = serviceUrl + window.location.href
    
    //Add it to the document, thus calling the service
    document.getElementsByTagName("head")[0].appendChild(authScript)
}

//This function will be called by the auth string response
writeAuthString = function(data) {
    if (data.theString) {
        document.getElementById("authStringHolder").innerHTML = data.theString
    }
}

    /* MOST POPULAR FUNCTIONS on search.nejm.org */

//Called when the data is loaded
fillAccordion = function(data) {
    //Create a <dl> to store accordion data in.
    accordion = new Element('dl').injectAfter($('mpHead'))
    accordion.className = 'accordion'

    //Add a <dt> (title) and <dd> (content) for each category in the accordion data 

    accordion.innerHTML = buildString(data.categories, function(cat) {
    if (cat.name == "Top Search Terms") {
        return '<dt>' + cat.name + '</dt><dd><ol>' + 
            getListItems(cat.links) + '</ol></dd>'
    } 
    else 
    { return ""}
    })
}

//Construct a link for each link in this category
getListItems = function(links) {
    return buildString(links, function(link) {
        return '<li><a href="' + unescape(link.url) + '">' + unescape(link.title) + '</a></li>'
    })
}

//Returns the concatenation of the results of running fn on each item in arr
buildString = function(arr, fn) {
    str = ''
    arr.each(function(item) { str += fn(item) })
    return str
}

     

    /*GENERAL SEARCH FUNCTIONS */

function popUp(URL,whichpage) {
	day = new Date();
	id = whichpage;
	eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=1,statusbar=1,menubar=1,resizable=1,width=700,height=600,left = 20,top = 20');");
}

    /*SPECIFIC TO SEARCH FORMS*/

function getCurrentDates () {

	var path = window.location.pathname;
	var page = path.substring(path.lastIndexOf('/') + 1);
    if(page == "cme-search.html" || page == "advanced-search.html" || page == "medline-search.html") {

	    var date = new Date();
	    var curYear = date.getFullYear();
	    var curMonth = date.getMonth();
	    var startMonth = (curMonth + 1);
	    curMonth = (curMonth + 1);
	    startYear = (curYear - 10);

	    if (page == "cme-search.html") {
	                   startMonth = curMonth;
		    startYear = (curYear - 2); 
	    }

	    if (page == "medline-search.html") {
		    curMonth = getTextMonth(curMonth);
		    startMonth = getTextMonth(startMonth);
		    selectOption('fmonth',startMonth);
		    selectOption('fyear',startYear);
		    selectOption('tmonth',curMonth);
		    selectOption('tyear',curYear);
	    }
	     if (page == "search.aspx") {
		    selectOption('lstStartMonth',startMonth);
		    selectOption('lstStartYear',startYear);
		    selectOption('lstEndMonth',curMonth);
		    selectOption('lstEndYear',curYear);
	    }
	    else {
		    selectOption('start_month',startMonth);
		    selectOption('start_year',startYear);
		    selectOption('end_month',curMonth);
		    selectOption('end_year',curYear);
	    }
    }
}
    function selectOption (select,optValue) {
	    var selectOptions = document.getElementById(select);
	    //alert (selectOptions.length);
	    for (j=0;j<selectOptions.length;j++) {
		    if (selectOptions[j].value == optValue) {
			    selectOptions[j].selected = "selected";
		    }
	    }
    }


    function getTextMonth (numMonth) {
	    months = {
		    1: ["Jan"],
		    2: ["Feb"], 
		    3: ["Mar"], 
		    4: ["Apr"], 
		    5: ["May"], 
		    6: ["Jun"], 
		    7: ["Jul"], 
		    8: ["Aug"], 
		    9: ["Sep"], 
		    10: ["Oct"], 
		    11: ["Nov"], 
		    12: ["Dec"] 
	    }
	    var month = months[numMonth];
	    return month[0];
    }


    function getTextMonthCases (numMonth) {
	    months = {
		    01: ["Jan"],
		    02: ["Feb"], 
		    03: ["Mar"], 
		    04: ["Apr"], 
		    05: ["May"], 
		    06: ["Jun"], 
		    07: ["Jul"], 
		    08: ["Aug"], 
		    09: ["Sep"], 
		    10: ["Oct"], 
		    11: ["Nov"], 
		    12: ["Dec"] 
	    }
	    var month = months[numMonth];
	    return month[0];
    }

/* SEARCH SURVEY CODE */

function showSurvey () {
    if(document.getElementById('pageWrapper') && document.getElementById('surveyMessage')) {
    	var hasCompleted = readCookie('nejmSearchSurvey');
	    if (!hasCompleted) {
		    new Fx.Style('pageWrapper', 'opacity', {duration:1}).start(.25);
		    var surveyLayer = document.getElementById('surveyMessage');
		    surveyLayer.style.display = "block";
		    document.surveyForm.surveyEmailAddress.focus();
	    }
	    if (hasCompleted) {
		    //setOpacity(pageWrapper,100);
	    }
    }
}

function hideSurvey () {
	createCookie('nejmSearchSurvey','false',365);
	document.surveyForm.surveyAction.value = "decline";
	document.surveyForm.submit();
}

function closeSurvey () {
	createCookie('nejmSearchSurvey','false',365);
    var surveyLayer = document.getElementById('surveyMessage');
    surveyLayer.style.display = "none";
	new Fx.Style('pageWrapper', 'opacity', {duration:1}).start(1);
}

function emailSurvey () {
    var refUrl = window.location;
	var emailAddress = document.getElementById('surveyEmailAddress').value;
	var verifyEmailMessage = verifyEmail(emailAddress);
	if (!verifyEmailMessage) {
		createCookie('nejmSearchSurvey','false',365);
		document.surveyForm.submit();
	} 
	else 
	{
		var emailAddress = document.getElementById('surveyErrors').innerHTML = verifyEmailMessage;
	}
}

function verifyEmail (emailAddress) {
	var verifyEmailMessage = "";
	if (emailAddress == "") {
		verifyEmailMessage = verifyEmailMessage + "You must enter an email address";
		return verifyEmailMessage;
	}
	if (emailAddress.indexOf("@") == -1) {
		verifyEmailMessage = "";
		verifyEmailMessage = verifyEmailMessage + "You must enter an email address that contains the @ symbol";
		return verifyEmailMessage;
	}
	if (emailAddress.indexOf(".") == -1) {
		verifyEmailMessage = "";
		verifyEmailMessage = verifyEmailMessage + "You must enter an email address that contains at least one period (.)";
		return verifyEmailMessage;
	}
	
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
	var c = ca[i];
	while (c.charAt(0)==' ') c = c.substring(1,c.length);
	if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function setOpacity(object,value) {
 	object.style.opacity = value/10;
	object.style.filter = 'alpha(opacity=' + value*10 + ')';
}

/* CITATION SEARCH CODE */


function doSearch () {
    var v = document.getElementById('v').value;
    var p = document.getElementById('p').value;
    var searchUrl = "citation-search/citation-search.aspx";
    var searchParams = "v=" + v + "&p=" + p;
    var myAjax = new Ajax(searchUrl,{postBody:searchParams, onComplete: citationSearchResults});
    myAjax.request();    
    return false;
}


function citationSearchResults (responseText, responseXml) {
	var message = document.getElementById('citationSearchMessage');
	var results = responseXml.childNodes[0];

	var count = responseXml.getElementsByTagName('count')[0].childNodes[0].nodeValue;
	
	if (count == 0) {
		message.innerHTML = "No articles match your criteria";
	}
	
	if (count == 1) {
		
		var url = responseXml.getElementsByTagName('url')[0].childNodes[0].nodeValue;
		message.innerHTML = "";
		window.location.href = url;
	}
	
	if (count >= 2) {
         	var v = document.getElementById('v').value;
    		var p = document.getElementById('p').value;
		var dois = "";
		var x = responseXml.getElementsByTagName('doi');
		//alert(x.length);
		for (j=0;j<x.length;j++) {
			var attlist = x[j].attributes;
			var doi = attlist.getNamedItem('DOI');
			doi = doi.value.toString();
			dois = dois + doi + "+";
		}
		var url = "http://search.nejm.org/search?w=" + v + ":" + p + "&ts=subs";
		window.location.href = url;
	}

}

/* SEARCH NAVIGATION FUNCTIONS */

function clickClear(thisField, defaultText) {
	if (thisField.value == defaultText) {
		thisField.value = "";
		thisField.style.color = "#000";
		
	}
}

function clickRecall(thisField, defaultText) {
	if (thisField.value == "") {
		thisField.value = defaultText;
		thisField.style.color = "#000";
	}
}

// for SLI search forms

function verifySearch(thisField,defaultText) {
	var searchUrl;

	if (thisField.value == defaultText || thisField.value == "Keyword, citation, or author") {
		location.href= "http://search.nejm.org";
		return false;
	}
	else {
        return true;
	}
}

/* END SEARCH NAVIGATION FUNCTIONS */

