$.fn.addCloseAuthorizeWindowHandler = function(){
    $("#twitter-connect-authorized").each(function(){
        window.opener.location = $(this).attr("rel");
        window.close();
    });//end each
}//end addCloseAuthorizeWindowHandler();

$.fn.addTwitterConnectHandler = function(){
    $(".twitterSignIn").click(function(e){
        e.preventDefault();
        
        //authorize
        window.open("/account/connect-twitter", "twitter", "status=0,toolbar=0,menubar=0,resizable=0,width=900,height=500,modal=yes,dependent=yes,alwaysRaised=yes,scrolling=no");
    });
}//end addTwitterConnectHandler()

// signUpForm
$.fn.authorizeAccount = function(){
    var options = {
        trigger : [ 'none', 'none' ],
        beforeSubmit : showRequest, // pre-submit callback
            success : showResponse,
            url : '/ajax/citizen-profile/authorize-account' // override for form's
    };
	
    // pre-submit callback
    function showRequest(formData, jqForm, options) {
        var queryString = $.param(formData);
        if($('#authorizeAccount').validate().form()){
            $('#authorizeAccount').mask('Saving...');
            return true;
        }else{
            return false;
        }
    }
		
    // post-submit callback
    function showResponse(responseText, statusText, xhr, $form) {
        var response = eval('(' + responseText + ')');
	
        if(response.success) {
            $('#messageBox .success').html('Account successfully linked. Logging you in now...').slideDown();
            setTimeout(function(){
                window.location = response.url;
            }, 2000);
				
            return;
        }else{
            $('#authorizeAccount').unmask();
            $('#messageBox .error').html(response.message).slideDown();
        }	
    }
		
    // set the form to be an ajax form
    return this.each(function() {
        $(this).ajaxForm(options);
    });
	
};

$(function(){
    $.fn.addTwitterConnectHandler();
    $.fn.addCloseAuthorizeWindowHandler();
    
    // prep form for ajax form
    $('#authorizeAccount').authorizeAccount();
});
