//console.log(navigator.userAgent.indexOf("Iphone"));

var click_or_touch;

if( navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i)  || navigator.userAgent.match(/Android/i)  || navigator.userAgent.match(/Mobile/i) ){
	
	click_or_touch = "click touchstart";
	
}else{
	
	click_or_touch = "click";

}

console.log(click_or_touch);

var templatedata;  // template json data is  stored in to this variable  through ajax call
// var animationdata; // animation json data is  stored in to this variable  through ajax call
var girlidle;      // object for girl animation for idle position
var girlleft;      // object for girl  animation for leftjump position
var girlright;     // object for girl  animation for rightjump position
var girlwrong;     // object for girl  animation for wrong door choosen
var girlcorrect;   // object for girl  animation for correct door choosen
var doorsprite = [];    // object for door  animation for opening and closing
var girlgameover;  // object for girl animation after game over
var girlgameoverloop; //object for girl animation after game over and loop
var animationdirection;  // variable for animating the girl character either left or right
var answer;              // boolean variable specifying corrct door choosen or not
var questionnumber = 0;    // variable specifying question number
var screenWid;           // variable for calculating screen width
var incorrectaudio;      // audio object for playing incorrectaudio
var correctstart;        // audio object for playing correctaudio start movement
var footsoff;            // audio object for playing girl foot sound play after entering to door
var finalapplause;       // audio object for playing after the end of the game
var ding;                // audio object for playing ding sound
var correctAudio;        // audio object for playing prise sound
var correctAudioSounds;  //array for storing the parise sounds url
var animationsoundArray = [];  //playlist for audios play in ipad
var explanationaudio;     //audio object for playing voice over on each word that belongs to each door other than ipad   
var audiotoggle = true;     //on/off toggle variable to stop or play the audio on each word 
var optionnumber = 0;       // a variable which stores option number related door
var allowplaycontent = true;//to stop playing voice over while animation is progress
var nextaudio;            //setTimeout variable for controling audios
var imagehide;            //variable to hold id of selected door image
var gameover = false;       //variable to specify gameover
var wrongAudioSounds;
var optionsarray = [];
var levelelement = 0;
var girlwalk;
var totalwidthneeded;
var centerpartwidth;
var resizeflag = true;
var CollisionAudio = null;
var firfox = 0;
var chrome = 0;
var resetImagesTimer;
var footerextbut = "assets/images/bg/";

var isIE8 = $.browser.msie && +$.browser.version === 8;

