var dimmed = false;

var tabs = {
    active:	'',
    ids:	['movies']
};
var arrow_index = -1;

function dimlights() {
	if (dimmed == false) {
		$('#overlay').css("display", "block").fadeTo("slow", 0.7);
		$('div.body_header').removeClass('ie-zindex');
		dimmed = true;
	} else {
		$('#overlay').fadeTo("slow", 1.0).css("display", "none");
		$('div.body_header').addClass('ie-zindex');
		dimmed = false;
	}
}

function setCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

$(document).ready(function() {
    // Hidden divs to allow screen readers and lacking JS browsers to still have content (thought it may be a bad viewing experience)
    $('.accessible').each(
        function(i) {
        $(this).removeClass('accessible');
        }
    );

    //$('#all_watchable').nyroModal();
    //$('#requestEpixModal').nyroModal();

    // If the user clicks on the tab ul...
	var set = true;
    $('ul.nav .movies').click(function(event) {
		if(set){
			setRecMovies(true);
			set = false;
		}
        var clicked = $(event.target);
        if(clicked.attr('href')) {
            clicked = clicked.parent();
        }
        var clazz = clicked.attr('class').replace(/ ?active/, '');
        if (clazz == 'logo') {
            return true;
        }

        var tab = $('#tab_'+clazz);

        // If we clicked on a button that has a corresponding tab...
        if(tab.length != 0) {
            $('ul.nav li').removeClass('active');
			clicked.addClass('active');
            //clicked.css({'background-color': ($(".curtain .moviepage").length == 0)?'':'#000'}).addClass('active');

            // Switch to the right tab
            for(var x=0; x<tabs.ids.length; x++) {
                var id = tabs.ids[x];
                var correspondingTab = $('#tab_'+id);
                if(clazz == id) {
                    correspondingTab.fadeIn('slow');
                } else {
                    correspondingTab.css('display', 'none');
                    $('ul.nav li.'+id).css({'height':''});
                }
            }

            // Tween the dropdown to the height of the corresponding tab, or hide it
            if(tabs.active == '') {
                $('#dropdown')
                    .css({display: 'block', 'height':0})
                    .animate({height: tab.height()}, 'swing');
                tabs.active = clazz;
                var tb_height = "center "+tab.height()+"px";
                if(!$('body').hasClass('page')) {
                    $('body')
                        .css({backgroundPosition: '50% 0'})
                        .animate({backgroundPosition: '(50% '+tab.height()+'px)'});
                }
            } else if(tabs.active == clazz) {
                $('#dropdown').animate({height: '0px'}, 1000, function() {
                    $('#dropdown').css('display', 'none');
                    $('ul.nav li.'+clazz).css({'height':''});
                    clicked.removeClass('active');
                });
                tabs.active = '';
                if(!$('body').hasClass('page')) {
                    $('body')
                        .animate({backgroundPosition: '(50% 0)'}, 1000);
                }
            } else {
                $('#dropdown').animate({height: tab.height()}, {duration:1000}, 'swing');
                tabs.active = clazz;
                $('.curtain')
                    .animate({backgroundPosition: '(50% '+tab.height()+'px)'}, 1000);
            }
        }
    }); //click event

    var sub_email = $('#subscribe_email');
    if(sub_email) {
        sub_email.val('Email Address');
        autoClearTf(sub_email);
    }
    $("#subscribe_form .btn").click(function(event) {
        event.preventDefault();
        var data = {
            email:$('#subscribe_email').attr('value')
        };
        $.post('/subscribe', data, function(response) {
            if(response.success) {
                $("#subscribe_form").html('<span>Your email has been added to the invite list. You may hear from us shortly!</span>').css('display', 'none').fadeIn('slow');
            } else {
                $("#subscribe_form .errors").html(response['errors']).css('display', 'none').fadeIn('slow');
            }
        }, 'json');
    })
    $("#subscribe_form").submit(function(event){event.preventDefault();});

    autoClearTf($('#login_username'));
    autoClearTf($('#login_email'));
    // Login form
    $('#login_form .close').click(function() {
                      $('#login_form').css({'display':'none'});
                      $('#login_border').css({'display':'none'});
                      });

    $("#login_form .btn").click(
        function(event) {
        event.preventDefault();
        var data = {
            'username':$('#login_username').attr('value'),
            'password':$('#login_password').attr('value')
        };

        $.get('/authenticate', data, function(response) {
              if(response.authenticated) {
                  window.location.reload();
              } else {
                  $("#login_form .errors").html(response.error);
              }
            }, 'json');
        }
    );
    if($('#login_div')) {
		/*
        // Facebook connnect
        //<div id="authenticated">Logged in as <fb:name uid="" capitalize="true"></fb:name><span id="login_btn" /></div>
        //$('#login_div').html('<div id="fb_connect"><fb:login-button size="medium" onlogin="facebookLogin();"></fb:login-button> / <a href="#" id="sign_in_btn">sign in</a></div>');
        //	'<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script>');

        //FB_RequireFeatures(["XFBML"], function(){
            //FB.Facebook.init(API_KEYS.Facebook.key, API_KEYS.Facebook.callback_url);
            //FB.Connect.ifUserConnected(facebookLogin);
        //});

        //document.getElementById('login_btn').innerHTML = 'Logged in as <fb:name uid="24403821" capitalize="true"></fb:name> <a href="#" id="logout">Logout</a>';*/
		
        $('#sign_in_btn').click(function() {
                    $('#login_form').css({'display':'block'});
                    $('#login_border').css({'display':'block'});
                    });
    }


    // SEARCH FUNCTIONALITY
	var current_url = document.location.toString();
	$('#search').submit(function(){
    	if(!current_url.match('/search/query/')) {
			document.location = '/search/query/#&freetext='+$("#q").val();
		}
		return false;
	});
	$("#q").blur(function(event){
        if ($("#q").attr("value") == "") {
            $("#q").attr("value", "search epix");
        }
    });
    $("#q").focus(function(event) {
        if ($("#q").attr("value") == "search epix") {
            $("#q").attr("value", "");
        }
	});
	/*
    $(document.body).click(function() {
        if(!$('#search_results').hasClass('hidden')) {
            $('#search_results').addClass('hidden');
            $('#q').val('').blur();
        }
    });
    
    $("#search_results, #search").click(function(event) {
        event.stopPropagation();
    });
    
    $("#q").blur(function(event){
        if ($("#q").attr("value") == "") {
            $("#q").attr("value", "search epix movies");
						if ( !document.addEventListener ) {
							$('#playerContainer').css({ position: 'relative' });	
						}
        }
    });
    $("#q").focus(function(event) {
        if ($("#q").attr("value") == "search epix movies") {
            $("#q").attr("value", "");
						if ( !document.addEventListener ) {
							$('#playerContainer').css({ position: 'static' });
						}
        }
		*/
	//close any open tabs
	if (tabs.active != '') {
	    click_tab(tabs.active);
	}

   
    $("#login_email").blur(function(event){
        if ($("#login_email").attr("value") == "") {
            $("#login_email").attr("value", "EMAIL ADDRESS");
        }
    });
    $("#login_email").focus(function(event) {
        if ($("#login_email").attr("value") == "EMAIL ADDRESS") {
            $("#login_email").attr("value", "");
        }
    });
    /*
    
    $("#i_zip").blur (function(event) {
    
        $("#zip_err").css({"display":"none"});
    
        // Once a user a enters a zip code and focus is away from the zip input, 
        // an ajax call, calls the server side getStateFromZip function
        // returns two letter state abbr
        $.ajax({
            url: "/getStateFromZip",
            data: $("#i_zip").serialize(),
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                showStateErr();
            },
            success: function (data) {
                var sub = data.slice(data.indexOf("STATE>"),data.length);
                if (sub.length > 1) {
                    var state = sub.substr(sub.indexOf(">")+1,2);
                    $("#i_state").val(state);
                } else {
                    showStateErr();
                }
            },
            timeout:5000,
            type: "POST"
        });
    });
    $("#search").keyup(function(event) {
        if ((event.keyCode != 27 && ((event.keyCode >= 97 && event.keyCode <= 122) || (event.keyCode >= 65 && event.keyCode <= 90) || (event.keyCode == 8) || event.keyCode == 46))
                    && ($("#q").val().length > 2)) {

            // Get matching results from the server
            $.getJSON('/ajax/search/' + $("#q").val() + '/',  function(data) {
                arrow_index = -1;
                var pos = $("#search").position();
                $("#search_results").css({top: '40px',left: '-60px'}).removeClass('hidden');
                $("#search_results #search-show-all").attr('checked', true);
                var len = data.length;
                var body = $("#search_results .body").html('');
                if (len > 0) {
                    // Build our result set
                    var ul = $('<ul></ul>');
                    for (var i=0; i < len; i++) {
                        var o = data[i];
                        var watch = o.watchable;
                        if(o.thumb) {
                            $('<li class="lint '+i+(watch ? ' watchable' : '')+'"><div class="search-poster"><a href="'+o.target+'"><img src="'+o.thumb+'" alt="'+o.title+'" /></a></div><div class="search_info">'+
                                '<img src="http://content.epixhd.com/styleassets/search-epix-logo.png" width="33" height="14" />'
								+'<h1>'+o.title+'</h1>'
                                +'<p>'+(o.synopsis ? (o.synopsis.length > 100 ? o.synopsis.substring(0,100) : o.synopsis ) : 'No synopsis stored for this movie')+'</p>'
                                +(watch == true ? '<div class="watch"><a href="'+o.target+'">Watch Now</a></div>' : '<span>&raquo; See Extras</span>')
                                +'<input type="hidden" value="'+o.target+'" />'
                                +'</div></li>')
                                .click(goToMovie)
                                .hover(function() {
                                    var me = $(this);
                                    if(me.hasClass('lint')) {
                                        if(arrow_index != -1) {
                                            $($('.body ul').children()[arrow_index]).removeClass('hover');
                                        }
                                        arrow_index = $('li').index(this) - 4;
                                    }
                                })
                                .appendTo(ul)
                        }
                    }
                    ul.appendTo(body);

                    // Resize and hide scrollbars depending on how many results come back
                    //$("#search_results .body").jScrollPaneRemove();
                    if(len <= 3) {
                        ul.parent().css({height:(140 * len)+'px', 'overflow':'hidden'});
                    } else {
                        $("#search_results .body").css({'height':'520px', 'overflow-y':'scroll', 'overflow-x':'hidden'});//.jScrollPane({showArrows:true, scrollbarWidth:11, arrowSize:1});
                    }
                    ul.addClass('');	// Fix for IE bug where margins don't show up till you hover on the element. Go on, try removing it!
                } else {
                    //$("#search_results .body").jScrollPaneRemove();
                    $("#search_results .body").css({'height':'30px', 'overflow':'hidden'}).html('<span class="no_dice">No movies found</span>');
                }
            }, "JSON");
            return false;
        } else if (event.keyCode == 27) {
            $("#search_results").addClass("hidden");
            $(event.target).val('').blur();
        }
    }).submit(function() {
        return false;
    }).keydown(function(event){
        var ul = $('.body ul');
        var kids = ul.children();
        if(!kids.length || (event.keyCode != 38 && event.keyCode != 40 && event.keyCode != 13)) {
            return;
        }
        var current = $(kids[arrow_index]);
        current.removeClass('hover');

        if (event.keyCode == 38) {// Up Arrow key pressed
            arrow_index--;
        } else if (event.keyCode == 40) {// Down Arrow key pressed
            arrow_index++;
        } else if (event.keyCode == 13) { // Return key pressed - will only redirect to a movie if one has been selected
            current_selected_search = current.find('input');
            if (typeof(current_selected_search.val()) != 'undefined')
            {
                window.location = '/search/'+current_selected_search.val()+'/';
            }
        }
        if(arrow_index < 0) {
            arrow_index = kids.length - 1;
        } else if(arrow_index >= kids.length) {
            arrow_index = 0;
        }
        var current = $(kids[arrow_index]);
        if(kids.length > 3) {
            $("#search_results .body")[0].scrollTo('.'+arrow_index);
        }
        current.addClass('hover');
    });
    //clock();
    
    // some stuff for handling urls (with anchors)
    var current_url = document.location.toString();
    if (current_url.match('#')) { // the URL contains an anchor
        // click the navigation item corresponding to the anchor
        var myAnchor = '#' + current_url.split('#')[1];
        // check the anchor against all 
       /* if (myAnchor == '#me_tab')
        {
            click_tab('me');
        } else //
        if (myAnchor == '#movies_tab')
        {
            click_tab('movies');
        } else 
        if (myAnchor == '#plus_tab')
        {
            click_tab('plus');
        } 
    }*/
    
    jQuery(document).everyTime( '200s',
        function() {
            jQuery.get('/ajax/user/refresh/','json');
        }, 
        0, true
    );
});

