﻿// when the DOM is ready
function loadChart(holder,imageSrc,altText) {
  var img = new Image();
  var reW = new RegExp("&width=[0-9]*","gi");
  var reH = new RegExp("&height=[0-9]*","gi");
  
  var w = $(window).width() - 300;
  var h = $(window).height() - 300;
  var anchorSrc = imageSrc.replace(reW,"&Width=" + w);
  anchorSrc = anchorSrc.replace(reH,"&Height=" + h);
    
  $(holder).children("a").attr('href', anchorSrc).attr('rel',altText);
    
  //$(holder).append(a);
    
  // wrap our new image in jQuery, then:
  $(img)
    // once the image has loaded, execute this code
    .load(function () {
      // set the image hidden by default    
      $(this).hide();
      
      // with the holding div #loader, apply:
      $(holder)
        // remove the loading class (so no background spinner), 
        .removeClass('loading')
        // then insert our image
        .children("a").append(this);
        //.append(this);
    
      // fade our image in to create a nice effect
      $(this).fadeIn();
    })
    
    // if there was an error loading the image, react accordingly
    .error(function () {
      // notify the user that the image could not be loaded
      alert('error loading chart');
    })
    
    // *finally*, set the src attribute of the new image to our image
    .attr('src', imageSrc)
    .attr('class','chartImage');
    //.attr('alt', "Click to enlarge chart");

}

function reloadChart(holder,imageSrc,altText) {
  $(holder).addClass('loading');
  $(holder).children("a").children("img").fadeOut();
  $(holder).children("a").children("img").remove();
  
  if ( altText.length == 0 ) {
    altText = $(holder).children('img').attr('alt');
    if ( altText == undefined ) {
        altText = "";
    }
  }
    
  loadChart(holder,imageSrc,altText);
}

function changeXigniteTimeFrame(url,newTimeFrame) {
  var tfRep = new RegExp("&StartDate=.*&End","gi");
  var newStart = getDateFromTimeFrame(newTimeFrame);
  var newDate = "&StartDate=" + (newStart.getMonth() + 1).toString() + "/" + newStart.getDate().toString() + "/" + newStart.getFullYear().toString() + "&End";
  return url.replace(tfRep,newDate);
}

function getDateFromTimeFrame(tf) {

    var today = new Date();
    var ret = new Date();
    
    switch (tf) {  
        case "wk":
            ret.setDate(parseInt(today.getDate()) - 7);
            break;
        case "mth":
            ret.setMonth(parseInt(today.getMonth()) - 1);
            break;
        case "qtr":
            ret.setDate(parseInt(today.getDate()) - 90);
            break;
        case "1y":
            ret.setFullYear(parseInt(today.getFullYear()) - 1);
            break;
        default:
            return today;
            break;
    }
    return ret;
}