SiggSearch = {

    siggData : [],

    timeout: 20 /* seconds */,

    updateCitations : function( siggData ) {
        this.siggData = siggData;
        if ( siggData.length > 0 ) {
            var html = "";
            for ( var i = 0, l = siggData.length; i < l; i++ ) {
                var sigg = siggData[i];
                html += "<p class=\"siggSuccess\">";
                html +=  "<a href=\"/posturl?url=" + encodeURIComponent("doi:"+sigg.doi) + "\"><img src='"+staticRoot+"/img/siggAdd.png'/></a>&nbsp;" + sigg.fullCitation +"</p>";
            }
        }
        else {
            html = "<p class=\"siggSuccess\">Nothing found. Try broadening your query.</p>";
        }
        SiggSearch.replaceHTML( "siggResult", html );
    },

    search : function () {

        // get the user''s query (aka the expression)
        var expression = document.getElementById("siggExpression").value;

        // don''t pass empty expressions, just return
        if ( expression.match( /^\s*$/ ) ) {
            return;
        }

        // disable the inputs so that you don''t get a double request
        SiggSearch.disableInput(true);

        // reset the results
        this.siggData = [];
        this.replaceHTML( "siggResult", "<span>Loading ... <img src='"+staticRoot+"/img/ajax-loader.gif'/></span>" );
	jQuery(".siggResult").show();


        // make the ajax call
        AjaxRequest.get(
            {
                url: "/sigg",

                parameters : { expression: expression },

                timeout: SiggSearch.timeout* 1000,

                onSuccess : function( response ) {
                    // parse the servers response
                    var json = null;
                    try {
                        json = eval( "(" + response.responseText + ")" ); // the parentheses are critical
                    }
                    catch ( e ) {
                        json = { status: 500, message: "Unable to use search results: " + e, matches: [] };
                    }
                    // present the citations
                    if ( json.status == 200 ) {
                        SiggSearch.updateCitations( json.matches );
                    }
                    else {
                        SiggSearch.replaceHTML( "siggResult", "<p class=\"siggError\">" + json.message + "</p>" );
                    }
                },

                onTimeout : function(){
                    SiggSearch.replaceHTML( "siggResult", "Service did not respond in " + SiggSearch.timeout + " seconds. Try again later." );
		    SiggSearch.disableInput(false);
                },

                onFailure : function(){
                    SiggSearch.replaceHTML( "siggResult", "Service not available. Try again later." );
		    SiggSearch.disableInput(false);
                },

                onComplete : function() {
                    // enable the inpits so that the user can find again
		    SiggSearch.disableInput(false);
                }

            }
        );

        return false;
    },

    disableInput: function(s) {
                    document.getElementById("siggExpression").disabled = s;
                    document.getElementById("siggButton").disabled = s;

    },

    replaceHTML : function( id, content ) {
        var oldElement = document.getElementById(id);
        var newElement = oldElement.cloneNode(false);
        oldElement.parentNode.replaceChild(newElement,oldElement);
        newElement.innerHTML = content;
    }
};

// END


PubmedSearch = {

	updateCitations : function(data) {
		//alert(siggData.length);

		if ( data && data.value && data.value.items && data.value.items.length > 0 ) {
			siggData = data.value.items
			var html = "";
			for ( var i = 0, l = siggData.length; i < l; i++ ) {
				var sigg = siggData[i];
				var article = sigg.MedlineCitation.Article;
				var au = sigg.MedlineCitation.Article.AuthorList.Author;

				html += "<p class=\"siggSuccess\">";
				html +=  "<a href=\"/posturl?url=" + encodeURIComponent("pmid:"+sigg.MedlineCitation.PMID) + "\"><img  src='"+staticRoot+"/img/siggAdd.png'/></a>&nbsp;" +
					sigg.MedlineCitation.Article.ArticleTitle +"<span style='margin-left:3em; display:block'><i>";
				// Journal of muscle research and cell motility, Vol. 18, No. 3. (June 1997), pp. 305-321.

				if (article.Journal.Title) {
					html += article.Journal.Title+", ";
				}
				var issue = article.Journal.JournalIssue;
				if (issue) {
					if (issue.Volume) html += "Vol. "+issue.Volume+", ";
					if (issue.Issue) html += "No. "+issue.Issue+". ";
					// "PubDate":{"Year":"2009","Month":"Sep","Day":"28"},
					var date = issue.PubDate;
					if (date) {
						html += "(";
						if (date.Day) html += date.Day+" ";
						if (date.Month) html += date.Month+" ";
						if (date.Year) html += date.Year;
						html += ")";
					}

				}
				html += "</i></span><span style='margin-left:3em; display:block'>";

				for (var j = 0; j < au.length; j++) {
					var a= au[j];
					if (j>0) {
						html += "; ";
					}
					var Initials = a["Initials"];
					var ForeName = a["ForeName"];
					var LastName = a["LastName"];
					var CollectiveName  = a["CollectiveName"]
					if (CollectiveName) {
						html += CollectiveName;
					} else {
						html += LastName;
						if (ForeName) {
							html += ", "+ForeName;
						} else if (Initials){
							html += ", "+Initials;
						}
					}

				}
				html += "</span></p>";
			}
		}
		else {
		    html = "<p class=\"siggSuccess\">Nothing found. Try broadening your query.</p>";
		}
		//alert(html);
		jQuery("#siggResult").html(html);
	},

	search : function () {
		// alert("PUBMED SEARCH");
		var expression = document.getElementById("siggExpression").value;

		// don''t pass empty expressions, just return
		if ( expression.match( /^\s*$/ ) ) {
		    return;
		}

		// disable the inputs so that you don''t get a double request
		SiggSearch.disableInput(true);

		var baseURL = "http://pipes.yahoo.com/pipes/pipe.run?_id=3e3c37c2c3c596293527b5844d66d6b3&_render=json&n=10&q="+encodeURIComponent(expression)+"&_callback=?"

		jQuery("#siggResult").html( "<span>Loading ... <img src='"+staticRoot+"/img/ajax-loader.gif'/></span>" );
		jQuery(".siggResult").show();

		jQuery.getJSON(baseURL,function(data) {
			SiggSearch.disableInput(false);
			PubmedSearch.updateCitations(data);
		})

		return false;

	}
}
