$(document).ready(setupFlashPopup);
$(document).ready(clipNewsToEllipsis);
$(document).ready(setupSubscribeClear);

function setupFlashPopup() {
   $('#homebanner_belance').click(function () {
      //open bookings popup from link's href attribute
      window.open(this.href, 'flashbrowser', 'width=1000,height=620,scrollbars=yes');
      return false;
   });
}


function setupSubscribeClear() {
   $('#subscribe_email').focus(function () {
      if (this.value == this.getAttribute('altvalue')) {
         this.value = '';
      }
   })
   .blur(function () {
      if (this.value == '') {
         this.value = this.getAttribute('altvalue');
      }
   });
}

function TweetShow() {
   var _self = this;
   var posturl, tweets, rootElement;
   var results = [];
   var formattedResults = [];
   var index = 0;

   var moveTime = 500;
   var pauseTime = 5000;


   _self.setUrl = function (url) {
      posturl = url;
   }
   _self.setElement = function (jRoot) {
      rootElement = jRoot;
   }
   _self.start = function () {
      jQuery.getJSON(
         posturl,
         function (jsonData, status, xhr) {
            results = jsonData.results;

            _self.formatResults();

            //set it in motion.
            _self.displayContent(0);
            setTimeout(_self.moveNext, pauseTime);
         }
      );
   }

   _self.getNextIndex = function () {
      index = ++index % results.length;

      return index;
   }
   _self.moveNext = function() {
      //move current out of sight
      rootElement.animate(
         { top:'-'+ rootElement.parent().get(0).offsetHeight },
         moveTime,
         function () {
            //when done,
            //fill with next data
            _self.displayContent(_self.getNextIndex());
            //move below bar
            rootElement.css({
               top: rootElement.parent().get(0).offsetHeight
            });

            //move back into sight.
            rootElement.animate({
               top: 0
            },
            moveTime);

            //wait for pauseTime
            //and start the cycle again.
            setTimeout(_self.moveNext, pauseTime);
         }
      );
   }

   _self.formatResults = function () {
      var baseurl = 'http://twitter.com/';
      var dtNow = new Date();

      //console.log(results.length);

      for (var i=0; i < results.length; i++) {
         //console.log('#'+i);
         //console.log(results[i].text);

         results[i].text = results[i].text.replace(/([@#]?elysium)/ig, '<a href="'+ baseurl +'thermenelysium" class="tweet_mention">$1</a>');
         results[i].text = results[i].text.replace(/(^| )(http:\/\/[^ ]+)($| )/ig, ' <a href="$2" class="tweet_link">$2</a> ');
         results[i].text = results[i].text.replace(/(@([a-z\d]+))/ig, ' <a href="'+ baseurl +'$2" class="tweet_userlink">$1</a> ');

         var dtCreated = new Date(results[i].created_at);
         var diffTime = dtNow.getTime() - dtCreated.getTime();
         var humanTime = getHumanTimeInterval(diffTime, dtCreated);

         formattedResults.push({
            user: results[i].from_user + ':',
            user_url: baseurl + results[i].from_user,
            text: results[i].text,
            date: humanTime +' '+ Globals.language.ago
         });

         //console.log(formattedResults[i].text);
      }
   }
   _self.displayContent = function (index) {
      $('.tweet_user', rootElement).html(formattedResults[index].user).attr('href', formattedResults[index].user_url);
      $('.tweet_text', rootElement).html(formattedResults[index].text);
      $('.tweet_date', rootElement).html(formattedResults[index].date);
   }
}

/* string getHumanTimeInterval
   in: difftime in milliseconds; fallback date if the time interval is too large.

   returns a labeled time since now, e.g. "5 seconds ago", "3 days ago".
*/
function getHumanTimeInterval(milliseconds, fallbackDate) {
   var humanTime;
   //console.log('ms', milliseconds);

   humanTime = milliseconds / (1000);
   //console.log('ht', humanTime);

   if (humanTime < 60) {
      return Math.floor(humanTime) + ' seconden';
   }

   humanTime = milliseconds / (1000 * 60);
   //console.log('ht', humanTime);

   if (humanTime < 60) {
      return Math.floor(humanTime) + ' minuten';
   }

   humanTime = milliseconds / (1000 * 60 * 60);
   //console.log('ht', humanTime);

   if (humanTime < 60) {
      return Math.floor(humanTime) + ' uur';
   }

   humanTime = milliseconds / (1000 * 60 * 60 * 24);
   //console.log('ht', humanTime);

   if (humanTime < 24) {
      return Math.floor(humanTime) + ' dagen';
   }

   humanTime = milliseconds / (1000 * 60 * 60 * 24 * 7);
   //console.log('ht', humanTime);

   if (humanTime < 7) {
      return Math.floor(humanTime) + ' weken';
   }

   return  fallBackDate.getDate() +' '+ (fallBackDate.getMonth() + 1) +' '+ fallBackDate.getFullYear() +', '
      + fallBackDate.getHours() +':'+ fallBackDate.getMinutes();
}

function clipNewsToEllipsis() {
	var canvasDiv = $('.homenews_newsintro');
   var wasClipped = false;

   canvasDiv.wrapInner('<div class="shrinkwrap">');

   var shrinkWrap = $('.shrinkwrap', canvasDiv);
	var strShrinkableHtml = shrinkWrap.text();

   while (shrinkWrap.height() > canvasDiv.height() + 2) {
      strShrinkableHtml = strShrinkableHtml.substr(0, strShrinkableHtml.length - 2);
		shrinkWrap.html(strShrinkableHtml);

		wasClipped = true;
   }

   if (wasClipped) {
      //cut off another few characters to make room for the ellipsis
      shrinkWrap.html( shrinkWrap.html().substr(0, shrinkWrap.html().length - 4).trim() + '...' );
   }
}
