///////////////////////////////////////////////
// Karma Piggy 1.3 by LDM 12-2008
// 
// Causes a Karma Piggy to fly around the screen. If you click 
// on the Karma Piggy and "capture" it, it awards you some free 
// karma points (logged in users only).
///////////////////////////////////////////////


///////////////////////////////////////////////
// CONFIGURATION 

// how often should the Karma Piggy appear?
// Pick a percentage between 1 and 100. A higher number 
// means the Karma Piggy will appear more often. 
// i.e. '100' will appear every time, '1' almost never
// '10' seems right (a 10% chance of appearing)
var frequency = 100;

var rand_chance = Math.random() * 100;
rand_chance = Math.round(rand_chance);
//alert(rand_chance);

//////////////
// Fly the Karma Piggy at a random speed? 
// '1' to use random, '0' to use fixed speed (below)
var use_random_speed = 1;

// if using a random speed, set the min & max speeds here
var minTargetSpeed = 5;  // slowest Karma Piggy speed
var maxTargetSpeed = 7; // fastest Karma Piggy speed 

// if using a fixed speed, how fast? (Test this to make sure it's not too fast!)
// for most images, a value of 5 or 6 is fine. 
var fixed_speed = 5;
//////////////


//////////////
// display the Karma Piggy on screen for a fixed or random time? 
// '1' for fixed time, '0' for random time (below)
displayTimeType = 0;

// if using a fixed display time, set it here 
// set time in seconds before Karma Piggy disappears, use 0 for never 
var stopDelayTime = 10;

// if using a random display time, set the min & max times here
// times are in seconds 
minDisplayTime = 10;
maxDisplayTime = 20;

// give how much Karma? Set min & max here
minKamaGiven = 1;
maxKamaGiven = 9;
//////////////


/////////////
// Image paths 
// relative path to the right-facing Karma Piggy image, "pig_r.gif"
var piggyRight = 'pig_r.gif';

// relative path to the left-facing Karma Piggy image, "pig_l.gif"
var piggyLeft = 'pig_l.gif';


/////////////
// file paths 
// relative path to the "karmapiggy.php" file
var actionFile = "karmapiggy.php";

// reference for the sound object ('oink-oink' sound)
var sndObj = '<OBJECT classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" WIDTH="5" HEIGHT="5" id="oink" ALIGN=""><PARAM NAME=movie VALUE="oink.swf"> <PARAM NAME=quality VALUE=high> <EMBED src="oink.swf" quality=high WIDTH="5" HEIGHT="5" NAME="Yourfilename" ALIGN="" TYPE="application/x-shockwave-flash" PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED> </OBJECT>';

// HTML/message to display if they wait too long to catch the Karma Piggy
var waitMsg = '<table class="bkbox" width="400" bgcolor="#ffffaa"><tr><td class="mtext" align="center">Oh no, you waited too long and the Karma Piggy escaped!<p>To try again, click the button below.<br><form name="kp" style="display:inline;"><input type="button" class="btext" value="more karma please" onclick="location.href=\'http://www.karmapiggy.com\';"></form>';


///////////////////////////////////////////////

var randomHideTime = randomnumber(2, 5) * 1000;
//alert('RandomHideTime: ' + randomHideTime);

// run the Karma Piggy?
//if( rand_chance <= frequency){ 

