/*
<!--                                            -->
<!--    Script created by Evangelos Pafilis     -->
<!--     as part of his PhD Reflect project     -->
<!--              November 2007                 -->
<!--                                            -->
<!--            pafilis@embl.de                 -->
<!--                                            -->
*/

/*
* <!--------------------------------------------->
* <!--                 History                 -->
* <!--------------------------------------------->
*
* 10.04.08: added Reflect_nestedFrameURL( url ): reflect the urls sent by the
*           content iframe
* 07.01.08: browser detection and appopriate page navigation added
* 06.01.08: added methods required for the main web page 
*           (content iframe creation and reseting implemented as generic 
*            iFrameHandling methods)
* 15.12.07: url encoding is required -> back in the code
* 14.12.07: not encoding the url to be send anymore - updating the iframe
*               overlib + pop-up script injection in the head modularised
* 09.12.07: pointing to reflect.embl.de (public) posting only the proxy server
*               (the proxy will communicate with the tagging server) 
* 16.11.07: switched to synchronous xmlhttp request 
* 09.11.07: main functionality retrieve a url via proxy and 'reflect' page
* 
* 14.10.08: added a security check to prevent content leaking for certain journals
*
*/


//<!--      constants           -->
//<!------------------------------>
//var Reflect_proxyURL = 'cgi-bin/reflectProxy.cgi'; // the servlet exists in the same server
var Reflect_proxyURL = 'REST/GetEntities'; // the servlet exists in the same server
var Reflect_debugging   = false;
var Reflect_WorkInProgressPage  = '<html><head><title>Reflection in progress</title>' +
'<link rel="stylesheet" type="text/css" href="style/Reflect.css" />' +
'</head>' +  
'<body class="greyBackground"><center><br><br><br><br><br>' +
'<img src="img/throbber.gif" alt="Reflection in progress..."/> '+
'</center></body></html>';
var Reflect_content_iframe_name = 'reflect_content_iframe';


var Reflect_FirefoxDownloadPage = "FirefoxDownload.html";
var Reflect_IEDownloadPage = "IEDownload.html";
var Reflect_BookmarkletDownloadPage = "BookmarkletDownload.html";

var input_is_url = 1;

//<!--      ReflectAURL page elements         -->
//<!-------------------------------------------->
//var Reflect_pageDoc     = this.document;
var Reflect_iFrame      = parent.reflect_content_iframe;//Reflect_pageDoc.getElementById(Reflect_content_iframe_name);
var Reflect_iFrameDoc   = Reflect_getIFrameDoc( Reflect_iFrame );

//<!--                  Procedures                       -->
//<!------------------------------------------------------->

function Reflect_setDownloadPage(){
        var link = Reflect_defineProperDownloadPage();
        Reflect_iFrame.location = link;
}

function Reflect_reflectRequestedURL() {
        
        var requestedURL = Reflect_getRequestedURL();
        
//        if (Reflect_URLIsAllowed( requestedURL ))
//        {
                Reflect_reflectURL(requestedURL);
//        }
//        else
//        {
//                alert('The Reflect web page is not allowed to process \n full text articles from this journal. \n\n Please try using the Reflect browser plug-in instead.' );
//        }
        
}


function Reflect_URLIsAllowed( url ){
        var allowed = true;

        //journal specific content leaking prevention rules
        if ( /dev\.biologists\.org\/cgi\/content\/full/.test( url ) )
        {
                allowed = false;   
        }
        else if ( /journals\.royalsociety\.org\/content/.test( url ) )
        {
                allowed = false;
        }

        return allowed;
}


function Reflect_processRequestedURL( url ){
        
        input_is_url = 1;
        
        if ( /\s/.test( url ) ) 
        { /* true if there is any white space in the provided url */
//                url = "http://www.google.com/search?ie=UTF-8&oe=UTF-8&q=" + Reflect_encodeURL( url );
                input_is_url = 0;
        }
        else if ( !(/\./.test(url)) )
        { /* there is not dot (and no white space) => single word, no IP */
//                url = "http://www.google.com/search?ie=UTF-8&oe=UTF-8&q=" + url;
                input_is_url = 0;
        }
        
        url = Reflect_appendHTTPProtocolIfMissing(url);         
        return url;
}


function Reflect_isOpera(){
        if (navigator.userAgent.indexOf("Opera") != -1)
        {
                return true;
        }
        else
        {
                return false;
        }
}


