// JavaScript Document

function convertDate(date) {
     var dateBits = date.split('-');
     var startDate = dateBits[1] + "/" + dateBits[2] + "/"+ dateBits[0];
     return startDate ;
     }

function dateDifference(date1, date2) {
     var startBits = date1.split('-');
     var finishBits = date2.split('-');

     //fix months
     startBits[1] = startBits[1] - 1;
     finishBits[1] = finishBits[1] - 1;

     //create date objects
     var startDate = new Date(startBits[0],startBits[1],startBits[2]);
     var finishDate = new Date(finishBits[0],finishBits[1],finishBits[2]);
     var difference;

     diff  = new Date();
     diff.setTime(Math.abs(startDate.getTime() - finishDate.getTime()));
     oneday = (1000 * 60 * 60 * 24);
     timediff = diff.getTime();

     weeks = Math.floor(timediff / (1000 * 60 * 60 * 24 * 7));
     timediff -= weeks * (1000 * 60 * 60 * 24 * 7);

     days = Math.floor(timediff / (1000 * 60 * 60 * 24)); 
     timediff -= days * (1000 * 60 * 60 * 24);


     if ((weeks == 0) && (days <= 1)) {
          difference = '1 day, ';
          }
     else if ((weeks == 0) && (days > 1)) {
          difference = days + ' days, ';
          }
     else if ((weeks == 1) && (days == 0)) {
          difference = '1 week, ';
          }
     else if ((weeks == 1) && (days == 1)) {
          difference = '1 week and 1 day, ';
          }
     else if ((weeks > 0) && (days == 0)) {
          difference = weeks + ' weeks, ';
          }
     else if ((weeks > 0) && (days == 1)) {
          difference = weeks + ' weeks and 1 day, '; 
          }
     else {
          difference = weeks + ' weeks and ' + days + ' days, '; 
          }
 
     return difference; 
}

