
function DoSearch()
{
    var search_term = $('#search-textEntry').val();
    if (search_term == '')
    {
        alert('Please enter at least one search term');
    }
    else
    { 
        top.location.href = "/search.aspx?term=" + encodeURIComponent(search_term) + ""; 
    }
    
    return false;
}

function CheckSearchSubmit(e)
{ 
    var characterCode;
    
    if (e && e.which)
    { 
        characterCode = e.which; 
    }
    else
    {
        characterCode = e.keyCode; 
    }
    
    // Check if user hit the enter/return key
    if(characterCode == 13)
    {
        return DoSearch();
    }
    else
    { 
        return true;
    }       
}

function LoadImage(imgSrc, imgDiv, loadingDiv)
{
    var imgToLoad = new Image();
    
    $('#' + imgDiv).hide();
    if (loadingDiv.length > 0)
    {
        $('#' + loadingDiv).show();
    }
        
    $(imgToLoad).load
    (
        function () 
        {
            $('#' + imgDiv).attr('src', imgSrc);
            if (loadingDiv.length > 0)
            {
                $('#' + loadingDiv).hide();
            }
            $('#' + imgDiv).fadeIn(500);
        }
    )
    
    // if there was an error loading the image, react accordingly
    $(imgToLoad).error
    (
        function () 
        {
            // Need to handle load errors?
        }
    )
    
    // Set image source to load the physical image
    $(imgToLoad).attr('src', imgSrc);
}

function LoadHomepageWidget(storyUrl)
{
    var so = new SWFObject("http://assets.moviefill.com/swf/DFHeadline.swf", "DFHeadline", "300", "340", "8", "#FFFFFF");
    so.addParam("FlashVars", storyUrl); 
    so.addParam("allowScriptAccess", "sameDomain"); 
    so.addParam("allowFullScreen", "false");
    so.addParam("wmode", "Transparent");
    so.write("homepage-item-widget-container");
}

function LoadLogo()
{
    var s = "http://assets.moviefill.com/swf/logo_v2.swf";
    var so = new SWFObject(s, "logo", "328", "81", "9.0");
    so.addParam("scaleMode", "noscale");
    so.addParam("wmode", "transparent");
    so.addParam("allowscriptaccess", "always");
    so.write("flash-logo");
}

function OpenFT()
{
    $.ajax
    (
        {
            type: "POST",
            url: "/ajax/checkOpenToolbox.ashx",
            data: "",
            success: function(msg)
            {
                if (msg == '1')
                {        
                    $('#fixed-toolbar').slideDown(500);
                }  
            }
        }
    );    
}

function CloseFT()
{
    $('#fixed-toolbar').fadeOut(200);
    $('#footer').css({ 'margin-bottom' : '0px' });
    
    $.ajax
    (
        {
            type: "POST",
            url: "/ajax/setCloseToolbox.ashx",
            data: "",
            success: function(msg)
            {
            }
        }
    );
}

function ShowAddThis(caller, topOffset, topLink, leftOffset)
{
    if (!topLink)
    {
        topOffset = topOffset + $(window).scrollTop(); 
    }
    
    addthis_offset_top = topOffset;
    addthis_offset_left = leftOffset;
    return addthis_open(caller, 'email', '[URL]', '[TITLE]');
}

function SetHomepage()
{
    if (document.all)
    {
        document.body.style.behavior='url(#default#homepage)';
        document.body.setHomePage('http://www.moviefill.com');
    }
    else
    {
        if (window.sidebar)    
        {
            if(window.netscape)
            {
                try
                {
                    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
                }
                catch(e)
                {
                    alert("This action was avoided by your browser.  If you want to enable please enter about:config in your address line and change the value of signed.applets.codebase_principal_support to true");
                }
            }
            var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components. interfaces.nsIPrefBranch);
            prefs.setCharPref('browser.startup.homepage','http://www.moviefill.com');
        }
    }
}

