/********************************************************************
  This javascript file requires jQuery to run.
  Written with jquery-1.5.1.min.js
*********************************************************************/

/********************************************************************
  function ad(pub_id, el_id)

  Parameters: pub_id : unique id of the publisher
              el_id  : a class or an id, must begin with a "." or a "#"

  Returns   : nothing

  This function sets up everything in order to create an ad.
  If it succeeds, it calls set(id,msg) to create the ad in the
    given class / id.
  If it fails, it calls that same function, but with a no ad message
    as its parameter

*********************************************************************/
function ad(pub_id,el_id)
{
  $(document).ready(function()
  {
    var content = new Array();                                                      // the keywords, body content, and description

    if(ajaxCheck() == true)                                                               // make sure ajax can be performed
    {
      var keywordArray = getKeywords();                                             // keyword array
      var descriptionArray = getDescription();                                      // description array
      var bodyArray = getBody();                                                    // body array
      
      if(keywordArray != undefined)                                                 // make sure variables are defined
        content = content.concat(keywordArray);
      if(descriptionArray != undefined)
        content = content.concat(descriptionArray);
      if(bodyArray != undefined)
        content = content.concat(bodyArray);
      
      if(content.length != 0)
      {
        content = clean(content);
        if(content != undefined)
          performAjax(el_id,pub_id,content);
        else
          noAd(el_id);
      }
      else
        noAd(el_id);
    }
    else
      noAd(el_id);
  });
}

/********************************************************************
  function performAjax(el_id,pub_id,content)

  Parameters: id          : a class or an id, must begin with a 
                            "." or a "#"
              content     : keywords of the body in array form  

  Returns   : nothing

  This function uses ajax in order to send information to the php
    file, retrieve information back, and call an appropriate
    function to set the given id.

*********************************************************************/
function performAjax(el_id,pub_id,content)
{
  content = "keywords=" + content.join(" ") + "&pid=" + pub_id;
  
  $.ajax(
  {
    type: "POST",                                                                    // type of the reqyest
    url: "https://adcenter.riight.com/pubs/ad.php",
    data: content,                                                                  // the content to send
    dataType: 'JSONP',
    crossDomain: true,
    cache: false,                                                                   // do not want to cache the ads
    success: function(data)                                                         // on success, display the ad
    {
      data.size == 0 ? noAd(el_id) : set(el_id,data); 
    },
    error: function(data)                                                           // on failure, display the given message
    {
      nAd(el_id);
    }
  });
}

/********************************************************************
  function set(el_id,msg)

  Parameters: el_id  : a class or an id, must begin with a "." or a "#"
              msg    : message to set the id to

  Returns   : nothing

  This function sets the given id to the selected message (msg).
  Used for setting the id/class to the html ad.

*********************************************************************/
function set(el_id,msg)
{
  $('#riightads').css("background", "#fff");
  $('#riightads').css("margin-bottom", "10px");
  $('#riightads').css("border-radius", "4px");
  $('#riightads').css("padding-bottom", "5px");
  $('#riightads').css("padding-top", "5px");
  $('#riightads').html('<span style="font-size: 10px; padding-left: 5px; color: #ccc;">sponsor ads</span>');
 
  for(var i=0; i<msg.size; i++)
  {
    $(el_id).html($(el_id).html() + msg['ad'+i].title + msg['ad'+i].line_1 + msg['ad'+i].line_2 + msg['ad'+i].url_disp );
  }

  $('#riightads').append('<span style="font-size: 11px; padding-left: 5px;"><a href="http://adcenter.riight.com" style="color: #0000FF; text-decoration: none;">Place your ad here</a></span>');
  
}
function noAd(el_id)
{

var noad = '<a href="http://adcenter.riight.com" style="text-decoration:none;"><div><div style="font-size: 14px; font-weight: bold; color: #000;">RIIGHTADS</div><div style="color: #666; font-size: 12px;">Advertise on RIIGHT In Just Minutes.</div><div style="color: #666; font-size: 12px">Instant Traffic. Immediate Results.</div><div style="color: #CC0000; font-size: 11px;">www.riight.com/riightads</div></div></a>';     // no ad message, in case something fails
  $(el_id).html(noad);
}

/********************************************************************
  function ajaxCheck()

  Parameters: none

  Returns   : true or false

  This function returns true or false, depending if browser supports
    ajax.

*********************************************************************/
function ajaxCheck()
{
  var check = undefined;
  try 
  {
    check = new XMLHttpRequest();
  } 
  catch(e1) 
  {
    try 
    {
      check = new ActiveXObject("Msxml2.XMLHTTP");
    } 
    catch(e2) 
    {
      try 
      {
        check = new ActiveXObject("Microsoft.XMLHTTP");
      } 
      catch(e3) 
      {
        check = undefined;
      }
    }
  }
  finally
  {
    if(check == undefined)
      return false;
    else
      return true;
  }
}
/********************************************************************
  function getKeywords()

  Parameters: none

  Returns   : a string of keywords from the document's meta tag

  This function returns an array of keywords from the document's
    meta tag.

*********************************************************************/
function getKeywords()
{
  var text = new Array();
  if($("meta[name*=keywords]").length != 0)
  {
    text = text.concat($("meta[name*=keywords]").attr("content").split(" "));       // get the keywords
    return text;
  }
  return undefined;
}

