function processAjaxDialogData(containerId, data){

    $('#' + containerId).html(data);
    Cufon.replace(".dialog-cufonize");
    
    $(".dialog-form :input:visible:enabled:first").focus();
}


function showAjaxDialog(dialogId, containerId, url, width, height, loaded_callback){

    width = typeof(width) != 'undefined' ? width : 500;
    height = typeof(height) != 'undefined' ? height : 250;
    
    outHeight = height + 2;
    outWidth = width + 2;
    windowHeight = $(window).height();
    windowWidth = $(window).width();

    if (height > windowHeight) {
        outHeight = windowHeight-60;
    }
    
    if (width > windowWidth) {
        outWidth = windowWidth;
    }
    
    $("#" + dialogId).modal({
        opacity: 60,
        overlayCss: {
            background: '#000'
        },
        onShow: function (dlg) {
            $(dlg.wrap).css('overflow', 'auto');
        },
        minWidth: outWidth,
        minHeight: outHeight
    });

    $("#" + containerId).html("<div id='dialog_loading'><div class='dialog-loading' style='width:" + (outWidth - 24) + "px; height:" + (outHeight - 6) + "px; overflow: auto;'>&nbsp;</div></div>");

    $.ajax({
        type: "GET",
        url: url,
        success: function(data, status, request){
            if (data.match("^Location")) {
                old_location = window.location.pathname;
                new_location = data.replace("Location: ", "");
                window.location = new_location;
                
                if (new_location.indexOf(old_location) == 0 &&
                new_location.indexOf("#") != -1) {
                    window.location.reload(true);
                }
            }
            else {
                processAjaxDialogData(containerId, data);
                if (typeof(loaded_callback) != 'undefined' && loaded_callback !== null) {
                    loaded_callback();
                }
            }
        }
    });
    return false;
}

function ajaxDialogSubmit(url, formId, containerId){
    $.ajax({
        type: "POST",
        url: url,
        data: $("#" + formId).serialize(),
        success: function(data, status, request){
            if (data.match("^Location")) {
                old_location = window.location.pathname;
                new_location = data.replace("Location: ", "");
                window.location = new_location;

                if (new_location.indexOf(old_location) == 0 &&
                new_location.indexOf("#") != -1) {
                    window.location.reload(true);
                }
            }
            else {
                processAjaxDialogData(containerId, data);
            }
        }
    });
    height = $("#" + containerId).height();
    width = $("#" + containerId).width();
    $("#" + containerId).html("<center><div style='width:" + width + "px; height:" + height + "px' class='dialog-loading'>&nbsp;</div></center>");
    
    return false;
}

function showConfirmDialog(title, message, url, width, height){
    width = typeof(width) != 'undefined' ? width : 300;
    height = typeof(height) != 'undefined' ? height : 150;
    
    $("#confirm_dialog").modal({
        opacity: 60,
        overlayCss: {
            background: '#000'
        },
        minWidth: width,
        minHeight: height,
        onShow: function(dialog){
            $('#confirm_title', dialog.data[0]).html(title);
            $('#confirm_message', dialog.data[0]).html(message);
            
            Cufon.replace("#confirm_title");
            
            // if the user clicks "yes"
            $('#confirm_yes', dialog.data[0]).click(function(){
                ajaxDialogSubmit(url, "confirm_form", "confirm_container");
                // the return stmt was stopping redirects
                //return false;
            });
        }
    });
    
    return false;
}

function ajaxInlineUpdate(url, formData, loadingDivId, successDivId, errorDivId){
    $("#" + successDivId).hide();
    $("#" + errorDivId).hide();
    $("#" + loadingDivId).show();
    $.ajax({
        type: "POST",
        url: url,
        data: formData,
        success: function(data, status, request){
            if (data.match("^Location")) {
                window.location = data.replace("Location: ", "");
            }
            else {
                $("#" + loadingDivId).hide();
                $("#" + successDivId).show();
            }
        },
        error: function(request, status, error){
            $("#" + loadingDivId).hide();
            $("#" + errorDivId).show();
        }
    });
}

