﻿
jQuery(document).ready(function(){
	startphoenixhunt();
});
/*  start of top-scoring code */

/*
 *
 * jquery.sound.js
 * (c) Vipin Kumar Rajput
 *
 */
(function($) {
    //
    // plugin definition
    //

	sound_enabled = true;

    $.fn.soundPlay = function(options) {
        
		if(!sound_enabled) return;

        // build main options before element iteration
        var opts = $.extend({}, $.fn.soundPlay.defaults, options);
        // iterate and reformat each matched element
        if(opts.command == "play") {
            $.fn.soundPlay.play(opts);
        } else if(opts.command == "stop") {
            $.fn.soundPlay.stop(opts);
        } else {
            
        }
    };

    function debug($obj) {
        if (window.console && window.console.log)
            window.console.log('soundPlay: ' + $obj.size());
    };
	
	$.fn.soundPlay.enable = function(){
		sound_enabled = true;
	}
	
	$.fn.soundPlay.disable = function(){
		sound_enabled = false;
	}
	
    $.fn.soundPlay.play = function(opts) {
        url = opts.url;
        id = opts.playerId;
        $("body").append('<embed id="' + id + '" src="'+url+'" autostart="true" hidden="true"></embed>');
        return false;
    };
    $.fn.soundPlay.stop = function(opts) {
        $('#'+opts.playerId).remove();
        return false;
    };
    //
    // plugin defaults
    //
    $.fn.soundPlay.defaults = {
        url: '',
        playerId: 'player',
        command: 'play'
    };

})(jQuery);

function endphoenixhunt(){
	_gaq.push(['_trackEvent', 'Phoenix Hunt', 'End']);
	flyaway();
	endgame();
	jQuery('#indicator').hide();
	jQuery('#indication').hide();
	jQuery('#scoreboard').hide();
	jQuery('#score').hide();
	jQuery('#score-screen').hide();
	jQuery('#bullets').hide();
	
	jQuery("#endgame_button").hide();
	jQuery("#startgame_button").show();
	jQuery("#bgone").hide();
	jQuery("#bgtwo").hide();
	
}

function startphoenixhunt(){
	_gaq.push(['_trackEvent', 'Phoenix Hunt', 'Start']);
	jQuery("#bgone").show();
	jQuery("#bgtwo").show();
	jQuery.fn.soundPlay({url: '/sounds/game/shot-hit.mp3'});
	jQuery.fn.soundPlay({url: '/phoenixhunt/shot.mp3'});
	jQuery.fn.soundPlay({url: '/sounds/game/chuckle2.mp3'});
	//jQuery("/sounds/game/shot-hit.mp3").play();
	//Sound.play("/phoenixhunt/shot.mp3");
	//Sound.play("/sounds/game/chuckle2.mp3");
	jQuery("#startgame_button").show();
	jQuery("#endgame_button").show();
	jQuery('#indicator').show();
	jQuery('#indication').show();
	jQuery('#scoreboard').show();
	jQuery('#score').show();
	jQuery('#score-screen').show();
	jQuery('#bullets').show();

	setTimeout(scrollTo, 0, 0, 1);startup();
}

var SCORE_SCRIPT = '/phoenixhunt/top_scores.php';

/*var ENTER_NAME_SCREEN = Object.extend(new Screen('congrats'), {
    show : function () {
        Screen.prototype.show.call(this);
        jQuery('player_name').focus();
    }
});
 */


function get_scores() {
    /*new Ajax.Request(SCORE_SCRIPT, {
        method: 'get',
        onComplete: show_scores,
        onFailure: show_error
    });*/
	jQuery.get(SCORE_SCRIPT, function(data) {
	 show_scores();
	}).error(function() { show_error });
}

var posted_scores     = false;
function post_score() {
    if (posted_scores) return; // prevent double post
    /*new Ajax.Request(SCORE_SCRIPT, {
        method: 'post',
        parameters: $H({
                        'name':  $F('player_name'),
						'email':  $F('player_email'),
					    'level': roundnum,
                        'score': totscr
                    }).toQueryString(),
        onComplete: endendgame,
        onFailure: show_error
    });*/
	jQuery.post(SCORE_SCRIPT, { name: jQuery('#player_name').val(), email: jQuery('#player_email').val(), level: roundnum, score: totscr }, function(data) {
	 	endendgame();
	}).error(function() { show_error(); })
    posted_scores = true;
}


