onDomReady(function () {

    // init
    header.initialize();
	moveError();
	blink("#FF7F00");
//	if($("promoLine1").innerHTML != "")
//		switchPromo(1);
});

function moveError()
{
	var obj=$("error");
	if(obj.innerHTML=="")
		return;
	//alert('ss');
	if(!obj.style.marginLeft)
		obj.style.marginLeft=0;
	obj.style.marginLeft=(parseInt(obj.style.marginLeft)+5)%900 + "px";
	setTimeout('moveError()',40);
}
function blink(color)
{
	//alert(color);
	$("nav_livenow").style.color=color;
	if($("myMovie"))
		$("myMovie").style.color=color;
	setTimeout("blink(" + (color=="" ? "'#FF7F00'" : "''") + ");",500);
}
function switchPromo(id)
{
	//alert(color);
	$("promoLine"+id).style.display='';
	$("promoLine"+(1-id)).style.display='none';
	setTimeout("switchPromo(" + (1-id) + ");",5000);
}
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,
	liveUserCallback:false,
    endCallback:false,
    endMovieId:null,
    
    //live indications members
    generalLiveIndication:null,
    personalLiveIndication:null,
    startingYourBroadcastIndication:null,
    myMovieLinkElement: null,
    //maxETA:30,
    //progressBarElement: null,
    //progressTimeElement: null,
    loggedIn:false,
    radioPwdMail:false,
     
     
    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 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 = $('live_indicator');
        header.personalLiveIndication = $('personalLiveIndication');
        header.startingYourBroadcastIndication = $('startingBroadcast');
        header.myMovieLinkElement = $('myMovie');
        header.progressBarElement = $('progressBar');
        header.progressTimeElement = $('progressTime');

        var loggedDiv = document.getElementById("LoggedIn");
        if(loggedDiv)
        {
          header.loggedIn = true
        }
        else
        {
           header.loggedIn = false;
        }
        
        //forgot password initialization
         $('lgPhone').disabled = false;
         $('lgCountryCode').disabled = false;
         $('lgEmail').disabled = true;
        
        this.checkIfLive();
    },
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    checkIfLive: function()
    {
            var poster = new Ajax("/main/PollForLive", {method:'get', onComplete:function()
            {
                var livemovieElements = this.transport.responseXML.documentElement.getElementsByTagName("livemovie");

                if (header.liveCallback)
                {
                   header.liveCallback(livemovieElements);
				   
                } // End of if
				if(livemovieElements.length > 0)
				{
					header.generalLiveIndication.style.display = "";
				}
				else
				{
					header.generalLiveIndication.style.display = "none";
				}
                
                //header.DoLiveLogic(livemovieElements,myFlixIdElement,myEtaElement);
        }}).request();
        
        if(header.loggedIn)
        {
                var poster = new Ajax("/main/PollLiveUser", {method:'get', onComplete:function()
                {
                    var myFlixIdElements = this.transport.responseXML.documentElement.getElementsByTagName("flixid");
					
                    if(myFlixIdElements.length > 0)
                    {
                         var flixId = myFlixIdElements[0].firstChild.nodeValue; 
                         header.startingYourBroadcastIndication.style.display = "";
                         header.myMovieLinkElement.setAttribute("href","/watch/"+flixId);
                    }
                    else
                    {
                         header.startingYourBroadcastIndication.style.display = "none";
                    }
            }}).request();
        
        } // End of if user is logged in
        
        window.setTimeout(header.checkIfLive, 4000);

    },
    
     ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    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("/gate/LogOut", {method: 'get', onComplete:function(){
            //document.location.reload();
            document.location.href = "/";
        }}).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("/gate/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)
                    {
                        //debugger;
                        document.location.reload();
                    } else {
                        document.getElementById("authFailedBox").style.display = "";
                        frm.passwordText.select();
                    }
                } catch (e) {
                    alert(e.description);
                }
                flix.hideReloader(); // hide reloader
            }}).request();
        }
    },
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    // search tabs
    selectSearchType: function(searchReq,value) {
        // hide last showed panel
        header.searchReq = searchReq;
		document.getElementById('searchSelect').innerHTML=value;
		this.showSelect();
        //flix.hideIt(header.showIndex);
    },
	 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	//show the select menu
	showSelect : function() {
		if(document.getElementById('selectDropdown').style.display=='block')
        {
            document.getElementById('selectDropdown').style.display='none';
        }
		else
        {
            document.getElementById('selectDropdown').style.display='block';
            document.getElementById('selectDropdown').style.zIndex = 100;

        }
	},
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

	//hide the select menu
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    // 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;
        }
    },
        
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //--------------------------------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(show) {
		var logIn=document.getElementById('logInButt');
        var SignInDiv = document.getElementById("SignIn");
        if(show)
		{
			logIn.style.color="silver";
			logIn.style.cursor='default';
            SignInDiv.style.display = "block";
            SignInDiv.style.zIndex = 100;
            
			document.getElementById('LoginForm').usernameText.focus();
		}
        else
		{
			logIn.style.cursor='pointer';
			logIn.style.color="";
            SignInDiv.style.display = "none";
		}
        
    },
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    // 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;


    
    },
    onForgotPwdRadioMobileSelect: function()
    {
         header.radioPwdMail = false; 
         $('lgPhone').disabled = false;
         $('lgCountryCode').disabled = false;
         $('lgEmail').disabled = true;
    },
    onForgotPwdRadioMailSelect: function()
    {
         header.radioPwdMail = true; 
         $('lgPhone').disabled = true;
         $('lgCountryCode').disabled = true;
         $('lgEmail').disabled = false;
    },
    sendPass: function ()
    {
    	// Alon - Check if Email/Phone number are Recognized
    	if(header.radioPwdMail == true)
        {
            if($('lgEmail').value == "")
            {
                $('errors').innerHTML = 'Please enter your e-mail address.';
                header.errorsLB.show();
                return;
           }
        } // End of if
        else
        {
            if ($('lgCountryCode').selectedIndex == 0 || $('lgPhone').value == "")
            {
                $('errors').innerHTML = 'Please enter your phone number.';
                header.errorsLB.show();
                return;
            }
        }
        
        
        
        flix.showReloader('Updating...','update');
        if(header.radioPwdMail == true)
        {
            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 = "";
        
    }    
    
    
};
