onDomReady(function () {

    // init
    header.initialize();
});


var header = {
 
    // global variables for search box
    searchIndex:null,
    searchTab:0, // 0 or 1 as default Tab
    searchReq:'/moviesearch/search', // search_movies or search_broadcasters
    searchText:'',

    //timer for inbox 5 minutes call
    headerTimer:0,
    
    liveCallback:false,
    endCallback:false,
    endMovieId:null,
    
    //live indications members
    generalLiveIndication:null,
    personalLiveIndication:null,
    startingYourBroadcastIndication:null,
    myMovieLinkElement: null,
    maxETA:30,
    progressBarElement: null,
    progressTimeElement: null,
    
    
    initialize: function()
    {
        //initialize the light box - forgot password
		if($("forgotPasswordBox"))
			header.forgotPasswordLB = new Lightbox($("forgotPasswordBox"),{opacity:0.5});

        //initialize the light box - errors
		if($("formValidationErrors"))
			header.errorsLB = new Lightbox($("formValidationErrors"),{opacity:0.5});

        //initialize the light box - success
		if($("formValidationSuccess"))
			header.successLB = new Lightbox($("formValidationSuccess"),{opacity:0.5});

        // load search tabs
        var searchTabs = $$('div.searchTab');
        searchTabs.each(function(el, i){
            if(i == header.searchTab) {
                el.addClass('current'); header.searchIndex = el;} // Need add to Css cursor pointer
        });

        if ($('buttSearch') == null) {
//            window.status = "Error loading page. Possible reason: There is no movie with this Id";
            return;
        }
        $('buttSearch').href=header.searchReq+"?search_string="+$('txtSearch').value;

        //if user logged in - update the number of messeges in inbox every 5 minutes
        if($('numOfInboxMesseges')){
            clearTimeout(header.headerTimer);
            header.updateNumOfInboxMesseges();
        }

        // set default showed tab
        header.searchText = $('txtSearch').value;
       
        header.generalLiveIndication = $('generalLiveIndication');
        header.personalLiveIndication = $('personalLiveIndication');
        header.startingYourBroadcastIndication = $('startingBroadcast');
        header.myMovieLinkElement = $('myMovie');
        header.progressBarElement = $('progressBar');
        header.progressTimeElement = $('progressTime');

        
        this.checkIfLive();
    },
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    checkIfLive: function() {
        var poster = new Ajax("/main/PollForLive", {method:'get', onComplete:function() {
            var liElements = this.transport.responseXML.documentElement.getElementsByTagName("li");
            var myFlixIdElement = this.transport.responseXML.documentElement.getElementsByTagName("flixid")[0];
            var myEtaElement = this.transport.responseXML.documentElement.getElementsByTagName("eta")[0];
            
            //var val = p.firstChild.nodeValue; 
           // debugger;

            if (header.liveCallback)
            {
               header.liveCallback(liElements);
            } // End of if

            header.DoLiveLogic(liElements,myFlixIdElement,myEtaElement);
            
            ////////////////////////////////////////
            if(header.endCallback && header.endMovieId)
            {
               var found = false;
               for(i=0;i<liElements.length;i++)
               {
                  id = liElements[i].getAttribute("id");
                  if(id == header.endMovieId)
                  {
                     found = true;
                     break;
                  
                  }
               } // End of for
               if(found == false)
               {
                 header.endCallback();
                 header.endMovieId = null;
               } 
            } // End of if
            ///////////////////////////////////////////
            
            window.setTimeout(header.checkIfLive, 4000);
        }}).request();
    },
    
     ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    loginFormKeyUp: function(f, e) {
        e = e || event;
        if (e.keyCode == 13) {
            this.checkLoginForm(f);
        }
    }, 
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    logout:function() {
        flix.showReloader('Signing out...','send');
        var updater = new Ajax("/alpha/LogOut", {method: 'get', onComplete:function(){
            document.location.reload();
        }}).request();
    },
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //check the login form
    checkLoginForm: function(f) {
        var frm = document.getElementById(f);

        if(frm.usernameText.value=="") frm.usernameText.focus();
        else if(frm.passwordText.value=="") frm.passwordText.focus();
        else {
            flix.showReloader('Signing in...','send');
            var updater = new Ajax("/alpha/Login/?user="+frm.usernameText.value+"&password="+frm.passwordText.value+"&remember_me="+frm.rememberme.checked , {method: 'get', onComplete:function(){
                try {
                    var status = eval(this.transport.responseXML.firstChild.getAttribute("success"));
                    if (status) {
                        document.location.reload();
                    } else {
                        document.getElementById("authFailedBox").style.display = "";
                        frm.passwordText.select();
                    }
                } catch (e) {
                    alert(e.description);
                }
                flix.hideReloader(); // hide reloader
            }}).request();
        }
    },
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    // search tabs
    showTab: function(o, searchReq) {
        // hide last showed panel

        header.searchReq = searchReq;
        //flix.hideIt(header.showIndex);
        if(o != header.searchIndex && o != null) {
            var last = header.searchIndex;
            last.removeClass('current');
        }
        header.searchIndex = o;
        if(!o.hasClass('current')) { o.addClass('current'); $('buttSearch').href=searchReq+"?search_string="+header.searchText; }
    },

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // search input updater
    updateString: function(o, e) {
        e = e || event;
        if (e.keyCode == 13) {
            document.location.href = header.searchReq+"?search_string="+header.searchText;
        } else {
            header.searchText = o.value;
            $('buttSearch').href=header.searchReq+"?search_string="+header.searchText;
        }
    },
        
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //--------------------------------logged in user inbox - number of messeges Ajax update header.php --------------------------------------------------//
    // header.php  (AJAX content) - refresh the number of messeges, every 5 minute
    updateNumOfInboxMesseges: function() {
/*
        header.showReloader('Update...','update'); // Violet
        var updater = new Ajax('includes/header/inbox.php?r=' + Math.floor(Math.random()*1000) , {method: 'get', update: $('numOfInboxMesseges'), onComplete:function(){
            header.hideReloader(); // hide reloader
        }}).request();

        //set off the function every 5 minute
        header.headerTimer = setTimeout("header.updateNumOfInboxMesseges()", 300000);
*/        
    },
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //activates on click on the log in link in header.php
    //-----shows the log in form
    showLoginForm: function() {
        var SignInDiv = document.getElementById("SignIn");
        var LoginLinksDiv = document.getElementById("LoginLinks");

        if((SignInDiv.style.display=="none")||(SignInDiv.style.display=="")){
            SignInDiv.style.display = "block";
            LoginLinksDiv.style.display = "none";
        }
        else{
            SignInDiv.style.display = "none";
            LoginLinksDiv.style.display = "block";
        }
        document.getElementById('LoginForm').usernameText.focus();
        
    },
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    // show reloader
    // content - may be any text or html tags
    // task - is options for colors (load, send, update)
    showReloader: function(content, task) {
        var o = $('reloader');
        o.setHTML(content);

        switch(task) {
            case 'load':
                o.setStyle('background','#E30A17'); // red
                break
            case 'send':
                o.setStyle('background','#78BA91'); // green
                break
            case 'update':
                o.setStyle('background','#7389AE'); // violet
                break
            default:
                //code to be executed if n is
                //different from case 1 and 2
        }
        o.show();
    },
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    // hide reloader after all Ajax request
    hideReloader: function() {
    var o = $('reloader');
    o.hide();
    },
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    sendOnEnter: function(ev) {
        if(header.getKeyCharCode(ev) == 13)
            window.location.href=$('buttSearch').href;
    },
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    getKeyCharCode: function(event){
        var key = null;
        if (window.event) {
            //ie
            key = window.event.keyCode;
        } else if (event.which) {
            key = event.which;
        }
        return key;
    },
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    DoLiveLogic: function(liElements,myFlixIdElement,myEtaElement)
    {
        if(myFlixIdElement)
        {
             document.getElementById('tlProgress').style.background = "red";
             //display the i'm broadcasting now element
             var flixId = myFlixIdElement.firstChild.nodeValue; 
             //check the eta element  of the flix (as sent by the video server)
             var eta =   myEtaElement.firstChild.nodeValue;

             if(eta <= 0)
             {
               // debugger;
                // if eta == 0 , the live movie is ready for viewing
                //this means that the progress bar should be filled to max
                // and that the reference should be active 
                //header.setProgressBar(1,0); //
                //document.getElementById('tlProgress').style.background = "gray";
                //set the reference when clicking on the image
                this.personalLiveIndication.style.display = "none";
                this.progressBarElement.style.display = "none";
                this.myMovieLinkElement.setAttribute("href","/watch/"+flixId);
                this.startingYourBroadcastIndication.style.display = "";
             } //end of if
             else // eta is some number bigger then 0 -movie is not ready yet 
             {
                this.myMovieLinkElement.setAttribute("href","#"); // make it reference to nothing
                this.startingYourBroadcastIndication.style.display = "none";
                this.personalLiveIndication.style.display = "";
                this.progressBarElement.style.display = "";
                             
                if(eta > this.maxETA)
                  eta =  this.maxETA;
                header.setProgressBar((1- eta/this.maxETA),eta); //

             } // End of else
             
             
             if(liElements.length > 1)
             {
                 header.generalLiveIndication.style.display = "";
             }
             else
             {
                 header.generalLiveIndication.style.display = "none";

             }
        }
        else
        {
             this.personalLiveIndication.style.display = "none";
             this.progressBarElement.style.display = "none";
             this.startingYourBroadcastIndication.style.display = "none";



             if(liElements.length > 0)
             {
                    this.generalLiveIndication.style.display = "";
             }
             else  //if any of the live indications are on , hide them
             {
                   this.generalLiveIndication.style.display = "none";
             }

             
        }
    
                   
    
    
    
    }, // End of method
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    tlInterval: 10,
    tlLength: 90,  // Length of movie
    tlWidth: 90,
    moveBy: 1,
    setProgressBar: function (percent,seconds)
    {
          if(percent > 1)
          {
              percent = 1;
          }
          
          document.getElementById('tlProgress').style.width =   this.tlWidth*percent+"px";



          //update the digits element
          var hstring;
          if(seconds > 3600)
          {
            this.progressTimeElement.innerHTML = '59:59'; 
            return;
          }
          
          var minutes = Math.floor(seconds/60);
          if(minutes < 10)
          {
              hstring = "0"+minutes.toString()+":";
          }
          else
          {
              hstring = minutes.toString()+":";
          }
          
          var secs =  seconds%60;

          if(secs < 10)
          {
              hstring += "0"+secs.toString();
          }
          else
          {
              hstring += secs.toString();
          }
          
          this.progressTimeElement.innerHTML =  hstring;
          
          
          

          var check = null;


    
    },
    sendPass: function ()
    {
    	// Alon - Check if Email/Phone number are Recognized
    	
        if ($('lgPhone').value == "" && $('lgEmail').value == "")
        {
    		$('errors').innerHTML = 'Please enter your phone number or your e-mail address.';
    		header.errorsLB.show();
            return;
    	}
        
        
        if ($('lgCountryCode').selectedIndex == 0 && $('lgEmail').value == "")
        {
            $('errors').innerHTML = 'Please enter your phone number or your e-mail address.';
            header.errorsLB.show();
            return;
        }
        
        
        flix.showReloader('Updating...','update');
        if($('lgEmail').value != "")
        {
            var poster = new Ajax("/account/ForgotPasswordSubmit?email="+$('lgEmail').value, {method:'get', onComplete:function() {
                flix.hideReloader();
                var success = this.transport.responseXML.documentElement.getElementsByTagName("Success")[0];
                if (!success.firstChild || success.firstChild.nodeValue == "false")
                {
                    var reason = this.transport.responseXML.documentElement.getElementsByTagName("FailText")[0];
                    $('errors').innerHTML = reason.firstChild.nodeValue;
                    header.errorsLB.show();
                }
                else
                {
                   $('success').innerHTML = 'We will send you an e-mail with your username and password shortly.';
                   header.successLB.show(); 
                }
            }}).request();
        
        }
        else
        {
            var countryCode = $("lgCountryCode").options[$("lgCountryCode").selectedIndex].value;
            var poster = new Ajax("/account/ForgotPasswordSubmit?countryCode="+countryCode+"&mobileNumber="+$('lgPhone').value, {method:'get', onComplete:function() {
                flix.hideReloader();
                var success = this.transport.responseXML.documentElement.getElementsByTagName("Success")[0];
                if (!success.firstChild || success.firstChild.nodeValue == "false")
                {
                     $('errors').innerHTML = "We're sorry but we don't recognize this phone number. Please try again.";
                     header.errorsLB.show();
                }
                else
                {
                     //see through what the server sent the user details , email or sms
                     var sentBy = this.transport.responseXML.documentElement.getElementsByTagName("SentBy")[0].firstChild.nodeValue;
                     if(sentBy == "mail")
                     {
                         $('success').innerHTML = 'We will send you an e-mail with your username and password shortly.';
                     
                     }
                     else
                     {
                          $('success').innerHTML = 'Your username and password are being sent to your mobile phone by text message. Please check your text messages.';
                     
                     }
                     header.successLB.show();
                }
            }}).request();
        
        } 
        
    },
    cancelPass: function ()
    {
        
        $('lgEmail').value = "";
        $('lgPhone').value = "";
        
    }    
    
    
};