/* NXT: merge with Reflect_reflectRequestedURL */
function Reflect_reflectURL( url ) {
        
        var requestedURL = url;
        
        if  (requestedURL == "") { return; }
        
        /* /_reg_ex_/.test("target") returns true if the target string matches the regEx */ 
        if  ( /type\ or\ paste\ a\ URL/.test( requestedURL ) ){ return; }

        requestedURL = Reflect_processRequestedURL( requestedURL );
                
//        requestedURL = "http://reflect.cbs.dtu.dk/REST/GetPopup?name="+encodeURIComponent(requestedURL)+"&entity_types=9606%20-1";
        if(input_is_url == 1){
          Reflect_iFrame.location = "http://reflect.cbs.dtu.dk/REST/GetHTML?uri="+encodeURIComponent(requestedURL);
        }else{
          var runAsynchronously = true;
          var reflectRequestData = "document="+requestedURL+"&format=tsv";
          var reflectedPage = Reflect_retrieveTaggedPageContents_updateIFrame(
            Reflect_proxyURL, reflectRequestData, runAsynchronously);
//          requestedURL = "http://reflect.cbs.dtu.dk/REST/GetPopup?name="+encodeURIComponent(requestedURL);
//          Reflect_iFrame.document.body.innerHTML = "";
//          Reflect_iFrame.document.write("<body style='text-align: center; background-color: #CCCCCC'><iframe scrolling='no' style='height: 247px; width: 402px;' src='"+requestedURL+"'></iframe></body>");
        }
        return;

        //updates input field (displays the http if it were missing)    
        Reflect_pageDoc.getElementById('reflect_urlInputField').value = requestedURL; 
        
        /* before doing anything else, reset the reflect_content_iframe */
//        if (Reflect_isOpera()){alert('opera 4a');}
        
        Reflect_resetIFrame(Reflect_content_iframe_name);
//        if (Reflect_isOpera()){alert('opera 4b');}
        
//        if (Reflect_isOpera()){alert('opera 1');}
        var org = document.getElementById("reflect_organism_selection").value;
        var reflectRequestData = 'url='+ Reflect_encodeURL(requestedURL) + '&entity_types=' + org;
        var runAsynchronously = true;
        var reflectedPage = Reflect_retrieveTaggedPageContents_updateIFrame(
        Reflect_proxyURL, reflectRequestData, runAsynchronously);
//        if ( Reflect_isOpera() ){ alert('opera 3'); }
}



function Reflect_appendHTTPProtocolIfMissing( url ) {
        var urlWithProtocol="";
        
        var containsHTTPProtocol = false;
        
        //RegEx \^http.?:\/\/.* matches either http://something or https://something
        containsHTTPProtocol = /^http.?:\/\/.*/.test(url);
        if (!containsHTTPProtocol)
        {
//                urlWithProtocol = "http://" + url;
                urlWithProtocol = url;
                return urlWithProtocol;
        }
        else
        {
                return url;
        }
}


/* cross-browser retrieval of the iFrame document */
function Reflect_getIFrameDoc( iFrame ){
        
        if (!iFrame) { return; }
        
        var iFrameDoc = '';
        
        if (iFrame.contentDocument) { //NS6, Safari, Opera
                iFrameDoc = iFrame.contentDocument; 
        } 
        else if (iFrame.contentWindow) { //IE5.5 and IE6
                iFrameDoc = iFrame.contentWindow.document;
        } 
        else if (iFrame.document) { //IE5
                iFrameDoc = iFrame.document;
        }
        
        return iFrameDoc;
}


function Reflect_removeIFrame ( iframe ) {
        var parent  = iframe.parentNode;
        parent.removeChild(iframe);
}



function Reflect_getRequestedURL() {
        var url = Reflect_trim(Reflect_extractURL()); 
        
        if (url == "") {  alert("You must enter a URL"); }
        
        if (Reflect_debugging) {alert('requestedURL, not-encoded:' + url); } 
        
        return url;
}






function Reflect_updateIFrameURL( iFrameDoc, newURL ) {
        iFrameDoc.location.href = newURL;
}


function Reflect_updateIFrameContents( iFrameDoc,   newContents ) {
        iFrameDoc.open();
        try { iFrameDoc.write( newContents ); } catch (e){alert(e);}
        iFrameDoc.close();
}






function Reflect_encodeURL( url ){
        
        var encodedURL = encodeURIComponent(url);
        if (Reflect_debugging) {alert('requestedURL, encoded:' + encodedURL); }
        return encodedURL;
        
}



