
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 = new Array();  //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 kind_of_screen;       //variable to specify screen kind
var wrongAudioSounds;
var optionsarray = new Array();
var levelelement = 0;
var girlwalk;
var CollisionAudio = null;
var imageTimer;
var dimenobject = {};
countertestimg = 0;
counterblockimg = 0;
var footerextbut = "assets/images/bg/";


var opts = {
    lines: 15, // The number of lines to draw
    length: 16, // The length of each line
    width: 4, // The line thickness
    radius: 10, // The radius of the inner circle
    corners: 0.8, // Corner roundness (0..1)
    rotate: 23, // The rotation offset
    color: '#000', // #rgb or #rrggbb
    speed: 1.1, // Rounds per second
    trail: 60, // Afterglow percentage
    shadow: false, // Whether to render a shadow
    hwaccel: false, // Whether to use hardware acceleration
    className: 'spinner', // The CSS class to assign to the spinner
    zIndex: 2e9, // The z-index (defaults to 2000000000)
    top: 'auto', // Top position relative to parent in px
    left: 'auto' // Left position relative to parent in px
};
var spinner = null;


function textAlign(id, number, kind_of_screen)
{
    var transform = 0;
    if (navigator.userAgent.match(/ipad/i) != null)
    {
        if (kind_of_screen != "onlycenterwithsmalldim")
        {
            var transform = number * 47;
            $("#" + id).css("-webkit-transform", "translateX(" + transform + "px)");
        } else
        {
            transform = number * 42;
            $("#" + id).css("-webkit-transform", "translateX(" + transform + "px)");
        }
    }

    if (navigator.userAgent.match(/Android/i) != null)
    {
        if (window.orientation % 180 != 0)
        {
            if (screen.availWidth == 600 && screen.availHeight == 1024)
            {
                if (templatedata.levels[levelelement].level.numberofdoors == 5)
                {

                    var transform = number * 120;
                    $("#" + id).css("-webkit-transform", "translateX(" + transform + "px)");
                }
                if (templatedata.levels[levelelement].level.numberofdoors <= 4)
                {
                    transform = number * 72;
                    $("#" + id).css("-webkit-transform", "translateX(" + transform + "px)");
                }
                else
                {

                    transform = number * 68;
                    $("#" + id).css("-webkit-transform", "translateX(" + transform + "px)");
                }


            }
            else {
                transform = number * 53;
                $("#" + id).css("-webkit-transform", "translateX(" + transform + "px)");
            }
        }
        else {
            if (screen.availWidth == 1024 && screen.availHeight == 600)
            {
                if (templatedata.levels[levelelement].level.numberofdoors == 5)
                {
                    var transform = number * 65;
                    $("#" + id).css("-webkit-transform", "translateX(" + transform + "px)");
                }
                if (templatedata.levels[levelelement].level.numberofdoors <= 4)
                {
                    var transform = number * 48;
                    $("#" + id).css("-webkit-transform", "translateX(" + transform + "px)");
                }
                else
                {
                    var transform = number * 42;
                    $("#" + id).css("-webkit-transform", "translateX(" + transform + "px)");
                }
            }
        }
    }
}


/*
 * sprite animation with changing the background position of element, class for sprite animation
 */

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 (BrowserDetect.browser == "Firefox")
                    {
                        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 (BrowserDetect.browser == "Firefox")
                    {
                        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 (BrowserDetect.browser == "Firefox")
        {
            element.domelement.style.backgroundPosition = "0px 0px";
        } else
        {
            element.domelement.style.backgroundPositionX = "0px";
            element.domelement.style.backgroundPositionY = "0px";
        }
    },
    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.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);

        element.shift = (element.shift) / (element.whichsprite);

        element.moveinterval = setInterval(
                function () {
                    element.movement = parseInt(element.domelement.style.left.split("p")[0]);
                    element.domelement.style.left = (element.movement - element.shift) + "px";

                    if (element.shift > 0)
                    {
                        if (parseInt(element.domelement.style.left.split("p")[0]) <=
                                (parseInt(targetelement.style.left.split("p")[0]) + (parseInt(targetelement.style.width.split("p")[0]) - parseInt(element.domelement.style.width.split("p")[0])) / 2))
                        {
                            element.moveinterval = clearInterval(element.moveinterval);
                            element.verticalmove(element, targetelement, verticalendsprite);
                        }
                    } else
                    {
                        if (parseInt(element.domelement.style.left.split("p")[0]) >=
                                (parseInt(targetelement.style.left.split("p")[0]) + (parseInt(targetelement.style.width.split("p")[0]) - parseInt(element.domelement.style.width.split("p")[0])) / 2))
                        {
                            element.moveinterval = clearInterval(element.moveinterval);
                            element.verticalmove(element, targetelement, verticalendsprite);
                        }
                    }
                }, Math.floor(element.timeslice / element.numberofsprites)
                );
    },
    verticalmove: function (element, targetelement, verticalendsprite) {
        element.whichsprite = parseInt(verticalendsprite - element.whichsprite);
        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 - 30) / (element.whichsprite);

        element.moveinterval = setInterval(
                function () {
                    element.movement = parseInt(element.domelement.style.top.split("p")[0]);
                    element.domelement.style.top = (element.movement - element.shift) + "px";


                    if ((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.moveinterval = clearInterval(element.moveinterval);
                    }

                }, Math.floor(element.timeslice / element.numberofsprites)
                );
    }

};

