/*extern ufJS, ufJSActions, ufJSParser, openUILink */ 
//�200-The MITRE Corporation.  All rights reserved.
//This code is available under the Creative Commons Attribution License


var directory = "" ;
var urlfileData = "";
var urlfilehtmlRender = "";
var jsonData = "timelinedata.js";
var htmlRender = "timelinedata.html";
var timelineDate = new Date();
var eventsCount = 0;
var fos1;
var fos2;
var datePeriod1 = "";
var datePeriod2 = "";
var date1="";
var date2="";
if (Components.utils.import) {
  try {
    Components.utils.import("rel:Microformats.js");
  } catch (ex) {}
}


var exhibit_timeline = {
      descriptionAll: "Exhibit Events",
       scope: {
       semantic: {
      "hCalendar" : "dtstart" 
      }
      },
        doActionAll: function(semanticObjects, semanticObjectType) {
      
           
          try {
          // Needed for Mozilla if local file tries to access an http URL
           netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
          } catch (e) {  /* ignore */ }
           setData(semanticObjects["hCalendar"], semanticObjectType);
           window.open(urlfilehtmlRender) ;
       //    fos1.remove();
       //    fos2.remove();
           //create script to display the timeline
           return;
       } 
      };

SemanticActions.add("exhibit_timeline", exhibit_timeline);
      

function setData(semanticObject, semanticObjectType) {

       
           //initialize the file for the data
          var file = Components.classes["@mozilla.org/file/directory_service;1"]
                     .getService(Components.interfaces.nsIProperties)
                     .get("TmpD", Components.interfaces.nsIFile);
          file.append(jsonData);
          file.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0664);
          // do whatever you need to the created file
          jsonData = file.leafName;
          // file is nsIFile
          var ios = Components.classes["@mozilla.org/network/io-service;1"]
                    .getService(Components.interfaces.nsIIOService);
          var fileHandler = ios.getProtocolHandler("file")
                     .QueryInterface(Components.interfaces.nsIFileProtocolHandler);
          urlfileData = fileHandler.getURLSpecFromFile(file);
          fos2 = Components.classes["@mozilla.org/network/file-output-stream;1"].
                               createInstance(Components.interfaces.nsIFileOutputStream);
    
           fos2.init(file, 0x04 | 0x08 | 0x20, 420, 0);
            var timelineEvent= "{'dateTimeFormat': 'iso8601', 'items' : [ " ;
           //convert hCalendar microformat into timeline JSON data format
           fos2.write(timelineEvent, timelineEvent.length);
           var data = timelineData2(semanticObject, semanticObjectType);
           data = data + "]}";
           fos2.write(data, data.length);
           fos2.close(); 
           //display the data into a timeline
            rendering2();
            return;
}