function paginatorClick(form_id, pageNum){
    $("#page_index").attr("value", pageNum);
    $("#" + form_id).submit();
}

function toggleCheckboxes(source_selector, dest_name_prefix){
    new_value = $(source_selector).attr("checked");
    $("input[name*='" + dest_name_prefix + "']").attr("checked", new_value);
}

function _showLoginDialog(redirect, error) {
    var finishedCallback = null;

    if(error) {
        finishedCallback = function() {
            $("#login_form .errors").html(error);
        };
    }

    showAjaxDialog(
        "login_dialog", "login_container", "/login?redirect=" + redirect,
        500, 250, finishedCallback
    );
}



// This function attempts to log the user in if they are logged into a supported
// external authentication backend, such as Facebook, and if that fails, then it
// shows the native login modal.
function showLoginDialog(redirect) {
    redirect = window.location.protocol + "//" +
        window.location.host + getRealRedirect(redirect);

    // If Facebook auth fails, show the native login dialog. In the future we
    // could extend this to support, e.g., Twitter logins, with a chain of
    // nextAuthMethod callbacks.
    nextAuthMethod = function() {
        _showLoginDialog(redirect);
    };

    loginFacebook(redirect, nextAuthMethod);
    return false;
}

// Hide all divs except 'show_id' in 'container_id' 
function filterContainer(container_id, show_id){
    if (show_id === null) {
        $("#" + container_id + " > div").show();
    }
    else {
        $("#" + container_id + " > div").hide();
        $("#" + show_id).show();
    }
    
    return false;
}

var facebookInitialized = false;
function initFacebook() {
    if (!facebookInitialized) {
        try {
            FB.init({
                appId: FACEBOOK_APP_ID,
                status: true,
                cookie: true,
                xfbml: true,
                oauth: true
            });

            facebookInitialized = true;
        } catch(e) {
            // Pass.
        }
    }
}

// Prepend a Facebook API command with an initialization step. 'tryLogin'
// will attempt to log the user in before running the command, and only run
// the command if login succeeded. On success we'll get an authResponse value.
//
// For more details on the response and authResponse values, see:
// https://developers.facebook.com/blog/post/525/
function facebookDo(doFunc, tryLogin) {
    initFacebook();
    params = { scope: 'email' };
    if (tryLogin) {
        FB.login(function(response) {
            // If the user is authenticated with Facebook and has authorized our
            // site, then the response will contain an 'authResponse' value.
            if (response.authResponse) {
                doFunc(response);
            }
        }, params);
    }
    else {
        FB.getLoginStatus(function(response) {
            // The Facebook response contains the status of the user's FB
            // authenticateion.
            if (response) {
                doFunc(response);
            }
        }, params);
    }
}

// Notify our server that the Facebook user logged in. The server responds
// with 'OK' if a matching UserProfile was found for the Facebook user ID.
// Will call errCallback if login failed.
function doFacebookLogin(response, redirect, errCallback) {
    if(response.authResponse) {
        $.ajax({
            // XXX: If this call is async, the user won't be authenticated
            // properly in Chrome.
            async: false,
            url: "/facebook_login",
            success: function(data, status, request) {
                if (data == "OK") {
                    window.location = redirect;
                } else if (errCallback) {
                    errCallback(data, status, request);
                }
            }
        });
    }
}

function createAccountFacebook() {
    facebookDo(function() {
        window.location = "/user_reg?use_facebook=1";
    }, true);
}

/**
 * Attempt to log the user in with Facebook.
 *
 * This function can be called as part of the automatic login process or as a
 * user-initiated action, such as clicking the "Log in with Facebook" button.
 *
 * If this is an automatic login and we couldn't find a Facebook account, or the
 * user isn't logged into Facebook, then try the next authentication method.
 *
 * If the user initiated login, but we can't find an account, then display the
 * native login dialog with an form error.
 */
