// the functions contained in this file depend upon the jQuery library
if(!Karmaloop)
  var Karmaloop = {
    clickThroughPath: '/clickthrough/',
    csvToObject:  function(csvData) {
                    // list of objects returned from this function
                    var objects = [];
                    // the data rows in the csv file
                    var rows    = csvData.split(/[\r\n]+/);
                    // the field names of the objects to be returned
                    var fields  = rows.shift().split(',');
                    // for each row of data, create an object and add it to the list
                    $.each(rows,function(index,row){
                          // skip any blank rows
                          if(!row || !row.length)
                            return;
                          // the individual values of the csv row
                          var datums = row.split(',');
                          // the object that will be added to the list
                          var obj = {};
                          $.each(datums, function(index2, data){
                              obj[fields[index2]] = data;
                            });
                          objects.push(obj);
                        });
                    return objects;
                  },
    impressionPath: '/impressions/',
    log:  function(msg){
            // ensure no exceptions are thrown from this function
            try {
              // test if the firebug console exists
              if(window.console && window.console.log) { 
                window.console.log(msg); return true; 
              }
              // if firebug does not exist, log the error in a hidden
              // container at the end of the page
            }
            catch(e) { /* nothing */ }
            // return failure
            return false;
          },
    rotator:  function(containerID, dataFile, rotationTime) {
                // grab the container and test if it exists
                var $container = $('#' + containerID);
                if(!$container.length) {
                  Karmaloop.log('Rotator container with id "' + containerID + '" was not found.' );
                  return false;
                }
                // parse the rotator data from the datafile
                $.ajax({
                      dataType: 'text',
                      error:    function(xhr, txtStatus, err){
                        /* do nothing, the image rotator is not built */
                        Karmaloop.log('Error while fetching the image rotator file: ' + err);
                      },
                      success:  function(data, txtStatus) {
                        // get the objects in this rotator
                        var rotatorIndex  = -1;
                        var rotatorDatums = Karmaloop.csvToObject(data);
                        // don't do anything if there is no rotation data
                        if(!rotatorDatums.length)
                          return;
                        // the <a> and <img> tags in the rotator
                        var $link = null;
                        var $img  = null;
                        // the function that will be called to rotate the images.
                        var rotateImages =  function() {
                            // go to the next image in the rotation
                            rotatorIndex++;
                            if(rotatorIndex>=rotatorDatums.length)
                              rotatorIndex = 0;
                            var rotationData = rotatorDatums[rotatorIndex];
                            // create the elements of the rotator if they 
                            // don't already exist
                            if(!$link)
                              $link = $('<a/>').append($img = $('<img border="0"/>'));
                            // set the values for this rotation
                            $img.attr('src',rotationData.img);
                            $img.attr('alt',rotationData.alt);
                            $link.attr('href',rotationData.url);
                            // if this image has tracking data, track this object
                            if(rotationData.trackName && rotationData.trackName.length) {
                              $link.unbind('click');
                              $link.click(function(){
                                  Karmaloop.track(Karmaloop.clickThroughPath + rotationData.trackName);
                                });
                              // track an impression if one hasn't already been tracked
                              if(!$container.data(rotationData.trackName)) {
                                Karmaloop.track(Karmaloop.impressionPath + rotationData.trackName);
                                $container.data(rotationData.trackName,true);
                              }
                            }// end if has tracking data
                            // add the link and image elements if they don't already exist
                            if(!$container.children().length)
                              $container.append($link);
                        };// end imageRotator function
                        // rotate on the first image, then set up the standard rotation
                        rotateImages();
                        setInterval(rotateImages,rotationTime);
                      },
                      url:      dataFile
                    });
              },
    track:  function(path) {
              try {
                if(typeof path !== 'string')
                  return Karmaloop.log('Path is not a string.');
                if(!pageTracker)
                  return Karmaloop.log('Page tracker does not exist.');
                if(typeof pageTracker._trackPageview !== 'function')
                  return Karmaloop.log('_trackPageview is not a function');
                pageTracker._trackPageview(path);
                Karmaloop.log('Path tracked: ' + path);
              }
              catch(e) {
                Karmaloop.log('Error while tracking: ' + e);
              }
            }
  };