function rendering2() {

       
           //initialize the file for the data
          var file = Components.classes["@mozilla.org/file/directory_service;1"]
                     .getService(Components.interfaces.nsIProperties)
                     .get("TmpD", Components.interfaces.nsIFile);
          file.append(htmlRender);
          file.createUnique(Components.interfaces.nsIFile.NORMAL_FILE_TYPE, 0664);
          // do whatever you need to the created file
          htmlRender = file.leafName;
          // file is nsIFile
          var ios = Components.classes["@mozilla.org/network/io-service;1"]
                    .getService(Components.interfaces.nsIIOService);
          var fileHandler = ios.getProtocolHandler("file")
                     .QueryInterface(Components.interfaces.nsIFileProtocolHandler);
          urlfilehtmlRender = fileHandler.getURLSpecFromFile(file);
    
          fos1 = Components.classes["@mozilla.org/network/file-output-stream;1"].
                               createInstance(Components.interfaces.nsIFileOutputStream);
    
          fos1.init(file, 0x04 | 0x08 | 0x20, 420, 0);
          //write the Javascript file in a temporary html file needed to call the timeline webservice
           var data = setTimeline2();
           fos1.write(data, data.length);
           fos1.close();
            return;
}



  function timelineData2(semanticObject, semanticObjectType)
  {
    var events="";
    var hcalendars;
    //retrieve all of the events;
    //hcalendars = Microformats.get("hCalendar",content.document);
     if (!semanticObjectType) {
      hcalendars = Microformats.get("hCalendar",content.document);
    } else {
      hcalendars = [];
     // hcalendars.push(semanticObjectType);
     hcalendars = Microformats.get("hCalendar",content.document);
    } 
    eventsCount = hcalendars.length/2
     var events = "";
     for (var i in hcalendars)  {
     
          var hcalendar = hcalendars[i];
          //semanticObject;
          
            var event='{type: "event",' + "\r\n" + 'label: "Event ' + i + '",' + "\r\n" ;
          
           var dtStartDate ="";
            if (hcalendar.dtstart) {
                dtStartDate = hcalendar.dtstart;
                event +=  "'start':" + "'" + dtStartDate + "',"  + "\r\n";
                timelineDate = hcalendar.dtstart; 
                 var year1, year2;
                 if (i==0) {
                    date1 =  dtStartDate.substring(5,7);
                    year1 = dtStartDate.substring(0,4);
                    }
                 date2 = dtStartDate.substring(5,7);
                 year2 = dtStartDate.substring(0,4);
                 //set the period based on the month
                 var dateMonth = date1 - date2;
                 if (dateMonth < 0) dateMonth= dateMonth * -1 ;
              
                 if (dateMonth > 0) { 
                    datePeriod1 = "MONTH";
                    datePeriod2 = "YEAR";
                    }
                 else {
                    datePeriod1 = "DAY";
                    datePeriod2 = "MONTH";
                 }
                 if (year1 != year2)
                 {
                    datePeriod1 = "YEAR";
                    datePeriod2 = "YEAR";
                 }
          }
          var dtEnd = "";
          if (hcalendar.dtend) {
               dtEnd = "'end':" + "'" + hcalendar.dtend + "'," + "\r\n";
                   //    + "'isDuration':'true',"  + "\r\n" ;
          }
          
        var color = "";
        
        if (hcalendar.category) {
         color = "'color':";
         switch (hcalendar.category[0].toLowerCase()) {
             case "meeting": color += "'blue',";
             case "appointment": color += "'aqua',";
             case "anniversary": color += "'fuchsia',";
             case "appointment": color += "'gray',";
             case "business": color += "'lime',";
             case "education": color += "'maroon',";
             case "holiday": color += "'silver',";
             case "meeting": color += "'aqua',";
             case "miscellaneous": color += "'teal',";
             case "non-working hours": color += "'navy',";
             case "not in office": color += "'green',";
             case "personal": color += "'white',";
             case "phone-call": color += "'yellow',";
             case "sick-day": color += "'red',";
             case "special-occassion": "'purple',";
             case "travel": color += "'green',";
             case "vacation": color += "'gray',";
             case "expo":  color += "'olive',";
             case "conference": color += "'maroon',";
             case "family": color += "'green',";
             case "finance": color += "'blue',";
             default:
               color = "";
        }
       } 
      
      
      
      var title = "'title':"
      
       if (hcalendar.summary) {
        title +=  "'" +   removeSpecialCharacters(hcalendar.summary)  + "'," + "\r\n";
        }
       else 
       { title += "''," + "\r\n";    }
       
    
    
      var description = "'description':";
      if (hcalendar.description) {
        description += "'" + removeSpecialCharacters(hcalendar.description)  +"'," + "\r\n";}
      else {
       description += "''," + "\r\n";
     }
     
  
  
  
   var link = "'link':";
    if (hcalendar.url) {
       link += "'" + hcalendar.url  +"'," + "\r\n"; }
    else {
       link += "''," + "\r\n";}
    
    
  
    var image =  "'image': 'dull-blue-circle.png'";
    
    events += event + dtEnd +  title + description + link + color + "}" + "\r\n";
    //add the comment at the end
    if (i < (hcalendars.length-1)) events += ",";
   
  //  alert (events);
    }
    
    
    return(events);
  };