var low_high_score = 100;

function show_scores(req) {
    jQuery('#result').val(req.responseText);
    var scores = $A(req.responseXML.getElementsByTagName('score'));
    scores.each(function(node) {
        place = node.getAttribute('place');
        Element.update(jQuery('#high_score_' + place), node.getAttribute('score'));
        Element.update(jQuery('#high_name_' + place), node.getAttribute('name'));
        jQuery('#high_row_' + place).className = node.getAttribute('age'); // 'old' or 'new'
    });
    low_high_score = parseInt(scores[scores.length -1].getAttribute('score'));
}


function show_error(req){
    jQuery('#result').val('error');
}

/*  end of top-scoring code */

function getObj(name){ 
    if (document.getElementById){
        this.obj = document.getElementById(name);
        this.style = document.getElementById(name).style;
        }
    else if (document.all){
        this.obj = document.all[name];
        this.style = document.all[name].style;
        }
    else if (document.layers){
        this.obj = document.layers[name];
        this.style = document.layers[name];
        }
    };

function rand(n){
    return (Math.floor(Math.random()*n+1));
    };


/* configured by thenumber */
var horizontal_step = 5;
var max_right_edge = 920;
var max_left_edge = 5;
var max_top_edge = 20;
var max_bottom_edge = 740;
var fall_speed = 20; //originally 30
var climb_speed = 50; //originally 30
var shot_freeze_time = 500;
var fall_interval = 30; //orig 200
var base_speed = 12; //orig 3
var speed_factor = 17; //orig 17
var speed_increment = 7;
var flyaway_interval = 120;



var flyobj1;
var flyobj2;
var begin;
var dog;
var tid;
var points;
var startscr = "000000";
var scr = 1500;
var totscr = 0;
var swap;
var drop;
var speed = 95;
var endgameTime;
var strMsg;
var strName;
var strPlayerIni;
var strURL;
var climb;
var cnt = 0;
var reset_timer;
var hit_test = false;
var xa = Math.floor(Math.random()*speed_factor)+base_speed;
var ya = -20; 
var count_hit = 0;
var count_shots = 0;
var currentx = rand(max_right_edge-1);
var currenty = max_bottom_edge-1;
var roundnum = 1;
var whichphoenix = 0;
var rndEndTest = new Boolean(false);
var rndTime;
var pics = [];
var load = [];
var disp = [];
var disp2 = [];
for(i = 0; i < 10; i++){
    pics[i]="/phoenixhunt/score-"+i+".gif";
    }              
for(i = 0; i < pics.length; i++){
    load[i] = new Image();
    load[i].src = pics[i];
    }

function startup() {
//	Sound.enable();
    begin = setInterval("start();",3500);
    jQuery('#rounddisp').attr("src",'/phoenixhunt/round-1.gif');
    jQuery('#rounddisplay').show();
    loadscore();
    loadindication();
    }

function loadscore() {
    for(i = 0; i < 6; i++){
        disp[i] = document.createElement("img"); 
        disp[i].setAttribute("src", load[0].src); 
        disp[i].setAttribute("id", "dgts'+i+'");
        disp[i].setAttribute("width", "8"); 
        disp[i].setAttribute("height", "7"); 
        document.getElementById("score").appendChild(disp[i]);
        }
    };
    
function loadindication() {
    for (i = 0; i < 10; i++){
        disp2[i] = document.createElement("img");
        disp2[i].setAttribute("src", '/phoenixhunt/hit-status-0.gif');
        disp2[i].setAttribute("id", "indic'+i+'");
        disp2[i].setAttribute("width", "8");
        disp2[i].setAttribute("height", "7");
        document.getElementById("indication").appendChild(disp2[i]);
        }
    };

