﻿var eMode = 1; //1 - Seach/Regular, 2 - MediaCut-Click    3 - MediaCut-DragPoint
var ePlayerMode = 1; //1 - Seach/Regular, 2 - MediaCut
//==============================================
//..... MEDIA CUT FUNCTIONS START      ..........

//http://localhost:2315/Current_v3.5.5.0_MediaCopy/PLAYER/PEPlayer.aspx?ProtocolID=3876

//==============================================

var elStart;
var elEnd;

var mc_StartTime;
var mc_EndTime;

/*
function SetMCMode(k) {
    eMode = k;
    CleanMCValue();
    if (eMode == 3) {

        $("#mainDiv font span").mousedown(
              function() {
                  var currentId = $(this).attr('id');
                  Goto(document.getElementById(currentId));
              });
        $("#mainDiv font span").mouseup(
              function() {
                  var currentId = $(this).attr('id');
                  Goto(document.getElementById(currentId));
              });

        $("#mainDiv font")
    }
}
*/

function SetMCMode(k) {
    eMode = k;
    CleanMCValue();
    if(eMode==3) {
         
//        $("#mainDiv font").mousedown(
//              function() {
//              //
//                   var curr_font = $(this) ;
//                   while(curr_font.children("span").length==0)
//                       curr_font = curr_font.next();
//                                              
//                   var oSpans = curr_font.children("span");                   
//                   if(oSpans.length>0)
//                   {                       
//                       
//                       Goto(oSpans[0]);                   
//                   }                                 
//              });
//              
//              
//        $("#mainDiv font").mouseup(
//             function() {
//              // 
//                   var curr_font = $(this) ;
//                   while(curr_font.children("span").length==0)
//                       curr_font = curr_font.next();
//                                              
//                   var oSpans = curr_font.children("span");                   
//                   if(oSpans.length>0)
//                   {                       
//                       
//                       Goto(oSpans[0]);                   
//                   }
//                  
//                 
//              });       
            
    }     
}


var mc_dp_el_start;
var mc_dp_el_end;


function CatchMediaMouseEvents() {

    $("#mainDiv font span").mouseover(function(e) {
        document.getElementById("debug").value = 'eMode=' + eMode;
        if (eMode == 2 || eMode == 3) {
            $("#cursor_media").show();
        }
    });

    $("#mainDiv font span").mousemove(function(e) {
        document.getElementById("debug").value = 'eMode=' + eMode;
        if (eMode == 2 || eMode == 3) {
            e.preventDefault();
            $("#cursor_media").css('left', e.pageX + 5);
            $("#cursor_media").css('top', e.pageY - 10);
        }
    });

    $("#mainDiv font span").mouseout(function(e) {
        document.getElementById("debug").value = '';
        $("#cursor_media").hide();
    });


    $("#mainDiv font").mousedown(function(e) {
        if (eMode == 3 && mc_StartTime == null) {
            var curr_font = $(this);
            while (curr_font.children("span").length == 0)
                curr_font = curr_font.next();

            var oSpans = curr_font.children("span");
            if (oSpans.length > 0) {
                mc_dp_el_start = oSpans[0];
            }
        }
    });

    $("#mainDiv font").mouseup(function(e) {
        if (eMode == 3 && mc_dp_el_start != null && mc_dp_el_end == null) {
            var curr_font = $(this);
            setEndPointByDragAndPoint(curr_font);

        }
    });

    $("#mainDiv").mouseup(function(e) {
        if (eMode == 3 && mc_dp_el_start != null && mc_dp_el_end == null) {
            alert('לא זיהה נקודת סיום - יש לשחרר את העכבר כשהסמן נמצא על טקסט');
            CleanMCValue();
        }
    });
}

function ShowMediaCutPanel() {
    var oMedia = document.getElementById('MEDIACUT_PANEL');
    var oSearch = document.getElementById('SEARCH_PANEL');
    if (oMedia.style.display == '') {
        eMode = 1;
        oMedia.style.display = 'none';
        oSearch.style.display = '';
        CleanMCValue();
        $("#cursor_media").hide();
        document.getElementById("CutMediaBtn").src = 'PE_ICONS/cutMediaDisable.png';
    }
    else 
    {
        
        eMode = 2;
        oMedia.style.display = '';
        oSearch.style.display = 'none';
        document.getElementById("CutMediaBtn").src = 'PE_ICONS/cutMediaEnable.png';
        CatchMediaMouseEvents();

    }
}

function setEndPointByDragAndPoint(curr_font) {
    //debugger;
    while (curr_font.children("span").length == 0)
        curr_font = curr_font.next();

    var oSpans = curr_font.children("span");
    if (oSpans.length > 1) {
        mc_dp_el_end = oSpans[1];
    }
    else if (oSpans.length > 0) {
        mc_dp_el_end = oSpans[0];
    }

    if (mc_dp_el_start != null && mc_dp_el_end != null) {
        Goto(mc_dp_el_start);
        Goto(mc_dp_el_end);
    }
}

var oMCPopupWin;