function loginFacebook(redirect, nextAuthMethod) {
    // This is a user-initiated action if we didn't get a nextAuthMethod to try.
    userInitiated = (nextAuthMethod === undefined);

    var loginError = "Your Facebook account is not associated with a Catchafire " +
                      "account. Please login using your Catchafire credentials or " +
                      "create a new account.";
    initFacebook();

    function tryFacebookLogin(response) {
        if (response.authResponse) {
            var loginErrorCallback = null;

            // If login failed and this was a user-initiated Facebook login,
            // show the login dialog with an error message. Otherwise try the
            // next authentication mechanism.
            if(userInitiated) {
                loginErrorCallback = function() {
                    _showLoginDialog(redirect, loginError);
                };
            } else if(nextAuthMethod) {
                loginErrorCallback = nextAuthMethod;
            }

            doFacebookLogin(response, redirect, loginErrorCallback);
        } else {
            // Try the next authentication method.
            nextAuthMethod();
        }
    }

    facebookDo(tryFacebookLogin, userInitiated);
}

function shareLinkFacebook(options) {
    facebookDo(function() {
        // calling the API ...
        var obj = {
          method: 'feed'
        };

        $.extend(obj, options);

        FB.ui(obj);
    }, true);
}


function shareHolidayNomination() {
    var logo_url = 'http://' + window.location.hostname +
        '/media/perm/images/logo_notext.png';

    var description = 'Every professional that registers on Catchafire ' +
        'between 12/1/2011 and 1/31/2012 can nominate an organization ' +
        'of their choice to win $2012.00. http://bit.ly/urMOjP';

    shareLinkFacebook({
      link: 'http://blog.catchafire.org/2011/12/07/catchafire-2012-holiday-campaign/',
      picture: logo_url,
      name: 'Catchafire Holiday Campaign',
      caption: "Give what you're good at this holiday season",
      description: description
    });
}

function renderProfileLink(linkData) {

    var newDiv = $("#profile-link-prototype").clone();
    var id_string = 'profile-link-' + linkData.id;
    
    newDiv.attr('id', id_string);
    
    newDiv.find('.profile-link-edit-type').html(linkData.title);
    newDiv.find('.profile-link-edit-url').html(linkData.url);
    
    $('#profile-links-edit-container').append(newDiv);
    
    newDiv.show();
    
    Cufon.replace('#' + id_string + ' h3.profile-link-edit-type');
    
}

function renderProfileLinks(linkArray){
    for (var index in linkArray) {
        renderProfileLink(linkArray[index]);
    }
}

function toggleHelp(help_type){
    $("#" + help_type + "_help").toggle();
    $("#" + help_type + "_show_help").toggle();
    
    ajaxInlineUpdate("/help_pref/" + help_type + "/" + ($("#" + help_type + "_help").is(":visible") ? "1" : "0"), {}, "a", "a", "a");
    
    return false;
}

function getRealRedirect(redirect){
    switch (redirect) {
        case "/":
        case "/user_reg_done":
        case "/verify_email":
            return "/dashboard";
        default:
            return redirect;
    }
}

function getInternetExplorerVersion(){
    var rv = -1; // Return value assumes failure.
    if (navigator.appName == 'Microsoft Internet Explorer') {
        var ua = navigator.userAgent;
        var re = new RegExp("MSIE ([0-9]{1,}[\\.0-9]{0,})");
        if (re.exec(ua) != null) {
            rv = parseFloat(RegExp.$1);
        }
    }
    return rv;
}


(function(){
    // capture all errors and dispatch to /jserror/ view

    var prevOnError = window.onerror;

    window.onerror = function(errorMsg, url, lineNumber){
        if (typeof(jQuery) != 'undefined') {
            jQuery.ajax({
                url : '/jserror/',
                type : 'POST',
                data : {
                    message : errorMsg,
                    url : url,
                    lineNumber : lineNumber,
                    browser : navigator.appName,
                    userAgent : navigator.userAgent
                }
            });
            if (prevOnError) {
                return prevOnError(errorMsg, url, lineNumber);
            }
            return false;
        }
    }
})();