/*
*  @param data "param=value" pairs
*  
*  update IFrame action takes place as a callback inside 
*  http_request.onreadystatechange (after the tagged text has been retrieved)
*  (readyState == 4 && http_request.status == 200)
* 
*/
function Reflect_retrieveTaggedPageContents_updateIFrame(middleware_url, data, runAsynchronously) {
        
        
        var http_request = false;
        
        
        if (window.XMLHttpRequest) { // Mozilla, Safari,...
                http_request = new XMLHttpRequest();
                if (http_request.overrideMimeType) { http_request.overrideMimeType('text/html');      }
        } 
        else if (window.ActiveXObject) { // IE 
                try {	http_request = new ActiveXObject("Msxml2.XMLHTTP"); 	} 
                catch (e) {
                        try   { 	http_request = new ActiveXObject("Microsoft.XMLHTTP"); } 
                        catch (e) {alert(e)}
                }
        }
        if (!http_request) { alert('Cannot create XMLHTTP instance');   return false;          }
        
        http_request.onreadystatechange = function() {
                if (http_request.readyState < 4) {
                        if (Reflect_debugging) { alert('1. http_request.readyState: ' +  http_request.readyState); }
                        
                        //Reflect_updateIFrameContents( Reflect_iFrameDoc, Reflect_WorkInProgressPage );
                        //Reflect_setContents (Reflect_content_iframe_name, Reflect_WorkInProgressPage );
                        
                }
                else //if (http_request.readyState == 4)
                        {
                                if (http_request.status == 200) {
                                        
                                        if (Reflect_debugging) { alert('2. http_request.status:' +  http_request.status);  }
                                        result = http_request.responseText;
                                        if (Reflect_debugging) {alert('retrieved ' + result); }

                                        var array = result.split("\n");
                                        var entities = new Array();
                                        for (var i=0;i<array.length;i++){
                                          if(array[i]){
                                            var tmp = array[i].split("\t");
                                            entities.push(encodeURI(tmp[2]+'.'+tmp[3]));
                                          }
                                        }
//                                        var popupURL = "http://reflect.cbs.dtu.dk/fcgi-bin/solveAmbig.fcgi?entities="+entities.join(";");
//                                        var iFrame = "<iframe style='height: 245px; width: 400px;' src='"+popupURL+"'></iframe>";

                                        if(entities.length > 0){
                                          Reflect_iFrame.document.location.href = "iframe.html?"+entities.join(";");
                                        }else{
                                          Reflect_iFrame.document.location.href = "noresult.html";
                                        }
//                                        Reflect_iFrame.document.body.innerHTML = "";
 //                                       Reflect_iFrame.document.write("<body style='text-align: center; background-color: #CCCCCC'>"+iFrame+"</body>");
//                                        Reflect_setURL( Reflect_content_iframe_name, result);
                                }
                                else { 
                                        alert(http_request.status + ' error ' + http_request.statusText);
                                        return;
                                }
                        } 
                }
                
                if (Reflect_debugging) {alert('POSTing: ' + middleware_url + ' to retrieve ' + data + ' contents ' ); }

                try 
                {
                    http_request.open("POST", middleware_url, runAsynchronously); //async (T/F)
                } 
                catch (e) 
                {
                    //alert('Error: ' + e + ' middleware_url: ' + middleware_url + ' data: ' + data);
                }
                
                //http_request.setRequestHeader("User-agent", "Mozilla/4.0");
                http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                http_request.setRequestHeader("Accept", "application/atom+xml,application/xml,text/xml");
                http_request.setRequestHeader("Connection", "close");
                http_request.send(data);  //parameter-value pair
        }
        
        
        function Reflect_getIFrameDocumentHead() {
                
                var head = Reflect_iFrameDoc.getElementsByTagName('head')[0];
                if(!head) { 
                        alert('html page without "head"');
                        return '';
                }
                return head;
        }
        
        
        function Reflect_extractURL() {
                
                var url = document.getElementById("reflect_urlInputField").value;
                return url;
        }
        
        
        
        
        // will trim all leading and trailing whitespace
        // from the incoming string, and convert all runs of more than one whitespace
        // character into a single space. The altered string gets returned.
        function Reflect_trim(string) {
                // If the incoming string is invalid, or nothing was passed in, return empty
                if (!string)
                        return "";
                
                string = string.replace(/^\s+/, ''); // Remove leading whitespace
                string = string.replace(/\s+$/, ''); // Remove trailing whitespace
                
                // Replace all whitespace runs with a single space
                string = string.replace(/\s+/g, ' ');
                
                return string; // Return the altered value
        }
        
        
        
        function Reflect_resetIFrame(iFrameName) {
         
                var iFrame = Reflect_getIFrame (iFrameName);
                var parentNode = iFrame.parentNode;
//                if (Reflect_isOpera()){alert('opera 5a, iframe: ' + iFrame + " iFParent "+ parentNode );}
                Reflect_removeIFrame(iFrame, parentNode);
//                if (Reflect_isOpera()){alert('opera 5b');}
        
                Reflect_createAndAdd(iFrameName, parentNode);
//                if (Reflect_isOpera()){alert('opera 5c');}
        
        }
        
        function Reflect_getIFrame(iFrameName){
                var iFrame = this.document.getElementById(iFrameName);
                return iFrame;
        }
        
        function Reflect_removeIFrame(iFrame, parentNode){
//                if (Reflect_isOpera()){alert('opera 5ai');}
                parentNode.removeChild(iFrame);			
//                if (Reflect_isOpera()){alert('opera 5aii');}
        
        }
        
        
        /* creates the iframe with the "iFrameName" id and adds it to the "parentNode" */ 
        function Reflect_createAndAdd(iFrameName, parentNode){ 
                var iFrame = this.document.createElement('iframe'); /* Do not change */
                iFrame.setAttribute('id', iFrameName);
                iFrame.setAttribute('scrolling', 'auto');
                iFrame.setAttribute('width', '100%');
                iFrame.setAttribute('height', '1800'); 
                iFrame.setAttribute('frameBorder', '0');
                parentNode.appendChild(iFrame);
        }
        
        
        
        
        
        function Reflect_setURL( iFrameName, url){
                var iFrameDoc = Reflect_getIFrameDoc( Reflect_getIFrame( iFrameName ) );
                iFrameDoc.location.href = url;
        }
        
        function Reflect_setContents( iFrameName,   newContents ) {
                var iFrameDoc = Reflect_getIFrameDoc( Reflect_getIFrame( iFrameName ) );
                iFrameDoc.open();
                try { iFrameDoc.write( newContents ); } catch (e){alert(e);}
                iFrameDoc.close();
        }
        
        
        
        
        /* reset the "iFrameName" iframe and sets its location to "url"*/
        function Reflect_display(url, iFrameName){
                Reflect_resetIFrame(iFrameName); 
                Reflect_setURL(iFrameName, url);
        }
        
        function Reflect_displayDownloadPage(){
                var downloadPageName = Reflect_defineProperDownloadPage();
                Reflect_display(downloadPageName, Reflect_content_iframe_name);
        }
        
        function Reflect_defineProperDownloadPage(){
                
                var downloadPageName = "";
                var browserName = Reflect_getBrowserName();
                if (browserName == "firefox"){
                        downloadPageName = Reflect_FirefoxDownloadPage;
                }
                else if (browserName == "msie") {
                        downloadPageName = Reflect_IEDownloadPage;
                }
                else {
                        downloadPageName = Reflect_BookmarkletDownloadPage;
                }
                
                return downloadPageName;
        }
        
        /*
        * source: http://quomon.com/question_How_Identify_browser_java_script_IE_Safari_Firefox_2311.aspx
        * @returns A string which specifies which is the current
        * browser in which we are running.
        *
        * Currently-supported browser detection and codes:
        * * 'opera' -- Opera
        * * 'msie' -- Internet Explorer
        * * 'safari' -- Safari
        * * 'firefox' -- FireFox
        * * 'mozilla' -- Mozilla
        *
        * If we are unable to property identify the browser, we
        * return an empty string.
        *
        * @type String
        */
        function Reflect_getBrowserName() {
                var browserName = "";
                
                var ua = navigator.userAgent.toLowerCase();
                if ( ua.indexOf( "opera" ) != -1 ) {
                        browserName = "opera";
                }
                else if ( ua.indexOf( "msie" ) != -1 ) {
                        browserName = "msie";
                }
                else if ( ua.indexOf( "safari" ) != -1 ) {
                        browserName = "safari";
                } 
                else if ( ua.indexOf( "mozilla" ) != -1 ) {
                        if ( ua.indexOf( "firefox" ) != -1 ) {
                                browserName = "firefox";
                        } 
                        else {
                                browserName = "mozilla";
                        }       
                }
                 
                return browserName;
        };
        
        