function setTimeline2() {

var head = ""

   head = "<html>" +
          "<head>" ;


var script = "";
    script =     '<link href="' + urlfileData + '" type="application/json" rel="exhibit/data" />' +
           '<script src="http://static.simile.mit.edu/exhibit/api/exhibit-api.js?views=timeline" type="text/javascript"></script>'  + "\r\n" +
              "<script>"  + "\r\n" +
              "var tl;" + "\r\n" + 
              " var timelineConfig = { " + "\r\n" +
              " timelineConstructor: " + "\r\n" +
              "function {" + "\r\n" +
               "var eventSource = new Timeline.DefaultEventSource(0);" + "\r\n" +
               "var theme = Timeline.ClassicTheme.create();" + "\r\n" +
               "theme.event.bubble.width = 320;" + "\r\n" +
               "theme.event.bubble.height = 220;" + "\r\n" +
               'var d = Timeline.DateTime.setIso8601(new Date(),"' + timelineDate +  '");' + "\r\n" +
                "var bandInfos = ["  + "\r\n" +
                    "Timeline.createBandInfo({" + "\r\n" +
                                             'width:          "90%",' + "\r\n" + 
                                             "intervalUnit:   Timeline.DateTime." + datePeriod1 + "," + "\r\n" + 
                                              "intervalPixels: 100," + "\r\n" +
                                              "eventSource:    eventSource," + "\r\n" +
                                              "date:           d," + "\r\n" +
                                              "theme:          theme" + "\r\n" +
                "}),"+ "\r\n" +
                 "return t1;} }" + "\r\n" + 
                  '       <link href="' + urlfileData + '" type="application/json" rel="exhibit/data" />' + "\r\n" +
                  " var resizeTimerID = null; " +
                  "function onResize() {" +
                     "if (resizeTimerID == null) {" +
                     "resizeTimerID = window.setTimeout(function() {" +
                      "resizeTimerID = null;" +
                       "tl.layout();" +
                       "}, 500);" +
                       "}"  +
                     '</script>' + 
                  
                      '<script src="http://static.simile.mit.edu/exhibit/api/exhibit-api.js" type="text/javascript">' +    
                     '</script>' + "\r\n" +
                    '<script type="text/javascript">' +
                    'function rowStyler(itemID, Database, tr) { ' +
                     
                            'tr.style.textAlign = "center"; '+
                            'tr.style.fontFamily = "Verdana, Geneva, Arial, Helvetica, sans-serif"; '+
                            'tr.style.fontWeight = "normal"; ' +
                            'tr.style.fontSize = "12px"; ' +
                            'tr.style.color = "#fff"; ' +
                            'tr.style.width = "280px"; ' +
                            'tr.style.backgroundColor = "#666"; ' +
                            'tr.style.border = "0px"; ' +
                            'tr.style.borderCollapse = "collapse"; ' +
                            'tr.style.borderSpacing = "0px"; '+
                            'tr.style.padding = "4px"; ' +
                            'tr.style.textAlign = "left"; ' +
                            'tr.border = "1px #fff solid"; ' + 


                      
                    '}</script>' + 
                    '<style>' +
                    "exhibit-control-panel {" +
                    "   clear:  both;" +
                    "}" +
                    "exhibit-browse-panel {" +
                    "}" +
                    "exhibit-view-panel {" +
                      "padding:   1 em o.5in;" +
                    "}" +
                    "div.exhibit-browsePanel-logoContainer {" +
                     "        display: none;" +
                     "    }" +
                "    div.exhibit-facet-frame {" +
                        "       width: 16em;" +
                        "       float: left;" +
                    "    }" +
                    "div.exhibit-facet-body {" +
                "        border: 1px solid #BCB79E;" +
                "    }" +
                    "td.exhibit-tileView-itemIndex {" +
                "        display: none;" +
                "   }" +
                "    span.exhibit-collectionView-group-count {" +
                "        color:       #ccc;" +
                "        font-weight: normal;" +
                "    }" +
                "    div.exhibit-facet-value-selected {" +
                "       background:  none;" +
                "        font-weight: bold;" +
                "    }" + "</style>" + 
                   ' </head>' + "\r\n";
              
        
           var body = "";
           body =   '<body id="body">' +
                    '<div id="exhibit-control-panel"></div>' +
                    '             <div id="exhibit-view-panel" >' + "\r\n" +
                    '               <div ex:role="exhibit-view"' +
                    '                    ex:viewClass="Exhibit.TabularView"' +
                    '                    ex:columns=".start, .title, .description, .link"' +
                    '                    ex:rowStyler="rowStyler"' +
                    '                    >' +
                
                    '                </div>' +
                    '        <div ex:role="exhibit-view"' +
                    '                    ex:viewClass="Exhibit.TimelineView"' +
                    '                    ex:start = ".start"' +
                    '                    ex:end = ".end" ' +
                    '                    ex:configuration="timelineConfig"' +
                                     '>' +
                                   '<div ex:if-exists=".title">' + 
                                      '<span ex:content=".title"></span>' +
                                   '</div>' +
                                   '<div ex:if-exists=".description">' +
                                             '<span ex:content=".description"></span>' + 
                                   ' </div>' +
                                    '<span ex:content=".start"></span>' +
                                    '<span ex:content=".end"></span>' +
                             '</div>' +
                    '       </div>' +
        
                     '</div>' + 
                    '<div id="exhibit-browse-panel" ex:facets=".start, .title"></div>' +
                    '</body></html>';
                    
                   
            return(head+script+body);
     };

//This function was adapted from yahoo.js
//written by Mike Kaply


function removeSpecialCharacters(s) {

 s = removeNL(s)
 s  = s.replace(/\<br\s*\>/gi, '%0D%0A');
 s  = s.replace(/\<\/p>/gi, '%0D%0A%0D%0A');
 s  = s.replace(/\<.*?\>/gi, '');
 s  = s.replace(/^\s+/, '');
  s=   s.replace(/\'/g, "&#xx;");
 return(s);

}

//This function has been adapted from
//http://www.rgagnon.com/jsdetails/js-0041.html

function removeNL(s) {
  /*
  ** Remove NewLine, CarriageReturn and Tab characters from a String
  **   s  string to be processed
  ** returns new string
  */
  var r = "";
  for (var i=0; i < s.length; i++) {
    if (s.charAt(i) != '\n' &&
        s.charAt(i) != '\r' &&
        s.charAt(i) != '\t') {
      r += s.charAt(i);
      }
    }
  return r;
  }
