 isAudioStart=true;
 $(function(){
 if(!detect.isIpad)
 audioPlayerr=new audiofunctinallity('_audio','media/sound/Gobbling_Gobs_1',dataSource,callBackSteps);
 });
 function changeAudio(obj){
 if(isAudioStart){
	obj.src="media/crops_new_UI/audio_off.png";
	isAudioStart=false;
	var oo=document.getElementsByTagName('Audio');
	for(var i=0;i<oo.length;i++){
		if(!oo[i].paused)
			oo[i].pause();
	}
 }
 else{
 obj.src="media/crops_new_UI/audio_on.png";
 isAudioStart=true;
 }
}
function startGame(){
//activeDevelopment();
activeMinified();
switchToGameCanvas();

}	


function checkStoporStart(dom){
if(typeof dom=='undefined')return false;
if(!ig.game.isGameCompleted){
var isGameActive=$(dom).attr('isGameActive');
if(typeof isGameActive!='undefined'){
if(isGameActive=='true'){
InactiveGame();
}
else{
ActiveGame();
}
}
}
}
var playAddress='media/crops_new_UI/play_game.png';
var pauseAddress='media/crops_new_UI/pause_game.png';
function ActiveGame(){
$('#toggleGame')
.attr('src',pauseAddress)
.attr('isGameActive','true');
ig.system.startRunLoop();
}
function InactiveGame(){
$('#toggleGame')
.attr('src',playAddress)
.attr('isGameActive','false');
ig.system.stopRunLoop();
}

var detect = new checkBrowsers();
var currentInstructionStatus=1;
	
	var value_json={
	"ball1_worth":1,
	"ball10_worth":10,
	"ball100_worth":100,
	"initail_Score":0,
	"target_score":22,
	"multiplication_factor":1
	}
	
	var AudioArray=[
	"GobblingGlobs_1",
	"GobblingGlobs_2",
	"GobblingGlobs_3",
	"GobblingGlobs_4",
	"GobblingGlobs_5",
	"GobblingGlobs_6",
	"GobblingGlobs_7",
	"GobblingGlobs_8",
	"GobblingGlobs_9",
	"GobblingGlobs_10",
	"GobblingGlobs_11",
	];
	var aud={};
	var path="media/sound/";
	
	var AudioStartCount=0;
	
	/*Ipad related audio code*/
	
	
var instructionSequence=[
"Tienes el control de esta burbuja. Tu valor es 0.",
"Haz clic en cualquier lugar para mover tu burbuja.",
"Haz clic cerca de tu burbuja para moverla despacio.",
"Haz clic lejos de tu burbuja para moverla rápidamente.",
"Haz clic y mantén presionado el botón para acelerar. ¡Yupi!",
"Haz un clic sobre tu burbuja para detenerla.",
"Los glóbulos amarillos <br>valen 1. Mueve tu burbuja para englutir un 1 y aumentar tu valor. ",
"Ahora tu valor es 1. ",
"Los glóbulos rosados valen 10. Mueve tu burbuja para englutir un 10 y aumentar tu valor.",
"1 + 10 = 11. ¡Ahora tu valor es 11!",
"Englute más glóbulos hasta que tengas el mismo valor que el número seleccionado.",
];  

    function step1(){
      if(isAudioStart)
		audioPlayerr.play('step1');
    }
	function step2(){
     if(isAudioStart)
			audioPlayerr.play('step2');
	
    }function step3(){
         if(isAudioStart)
			audioPlayerr.play('step3');
	
    }function step4(){
     if(isAudioStart)
	audioPlayerr.play('step4');
    }function step5(){
        if(isAudioStart)
	audioPlayerr.play('step5');
    }function step6(){
     if(isAudioStart)
	audioPlayerr.play('step6');
    }function step7(){
       if(isAudioStart)
		audioPlayerr.play('step7');
    }function step8(){
        if(isAudioStart)
		audioPlayerr.play('step8');
    }function step9(){
       if(isAudioStart)
		audioPlayerr.play('step9');
    }function step10(){
   if(isAudioStart)
		audioPlayerr.play('step10');
    }function step11(){
       if(isAudioStart)
		audioPlayerr.play('step11');
	}
   
	/*ipad related audio code ends*/
	
	function stopAllAudio(){
	for(key in aud){
	if(! aud[key].paused)
	aud[key].pause();
	}
	var o=document.getElementsByTagName('audio');
	for(var i=0;i<o.length;i++){
	if(!o[i].paused)
	o[i].pause();
	}
	}
	var AudioCount=0;
	var isInstructionChangeInProgress=false;