function LoadGames()
{
    var gameList = $('#gameList').html();
    if (gameList.length > 10 && gameList.Length != "undefined" && gameList != null)
    {
        var jsonA = eval('(' + gameList + ')');  
        jQuery.each(jsonA, function()
        {
            LoadGame(this.divId, this.gameFeed);
        });
    }        
}

function LoadGame(divId, gameFeed)
{
    var so = new SWFObject("http://assets.moviefill.com/swf/questiongame5.swf", "QuestionGame", "300", "246", "8", "#FFFFFF");
    so.addParam("FlashVars", gameFeed);
    so.addParam("allowScriptAccess", "always"); 
    so.addParam("wmode", "Transparent");
    so.addParam("allowFullScreen", "false");
    so.write(divId);
}

// HEADER SEARCH AUTOCOMPLETE - start
function findValue(li) {
    return row[0];
}

function selectItem(li) {
	findValue(li);
}

function formatItem(row) {
    var dropdownHTML1 = '<span id="results-wrap"><img src="';
    var dropdownHTML2 = '" alt="" />';
    var dropdownHTML3 = '</span>';
	return "" + dropdownHTML1  +"" + row[1] + "" + dropdownHTML2  + "" + row[0] + "" + dropdownHTML3 + "";
}
// HEADER SEARCH AUTOCOMPLETE - end

function LoadSearchDropdown()
{
     // MODAL BOX POPUP
     $('.boxy').boxy({modal: true});
     
     // HEADER SEARCH AUTOCOMPLETE
     $("#search-textEntry").autocomplete("/celebjson.ashx",
		{   delay:10,
			minChars:2,
			matchSubset:1,
			matchContains:1,
			cacheLength:10,
			onItemSelect:selectItem,
			onFindValue:findValue,
			formatItem:formatItem,
			scrollHeight:400,
			autoFill:true
		}
	).result(function(event,row){location.href = row[3] + "";});
}

