var handlingSlideEvent = false;
//function updateCurrentAssets(clip , time) {
//    var closestCuePoint;
//    var slideCuePoints = $(".slidesCarousel li img");
//    for (i = 0; i < slideCuePoints.length; i++)
//    {
//        var cuepoint = slideCuePoints[i];
//        var scriptData = cuepoint.metadata();
//        if (scriptData.ScriptEventTime < time)
//            closestCuePoint = cuepoint;
//        else
//            break;    
//    }
//    if (closestCuePoint) {
//        alert(closestCuePoint.src);
//    }
//}

function updateCurrentAssets(clip, time) {
    // add 1 second to the time in case there are slides within the next second
    time = (time + 2) * 1000; // convert to milli secs
    var clip = getClip(clip.url, clip.start);
    var cuepointCount = clip.CuePoints.length;
    var closestSlide;
    for (i = 0; i < cuepointCount; i++) {
        eventCuepoint = clip.CuePoints[i];
        if (eventCuepoint.Key == "2") {
            if (closestSlide) {
                if (eventCuepoint.TimeMilliseconds > closestSlide.TimeMilliseconds && eventCuepoint.TimeMilliseconds < time)
                    closestSlide = eventCuepoint;
            }
            else if (eventCuepoint.TimeMilliseconds < time){
                closestSlide = eventCuepoint
            }
        }
    }
    if (closestSlide)
        OnScript(closestSlide.Key, closestSlide.Value, eventID);
}


function getClip(clipSrc, clipStart) {
    var clipCount = pl.length;
    for (var i = 0; i < clipCount; i++) {
        var playlistClipStart = pl[i].StartTime;
        var playlistStreamName = pl[i].StreamName;
        if ((pl[i].StreamPrefix + ':' + playlistStreamName == clipSrc) && (playlistClipStart.toString() == clipStart.toString())) {
            return pl[i];
        }
    }
}

function OnScript(h, d, eventID) {
    //    if (window.console)
    //        console.info("Script Event triggered. ScriptEventType:" + h + " ScriptEventValue " + d);
    if (h == "MOD" || h == "mod" || h == "slide" || h == "SLIDE") {
        currentAssetType = "slide";
        eventStarted = true;
        var q = d.split(",");
        currentSlide = q[1];
        if ($('#slidecheck')) {
            if (q[1] == 5) {
                $('#slidecheck').html("<img id=\"slidespassed\" border='0' src='images/yes.gif'>");
            }
            else {
                if ($('#slidespassed').length == 0)
                    $('#slidecheck').html(q[1]);
            }
            $('#slidesworking').html("<b>Working</b>");
        }
        // zeroise slides
        var speakerIndex;
        if (q[0].length == 1) {
            speakerIndex = "0" + q[0];
        }
        //        if (q[0].length == 2) {
        //            speakerIndex = "0" + q[0];
        //        }
        if (q[1].length == 1) {
            q[1] = "0" + q[1];
        }
        //        if (q[1].length == 2) {
        //            q[1] = "0" + q[1];
        //        }
        // currentSlide and currentSlidesetIndexIndex are defined in player.js   
        slideSrc = "slides/" + eventID + "/" + speakerIndex + "/slide" + q[1] + ".jpg";
        speakerSrc = "speakers/" + eventID + "/presenter" + speakerIndex + ".jpg";
        if ($("#slides").attr('src') != slideSrc) {
            $("#slides").hide().attr('src', slideSrc);
        }
        // hide all speakers and show the current speaker only
        $("div.speakersList").each(function() {
            if (window.console) {
                console.log("Showing current speaker.");
            }
            $(this).children().hide();
            $(this).children().eq(q[0] - 1).show();
        });
        showSlides();
    }
    else if (h == "POLL" || h == "poll" || h == 4) {
        currentAssetType = "poll";
        var url = "polls.aspx?";
        url += "PollID=" + d;

        $("#pollDiv").load(url, function() {
            $("#slides").hide();
            $("#pollDiv").fadeIn("slow");
        });
        currentPoll = d;
    }
    else if (h == "POLLANSWERS" || h == "PollAnswers" || h == "pollAnswers" || h == "pollanswers") {
        currentAssetType = "poll";
        var url = "pollanswers.aspx?";
        url += "PollID=" + d;

        $("#pollDiv").load(url, function() {
            $("#slides").hide();

            $("#pollDiv").fadeIn("slow");
        });

        //        ServiceMethod("assetservice.asmx","GetPollQuestions" , ["pollID", d ], function(result){
        //                $("#pollDiv").html(result);
        //                $("#slides").hide();
        //                $("#pollDiv").fadeIn("slow");
        //            }
        //            , function(){
        //                alert("An error occured while getting questions.");
        //            });

        currentPoll = d;
    }
    else if (h == "POLLQUESTION" || h == "pollquestion" || h == "question" || h == 14) {
        currentAssetType = "poll";
        var url = "poll.aspx?";
        url += "PQID=" + d;
        $("#pollDiv").load(url, function() {
            $("#slides").hide();
            $("#pollDiv").fadeIn("slow");
        });
        currentPoll = d;
    }
    else if (h == 0) {
        // first find selected speaker and change their style to normal.
        var previousSpeaker = getObjInFrameName("divSpeaker_" + currentSpeakerID, "Tab");
        if (previousSpeaker) {
            previousSpeaker.className = originalSpeakerCSS;
        }

        var speakerDivObj = getObjInFrameName("divSpeaker_" + d, "Tab");
        if (speakerDivObj) {
            originalSpeakerCSS = speakerDivObj.className;
            speakerDivObj.className = "selectedSpeaker";
        }
        currentSpeakerID = d;
    }
    else if (h == 1) {
        handlingSlideEvent = true;
        currentAssetType = "slide";
        var slideURL = "AjaxHandler.ashx?fn=slide&SlideID=" + d;
        $.galleria.activate(slideURL);
        currentSlide = slideURL;
        currentSlideID = d;
        handlingSlideEvent = false;
    }
    else if (h == 2) {
        // FillCaptionDivContent(d);
        $.ajax({
            type: "GET",
            url: "AjaxHandler.ashx?CaptionID=" + d + "&fn=caption",
            dataType: "text",
            success: function(result) { OnScript("mod", result, eventID); }
        });
    }
    else if (h == 14) {
        // load test
        window.location = "test.aspx?PollID=" + d;
    }
}