function showStateErr() {
    $("#zip_err").css({"display":"block"});
    $("#zip_err").text("We're sorry your state could not be	retrieved. Please enter the two letter abbreviation.");
}

// Find the a tag of the movie we clicked on and go to it
function goToMovie(event) {
    var element = $(event.target);
    if(!element.hasClass('lint')) {
        element = element.parent();
    }
    window.location = element.find('input').attr('value');
}

function facebookLogin() {
    FB.ensureInit(function() {
        var api = FB.Facebook.apiClient;
        //alert(api.get_session());
        if(api.get_session()) {
            api.requireLogin(function(exception) {
                $('#login_div').html('<div id="authenticated">Logged in as <fb:name uid="'+api.get_session().uid+'" capitalize="true" useyou="false"></fb:name>'+
                    '<fb:profile-pic uid=loggedinuser facebook-logo=true></fb:profile-pic><a href="#" id="fb_logout">Logout</a>');
                $('#fb_logout').click(function() {
                    FB.Connect.logoutAndRedirect('/');
                });

                FB.XFBML.Host.parseDomTree();
                //console.log("Current user id is " + api.get_session().uid);

                // Get friends list
                api.friends_get(null, function(result){
                //console.log(result);
                });
            });
        }
    });
}

function autoClearTf(elements) {
    if(elements || elements.length) {
        for(var x=0; x<elements.length; x++) {
            var element = $(elements[x]);
            clearTf(element);
        }
    }
}

