/* NOTE: this module requires the presence of the following scripts */
document.writeln('<SCRIPT LANGUAGE="JavaScript" type="text/Javascript" src="cookie.js"></script>');
document.writeln('<SCRIPT LANGUAGE="JavaScript" type="text/Javascript" src="util.js"></script>');

var COURSES_TITLE       = 0;
var COURSES_ID          = 1;
var COURSES_DESC_LINK   = 2;
var COURSES_LOCATION    = 3;
var COURSES_DATE        = 4;
var COURSES_HIDDEN_DATE = 5;
var COURSES_PDU         = 6;
var COURSES_PRICE       = 7;

/* number of months to subtract from current month to decide how to sort */
/* course dates */
var courses_MONTH_OFFSET = 2;

/* the following serves as an example:
var COURSES_list =
[

  [
    "Microsoft Office Project 2003 Fundamentals",
    "Fundamentals Webinar",
    "fundamentals.htm",
    "Toronto",
    "Nov. 28-29",
    "",
    "14",
    "CAN$1095"
  ],

  [
    "Dynamic Scheduling with Microsoft Office Project 2003",
    "Dynamic Scheduling Webinar",
    "Dynamic Scheduling with Microsoft Office Project 2003",
    "Ottawa",
    "Dec. 7 - Dec. 8",
    "",
    "14",
    "CAN$1395"
  ],


  [
    "End of list",
    "",
    "",
    "",
    "",
    ""
  ]

];
*/

/* used to convert a month string to a month index */
var courses_month2index = new Array();
courses_month2index["Jan"] = 0;
courses_month2index["Feb"] = 1;
courses_month2index["Mar"] = 2;
courses_month2index["Apr"] = 3;
courses_month2index["May"] = 4;
courses_month2index["Jun"] = 5;
courses_month2index["Jul"] = 6;
courses_month2index["Aug"] = 7;
courses_month2index["Sep"] = 8;
courses_month2index["Oct"] = 9;
courses_month2index["Nov"] = 10;
courses_month2index["Dec"] = 11;

/* this is a list of months, taking into account that the current month */
/* needs to play a factor in which month is considered first when sorting */
/* the dates. For example, if this is October, then is August considered more */
/*  or less recent than October? When referring to August, do we mean  */
/*  last August or next August? */
var courses_relativeMonthList = new Array(12);

/* name of the cookie to be used for storing the last "sort by" value */
var courses_cookieName;

/* indicates if we are sorting in a positive or negative direction */
var courses_sortDir = null;

var courses_lastSortType = "";

/* used to dynamically insert an image into the table header */
var courses_arrowHtml = new Array();
courses_arrowHtml["title"]    = "";
courses_arrowHtml["location"] = "";
courses_arrowHtml["date"]     = "";
courses_arrowHtml["pdu"]      = "";
courses_arrowHtml["price"]    = "";

var courses_table;

// setup sort methods
HtmlTable.Parsers.courseDate = {
  match : /.*/, // no idea why this doesn't work, so perform matching in the filter in convert

  convert : function() {
    // get the text from the hidden date portion of the date text
    var text = this.get('text').match(/~[^~]*~/);
    text = text[0].replace(/~/g,""); // remove the "~" characters

    // if there is no date, set the value to 0 for sorting
    if (text == "") {
      return 0;
    } /* endif */

    /* break the date into separate pieces */
    /* A date is in one of the following formats: */
    /* (NOTE: the "." after the month is completely optional) */
    /*  Jan. 18 2010  */
    /*  Jan 18 2010  */
    /*  Nov. 30 2010 */
    var dateA = text.split(" ");

    /* get just the start month (1st 3 chars) */
    var monthA = courses_month2index[dateA[0].substr(0,3)];

    var dayA = parseInt(dateA[1]);  /* get the day */
    var yearA = parseInt(dateA[2]); /* get the year */
    var fullDateA = new Date(yearA,monthA,dayA);
    var millisecondsA = fullDateA.getTime();
    return millisecondsA;
  },
  number : true
};