function EscapeString(OriginalString)
{                
    if(OriginalString.length > 0)
    {
        return OriginalString.replace(/'/g,"&#39;");
    }
    
    return OriginalString;     
}

function SignUpNewsletterSubmit() 
{
    if ($("#Email").val().length > 0) 
    {
        sUrl = "/services.asmx/SubscribeNewsletter";
        var jsonpostdata = "{";
        jsonpostdata += "Email:'" + EscapeString($("#Email").val()) + "'";              
        jsonpostdata += "}";
        $.ajax({
            url: sUrl,
            type: 'POST',
            data: jsonpostdata,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            timeout: 20000,
            error: function() {
                Boxy.get($("#SignUpNewsletter")).hide();
            },
            success: function(json) {
                Boxy.get($("#SignUpNewsletter")).hide();
            }
        });
    }
    else
    { 
        alert('Please enter your email address before submitting.'); 
    }
}

function LoadGlobalEvents()
{       
    $("#FooterNewsletterSignup").click(function(){ 
        if ($("#FooterNewsletterSignupEmail").val().length > 0) 
        {
            sUrl = "/services.asmx/SubscribeNewsletter";
            var jsonpostdata = "{";
            jsonpostdata += "Email:'" + EscapeString($("#FooterNewsletterSignupEmail").val()) + "'";              
            jsonpostdata += "}";
            $.ajax({
                url: sUrl,
                type: 'POST',
                data: jsonpostdata,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                timeout: 20000,
                error: function() {
                    document.getElementById("FooterNewsletterSignupStatus").innerHTML = "Error with your email address.";
                },
                success: function(json) {
                    document.getElementById("FooterNewsletterSignupStatus").innerHTML = "Thanks for signing up.";
                }
            });
        }
        else
        { 
            alert('Please enter your email address before submitting.'); 
        }
    });
}

function TrackGAEvent(category, action, label)
{                
    pageTracker._trackEvent(category, action, label);
}

function ToggleStats(stateId) {
    $('#ulStats_state1').hide();
    $('#ulStats_state2').hide();
    $('#ulStats_' + stateId).show();

    $('#top-articles').removeClass();
    $('#top-articles').addClass('' + stateId);
}

function DoTooltip(pX, pY, divId) {
    $('#' + divId).css({ left: pX + "px", top: pY + "px" });
    $('#' + divId).show();
}

// User methods - BEGIN

// Callbacks will be invoked after ajax calls to auth user, set these prior to calling the DoLogin() functions
var _loginSuccessCallback = null;
var _loginFailureCallback = null;
var _loginPopup = null;
var _loginFormVars = '';

function LoadCurrentUser() {
    var jsonStr = $('#currentUserJson').html();
    LoadUser(jsonStr);
}

function LoadAjaxUser() {
    $.ajax
    (
        {
            type: "POST",
            url: "/ajax/user/getCurrentUser.ashx",
            data: "",
            success: function(msg) {
                LoadUser(msg);
            }
        }
    );
}

function LoadUser(jsonStr) {
    _loggedIn = false;

    if (jsonStr.length > 0) {
        var create_json = "_currentUser = " + jsonStr;
        eval(create_json);

        if (_currentUser.Id > 0) {
            _loggedIn = true;
        }
    }
}

function DoFacebookLogin() {
    if (FB.Connect.get_loggedInUser() != null) {
        $.ajax
        (
            {
                type: "POST",
                url: "/ajax/user/facebookLogin.ashx",
                data: "",
                success: function(msg) {
                    if (msg == '1') {
                        DoPopupLoginSuccess();

                        if (_loginSuccessCallback) {
                            _loginSuccessCallback();
                        }
                    }
                    else {
                        if (_loginFailureCallback) {
                            _loginFailureCallback();
                        }
                    }
                }
            }
        );
    }
    else {
        if (_loginFailureCallback) {
            _loginFailureCallback();
        }
    }
}

function DoMyspaceLogin(newWindow, formVars) {
    var url = '/ajax/user/myspacelogin.aspx?' + formVars;
    if (newWindow == '1') {
        window.open(url);
    }
    else {
        window.location.href = url;
    }
}

function DoPopupLogin() {
    if (_loginPopup) {
        _loginPopup.show();
    }
    else {
        var loadingContent = $('#tempPopupLoginContainer').html();
        _loginPopup = new Boxy(loadingContent, { modal: true, closeable: true, closeText: "Close", title: "Login to DailyFill.com" });

        $.ajax
        (
            {
                type: "POST",
                url: "/ajax/user/popupLogin.aspx",
                data: "",
                success: function(msg) {
                    _loginPopup.setContent(msg);
                }
            }
        );
    }

    TrackGAEvent('User Login', 'Popup Login', 'Display');
}

function ClosePopupLogin() {
    if (_loginPopup) {
        _loginPopup.hide();
    }
}

function DoFbPopupLogin() {
    if (_loginSuccessCallback == null) {
        _loginSuccessCallback = DoPopupLoginSuccess;
    }
    DoFacebookLogin();
}

function DoPopupLoginSuccess() {
    ClosePopupLogin();
    SetUserHeader();
    LoadAjaxUser();
}

function DoMsPopupLogin() {
    if (_loginFormVars.length == 0) {
        _loginFormVars = 'redirectUrl=' + $('#tempPopupLoginRedirectUrl').html();
    }

    DoMyspaceLogin('0', _loginFormVars);
}

function DoDfPopupLogin() {
    var email = $('#modal-entry-un').val();
    var pw = $('#modal-entry-pw').val();

    $.ajax
    (
        {
            type: "POST",
            url: "/ajax/user/movieFillLogin.ashx",
            data: "e=" + email + "&p=" + pw,
            success: function(msg) {
                if (msg == '1') {
                    DoPopupLoginSuccess();

                    if (_loginSuccessCallback) {
                        _loginSuccessCallback();
                    }
                }
                else {
                    $('#modal-form-error').html('Invalid email and/or password.  Please try again.');
                    $('#modal-form-error').show();
                }
            }
        }
    );
}

function DoDfPopupForgotPw() {
    var email = $('#modal-entry-email').val();

    $.ajax
    (
        {
            type: "POST",
            url: "/ajax/user/forgotPassword.ashx",
            data: "e=" + email,
            success: function(msg) {
                if (msg == '1') {
                    $('#modal-form-error').html('<font color="#3f022d">Your password was delivered.  Please check your email.</font>');
                    $('#modal-form-error').show();
                    $('#btn-pw').hide();
                }
                else {
                    $('#modal-form-error').html('That email address was not found.  Please re-enter your email.');
                    $('#modal-form-error').show();
                }
            }
        }
    );
}

function SetUserHeader() {
    $.ajax
    (
        {
            type: "POST",
            url: "/ajax/user/getUserHeader.aspx",
            data: "",
            success: function(msg) {
                $('#user-links').html(msg);
            }
        }
    );
}

function DoHeaderLogout() {
    var userType = '' + $('#hiddenLogoutUserType').html();
    $('#user-links').html('Logging out...');
    var rUrl = '' + $('#tempPopupLoginRedirectUrl').html();

    $.ajax
    (
        {
            type: "POST",
            url: "/ajax/user/logout.ashx",
            data: "currentUrl=" + rUrl,
            success: function(msg) {
                rUrl = '' + msg;

                switch (userType) {
                    case '2':
                        DoFacebookLogout(rUrl);
                        break;
                    case '3':
                        DoMyspaceLogout(rUrl);
                        break;
                    default:
                        DoHeaderLogoutSuccess(rUrl);
                }
            }
        }
    );
}

function DoFacebookLogout(rUrl) {
    FB.Connect.logout
    (
        function() {
            DoHeaderLogoutSuccess(rUrl);
        }
    );
}

function DoMyspaceLogout(rUrl) {
    window.open('http://www.myspace.com/index.cfm?fuseaction=signout');
    DoHeaderLogoutSuccess(rUrl);
}

function DoHeaderLogoutSuccess(rUrl) {
    if (rUrl.length > 0) {
        window.location.href = rUrl;
    }
    else {
        SetUserHeader();
    }
}

function DoPopupLoginTab(tabId) {
    $('#modal-form-error').hide();
    $('#modal-title-forgot-pw').hide();
    $('#btn-pw').hide();
    $('#forgotpassword-login-link').hide();
    $('#modal-form-pw').hide();

    $('#modal-title-login').show();
    $('.modal-menu').show();

    // Site forms
    $('#modal-form-df').hide();
    $('#modal-form-fb').hide();
    $('#modal-form-ms').hide();
    $('#' + tabId).show();

    // Site buttons
    $('#modal-form-df-btn').removeClass("selected");
    $('#modal-form-fb-btn').removeClass("selected");
    $('#modal-form-ms-btn').removeClass("selected");
    $('#' + tabId + "-btn").addClass("selected");

    if (tabId == 'modal-form-df') {
        $('.modal-login-remember').show();
        $('#btn-login').show();
        $('#forgotpassword-pw-link').show();
    }
    else {
        $('.modal-login-remember').hide();
        $('#btn-login').hide();
        $('#forgotpassword-pw-link').hide();
    }

    TrackGAEvent('User Login', 'Popup Login Tab', tabId);
}

function DoPopupForgotPW() {
    $('#modal-form-error').hide();
    $('#modal-title-forgot-pw').show();
    $('#btn-pw').show();
    $('#forgotpassword-login-link').show();
    $('#modal-form-pw').show();

    $('#btn-login').hide();
    $('#modal-title-login').hide();
    $('#forgotpassword-pw-link').hide();
    $('.modal-menu').hide();
    $('.modal-login-remember').hide();
    $('#modal-form-df').hide();
    $('#modal-form-fb').hide();
    $('#modal-form-ms').hide();
}

function TrackUserSharing(shareType, shareObjectId) {
    $.ajax
    (
        {
            type: "POST",
            url: "/ajax/user/trackSharing.ashx",
            data: "type=" + shareType + "&id=" + shareObjectId,
            success: function(msg) {
            }
        }
    );
}

function UpdateFavCeleb(celebId, updateOption, callback) {
    $.ajax
    (
        {
            type: "POST",
            url: "/ajax/user/updateFavoriteCelebrity.ashx",
            data: "uo=" + updateOption + "&id=" + celebId,
            success: function(msg) {
                if (msg == '1') {
                    if (callback) {
                        callback();
                    }
                }
            }
        }
    );
}

function CommentPaging(pageNumber) {
    id = $('#contentId').val();
    divId = "#pageComment_" + pageNumber;


    $("#pagination").html(renderPaging(pageNumber, "CommentPaging"));
    $.ajax
        (
            {
                type: "POST",
                url: "/ajax/commentPaging.ashx",
                data: "id=" + id + "&pageNumber=" + pageNumber + "&hs=" + $('#hiddenPostHash').val(),
                success: function(msg) {
                    if (msg != '0') {
                        $('#commentsDisplay').html(msg);
                        
                    }
                }
            }

        );
}


function CelebrityCommentPaging(pageNumber) {
    id = $('#celebrityId').val();
    divId = "#pageComment_" + pageNumber;


    $("#pagination").html(renderPaging(pageNumber, "CelebrityCommentPaging"));
    $.ajax
        (
            {
                type: "POST",
                url: "/ajax/celebrityCommentPaging.ashx",
                data: "id=" + id + "&pageNumber=" + pageNumber + "&hs=" + $('#hiddenPostHash').val(),
                success: function(msg) {
                    if (msg != '0') {
                        $('#commentsDisplay').html(msg);
                    }
                }
            }

        );
}

var renderPaging = function(currentPage, onClickFunction) {
    var html = '';

    count = $('#count').val();
    var numberOfPages = 0;
    if (count > 0) {
        numberOfPages = Math.ceil(count / 30) ;
    }

    if (currentPage < 1) {
        currentPage = 1;
    }
    if (currentPage > numberOfPages) {
        currentPage = numberOfPages;
    }

    if (numberOfPages <= 1)
        html = ''
    else {
        var startIndex = currentPage - 2;
        if (startIndex < 1)
            startIndex = 1;
        endIndex = startIndex + 4;
        if (endIndex > numberOfPages) {
            endIndex = numberOfPages;
        }
        var nextIndex = endIndex + 3;
        if (nextIndex > numberOfPages) {
            nextIndex = numberOfPages;
        }

        if (startIndex > 1) {
            html = html + "<a href='#ajaxanchor' class='navlinkoff' onclick='javascript:" + onClickFunction + "(" + (currentPage - 3) + ")'>prev</a> ";
        }
        for (var i = startIndex; i < endIndex + 1; i++) {
            if (i == currentPage) {
                html = html + "<a href='#ajaxanchor' class='navlink'>" + i + "</a> ";
            } else {
                html = html + "<a href='#ajaxanchor' class='navlinkoff' onclick='javascript:" + onClickFunction + "(" + i + ")'>" + i + "</a> ";
            }
        }
        if (numberOfPages > endIndex) {
            html = html + "<a href='#ajaxanchor' class='navlinkoff' onclick='javascript:" + onClickFunction + "(" + (currentPage + 3) + ")'>next</a> ";
        }
    }

    return html;
}


function CommentSubmit() {
    if (_loggedIn) {
        DoPostComment();
    }
    else {
        DoPopupLogin();
    }
}

function DoPostComment() {
    comment = escape($('#CommentTxt').val());
    count = $('#count').val();
    id = $('#contentId').val();
    name = escape($('#contentName').val());
    url = encodeURIComponent($('#contentUrl').val());
    ip = $('#ip').val();
    userName = escape($('#userName').val());
    userEmail = EscapeString($('#userEmail').val());

    dataString = "commentText=" + comment + "&id=" + id + "&name=" + name + "&url=" + url + "&userName=" + userName + "&userEmail=" + userEmail + "&hs=" + $('#hiddenPostHash').val() + "&ip=" + ip;
    
    if ($('#guid').length > 0) {
        guid = $('#guid').val();
        captcha = $('#challengeText').val();
        dataString = "commentText=" + comment + "&id=" + id + "&name=" + name + "&url=" + url + "&userName=" + userName + "&userEmail=" + userEmail + "&hs=" + $('#hiddenPostHash').val() + "&ip=" + ip + "&guid=" + guid + "&challengeText=" + captcha;
    }

    $.ajax
    (
        {
            type: "POST",
            url: "/ajax/addComment.ashx",
            data: dataString,
            success: function(msg) {
                if (msg != '0') {
                    if (msg.toString().indexOf("input type=\"hidden\" name=\"guid\" id=\"guid\"") > 0) {
                        $('#displayCaptcha').html(msg);
                        $('#commentError').hide();
                    }
                    else {
                        newCount = count * 1 + 1;
                        oldDisplay = $('#commentsDisplay').html();
                        $('#commentCount').html("Comments (" + newCount + ")");
                        $('#commentsDisplay').html(msg + oldDisplay);
                        $('#count').val(newCount);
                        $('#CommentTxt').val('');
                        $('#displayCaptcha').html('');
                        $('#commentError').hide();
                    }
                }
                else {
                    $('#commentError').show();
                }
            }
        }

    );
}

function CelebrityCommentSubmit() {
    if (_loggedIn) {
        DoCelebrityPostComment();
    }
    else {
        DoPopupLogin();
    }
}

function DoCelebrityPostComment() {
    comment = escape($('#CommentTxt').val());
    count = $('#count').val();
    id = $('#celebrityId').val();
    name = escape($('#contentName').val());
    url = encodeURIComponent($('#contentUrl').val());
    ip = $('#ip').val();
    userName = escape($('#userName').val());
    userEmail = EscapeString($('#userEmail').val());

    dataString = "commentText=" + comment + "&id=" + id + "&name=" + name + "&url=" + url + "&userName=" + userName + "&userEmail=" + userEmail + "&hs=" + $('#hiddenPostHash').val() + "&ip=" + ip;

    if ($('#guid').length > 0) {
        guid = $('#guid').val();
        captcha = $('#challengeText').val();
        dataString = "commentText=" + comment + "&id=" + id + "&name=" + name + "&url=" + url + "&userName=" + userName + "&userEmail=" + userEmail + "&hs=" + $('#hiddenPostHash').val() + "&ip=" + ip + "&guid=" + guid + "&challengeText=" + captcha;
    }
    
    $.ajax
    (
        {
            type: "POST",
            url: "/ajax/addCelebrityComment.ashx",
            data: dataString,
            success: function(msg) {
                if (msg != '0') {
                    if (msg.toString().indexOf("input type=\"hidden\" name=\"guid\" id=\"guid\"") > 0) {
                        $('#displayCaptcha').html(msg);
                        $('#commentError').hide();
                    }
                    else {
                        newCount = count * 1 + 1;
                        oldDisplay = $('#commentsDisplay').html();
                        $('#commentCount').html("Comments (" + newCount + ")");
                        $('#commentsDisplay').html(msg + oldDisplay);
                        $('#count').val(newCount);
                        $('#CommentTxt').val('');
                        $('#displayCaptcha').html('');
                        $('#commentError').hide();
                    }
                }
                else {
                    $('#commentError').show();
                }
            }
        }

    );
}


function CommentSetUserValue(userName, userEmail) {
    $('#userName').val(userName);
    $('#userEmail').val(userEmail);
}