function start() {
    clearInterval(begin);
    jQuery('#rounddisplay').hide();
    flyobj1 = jQuery("#phoenix");
    flyobj2 = jQuery("#hotspot");
    dog = jQuery("#dog");
    bullets();
    disp2[whichphoenix].setAttribute("src", '/phoenixhunt/hit-status-1.gif');
    flyobj1.show();
    flyobj2.show();
    jQuery('#game_area').show();
    tid = setInterval("move(xa,ya);",speed);
    points = setInterval("pointCalc();",100);
    };

function pointCalc() {
    cnt ++;
    if (cnt == 100) {
        flyaway();
        }
    scr = scr - 10;
    };
    
function updateRound(){
    _gaq.push(['_trackEvent', 'Phoenix Hunt', 'New Round',roundnum]);
	jQuery('#rounddisp').attr("src","/phoenixhunt/round-"+roundnum+".gif");
    jQuery('#rounddisplay').show();
    };
    
function updateScore() {
	var v1, v2, v3;
	v1 = totscr.toString();
	v2 = v1.split("");
	v3 = 6 - v2.length;
	for(i = 0; i < v2.length; i++){
		disp[i+v3].setAttribute("src", load[v2[i]].src);
		}
	};
    
function shot() {
	jQuery.fn.soundPlay({url: '/sounds/game/shot-hit.mp3'});
 	//Sound.play("/sounds/game/shot-hit.mp3");
  	_gaq.push(['_trackEvent', 'Phoenix Hunt', 'Shot']);
    
    clearInterval(tid);
    clearInterval(points);
    totscr = totscr + scr;
    hit_test = true;
	count_hit ++;
	count_shots ++;
    bullets();
    updateScore();
    disp2[whichphoenix].setAttribute("src", '/phoenixhunt/hit-status-2.gif');
    flyobj2.hide();
    jQuery('#game_area').hide();
    jQuery('#phoeniximg').attr('src', "/phoenixhunt/phoenix-shot.gif");    
    swap = setInterval("fall();",shot_freeze_time);
    };

function miss() {
   //Sound.play("/phoenixhunt/shot.mp3")

	scr = scr - 100;
    count_shots ++;
    bullets();
    };

function fall() {
    clearInterval(swap);
    jQuery('#phoeniximg').attr('src', "/phoenixhunt/phoenix-fall.gif");
    drop = setInterval("falling();",fall_interval);
    };

function move(dx, dy) {
//	console.log(flyobj1.style.top,flyobj1.style.left);
   currentx += dx;
   currenty += dy;
   jQuery('#phoenix').css("top", currenty);
   jQuery('#hotspot').css("top", currenty);
   jQuery('#phoenix').css("left", currentx);
   jQuery('#hotspot').css("left", currentx);   
   if (currentx >= max_right_edge) {
    xa = -xa; 
    jQuery('#phoeniximg').attr('src', "/phoenixhunt/phoenix-fly-left.gif");}
    if (currentx <= max_left_edge) {
    xa = -xa;
    jQuery('#phoeniximg').attr('src', "/phoenixhunt/flying-phoenix.gif");}
    if (currenty >= max_bottom_edge) {
    ya = -ya; }
    if (currenty <= max_top_edge) {
    ya = -ya; }
    };

function falling() {
    if (currenty <=max_bottom_edge){
        jQuery('#phoenix').css('top', currenty + fall_speed);
        jQuery('#hotspot').css('top', currenty + fall_speed);
        currenty = currenty + fall_speed;
        }
    else {
        clearInterval(drop);
        animate_dog();    
        }
    };

function climbing() {
    if (currenty >=-200){
        jQuery('#phoenix').css('top', currenty - climb_speed);
        jQuery('#hotspot').css('top', currenty - climb_speed);
        currenty = currenty - climb_speed;        
        }

    else {
        clearInterval(climb);
        jQuery('#flyingaway').hide();
        disp2[whichphoenix].setAttribute("src", '/phoenixhunt/hit-status-0.gif');        
        jQuery('#doganim').attr('src', "/phoenixhunt/instigatoranim2.gif");
        jQuery('#phoeniximg').attr('src', "/phoenixhunt/flying-phoenix.gif");
		setTimeout("jQuery.fn.soundPlay({url: '/sounds/game/chuckle2.mp3'};", 500);
	     //setTimeout("Sound.play('/sounds/game/chuckle2.mp3');",500);        
	

        reset_timer=setInterval("reset();",3500);        
        }
    };