function clearTf(element) {
    var original = element.val();
    element.focus(function() {
        if(element.val() == original) {
            element.attr('value', '');
        }
    });
    element.blur(function() {
        if(element.val() == '') {
            element.attr('value', original);
        }
    });
}

function showNavSection (section) {
        // Shows the specified dropdown menu
        var tab_classname = "."+section;
        var tab_id = "#tab_"+section;
        $(tab_classname).css({'height':'58px', 'background-color': ($(".curtain .moviepage").length == 0)?'#B8B6B7':'#000'});
        $(tab_classname).addClass('active');
        var tab = $(tab_id);
        $('#dropdown').css({'display': 'block', 'height':0});
        $('#dropdown').animate({'height': tab.height()}, 'swing');
        tab.css('display','block');
}

// Checks if user is at /me or /movies
// note: me_on and movies_on are defined on frame_body.tal
/*if (plus_on) {
    // if user at /plus, the "plus" nav dropdown is set to show
    showNavSection("plus");
}

if (me_on) {
    // if user at /me, the "me" nav dropdown is set to show
    showNavSection("me");
}*/

if (movies_on) {
    // if user at /movies, the "movies" nav dropdown is set to show
    showNavSection("movies");
}

function clock() {	
    if ($('#countdown').length > 0) {
        var countdownDate = (startDate ? startDate.getTime() : 0);

        if (countdownDate) {
            var todayDate = new Date().getTime();
            if (!(countdownDate - todayDate <= 0)) {
                var timeDiff = ((countdownDate - todayDate) / 1000);
                var days = Math.floor((timeDiff) / (60*60*24)).toString();
                var hours = Math.floor((timeDiff/3600) % 24).toString();
                var minutes = Math.floor((timeDiff/60) % 60).toString();
                var seconds = Math.floor((timeDiff/1) % 60).toString();
                $('#days').html((days.length == 1) ? '0' + days : days);
                $('#hours').html((hours.length == 1) ? '0' + hours : hours);
                $('#minutes').html((minutes.length == 2) ? minutes : '0' + minutes);
                $('#seconds').html((seconds.length == 2) ? seconds : '0' + seconds);
                setTimeout('clock()', 1000);
            }
        }
    }
}