function PreviewMediaCut() {
 
    mc_StartTime = GetTimeSpanFromValue(document.getElementById('mc_timeStart_txt').value);
    mc_EndTime = GetTimeSpanFromValue(document.getElementById('mc_timeEnd_txt').value);

    if (isNaN(mc_StartTime) || mc_StartTime < 0) {
        alert('יש לבחור נקודת התחלה');
        mc_StartTime = null;
        mc_EndTime = null;
    }
    else if (isNaN(mc_EndTime) || mc_EndTime < 0) {
        alert('יש לבחור נקודת סיום');
        mc_EndTime = null;
    }
    else {

        //MODAL WINDOW
        //============
        //var sTicks = (new Date()).getTime().toString();        
        //oMCPopupWin = window.showModalDialog('MediaCutPreview.aspx?id=' + ProtocolID + '&strmServer=' + strmServer + '&strmFile=' + strmFile + '&Start=' + mc_StartTime + '&End=' + mc_EndTime + '&nocashe=' + sTicks, '_blank', 'dialogWidth:320px; dialogHeight:300px;center:yes; edge:sunken; help:no; resizable:yes; scroll:yes; status:no;');

        //NON-MODAL WINDOW
        //============
        PausePlayer();
        oMCPopupWin = window.open("MediaCutPreview.aspx?id=" + ProtocolID + "&strmFile=" + strmFile + "&Start=" + mc_StartTime + "&End=" + mc_EndTime, "MediaCut", "height=300px, width=320px");
        //setInterval('StayOnTop();', 300);
        setInterval('CatchMediaMouseEvents();', 1000);
    }
}


/*
function StayOnTop()
{
    try
    {
         if(oMCPopupWin!=null)
             oMCPopupWin.focus();
    }
    catch(e){  }
     
}
*/

function GetTimeSpanFromValue(v) {
    try {
        
        var res = -1;
        if (v != "") {
            var args = v.split(":");
            if (args.length < 3)
                alert('שגיאה - זמן לא תקין');
            if (isNaN(args[0]) || isNaN(args[1]) || isNaN(args[2]))
                alert('שגיאה - זמן לא תקין');

            res = parseInt(args[0]) * 60 * 60 + parseInt(args[1]) * 60 + parseInt(args[2]);
            //alert(res);
            //res = parseInt(args[0]) * 60 + parseInt(args[1]);
        }
        return res;
    }
    catch (e) {
        return -1;
    }
}

function GetTimeStringFromTimeSpan(r) {
    try {
        //r = r / 1000; //move to seconds
        var TOTAL_MINUTES = parseInt(r / 60);

        var HH = parseInt(TOTAL_MINUTES / 60);
        var MM = TOTAL_MINUTES % 60;
        var SS = r % 60;
            
        //var HH = parseInt(r / 60); //hours        
        //var MM = r % 60;
        //return HH + ":" + MM;
        
        return HH + ":" + MM + ":" + SS;
    }
    catch (e) {
        alert("שגיאה: " + e);
    }
}

function CleanMCValue() {
    mc_StartTime = null;
    mc_EndTime = null;
    mc_dp_el_start = null;
    mc_dp_el_end = null;
    document.getElementById('mc_timeStart_txt').value = "";
    document.getElementById('mc_timeEnd_txt').value = "";
    if(elStart!=null)
        elStart.style.background = '';
    if(elEnd!=null)
        elEnd.style.background = '';
}
//==============================================
//..... MEDIA CUT FUNCTIONS END  .......
//==============================================


