var playAddress='media/crops_new_UI/play_game.png';

var pauseAddress='media/crops_new_UI/pause_game.png';

var isAudioStart=true;

 

function changeAudio(obj){

    if(!isSubmitInOpenState){

	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 ActiveGame(){

$('#toggleGame')

.attr('src',pauseAddress)

.attr('isGameActive','true');

ig.system.startRunLoop();

}

function InactiveGame(){

$('#toggleGame')

.attr('src',playAddress)

.attr('isGameActive','false');

ig.system.stopRunLoop();

}

$(function(){

/*if(!(navigator.userAgent.toLowerCase().indexOf('msie')!=-1))

{$(window).bind("beforeunload",function(){window.close();});}

*/

window.onorientationchange = detectIPadOrientation;

    window.onload = detectIPadOrientation;

});

function TutorialOpener(){

 var top=(jQuery(window).height()/2)-(600/2);

  var left=(jQuery(window).width()/2)-(960/2);

  if( typeof screenLeft!='undefined' && typeof screenTop!='undefined' &&  typeof screen !='undefiend' && navigator.userAgent.indexOf('MSIE')==-1){

  MyWindow1=window.open('game_tutorial/tutorial.html','MyWindow1','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=960,height=600,left='+screenLeft+', top='+screenTop); 

  }

  else{

  MyWindow1=window.open('game_tutorial/tutorial.html','MyWindow1','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=960,height=600,left='+left+', top='+top); 

  }



   var gameMode = {

        "actor": {

            "id": Setting["actor.id"]

        },

        "published": "",



        "generator": {"appId": Setting["generator.appId"]},

        "target": {

            "objectType": "game",

            "displayName": Setting["target.displayName"]

        },

        "object": {

            "id": "123",

            "gameLevel": _gameLevel,

            "objectType": "Learn"

        },

        "verb": "gameMode"

    };



/*data captures*/

gameMode.published=getTimeStamp();

gameMode.object.type="Learn";

//gameMode=JSON.stringify(gameMode); 

if(typeof window.seer!='undefined') 

window.seer.activity(gameMode);

/*data captures complete*/

  }

	

function checkStoporStart(dom){

if(typeof dom=='undefined')return false;

if(!ig.game.isGameCompleted && !isSubmitInOpenState){

var isGameActive=$(dom).attr('isGameActive');

if(typeof isGameActive!='undefined'){

if(isGameActive=='true'){

InactiveGame();

}

else{

ActiveGame();

}

}

}

}

   var text = document.getElementById('text');

   var playvalue=0;

	var audioPlayer = document.createElement('audio');

    if(!!audioPlayer.canPlayType('audio/mpeg') === true){

        audioPlayer.setAttribute('src', "media/sound/MathGame_combined_SFX.mp3");

    }else{

	  audioPlayer.setAttribute('src', "media/sound/MathGame_combined_SFX.ogg");

	}

    audioPlayer.setAttribute('id','CollisionAudio');

    $('body').append(audioPlayer);

    audioPlayer.load();

    var CollisionAudio = document.getElementById('CollisionAudio');

    CollisionAudio.addEventListener("timeupdate",function(){

        if(playvalue==1)

        {

            if(CollisionAudio.currentTime >= 2){

                CollisionAudio.pause() ;

				 playvalue=0;

            }

        }

        if(playvalue==2)

        {

            if(CollisionAudio.currentTime >= 6){

                CollisionAudio.pause();

				playvalue=0;

            }

        }

        if(playvalue==3)

        {

           if(CollisionAudio.currentTime >= 10){

                CollisionAudio.pause();

				playvalue=0;

            }

        }

		if(playvalue==4){

		 if(CollisionAudio.currentTime >= 12){

                CollisionAudio.pause();

				playvalue=0;

            }

		}

    },true);

    function PlayCollision() {

if(isAudioStart){

	  playvalue=1;

        CollisionAudio.currentTime=1;

        if(isSoundLoadComplete)

		CollisionAudio.play();

	}

  }

    function playLevelComplete(){

if(isAudioStart){

	setTimeout(function(){

        playvalue=2;

          CollisionAudio.currentTime=3.5;

        	 if(isSoundLoadComplete)

					CollisionAudio.play();

				},500);

				}

    }

    function playGameComplete() {

	if(isAudioStart){

		setTimeout(function(){

        playvalue=3;

        CollisionAudio.currentTime=7;

		if(isSoundLoadComplete)       

			CollisionAudio.play();

		},200);

			}

    }

	function playIncorrect() {

	if(isAudioStart){

	setTimeout(function(){

        playvalue=4;

        CollisionAudio.currentTime=11;

  if(isSoundLoadComplete)

		CollisionAudio.play();

		},600);

		}

    }



    var ss = document.getElementById('score');

    function textHighlight(){

	 $(ss).css('line-height','70px');

	        $(ss).animate({"font-size":global_score_control.text_animation_font.init,"line-height":"80px"},200,function(){

			if(ig.system.running){

            $(this).animate({'font-size':global_score_control.text_animation_font.mid,"line-height":"60px"},200,function(){

			if(ig.system.running){

                $(this).animate({'font-size':global_score_control.text_animation_font.finall,"line-height":"72px"},100,function(){});

				} 

				});

				}

        });

	 }

	 

	 isGameDisplayYes=false;

    function startGame(){

    document.getElementById("Container").style.display="none";

    document.getElementById("canvas_background").style.display="block";

	productionVesion();

	//DevelopmentVersion();

	CollisionAudio.load();

	isGameDisplayYes=true;

	var levelselection = {

        "actor": {

            "id": Setting["actor.id"]

        },

        "generator": {"appId": Setting["generator.appId"]},

        "target": {

            "objectType": "game",

            "displayName": Setting["target.displayName"]

        },

        "published": "",

        "verb": "levelSelected",

        "object": {

            "id": "123",

            "levelSelecetd": _gameLevel,

            "range": _range,

            "objectType": "Play"

        }

    };

/*data captures*/

levelselection.published=getTimeStamp();

//levelselection=JSON.stringify(levelselection); 

if(typeof window.seer!='undefined') 

window.seer.activity(levelselection);

/*data captures complete*/

CollisionAudio.addEventListener("canplaythrough",function(){

	isSoundLoadComplete=true;

	},false);

}

	var isSoundLoadComplete=false;

	function DevelopmentVersion(){

	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 productionVesion(){

	 var fileref=document.createElement('script');

        fileref.setAttribute("type","text/javascript");

        fileref.setAttribute("src","game.min.js");

        document.getElementsByTagName("head")[0].appendChild(fileref);

	}

	

	

    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');

       }

      }

  }

  

  