function loadEnded() {
    $("#toplayer").css("display", "none");
    if (spinner != null)
        spinner.stop();
// alert(event);
}

window.onload = function ()
{
    loadEnded();

    if (navigator.userAgent.match(/Android|Android 3.2|Android 3.1|Android 3.0/) != null)
    {
        loaderindicator = 1;
    }

}

function commonOrientation()
{
    if (spinner != null)
    {
        switch (window.orientation)
        {
            case -90:
            case 90:
                {
                    if (spinner.el != null)
                    {

                        $(spinner.el).css({left: 500, top: 325});
                    }
                }
                break;
            default:
                {
                    if (spinner.el != null)
                    {
                        window.scrollTo(0, 0);
                        $(spinner.el).css({left: 550, top: 700});
                    }
                }
                break;
        }
    }
}


window.addEventListener("orientationchange", function () {
    commonOrientation();
}, false);


$(document).ready(function () {


// if(navigator.userAgent.match(/ipad/i)!= null)
// {
// $("#toplayer").css("display","block"); 
// spinner = new Spinner(opts).spin(document.getElementById("toplayer"));
    // commonOrientation();
// }

    // if(navigator.userAgent.match(/ipad/i)!= null){
    // $(document).bind("touchstart",function(event){
//    
    // var audioed=getAudioExtension("assets/audio/applause_clapping_w_cheers",".mp3")
    // playAnimationaudios(audioed);
//    
    // $(document).unbind("touchstart");
//    
    // });
    // }

    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", resetActivity);

    $("#reset").bind("touchstart", function () {
        document.getElementById("reset").getElementsByTagName('img')[0].src = footerextbut + templatedata.ResetButHover;
    });
    $("#reset").bind("touchend", function () {
        document.getElementById("reset").getElementsByTagName('img')[0].src = footerextbut + templatedata.ResetButNormal;
    });
    $("#menuButton").bind("touchstart", function () {
        document.getElementById("menuButton").getElementsByTagName('img')[0].src = footerextbut + templatedata.MenuButHover;
    });
    $("#menuButton").bind("touchend", function () {
        document.getElementById("menuButton").getElementsByTagName('img')[0].src = footerextbut + templatedata.MenuButNormal;
    });

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

    // $("#menuButton").hover(function(){
    // 
    // },function(){
    // 
    // });
    $("#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;   
//          
    // },
    // 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()
{
   

    if (navigator.userAgent.match(/ipad/i) == null)
    {
        explanationaudio = createAudio(getAudioExtension("assets/audio/super1", ".mp3"));
        finalapplause = createAudio(getAudioExtension("assets/audio/super1", ".mp3"));
    }
    // creating audio objects with source
    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.play();
                } else
                {
                    audiotoggle = true;
                    optionnumber = 0;
                }
            }, false);
        }
    }
    /*calculating requried screen width*/
    if (navigator.userAgent.match(/Android/i) != null)
    {
        if (window.orientation == 90 || window.orientation == -90)
            screenWid = screen.availHeight;
        else
            screenWid = screen.availWidth;
    } else
    {
        if (navigator.userAgent.match(/ipad/i) != null)
        {
            screenWid = screen.availHeight;
        } else
        {
            screenWid = screen.availWidth;
        }
    }

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

    //placing all image of button

    $("#reset1").attr("src", footerextbut + templatedata.ResetButNormal);
    $("#menuButton1").attr("src", footerextbut + templatedata.MenuButNormal);

    /*if the requried screen width is greater then the avaliable screen width  removing leftpart and right part*/
    if (screenWid < totalwidthneeded)
    {
        /*calculating requried screen width with centerpart only*/
        totalwidthneeded = ((templatedata.levels[levelelement].level.numberofdoors) * (parseInt(templatedata.centerpart.doorwidth) +
                parseInt(templatedata.centerpart.spacebetweendoors) + 1));
        /*if the requried screen width is even greater then the avaliable screen width  then load small size images*/


        if (screenWid < totalwidthneeded)
        {
            totalwidthneeded = ((templatedata.levels[levelelement].level.numberofdoors) * (parseInt(templatedata.centerpart.smallscreen.doorwidth) +
                    parseInt(templatedata.centerpart.spacebetweendoors) + 1))
            constructScreen("onlycenterwithsmalldim", totalwidthneeded);  /*calling function with only center part and small size image dimentions*/
        } else
        {
            constructScreen("onlycenter", totalwidthneeded);  /*calling function only with centerpart*/
        }
    } else
    {
        constructScreen("allparts", totalwidthneeded);   /*calling function with three parts included*/
    }
}