var sprites = function (domelement1, domimageelement, object, dummyobject, 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.domimageelement = domimageelement;
    this.setinterval;                //setInterval for animation 
    this.moveinterval;               //setInterval for motion 
    this.spritecount = 0;
    this.dummyobject = dummyobject;
    this.object = object;
    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, startsprite, callback) {

        element.noofloops = numberofloops;
        element.spritecount = startsprite;
        element.setinterval = setInterval(
                function () {
                    element.animate(element);
                    element.spritecount++;
                    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.spritecount = 0;
                                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) {

        element.domimageelement.style.marginLeft = "0px";
        element.domimageelement.style.marginTop = "0px";
    },
    animate: function (element) {
        element.dummyobject.width = Math.floor(element.object.width * ($("#centerpart").width() / centerpartwidth));
        element.dummyobject.height = Math.floor(element.object.height * ($("#centerpart").width() / centerpartwidth));
        if (($(window).width()) < totalwidthneeded)
        {
            element.dummyobject.top = Math.floor(element.object.top * ($("#centerpart").width() / centerpartwidth)) + 3.5;
        } else
        {
            element.dummyobject.top = Math.floor(element.object.top * ($("#centerpart").width() / centerpartwidth));
        }
        element.dummyobject.left = Math.floor(element.object.left * ($("#centerpart").width() / centerpartwidth));

        element.domelement.style.width = element.dummyobject.width + "px";
        element.domelement.style.height = element.dummyobject.height + "px";
        element.domimageelement.style.width = (element.dummyobject.width * element.harizontalsprites) + "px";
        element.domimageelement.style.height = (element.dummyobject.height * element.verticalsprites) + "px";
        element.domimageelement.style.marginLeft = -((element.spritecount % element.harizontalsprites) * element.dummyobject.width) + "px";
        element.domimageelement.style.marginTop = -(Math.floor(element.spritecount / element.harizontalsprites) * element.dummyobject.height) + "px";
    },
    resize: function (element) {
        element.dummyobject.width = Math.floor(element.object.width * ($("#centerpart").width() / centerpartwidth));
        element.dummyobject.height = Math.floor(element.object.height * ($("#centerpart").width() / centerpartwidth));
        if (($(window).width()) < totalwidthneeded)
        {
            element.dummyobject.top = Math.floor(element.object.top * ($("#centerpart").width() / centerpartwidth)) + 3.5;
        } else
        {
            element.dummyobject.top = Math.floor(element.object.top * ($("#centerpart").width() / centerpartwidth));
        }
        element.dummyobject.left = Math.floor(element.object.left * ($("#centerpart").width() / centerpartwidth));
        element.domelement.style.width = element.dummyobject.width + "px";
        element.domelement.style.height = element.dummyobject.height + "px";
        element.domimageelement.style.width = (element.dummyobject.width * element.harizontalsprites) + "px";
        element.domimageelement.style.height = (element.dummyobject.height * element.verticalsprites) + "px";
        element.domelement.style.top = element.dummyobject.top + "px";
        element.domelement.style.left = element.dummyobject.left + "px";
        element.domimageelement.style.marginLeft = -((element.spritecount % element.harizontalsprites) * element.dummyobject.width) + "px";
        element.domimageelement.style.marginTop = -(Math.floor(element.spritecount / element.harizontalsprites) * element.dummyobject.height) + "px";

    },
    harizontalmove: function (element, targetelement, horizontalendsprite, verticalendsprite) {

        // element.shift=(parseInt(targetelement.style.left.split("p")[0]) - parseInt(element.domelement.style.left.split("p")[0]));
        element.whichsprite = parseInt(horizontalendsprite);
        element.moveinterval = setInterval(
                function () {
                    element.shift = (parseInt(targetelement.style.width.split("p")[0]) - parseInt(element.domelement.style.width.split("p")[0])) / 2;
                    element.shift = parseInt(targetelement.style.left.split("p")[0]) + element.shift;
                    element.shift = (parseInt(element.domelement.style.left.split("p")[0]) - element.shift);
                    if ((element.whichsprite - element.spritecount) != 0)
                        element.shift = (element.shift) / (element.whichsprite - element.spritecount);

                    element.movement = parseInt(element.domelement.style.left.split("p")[0]);
                    element.domelement.style.left = element.movement - element.shift + "px";
                    if (element.whichsprite == element.spritecount)
                    {
                        element.moveinterval = clearInterval(element.moveinterval);
                        element.verticalmove(element, targetelement, horizontalendsprite, verticalendsprite);
                    }
                }, Math.floor(element.timeslice / element.numberofsprites)
                );
    },
    verticalmove: function (element, targetelement, horizontalendsprite, verticalendsprite) {
        element.whichsprite = parseInt(verticalendsprite - element.whichsprite);
        element.moveinterval = setInterval(
                function () {
                    element.shift = ((parseInt(element.domelement.style.top.split("p")[0]) + parseInt(element.domelement.style.height.split("p")[0])) - (parseInt(targetelement.style.top.split("p")[0]) + parseInt(targetelement.style.height.split("p")[0])));

                    element.shift = (element.shift) / ((parseInt(horizontalendsprite) + element.whichsprite) - element.spritecount);
                    element.movement = parseInt(element.domelement.style.top.split("p")[0]);
                    element.domelement.style.top = (element.movement - element.shift) + "px";
                    if ((parseInt(horizontalendsprite) + element.whichsprite) == element.spritecount || element.spritecount == 0)
                    {
                        element.moveinterval = clearInterval(element.moveinterval);
                    }
                }, Math.floor(element.timeslice / element.numberofsprites)
                );
    }

};

$(document).ready(function () {


//    $.browser.chrome = /chrom(e|ium)/.test(navigator.userAgent.toLowerCase());
//    if ($.browser.chrome)
//    {
//        chrome = 1;
//
//    }
//    else
//    {
//
//        chrome = 0;
//    }
//
//
//    if (navigator.userAgent.match(/Android|Android 3.2|Android 3.1|Android 3.0/) != null)
//    {
//        if ($.browser.mozilla)
//        {
//            firfox = 1;
//        }
//        else
//        {
//            firfox = 0;
//        }
//    }
//    else
//    {
//        firfox = 0;
//    }


//    if (firfox)
//    {
//        if (navigator.userAgent.match(/ipad/i) == null && !isIE8)
//        {
//            if (!chrome)
//                CollisionAudio = new audiofunctinallity("myaudio", "assets/audio/CompileInOne_1", timeobject);
//        }
//    }


    // if(!isIE8){
    // CollisionAudio=new audiofunctinallity("myaudio","assets/audio/CompileInOne",timeobject);
    // }

    // window.setTimeout(function(){
    // if(!isIE8)
    // {
    // var dummyarray=["L3_25AM01","L3_25AM02","L3_25AM03","L3_25AM04"];
    // CollisionAudio.playBackToBack(dummyarray);
    // }
//    	
    // },2000); 
    // window.setTimeout(function(){
    // if(!isIE8)
    // {
    // var dummyarray=["L3_25AM01","L3_25AM02","L3_25AM03","L3_25AM04"];
    // CollisionAudio.playBackToBack(dummyarray);
    // }
//    	
    // },10000);      




    templatedata = $.extend({}, settings, bodycontent);

    renderAnimationFile();

    // preloading
    function preloader() {
        if (document.images) {
            var img1 = new Image();
            var img2 = new Image();
            var img3 = new Image();

            img1.src = "assets/images/Sprites/girl_anim_jumpRight_Walk.png";
            img2.src = "assets/images/Sprites/girl_anim_jumpLeft_Walk.png";
            img3.src = "assets/images/Sprites/girl_anim_incorrect.png";
        }
    }
    /*
     *   preloading images 
     */
    function addLoadEvent(func) {
        var oldonload = window.onload;
        if (typeof window.onload != 'function') {
            window.onload = func;
        } else {
            window.onload = function () {
                if (oldonload) {
                    oldonload();
                }
                func();
            }
        }
    }
    addLoadEvent(preloader);

    $("#reset span").html(templatedata.settings.text_reset);
    $("#menuButton span a").html(templatedata.settings.text_help);

    $("#reset").live(click_or_touch, resetActivity);


    $("#reset").hover(function () {
        document.getElementById("reset").getElementsByTagName('img')[0].src = footerextbut + templatedata.ResetButHover;
    }, function () {
        document.getElementById("reset").getElementsByTagName('img')[0].src = footerextbut + templatedata.ResetButNormal;
    });
    $("#reset").mousedown(function () {
        document.getElementById("reset").getElementsByTagName('img')[0].src = footerextbut + templatedata.ResetButHover;
    });

    $("#menuButton").hover(function () {

        document.getElementById("menuButton").getElementsByTagName('img')[0].src = footerextbut + templatedata.MenuButHover;
    }, function () {
        document.getElementById("menuButton").getElementsByTagName('img')[0].src = footerextbut + templatedata.MenuButNormal;
    });
    $("#menuButton").mousedown(function () {
        document.getElementById("menuButton").getElementsByTagName('img')[0].src = footerextbut + templatedata.MenuButHover;
    });

    $(".audioimage").live({
        mouseenter:
                function ()
                {
                    $(this).attr("src", "assets/images/content/audio_O1.png");
                },
        mouseleave:
                function ()
                {
                    $(this).attr("src", "assets/images/content/audio_N1.png");
                }
    }
    );
    $(".audioimage").live('mousedown',
            function () {
                $(this).attr("src", "assets/images/content/audio_D1.png");
            });



    //$(".heading").corner("round top 10px", "white");

    $("#menuButton").click(function ()
    {
        location.href = templatedata.centerpart.QuitURL;
    });
});





/*
 *   ajax call for getting animationjson file
 */
function renderAnimationFile()
{ //  $.ajax({
    // url: "json/animationjson.json",
    // dataType:'json',
    // type:'get',
    // success: function(data1) {
    // animationdata=data1;   
    // renderScreen();
    // },
    // error : function()
    // {                            /*  if error occured in geting data callback function*/
    // alert("network error1");
    // }
    // });

    renderScreen();
}


/*
 * function to check whether data will fit into screen, animation screen is divided into three parts leftpart where books stand and left wall is present
 * centerpart where doors and girl are present and rightpart where right wall is present 
 */
function renderScreen()
{

    // creating audio objects with source

//    if (navigator.userAgent.match(/ipad/i) == null)
//    {
        explanationaudio = createAudio(getAudioExtension("assets/audio/CompileInOne_1", ".mp3"));
        finalapplause = createAudio(getAudioExtension("assets/audio/CompileInOne_1", ".mp3"));

//
//    }


//    if (html5_audio())
//    {
//

//        if (navigator.userAgent.match(/ipad/i) != null)
//        {
//
//
//            document.getElementById("muitiaudio").addEventListener('canplaythrough', canPlayThrough, false);
//
//        } else
//        {

            explanationaudio.addEventListener('ended', function () {
                optionnumber++;

                if (optionnumber != (templatedata.levels[levelelement].level.numberofdoors))
                {
                    explanationaudio.src = "assets/audio/" + getAudioExtension(optionsarray[optionnumber].door.sound, ".mp3");
                    explanationaudio.load();
                    explanationaudio.play();


                } else
                {

                    audiotoggle = true;
                    optionnumber = 0;
                }
            }, false);
//        }
//    }


    screenWid = $(window).width();



    totalwidthneeded = parseInt(templatedata.leftpart.width) + ((templatedata.levels[levelelement].level.numberofdoors) * (parseInt(templatedata.centerpart.doorwidth) +
            parseInt(templatedata.centerpart.spacebetweendoors) + 1)) + parseInt(templatedata.rightpart.width);

    setContainer();
    headerfonts();

    constructScreen();
}

/*if the requried screen width is greater then the avaliable screen width  removing leftpart and right part*/


function constructScreen()
{
    //setting images for buttos
    document.getElementById("reset").getElementsByTagName('img')[0].src = footerextbut + templatedata.ResetButNormal;
    document.getElementById("menuButton").getElementsByTagName('img')[0].src = footerextbut + templatedata.MenuButNormal;


    $(".container").append("<div class='leftpart' id='leftpart' style=' position:relative; left:0px;top:0px; width:" + (((templatedata.leftpart.width) * 100) / totalwidthneeded) + "%;  height:100%'><img src=" + templatedata.leftpart.image + " style='position:absolute;top:0px;left:0px;width:100%;height:100%'/></div>");
    centerpartwidth = ((parseInt(templatedata.centerpart.doorwidth) + parseInt(templatedata.centerpart.spacebetweendoors) + 1) * (parseInt(templatedata.levels[levelelement].level.numberofdoors)));
    $(".container").append("<div class='centerpart' id='centerpart' style=' position:absolute; left:" + (((templatedata.leftpart.width) * 100) / totalwidthneeded) + "% ;top:0px; width:" + ((centerpartwidth * 100) / totalwidthneeded) + "%; height:100%'><img src=" + templatedata.centerpart.image + " style='position:absolute;top:0px;left:0px;width:100%;height:100%'/></div>");

    $(".container").append("<div class='rightpart' id='rightpart'  style=' position:absolute;left:" + ((((templatedata.leftpart.width) * 100) / totalwidthneeded) + ((centerpartwidth * 100) / totalwidthneeded)) + "% ;top:0px; width:" + ((templatedata.rightpart.width * 100) / totalwidthneeded) + "%;  height:100%;'><img src=" + templatedata.rightpart.image + " style='position:absolute;top:0px;left:0px;width:100%;height:100%'/></div>");

    $(".centerpart").append("<img  class='audiobutton' id='allAudio' title='audio' onclick='playContentAudios()' onMousedown='audiobuttonmousedown()' onMouseout='audiobuttonmouseout()' onMouseover='audiobuttonmousein()' src='assets/images/content/audio_N.png' style='position:absolute;cursor:pointer; left:0px; top:0px; z-index:500;width:" + (40 * 100) / centerpartwidth + "% ; height:" + (55 * 100) / 459 + "% '/>");
    $(".centerpart").append('<img src="assets/images/bg/bg3.jpg" style="width:99%;height:100%;top:0%;left:0%; z-index:-1;position:absolute"/>');

    for (var i = 1; i <= parseInt(templatedata.levels[levelelement].level.numberofdoors); i++)
    {
        /*creating doors*/
        $(".centerpart").append("<div class='door' id='door" + i + "' style='position:absolute; width:" + ((templatedata.centerpart.doorwidth * 100) / centerpartwidth) + "%;  height:" + (templatedata.centerpart.doorheight * 100) / 459 + "%; top:" + (templatedata.centerpart.doortop) + "px; left:" + ((parseInt(templatedata.centerpart.spacebetweendoors) * i) + (parseInt(templatedata.centerpart.doorwidth) * (i - 1))) + "px;cursor: pointer;cursor: hand; overflow: hidden'><img src=" + templatedata.centerpart.doorimage + " id='doorsprite" + i + "'    style='position:absolute;top:0px;left:0px;'/></div>");
        var dim = {};
        var dummydim = {};
        dim["width"] = templatedata.centerpart.doorwidth;
        dummydim["width"] = templatedata.centerpart.doorwidth;
        dim["height"] = templatedata.centerpart.doorheight;
        dummydim["height"] = templatedata.centerpart.doorheight;
        dim["top"] = templatedata.centerpart.doortop;
        dummydim["top"] = templatedata.centerpart.doortop;
        dim["left"] = ((parseInt(templatedata.centerpart.spacebetweendoors) * i) + (parseInt(templatedata.centerpart.doorwidth) * (i - 1)));
        dummydim["left"] = ((parseInt(templatedata.centerpart.spacebetweendoors) * i) + (parseInt(templatedata.centerpart.doorwidth) * (i - 1)));
        doorsprite[i] = new sprites(document.getElementById("door" + i), document.getElementById("doorsprite" + i), dim, dummydim, animationdata.animationtemplate[0].timeinterval, animationdata.animationtemplate[0].framescount, animationdata.animationtemplate[0].horizontalframes, animationdata.animationtemplate[0].verticalframes);
        doorsprite[i].resize(doorsprite[i]);
    }

    /*creating girl idle*/

    leftforgirl = (centerpartwidth - parseInt(animationdata.animationtemplate[2].width)) / 2

    $(".centerpart").append("<div class='girlidle' id='girlidle' style='position:absolute; width:" + ((animationdata.animationtemplate[2].width * 100) / centerpartwidth) + "%;  height:" + ((animationdata.animationtemplate[2].height * 100) / centerpartwidth) + "%; top:" + (animationdata.animationtemplate[2].top) + "; left:" + leftforgirl + "%;z-index:1000;display:block;overflow:hidden'><img src=" + animationdata.animationtemplate[2].images + " id='girlidlesprite'   style='position:absolute;top:0px;left:0px;'/></div>");
    var dimgirlidle = {};
    var dummydimgirlidle = {};
    dimgirlidle["width"] = animationdata.animationtemplate[2].width;
    dummydimgirlidle["width"] = animationdata.animationtemplate[2].width;
    dimgirlidle["height"] = animationdata.animationtemplate[2].height;
    dummydimgirlidle["height"] = animationdata.animationtemplate[2].height;
    dimgirlidle["top"] = animationdata.animationtemplate[2].top;
    dummydimgirlidle["top"] = animationdata.animationtemplate[2].top;
    dimgirlidle["left"] = leftforgirl;
    dummydimgirlidle["left"] = leftforgirl;

    girlidle = new sprites(document.getElementById('girlidle'), document.getElementById("girlidlesprite"), dimgirlidle, dummydimgirlidle, animationdata.animationtemplate[2].timeinterval, animationdata.animationtemplate[2].framescount, animationdata.animationtemplate[2].horizontalframes, animationdata.animationtemplate[2].verticalframes);
    girlidle.resize(girlidle);
    girlidle.start(girlidle, 0, 1);

    $(".centerpart").append("<div class='girlleftjump' id='girlleftjump' style='position:absolute; width:" + ((animationdata.animationtemplate[4].width * 100) / centerpartwidth) + ";  height:" + ((animationdata.animationtemplate[4].height * 100) / centerpartwidth) + "%; top:" + ((animationdata.animationtemplate[4].top * 100) / 459) + "%; left:" + (leftforgirl * 100) / centerpartwidth + "% ;z-index:1000;display:none;overflow:hidden'><img src=" + animationdata.animationtemplate[4].images + " id='girlleftjumpsprite'   style='position:absolute;top:0px;left:0px;'/></div>");
    var dimgirlleftjump = {};
    var dummydimgirlleftjump = {};
    dimgirlleftjump["width"] = animationdata.animationtemplate[4].width;
    dummydimgirlleftjump["width"] = animationdata.animationtemplate[4].width;
    dimgirlleftjump["height"] = animationdata.animationtemplate[4].height;
    dummydimgirlleftjump["height"] = animationdata.animationtemplate[4].height;
    dimgirlleftjump["top"] = animationdata.animationtemplate[4].top;
    dummydimgirlleftjump["top"] = animationdata.animationtemplate[4].top;
    dimgirlleftjump["left"] = leftforgirl;
    dummydimgirlleftjump["left"] = leftforgirl;
    girlleft = new sprites(document.getElementById('girlleftjump'), document.getElementById("girlleftjumpsprite"), dimgirlleftjump, dummydimgirlleftjump, animationdata.animationtemplate[4].timeinterval, animationdata.animationtemplate[4].framescount, animationdata.animationtemplate[4].horizontalframes, animationdata.animationtemplate[4].verticalframes);
    girlleft.resize(girlleft);


    $(".centerpart").append("<div class='girlrightjump' id='girlrightjump' style='position:absolute; width:" + ((animationdata.animationtemplate[5].width * 100) / centerpartwidth) + ";  height:" + ((animationdata.animationtemplate[5].height * 100) / centerpartwidth) + "%; top:" + ((animationdata.animationtemplate[5].top * 100) / 459) + "%; left:" + (leftforgirl * 100) / centerpartwidth + "% ;z-index:1000;display:none;overflow:hidden'><img src=" + animationdata.animationtemplate[5].images + " id='girlrightjumpsprite'   style='position:absolute;top:0px;left:0px;'/></div>");
    var dimgirlrightjump = {};
    var dummydimgirlrightjump = {};
    dimgirlrightjump["width"] = animationdata.animationtemplate[5].width;
    dummydimgirlrightjump["width"] = animationdata.animationtemplate[5].width;
    dimgirlrightjump["height"] = animationdata.animationtemplate[5].height;
    dummydimgirlrightjump["height"] = animationdata.animationtemplate[5].height;
    dimgirlrightjump["top"] = animationdata.animationtemplate[5].top;
    dummydimgirlrightjump["top"] = animationdata.animationtemplate[5].top;
    dimgirlrightjump["left"] = leftforgirl;
    dummydimgirlrightjump["left"] = leftforgirl;
    girlright = new sprites(document.getElementById('girlrightjump'), document.getElementById("girlrightjumpsprite"), dimgirlrightjump, dummydimgirlrightjump, animationdata.animationtemplate[5].timeinterval, animationdata.animationtemplate[5].framescount, animationdata.animationtemplate[5].horizontalframes, animationdata.animationtemplate[5].verticalframes);
    girlright.resize(girlright);

    $(".centerpart").append("<div class='girlwrong' id='girlwrong' style='position:absolute; width:" + ((animationdata.animationtemplate[3].width * 100) / centerpartwidth) + ";  height:" + ((animationdata.animationtemplate[3].height * 100) / centerpartwidth) + "%; top:" + ((animationdata.animationtemplate[3].top * 100) / 459) + "%; left:" + (leftforgirl * 100) / centerpartwidth + "% ;z-index:1000;display:none;overflow:hidden'><img src=" + animationdata.animationtemplate[3].images + " id='girlwrongsprite'   style='position:absolute;top:0px;left:0px;'/></div>");
    var dimgirlwrong = {};
    var dummydimgirlwrong = {};
    dimgirlwrong["width"] = animationdata.animationtemplate[3].width;
    dummydimgirlwrong["width"] = animationdata.animationtemplate[3].width;
    dimgirlwrong["height"] = animationdata.animationtemplate[3].height;
    dummydimgirlwrong["height"] = animationdata.animationtemplate[3].height;
    dimgirlwrong["top"] = animationdata.animationtemplate[3].top;
    dummydimgirlwrong["top"] = animationdata.animationtemplate[3].top;
    dimgirlwrong["left"] = leftforgirl;
    dummydimgirlwrong["left"] = leftforgirl;
    girlwrong = new sprites(document.getElementById('girlwrong'), document.getElementById("girlwrongsprite"), dimgirlwrong, dummydimgirlwrong, animationdata.animationtemplate[3].timeinterval, animationdata.animationtemplate[3].framescount, animationdata.animationtemplate[3].horizontalframes, animationdata.animationtemplate[3].verticalframes);
    girlwrong.resize(girlwrong);


    $(".centerpart").append("<div class='girlcorrect' id='girlcorrect' style='position:absolute; width:" + ((animationdata.animationtemplate[1].width * 100) / centerpartwidth) + ";  height:" + ((animationdata.animationtemplate[1].height * 100) / centerpartwidth) + "%; top:" + ((animationdata.animationtemplate[1].top * 100) / 459) + "%; left:" + (leftforgirl * 100) / centerpartwidth + "% ;z-index:1000;display:none;overflow:hidden'><img src=" + animationdata.animationtemplate[1].images + " id='girlcorrectsprite'   style='position:absolute;top:0px;left:0px;'/></div>");
    var dimgirlcorrect = {};
    var dummydimgirlcorrect = {};
    dimgirlcorrect["width"] = animationdata.animationtemplate[1].width;
    dummydimgirlcorrect["width"] = animationdata.animationtemplate[1].width;
    dimgirlcorrect["height"] = animationdata.animationtemplate[1].height;
    dummydimgirlcorrect["height"] = animationdata.animationtemplate[1].height;
    dimgirlcorrect["top"] = animationdata.animationtemplate[1].top;
    dummydimgirlcorrect["top"] = animationdata.animationtemplate[1].top;
    dimgirlcorrect["left"] = leftforgirl;
    dummydimgirlcorrect["left"] = leftforgirl;
    girlcorrect = new sprites(document.getElementById('girlcorrect'), document.getElementById("girlcorrectsprite"), dimgirlwrong, dummydimgirlwrong, animationdata.animationtemplate[1].timeinterval, animationdata.animationtemplate[1].framescount, animationdata.animationtemplate[1].horizontalframes, animationdata.animationtemplate[1].verticalframes);
    girlcorrect.resize(girlcorrect);

    $(".centerpart").append("<div class='girlgameover' id='girlgameover' style='position:absolute; width:" + ((animationdata.animationtemplate[6].width * 100) / centerpartwidth) + ";  height:" + ((animationdata.animationtemplate[6].height * 100) / centerpartwidth) + "%; top:" + ((animationdata.animationtemplate[6].top * 100) / 459) + "%; left:" + (leftforgirl * 100) / centerpartwidth + "% ;z-index:1000;display:none;overflow:hidden'><img src=" + animationdata.animationtemplate[6].images + " id='girlgameoversprite'   style='position:absolute;top:0px;left:0px;'/></div>");
    var dimgirlgameover = {};
    var dummydimgirlgameover = {};
    dimgirlgameover["width"] = animationdata.animationtemplate[6].width;
    dummydimgirlgameover["width"] = animationdata.animationtemplate[6].width;
    dimgirlgameover["height"] = animationdata.animationtemplate[6].height;
    dummydimgirlgameover["height"] = animationdata.animationtemplate[6].height;
    dimgirlgameover["top"] = animationdata.animationtemplate[6].top;
    dummydimgirlgameover["top"] = animationdata.animationtemplate[6].top;
    dimgirlgameover["left"] = leftforgirl;
    dummydimgirlgameover["left"] = leftforgirl;
    girlgameover = new sprites(document.getElementById('girlgameover'), document.getElementById("girlgameoversprite"), dimgirlwrong, dummydimgirlwrong, animationdata.animationtemplate[6].timeinterval, animationdata.animationtemplate[6].framescount, animationdata.animationtemplate[6].horizontalframes, animationdata.animationtemplate[6].verticalframes);
    girlgameover.resize(girlgameover);

    $(".centerpart").append("<div class='girlgameoverloop' id='girlgameoverloop' style='position:absolute; width:" + ((animationdata.animationtemplate[7].width * 100) / centerpartwidth) + ";  height:" + ((animationdata.animationtemplate[7].height * 100) / centerpartwidth) + "%; top:" + ((animationdata.animationtemplate[7].top * 100) / 459) + "%; left:" + (leftforgirl * 100) / centerpartwidth + "% ;z-index:1000;display:none;overflow:hidden'><img src=" + animationdata.animationtemplate[7].images + " id='girlgameoverloopsprite'   style='position:absolute;top:0px;left:0px;'/></div>");
    var dimgirlgameoverloop = {};
    var dummydimgirlgameoverloop = {};
    dimgirlgameoverloop["width"] = animationdata.animationtemplate[7].width;
    dummydimgirlgameoverloop["width"] = animationdata.animationtemplate[7].width;
    dimgirlgameoverloop["height"] = animationdata.animationtemplate[7].height;
    dummydimgirlgameoverloop["height"] = animationdata.animationtemplate[7].height;
    dimgirlgameoverloop["top"] = animationdata.animationtemplate[7].top;
    dummydimgirlgameoverloop["top"] = animationdata.animationtemplate[7].top;
    dimgirlgameoverloop["left"] = leftforgirl;
    dummydimgirlgameoverloop["left"] = leftforgirl;
    girlgameoverloop = new sprites(document.getElementById('girlgameoverloop'), document.getElementById("girlgameoverloopsprite"), dimgirlwrong, dummydimgirlwrong, animationdata.animationtemplate[7].timeinterval, animationdata.animationtemplate[7].framescount, animationdata.animationtemplate[7].horizontalframes, animationdata.animationtemplate[7].verticalframes);
    girlgameoverloop.resize(girlgameoverloop);

    $(".centerpart").append("<div class='girlwalk' id='girlwalk' style='position:absolute; width:" + ((animationdata.animationtemplate[9].width * 100) / centerpartwidth) + ";  height:" + ((animationdata.animationtemplate[9].height * 100) / centerpartwidth) + "%; top:" + ((animationdata.animationtemplate[9].top * 100) / 459) + "%; left:" + (leftforgirl * 100) / centerpartwidth + "% ;z-index:1000;display:none;overflow:hidden'><img src=" + animationdata.animationtemplate[9].images + " id='girlwalksprite'   style='position:absolute;top:0px;left:0px;'/></div>");
    var dimgirlwalk = {};
    var dummydimgirlwalk = {};
    dimgirlwalk["width"] = animationdata.animationtemplate[9].width;
    dummydimgirlwalk["width"] = animationdata.animationtemplate[9].width;
    dimgirlwalk["height"] = animationdata.animationtemplate[9].height;
    dummydimgirlwalk["height"] = animationdata.animationtemplate[9].height;
    dimgirlwalk["top"] = animationdata.animationtemplate[9].top;
    dummydimgirlwalk["top"] = animationdata.animationtemplate[9].top;
    dimgirlwalk["left"] = leftforgirl;
    dummydimgirlwalk["left"] = leftforgirl;
    girlwalk = new sprites(document.getElementById('girlwalk'), document.getElementById("girlwalksprite"), dimgirlwrong, dummydimgirlwrong, animationdata.animationtemplate[9].timeinterval, animationdata.animationtemplate[9].framescount, animationdata.animationtemplate[9].horizontalframes, animationdata.animationtemplate[9].verticalframes);
    girlwalk.resize(girlwalk);
    templatedata.levels[levelelement].level.levelelements = arrayrandamise(templatedata.levels[levelelement].level.levelelements);
    correctAudioSounds = templatedata.settings.positivefeedbackaudio.split(",");
    correctAudioSounds = arrayrandamise(correctAudioSounds);
    wrongAudioSounds = templatedata.settings.negativefeedbackaudio.split(",");
    wrongAudioSounds = arrayrandamise(wrongAudioSounds);



    appendimages();
    backReset();
    fontResize();
    $("#allAudio").css("visibility", "hidden");
}

/*
 *  function to   randamise array 
 */
function arrayrandamise(arraysort) {
    var i = arraysort.length;
    if (i == 0)
        return false;
    while (i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var tempi = arraysort[i];
        var tempj = arraysort[j];
        arraysort[i] = tempj;
        arraysort[j] = tempi;
    }
    return arraysort;
}

/*
 * function past images on the doors  and to dectect game over  
 */
function appendimages()
{
    $("#lowerhead").css("display", "block");
    $("#lowerhead").html(templatedata.levels[levelelement].level.rubric);
    $("#lowerhead").after("<span style=\"float:right; margin-right:10px;position: absolute;right: 0px;bottom: 0px;color:white;font-size:19px;\">" + templatedata.settings.text_noOfQuestions + ": " + templatedata.settings.noOfQuestions + "</span>");
    $(".doorimage").remove();
    $(".audioimage").remove();
    if (questionnumber != (templatedata.settings.noOfQuestions))
    {
        templatedata.levels[levelelement].level.levelelements[questionnumber].group = arrayrandamise(templatedata.levels[levelelement].level.levelelements[questionnumber].group);
        var correctpresent = false;
        var correctposition = 0;
        for (var i = 0; i < templatedata.levels[levelelement].level.numberofdoors; i++)
        {
            if (templatedata.levels[levelelement].level.levelelements[questionnumber].group[i].door.correct == "true")
            {
                correctpresent = true;
                break;
            }
        }
        for (var i = 0; i < templatedata.levels[levelelement].level.levelelements[questionnumber].group.length; i++)
        {
            if (templatedata.levels[levelelement].level.levelelements[questionnumber].group[i].door.correct == "true")
            {
                correctposition = i;
                break;
            }
        }
        optionsarray = templatedata.levels[levelelement].level.levelelements[questionnumber].group;
        pathextension = templatedata.levels[levelelement].level.imgpath;
        if (!correctpresent)
        {
            var rannumber = Math.floor(Math.random() * (templatedata.levels[levelelement].level.numberofdoors - 1));
            var swap = optionsarray[correctposition];
            var swap2 = optionsarray[rannumber];
            optionsarray[rannumber] = swap;
            optionsarray[correctposition] = swap2;
        }
        //optionsarraymain=optionsarray; 


        for (var i = 0; i < templatedata.levels[levelelement].level.numberofdoors; i++)
        {
            var leftofdoor = $("#door" + (i + 1)).position().left;
            var topofdoor = $("#door" + (i + 1)).position().top;

            if (optionsarray[i].door.image != "")
            {
                $("#door" + (i + 1)).append('<img id="testing' + i + '" class="testingimg" src=' + pathextension + optionsarray[i].door.image + ' alt="image" style="width:auto;height:auto;position:absolute">');
                $("#testing" + i).css("visibility", "hidden");
            }

            var ht = 50;
            var wd = 50;
            var fontsize = 15;
            if (($(window).width()) < totalwidthneeded)
            {
                fontsize = Math.floor(18 * ($(window).width() / totalwidthneeded));
                ht = (50) * ($(window).width() / totalwidthneeded);
                wd = (50) * ($(window).width() / totalwidthneeded);
            }
            if (optionsarray[i].door.image == "")
            {
                $(".example").remove();
                $(".centerpart").append("<p class='example'  id='example' correct=" + optionsarray[i].door.correct + " style='position:absolute; height:auto; width:auto; font-family: helvetica, Verdana, sans-serif;font-weight: bold; font-size:" + fontsize + "px; text-align: center ;display:none;z-index:500;cursor:pointer'>" + optionsarray[i].door.text + "</p>");
                wd = $('#example').width();
                ht = $('#example').height();

            }
            var left = (leftofdoor + parseInt(templatedata.centerpart.optionleft)) + ((parseInt(templatedata.centerpart.optionwidth) - wd) / 2);
            var top = (topofdoor + parseInt(templatedata.centerpart.optiontop)) + ((parseInt(templatedata.centerpart.optionheight) - ht) / 2);
            if (($(window).width()) < totalwidthneeded)
            {
                left = (leftofdoor + (parseInt(templatedata.centerpart.optionleft) * ($(window).width() / totalwidthneeded)) + ((parseInt(templatedata.centerpart.optionwidth) * ($(window).width() / totalwidthneeded)) - wd) / 2);
                top = (topofdoor + (parseInt(templatedata.centerpart.optiontop) * ($(window).width() / totalwidthneeded)) + ((parseInt(templatedata.centerpart.optionheight) * ($(window).width() / totalwidthneeded)) - ht) / 2);
            }

            if (templatedata.sound == "yes")
            {
                $(".centerpart").append("<img class='audioimage' audsrc='" + optionsarray[i].door.sound + "' alt='audio' title='audio' id='audioimage" + (i + 1) + "'  src='assets/images/content/audio_N1.png'  style='position:absolute; height:" + (40 * 100) / 459 + "%; cursor:pointer; width:" + (40 * 100) / (centerpartwidth) + "%;z-index:5010;display:block'/>");
                audioleft = leftofdoor + ($("#door" + (i + 1)).width() - ($("#audioimage" + (i + 1)).width())) / 2;
                audiotop = topofdoor - ($("#audioimage" + (i + 1)).height());
            }
            if (templatedata.sound == "yes")
            {
                $("#audioimage" + (i + 1)).css("left", ((audioleft * 100) / ($("#centerpart").width())) + "%");
                $("#audioimage" + (i + 1)).css("top", ((audiotop * 100) / ($("#centerpart").height())) + "%");
            }

            if (optionsarray[i].door.image == "")
            {
                $(".centerpart").append("<div class='doorimage'  id='doorimage" + (i + 1) + "' correct=" + optionsarray[i].door.correct + " style='position:absolute; height:auto; width:auto; font-family: helvetica, Verdana, sans-serif;font-weight: bold; font-size:" + fontsize + "px; text-align: center ;left:" + (left * 100) / $("#centerpart").width() + "%; top:" + (top * 100) / $("#centerpart").height() + "%;z-index:500;cursor:pointer'>" + optionsarray[i].door.text + "</div>");
                $(".doorimage").css("visibility", "hidden");
            }
            else
            {

                $(".centerpart").append("<img class='doorimage'   title=" + optionsarray[i].door.alt + " id='doorimage" + (i + 1) + "'alt=" + optionsarray[i].door.alt + " src=" + pathextension + optionsarray[i].door.image + " correct=" + optionsarray[i].door.correct + " style='position:absolute; height:auto; width:auto;  left:" + (left * 100) / $("#centerpart").width() + "%; top:" + (top * 100) / $("#centerpart").height() + "%;z-index:500;cursor:pointer'/>");
                $(".doorimage").css("visibility", "hidden");
            }
        }
        $(".door").bind(click_or_touch, doorClicked);
		$(".doorimage").bind(click_or_touch, doorImageClicked);
        $(".audioimage").bind(click_or_touch, doorAudioImageClicked);
        questionnumber++;
    }
    else
    {
        girlidle.domelement.style.display = "none";
        document.getElementById("gameover").innerHTML = templatedata.centerpart.gameendtext;
        document.getElementById("girlgameover").style.display = "block";
        document.getElementById("gameover").style.display = "block";
        girlgameover.domelement.style.display = "block";
        document.getElementById("allAudio").style.display = "none";
        var animationarray = new Array();
        animationarray.push(finalloop);
        gameover = true;
        allowplaycontent = false;
        levelelement++;
        if (templatedata.levels.length == levelelement)
        {
            levelelement = 0;
        }
//        if (html5_audio())
//        {
//            if (navigator.userAgent.match(/ipad/i) != null)
//            {
//                optionnumber = 4;
                document.getElementById("correctanimation").src = getAudioExtension(("assets/audio/" + templatedata.settings.reward), ".mp3");
                document.getElementById("correctanimation").load();
                document.getElementById("correctanimation").play();
//            } else
//            {
//                finalapplause.src = getAudioExtension(("assets/audio/" + templatedata.settings.reward), ".mp3");
//                 finalapplause.laod();
//        finalapplause.play();
//            }
//        } else
//        {
//            PlayIESound(getAudioExtension(("assets/audio/" + templatedata.settings.reward), ".mp3"));
//        }
        girlgameover.start(girlgameover, 1, 1, animationarray);
    }


    resetImagesTimer = setTimeout(function () {
        resizeDoorImages();
    }, 1000);

}


function resizeDoorImages()
{

    for (i = 0; i < templatedata.levels[levelelement].level.numberofdoors; i++)
    {

        var leftofdoor = $("#door" + (i + 1)).position().left;
        var topofdoor = $("#door" + (i + 1)).position().top;
		
		if(!gameover){
			
			var tempid = document.getElementById("doorimage" + (i + 1)).getAttribute("id");
			
		}

        if ($("#" + tempid).attr("src") != null)
        {


            var ht = $("#testing" + i).height();
            var wd = $("#testing" + i).width();
            if (($(window).width()) < totalwidthneeded)
            {
                ht = $("#testing" + i).height() * ($(window).width() / totalwidthneeded);
                wd = $("#testing" + i).width() * ($(window).width() / totalwidthneeded);
            }
            var left = (leftofdoor + parseInt(templatedata.centerpart.optionleft)) + ((parseInt(templatedata.centerpart.optionwidth) - wd) / 2);
            var top = (topofdoor + parseInt(templatedata.centerpart.optiontop)) + ((parseInt(templatedata.centerpart.optionheight) - ht) / 2);
            if (($(window).width()) < totalwidthneeded)
            {
                left = (leftofdoor + (parseInt(templatedata.centerpart.optionleft) * ($(window).width() / totalwidthneeded)) + ((parseInt(templatedata.centerpart.optionwidth) * ($(window).width() / totalwidthneeded)) - wd) / 2);
                top = (topofdoor + (parseInt(templatedata.centerpart.optiontop) * ($(window).width() / totalwidthneeded)) + ((parseInt(templatedata.centerpart.optionheight) * ($(window).width() / totalwidthneeded)) - ht) / 2);
            }
            // left:"+(left*100)/$("#centerpart").width()+"%; top:"+(top*100)/$("#centerpart").height()+"%
            $("#" + tempid).css("top", (top * 100) / $("#centerpart").height() + "%");
            $("#" + tempid).css("left", (left * 100) / $("#centerpart").width() + "%");
            $("#" + tempid).css("height", ($("#testing" + i).height() * 100) / (459) + "%");
            $("#" + tempid).css("width", ($("#testing" + i).width() * 100) / centerpartwidth + "%");
            $("#" + tempid).css("visibility", "visible");
            $("#testing" + i).remove();
        }
        else {
            $("#" + tempid).css("visibility", "visible");
        }
    }

}


/*
 * door click callback function 
 */
function doorClicked(e)
{

    var element = document.getElementById($(e.currentTarget).attr("id"));
    var value = document.getElementById("doorimage" + $(e.currentTarget).attr("id").split("door")[1]).getAttribute("correct");
    imagehide = "doorimage" + $(e.currentTarget).attr("id").split("door")[1];
    animate(element, value);
}

/*
 * doorimage click callback function 
 */
function doorImageClicked(e)
{
    var value = document.getElementById($(e.currentTarget).attr("id")).getAttribute("correct");
    var element = document.getElementById("door" + $(e.currentTarget).attr("id").split("doorimage")[1]);
    imagehide = $(e.currentTarget).attr("id");
    animate(element, value);
}
/*
 * suffimage click callback function 
 */
function suffClicked(e)
{
    var value = document.getElementById("doorimage" + $(e.currentTarget).attr("id").split("suffdoor")[1]).getAttribute("correct");
    var element = document.getElementById($(e.currentTarget).attr("id").split("suff")[1]);
    imagehide = "doorimage" + $(e.currentTarget).attr("id").split("suffdoor")[1];
    animate(element, value);
}
/*
 * animate start in this function
 */
function animate(element, value)
{

    if (CollisionAudio != null)
    {
        CollisionAudio.pauseBackToBack();
    }
    else
    {
//        if (html5_audio())
//        {
//            if (navigator.userAgent.match(/ipad/i) != null)
//            {
//                if (!document.getElementById("muitiaudio").paused)
//                {
//                    document.getElementById("muitiaudio").pause();
//                    if (nextaudio != "undefined")
//                        nextaudio = clearTimeout(nextaudio);
//                }
//                audiotoggle = true;
//            } else
//            {
                if (!explanationaudio.paused)
                    explanationaudio.pause();
                audiotoggle = true;
//            }
//        } else
//        {
//            optionnumber = 0;
//            if (nextaudio != "undefined")
//                nextaudio = clearTimeout(nextaudio);
//        }
    }

    allowplaycontent = false;
    resizeflag = false;
    $(".door").unbind(click_or_touch, doorClicked);
    $(".doorimage").unbind(click_or_touch, doorImageClicked);
    $(".suffimage").unbind(click_or_touch, suffClicked);
    $(".audioimage").unbind(click_or_touch, doorAudioImageClicked);
    if (CollisionAudio != null)
    {
        CollisionAudio.play("SFX_correct");
        CollisionAudio.play("SFX_correct");
    }
    else
    {
        var audioed = getAudioExtension("assets/audio/SFX_correct", ".mp3")
        playAnimationaudios(audioed);
    }
    var animations = new Array();
    answer = value;
    animations.push(doorcallback);
    girlidle.stop(girlidle);
    girlidle.domelement.style.display = "none";
    if (parseInt(element.style.left.split("p")[0]) < parseInt(document.getElementById("girlidle").style.left.split("p")[0]))
    {
        if (templatedata.levels[levelelement].level.numberofdoors % 2 != 0)
        {
            if (parseInt(element.getAttribute("id").split("door")[1]) == (Math.floor(templatedata.levels[levelelement].level.numberofdoors / 2) + 1))
            {
                document.getElementById("girlwalk").style.display = "block";
                animationdirection = "center";
                girlwalk.start(girlwalk, 1, 1, animations);
                girlwalk.whichsprite = 0;
                girlwalk.verticalmove(girlwalk, element, 0, 23);
            } else
            {
                girlleft.harizontalmove(girlleft, element, animationdata.animationtemplate[4].harizontalmovement.endframe, animationdata.animationtemplate[4].varticalmovement.endframe);
                document.getElementById("girlleftjump").style.display = "block";
                animationdirection = "left";
                girlleft.start(girlleft, 1, 1, animations);
            }
        } else
        {
            girlleft.harizontalmove(girlleft, element, animationdata.animationtemplate[4].harizontalmovement.endframe, animationdata.animationtemplate[4].varticalmovement.endframe);
            document.getElementById("girlleftjump").style.display = "block";
            animationdirection = "left";
            girlleft.start(girlleft, 1, 1, animations);
        }
    } else
    {
        if (templatedata.levels[levelelement].level.numberofdoors % 2 != 0)
        {
            if (parseInt(element.getAttribute("id").split("door")[1]) == (Math.floor(templatedata.levels[levelelement].level.numberofdoors / 2) + 1))
            {
                document.getElementById("girlwalk").style.display = "block";
                animationdirection = "center";
                girlwalk.start(girlwalk, 1, 1, animations);
                girlwalk.whichsprite = 0;
                girlwalk.verticalmove(girlwalk, element, 23);
            } else
            {
                girlright.harizontalmove(girlright, element, animationdata.animationtemplate[5].harizontalmovement.endframe, animationdata.animationtemplate[5].varticalmovement.endframe);
                document.getElementById("girlrightjump").style.display = "block";
                animationdirection = "right";
                girlright.start(girlright, 1, 1, animations);
            }
        } else
        {
            girlright.harizontalmove(girlright, element, animationdata.animationtemplate[5].harizontalmovement.endframe, animationdata.animationtemplate[5].varticalmovement.endframe);
            document.getElementById("girlrightjump").style.display = "block";
            animationdirection = "right";
            girlright.start(girlright, 1, 1, animations);
        }
    }
}

/*
 * call back function after leftjump and rightjump animation completes
 */

function doorcallback()
{
    var animations1 = new Array();
    if (answer == "true")
    {
        $("#" + imagehide).css("display", "none");
        animations1.push(girlcorrectcallback);
        doorsprite[parseInt(imagehide.split("doorimage")[1])].numberofsprites = 31;
        doorsprite[parseInt(imagehide.split("doorimage")[1])].start(doorsprite[parseInt(imagehide.split("doorimage")[1])], 1, 1, animations1);
    } else
    {
        if (animationdirection == "left")
        {
            girlleft.domelement.style.display = "none";
            girlwrong.domelement.style.left = (parseInt(girlleft.domelement.style.left.split("p")[0])) + "px";
            girlwrong.domelement.style.top = girlleft.domelement.style.top;
        } else if (animationdirection == "right")
        {
            girlright.domelement.style.display = "none";
            girlwrong.domelement.style.left = (parseInt(girlright.domelement.style.left.split("p")[0])) + "px";
            girlwrong.domelement.style.top = girlright.domelement.style.top;
        } else
        {
            girlwalk.domelement.style.display = "none";
            girlwrong.domelement.style.left = (parseInt(girlwalk.domelement.style.left.split("p")[0])) + "px";
            girlwrong.domelement.style.top = girlwalk.domelement.style.top;
        }
        girlwrong.domelement.style.display = "block";
        var checkvar = document.getElementById("suff" + doorsprite[parseInt(imagehide.split("doorimage")[1])].domelement.getAttribute("id"))
        if (checkvar == null) {
            $(".centerpart").append("<img class='suffimage' id='suff" + doorsprite[parseInt(imagehide.split("doorimage")[1])].domelement.getAttribute("id") + "' src=" + templatedata.centerpart.suffimage + " style='position:absolute; width:" + (((parseInt(templatedata.centerpart.suffwidth) - 10) * 100) / centerpartwidth) + "% ; height:" + (((parseInt(templatedata.centerpart.suffheight) - 10) * 100) / 459) + "%; left:" + (((parseInt(doorsprite[parseInt(imagehide.split("doorimage")[1])].object.left) + parseInt(templatedata.centerpart.suffleft)) * 100) / centerpartwidth) + "%; top:" + (((parseInt(doorsprite[parseInt(imagehide.split("doorimage")[1])].object.top) + parseInt(templatedata.centerpart.sufftop)) * 100) / 459) + "%;z-index:500;cursor: pointer;cursor: hand;'/>");
        }
        animations1.push(oneMoreTry);
        // if(html5_audio())
        // {
        // CollisionAudio.play([wrongAudioSounds[Math.floor(Math.random()*(wrongAudioSounds.length))]]);
//         
        // }else{
        if (CollisionAudio != null)
        {
            CollisionAudio.play(wrongAudioSounds[Math.floor(Math.random() * (wrongAudioSounds.length))]);
        }
        else
        {
            var audioed = getAudioExtension("assets/audio/" + wrongAudioSounds[Math.floor(Math.random() * (wrongAudioSounds.length))], ".mp3");
            playAnimationaudios(audioed);
        }
        //}

        girlwrong.start(girlwrong, 1, 1, animations1);
    }


}

/*
 * call back function   correct door click
 */
function girlcorrectcallback()
{
    var animations2 = new Array();
    // if(html5_audio())
    // {
    // CollisionAudio.play([correctAudioSounds[questionnumber]]);
//         
    // }else{

    var audioed = getAudioExtension("assets/audio/" + correctAudioSounds[questionnumber], ".mp3")
    playAnimationaudios(audioed);

    //         }
    animations2.push(doorClose);
    if (animationdirection == "left")
    {
        girlleft.domelement.style.display = "none";
        girlcorrect.domelement.style.left = (parseInt(girlleft.domelement.style.left.split("p")[0])) + "px";
        girlcorrect.domelement.style.top = girlleft.domelement.style.top;
    } else if (animationdirection == "right")
    {
        girlright.domelement.style.display = "none";
        girlcorrect.domelement.style.left = (parseInt(girlright.domelement.style.left.split("p")[0])) + "px";
        girlcorrect.domelement.style.top = girlright.domelement.style.top;
    } else
    {
        girlwalk.domelement.style.display = "none";
        girlcorrect.domelement.style.left = (parseInt(girlwalk.domelement.style.left.split("p")[0])) + "px";
        girlcorrect.domelement.style.top = girlwalk.domelement.style.top;
    }
    girlcorrect.domelement.style.display = "block";
    girlcorrect.start(girlcorrect, 1, 1, animations2);
}
/*
 * call back function for closing the door
 */
function doorClose()
{
    var animations3 = new Array();
    // if(html5_audio())
    // {
    // CollisionAudio.play(["doorbuster_footsteps_off"]);
//         
    // }else{
    var audied = getAudioExtension("assets/audio/doorbuster_footsteps_off", ".mp3");
    playAnimationaudios(audied);
    //   }
    animations3.push(reload);
    girlcorrect.domelement.style.display = "none";
    doorsprite[parseInt(imagehide.split("doorimage")[1])].numberofsprites = 61;
    doorsprite[parseInt(imagehide.split("doorimage")[1])].start(doorsprite[parseInt(imagehide.split("doorimage")[1])], 1, 31, animations3);
}
/*
 * resetting all images and removing suffimage after correct animation complete
 */
function reload()
{
    resetAllImages();
    $(".suffimage").remove();
    appendimages();
    $(".audioimage").bind(click_or_touch, doorAudioImageClicked);
}

/*
 * function called after the wrong option is choosen
 */
function oneMoreTry()
{
    girlwrong.domelement.style.display = "none";
    resetAllImages()
    $(".door").bind(click_or_touch, doorClicked);
    $(".doorimage").bind(click_or_touch, doorImageClicked);
    $(".audioimage").bind(click_or_touch, doorAudioImageClicked);
}

/*
 * resetting all images to original position
 */
function resetAllImages()
{
    resizeflag = true;
    if (resizeattempt)
    {
        //window.resizeTo($(window).width(),$(window).height());
        resizeLayout();
        resizeattempt = false;
    }
    allowplaycontent = true;
    girlleft.reset(girlleft);
    girlright.reset(girlright);
    girlwrong.reset(girlwrong);
    girlcorrect.reset(girlcorrect);
    girlidle.reset(girlidle);
    girlwalk.reset(girlwalk);
    doorsprite[parseInt(imagehide.split("doorimage")[1])].reset(doorsprite[parseInt(imagehide.split("doorimage")[1])]);
    $(".suffimage").bind(click_or_touch, suffClicked);
    girlcorrect.domelement.style.left = girlcorrect.dummyobject.left + "px";
    girlcorrect.domelement.style.top = girlcorrect.dummyobject.top + "px";
    girlleft.domelement.style.left = girlleft.dummyobject.left + "px";
    girlleft.domelement.style.top = girlleft.dummyobject.top + "px";
    girlright.domelement.style.left = girlright.dummyobject.left + "px";
    girlright.domelement.style.top = girlright.dummyobject.top + "px";
    girlwrong.domelement.style.left = girlwrong.dummyobject.left + "px";
    girlwrong.domelement.style.top = girlwrong.dummyobject.top + "px";
    girlcorrect.domelement.style.left = girlcorrect.dummyobject.left + "px";
    girlcorrect.domelement.style.top = girlcorrect.dummyobject.top + "px";
    girlwalk.domelement.style.left = girlwalk.dummyobject.left + "px";
    girlwalk.domelement.style.top = girlwalk.dummyobject.top + "px";
    girlidle.domelement.style.display = "block";
    girlidle.start(girlidle, 0, 1);

}


/*
 * call back function for audio icon click
 */


function playContentAudios()
{

    var dummyarray = [];
//alert(templatedata.levels[levelelement].level.numberofdoors)	;
    for (i = 0; i < optionsarray.length; i++)
    {
        if (optionsarray[i].door.sound != "" && i < templatedata.levels[levelelement].level.numberofdoors)
        {
            dummyarray[i] = optionsarray[i].door.sound;
        }
    }


    if (allowplaycontent)
    {

        if (CollisionAudio != null)
        {
            CollisionAudio.playBackToBack(dummyarray);
        }
        else
        {
//            if (html5_audio())
//            {
                if (navigator.userAgent.match(/ipad/i) != null)
                {
                    if (audiotoggle)
                    {
                        if (!document.getElementById("muitiaudio").paused)
                            document.getElementById("muitiaudio").pause();
                        optionnumber = 0;
                        document.getElementById("muitiaudio").src = "assets/audio/" + getAudioExtension(optionsarray[0].door.sound, ".mp3");
                        document.getElementById("muitiaudio").load();
                        document.getElementById("muitiaudio").play();
                        // nextaudio=setInterval(sequentialAudios,1000);
                    } else
                    {
                        if (!document.getElementById("muitiaudio").paused)
                            document.getElementById("muitiaudio").pause();
                        if (nextaudio != "undefined")
                            nextaudio = clearTimeout(nextaudio);
                        optionnumber = 0;
                    }
                    audiotoggle = !audiotoggle;
                } else
                {
                    if (audiotoggle)
                    {
                        optionnumber = 0;
                        explanationaudio.src = "assets/audio/" + getAudioExtension(optionsarray[0].door.sound, ".mp3");
                        
                            explanationaudio.load();
                      
                        explanationaudio.play();
                    } else
                    {
                        explanationaudio.pause();
                        optionnumber = 0;
                    }
                    audiotoggle = !audiotoggle;
                }
//            } else
//            {
//                if (nextaudio != "undefined")
//                {
//                    PlayIESound("assets/audio/" + getAudioExtension(optionsarray[0].door.sound, ".mp3"));
//                    nextaudio = setInterval(ieaudioplayer, 1500);
//                } else
//                {
//                    optionnumber = 0;
//                    nextaudio = clearInterval(nextaudio);
//                }
//            }
        }
    }
}

/*
 * function to play ie8 audios of door images
 */

function ieaudioplayer()
{
    optionnumber++;
    PlayIESound("assets/audio/" + getAudioExtension(optionsarray[optionnumber].door.sound, ".mp3"));
    if (optionnumber == (templatedata.levels[levelelement].level.numberofdoors - 1))
    {
        optionnumber = 0;
        nextaudio = clearInterval(nextaudio);
    }
}
/*
 * function to play  audios of door images  for ipad
 */

function sequentialAudios()
{
    optionnumber++;
    if (optionnumber != (templatedata.levels[levelelement].level.numberofdoors))
    {
        if (!document.getElementById("muitiaudio").paused)
            document.getElementById("muitiaudio").pause();
        document.getElementById("muitiaudio").src = "assets/audio/" + getAudioExtension(optionsarray[optionnumber].door.sound, ".mp3");
        document.getElementById("muitiaudio").load();
        document.getElementById("muitiaudio").play();

    } else
    {
        if (!document.getElementById("muitiaudio").paused)
            document.getElementById("muitiaudio").pause();
        nextaudio = clearTimeout(nextaudio);
        audiotoggle = true;
        optionnumber = 0;
    }

}
/*
 * call back function for play again button
 */
function resetActivity(e)
{

    if (resetImagesTimer)
        clearTimeout(resetImagesTimer);

    if (allowplaycontent || gameover)
    {
        if (CollisionAudio != null)
        {
            CollisionAudio.pause();
        }

//
//        if (html5_audio())
//        {
            if (!(document.getElementById("muitiaudio").paused))
            {
                document.getElementById("muitiaudio").pause();
            }
//            if (navigator.userAgent.match(/ipad/i) == null)
//            {
                if (!(finalapplause.paused))
                {
                    finalapplause.pause();
                }
                if (!(explanationaudio.paused))
                {
                    explanationaudio.pause();
                }
//            }
//        }
//        if (!html5_audio())
//        {
//            PlayIESound("");
//        }
//        if (navigator.userAgent.match(/ipad/i) != null)
//        {
//            document.getElementById("muitiaudio").removeEventListener('canplaythrough', canPlayThrough, false);
//        }
        if (nextaudio != "undefined")
            nextaudio = clearTimeout(nextaudio);



        document.getElementById("gameover").style.display = "none";
        girlgameoverloop.stop(girlgameoverloop);
        girlgameoverloop.domelement.style.display = "block";
        document.getElementById("container").innerHTML = "";
        girlgameover = 0;
        girlidle = 0;
        girlleft = 0;
        girlright = 0;
        girlwrong = 0;
        girlwalk = 0;
        gameover = false;
        girlcorrect = "";
        for (var i = 0; i < doorsprite.length; i++)
        {
            doorsprite.pop();
        }
        animationdirection = "";
        answer = "";
        questionnumber = 0;
        screenWid = "";
//        if (navigator.userAgent.match(/ipad/i) == null)
//        {
            finalapplause = ""
            explanationaudio = 0
//        }
        animationsoundArray.length = 0;
        audiotoggle = true;
        optionnumber = 0;
        allowplaycontent = true;
        $(".door").css("cursor", "pointer");
        $(".audiobutton").css("cursor", "pointer");
        renderScreen();
    }
}
/*
 * event handler for canplaythrough even
 */
/*function canPlayThrough()
 {
 document.getElementById("muitiaudio").play();
 var duriation;
 if(isNaN(document.getElementById("muitiaudio").duration))
 {
 duriation=2;
 }else
 {
 duriation=document.getElementById("muitiaudio").duration;
 }
 nextaudio=setTimeout(sequentialAudios,(duriation)*1000);
 }*/

function finalloop()
{
    girlgameover.domelement.style.display = "none";
    girlgameoverloop.domelement.style.display = "block";
    //$(".gameover").corner("cc:#FEFE46 10px");
    $(".door").css("cursor", "default");
    $(".audiobutton").css("cursor", "default");
    girlgameoverloop.start(girlgameoverloop, 0, 1);
}

/*audio image clicked called function*/

function doorAudioImageClicked(e)
{

    var audiosrc = document.getElementById($(e.currentTarget).attr("id")).getAttribute("audsrc");
    //alert(audiosrc);

    if (CollisionAudio != null)
    {

        CollisionAudio.play(audiosrc);
    }
    else
    {
//        if (html5_audio())
//        {
//            if (navigator.userAgent.match(/ipad/i) != null)
//            {
//                if (!document.getElementById("muitiaudio").paused)
//                {
//                    document.getElementById("muitiaudio").pause();
//                    if (nextaudio != "undefined")
//                        nextaudio = clearTimeout(nextaudio);
//                }
//                audiotoggle = true;
//            } else
//            {
                if (!document.getElementById("muitiaudio").paused)
                {
                    document.getElementById("muitiaudio").pause();
                    if (nextaudio != "undefined")
                        nextaudio = clearTimeout(nextaudio);
                }
                if (!explanationaudio.paused)
                    explanationaudio.pause();
                audiotoggle = true;
//            }
//        } else
//        {
//            optionnumber = 0;
//            if (nextaudio != "undefined")
//                nextaudio = clearTimeout(nextaudio);
//        }
        var audiosrc = document.getElementById($(e.currentTarget).attr("id")).getAttribute("audsrc");
//        if (html5_audio())
//        {
            if (!document.getElementById("correct").paused)
                document.getElementById("correct").pause();
            $("#correct").attr("src", getAudioExtension("assets/audio/" + audiosrc, ".mp3"));
            var ua = navigator.userAgent.toLowerCase();
            //var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");

                document.getElementById("correct").load();
            
            document.getElementById("correct").play();
//        }
//        else
//        {
//            PlayIESound(getAudioExtension("assets/audio/" + audiosrc, ".mp3"));
//        }
    }


}


function audiobuttonmousein()
{
    document.getElementById("allAudio").src = "assets/images/content/audio_O.png";
}
function audiobuttonmouseout()
{
    document.getElementById("allAudio").src = "assets/images/content/audio_N.png";
}
function audiobuttonmousedown()
{
    document.getElementById("allAudio").src = "assets/images/content/audio_D.png";
}