HtmlTable.Parsers.price = {
  match : /.*/, // no idea why this doesn't work, so perform matching in the filter in convert
  convert : function() {
    /* price looks like this: CAN$745 approx USD$738 */
    var price = this.get("text").match(/\d+\.?\d*/);

    // if there is no price, (it's a link instead, make it sort as the lowest value)
    if (!price) {
      return -1;
    } else {
      return price[0].toFloat();
    } // endif
  },
  number : true
};

/* === stores the name of the cookie where the last "sort by" method is to be stored */
/* === initializes the variables needed to perform a sort by date function           */
function COURSES_init(cookieName) {

  /* store the name of the cookie we are to use */
  courses_cookieName = cookieName;
}  /* end of COURSE_init */

function courses_mailto(listing,index) {
  var mailtoTxt = "mailto:" + "sales" +"@" +"ProjectProCorp" +".com?subject=" +
       listing[index][COURSES_TITLE] + ", " +
       listing[index][COURSES_LOCATION] + ", " +
       listing[index][COURSES_DATE];

  location.href = mailtoTxt.replace(/<br>/gi," ");

}  /* end of courses_mailTo */

/* === This Displays the table of courses */
function COURSES_show(divName,courseList,shoppingCartPage,courseRegistrationPage,exchangeRate)
{
  var i;      /* loop counter */
  var target; /* indicates where the target of a link should be displayed */

  /* get a pointer to the "<DIV>" tag that we will need to modify */
  var courseDisplay = $(divName);
  var newHtml="";

  var itemId;
  var options;
  var desc;
  var price;
  var priceString;

  var courses_table = new HtmlTable("courseTable",{
    properties : {
      width : "100%",
      border : 1,
      "class" : "courseTable"
    },
    sortable : true,
    parsers : ["string","string","courseDate","float","price"],
    headers : [
      '<button type="button" class="courseTitleButton">Course Title <span class="arrow">&nbsp;&nbsp;</span></button>',
      '<button type="button" class="courseTitleButton">City or Online<sup>1</sup> <span class="arrow">&nbsp;&nbsp;</span></button>',
      '<button type="button" class="courseTitleButton">Date <span class="arrow">&nbsp;&nbsp;</span></button>',
      '<button type="button" class="courseTitleButton">PDU\'s<sup>2</sup> <span class="arrow">&nbsp;&nbsp;</span></button>',
      '<button type="button" class="courseTitleButton">Price <span class="arrow">&nbsp;&nbsp;</span></button>',
      {
        content : '&nbsp;',
        properties : {
          "class" : "table-th-nosort"
        }
      }
    ]
  });

  for (i=0; i < courseList.length; i++ ) {
    if (courseList[i][COURSES_TITLE] != "End of list") {
      /* if this is an external link */
      if (courseList[i][COURSES_DESC_LINK].search(/^http/i) == 0) {
        target = "_blank";

      /* this is not an external link */
      } else {
        target = "_self";
      } /* endif */

      priceString = courseList[i][COURSES_PRICE];

      // if the price, is a price, not a link
      if (priceString.indexOf("<a href=") == -1) {
        itemId  = courseList[i][COURSES_ID];
        info    = courseList[i][COURSES_TITLE];
        price = priceString;
        priceString = "CAD$" + courseList[i][COURSES_PRICE] + ",<br>approx.<br>USD$" + (courseList[i][COURSES_PRICE] * exchangeRate).round(0)

        // price is not 0 so allow this to be added to the shopping cart
        if (parseInt(price) != 0) {
          link     = '<form name="gtEcartAddForm" method="POST" action="'+shoppingCartPage+'" class="gtEcartForm" >';
          link    += '  <input type="hidden" id="gtEcartId-' + itemId + '"          name="gtEcartId"            value="' + itemId + '" >';
          link    += '  <input type="hidden" id="gtEcartOptions-' + itemId + '"     name="gtEcartOptions"       value="">';
          link    += '  <input type="hidden" id="gtEcartDesc-' + itemId + '"        name="gtEcartDesc"          value="' + info + '<br>' + courseList[i][COURSES_DATE] + '" >';
          link    += '  <input type="hidden" id="gtEcartPrice-' + itemId + '"       name="gtEcartPrice"         value="' + price + '" >';
          link    += '  <input type="hidden" id="gtEcartItemsPerPkg-' + itemId + '" name="gtEcartItemsPerPkg"   value="1" >';
          link    += '  <input type="hidden" id="gtEcartNumPkgs-' + itemId + '"   name="gtEcartNumPkgs" value="1" >';
          link    += '  <input type="hidden" id="gtEcartContinueShopping"   name="gtEcartContinueShopping" value="courseDates.php" >';
          link    += '  <input type="submit" class="gtEcartButton" id="gtEcartAdd-' + itemId + '" name="gtEcartAdd"    value="Add to Cart" >';
          link    += '</form>';

        // price is 0 so need to send an email for registration
        } else {
          link     = '<form name="gtEcartAddForm" method="POST" action="'+courseRegistrationPage+'" class="gtEcartForm" >';
          link    += '  <input type="hidden" id="gtEcartId-' + itemId + '"          name="gtEcartId"            value="' + itemId + '" >';
          link    += '  <input type="hidden" id="gtEcartOptions-' + itemId + '"     name="gtEcartOptions"       value="">';
          link    += '  <input type="hidden" id="gtEcartDesc-' + itemId + '"        name="gtEcartDesc"          value="' + info + '<br>' + courseList[i][COURSES_DATE] + '" >';
          link    += '  <input type="hidden" id="gtEcartPrice-' + itemId + '"       name="gtEcartPrice"         value="' + price + '" >';
          link    += '  <input type="hidden" id="gtEcartItemsPerPkg-' + itemId + '" name="gtEcartItemsPerPkg"   value="1" >';
          link    += '  <input type="hidden" id="gtEcartNumPkgs-' + itemId + '"   name="gtEcartNumPkgs" value="1" >';
          link    += '  <input type="hidden" id="gtEcartContinueShopping"   name="gtEcartContinueShopping" value="courseDates.php" >';
                                                                                                                                        // force this to match width of
                                                                                                                                        // add to cart button
          link    += '  <input type="submit" class="gtEcartButton" id="gtEcartAdd-' + itemId + '" name="freeWebinarReg"    value="Register" style="width:94px;">';
          link    += '</form>';
        } // endif

      } else {
        link = '&nbsp;';
      } // endif

      // build a table row
      courses_table.push([
        {
          properties : { // link
            "class" : "courseTableCell"
          },
          content : '<a href="'+ courseList[i][COURSES_DESC_LINK] + '" target="' + target + '">' + courseList[i][COURSES_TITLE] + '</a>'
        },
        {
          properties : { // location
            "class" : "courseTableCell"
          },
          content : courseList[i][COURSES_LOCATION]
        },
        {
          properties : { // date
            "class" : "courseTableCell"
          },
          // note a hidden date in inserted here for use with sorting
          content : "<span style='display:none'>~"+ courseList[i][COURSES_HIDDEN_DATE] + "~</span>" + courseList[i][COURSES_DATE]
        },
        {
          properties : { // pdu
            "class" : "courseTableCell",
            "width" : 78
          },
          content : courseList[i][COURSES_PDU]
        },
        {
          properties : { // price
            "class" : "courseTableCell"
          },
          content : priceString
        },
        {
          properties : { // register
            "class" : "registerCell"
          },
          content : link
        }
      ]);
    } /* endif */
  } /* end for */

  /* make the change to the inner html of the "<DIV>" tag */
  $(courseDisplay).empty();
  courses_table.inject($(courseDisplay));

} /* end of COURSES_show */