function constructScreen(kindofscreen, totalWidth)
{
    /*applying  css to the container so that it is kept in the center*/
    kind_of_screen = kindofscreen;

    $(".container").css({
        "left": ((screenWid - totalWidth) / 2) + "px",
        "width": totalWidth + "px",
        "top": "90px",
        "height": templatedata.templateheight,
        "background-image": "url(" + templatedata.bgimage + ")",
        "background-repeat": "repeat"
    });
    $(".heading").css({
        "left": ((screenWid - totalWidth) / 2) + "px",
        "width": totalWidth + "px",
        "top": "20px",
        "height": templatedata.centerpart.headingheight,
        "background-repeat": "repeat"

    });
    $(".footer").css({
        "left": ((screenWid - totalWidth) / 2) + "px",
        "width": totalWidth + "px",
        "top": "549px",
        "height": templatedata.centerpart.footerheight

    });
    $("#reset").css({
        "width": "149px",
        "height": "40px"


    });
    $("#menuButton").css({
        "width": "99px",
        "height": "40px"


    });

    var doorwidth;
    /*calculating doorwidth depends on the screen kind*/
    if (kindofscreen != "onlycenterwithsmalldim")
    {
        doorwidth = parseInt(templatedata.centerpart.doorwidth);
    } else
    {
        doorwidth = parseInt(templatedata.centerpart.smallscreen.doorwidth);
    }

    if (kindofscreen == "allparts")
    {
        /*creating leftpart rightpart and centerpart*/
        $(".container").append("<div class='leftpart' style=' position:absolute; left:0px;top:0px; width:" + templatedata.leftpart.width + "px;  height:" + templatedata.leftpart.height + "px; background:url(" + templatedata.leftpart.image + ");background-repeat: no-repeat'></div>");
        $(".container").append("<div class='rightpart' style=' position:absolute; left:" + (totalWidth - parseInt(templatedata.rightpart.width)) + "px;top:0px; width:" + templatedata.rightpart.width + "px;  height:" + templatedata.rightpart.height + "px; background:url(" + templatedata.rightpart.image + ");background-repeat: no-repeat'></div>");
        $(".container").append("<div class='centerpart' id='centerpart' style=' position:absolute; left:" + templatedata.leftpart.width + "px;top:0px; width:" + (((parseInt(templatedata.centerpart.doorwidth) + parseInt(templatedata.centerpart.spacebetweendoors) + 1) * (parseInt(templatedata.levels[levelelement].level.numberofdoors)))) + "px;  height:" + templatedata.centerpart.height + "px ; background:url(assets/images/bg/bd3.jpg);background-repeat: no-repeat'></div>");
    } else
    {
        /*creating centerpart for small screen*/
        $(".container").append("<div class='centerpart' id='centerpart' style=' position:absolute; left:0px;top:0px; width:" + (((parseInt(templatedata.centerpart.doorwidth) + parseInt(templatedata.centerpart.spacebetweendoors) + 1) * (parseInt(templatedata.levels[levelelement].level.numberofdoors)))) + "px;  height:" + templatedata.centerpart.height + "px background:url(assets/images/bg/bd3.jpg);background-repeat: no-repeat'></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'/>");
    if (kindofscreen == "onlycenterwithsmalldim")
    {

        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.smallscreen.doorwidth + "px;  height:" + templatedata.centerpart.smallscreen.doorheight + "px; top:" + templatedata.centerpart.smallscreen.doortop + "px; left:" + ((parseInt(templatedata.centerpart.spacebetweendoors) * i) + (parseInt(templatedata.centerpart.smallscreen.doorwidth) * (i - 1))) + "px ;  background:url(" + templatedata.centerpart.smallscreen.doorimage + "); background-position-x:0px;background-position-y:0px;background-position:0px 0px;background-repeat: no-repeat;cursor: pointer;cursor: hand;'></div>");
        }
    }
    else
    {
        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 + "px;  height:" + templatedata.centerpart.doorheight + "px; top:" + templatedata.centerpart.doortop + "px; left:" + ((parseInt(templatedata.centerpart.spacebetweendoors) * i) + (parseInt(templatedata.centerpart.doorwidth) * (i - 1))) + "px ;  background:url(" + templatedata.centerpart.doorimage + "); background-position-x:0px;background-position-y:0px;background-position:0px 0px;background-repeat: no-repeat;cursor: pointer;cursor: hand;'></div>");
        }
    }
    /*creating girl idle*/

    var leftforgirl = parseInt(document.getElementById("centerpart").style.width);

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

    $(".centerpart").append("<div class='girlidle' id='girlidle' style='position:absolute; width:" + animationdata.animationtemplate[2].width + "px;  height:" + animationdata.animationtemplate[2].height + "px; top:" + animationdata.animationtemplate[2].top + "px; left:" + leftforgirl + "px ;  background:url(" + animationdata.animationtemplate[2].images + ");z-index:1000;display:block;background-position-x:0px;background-position-y:0px;background-position:0px 0px;background-repeat: no-repeat'></div>");
    var girlidleimage = document.getElementById("girlidle");
    girlidle = new sprites(girlidleimage, animationdata.animationtemplate[2].timeinterval, animationdata.animationtemplate[2].framescount, animationdata.animationtemplate[2].horizontalframes, animationdata.animationtemplate[2].verticalframes);
    girlidle.start(girlidle, 0);

    $(".centerpart").append("<div class='girlleftjump' id='girlleftjump' style='position:absolute; width:" + animationdata.animationtemplate[4].width + "px;  height:" + animationdata.animationtemplate[4].height + "px; top:" + animationdata.animationtemplate[4].top + "px; left:" + leftforgirl + "px ;  background:url(" + animationdata.animationtemplate[4].images + ");z-index:1000;display:none;background-position-x:0px;background-position-y:0px;background-position:0px 0px;background-repeat: no-repeat'></div>");
    girlleftimage = document.getElementById("girlleftjump");
    girlleft = new sprites(girlleftimage, animationdata.animationtemplate[4].timeinterval, animationdata.animationtemplate[4].framescount, animationdata.animationtemplate[4].horizontalframes, animationdata.animationtemplate[4].verticalframes);
    $(".centerpart").append("<div class='girlrightjump' id='girlrightjump' style='position:absolute; width:" + animationdata.animationtemplate[5].width + "px;  height:" + animationdata.animationtemplate[5].height + "px; top:" + animationdata.animationtemplate[5].top + "px; left:" + leftforgirl + "px ;  background:url(" + animationdata.animationtemplate[5].images + ");z-index:1000;display:none;background-position-x:0px;background-position-y:0px;background-position:0px 0px;background-repeat: no-repeat'></div>");
    var girlrightimage = document.getElementById("girlrightjump");

    girlright = new sprites(girlrightimage, animationdata.animationtemplate[5].timeinterval, animationdata.animationtemplate[5].framescount, animationdata.animationtemplate[5].horizontalframes, animationdata.animationtemplate[5].verticalframes);

    $(".centerpart").append("<div class='girlwrong' id='girlwrong' style='position:absolute; width:" + animationdata.animationtemplate[3].width + "px;  height:" + animationdata.animationtemplate[3].height + "px; top:" + animationdata.animationtemplate[3].top + "px; left:" + leftforgirl + "px ;  background:url(" + animationdata.animationtemplate[3].images + ");z-index:1000;display:none;background-position-x:0px;background-position-y:0px;background-position:0px 0px;background-repeat: no-repeat'></div>");
    var girlwrongimage = document.getElementById("girlwrong");

    girlwrong = new sprites(girlwrongimage, animationdata.animationtemplate[3].timeinterval, animationdata.animationtemplate[3].framescount, animationdata.animationtemplate[3].horizontalframes, animationdata.animationtemplate[3].verticalframes);

    $(".centerpart").append("<div class='girlcorrect' id='girlcorrect' style='position:absolute; width:" + animationdata.animationtemplate[1].width + "px;  height:" + animationdata.animationtemplate[1].height + "px; top:" + animationdata.animationtemplate[1].top + "px; left:" + leftforgirl + "px ;  background:url(" + animationdata.animationtemplate[1].images + ");z-index:1000;display:none;background-position-x:0px;background-position-y:0px;background-position:0px 0px;background-repeat: no-repeat'></div>");
    var girlcorrectimage = document.getElementById("girlcorrect");

    girlcorrect = new sprites(girlcorrectimage, animationdata.animationtemplate[1].timeinterval, animationdata.animationtemplate[1].framescount, animationdata.animationtemplate[1].horizontalframes, animationdata.animationtemplate[1].verticalframes);


    $(".centerpart").append("<div class='girlgameover' id='girlgameover' style='position:absolute; width:" + animationdata.animationtemplate[6].width + "px;  height:" + animationdata.animationtemplate[6].height + "px; top:" + animationdata.animationtemplate[6].top + "px; left:" + leftforgirl + "px ;  background:url(" + animationdata.animationtemplate[6].images + ");display:none;z-index:1000;display:none;background-position-x:0px;background-position-y:0px;background-position:0px 0px;background-repeat: no-repeat'></div>");
    var girlgameoverimage = document.getElementById("girlgameover");
    girlgameover = new sprites(girlgameoverimage, animationdata.animationtemplate[6].timeinterval, animationdata.animationtemplate[6].framescount, animationdata.animationtemplate[6].horizontalframes, animationdata.animationtemplate[6].verticalframes);



    $(".centerpart").append("<div class='girlgameoverloop' id='girlgameoverloop' style='position:absolute; width:" + animationdata.animationtemplate[7].width + "px;  height:" + animationdata.animationtemplate[7].height + "px; top:" + animationdata.animationtemplate[7].top + "px; left:" + leftforgirl + "px ;  background:url(" + animationdata.animationtemplate[7].images + ");display:none;z-index:1000;display:none;background-position-x:0px;background-position-y:0px;background-position:0px 0px;background-repeat: no-repeat'></div>");
    var girlgameoverloopimage = document.getElementById("girlgameoverloop");
    girlgameoverloop = new sprites(girlgameoverloopimage, animationdata.animationtemplate[7].timeinterval, animationdata.animationtemplate[7].framescount, animationdata.animationtemplate[7].horizontalframes, animationdata.animationtemplate[7].verticalframes);


    $(".centerpart").append("<div class='girlwalk' id='girlwalk' style='position:absolute; width:" + animationdata.animationtemplate[9].width + "px;  height:" + animationdata.animationtemplate[9].height + "px; top:" + animationdata.animationtemplate[9].top + "px; left:" + leftforgirl + "px ;  background:url(" + animationdata.animationtemplate[9].images + ");display:none;z-index:1000;display:none;background-position-x:0px;background-position-y:0px;background-position:0px 0px;background-repeat: no-repeat'></div>");
    var girlwalkimage = document.getElementById("girlwalk");
    girlwalk = new sprites(girlwalkimage, animationdata.animationtemplate[9].timeinterval, animationdata.animationtemplate[9].framescount, animationdata.animationtemplate[9].horizontalframes, animationdata.animationtemplate[9].verticalframes);

    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();
    $("#allAudio").css("visibility", "hidden");

}