function click_tab(tab_to_toggle) {
    var clicked = $('ul.nav li.' + tab_to_toggle);
    var clazz = tab_to_toggle;
    var tab = $('#tab_'+clazz);

    // If we clicked on a button that has a corresponding tab...
    if(tab.length != 0) {
        $('ul.nav li').removeClass('active');
        clicked.css({'background-color': ($(".curtain .moviepage").length == 0)?'':'#000'}).addClass('active');

        // Switch to the right tab
        for(var x=0; x<tabs.ids.length; x++) {
            var id = tabs.ids[x];
            var correspondingTab = $('#tab_'+id);
            if(clazz == id) {
                correspondingTab.fadeIn('slow');
            } else {
                correspondingTab.css('display', 'none');
                $('ul.nav li.'+id).css({'height':''});
            }
        }

        // Tween the dropdown to the height of the corresponding tab, or hide it
        if(tabs.active == '') {
            $('#dropdown')
                .css({display: 'block', 'height':0})
                .animate({height: tab.height()}, 'swing');
            tabs.active = clazz;
            var tb_height = "center "+tab.height()+"px";
            if(!$('body').hasClass('page')) {
                $('body')
                    .css({backgroundPosition: '50% 0'})
                    .animate({backgroundPosition: '(50% '+tab.height()+'px)'});
            }
        } else if(tabs.active == clazz) {
            $('#dropdown').animate({height: '0px'}, 1000, function() {
                $('#dropdown').css('display', 'none');
                $('ul.nav li.'+clazz).css({'height':''});
                clicked.removeClass('active');
            });
            tabs.active = '';
            if(!$('body').hasClass('page')) {
                $('body')
                    .animate({backgroundPosition: '(50% 0)'}, 1000);
            }
        } else {
            $('#dropdown').animate({height: tab.height()}, {duration:1000}, 'swing');
            tabs.active = clazz;
            $('.curtain')
                .animate({backgroundPosition: '(50% '+tab.height()+'px)'}, 1000);
        }
    }
    return false;
}

