function toCode62(n){
  var code62Map = ['0','1','2','3','4','5','6','7','8','9',
                   'A','B','C','D','E','F','G','H','I','J','K','L','M',
                   'N','O','P','Q','R','S','T','U','V','W','X','Y','Z',
                   'a','b','c','d','e','f','g','h','i','j','k','l','m',
                   'n','o','p','q','r','s','t','u','v','w','x','y','z'];
  return code62Map[n];
}

function fromCode62(code){
  if(code == '-'){
    return -1;
  }

  var n = code.charCodeAt(0);

  if(n >= 48 && n <= 57){       // 0-9
    n -= 48;
  }
  else if(n >= 65 && n <= 90){  // A-Z
    n -= 55;
  }
  else if(n >= 97 && n <= 122){ // a-z
    n -= 61;
  }
  else{
    n = -1;   // exception
  }

  return n;
}

function generateCkGamerAdString(ck, cookiePos, adIndex){
  var CK_GAMER_AD_LENGTH = 16;

  var ckStr = ck, i;
  if(ck == ''){
    for(i = 0;i < CK_GAMER_AD_LENGTH;i++){
      ckStr += '-';
    }
  }

  ckStr = ckStr.substring(0, cookiePos) + toCode62(adIndex) + ckStr.substring(cookiePos + 1);

  return escape(ckStr);
}

// cookiePos: zero based
function getAdIndex(cookiePos, adCount){
  if(adCount < 1 || cookiePos < 0 || cookiePos > 64){
    return 0;
  }

  var ckGamerAd = $.cookie.get('ckBahaAd');
  var adIndex = 0;
  if(ckGamerAd == ''){
    adIndex = Math.round(Math.random() * (adCount - 1));
  }
  else{
    adIndex = fromCode62(ckGamerAd.charAt(cookiePos));
    if(adIndex < 0){
      adIndex = Math.round(Math.random() * (adCount - 1));
    }
    else{
      adIndex = ++adIndex % adCount;
    }
  }

  document.cookie = 'ckBahaAd=' + generateCkGamerAdString(ckGamerAd, cookiePos, adIndex) + 
                    ';expires=' + new Date().toDateString() + ' 23:59:59 UTC+0800;domain=.gamer.com.tw';

  return adIndex;
}