/*
 * 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 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").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; 
        if (kind_of_screen == "onlycenterwithsmalldim")
        {

            for (var i = 0; i < templatedata.levels[levelelement].level.numberofdoors; i++)
            {
                if (optionsarray[i].door.image != "")
                {
                    countertestimg++;
                    $("#door" + (i + 1)).append("<img class='testingclass' id=testimage" + i + " src=" + pathextension + optionsarray[i].door.image + "  style='width:auto;height:auto;position:absolute;visibility:hidden'></img>");
                    $("testimage" + i).css("visibility", "hidden");
                }

            }



            $(".testingclass").one('load', function () {
                dimenobject["w" + $(this).attr("id").split("ge")[1]] = $(this).width();
                dimenobject["h" + $(this).attr("id").split("ge")[1]] = $(this).height();
                counterblockimg++;
                if (counterblockimg == countertestimg)
                {
                    extnAppendImagesSmall();
                }

            }).each(function () {
                if (this.complete)
                    $(this).load();
            });



        }
        else
        {

            for (var i = 0; i < templatedata.levels[levelelement].level.numberofdoors; i++)
            {
                if (optionsarray[i].door.image != "")
                {
                    countertestimg++;
                    $("#door" + (i + 1)).append("<img class='testingclass' id=testimage" + i + " src=" + pathextension + optionsarray[i].door.image + "  style='width:auto;height:auto;position:absolute;visibility:hidden'></img>");
                    $("testimage" + i).css("visibility", "hidden");
                }

            }



            $(".testingclass").one('load', function () {
                dimenobject["w" + $(this).attr("id").split("ge")[1]] = $(this).width();
                dimenobject["h" + $(this).attr("id").split("ge")[1]] = $(this).height();
                counterblockimg++;
                if (counterblockimg == countertestimg)
                {
                    extnAppendImages();
                }

            }).each(function () {
                if (this.complete)
                    $(this).load();
            });


        }
    } 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 (CollisionAudio != null)
        {
            CollisionAudio.play(templatedata.settings.reward);
        }
        else {
            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.load();    
//                finalapplause.play();
                document.getElementById("correctanimation").src = getAudioExtension(("assets/audio/" + templatedata.settings.reward), ".mp3");
                    document.getElementById("correctanimation").load();
                    document.getElementById("correctanimation").play();
                }
            } else
            {
                PlayIESound(getAudioExtension(("assets/audio/" + templatedata.settings.reward), ".mp3"));
            }
        }
        girlgameover.start(girlgameover, 1, animationarray);
    }

}

function extnAppendImagesSmall()
{

    pathextension = pathextension.split("content/")[0] + "content_smaller/";

    girlidle.domelement.style.left = (parseInt(girlidle.domelement.style.left.split("p")[0]) - 50) + "px";
    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;

        var ht = dimenobject["h" + i];//optionsarray[i].door.height;
        var wd = dimenobject["w" + i];
        // var ht=optionsarray[i].door.smallerscreen.height;
        // var wd=optionsarray[i].door.smallerscreen.width;   		   
        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:18px; text-align: center ;display:none;z-index:500;cursor:pointer'>" + optionsarray[i].door.text + "</p>");
            wd = document.getElementById("example").clientWidth + 1;
            ht = document.getElementById("example").clientHeight + 1;
        }
        var left = leftofdoor + (parseInt(templatedata.centerpart.optionleft) - 5) + ((parseInt(templatedata.centerpart.optionwidth) - 5) - wd) / 2;
        var top = topofdoor + (parseInt(templatedata.centerpart.optiontop) - 5) + ((parseInt(templatedata.centerpart.optionheight) - 25) - ht) / 2;
        var audioleft = 1;
        var audiotop = 1;
        if (templatedata.sound == "yes")
        {
            $(".centerpart").append("<img class='audioimage' audsrc='" + optionsarray[i].door.sound + "' id='audioimage" + (i + 1) + "' alt='audio' title='audio' src='assets/images/content/audio_N1.png'  style='position:absolute; height:auto; cursor:pointer; width:auto;z-index:5010;display:block'/>");
            audioleft = leftofdoor + ($("#door" + (i + 1)).width() - (templatedata.centerpart.dooraudioImgWidth)) / 2;

            audiotop = topofdoor - (templatedata.centerpart.dooraudioImgHeight);
        }

        if (navigator.userAgent.match(/ipad/i) != null)
        {
            if (window.orientation == 0 || window.orientation == 180)
            {
                left = left + (i * 42);
                audioleft = audioleft + (i * 42.5)
                top = top + (20);
                audiotop = audiotop + (26);
            }
        }
        if (navigator.userAgent.match(/Android/i) != null)
        {
            if (window.orientation == 90 || window.orientation == -90)
            {

                left = left + (i * 42);
                audioleft = audioleft + (i * 48)
                top = top + (10)
                audiotop = audiotop + (15);
            }
            if (window.orientation % 180 != 0)
            {
                if (screen.availWidth == 600 && screen.availHeight == 1024)
                {
                    if (templatedata.levels[levelelement].level.numberofdoors <= 4)
                    {

                        left = left + (i * 28);
                        audioleft = audioleft + (i * 28)
                        top = top + (10)
                        audiotop = audiotop + (15);
                    }
                    else
                    {

                        left = left + (i * 25);
                        audioleft = audioleft + (i * 19)
                        top = top + (35)
                        audiotop = audiotop + (15.5);
                    }
                }
            }
            else
            {

                if (screen.availWidth == 1024 && screen.availHeight == 600)
                {

                    if (templatedata.levels[levelelement].level.numberofdoors <= 4)
                    {
                        left = left + (i * 48);
                        audioleft = audioleft + (i * 48)
                        top = top + (10)
                        audiotop = audiotop + (15);

                    }
                    else
                    {
                        left = left + (i * 42);
                        audioleft = audioleft + (i * 42)
                        top = top + (35)
                        audiotop = audiotop + (15);
                    }
                }
            }
        }

        if (templatedata.sound == "yes")
        {
            $("#audioimage" + (i + 1)).css("left", audioleft);
            $("#audioimage" + (i + 1)).css("top", audiotop);
        }

        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; text-align: center ; font-size:18px; left:" + left + "px; top:" + (top - 20) + "px;z-index:500;cursor:pointer'>" + optionsarray[i].door.text + "</div>");

            if (navigator.userAgent.match(/Android/i) != null)
            {
                if (window.orientation == 90 || window.orientation == -90)
                {
                    textAlign("doorimage" + (i + 1), i, kind_of_screen);
                }
                if (window.orientation % 180 != 0)
                {
                    if (screen.availWidth == 600 && screen.availHeight == 1024)
                    {
                        textAlign("doorimage" + (i + 1), i, kind_of_screen);
                    }
                }
                else
                {
                    if (screen.availWidth == 1024 && screen.availHeight == 600)
                    {
                        textAlign("doorimage" + (i + 1), i, kind_of_screen);
                    }
                }
            }
            if (navigator.userAgent.match(/ipad/i) != null)
            {
                if (window.orientation == 0 || window.orientation == 180)
                {
                    textAlign("doorimage" + (i + 1), i, kind_of_screen);
                }
            }
        }
        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.smallerscreen.image + " correct=" + optionsarray[i].door.correct + " style='position:absolute; height:auto; width:auto;  left:" + left + "px; top:" + top + "px;z-index:500;cursor:pointer'/>");
        }
        if (optionsarray[i].door.image == "")
        {

            $("#doorimage" + (i + 1)).css("left", leftofdoor + ($("#door" + (i + 1)).width() - $("#doorimage" + (i + 1)).width()) / 2);
        }
        else
        {
            $("#doorimage" + (i + 1)).css("left", left + "px");
        }
    }
    $(".door").bind("click", doorClicked);
    $(".doorimage").bind("click", doorImageClicked);
    $(".audioimage").bind("click", doorAudioImageClicked);
    questionnumber++;
}



function extnAppendImages()
{


    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;
        var ht = dimenobject["h" + i];//optionsarray[i].door.height;
        var wd = dimenobject["w" + i];//optionsarray[i].door.width;




        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;font-weight: bold; font-size:18px; text-align: center ;display:none;z-index:500;cursor:pointer'>" + optionsarray[i].door.text + "</p>");
            wd = document.getElementById("example").clientWidth + 1;
            ht = document.getElementById("example").clientHeight + 1;
        }
        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);
        var audioleft = 1;
        var audiotop = 1;
        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:auto; cursor:pointer; width:auto;z-index:5010;display:block'/>");
            audioleft = leftofdoor + ($("#door" + (i + 1)).width() - (templatedata.centerpart.dooraudioImgWidth)) / 2;
            audiotop = topofdoor - (templatedata.centerpart.dooraudioImgHeight);
        }
        if (navigator.userAgent.match(/ipad/i) != null)
        {
            if (window.orientation == 0 || window.orientation == 180)
            {
                left = left + (i * 48);
                audioleft = audioleft + (i * 48)
                top = top + (10);
                audiotop = audiotop + (18.5);
            }
        }
        if (navigator.userAgent.match(/Android/i) != null)
        {
            if (window.orientation == 90 || window.orientation == -90)
            {
                left = left + (i * 53);
                audioleft = audioleft + (i * 52)
                top = top + (20)
                audiotop = audiotop + (20);
            }

            if (window.orientation % 180 != 0)
            {
                if (screen.availWidth == 600 && screen.availHeight == 1024)
                {
                    if (templatedata.levels[levelelement].level.numberofdoors == 5)
                    {
                        left = left + (i * 22);
                        audioleft = audioleft + (i * 23.5)
                        top = top + (10)
                        audiotop = audiotop + (0);
                    }
                    else
                    {
                        if (templatedata.levels[levelelement].level.numberofdoors <= 4)
                        {

                            left = left + (i * 24);
                            audioleft = audioleft + (i * 24)
                            top = top + (10)
                            audiotop = audiotop + (7.4);
                        }
                        else
                        {
                            left = left + (i * 28);
                            audioleft = audioleft + (i * 28)
                            top = top + (10)
                            audiotop = audiotop + (15);
                        }
                    }

                }
            }
            else
            {

                if (screen.availWidth == 1024 && screen.availHeight == 600)
                {

                    if (templatedata.levels[levelelement].level.numberofdoors == 5)
                    {
                        left = left + (i * 47);
                        audioleft = audioleft + (i * 47)
                        top = top + (10)
                        audiotop = audiotop + (15);
                    }
                    else
                    {
                        if (templatedata.levels[levelelement].level.numberofdoors <= 4)
                        {
                            left = left + (i * 48);
                            audioleft = audioleft + (i * 48)
                            top = top + (10)
                            audiotop = audiotop + (15);
                        }
                        else
                        {

                            left = left + (i * 88);
                            audioleft = audioleft + (i * 88)
                            top = top + (10)
                            audiotop = audiotop + (15);
                        }
                    }


                }
            }
        }
        if (templatedata.sound == "yes")
        {
            $("#audioimage" + (i + 1)).css("left", audioleft);
            $("#audioimage" + (i + 1)).css("top", audiotop);
        }
        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;font-weight: bold; font-size:18px; text-align: center ;left:" + left + "px; top:" + (top - 20) + "px;z-index:500;cursor:pointer'>" + optionsarray[i].door.text + "</div>");

            if (navigator.userAgent.match(/Android/i) != null)
            {
                if (window.orientation == 90 || window.orientation == -90)
                {
                    textAlign("doorimage" + (i + 1), i, kind_of_screen);
                }

                if (window.orientation % 180 != 0)
                {
                    if (screen.availWidth == 600 && screen.availHeight == 1024)
                    {
                        textAlign("doorimage" + (i + 1), i, kind_of_screen);
                    }
                }
                else
                {
                    if (screen.availWidth == 1024 && screen.availHeight == 600)
                    {
                        textAlign("doorimage" + (i + 1), i, kind_of_screen);
                    }
                }

            }
            if (navigator.userAgent.match(/ipad/i) != null)
            {
                if (window.orientation == 0 || window.orientation == 180)
                {
                    textAlign("doorimage" + (i + 1), i, kind_of_screen);
                }
            }
        }
        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 + "px; top:" + top + "px;z-index:500;cursor:pointer'/>");

        }
        //$("#doorimage"+(i+1)).css("top",top+"px"); 
        if (optionsarray[i].door.image == "")
        {
            $("#doorimage" + (i + 1)).css("left", leftofdoor + ($("#door" + (i + 1)).width() - $("#doorimage" + (i + 1)).width()) / 2);
        }
        else
        {
            $("#doorimage" + (i + 1)).css("left", left + "px");
        }
    }
    $(".door").bind("click", doorClicked);
    $(".doorimage").bind("click", doorImageClicked);
    $(".audioimage").bind("click", doorAudioImageClicked);
    $(".testingclass").remove();
    questionnumber++;
}



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

    if (navigator.userAgent.match(/ipad/i) != null)
    {
        if (CollisionAudio == null) {
            $("#toplayer").css("display", "block");
            spinner = new Spinner(opts).spin(document.getElementById("toplayer"));

            CollisionAudio = new audiofunctinallity("myaudio", "assets/audio/CompileInOne_1", timeobject, doorClicked, e);
        }
    }

    if (loaderindicator)
    {

        loadEnded();
        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)
{
    if (navigator.userAgent.match(/ipad/i) != null)
    {
        if (CollisionAudio == null) {
            $("#toplayer").css("display", "block");
            spinner = new Spinner(opts).spin(document.getElementById("toplayer"));

            CollisionAudio = new audiofunctinallity("myaudio", "assets/audio/CompileInOne_1", timeobject, doorImageClicked, e);
        }
    }

    if (loaderindicator)
    {

        loadEnded();
        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)
{
    if (navigator.userAgent.match(/ipad/i) != null)
    {
        if (CollisionAudio == null) {
            $("#toplayer").css("display", "block");
            spinner = new Spinner(opts).spin(document.getElementById("toplayer"));

            CollisionAudio = new audiofunctinallity("myaudio", "assets/audio/CompileInOne_1", timeobject, suffClicked, e);
        }
    }

    if (loaderindicator)
    {

        loadEnded();
        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;
    $(".door").unbind("click", doorClicked);
    $(".doorimage").unbind("click", doorImageClicked);
    $(".suffimage").unbind("click", suffClicked);
    $(".audioimage").unbind("click", doorAudioImageClicked);

    if (CollisionAudio != null)
    {
        CollisionAudio.play(["SFX_correct"]);
    }
    else
    {
        var audioed = getAudioExtension("assets/audio/SFX_correct", ".mp3");
        playAnimationaudios(audioed);
    }
    // CollisionAudio.play(["SFX_correct"]);

    var animations = new Array();
    if (kind_of_screen == "onlycenterwithsmalldim")
    {
        doorsprite = new sprites(element, animationdata.animationtemplate[8].timeinterval, animationdata.animationtemplate[8].framescount, animationdata.animationtemplate[8].horizontalframes, animationdata.animationtemplate[8].verticalframes);
    }
    else
    {
        doorsprite = new sprites(element, animationdata.animationtemplate[0].timeinterval, animationdata.animationtemplate[0].framescount, animationdata.animationtemplate[0].horizontalframes, animationdata.animationtemplate[0].verticalframes);
    }
    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, animations);
                girlwalk.whichsprite = 0;
                girlwalk.verticalmove(girlwalk, element, 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, 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, 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, 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, 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, animations);
        }
    }
}

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

function doorcallback()
{
    //alert("");
    var animations1 = new Array();
    if (answer == "true")
    {
        $("#" + imagehide).css("display", "none");
        animations1.push(girlcorrectcallback);
        doorsprite.numberofsprites = 31;
        doorsprite.start(doorsprite, 1, animations1);
    } else
    {
        if (animationdirection == "left")
        {
            girlleft.domelement.style.display = "none";
            girlwrong.domelement.style.left = (parseInt(girlleft.domelement.style.left.split("p")[0]) + 10) + "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]) - 5) + "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]) + 10) + "px";
            girlwrong.domelement.style.top = girlwalk.domelement.style.top;
        }
        girlwrong.domelement.style.display = "block";
        var checkvar = document.getElementById("suff" + doorsprite.domelement.getAttribute("id"))
        if (checkvar == null) {
            $(".centerpart").append("<img class='suffimage' id='suff" + doorsprite.domelement.getAttribute("id") + "' src=" + templatedata.centerpart.suffimage + " style='position:absolute; width:" + ((parseInt(templatedata.centerpart.suffwidth.split("p")[0])) - 10) + "px ; height:auto; left:" + (parseInt(doorsprite.domelement.style.left.split("p")[0]) + parseInt(templatedata.centerpart.suffleft)) + "px; top:" + ((parseInt(doorsprite.domelement.style.top.split("p")[0]) + parseInt(templatedata.centerpart.sufftop)) - 10) + "px;z-index:500;cursor: pointer;cursor: hand;'/>");

        }
        animations1.push(oneMoreTry);
        /*var audioed=getAudioExtension("assets/audio/"+wrongAudioSounds[Math.floor(Math.random()*(wrongAudioSounds.length))],".mp3");
         playAnimationaudios();
         */         //  CollisionAudio.play([wrongAudioSounds[Math.floor(Math.random()*(wrongAudioSounds.length))]]);  

        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, animations1);
    }
}