function animate_dog() {
    jQuery('#doganim').attr('src', "/phoenixhunt/instigatoranim.gif");
    jQuery('#phoeniximg').attr('src', '/phoenixhunt/flying-phoenix.gif');
  reset_timer=setInterval("reset();",3500);
    };

function bullets() {
    if (count_shots == 3){
        if (hit_test == false){
			jQuery('#bulletsimg').attr('src', '/phoenixhunt/bullets-0.gif');
        	flyaway();
			}
		else {
		jQuery('#bulletsimg').attr('src', '/phoenixhunt/bullets-0.gif');
		}
        }
    if (count_shots == 2){
        jQuery('#bulletsimg').attr('src', '/phoenixhunt/bullets-1.gif');
        }
    if (count_shots == 1){
        jQuery('#bulletsimg').attr('src', '/phoenixhunt/bullets-2.gif');
        }
    if (count_shots == 0){
        jQuery('#bulletsimg').attr('src', '/phoenixhunt/bullets-3.gif');
        }
    };

function flyaway() {
    jQuery('#phoeniximg').attr('src', '/phoenixhunt/phoenix-fly-away.gif');
    jQuery('#flyingaway').show();
    clearInterval(tid);
    clearInterval(points);
	flyobj2.hide();
	jQuery('#game_area').hide();
    climb=setInterval("climbing();",flyaway_interval);
    };
    
function reset() {
    clearInterval(reset_timer);
    if (whichphoenix <= 8){
        whichphoenix ++;
        disp2[whichphoenix].setAttribute("src", '/phoenixhunt/hit-status-1.gif');
        rndEndTest = false;
        reset2();
        }
    else {
        if (count_hit >= 6){
            if (count_hit == 10){
                totscr = totscr+5000;
                updateScore();
                }
            whichphoenix = 0;
            roundnum ++;
            if (roundnum == 10){
                gameover.show();
                endgameTime = setInterval("endgame();",3500);
                }
            updateRound();
            for (i = 0; i < 10; i++){
                disp2[i].setAttribute("src", '/phoenixhunt/hit-status-0.gif');
                }
            count_hit = 0;
            disp2[whichphoenix].setAttribute("src", '/phoenixhunt/hit-status-1.gif');
            rndEndTest = true;
            speed = speed - speed_increment;
            rndTime = setInterval("reset2();",3500);
            }
            else {
                jQuery('#gameover').show();    
                endgameTime = setInterval("endgame();",3500);
                }
            }
        };

		function endgame(){
		    clearInterval(endgameTime);
			jQuery('#end_game_screen').show(); 
			jQuery('#player_name').focus(); 
			//	post_score();
		 	    };
  
			function endendgame(){
			   strURL = "/top_scores" ;//+ "?score=" + totscr + '&name=chris&level=2';
			    window.location = strURL;
			    };


function reset2() {
    if (rndEndTest == true){
        clearInterval(rndTime);
        rndEndTest = false;
        jQuery('#rounddisplay').hide();
        }
    flyobj1 = null;
    flyobj2 = null;
    begin = null;
    dog = null;
    tid = null;
    swap = null;
    drop = null;
    reset_timer = null;
    hit_test = false;
    scr = 1500;
    xa = Math.floor(Math.random()*speed_factor)+base_speed;
    ya = -20; 
    cnt = 0;
    count_shots = 0;
    bullets();
	 currentx = rand(max_right_edge-1);
	 currenty = max_bottom_edge-1;
    flyobj1 =  jQuery('#phoenix');
    flyobj2 =  jQuery('#hotspot');
    dog = jQuery("#dog");
    jQuery('#phoenix').show();
  jQuery('#hotspot').show();
    jQuery('#game_area').show();
    tid = setInterval("move(xa,ya);",speed);
    points = setInterval("pointCalc();",100);
    };