/********************************************************************
  function getDescription()

  Parameters: none

  Returns   : description from the document's meta tag

  This function returns a description from the document's meta tag.

*********************************************************************/
function getDescription()
{
  var text = new Array();
  if($("meta[name*=description]").length != 0)
  {
    text = text.concat($("meta[name*=description]").attr("content").split(" "));    // get the description
    return text;
  }
  return undefined;
}

/********************************************************************
  function getBody()

  Parameters: none

  Returns   : array of words from the document's body tag

  This function returns a string of words from the document's body.

*********************************************************************/
function getBody()
{
  var text = new Array();
  var tagArray = ["h1","h2","h3","b","i","strong","em","a","li","td","p"];          // the tags to get the text of
  for(var i=0; i<tagArray.length; i++)                                              // loop through each tag
  {
    $("body").find(tagArray[i]).each(function()                                     // append text of each tag to text variable
    {
        text = text.concat($(this).text().split(" "));
    });
  }
  if(text.length == 0)                                                              // check to make sure we have some elements...
    return undefined;
  
  return text;
}
/********************************************************************
  function clean(wordArray)

  Parameters: wordArray : an array of strings

  Returns   : a clean array of strings

  This function cleans an array and returns it.
  - It removes words that are shorther than 5 characters.
  - It removes punctuation, specified by isPunc function.
  - It removes words that contain non-roman alphabet characters,
     specified by isLetter function. 
  - It removes any duplicate words found in the string.

*********************************************************************/
function clean(wordArray)
{
  /* clean each word */
  for(var i=0; i<wordArray.length; i++)                                             // loop through each word in the array
  {
    outerLoop:
    if(wordArray[i].length >= 5)                                                    // check if word is of 'proper' length
    {
      wordArray[i] = wordArray[i].toLowerCase();
      for(var j=0; j<wordArray[i].length; j++)                                      // loop through each letter in the word
      { 
        var letterC = wordArray[i].charAt(j);                                       // character letter 
        var letterN = wordArray[i].charCodeAt(j);                                   // integer letter
        if(isPunc(letterC))                                                         // check if letter is punctuation
        {
          if(j+1 == wordArray[i].length || j == 0)                                  // if punctuation mark is the first 
            wordArray[i] = wordArray[i].replace(letterC,"");                        // or last letter in a word, delete it
          else                                                                      // punctuation is in the middle of a word, remove
          {
            wordArray.splice(i,1); i--;
            break outerLoop;
          }
        }
        else if(!isLetter(letterN))                                                 // check ascii value of a letter
        {                                                                           // remove single word at [i]
          wordArray.splice(i,1); i--;                                               // need to check [i] again 
          break outerLoop;                                                          // break from the inner loop
        }
      }
    }
    else                                                                            // word is of improper length
    {
      wordArray.splice(i,1);                                                        // remove single word at [i]
      i--;                                                                          // need to check [i] again...
    }
  }

  /* remove duplicates */
  var newArray = new Array();                                                       // create a new array 
  outerLoop:
  for(var i=0; i<wordArray.length; i++)                                             // for each word in the original array
  {  
    for(var j=0; j<newArray.length; j++)
    {
      if(newArray[j] == wordArray[i])                                               // if a duplicate has been found... 
        continue outerLoop;
    }
    newArray[newArray.length] = wordArray[i];
  }
  
  if(newArray.length == 0)
    return undefined;
    
  return newArray;
}
/********************************************************************
  function isPunc(characterC)

  Parameters: characterC : a single string character

  Returns   : boolean    : true if a given character is punctuation
                           false otherwise

  This function determines if a given character is a punctuation
  mark. Returns either true or false. 

*********************************************************************/
function isPunc(characterC)
{
  var puncArray = [",",".",";",":","'",'"',"[","]","{","}","(",")","?","!"];        // an array of punctuation marks 
  for(var i=0; i<puncArray.length; i++)                                             // looping through the array
  {
    if(puncArray[i] == characterC)                                                  // return true if we find a punctuation match
      return true;
  }
  return false;
}
/********************************************************************
  function isLetter(characterN)

  Parameters: characterN : number representing an ascii character

  Returns   : boolean    : true if a given character is a letter
                             from the latin alphabet.
                           false otherwise

  This function determines if a given character is a letter from
  the roman alphabet (ascii / utf compatible?). 

*********************************************************************/
function isLetter(characterN)
{
  if( (characterN >= 65 && characterN <= 90) ||                                     // check if character is A-Z or a-z
      (characterN >= 97 && characterN <= 122) )
    return true;                                                                    // return true if character is a-z or A-Z
  return false;                                                                     // false otherwise
}