if( rand_chance <= frequency){ 

	// randomly select up/down, left/right so Karma Piggy 
	// appears mysteriously and unpredictably :)
	var updown = randomnumber(1, 10);
	if(updown >= 5){var initY = 'up';}else{var initY = 'down';}

	var leftright = randomnumber(1, 10);
	if(leftright >= 5){var initX = 'left';}else{var initX = 'right';}


	// hide the Karma Piggy for the random time (randomHideTime), then display it... 
	setTimeout('document.getElementById("karmaTarget").style.display="block"; xDir=initX; yDir=initY; startSound()',randomHideTime);

	if(use_random_speed == '1'){
		// pick a random speed for the Karma Piggy 
		var randomSpeed = randomnumber(minTargetSpeed, maxTargetSpeed);
		var TargetSpeed = randomSpeed;
	}else{
		// use a fixed speed
		var TargetSpeed = fixed_speed;
	}


	// Configure the Karma Piggy size - used for bounce control
	var targetWidth = 68;
	var targetHeight = 72;

	if(displayTimeType == '0'){
		// pick a random display time for the Karma Piggy 
		var randomDisplayTime = randomnumber(minDisplayTime, maxDisplayTime);
		var stopafter = randomDisplayTime + (parseInt(randomHideTime) / 1000);
	}else{
		// used a fixed time
		var stopafter = stopDelayTime + (parseInt(randomHideTime) / 1000);  
	}

	//alert('Target Speed: ' + TargetSpeed +', DisplayTime: ' + stopafter);

	var hideTime = 3000; // how long to show the Karma Piggy after 'catching' it?

	// set karma min & max values
	var bonusKarma = randomnumber(minKamaGiven, maxKamaGiven);
	if(bonusKarma < parseInt(1)){bonusKarma = parseInt(1);}
	bonusKarma = Math.round(parseInt(bonusKarma));

	var maxTargetSpeed = 50;
	var xMax;
	var yMax;
	var xPos = 0;
	var yPos = 0;
	var xDir = 'right';
	var yDir = 'down';
	var karmaTargetRunning = true;
	var tempTargetSpeed;
	var newXDir;
	var newYDir;
	already_captured = 0;
	var piggyImg;

}else{

	// don't run or show the karma target
	stopit();

} // end if rand_chance


function stopit(){
	// stop the oink-oink sound
	stopSound();

	clearTimeout(doit);

	// show the fail message if the time ran out and 
	// they didn't capture the Karma Piggy
	if(already_captured != '1'){
		document.getElementById('msg').innerHTML=waitMsg;
		document.getElementById('msg').style.visibility="visible";
	}

	if (document.getElementById)
		document.getElementById("karmaTarget").style.visibility="hidden"
	else if (document.all)
		document.all("karmaTarget").style.visibility = "hidden";
	else
		document.layers["karmaTarget"].visibility = "hide";
}

function initializeTarget() {

	piggyImg = document.getElementById('karmaImage');
	if(initX == 'left'){piggyImg.src=piggyLeft;}

if (document.all) {
	xMax = document.body.clientWidth
	yMax = document.body.clientHeight
	document.all("karmaTarget").style.visibility = "visible";
}
else if (document.layers||document.getElementById) {
	xMax = window.innerWidth-14;
	yMax = window.innerHeight;
if (document.getElementById)
	document.getElementById("karmaTarget").style.visibility="visible"
	else
	document.layers["karmaTarget"].visibility = "show";
}
setTimeout('movePiggy()',400);

if (stopafter>0)
	setTimeout("stopit()",stopafter*1000)
}


function movePiggy() {

	if (karmaTargetRunning == true) {
		calculatePosition();
		if (document.all) {
			document.all("karmaTarget").style.left = xPos + document.body.scrollLeft;
			document.all("karmaTarget").style.top = yPos + document.body.scrollTop;
		}
		else if (document.layers) {
			document.layers["karmaTarget"].left = xPos + pageXOffset;
			document.layers["karmaTarget"].top = yPos + pageYOffset;
		}
		else if (document.getElementById) {
			document.getElementById("karmaTarget").style.left = xPos + pageXOffset + 'px';
			document.getElementById("karmaTarget").style.top = yPos + pageYOffset + 'px';
		}
		doit=setTimeout('movePiggy()',30);
	}

}