/*utility method for checking browser*/

function checkBrowsers(){
var ua = navigator.userAgent.toLowerCase();
this.isIpad = (ua.indexOf('ipad') != -1);
this.isAndroid = ua.indexOf('android') != -1;
this.isIE = ua.indexOf('msie') != -1;
this.isWebkit = ua.indexOf('webkit') != -1;
this.isFirefox = ua.indexOf('firefox') != -1;
this.isSafari=ua.indexOf('safari')!=-1;
}

dataSource={
"step1":"00.00-05.36",
"step2":"06.63-09.59",
"step3":"11.03-14.84",
"step4":"16.25-20.62",
"step5":"21.30-26.79",
"step6":"28.24-31.10",
"step7":"32.76-40.50",
"step8":"41.30-43.94",
"step9":"45.35-52.63",
"step10":"54.92-59.90",
"step11":"60.30-66.35"
};
var audioPlayerr=null;
function callBackSteps(){
$('#preloader_image').hide();
	ActivateGameSequenceWise(currentInstructionStatus);
}
jQuery(function(){    
	/*adding click event to play next*/
	$('#next_step_ok').bind('click touchstart',function(){
	ActivateGameSequenceWise(currentInstructionStatus);
	});
	
	
	$('#startTut').bind('click touchstart',function(){
	if(audioPlayerr==null){
		audioPlayerr=new audiofunctinallity('_audio','media/sound/Gobbling_Gobs_1',dataSource,callBackSteps);
		$('#preloader_image').show();	
	}
	else
	{
	ActivateGameSequenceWise(currentInstructionStatus);
	}
	});
	
	$('#play_next').bind('click touchstart',function(){
 	ActivateGameSequenceWise(currentInstructionStatus);	
	});
	$('.close').bind('click touchstart',function(){
	window.close();
	});
		
	
		//originalPosition
		$("#green_box").draggable({	//drag and drop for desktop.
             revert : "false",
             containment : "canvas_drop",
             start : function(event, ui) {
               
             },drag:function(event,ui){
        
             },
             stop:function(event, ui){
             if(ui.offset.left+24<0 ||ui.offset.left>ig.system.width-$(event.target).width()+20||ui.offset.top>ig.system.height-$(event.target).height						()+21 ||ui.offset.top+21<0)   {
             $(event.target).css({'left':ui.originalPosition.left,'top':ui.originalPosition.top}); 
            }
           }
         });
	if(detect.isIpad || detect.isAndroid)
		{
		document.addEventListener("touchstart",function(e){e.preventDefault();},false);
		init();
		}
    startGame();	
});

function touchHandler(event)
{
    var touches =event.changedTouches;
    var first=touches[0];
    var type = "";
         switch(event.type)
{
        case "touchstart":
        case "mousedown" :
        type = "mousedown"; break;
        case "touchmove": 
        case "mousemove" :
        type="mousemove"; break;        
        case "touchend": 
        case "mouseup" :
        type="mouseup"; break;
        default: return;
}
    var simulatedEvent = document.createEvent("MouseEvent");
    simulatedEvent.initMouseEvent(type, true, true, window, 1,first.screenX, first.screenY,first.clientX,first.clientY,false,false, false, false, 0/*left*/, null);
    first.target.dispatchEvent(simulatedEvent);
    event.preventDefault();
}