function Goto(el) {

    lastBookmarkIndex = 0;
    var old_timer = timer;

    if (el.id.indexOf('nob') >= 0) {
        document.getElementById('BookmarkNotFound').style.display = '';
        setTimeout("document.getElementById('BookmarkNotFound').style.display='none';", 2000);
        if (eMode == 2 || eMode == 3) {
            
            alert("נקודת סינכרון לא קיימת. נסה לסמן במיקום אחר בטקסט");

        }
        return;
    }

    m_index = parseInt(el.id.substring(4));

    var iCounterSearchClosestBookmark = 0;

    while (bk[m_index] < 0) {
        m_index--;
        iCounterSearchClosestBookmark++;
        if (m_index < 1) { iCounterSearchClosestBookmark = 4; break; }
    }

    if (iCounterSearchClosestBookmark > 3) {
        //alert('לא נמצאה נקודת סינכרון למקטע זה');
        document.getElementById('BookmarkNotFound').style.display = '';
        document.getElementById('BookmarkNotFound').innerHTML = '<img src="PE_ICONS/pagebook.gif" alt="loading..." />loading...';
        setTimeout("document.getElementById('BookmarkNotFound').style.display='none';", 2000);
        if (eMode == 2 || eMode == 3) {

            alert("נקודת סינכרון לא קיימת. נסה לסמן במיקום אחר בטקסט");

        }
        return;
    }
    else //בדוק אם נקודת סנכרון רציונלית לפי שני הבאות אחריה
    {
        if (bk.length > m_index + 2) {
            if (bk[m_index] > bk[m_index + 1] && bk[m_index] > bk[m_index + 2]) {
                if (bk[m_index - 1] < bk[m_index + 1])
                    m_index = m_index - 1;
                else
                    m_index = m_index + 1;
            }
        }
    }
    //MEDIA CUT MODE
    if (eMode == 2 || eMode == 3) {

        if (mc_StartTime == null) {

            mc_StartTime = bk[m_index];
            document.getElementById('mc_timeStart_txt').value = GetTimeStringFromTimeSpan(mc_StartTime);

            if (elStart != null)
                elStart.style.background = '';
            el.style.backgroundImage = 'url(PE_ICONS/mc_start.png)';  //backgroundColor = 'gray';
            el.style.backgroundRepeat = 'no-repeat';
            el.style.backgroundPosition = 'right top';

            elStart = el;
        }
        else if (mc_EndTime == null) {
            if (bk[m_index + 1] <= mc_StartTime) {
                while (bk[m_index + 1] <= mc_StartTime) {
                    m_index++;

                }
                el = document.getElementById("txt_" + m_index);               
            }


            mc_EndTime = bk[m_index+1];
            document.getElementById('mc_timeEnd_txt').value = GetTimeStringFromTimeSpan(mc_EndTime);

            if (elEnd != null)
                elEnd.style.background = '';
            el.style.backgroundImage = 'url(PE_ICONS/mc_end.png)';  //
            el.style.backgroundRepeat = 'no-repeat';
            el.style.backgroundPosition = 'left top';

            elEnd = el;
        }         
        else {
            alert("יש להסיר נקודות התחלה וסיום קיימות לפני בחירה מחדש");
        }
    }
    else if (eMode == 1) {
        //REGULAR/SEARCH MODE

        document.getElementById('JumpingToBookmark').style.display = '';
        setTimeout("document.getElementById('JumpingToBookmark').style.display='none';", 1500);

        bFromClickOnText = true;
        iCurrElementIndexForSearch = m_index;
        SetTimer(bk[m_index]);


        if (timer >= 0) {
            Seek();
        }
        else {
            SetTimer(old_timer);
        }
    }
}
  
 
        
        function getH(){
            
            var h = 9999;
            var temp;
//            if(document.body)
//            { 
//                temp=document.body.clientHeight; 
//                if(temp<h) h=temp;
//            }
            
            
            if(document.documentElement.clientHeight)
            { 
                temp=document.documentElement.clientHeight;
                if(temp<h) h=temp;
            } 
            
                    
//            if(document.innerHeight)
//            { 
//                temp=document.innerHeight;
//                if(temp<h) h=temp;
//            } 
            
            return h;
        }
        
        function getH2(){
            
            var h;
            if(document.body)
            { 
                h=document.body.clientHeight; 
            }
            else if(document.documentElement.clientHeight)
            { 
                h=document.documentElement.clientHeight;
            } 
            else if(document.innerHeight)
            { 
                h=document.innerHeight;
            } 
            return h;
        }
         
        function __getH(){
             
            var h;
            if(document.innerHeight)
            { 
                h=document.innerHeight;
            } 
            else if(document.documentElement.clientHeight)
            { 
                h=document.documentElement.clientHeight;
            } 
            else if(document.body)
            { 
                h=document.body.clientHeight; 
            }
            return h;
        }
        
        function getW(){
            var w;
            if(document.innerWidth){ w=document.innerWidth;
            } else if(document.documentElement.clientWidth){ w=document.documentElement.clientWidth;
            } else if(document.body){ w=document.body.clientWidth; }
            return w;
        }

        var index = 0;
        var currIndex = 0;
        var bFreeze = false;
        var lastBookmarkIndex = 0;
        var bFromClickOnText = false;
        var bStartPlayFrom3Minutes;
        
        /*# FLV PLAYER PARAMETERS AND LISTENERS */
        var currentPosition = 0; 
        var currentVolume = 0; 
        var currentMute = false;
        var currentState = "Idle";       
        
        var player;
        

        function addListeners() {
		    if(player.view) {
			    player.addListener('LOAD',loadUpdate);
			    player.addListener('STATE',stateUpdate);
			    player.addListener('TIME',timeUpdate);
		    } 
		    else {
			    setTimeout("addListeners()",300);
		    }
	    };
	     
        
        var bSeek = false;
        var bStopBySearch = false;
        var bListenrLOADEventFired = false;
        function loadUpdate(lld)
        {
           
            sStatTrak = sStatTrak  + " [loadUpdate] ";

            if (bDoOnloadJob && !bListenrLOADEventFired)
            {
                bListenrLOADEventFired = true;   //bDoOnloadJob = false;
                if(querySt("Element")!="")
        	    {        	    
        	        bFromSearch = true;
        	           
        	        setTimeout('SetTimer(bk[parseInt(querySt("Element"))]);  Seek();',300);         	       	          	    
        	    }         	     
                else //if(bStartPlayFrom3Minutes)
                {        
                        
                    setTimeout("SetTimer(bk[iBMStartIdx]);   if(timer>200) timer=180; Seek();",300);         
        	    }
        	           
        	}
        }
   
      
        function timeUpdate(pos, duration) 
        {          
 
            synchTimer =   parseInt(pos.toString())
            if(Math.abs(synchTimer - currentPosition)>10 && !bFromClickOnText)
            {
                iCurrElementIndexForSearch = 1;                 
            }
            
            bFromClickOnText = false;
            var pMM = synchTimer%60;
            var pHH = synchTimer / 60;
            
            //DEBUG
            //document.getElementById("debug_time").value =  parseInt(pHH) + ":" + pMM;
            
            if (bDoOnloadJob && ePlayerMode==1 &&(iBulkIndex == 1 && synchTimer > bk[iBMEndIdx]) || (iBulkIndex > 1 && (synchTimer < bk[iBMStartIdx] || synchTimer > bk[iBMEndIdx])))             
             { 
                document.getElementById('JumpingToBookmark').style.display='';
                setTimeout("document.getElementById('JumpingToBookmark').style.display='none';", 1500);                                                      
                loadContent(true);
              }
               
             
            currentPosition = synchTimer;

        }

        function ShowDebug() {
            alert('bDoOnloadJob:' + bDoOnloadJob + '; ePlayerMode:' + ePlayerMode);
        }
        
          
        var sStatTrak = "";        
        
        function stateUpdate(oldState, newState) {
             
            if (ePlayerMode != 1) return;
            
            //  
            currentState = newState; 
           
            sStatTrak =  "[" + timer + "] current:" + currentState + " old:" + oldState;
                                          
            //document.getElementById('my_debug').innerText =  sStatTrak;
            
            if(currentState=='Playing' && (!bFreeze || oldState=='Idle' || oldState=='Paused' || oldState=='Closed' || oldState=='Buffering')) // (oldState=='Paused' ||  oldState=='Closed' ||  oldState=='Idle'))
            { 
                
                if(bStopBySearch)
                {
                  Seek();
                  setTimeout("bStopBySearch = false;", 500);
                  //return;
                }       	    
                bFreeze = false;                
                mark();    
                            
            }
            else if(currentState=='Paused'   && currentState!=oldState)
            {
                 
                bFreeze = true;                          
            }           
            else if((currentState=='Closed' || currentState=='Idle')   && currentState!=oldState)
            {
                bFreeze = true;                    
                iCurrElementIndexForSearch = 1;                      
                if(!bStopBySearch){ 
                    
                    SetTimer(bk[iBMStartIdx]);    
                    
                }
            }                        
        }
        
        function SetTimer(val)
        {
             timer = val;
             
        }
       
        function Seek()
        {
            //if(!bInnerSearchWasMade)
            bSeek = true;           
                
            try{
                if(currentState!= 'Playing')
                    player.sendEvent('play', true);
                player.sendEvent('scrub',timer)  
                
//                if(currentState== 'Playing')
//                    player.sendEvent('scrub',timer)  
//                else                
//                    setTimeout("Seek()",100);              
            }
            catch(e)
            {
                setTimeout("Seek()",300);
            }                    
        }        
        

        function CreatePlayer(mmsServer, wmvPath)
        {
            var elm = document.getElementById("placeholder1");
            var src = 'wmvplayer.xaml';
            var cfg = {
                image: 'preview.jpg',
                overstretch:'true',
                lightcolor:'f85010',
                file: mmsServer + wmvPath,
                autostart: 'false',
                showstop: 'true',
                screencolor:'ffffff',
                width:'280',
                height:'210',
                backgroundcolor:'0173e0'
                 
            };
            player = new jeroenwijering.Player(elm, src, cfg);
            addListeners();
        }
        
        var timer = 0;                        
        var synchTimer = 0;
        var BindScrollerToMedia = true;
        
        function SetScroller(etype)
        {
            if(etype=='bind')
            {
                BindScrollerToMedia = true;
            }
            else
            {
                BindScrollerToMedia = false;
            }
        }
        
        function SetScroller2(elImg)
        {
            if(elImg.src.indexOf('Synchronize.png')>0)
            {
                BindScrollerToMedia = false;
                elImg.src = 'PE_Icons/SynchronizeOff.png';
            }
            else
            {
                try
                {
                BindScrollerToMedia = true;
                elImg.src = 'PE_Icons/Synchronize.png';
                var iTemp = index-10;                
                if(iTemp<1) iTemp=1;
                if(iTemp<iBMStartIdx)  iTemp=iBMStartIdx;
                var scrollElementInView = document.getElementById('txt_' + iTemp);                
                scrollElementInView.scrollIntoView(true);
                }
                catch(e)
                {
                
                }
            }
        }
        
        var iBMStartIdx = -1;
        var iBMEndIdx = 9999999;
        var iBulkIndex = 0;
        
        var iLastBulkStartBMIndex=1; //used for PREV button - to go to the top of the last bulk
        
        var iPageStart = 0;
        var iPageEnd = 999;
        
        var bFromSearch = false;
        
        var iCurrElementIndexForSearch = 0;
        
        
        var InServerCallStat = 0;
        var LastTimeServerCall = 0;

        function loadStaticBulk(iBulk, _iElement, _sPharse, _itemNum) {
             
            if (!bDoOnloadJob)
                return;
                   
            SetTimer(bk[_iElement]);
            bFromSearch = false;
            iCurrElementIndexForSearch = _iElement;
            
            $.post(
                "ReqContent.aspx",
                {__EVENTTARGET: "BULK::" + ProtocolID + "::" + iBulk + "::" +  _iElement + "::" + _sPharse + "::" + _itemNum}, 
                SetContentByServerForBulk);
                
            $.post(
                "ReqContent.aspx",
                {__EVENTTARGET: "BOOKMARK_RANGE_BULK::" + ProtocolID + "::" + iBulk }, 
                SetIndexesByServer);                              
         
                      
            oLastMatches = null;
            lastHash = null;
        }
        
        function loadContent(bShowSyncMsg) {
            if (!bDoOnloadJob)
                return;
                
            if(InServerCallStat>0 && Math.abs(LastTimeServerCall - synchTimer)<5) return;
             
            InServerCallStat = 2; 
            LastTimeServerCall = synchTimer;
            
            if(bShowSyncMsg){
                document.getElementById('JumpingToBookmark').style.display='';
                setTimeout("document.getElementById('JumpingToBookmark').style.display='none';", 1500); 
            }
            $.post(
                "ReqContent.aspx",
                {__EVENTTARGET: "CONTENT::" + ProtocolID + "::" + synchTimer }, 
                SetContentByServer);
                
            $.post(
                "ReqContent.aspx",
                {__EVENTTARGET: "BOOKMARK_RANGE::" + ProtocolID + "::" + synchTimer }, 
                SetIndexesByServer);                              
         
                      
            oLastMatches = null;
            lastHash = null;
        }

        function SetContentByServerForBulk(data) {
             
            if (!bDoOnloadJob)
                return;
                
            if (iCurrElementIndexForSearch != undefined) {
                document.getElementById('mainDiv').innerHTML = data;
                var scrollElementInView = document.getElementById('txt_' + iCurrElementIndexForSearch);
                if (scrollElementInView == null)
                    scrollElementInView = document.getElementById('nob_' + iCurrElementIndexForSearch);
                scrollElementInView.scrollIntoView(true);
            }
            iCurrElementIndexForSearch = 1;                        
            
        }
        
        function SetContentByServer(data) {
            if (!bDoOnloadJob)
                return;
                   
            document.getElementById('mainDiv').innerHTML = data; 
            InServerCallStat = InServerCallStat -1;
             
            if(bFromSearch)
            {                 
                var pElmnt = querySt("Element");
                Goto(document.getElementById("txt_" + pElmnt)); 
                bFromSearch = false;
            } 
            
        }
        
        var iAttemptesToLoadContent = 0;
        //var bInitAtFirstBKindex = true;
        
        function SetIndexesByServer(data)
        {  
            InServerCallStat = InServerCallStat -1;     
            if(data.indexOf("::")<0){  
                  iAttemptesToLoadContent++;
                  if(iAttemptesToLoadContent>20) 
                            SetTimer(bk[iBMStartIdx]); 
                   InServerCallStat = 0;                                               
                   loadContent(true); 
                   return;
                  } 
            iAttemptesToLoadContent = 0;        
            var t = data.split("::");       
            
            
            iBulkIndex = parseInt(t[0]);
            iBMStartIdx = parseInt(t[1]);
            iBMEndIdx =  parseInt(t[2]);            
             
             
            try
            {
                 
                oLastPager. style.backgroundColor='';
                oLastPager.style.fontWeight='normal';   
                oLastPager = document.getElementById("pager_" + iBulkIndex);                             
                oLastPager.style.backgroundColor='yellow';
                oLastPager.style.fontWeight='bold'; 
                document.getElementById('lblMiktaTitle').innerText ='מקטע ' + oLastPager.innerText;               
            }
            catch(e)
            {
                 
            } 
        }
        
        
        
        function getAllMatchesIndexByTimer()
        {
             
            //if(lastBookmarkIndex - 3 < 0)
            lastBookmarkIndex = parseInt(iCurrElementIndexForSearch); //*******************//
                         
            var countIrrelevantLoops = -99999;
            var gap = 999;
            var best;                       
            
            var _to = bk.length;
            if(lastBookmarkIndex < iBMStartIdx)
                lastBookmarkIndex = iBMStartIdx;
            if(  iBMEndIdx < _to )
                _to = iBMEndIdx;           
            
            document.getElementById("my_debug").innerText = "looking from " + lastBookmarkIndex + " to " + _to;  
                                         
            for(i=lastBookmarkIndex; i<_to; i++)
            {
                 if(bk[i]<=0) continue;
                 if(bk[i]>synchTimer) {
                    best = i;           
                    break;
                  }                                                       
            }                         
             
            var oMatches = new Array();
            var pIndex = 0;             
            for(i=best-1; i>0 ; i--)
            {
                if(bk[i] == bk[best-1] )
                    oMatches[pIndex++] = i;
                else
                    break;
            } 
            
            
            //-----------------------------------------          
            var sDebug = '';
            for(p=0; p<oMatches.length; p++){                 
                
                var pMM = bk[oMatches[p]]%60;
                var pHH = bk[oMatches[p]]/60;
                
                sDebug = sDebug + ' ; ' +   parseInt(pHH) + ":" +pMM;
            }
            //document.getElementById('my_debug2').innerText=sDebug; 
                 

             return oMatches;                           
        }                  
        
        
        function ______getAllMatchesIndexByTimer()
        {
             
            //if(lastBookmarkIndex - 3 < 0)
            lastBookmarkIndex = parseInt(iCurrElementIndexForSearch); //*******************//
                         
            var countIrrelevantLoops = -99999;
            var gap = 999;
            var best;
            for(i=lastBookmarkIndex; i<bk.length; i++)
            {
                 if(bk[i]<=0) continue;
                 
                 if((synchTimer - bk[i]>=0) && (synchTimer - bk[i]<gap))
                 {
                    gap = synchTimer - bk[i];
                    best = i;
                    countIrrelevantLoops = 0;
                 } 
                 //try to find more 20 bookmarks ahead. if not found better- break and use current best found
                 if(countIrrelevantLoops>20)
                    break;                 
            }  
             
            lastBookmarkIndex = best;
             
             var oMatches = new Array();
            var pIndex = 0;             
            for(i=lastBookmarkIndex; i<bk.length; i++)
            {
                if(bk[i] == bk[best] )
                    oMatches[pIndex++] = i;
            } 
                      
            var sDebug = '';
            for(p=0; p<oMatches.length; p++){                 
                
                var pMM = bk[oMatches[p]]%60;
                var pHH = bk[oMatches[p]]/60;
                
                sDebug = sDebug + ' ; ' +   parseInt(pHH) + ":" +pMM;
            }
            //document.getElementById('my_debug2').innerText=sDebug; 
                 

             return oMatches;                           
        }                  
       
         
        var oLastMatches;
        
        var lastHash = 0;
        
        function hashedIndexes(MatchedIndexes)
        {
            var hash = 0;
            for(i=0; i<MatchedIndexes.length; i++){
                hash = hash + MatchedIndexes[i];
            }
            //if(hash==8482)
            //    
            return hash;
        }
         
        
        //var oMarkIsRunning = false;
         
        function mark() //MARK ALL MATCHED ELEMENTS
        {         
             
            if(!bFreeze)
            {                                               
                var MatchedIndexes = getAllMatchesIndexByTimer();       
                                                       
                var currHash = hashedIndexes(MatchedIndexes);
                //document.getElementById('txtSeach').value = currHash + "::" + lastHash;
                if(currHash != lastHash)
                {                                                  
                    
                    lastHash = currHash;
                    
                    if(MatchedIndexes[0]>iBMEndIdx && bk[MatchedIndexes[0]]>0)  { 
                        ShowPagingGif(null, null);                                          
                        loadContent(true); //                
                    }  
                    
                                                            
                    if(oLastMatches!= null){
                        for(i=0; i<oLastMatches.length; i++){
                            //if(MatchedIndexes[i] >= iBMStartIdx && MatchedIndexes[i] <= iBMEndIdx){
                            try{
                                var el =  document.getElementById('txt_' + oLastMatches[i]);                                  
                                el.style.backgroundColor=''; 
                            }
                            catch(e){
                                
                                }
                            //}
                        }
                    }
                    
                    for(i=0; i<MatchedIndexes.length; i++){
                        //if(MatchedIndexes[i] >= iBMStartIdx && MatchedIndexes[i] <= iBMEndIdx){
                            try{
                                var el =  document.getElementById('txt_' + MatchedIndexes[i]);                                
                                el.style.backgroundColor='yellow'; 
                            }
                            catch(e){ }    
                        //}
                    }
                    
                    index = MatchedIndexes[0];
                    
                    try{
                        var iTemp = index-4;
                        if(iTemp<0) iTemp=0;
                        if(iTemp<iBMStartIdx)  iTemp = iBMStartIdx;
                        var scrollElementInView = document.getElementById('txt_' + iTemp);
                        if(BindScrollerToMedia)
                            scrollElementInView.scrollIntoView(true);
                    }
                    catch(e)
                    {
                                            
                    }                                       
                    oLastMatches = MatchedIndexes;                                                                                            
                }
                
                                                                          
                 
                setTimeout("mark()", 1000);  
            }
            
             
        }

        
        
         
        
 
        var elSearch;
        var pAll;
        var current_k;
        
        var jump_to_element_index_on_load = null;

        var PagingDivLoaded = false;
        var divTag;
        var oLastPager; // = document.getElementById("pager_1");
        
        function GotoPager(sTarget)
        {
            iCurrElementIndexForSearch = 1;  
            if(sTarget=='FIRST'){
                 
                SetTimer(bk[1]);
            }
             
            else if(sTarget=='NEXT')
            {               
                
                try{                      
                  iNextBulk = iBulkIndex+1;
                  oRelPager = document.getElementById("pager_" +  iNextBulk);  
                  oValue = oRelPager.onclick.toString();                                                       
                  SetTimer(parseInt( oValue.split(",")[1]));                   
                 }
                 catch(e){}
                
            }
            else if(sTarget=='PREV'){
                if(iBulkIndex>1)
                {
                   iPrevBulk = iBulkIndex-1;
                   oRelPager = document.getElementById("pager_" +  iPrevBulk);  
                   oValue = oRelPager.onclick.toString();                                                       
                   SetTimer(parseInt( oValue.split(",")[1]));
                }
                else
                   alert("אתה נמצא במקטע הראשון");                           
            }                        
            Seek();             
        }
        
        function ShowPagingGif(fromPage, toPage)
        {
             
            if(!PagingDivLoaded){
                divTag = document.createElement("div");                
                divTag.id = "imagePaging";                
                divTag.setAttribute("align","center");                                        
                divTag.className ="PagingDiv";                                          
                document.body.appendChild(divTag);
                PagingDivLoaded=true;
            }
            
            divTag.style.display='';
            var sHtml = '<br /><img src="PE_ICONS/pagebook.gif" alt="loading..." /><br />';
            if(fromPage!=null)
                sHtml = sHtml +  '<br /><font style="font-weight:bold"> טוען עמ\' ' + fromPage + ' עד ' + toPage + '</font>';  
            
            divTag.innerHTML =   sHtml;
                                        
            setTimeout("document.getElementById('imagePaging').style.display='none';", 1500);

        }   
        
                
                        
        function GotoTime(oPager, t, fromPage, toPage)
        {
            iCurrElementIndexForSearch = 1;             
            ShowPagingGif(fromPage, toPage);
            
            $.post(
                "ReqContent.aspx",
                {__EVENTTARGET: "GET_FIRST_INDEX_FOR_BULK::" + ProtocolID + "::" + oPager.innerText}, 
                function(firstIndexVal){SetTimer(bk[firstIndexVal]);  Seek();  } );
                   
            //SetTimer(t+2);              
      
            try
            {               
                oLastPager.style.backgroundColor='';
                oLastPager.style.fontWeight='normal';   
                oPager.style.backgroundColor='yellow';
                oPager.style.fontWeight='bold';
                oLastPager=oPager;
                document.getElementById('lblMiktaTitle').innerText ='מקטע ' + oPager.innerText;
            }
            catch(e)
            {
                //alert(e);
            } 
            
            //Seek();                               
        } 
 
        