function getUnreadMessages() {

    jQuery.getJSON('/ajax/getUnreadMessages/', function(data){

        var messages = data;

        var str ='';

	var strLI='';
        for (var i = 0; i < messages.msgError.length; i++) strLI += '<li>'+messages.msgError[i].msg+'</li>';
	if (strLI.length>0) str+='<ul class="msgError">'+strLI+'</ul>';
        
        strLI='';
	for (var i = 0; i < messages.msgWarning.length; i++) strLI += '<li>'+messages.msgWarning[i].msg+'</li>';
        if (strLI.length>0) str+='<ul class="msgWarning">'+strLI+'</ul>';

        strLI='';
        for (var i = 0; i < messages.msgInfo.length; i++) strLI += '<li>'+messages.msgInfo[i].msg+'</li>';
        if (strLI.length>0) str+='<ul class="msgInfo">'+strLI+'</ul>';

        //alert(str);
       // jQuery('#messagearea').html(str);
    });
}
/*
jQuery(document).oneTime( '15s',
    function() {
        $('#messagearea ul:last').fadeOut('slow', function() {
            $(this).remove();
        }).oneTime( '5s',
        function() {
            $('#messagearea ul:last').fadeOut('slow', function() {
                $(this).remove();
            }).oneTime( '5s',
            function() {
                $('#messagearea ul:last').fadeOut('slow', function() {
                    $(this).remove();
                });
            });
        });
    }
);*/