function preloadImages(imgArray,relativepath){

$.imgpreload(imgArray,

{

    each:function(imgobject,currentnumber,totalimages)

    { 

    },

    all: function()

    {

    },relativeURL:relativepath	

});

}

if ('undefined' != typeof jQuery)

{(function($){

	// extend jquery (because i love jQuery)

		$.imgpreload = function (imgs,settings)

		{

			settings = $.extend({},$.fn.imgpreload.defaults,(settings instanceof Function)?{all:settings}:settings);

			// use of typeof required

			// https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Operators/Special_Operators/Instanceof_Operator#Description

			if ('string' == typeof imgs) { imgs = new Array(imgs); }

			var loaded = new Array();

			$.each(imgs,function(i,elem)

			{

				var img = new Image();

		                if(settings.relativeURL != null){elem= settings.relativeURL + elem }

				var url = elem;

				var img_obj = img;

				if ('string' != typeof elem){

					url = $(elem).attr('src');

					img_obj = elem;

				}

				$(img).bind('load error', function(e)

				{

					loaded.push(img_obj);

					$.data(img_obj, 'loaded',('error'==e.type)?false:true);				

					if (settings.each instanceof Function) { settings.each.call(this,img_obj,loaded.length,imgs.length); }

					// http://jsperf.com/length-in-a-variable

					if (loaded.length>=imgs.length && settings.all instanceof Function) { settings.all.call(loaded); }

					$(this).unbind('load error');

				});

				img.src = url;

			});

		};

		$.fn.imgpreload = function(settings)

		{$.imgpreload(this,settings);return this;

		};

		$.fn.imgpreload.defaults={

			each: null // callback invoked when each image in a group loads

			, all: null // callback invoked when when the entire group of images has loaded

			,relativeURL:null

		};



	})(jQuery);

};

var pngimages=[

/*png images*/

"../png/01.jpg",

"../png/bg1.jpg",

"../png/HowToPlay_btn.png",

"../png/play_btn.png",

"../png/play_btn_start.png"

];

var mediaImages=[

/*media images*/

"1-9.png",

"1.png",

"10-90.png",

"10.png",

"100.png",

"Animation2_new.png",

"Animation_edge_glow.png",

"Animation_reward_new2.png",

"background.png",

"Burst6_01-09.png",

"Burst6_10-90.png",

/*"Done.png",*/

"end_text_popup.png",

"Math_end.png",

"OK_btn.png",

"Open_screen.png"

];

var crops=[

/*crops_new ui folder images*/

"crops_new_UI/audio_off.png"

,"crops_new_UI/audio_on.png"

,"crops_new_UI/Help_btn.png"

,"crops_new_UI/level_indicator_current.png"

,"crops_new_UI/level_indicator_passed.png"

,"crops_new_UI/level_indicator_unattempted.png"

,"crops_new_UI/number_BG.png"

,"crops_new_UI/pause_game.png"

,"crops_new_UI/play_game.png"

,"crops_new_UI/sidebar.png"

];



setTimeout(function(){preloadImages(pngimages,"media/");},1);



setTimeout(function(){preloadImages(mediaImages,"media/");},2);



setTimeout(function(){preloadImages(crops,"media/");},5);





var submitImages=[

"cancel_Default.png",

"cancel_Over.png",

"cancel_Pressed.png",

"submit_Default.png",

"submit_Disabled.png",

"submit_Over.png",

"submit_Pressed.png",

"Submit_Progress-Dialog-Box.png",

"x_Default.png",

"x_Disabled.png",

"x_Over.png",

"x_Pressed.png"

];



$(function(){

setTimeout(function(){

if(isCheckScormAvailable())

preloadImages(submitImages,"media/submit_button/");

},100);

});