function submitQuestion(eventID, eventTitle) {
    var quest = $("#questionfield").val();
    var title = $("#questionfield").attr("title");
    if (quest != "" && quest != title) {
        $("#error").hide();
        ServiceMethod("assetservice.asmx", "SubmitQuestion", ["question", quest, "eventID", eventID, "eventTitle", eventTitle], submitQuestionSucceeded, AjaxFailed);
        $("#questions div.box").block({
            message: $("#questionProgressDiv").html(),
            css: {
                padding: 0,
                margin: 0,
                width: '100%',
                top: '0',
                left: '35%',
                textAlign: 'center',
                color: '#666666',
                border: '0px solid #aaa',
                backgroundColor: '#fff',
                cursor: 'wait'
            },
            overlayCSS: {
                backgroundColor: '#fff',
                opacity: 1.0,
                cursor: 'wait'
            }
        });
    }
    else {
        $("#error").show();
    }
}

function submitQuestionSucceeded(result) {
    if (result.d)
        result = result.d;
    $("#questions div.box").unblock();
    $('#submitQuestionForm').hide();
    $('#submitQuestionResult').show();

    var divResult = $("#submitQuestionResult");
    divResult.html(result);
    divResult.fadeIn();
    $("#questionfield").attr("value", "");
    $("#questionfield").hint();
}


function showSlides() {
    $("#pollDiv").fadeOut("slow", function() { $("#slides").show(); });
    $("#slides").show();
}

function submitPoll() {
    var options = {
        target: '#pollDiv',
        success: function() {
            $('#pollForm').hide();
            // for IMS some questions will show the slide after some time while others
            // will show the results after sometime, so, better leave the control of what gets
            // displayed to the script events
            //    setTimeout(showSlides, 5000); 
        }
    };

    $('#pollForm').ajaxSubmit(options);
    return false;
}

function enlargeSlides() {
    $('#bigSlides').dialog('open');
    try {
        $f().hide();
    }
    catch (ex) {
        if (window.console) {
            console.log("couldn't hide flow player");
            console.log(ex);
        }
    }
}