function init() 
{
 document.getElementById('green_box').addEventListener("touchstart", touchHandler, true);
 document.getElementById('green_box').addEventListener("touchmove", touchHandler, true);
 document.getElementById('green_box').addEventListener("touchend", touchHandler, true);
 document.getElementById('green_box').addEventListener("touchcancel", touchHandler, true);    
}

function changeInstrutionInHtml(text){
document.getElementById('instruction_box').innerHTML=(text=='undefined' ||text==null)?'':text;
}

function ActivateGameSequenceWise(num){
    if(num=='undefined' || num==0)
	{
	return false;
	}
	if(isInstructionChangeInProgress){
	return false;
	}
	isInstructionChangeInProgress=true;
    switch(num){
    case 1:
	document.getElementById('startTut').style.display="none";
	document.getElementById('next_step_ok').style.display="block";
    TutorialStart();
    changeInstrutionInHtml(instructionSequence[currentInstructionStatus-1]);
     currentInstructionStatus++;
	 isInstructionChangeInProgress=false;	
		stopAllAudio();	 
		 step1();
	
	 
    break;
    case 2:

        document.getElementById('next_step_ok').style.display='none';
        arrow1_Sprite.stop(arrow1_Sprite);
        arrow2_Sprite.stop(arrow2_Sprite);
    
        var arrowList=document.getElementsByClassName('arrow');
        for(var i=0;i<arrowList.length;i++){
        arrowList[i].style.display='none';    
        }

        changeInstrutionInHtml(instructionSequence[currentInstructionStatus-1]);
        ig.game.BindKey();
        var player=ig.game.getEntitiesByType(EntityPlayer)[0];
       
     currentInstructionStatus++;
		isInstructionChangeInProgress=false;
		stopAllAudio();	
		 step2();
	
    break; 
	case 3:
	 setTimeout(function(){
	changeInstrutionInHtml(instructionSequence[currentInstructionStatus-1]);
	currentInstructionStatus++;
	isInstructionChangeInProgress=false;
	stopAllAudio();
		 step3();
		
	},1000);
	break;
	
    case 4:
	 setTimeout(function(){
	changeInstrutionInHtml(instructionSequence[currentInstructionStatus-1]);
	currentInstructionStatus++;
	isInstructionChangeInProgress=false;
		stopAllAudio();
		 step4();
	 },1000);
	break;
    case 5:
	 setTimeout(function(){
	changeInstrutionInHtml(instructionSequence[currentInstructionStatus-1]);
	currentInstructionStatus++;
	isInstructionChangeInProgress=false;
			stopAllAudio();
		 step5();
	},1000);
	break;
    case 6:	
    setTimeout(function(){
	changeInstrutionInHtml(instructionSequence[currentInstructionStatus-1]);
	currentInstructionStatus++;
	isInstructionChangeInProgress=false;
		stopAllAudio();
		 step6();
		},1000);
    break;
   
   case 7:
    setTimeout(function(){
    changeInstrutionInHtml(instructionSequence[currentInstructionStatus-1]);
	
    var aa=ig.game.static_entity_creator(EntityBall1,0,false);
   if(typeof aa!='undefined'){
    aa.vel.x=0;
    aa.vel.y=0;
    }
    currentInstructionStatus++;
    isInstructionChangeInProgress=false;
		stopAllAudio();
		 step7();
		},1000);
    break;  
  case 8:
    setTimeout(function(){
	changeInstrutionInHtml(instructionSequence[currentInstructionStatus-1]);
    document.getElementById('next_step_ok').style.display='block'
	 $('#arr1').css({'background-position':'-1206px 0','margin':'103px 0px 0px 791px','display':'block'});
    currentInstructionStatus++;
   isInstructionChangeInProgress=false;
  	stopAllAudio();
		 step8();
		},1000);
    ig.game.unbindKey();
   break;

   case 9:
	ig.game.BindKey();
      document.getElementById('next_step_ok').style.display='none'
      changeInstrutionInHtml(instructionSequence[currentInstructionStatus-1]);
	  $('#arr1').css({'display':'none'});
     var aa=ig.game.static_entity_creator(EntityBall10,1,false);
	if(typeof aa!='undefined'){
        aa.vel.x=0;
        aa.vel.y=0;
        }
	currentInstructionStatus++;
  isInstructionChangeInProgress=false;
 	stopAllAudio();
	 step9();
		
    break;
   
   case 10:
    setTimeout(function(){
	ig.game.unbindKey();
	changeInstrutionInHtml(instructionSequence[currentInstructionStatus-1]);
    document.getElementById('next_step_ok').style.display='block';
	
	 $('#arr1').css({'background-position':'-1206px 0','margin':'103px 0px 0px 791px','display':'block'});
	currentInstructionStatus++;
	isInstructionChangeInProgress=false;
		stopAllAudio();
		 step10();
    },1000);
    break;
   
   case 11:
    setTimeout(function(){
	ig.game.BindKey();
    document.getElementById('next_step_ok').style.display='none';
    document.getElementById('play_next').style.display='block'
	document.getElementById('arr1').style.display='none';
	document.getElementById('arrow_target').style.display='block'
    changeInstrutionInHtml(instructionSequence[currentInstructionStatus-1]);
    currentInstructionStatus++;
	isInstructionChangeInProgress=false;
		 step11();
	    },1000)
    break;
   
   case 12:
   isInstructionChangeInProgress=false;
     window.close();
    }
}

 function TutorialStart(){
 $('.disable').removeClass('disable');
 arrow1_Sprite= new sprites(document.getElementById('arr1'),2000,31,30,1);
 arrow2_Sprite= new sprites(document.getElementById('arr2'),2000,31,30,1);
 arrow1_Sprite.start(arrow1_Sprite,0,[a]);
 arrow2_Sprite.start(arrow2_Sprite,0,[a])
 }
    function PlayCollision() {
	 if(isAudioStart)
		 {	audioPlayerr.pause();
		 
			setTimeout(function(){audioPlayerr.play('eating');},400);	
		 }
   }

   function playLevelComplete(){
	 if(isAudioStart)
	audioPlayerr.play('levelComplete');
    }
    function playGameComplete() {
		 if(isAudioStart)
		audioPlayerr.play('gameEnd');
    }
	function playIncorrect() {
 		 if(isAudioStart)
		audioPlayerr.play('busting');
    }
    function textHighlight() {
        $('#score').animate({"font-size":"42pt"},200,function(){
            $(this).animate({'font-size':'64pt'},200,function(){
                $(this).animate({'font-size':'45pt'},100,function(){});

            });
        });
    }
 function a(){}
    function activeDevelopment(){
        var fileref=document.createElement('script')
        fileref.setAttribute("type","text/javascript")
        fileref.setAttribute("src","lib/impact/impact.js");
        document.getElementsByTagName("head")[0].appendChild(fileref)
        fileref=document.createElement('script')
        fileref.setAttribute("type","text/javascript")
        fileref.setAttribute("src","lib/game/main.js");
        document.getElementsByTagName("head")[0].appendChild(fileref);   
    }
	function activeMinified(){
      var fileref=document.createElement('script');
        fileref.setAttribute("type","text/javascript");
        fileref.setAttribute("src","game.min.js");
        document.getElementsByTagName("head")[0].appendChild(fileref);
	}
    function switchToGameCanvas(){
        document.getElementById("Container").style.display="none";
		document.getElementById("canvas_background").style.display="block";
	};
	window.onorientationchange = detectIPadOrientation;
    window.onload = detectIPadOrientation;
    function detectIPadOrientation(){
        if((navigator.userAgent.indexOf('iPad') != -1)) {            
       if(window.orientation % 180 == 0 ) {
       $('meta[name=viewport]').attr('content','width=768, height=1024, initial-scale=0.75, maximum-scale=0.75, user-scalable=no');
       }  else if(window.orientation % 90 == 0) {
       $('meta[name=viewport]').attr('content','width=1024, height=768, initial-scale=1, maximum-scale=1.0, user-scalable=no');
       }
      }
  }
  