/*
 * call back function   correct door click
 */
function girlcorrectcallback()
{
    var animations2 = new Array();

    // alert(correctAudioSounds[questionnumber]);

    if (CollisionAudio != null)
    {
        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]) + 10) + "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]) - 5) + "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]) + 10) + "px";
        girlcorrect.domelement.style.top = girlwalk.domelement.style.top;
    }
    girlcorrect.domelement.style.display = "block";
    girlcorrect.start(girlcorrect, 1, animations2);
}
/*
 * call back function for closing the door
 */
function doorClose()
{

    var animations3 = new Array();
    if (CollisionAudio != null)
    {
        CollisionAudio.play("doorbuster_footsteps_off");
    }
    else
    {

        var audied = getAudioExtension("assets/audio/doorbuster_footsteps_off", ".mp3");
        playAnimationaudios(audied);
    }
    //   CollisionAudio.play(["doorbuster_footsteps_off"]);
    animations3.push(reload);
    girlcorrect.domelement.style.display = "none";
    doorsprite.start(doorsprite, 1, animations3);
}
/*
 * resetting all images and removing suffimage after correct animation complete
 */
function reload()
{
    if (kind_of_screen == "onlycenterwithsmalldim")
    {
        girlidle.domelement.style.left = (parseInt(girlidle.domelement.style.left.split("p")[0]) + 50) + "px";
    }
    resetAllImages();
    $(".suffimage").remove();
    appendimages();
    $(".audioimage").bind("click", doorAudioImageClicked);
}

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