//        var PauseCounter = 0;
        var mSeach_iBulk;
        var mSeach_iElementIndexer;
        var mSeach_sPharse;
        var mSeach_iItemNum;
        
        function rplc(m, txt, rep)
        {
            while(m.indexOf(txt)>=0)
                m = m.replace(txt, rep);
            return m;    
        }

        function ProtEOnline(iTor, iBulk, iElementIndexer, sPharse, iItemNum) {
            //debugger;
            //var iElementIndexer = _iElementIndexer - 1;
            
            mSeach_iBulk = iBulk;                          
            mSeach_iElementIndexer = iElementIndexer;
            mSeach_sPharse = rplc(sPharse, '#GERESH#','\"');
            mSeach_iItemNum = iItemNum;
    
            
            bFreeze=true;
            SetTimer(bk[iElementIndexer]);
            
            
            Seek();            
            PausePlayer();
            
          }
          
        function ProtEOnlineStartWithSeach(iTor, iBulk, iElementIndexer, sPharse, iItemNum, sSearchOnload)
        { 
            ProtEOnline(iTor, iBulk, iElementIndexer, sPharse, iItemNum);
        }
          
        var PauseIntervalID;
        function PausePlayer()
        {                 
            if(currentState=='Paused')  
            {                 
                clearInterval(PauseIntervalID);
                loadStaticBulk(mSeach_iBulk, mSeach_iElementIndexer, mSeach_sPharse, mSeach_iItemNum);
                PauseIntervalID = null;
                
//                iTimeBySearch = bk[mSeach_iElementIndexer];
//                bInnerSearchWasMade = true;
                return;
            }               
            else
            {
//                if(currentState=='Closed') {
//                    Seek(bk[mSeach_iElementIndexer]);
//                    timer = bk[mSeach_iElementIndexer];
//                    clearInterval(PauseIntervalID);
//                    PauseIntervalID = setInterval('PausePlayer();', 500);
//                    return;
//                }
                if(currentState=='Playing') player.sendEvent('play',false);
                if(PauseIntervalID==null)  PauseIntervalID = setInterval('PausePlayer();', 150);
            }
        }
        
 
        
        function ProtEOnline_InnerSeachInBulk(iElementIndexer)
        {
                
            SetTimer(bk[iElementIndexer]);
            Seek();
        }

        
        var sbw_element_index_value;
        var sbw_sPharse;
        

        function btnSearch_onclick() 
        {
            
            document.getElementById('ajax').style.display='';
            document.getElementById('ajax1').style.display='';             
            document.getElementById('searching').style.display=''; 
            
            if(querySt("InnerSeachOnly")=="")
            {
                //***** DB SEARCH ****************************
                $.post(
                    "ReqSearch.aspx",
                    {__EVENTTARGET: ProtocolID + "::" + document.getElementById('txtSeach').value }, 
                    ProcessSearch);   
            }    
            else
            {
                //*****  SEARCH INNER BULK HTML ONLY **********
                var pAll = document.getElementsByTagName("span");                                      
                var sRes = "";			 
			    h = pAll.length;      
               
                 
			    for(k=0; k<h; k++)
			    {
    			   
				    elSearch =  pAll[k];
				    var oIndexOf = elSearch.innerHTML.indexOf(sPharse);
				    var sPharse = txtSeach.value;
                    var sPreview = '';
				    if (oIndexOf>=0)
				    {   
				        //				    
				        sPreview = sPreview + '<img src=\'PE_ICONS\\bullet.gif\' alt=\'תוצאת חיפוש\'>...' + elSearch.innerText.substring(oIndexOf-100, oIndexOf);				     
				        if(elSearch.id.indexOf('nob')>=0){
				            sPreview = sPreview + '<b>' + sPharse + '</b>';
				        }
				        else {				    
				            var elIndexer = elSearch.id.substring(4);
				            sPreview = sPreview + '<a href="javascript:;" onclick="ProtEOnline_InnerSeachInBulk(' + elIndexer + ');">' + sPharse + '</a>';
				        }
				        sPreview = sPreview + elSearch.innerText.substring( oIndexOf + sPharse.length, 100) + '...<br/>';					
					    sRes = sRes + sPreview;					 
				    }
			    } 
			    ProcessSearch(sRes);	
			}					 
        }
        
        function ProcessSearch(data)
        {        
                  
            data = data.substring(0, data.indexOf('<!DOCTYPE'));
            //alert(data);
            
            if(data.indexOf('#EMPTY#')<0)
            {
                document.getElementById('tblSearchTable').style.display='';
			    //document.getElementById('srchResults').innerHTML = '<table cellpadding="0" cellspacing="0" width=\"100%\"><tr><td><b>תוצאות חיפוש:</b></td><td align="left" style=\"padding-left:30px\"><img src=\"PE_ICONS/search_resize.png\" alt=\"הרחב-צמצם תוצאות חיפוש\"  onclick=\"ResetPanelsHeight();\"/> </td></tr></table>' + data; //<a href=\"javascript:;\" onclick=\"ResetPanelsHeight();\">[סגור]</a>
			    document.getElementById('srchResults').innerHTML = data;
			     document.getElementById('tdSearchTitle').innerHTML = '';
                SearchPanelOpened = true;
                ResizePanelsForSearch();
			}
			else
			{
			     document.getElementById('tblSearchTable').style.display='';
			     document.getElementById('tdSearchTitle').innerHTML = '<b>לא נמצאו תוצאות לביטוי. </b>';
			     document.getElementById('srchResults').innerHTML = '';
			}   
			document.getElementById('ajax').style.display='none';  
            document.getElementById('ajax1').style.display='none';              
            document.getElementById('searching').style.display='none';                       
        }
        
 
        var SearchPanelOpened = false;
        
        function ResizePanelsForSearch()
        {
            if(SearchPanelOpened)
            {
                document.getElementById('srchResults').style.height= "320px"; //345
                document.getElementById('mainDiv').style.height= "620px";
                SearchPanelOpened=false;
            }
            else
            {                
                document.getElementById('mainDiv').style.height= (getH()-252) + "px";
                document.getElementById('srchResults').style.height= (getH()-552) + "px";  //512
                SearchPanelOpened=true; 
            }     
        }
        
        function ResetPanelsHeight() {
            try {
                document.getElementById('srchResults').innerHTML = "";
                document.getElementById('mainDiv').style.height = (getH() - 252) + "px";
                document.getElementById('srchResults').style.height = (getH() - 552) + "px";  //512                
            }
            catch (e) {
            }
        }
        
