That's happening because a closure is created that retains the last value of i
from the for loop, you need to change this line:
p.addEventListener("click", function(e){popup(e, i);}, false);
To fix this, first declare a new function:
function createfunc(i) {
return function(e) {popup(e, i); }
}
Then change that line to:
p.addEventListener("click", createfunc(i), false);
Check this question for more information about this technique.