/*A NIPS object that tries to prevent namespace pollution and provides common javascript utilities*/
/*Tested with jquery 1.4.2*/
NIPS = {};
NIPS.log = function(t, m) { //Type should be one of: Info, Notice, Error
  $.ajax({
     type: 'POST',
     timeout: 600, //10s
     url: '/ajax/log.php',
     data: ({Type : t, Message : m}),
   });
}

NIPS.showCountdown = function(deadline, container) {  //deadline is in unixtime and is less than 1 week away
  var Countdown = [];
  Countdown[container] = deadline;
  
  setInterval(function() {
    var NowObj = new Date();
    var NowTime = parseInt(NowObj.getTime()/1000);
    var secondsLeft = Countdown[container] - NowTime;
    
    if (secondsLeft < 0) {
      return;
    }
    
    minutesLeft = parseInt(secondsLeft/60);
    hoursLeft = parseInt(secondsLeft/60/60);
    daysLeft = parseInt(secondsLeft/60/60/24);
    hourCount = parseInt(hoursLeft - (daysLeft*24));
    minuteCount = parseInt(minutesLeft - (hoursLeft*60));
    secondCount = secondsLeft - minutesLeft*60;
    
    $('#'+container).html(NIPS.addLeadingZero(daysLeft) + 'd ' + NIPS.addLeadingZero(hourCount) + 'h ' + NIPS.addLeadingZero(minuteCount) + 'm ' + NIPS.addLeadingZero(secondCount) + 's');

  },1000);
  
}

NIPS.addLeadingZero = function(number) {
  if (/^\d$/.test(number)) {
    return '0' + number;
  }
  return number;
}

NIPS.escapeHTML = function (s) {
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
};

NIPS.replaceFields = function (fields, text) {
  for (var f in fields) {
    var k = "{" + f + "}";
    while (text.indexOf(k) != -1) {
      text = text.replace(k, fields[f]);
    }
  }
  
  return text;
}

$(document).ready(function () {
  $.ajaxSetup({"error":function(XMLHttpRequest,TextStatus, Exception) {
    if (!Exception) {
      return;   //filters out noise
    }
    else if (!Exception.message) {
      return; //filters out more noise
    }
    else {
      Message = Exception.message;
    }
    
    NIPS.log('Info', "\nHTTP Status: " + XMLHttpRequest.status + "\n\nText Status: " + TextStatus + "\n\nXMLHttpRequest: " + XMLHttpRequest.responseText + "\n\nException If Thrown: " + Message);
   }});
});