//        function ResizeWindowEvent()
//        {                          
//            if(document.getElementById('srchResults').innerHTML != "")
//            {
//                document.getElementById('srchResults').style.height= "320px"; //345
//                document.getElementById('mainDiv').style.height= "620px";
//            }
//            else
//            {
//                document.getElementById('mainDiv').style.height= (getH()-252) + "px";
//                document.getElementById('srchResults').style.height= (getH()-552) + "px";  //512                
//            }
//        }

        
        function querySt(ji) {
            hu = window.location.search.substring(1);
            gy = hu.split("&");
            for (i=0;i<gy.length;i++) {
                ft = gy[i].split("=");
                if (ft[0] == ji) {
                    return ft[1];
                }
            }
            return "";
        }
       
       function EnterPressedDoSearch()
       {
            if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) 
            {
                 btnSearch_onclick();
                return false;
            }  
             else 
                return true; 
       }
       
       function ShowBookmarks()
       {
           document.getElementById("debug_time").style.display=''; 
           for(var ib=iBMStartIdx; ib<=iBMEndIdx;ib++)
           {    
               try{
                 
                    var pMM = bk[ib]%60;
                    var pHH = bk[ib]/60;
                    
                    document.getElementById("txt_" + ib).innerHTML = "{" +  parseInt(pHH) + ":" +pMM   + "} " +  document.getElementById("txt_" + ib).innerHTML
                    //document.getElementById("txt_" + ib).innerHTML = "{" +bk[ib] + "} " +  document.getElementById("txt_" + ib).innerHTML
                }
                catch(e){}                      
           }
       }
        
       function printSpecial(divPrintable, title)
        {
            if (document.getElementById != null)
            {
                var html = '<HTML>\n<HEAD>\n';

                html += '<title>E-Parliament</title>\n';
                html += '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">\n';
                html += '<link href="fadida_Protocols_styles.css" rel="stylesheet" type="text/css" />\n';    
                html += '<script type="text/javascript">function Goto(e) { return false; }  </script>\n';        
  
                html += '\n</HEAD>\n\n<BODY DIR=\'RTL\'>';

                var printTitle = document.getElementById(title);
                if (printTitle != null)
                {
                    html += '<center><font id="print_title" style="font-weight:bold; font-family: Arial, Helvetica, sans-serif; font-size: 15px; color:#5F6581">' + printTitle.innerHTML + '</font></center><br/><br/>';
                }
                else
                {
                    alert("Could not find the printReady function");
                    return;
                }
                    
                var printReadyElem = document.getElementById(divPrintable);

                if (printReadyElem != null)
                {
                    html += printReadyElem.innerHTML;
                }
                else
                {
                    alert("Could not find the printReady function");
                    return;
                }

                html += '\n</BODY>\n</HTML>';

                var printWin = window.open("","printSpecial"); 
                printWin.document.open();
                printWin.document.write(html);  
                printWin.document.close();             
                printWin.print();                
            }
            else
            {
            alert("The print ready feature is only available if you are using an browser. Please update your browswer.");
            }
        }