RavelryThing2 = function() {
     var progressData = null;
            
     // Dollar and Dollar E convenience
     var $ = function(id) { return document.getElementById(id); };
        
     var $E = function(data) {
     var el;
     if ('string' == typeof data) {
          el = document.createTextNode(data);
     } else {
          el = document.createElement(data.tag);
          delete(data.tag);
          if ('undefined' != typeof data.children) {
                for (var i=0, child=null; 'undefined' != typeof (child=data.children[i]); i++) { if (child) { el.appendChild($E(child)); } }
                delete(data.children);
                }
          for (attr in data) { 
                if (attr == 'style') {
                for (s in data[attr]) {
                     el.style[s] =  data[attr][s];
                     } 
                } else if (data[attr]) {
                     el[attr]=data[attr]; 
                     }
                }
          }
          return el;
     };
            
     return {
          progressReceived: function(data) {
          progressData = data;
          },
        
              /*
                Allowed options are: color, width, height. For example:
                drawProgressBars({color: 'red', width: 200, height: 20});
              */
              drawProgressBars: function(options) {
                if (!progressData) return;
                
                if (!options) options = {};
                if ('number' == typeof options.height) options.height += 'px';
                if (!options.height) options.height = '1em';
                if (!options.width) options.width = 100;
                if (!options.color) options.color = 'lightgreen';
                if (!options.container) options.container = 'rav_progress_bars2';
                
                var container = $(options.container);
                if (!container) {
                  document.write("I have " + progressData.projects.length + " finished projects listed on ravelry! <div id='" + options.container + "'></div>");
                  container = $(options.container);
                }

// sort projects by started date
                    var projectsByDate = {};
                    var projectDates = [];
                    for (var i=0; i < progressData.projects.length; i++) {
                        var project = progressData.projects[i];
                        // assume any project without a start date was started the day completed 
                        if  (!project.started) project.started = project.completed;
                        var date = project.started;
                         if (!projectsByDate[date]) {
                             projectsByDate[date] = new Array();
                            projectDates.push(date);
                         } 
                         projectsByDate[date].push(project);
                    }

// reverse sort order (so newer projects come first)                    
                    projectDates.sort().reverse();
                    var selectedProjects = [];
                    for (var i=0; i < projectDates.length; i++) {
                        var currentDate = projectsByDate[projectDates[i]];
                        for (var j=0; j < currentDate.length; j++) {
                           selectedProjects.push(currentDate[j]);
                        }
                    }
               
                
                for (var i=0; i < selectedProjects.length; i++) {
                  var project = selectedProjects[i];
                  var filledStyle = { width: Math.round((project.progress/100) * options.width) + 'px', height: options.height, backgroundColor: options.color};
                  var barStyle = { width: (options.width) + 'px', height: options.height};
                  var className = 'fo_gallery'
                  
                  var photo = null;
                  if (options.photos && project.thumbnail) {
                  className += ' rav_project_with_photos';
                  photo = { tag: 'a', className: 'rav_photo_link', rel: 'lightbox[Gallery]', title: project.name + '<br><a href=\"' + project.thumbnail.flickrUrl + '\"> <img src=\"http://www.sarahspins.com/images/flickr-favicon.png\">flickr</a>', href: project.thumbnail.medium, children: [
{tag: 'img', src: project.thumbnail.src }
]
};
}
                  
                  var title = null;
                  if (options.title != false) {
                    title = { tag: 'a', className: 'rav_title', href: project.url, children: [project.name] };
                  }

//designer
                var designer = null;
                
                designer = {
                    tag: 'a',
                    target: '_blank',
                    className: 'rav_designer'
                };
                try {
                    designer.href = project.pattern.designer.url;
                    designer.children = [' by ' + project.pattern.designer.name];
                } 
                catch (ex) {
                    designer.href = ['http://www.sarahspins.com/'];
                     designer.children = ['(my own design)'];
                }

                var linebreak = null;
                linebreak = {
                tag: 'br'
                }
                


//favorited
                  var favorited = null;
                  if (project.favorited != 0) {
                  var favorited_text = null;
                  if (project.favorited == 1) { favorited_text = ' person loves this';}
                  else { favorited_text = ' people love this';}
                  favorited = { tag: 'a', title: project.favorited + favorited_text, className: 'rav_favorited',  href: [ project.url + '/comments' ], children: [ {tag: 'img', src: 'http://www.sarahspins.com/silk-heart.png', className: 'rav_favorited'}, ''+project.favorited] };
                  }

//comments
                  var comments = null;
                  if (project.comments != 0) {
                  var comment_text = null;
                  if (project.comments == 1) { comment_text = ' comment';}
                  else { comment_text = ' comments';}
                  comments = { tag: 'a', title: project.comments + comment_text, className: 'rav_favorited',  href: [ project.url + '/comments' ], children: [ {tag: 'img', src: 'http://www.sarahspins.com/silk-comment.png', className: 'rav_favorited'}, ''+project.comments] };
                  }

//yarn - for now only showing the first yarn used, I think for progress bars this is probably best
//                  var first_yarn = project.yarns[0];
//                  var yarn = null;
//                  yarn = { tag: 'a', className: 'rav_yarn', href: first_yarn.url, children: [' using ' + first_yarn.brand + ' ' + first_yarn.name ] };

		    var yarns = null;
		    if (options.yarns != false) {
			var yarnsOutput = 'using ';
//			if (project.yarns.length > 1) yarnsOutput += 's';
//			yarnsOutput += ': ';
			for (var j=0; j < project.yarns.length; j++) {
				if (j > 0  && j != project.yarns.length) {
					yarnsOutput += ", ";
				}
				yarnsOutput += project.yarns[j].brand + ' ' + project.yarns[j].name;

			}   
			yarns = { tag: 'div', className: 'rav_yarn', children: [yarnsOutput] };
                  }


                      var started = null;
                      if (project.started != false) {
                    
                        //convert date to mm/yyyy
                        var formattedStartDate = convertDate(project.started);
                          started = { tag: 'div', className: 'rav_started', children: ['started:' + formattedStartDate] };
                      }       
                      if (project.started == false) {
                        //var formattedStartDate = convertDate(project.completed);
                          started = { tag: 'div', className: 'rav_started', children: ['no start date given'] };
                          }

                      if (project.started == null) {
                        //var formattedStartDate = convertDate(project.completed);
                          started = { tag: 'div', className: 'rav_started', children: ['no start date given'] };
                          }

var happy_pic;
var happy_text;
if (project.happiness==4) {
happy_pic = 'http://www.sarahspins.com/emoticons/grin.png';
happy_text = 'I like this a lot!'
}
if (project.happiness==3) {
happy_pic = 'http://www.sarahspins.com/emoticons/smile.png';
happy_text = 'I like this a little'
}
if (project.happiness==2) {
happy_pic = 'http://www.sarahspins.com/emoticons/meh.png';
happy_text = 'This was okay'
}
if (project.happiness==1) {
happy_pic = 'http://www.sarahspins.com/emoticons/sad.png';
happy_text = 'I hate this'
}
if (project.happiness==0) {
happy_pic = 'http://www.sarahspins.com/emoticons/loser.png';
happy_text = 'This was horrible'
}

var happy = null;
if (project.happiness != 0)
{
happy = { tag: 'a', className: 'rav_happy', href: project.url, children: [
{ tag: 'img', title: happy_text, className: 'rav_happy', src: happy_pic }]
};
}

      var finished = null;
                      if (options.completed != false) {
                    
                        //convert date to mm/dd/yyyy
                        var formattedFinishDate = convertDate(project.completed);
                          finished = { tag: 'div', className: 'rav_started', children: ['Finished: ' + formattedFinishDate] };
                      } else {
                          finished = { tag: 'div', className: 'rav_started', children: ['no finish date given'] };
                      }

     
// time to finish
var timefinished = null;
var timefinishedformat = dateDifference(project.started, project.completed);
timefinished = { tag: 'div', className: 'rav_yarn', children: ['Completed in ' + timefinishedformat] };

                  container.appendChild($E({
                    tag: 'div',
                    className: className,
                    children: [ photo, { tag: 'div', className: 'rav_comment_fav_container', children: [ happy, comments, favorited ] }, title, linebreak, designer, started, finished, timefinished, yarns ]
                  }));
                }
              }
            }
          }();