/* for re-use: 

ul.promo-articles is the list of articles
ul.pagination is the list of links to control the display of articles
.active is the class that makes a control highlighted

*/

var promos = function() {
  var controls = $(".pagination").children("li");
  var current = $(".pagination").children("li.active")[0];
  var link = makeHref(current);
  //make an object with all the values needed
  var details = {
    controls : controls,
    arrows : [controls[0],controls[controls.length-1]],
    ends : [controls[1],controls[controls.length-2]],
    // add a method that works out the position of the passed element in the controls array
    currentPos : function(present) {
                    for(i=0;i<this.controls.length;i++) {
                      if(this.controls[i] == present) {
                        var presentPos = i;
                      }
                    }
                    return presentPos;
                 }
  }
  
  //start by displaying the default article
  display(link);
  
  //clicking on a control element finds the new 'current' one and makes it active
  $(".pagination").children("li").click(function() {
    current = getCurrent(this, details, current);  
    link = makeHref(current);
    display(link);
    makeActive(current); 
    return false;
  });
  
}

//moves the active class to the correct element
var makeActive = function(current) {
  var shown = $(".pagination").children("li.active")[0];
  $(shown).removeClass("active");
  $(current).addClass("active");
}

//makes an id string from the control's href (which is linked to the relevant article
var makeHref = function(current) {
  var link = $(current).children("a").attr("href");
  link = link.substring(1,link.length);
   return link;
}   

//displays the promo passed in
var display = function(elem){
  $("ul.promo-articles").children("li").css({ "display":"none" });
  $("ul.promo-articles").children("li[id='"+elem+"']").css({ "display":"block" });
}

//find the current promo (the one actually selected by the controls' input
var getCurrent = function(obj, data, present) {
  //if the control clicked is a left arrow
  
  if(obj == data.arrows[0]) {
    //if the active control's not at the start of the list of numbers move it left by 1, otherwise nothing happens
    if(present != data.ends[0]) {
      present = data.controls[data.currentPos(present)-1];
    }
  }

  //if the control clicked is a right arrow
  else if(obj == data.arrows[1]) {
    //if the active control's not at the end of the list of numbers move it right by 1, otherwise nothing happens
    if(present != data.ends[1]) {
      present = data.controls[data.currentPos(present)+1];
    }
  }
  
  //otherwise
  else {
    present = obj;
  }
  return present;
}

