jQuery(document).ready(
    function(){		
        function populateContentPopup(content)
        {
            jQuery('#reg-flow').html(content);
            bindEvents();
        }
        user_status = {};
        function updateUserStatus(afterStatusUpdateFunction)
        {
            var current_url = document.location.toString();
            jQuery.getJSON('/ajax/user/status/', {'targetForCallbacks': current_url}, function(data){
                user_status = data;
                if (data.redirect_to != false)
                {
                    document.location = data.redirect_to;
                }
                renderAppropriateContent(user_status);
                if (user_status.msostatus.authenticated == true)
                {
                    jQuery('#psr-invite').fadeIn('slow');
                }
                if (typeof(afterStatusUpdateFunction) == 'function')
                {
                    afterStatusUpdateFunction();
                }
				if(user_status.msostatus.couponStatus == true)
                {
                    $('.body_header .brand-logo img').attr('src','http://content.epixhd.com/styleassets/logo2.png');
					$('.body_header').css('padding-bottom','15px');
                }
				setRecMovies(false);
				if (user_status.loggedin == true){
					updateGenreCounts();
					//updateTotalCounts(current_url);
    				if (csa_movie_id) intMovieRecs();
					refreshUserOptions ();					
				}
            });
        }
		
		function updateTotalCounts(myUrl){
			if((myUrl.match('mediacom.epixhd.com')) || (myUrl.match('www.epixhd.com'))){
            	jQuery.getJSON('/ajax/user-movie-count/',function(response){
                	totalMovies = response.count;
                	if(totalMovies >= 1)   {      
						$('span.movies-count').html(totalMovies);
               		}  
            	});
			}
		}
		
		function refreshUserOptions(){
            if (csa_movie_id){
				var mId = csa_movie_id.split('movie_')[1];
				$.getJSON('/ajax/myqueue/check/'+mId+'/',function(data){
					if(data.success){
						if(data.inqueue){
							$('#queue').attr('href','#remove');
							$('#queue img').attr('src','http://content.epixhd.com/styleassets/in-queue.gif');
						}
						else {
							$('#queue').attr('href','#add');
							$('#queue img').attr('src','http://content.epixhd.com/styleassets/add-to-queue.gif');
						}
						$('#queue-wrap').attr('style','display:block');
						$('#tv-header').addClass('button-wrap').css('padding','10px 0 4px');
					}
					else $('#queue-wrap').hide();
				});
				
				//get the state and update the button
    			$.getJSON('/ajax/ilikeit/check/'+mId+'/', function(data) {
					if (data.success){
						if(data.liked) {
							$('#ilikemovie img').attr('src', 'http://content.epixhd.com/styleassets/like-button-active.gif');
				    	} else{
							$('#ilikemovie img').attr('src', 'http://content.epixhd.com/styleassets/like-button-inactive.gif');
				   		}
						$('.like').attr('style','display:block');
					}
					else $('.like').hide();
				});
				
				bindEvents();
			}
		}
		
		function updateGenreCounts(){	
			//update all genre counts in the movie tab
			jQuery.getJSON('/ajax/movies-by-genre/movies_tab-genres_list/',function(response){
				//alert(response);
				gData1 = response.content;
				$('#movieTab .genres').html('<h3>By Genres</h3>'+gData1);
				$('.movies-tab-genre-count').show();
			});
		/*	
			//update all genre counts on the homepage
			if($('.watch-movies-content').length){
				jQuery.getJSON('/ajax/movies-by-genre/movies_tab-genres_list/9;18;2;1;4;24;5;46;3;30/',function(response){
					//alert(response);
					gData2 = response.content;
					jQuery('.watch-movies-content #genres .genres-list').html(gData2);
				});
			}
			*/
		}
		/*
		function setRecMovies(moviesTab){
			var cookieID = readCookie('__utma');
			var movies = new csRR ("c04468d5f8c13767", "home_page");
			var movie = new csRR ("c04468d5f8c13767", "product_detail");		
			if(user_status.msostatus.user_id != undefined){
				movies.setParameter("user_id", user_status.msostatus.user_id);		
				movie.setParameter("user_id", user_status.msostatus.user_id);
			}				
			
			//movie tab
			if(moviesTab){
				movies.setParameter("cookie_id", cookieID); // 1st party cookie, 1+ yr expiration
				movies.addRecoDisplayRequest("csa_mv", {"appcontext": "Movies", "choice_set_filter": "epix_rating <= 100"});
				movies.send();	
			}
			
			//both movie detail and private screening room				
			movie.setParameter("cookie_id", cookieID); // 1st party cookie, 1+ yr expiration
			
			var current_url = document.location.toString();					
			
			if(setMovieRecs){
				if(!current_url.match('/private_screening/')){		 //movie page only
					movie.addRecoDisplayRequest("csa_mv_sub",  {"appcontext": "Movie Detail", "choice_set_filter": "epix_rating <= 100"});
				}
				movie.addItem(csa_movie_id); // movie ID  	
				movie.send();
			}
		}*/
		
        function resizeTab()
        {
            if (jQuery('#dropdown').queue('fx').length == 0)
                jQuery('#dropdown:visible').animate({height: jQuery('#tab_me').height()}, 'swing');
        }
        function refreshPlayer()
        {
            if (jQuery('#playerContainer') != undefined)
            {
                var current_movie = jQuery('#epixmovieshortname').val();
                if (current_movie != "" && current_movie != undefined)
                {
                    jQuery.getJSON('/ajax/getplayer/' + current_movie + '/',function(response){
                        jQuery('#playerContainer').html(response.content);
                        bindEvents();
                    });
                }
            }
        }
    
    function getUrlVars()
    {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
     
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
     
        return vars;
    }
	
        function renderAppropriateContent(userstatus)
        {
            //this will retrieve any unread messages from server
            getUnreadMessages();
			vars = getUrlVars();
            jQuery.getJSON('/ajax/user/presence/',function(response){
                jQuery('#userpresence').html(response.content);
				if (vars['signup'] != undefined){
					gShowSignUp()
				}	
                bindEvents();
            });
            refreshPlayer();	
			
			//if logged in, reveal me-tab
			if(userstatus.loggedin == true){
				$('li.me-bar').removeClass('hidden');
				$('li.me').removeClass('hidden');
			}else{
				$('li.me-bar').addClass('hidden');
				$('li.me').addClass('hidden');
			}
        }
        function unbindEvents()
        {
            jQuery('a.showsignup').unbind('click');
            jQuery('a.showsignin').unbind('click');
            jQuery('#reg-flow #epixtv-mso select').unbind('change');
            jQuery('#reg-flow #epixtv-mso a').unbind('click');
            jQuery('#reg-flow form').unbind('submit');
			$('#reg-flow #forgotpassword').unbind('click');
			$('.poster-overlay a#selectprovider').unbind('click');
			$('#queue').unbind('click');
			$('#ilikemovie').unbind('click');
        }
        
		function showSignUp(){
                jQuery.getJSON('/ajax/chooseMSO/',function(response){
                    populateContentPopup(response.content);
                    $('#reg-flow-wrap').show();
                    $('#reg-flow-wrap').toggleClass('hidden');
                    $('#reg-flow-wrap').css('left','-100px');
                    jQuery('#reg-flow #epixtv-mso a.invite-code').click( function () {
                    	jQuery('#reg-flow #epixtv-mso').hide();
                    	jQuery('#reg-flow #epixtv-invite').show();
                    	return false;
					});

		});
		}
		gShowSignUp = showSignUp;
        function bindEvents(){
            unbindEvents();
            // bind the bubble contents
            $(document.body).click(function() {
                if(!$('#reg-flow-wrap').hasClass('hidden')) {
                    $('#reg-flow-wrap').addClass('hidden');
                    $('#cntnt01user_email').val('').blur();
                    $('#cntnt01user_password').val('').blur();
                }
				var current_url = document.location.toString();
                if (current_url.match('/channel/schedule/')) {
					$('#searchPage #scheduleslider').css('z-index',0)
				}
				$('#playerContainer').css('z-index',3)
				
            });
			
			$('#queue').click(function(){
				var mId = csa_movie_id.split('movie_')[1];
				$('#queue').attr('style','opacity:.5; display:block;');
				if(this.hash == '#add') action = 'add';
				else action = 'delete';
				$.getJSON('/ajax/myqueue/'+action+'/'+mId+'/',function(data){
					if(data.inqueue) {    
						$('#queue').attr('href','#remove');
						$('#queue img').attr('src','http://content.epixhd.com/styleassets/in-queue.gif');
					}
					else {
						$('#queue').attr('href','#add');
						$('#queue img').attr('src','http://content.epixhd.com/styleassets/add-to-queue.gif');
					}
					$('#queue').attr('style','opacity:1; display:block;');
				});
				return false;
			});
			
			$("#ilikemovie").click(function () {
				var mId = csa_movie_id.split('movie_')[1];
				$.getJSON('/ajax/ilikeit/like/'+mId+'/', function(data) {
				   if (data.success && data.liked) {		   
						$('#ilikemovie img').attr('src', 'http://content.epixhd.com/styleassets/like-button-active.gif');
				   } else {		   
						$('#ilikemovie img').attr('src', 'http://content.epixhd.com/styleassets/like-button-inactive.gif');
				   }
				});
			});
			
        
            $('#reg-flow-wrap').click(function(event) {
                event.stopPropagation();
            });
        
            $('#cntnt01user_email').live('blur', function(){
                if ($('#cntnt01user_email').attr("value") == "")
                    $('#cntnt01user_email').attr("value", "Email Address");
            });
        
            $('#cntnt01user_email').live('focus', function(){
                if ($("#cntnt01user_email").attr("value") == "Email Address")
                    $("#cntnt01user_email").attr("value", "");
            });	
			
            $('#temp_password').live('focus', function(){
                $("#temp_password").hide();
				$("#pwd-input").show();
                $("#cntnt01user_password").focus();
            });
        
            $('#cntnt01user_password').live('blur', function(){
                if ($('#cntnt01user_password').attr("value") == ""){
                	$("#temp_password").show();
                    $('#pwd-input').hide();
				}
            });
        
// signup bubbles
            jQuery('a.showsignin').click(function(){
				$('.poster-overlay').css('display', 'none');
				var current_url = document.location.toString();
                if (current_url.match('/channel/schedule/')) {
					$('#searchPage #scheduleslider').css('z-index',-10)
				}
				$('#playerContainer').css('z-index',-1)
                jQuery.getJSON('/ajax/user/login/form/',function(response){
                    populateContentPopup(response.content);
                    
                        $('#reg-flow-wrap').show();
                        $('#reg-flow-wrap').toggleClass('hidden');
                        $('#reg-flow-wrap').css('left','-50px');
                    bindEvents();
                });
                return false;
            });
            jQuery('a.showsignup').click(function(){
				$('.poster-overlay').css('display', 'none');
				var current_url = document.location.toString();
                if (current_url.match('/channel/schedule/')) {
					$('#searchPage #scheduleslider').css('z-index',-10)
				}
				$('#playerContainer').css('z-index',-1)
                jQuery.getJSON('/ajax/chooseMSO/',function(response){
                    populateContentPopup(response.content);
                        $('#reg-flow-wrap').show();
                        $('#reg-flow-wrap').toggleClass('hidden');
                        $('#reg-flow-wrap').css('left','-100px');
                        jQuery('#reg-flow #epixtv-mso a.invite-code').click( function () {
                                jQuery('#reg-flow #epixtv-mso').hide();
                                jQuery('#reg-flow #epixtv-invite').show();
                                return false;
                            }
                        );
                    bindEvents();
                });
                return false;
            });
			
			$('#reg-flow .sign-in select').change(function(){
				if(this.value != 0)
					document.location = '/epixprofile/?tvpid='+this.value;
				else {
					$('#epix-sign-in').fadeIn();
					$('#general-sign-in').hide();
				}
			});
			
			$('#psr-sign-in select').change(function(){
				if(this.value != 0)
					document.location = '/epixprofile/?tvpid='+this.value;
				else {
					$('#psr-epix-sign-in').fadeIn();
					$('#psr-sign-in').hide();
				}
			});
            
            jQuery('#reg-flow .sign-in form').submit(
                function(){
                    jQuery.getJSON(
                    //'https://secure.epixhd.com/?jsoncallback=?',
                    '/?jsoncallback=?',
                    jQuery('#reg-flow .sign-in form').serialize(),
                    function(response){
                        // authme
                        if (response.success != false )
                        {
                            jQuery.post('/ajax/user/auth/',{'cntnt01otk':response.otk},
                                function(data){
                                if (data.success == true )
                                {
                                    if (data.redirect_to != false)
                                    {
                                        document.location = data.redirect_to;
                                    } else {
                                        if(!$('#reg-flow-wrap').hasClass('hidden')) {
                                            $('#reg-flow-wrap').addClass('hidden');
                                            $('#cntnt01user_email').val('').blur();
                                            $('#cntnt01user_password').val('').blur();
                                        }
                                           // 
                                        var current_url = document.location.toString();
                                        if (current_url.match('/epixprofile')) {
                                            // refresh the page
											document.location = '/epixprofile';
                                        }
										else {										
											//reload the page
											//location.reload(true);
											updateUserStatus();
										}
                                    }
                                    if (typeof(action_loginSuccessful) == 'function')
                                    {
                                        action_loginSuccessful();
                                    }
                                } else {
                                    populateContentPopup(data.content);
                                }
                            },
                            'json');
                        } else {
                            jQuery('#error_msg').html(response.error_message);
                            jQuery('#error_msg').show();
                            bindEvents();
                        }
                    }, "jsonp");
                    return false;
                }
            );
			
            $('#reg-flow #epixtv-mso select').change(function(){
            	document.location = '/epixprofile?tvpid=' + jQuery('#reg-flow #renderMSOProcessForm form select').val();
            });
			
            jQuery('#reg-flow #renderMSOProcessForm form').submit( function(){
               if($('#cntnt01coupon').val() != '')
                   jQuery.post('/ajax/chooseMSO/',{'coupon':$('#cntnt01coupon').val()},function(response){
                   if (response.success == true && response.authenticated == true)
                   {
                       document.location = '/epixprofile?invite_code=' + jQuery('#reg-flow #renderMSOProcessForm form input[type=text]').val();
                       //populateContent('<h1>'+response.status_msg+'</h1>',true);
                   } else {
                       $('#error_msg').html(response.error_msg);
                       $('#error_msg').show();
                   }
               });
               else {
                   $('#error_msg').html('Please enter an invite code');
                   $('#error_msg').show();
               }
               return false;
            });
			
            jQuery('#reg-flow #epixtv-mso a#invite-code').click( function () {
                    jQuery('#reg-flow #epixtv-mso').hide();
                    jQuery('#reg-flow #epixtv-invite').show();
                    return false;
                }
            );
            
            jQuery('#reg-flow #forgotpassword').click(
                function(){
                    jQuery.getJSON(
                        '/ajax/user/forgotpassword/',
                        function(response){
                            populateContentPopup(response.content);
                            bindEvents();
                        }
                    );
                return false;
                }
            );
            
            jQuery('#reg-flow #forgottenpassword form').submit(
                function(e){
					$('#reg-flow #forgottenpassword form input:last').attr({disabled:'true',style:'color:#a1a1a1;'});
                    jQuery.post(
                    '/',
                    jQuery('#reg-flow #forgottenpassword form').serialize(),
                    function(data){
                        if (data.success == true )
                        {
                            jQuery('#reg-flow').html(data.content);
                            setTimeout(function(){
                                jQuery.getJSON('/ajax/user/login/form/',function(response){
                                    populateContentPopup(response.content);
                                        $('#reg-flow-wrap').show();
                                        $('#reg-flow-wrap').toggleClass('hidden');
                                        $('#reg-flow-wrap').css('left','-50px');
                                });
                            },5000);
                        } else {
                            populateContentPopup(data.content);
                        }
                    }, "json");
                return false;
                }
            );
            
        //resend confirm
        jQuery('#reg-flow a#resendconfirm').click(
            function(){
                jQuery.getJSON('/ajax/user/resendconfirm/',function(response){
                    populateContentPopup(response.content);
                });
                return false;
            }
        );
        jQuery('#reg-flow #resendconfirm form').submit(
            function(){
                jQuery.post(
                '/',
                jQuery('#reg-flow #resendconfirm form').serialize(),
                function(data){
                    if (data.success == true )
                    {
                        populateContentPopup(data.content);
                        setTimeout(function(){
                            jQuery.getJSON('/ajax/user/loginregisterform/',function(response){
                                populateContentPopup(response.content);
                            });
                        },5000);
                    } else {
                        populateContentPopup(data.content);
                    }
                }, 
                "json");
                return false;
            }
        );
        
        jQuery('#reg-flow #remote-logout form').submit(
            function(){
                jQuery.post(
                '/',
                jQuery('#reg-flow #remote-logout form').serialize(),
                function(data){
                    if (data.success == true )
                    {
                        populateContentPopup(data.content);
                        setTimeout(function(){
                            updateUserStatus();
                        },5000);
                    } else {
                        populateContentPopup(data.content);
                    }
                }, "json");
            return false;
            }
        );
        jQuery('#reg-flow a#logmeout').click(
            function(){
                jQuery.getJSON('/ajax/user/remotelogout/',function(response){
                    populateContentPopup(response.content);
                });
                return false;
            }
        );
        jQuery('#reg-flow a#cancel-edit').click(
            function(){
                jQuery.getJSON('/ajax/user/login/form/',function(response){
                    populateContentPopup(response.content);
                        $('#reg-flow-wrap').show();
                        $('#reg-flow-wrap').toggleClass('hidden');
                        $('#reg-flow-wrap').css('left','-50px');
                    bindEvents();
                });
                return false;
            }
        );
        
        /* close button functionality for login/signup popup */            
		$(function() {
		$('a.close-logsign-popup').click(function(){
					jQuery('#reg-flow-wrap').addClass('hidden');
		           return false;
		            });
		});

		
		$('.poster-overlay a#selectprovider').click(function(){
			document.location = '/epixprofile/?editsub=1';															 
			return false;
		});
    };
    
    updateUserStatus();
    // additional 
	function intMovieRecs() {
		var current_url = document.location.toString();
		var hasFired = 0;
        jQuery(document).everyTime( '20s', 'isplaying',
            function() {
                var el = document.getElementById('solo_view');// || document.getElementById('screener');
					if (el) {
					 var value = el.getPosition();
					 if (value > 10) {
					  // record that the video has played
					  var current_movie = jQuery('#epixmovieshortname').val();
					  jQuery.post('/ajax/user/update/', {'movie':current_movie,'event':'watching'});
					 }
					 
					 if ((value > 600) && (hasFired === 0)){
					  var movie_watch = new csRR ("c04468d5f8c13767", "order_confirmation");
					
					  if(user_status.msostatus.user_id != undefined){
					   movie_watch.setParameter("user_id", user_status.msostatus.user_id);
					  }                           
					  var cookieID = readCookie('__utma');                        
					  var purchaseID = readCookie('__utmb');
					
					  movie_watch.setParameter("cookie_id", cookieID);
					  movie_watch.setParameter("purchase_id", purchaseID); // unique identifier of this playing of a video
					  movie_watch.addItem(csa_movie_id, {"unit_price": "0.00", "quantity": "1"}); // movie ID
					  movie_watch.send(); // this is the only item that needs to be sent after the time limit
					  hasFired = 1;
					 }
					}
            }, 0, true
        );
		if(!current_url.match('/private_screening/')){
			prevPosition = -1;
			isPaused = 0;
			anim = 1;
			fadeFirst = 1;
			jQuery(document).everyTime( '2s', 'isPaused',
				function() {
					if (document.getElementById('solo_view') != undefined){
						var value = document.getElementById('solo_view').getPosition();
						if (value > 0){
							currentPosition = document.getElementById('solo_view').getPosition();
							if (currentPosition == prevPosition){
								 if(anim == 1){
									//$('#playerContainer').animate({left:100},1000,function(){$('#csa_mv_sub').fadeIn();});
									$('#csa_mv_sub').fadeIn();
									anim = 0;	
									}					
								isPaused = 1;
							}
							else { 
								isPaused = 0; 
								if((anim == 0) || (fadeFirst)){
									$('#csa_mv_sub').fadeOut();
									//$('#playerContainer').animate({left:0},1000);
									anim = 1;	
									fadeFirst = 0;
								}
							}
							prevPosition = currentPosition;
						}
					}
				}, 0, true
			);
		}
	}    	
});