/*
 * resetting all images to original position
 */
function resetAllImages()
{
    allowplaycontent = true;
    girlleft.reset(girlleft);
    girlright.reset(girlright);
    girlwrong.reset(girlwrong);
    girlcorrect.reset(girlcorrect);
    girlidle.reset(girlidle);
    girlwalk.reset(girlwalk);
    doorsprite.reset(doorsprite);
    $(".suffimage").bind("click", suffClicked);
    girlcorrect.domelement.style.left = girlidle.domelement.style.left;
    girlcorrect.domelement.style.top = girlidle.domelement.style.top;
    girlleft.domelement.style.left = girlidle.domelement.style.left;
    girlleft.domelement.style.top = animationdata.animationtemplate[4].top + "px";
    girlright.domelement.style.left = girlidle.domelement.style.left;
    girlright.domelement.style.top = animationdata.animationtemplate[5].top + "px";
    girlwrong.domelement.style.left = girlidle.domelement.style.left;
    girlwrong.domelement.style.top = girlidle.domelement.style.top;
    girlcorrect.domelement.style.left = girlidle.domelement.style.left;
    girlcorrect.domelement.style.top = girlidle.domelement.style.top;
    girlwalk.domelement.style.left = girlidle.domelement.style.left;
    girlwalk.domelement.style.top = girlidle.domelement.style.top;
    girlidle.domelement.style.display = "block";
    girlidle.start(girlidle, 0);
}


