
var numArticles = 0;
var articles = new Array();

var monthNames = new Array(12);
monthNames[0] = "Jan";
monthNames[1] = "Feb";
monthNames[2] = "Mar";
monthNames[3] = "Apr";
monthNames[4] = "May";
monthNames[5] = "Jun";
monthNames[6] = "Jul";
monthNames[7] = "Aug";
monthNames[8] = "Sep";
monthNames[9] = "Oct";
monthNames[10] = "Nov";
monthNames[11] = "Dec";

var totalMonthsWidth = 0;
var monthWidths = null;
var dayWidth = 0;
var weekWidth = 0;
var frameWidth = 0;
var monthsOffset = 0;

//Time information
var today = null;
var year = 0;
var numDaysInYear = 0;
var firstDayInYear = 1;


function initTimeline() {

	$j(document).ready(function(){  
      
    frameWidth = $j("#timeline").width();
    
    calcTime();    
    monthWidths = new Array(12);
    dayWidth = 2;
    weekWidth = (dayWidth * 7) - 1;
    
    $j("#tl_year_overlay").html(year);    
    
    generateTimeline();
      
    /* THOMAS */
    ysortArticles(); 
    applyfloat();
       
    
    $j("#tl_zoom_out").click(zoomOut);
    $j("#tl_zoom_in").click(zoomIn);    
  });
}


function calcTime() {
  today = new Date();
  
  year = today.getFullYear();

  today.setMonth(0);            
  today.setDate(1);        
  today.setFullYear(year + 1);

  var endOfYear = today.getTime() - today.getTimezoneOffset();

  today.setFullYear(year);  

  firstDayInYear = today.getDay();
  
  var startOfYear = today.getTime() - today.getTimezoneOffset();
  
  var difference = endOfYear - startOfYear;

  numDaysInYear = Math.floor((((difference / 1000) / 60) / 60) / 24);  
}


function calcMonthWidths() {
  var index = 0;
  var dayCounter = 0;
  
  // Find the amount of days in each month
  for(var m = 0; m < 12; m++) {
    for(var d = 1; d < 33; d++) {
      today.setMonth(m);      
      today.setDate(d);
      
      if(today.getMonth() == m) {
        dayCounter++;
      }
    }

    monthWidths[index] = dayCounter * dayWidth;
    index++;
    dayCounter = 0;
  }  
}


function generateTimeline() {
  //Months
  for(var m = 0; m < 12; m++) {
    if(m % 2 == 0) {
      $j("#tl_months").append("<div class='even_column'><span>" + monthNames[m] + "</span></div>");
    }
    else {
      $j("#tl_months").append("<div><span>" + monthNames[m] + "</span></div>");      
    }
  }  
  $j("#tl_months").append("<div class='no_float'></div>");
  
  //Weeks
  for(var w = 0; w < 53; w++) {
    $j("#tl_weeks").append("<div style='width:" + weekWidth + "px;'></div>");          
  }
  $j("#tl_weeks").append("<div class='no_float'></div>");
  
  scaleTimeline();
}


function zoomOut() {
  $j(document).ready(function(){
    //dayWidth--;
    dayWidth -= 2;
    if(dayWidth < 2) {
      dayWidth = 2;
    }
    scaleTimeline();
  });    
}


function zoomIn() {
  $j(document).ready(function(){    
    //dayWidth++;
    dayWidth += 2;
    //document.getElementById("tl_frame").scrollLeft += document.getElementById("tl_frame").scrollLeft * 2;
    
    scaleTimeline();
  });    
}


function scaleTimeline() {
  // Scale months  
  calcMonthWidths();
  
  var cols = $j("#tl_months").find("div");
  for(var m = 0; m < 12; m++) {
    $j(cols[m]).css("width", monthWidths[m] + "px");
  }  
  
  // Calculate total months width   
  totalMonthsWidth = 0;
  jQuery.each(monthWidths, function(){totalMonthsWidth += this});  
  $j("#tl_months").css("width", totalMonthsWidth + "px");

  // Calculate months offset
  monthsOffset = (firstDayInYear * dayWidth) - dayWidth;
  $j("#tl_months").css("left", monthsOffset + "px");
  
  
  // Scale weeks
  weekWidth = (dayWidth * 7) - 1;
  cols = $j("#tl_weeks").find("div");
  for(var w = 0; w < 53; w++) {
    $j(cols[w]).css("width", weekWidth + "px");
  }

  // Calculate total weeks width     
  $j("#tl_weeks").css("width", ((weekWidth + 1) * 53) + "px");
  
  // Reposition the articles
  for(var i = 0; i < numArticles; i++) {
    articles[i].xposition();
  }
  ysortArticles();
  applyfloat();
}