function calculatePosition() {



var makechange = randomnumber(1, 100);

/*
if(makechange > 50 && makechange < 60){

	var changeXdir = randomnumber(1, 100);

	if(changeXdir > 50 && changeXdir < 70){

		if(xDir=='left'){
			xDir='right';
			piggyImg = document.getElementById('karmaImage');
			piggyImg.src=piggyRight;
			xDir = "right";
		}else{
			xDir=='left';
			piggyImg = document.getElementById('karmaImage');
			piggyImg.src=piggyLeft;
			xDir = "left";
		}
		changeXdir=0;
	}

	var changeYdir = randomnumber(1, 100);

	if(changeYdir > 50 && changeYdir < 70){

		if(yDir=='up'){
			yDir='down';
		}else{
			yDir=='up';
		}

		changeYdir=0;
	}

}
*/


if (xDir == "right") {
	
	if (xPos > (xMax - targetWidth - TargetSpeed)) { 
		// flip piggy so he flies face-forward
		piggyImg = document.getElementById('karmaImage');
		piggyImg.src=piggyLeft;
		xDir = "left";
	}

}else if (xDir == "left") {

	if (xPos < (0 + TargetSpeed)) {
		// flip piggy so he flies face-forward
		piggyImg = document.getElementById('karmaImage');
		piggyImg.src=piggyRight;
		xDir = "right";
	}

}


if (yDir == "down") {
	if (yPos > (yMax - targetHeight - TargetSpeed)) {
	yDir = "up";
	}
}
else if (yDir == "up") {
	if (yPos < (0 + TargetSpeed)) {
		yDir = "down";
	
	}
}
if (xDir == "right") {
	xPos = xPos + TargetSpeed;
}
else if (xDir == "left") {
	xPos = xPos - TargetSpeed;
}
else {
	xPos = xPos;
}
if (yDir == "down") {
	yPos = yPos + TargetSpeed;
}
else if (yDir == "up") {
	yPos = yPos - TargetSpeed;
}
else {
	yPos = yPos;
}
}

if (document.all||document.layers||document.getElementById){
	window.onload = initializeTarget;
	window.onresize = new Function("window.location.reload()");
}


function startSound(){
	// start the oink-oink sound
	document.getElementById('snd').innerHTML=sndObj;
}

function stopSound(){
	// stop the oink-oink sound
	document.getElementById('snd').innerHTML='';
}

///////////////////////////////////////////////
function captured(){
	if(already_captured != '1'){

		// stop the oink-oink sound
		stopSound();

		// set the 'captured' flag to foil click-happy cheaters :)
		already_captured = 1;

		// apply the karma!
		//xmlhttpPost(actionFile);

		// for testing only
		//document.getElementById('karmaTarget').style.backgroundColor='#ffff22';

		// freeze the Karma Piggy on the screen 
		TargetSpeed=0;

		// if you want, use this to swap the graphic once the image is clicked
		//document.getElementById('karmaTarget').innerHTML="<img src='/pig_r.gif'>";

		// display text when target is captured/clicked  
		alert('Hooray, you caught the Karma Piggy! \n\nThe Karma Piggy awards you ' + bonusKarma + ' karma points.');

		// hide the image after the time specified in 'hideTime' 
		setTimeout("document.getElementById('karmaTarget').style.display='none'",hideTime);
	}
}
///////////////////////////////////////////////


///////////////////////////////////////////////
//function to get random number betweeen two values 
function randomnumber(minVal,maxVal,floatVal){
  var randVal = minVal+(Math.random()*(maxVal-minVal));
  return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}
///////////////////////////////////////////////

///////////////////////////////////////////////
// AJAX functions
function xmlhttpPost(strURL) {
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            updatepage(self.xmlHttpReq.responseText);
        }
    }
    self.xmlHttpReq.send(getquerystring());
}

function getquerystring() {
    var word = 'add';
    qstr = 'w=' + escape(word) + '&pts=' + escape(bonusKarma) + '&uid=' + escape(uid);  // NOTE: no '?' before querystring
    return qstr;
}

function updatepage(str){
	// uncomment for diagnostic purposes only 
    //document.getElementById("karmaTarget").innerHTML = str;
}
///////////////////////////////////////////////