/*
 * call back function for audio icon click
 */
function playContentAudios()
{

    if (navigator.userAgent.match(/ipad/i) != null)
    {
        if (CollisionAudio == null) {
            $("#toplayer").css("display", "block");
            spinner = new Spinner(opts).spin(document.getElementById("toplayer"));

            CollisionAudio = new audiofunctinallity("myaudio", "assets/audio/CompileInOne_1", timeobject, playContentAudios);
        }
    }

    if (loaderindicator)
    {
        loadEnded();
        var dummyarray = [];

        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");
                            if (navigator.userAgent.match(/Android/i) == null)
                            {
                                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  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 (CollisionAudio != null)
    {
        CollisionAudio.pause();
    }
    else {


        if (allowplaycontent || gameover)
        {
            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 (kind_of_screen == "onlycenterwithsmalldim")
    {
        girlidle.domelement.style.left = (parseInt(girlidle.domelement.style.left.split("p")[0]) + 50) + "px";
    }
    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 = "";
    doorsprite = "";
    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();

}


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

/*audio image clicked called function*/

function doorAudioImageClicked(e)
{
    if (navigator.userAgent.match(/ipad/i) != null)
    {
        if (CollisionAudio == null) {
            $("#toplayer").css("display", "block");
            spinner = new Spinner(opts).spin(document.getElementById("toplayer"));

            CollisionAudio = new audiofunctinallity("myaudio", "assets/audio/CompileInOne_1", timeobject, doorAudioImageClicked, e);
        }
    }

    if (loaderindicator)
    {
        loadEnded();

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


        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");
                if (!isAndroid) {

                    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";
}