function setRecMovies(moviesTab){
	var cookieID = readCookie('__utma');
	var movies = new csRR ("c04468d5f8c13767", "home_page");
	var movie = new csRR ("c04468d5f8c13767", "product_detail");		
	if(user_status.msostatus.user_id != undefined){
		movies.setParameter("user_id", user_status.msostatus.user_id);		
		movie.setParameter("user_id", user_status.msostatus.user_id);
	}				
	
	//movie tab
	if(moviesTab){
		movies.setParameter("cookie_id", cookieID); // 1st party cookie, 1+ yr expiration			
			if($.inArray('ALL MEGAPLEX MOVIES', user_status.msostatus.productGroups))
				movies.addRecoDisplayRequest("csa_mv", {"appcontext": "Movies", "choice_set_filter": "epix_rating <= 100"});
			else
				movies.addRecoDisplayRequest("csa_mv", {"appcontext": "Movies", "choice_set_filter": "epix_rating <= 100", 'choice_set_filter': 'epix_movie_type == "epix"'});
		movies.send();	
	}
	
	//both movie detail and private screening room				
	movie.setParameter("cookie_id", cookieID); // 1st party cookie, 1+ yr expiration
	
	var current_url = document.location.toString();					
		
	if(setMovieRecs){
		if(!current_url.match('/private_screening/')){		 //movie page only			
			if($.inArray('ALL MEGAPLEX MOVIES', user_status.msostatus.productGroups))
				movie.addRecoDisplayRequest("csa_mv_sub", {"appcontext": "Movies", "choice_set_filter": "epix_rating <= 100"});
			else
				movie.addRecoDisplayRequest("csa_mv_sub", {"appcontext": "Movies", "choice_set_filter": "epix_rating <= 100", 'choice_set_filter': 'epix_movie_type == "epix"'});
		}
		movie.addItem(csa_movie_id); // movie ID  	
		movie.send();
		setMovieRecs = false;
	}
}

function UFPageType() {
    var myURL = document.location.toString();
    var path = "";
    path = myURL.split(".com/")[1];
    if (path == "" || path.split("#")[0] == "" ) 
        return "";
    if (path.match("extras/") )
        return "extras/";
    return path.split("/")[0] + "/";
}
             
function UFLogEvent(item_title, item_id) 
{
    var item_url = '/'+UFPageType()+'#video_'+ item_id;
    jQuery.post('/ajax/user/update/', {'title': item_title,'event':'videoextra', 'url': item_url});
}