var sprites = function(domelement1, duriation, numberofsprites, harizontalsprites, verticalsprites) {
    this.domelement = domelement1;
    //refer to element that we want animate
    this.timeslice = duriation;
    //time for animation
    this.numberofsprites = numberofsprites;
    //number of small images in the sprite image
    this.harizontalsprites = harizontalsprites;
    //number of horizontal images
    this.verticalsprites = verticalsprites;
    //number of vertical images
    this.setinterval//setInterval for animation
    this.moveinterval//setInterval for motion
    this.spritecount = 0;
    this.xposition
    this.yposition
    this.width
    this.height
    this.positions
    this.noofloops
    this.z = 1;
    this.movement
    this.shift
    this.whichsprite
};

// prototypes for sprite class
sprites.prototype = {
    start : function(element, numberofloops, callback) {
        element.noofloops = numberofloops;
        element.spritecount = 1;
        element.setinterval = setInterval(function() {
            if (detect.isFirefox) {
                element.positions = element.domelement.style.backgroundPosition;
                element.xposition = element.positions.split(" ")[0].split("p")[0];
                element.yposition = element.positions.split(" ")[1].split("p")[0];
            } else {
                element.xposition = element.domelement.style.backgroundPositionX.split("p")[0];
                element.yposition = element.domelement.style.backgroundPositionY.split("p")[0];
            }
            element.xposition = parseInt(element.xposition);
            element.yposition = parseInt(element.yposition);
            element.width = parseInt(element.domelement.style.width.split("p")[0]);
            element.xposition = element.xposition - element.width;
            if (-(element.xposition) > (element.harizontalsprites - 1) * element.width) {
                element.xposition = 0;
                element.height = element.domelement.style.height.split("p")[0];
                element.yposition = element.yposition - element.height;
                if (-(element.yposition) > (element.verticalsprites * element.height)) {
                    element.yposition = 0;
                }
            }
            element.spritecount++;
            if (detect.isFirefox) {
                element.domelement.style.backgroundPosition = element.xposition + "px" + " " + element.yposition + "px";
            } else {
                element.domelement.style.backgroundPositionX = element.xposition + "px";
                element.domelement.style.backgroundPositionY = element.yposition + "px";
            }
            if (element.spritecount >= element.numberofsprites) {
                element.spritecount = 1;
                if (element.noofloops == 0) {
                    element.reset(element);
                }
                if (element.noofloops != 0) {
                    if (element.z == element.noofloops) {
                        element.setinterval = clearInterval(element.setinterval);
                        this.callback = callback;
                        if ( typeof this.callback != 'undefined') {
                            if (this.callback.length != 0) {
                                this.firstelement = this.callback[0];
                                this.callback.reverse();
                                this.callback.pop();
                                this.callback.reverse();
                                this.firstelement();
                            }
                        }
                    } else {
                        element.z++;
                    }
                }
            }
        }, Math.floor(element.timeslice / element.numberofsprites));
    },
    stop : function(element) {
        if (element.setinterval != "undefined")
            element.setinterval = clearInterval(element.setinterval);
    },
    reset: function(element) {
        if (detect.isFirefox) {
            element.domelement.style.backgroundPosition = "0px 0px";
        } else {
            element.domelement.style.backgroundPositionX = "0px";
            element.domelement.style.backgroundPositionY = "0px";
        }
    }
};
	
numberWithCommas=function(x){
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
		