function addSingleArticle(topic) {
    var pdates = topic.publishDate.split("-");
    //document.write(topic.title+"<br />");
   //console.log(pdates);
   
    $j(document).ready(function(){  
    numArticles++;
    $j("#tl_frame").append("<div class='tl_story'>" +
    
      "<div class='tl_story_content'>" +
        "<a href='" + topic.url + "'>" +
          "<img src='" + topic.pictureUrl + "' alt='' />" +
        "</a>" +
        "<div class='tl_story_content_text'>" +
            "<a href='" + topic.url + "'>" +
              "<div class='tl_story_content_title'>" + topic.title+ "</div>" + 
              "<div class='tl_story_content_date'>" + pdates[2] + ". " + monthNames[pdates[1] - 1] + " " + pdates[0] + "</div>" +
              "<div class='tl_story_content_teaser'>" +  topic.teaser + "</div>" +
            "</a>" +  
        "</div>" + 
        "<div class='no_float'></div>" + 
      "</div>" + 
      "<div class='tl_story_shadow'></div></div>");

    // Attach mouse over events
    $j($j("#tl_frame").find(".tl_story")[numArticles - 1]).mouseover(function(e){$j(this).toggleClass("mouseover")});
    $j($j("#tl_frame").find(".tl_story")[numArticles - 1]).mouseout(function(e){$j(this).toggleClass("mouseover")});      
    
    // Create article object
    articles.push(new TimelineArticle($j("#tl_frame").find(".tl_story")[numArticles - 1], parseInt(pdates[2],10), parseInt(pdates[1],10)));
  });
}


function addArticles(topics) {
  var x;
  //console.log(topics);
  for (x in topics) {
    if (topics[x].title != undefined)
      addSingleArticle(topics[x]);
  }
}

function TimelineArticle(artId, day, month) {
  
  var m_day = day;
  var m_month = month;
  var m_artId = artId;

  var m_xpos = 0;
  var m_ypos = 0;

  this.xposition = function() {
    m_xpos = monthsOffset;
    
    for(var m = 0; m < month - 1; m++) {
      m_xpos += monthWidths[m];
    }
    m_xpos += (day - 1) * dayWidth;
    
    $j(m_artId).css("left", (m_xpos - 29) + "px");
  }
  
  this.yposition = function(ypos) {
    m_ypos = ypos;
    $j(m_artId).css("top", m_ypos + "px");    
  }
  
  this.getDay = function() {
    return m_day;
  }

  this.getMonth = function() {
    return m_month;
  }
  
  /*THOMAS*/
  this.getX = function() {
    return m_xpos;
  }

  this.getY = function() {
    return m_ypos;
  }
  
  /*
  this.getW = function() {
    return m_xpos + 0;
  }

  this.getH = function() {
    return m_ypos;
  }*/
   
}


function ysortArticles() {
  
  var y = $j("#tl_weeks").position().top;  
  var day = 0;
  var month = 0;
  var prevDay = 0;
  var prevMonth = 0;

  for(var i = 0; i < numArticles; i++) {
    prevDay = day;
    prevMonth = month;
    day = articles[i].getDay();
    month = articles[i].getMonth();
    
    if(month == prevMonth && day == prevDay) {
      y += $j($j("#tl_frame").find(".tl_story")[0]).innerHeight();          
    }
    else {
      y = $j("#tl_weeks").position().top;
    }

    articles[i].yposition(y);
  }
}

// BEGIN NHST FLOAT CODE
// This is the code we use in our timeline
// Above code is only for drag/drop purposes
//
// Code assumes that the elements are placed from left to right
// and that we get an array of these elements in the right order
//
// thomas.kjelsrud@dn.no
//
change = false;

function applyfloat() {
  // Get list of elements (will be divs in our timeline)
  // This list must be ordered (left -> right placement)
  // Every div must have left/top and width/height set in CSS
  // If width/height is not set in CSS - we can use constants
  //

  // TEMP - Hard coding width + height
  w = 150;
  h = 53;
  //
  rectList = new Array();
  
  for(i = 0; i < numArticles; i++) {
    
    tRect = new Array(articles[i].getX(), articles[i].getY(), articles[i].getX() + w, articles[i].getY() + h );
    newRect = findlocy(rectList, tRect);
    rectList[i] = newRect;
    articles[i].yposition(newRect[1]);
  }
  if(change) {
    //
    // Run another recursion if changes were made the last round
    //
    change = false;
    applyfloat();
  }
}

function findlocy(rectList, rect) {
  // This code finds space on the Y-axis for the element (rect)
  //
  pad = 5;
  for(j = 0; j < rectList.length; j++) {
    xRect = rectList[j];
    xIn = false;
    yIn = false;
    if(xRect[0] <= rect[0] && xRect[2] >= rect[0]) xIn = true;
    if(xRect[1] <= rect[1] && xRect[3] >= rect[1]) yIn = true;

   if(xIn && yIn) {
     rect[1] = rect[1] + (xRect[3] - rect[1]) + pad;
     rect[3] = rect[3] + (xRect[3] - rect[1]) + pad;
     change = true;
   }
  }
  return rect;
}
//
// END FLOAT CODE
//


