var agaVotingEnabled = true;

// jQuery function for escaping all HTML entities from the input string
function escape_entities(s) {
  var esc = $('<div/>').text(s).html();
  return esc.replace(/'/g, "&#39;").replace(/&/g, "&amp;");
}
// jQuery function for unescaping all HTML entities from the input string (inverse to the above)
function unescape_entities(s) {
  return $('<div>' + s + '</div>').html();
}
// build votes data from cookie
function get_current_votes_data(polls) {
  var data = [];
  var votes;
  var cookieData = $.cookie('aga_votes');
  // check for any existing votes
  if (cookieData) {
    votes = JSON.parse(cookieData);
    // if any votes already casted -- parse API output and save poll data for showing in the module
    if (votes.length) {
      $.each(polls.ballot, function(i, poll) {
        for (var i = 0; i < votes.length; i++) {
          if (votes[i].ballot_idx == poll.index) {
            var game;
            for (var j = 0; j < poll.lineItem.length; j++) {
              if (poll.lineItem[j].id == votes[i].lineItem_id) {
                game = poll.lineItem[j];
                break;
              }
            }
            data.push({poll:poll, game:game, pic_idx:(j+1)});
          }
        }
      });
    }
  }
  return data;
}
function get_votes_from_url(polls) {
  var data = [];
  $.each(polls.ballot, function(i, poll) {
    if (typeof $.url.param('game' + String(poll.index)) != 'undefined') {
      // vote casted for category
      var gameId = $.url.param('game' + poll.index);
      var game;
      for (var j = 0; j < poll.lineItem.length; j++) {
        if (poll.lineItem[j].id == gameId) {
          game = poll.lineItem[j];
          break;
        }
      }
      data.push({poll:poll, game:game, pic_idx:(Number(gameId)+1)});
    }
  });
  return data;
}

function build_voted_for_module(polls) {
  var data = get_current_votes_data(polls);
  $('#mod_voted_for').setTemplateURL('voted_mod_tpl.php');
  $('#mod_voted_for').setParam('escape', escape_entities);    
  $('#mod_voted_for').processTemplate({items:data});
  
  $('#voted_for_action a').jHelperTip({
    trigger: 'click',
    dC: '#gi_voted_for_post_w',
    leftOff: -100,
    topOff: -250
  });
}
function build_embedded_voted_for_module(polls) {
  var data = get_votes_from_url(polls);
  // console.log(data);
  $('#mod_voted_for').setTemplateURL('voted_mod_tpl.php');
  $('#mod_voted_for').setParam('escape', escape_entities);    
  $('#mod_voted_for').processTemplate({items:data, embedded:true});    
}
function voted_for_module_embed_params(polls) {
  var data = get_current_votes_data(polls);
  var out = '';
  $.each(data, function(i, o) {
    out += 'game' + String(o.poll.index) + '=' + String(o.game.id) + '&amp;'
  });
  if (out.length) {
    return out.substring(0, out.length - 5);
  }
  return '';
}
function update_award_categories_voting(polls) {
  var data = [];
  if (agaVotingEnabled) {
    // disable voted for items
    data = get_current_votes_data(polls);
  } else {
    // disable all by default
    $.each(polls.ballot, function(i, poll) {
      data.push({poll:poll});
    });
  }
  $.each(data, function(i, o) {
    // cat. page
    if ($('#poll_' + o.poll.name + ' .vote'))
      $('#poll_' + o.poll.name + ' .vote').addClass('disabled');
    if (o.game && $('#vote_btn_' + o.poll.index + '_' + o.game.id))
      $('#vote_btn_' + o.poll.index + '_' + o.game.id).addClass('selected');
    // game page
    if ($('#game_vote_btn_' + o.poll.index)){
      $('#game_vote_btn_' + o.poll.index).addClass('voted');
    }
  });        
} 

function show_bumper_with_url(url) {
  if( jQuery.browser.msie ) {
  window.location='bumper.php?dest=home.php';
  }
  else{
  window.location='bumper.php?dest='+encodeURIComponent(url);
  }
}

function show_warning_with_url(url) {
  window.location='warning.php?dest='+encodeURIComponent(url);
}
function play_game(ballotNo, lineNo, gameName) {
play_game_winners( ballotNo, lineNo, gameName, 'false' );
}
function play_game_winners(ballotNo, lineNo, gameName, winnerPage) {
  var name = '';
  if (String(unescape_entities(gameName)).length) {
    name = escape(unescape_entities(gameName));
  }
  var gameURL = 'game.php?winner=' + winnerPage +'&poll=' + ballotNo + '&item=' + lineNo + (gameName.length ? '&game=' + name : '');
  window.location = gameURL;
}
function cast_vote(ballotNo, lineNo, gameName, jumpNext) {
  var name = unescape_entities(gameName);
  var voteData = {ballot_idx:ballotNo, lineItem_id:lineNo, lineItem_name:name};
  var cookieData = $.cookie('aga_votes');
  var votes = [];
  var playNext = jumpNext || false;
  if (cookieData) {
    // load any previous votes
    votes = JSON.parse(cookieData);
  }
  // check if didn't already vote for current poll
  var votedAlready = false;
  for (var i = 0; i < votes.length; i++) {
    if (votes[i].ballot_idx == ballotNo) {
      votedAlready = true;
      break;
    }
  }
  // if not already voted for save vote in cookie
  if (agaVotingEnabled && !votedAlready) {
    votes.push(voteData);
    var date = new Date();
    date.setTime(date.getTime() + 3600 * 1000); // 1hr
    $.cookie('aga_votes', JSON.stringify(votes), {expires:date, path:'/'});
    build_voted_for_module(pollsData);
    update_award_categories_voting(pollsData);
    $.get('cast_vote.php', // URL
      {ballot: ballotNo, line: lineNo} // request params
    );
  } else if (playNext) {
    // play_game(ballotNo+1, 0, '');
    var next = ballotNo >= pollsData.ballot.length - 1 ? 0 : ballotNo + 1;
    $.each(pollsData.ballot, function (i, poll) {
      if (poll.index == next) {
        window.location='category.php#poll_' + poll.name;
        return true;
      }
    });
  }
}

function add_category_icons(polls) {
  var iconsPrefix = 'ico057x053cat_';
  $.each(polls.ballot, function (i, poll) {
    switch($.trim(poll.name)) {
      case 'ag1':
        poll.catIcon = iconsPrefix + 'most_ag.gif';
        break;
      case 'ag2':
        poll.catIcon = iconsPrefix + 'best_perf_monkey.gif';
        break;
      case 'ag3':
        poll.catIcon = iconsPrefix + 'best_stick_fig.gif';
        break;
      case 'ag4':
        poll.catIcon = iconsPrefix + 'great_escape.gif';
        break;
      case 'ag5':
        poll.catIcon = iconsPrefix + 'best_from_planet.gif';
        break;
      case 'ag6':
        poll.catIcon = iconsPrefix + 'moms_fav.gif';
        break;
      case 'ag7':
        poll.catIcon = iconsPrefix + 'best_perf_robot.gif';
        break;
      case 'ag8':
        poll.catIcon = iconsPrefix + 'most_adrenaline.gif';
        break;
      case 'ag9':
        poll.catIcon = iconsPrefix + 'pop_cult.gif';
        break;
      case 'ag10':
        poll.catIcon = iconsPrefix + 'most_edumac.gif';
        break;
   }
  });
  return polls;
}

function decorate_games_with_assets(polls, assets) {
  $.each(polls.ballot, function (i, poll) {
    $.each(poll.lineItem, function (j, game) {
      var gassets = {};
      if (game.question.substr(0, game.question.length - 1) == "Let's Get Cookin") {
        polls.ballot[i].lineItem[j].question = "Let's get Cookin'";
      }
      $.each(assets.game, function (k, ga) {
        if (Number(poll.index) == Number(ga["@ballot_index"]) && Number(game.id) == Number(ga["@lineItem_id"])) {
          gassets = { 
            embed_width: ga.object["@width"],
            embed_height: ga.object["@height"],
            embed_type: ga.object["@type"],
            embed_data: ga.object["#cdata"],
            small_image: ga.small_image,
            medium_image: ga.medium_image,
            badge_image: ga.game_badge,
            review_url: ga.review_url,
            game_url: ga.game_url
          };
        }
      });
      polls.ballot[i].lineItem[j].assets = gassets;
    });
  });
  // console.log(polls);
  return polls;
}

// trap ad clicks to show warning
function trap_ad_click(event) {
  show_warning_with_url(event.target.href || event.currentTarget.href);
  return false;
}
$(document).ready(function(){
  $('a.ad_click').click(trap_ad_click);
});
