var $jqr = jQuery.noConflict();
var loading = "<img src='/images/ajax-loader.gif'>";

$jqr(document).ready(function() {
    $jqr("#logout_user").live('click', function(e){
        logoutUser();
    });

    $jqr('#post_comment').live('click', function(e){
        processComment();
    });

    $jqr('#login_form').live('submit',function(e){
        loginGUser();
    });

    $jqr('#fb_wall_publish').live('click', function(e){
        showStream();
    });

});

//this is called whenever a user does not have gizmag session variables set
//checks if they have a valid fb token, and logs them in automatically if so
function checkFBUser(){
    var article = $jqr('#comment_form').attr('data-article');

    FB.getLoginStatus(function(response) {

        if (response.status === 'connected') {

            $jqr.ajax({
                url:'/login_comments.php',
                type: 'post',       
                data: { article: article, action: 'fb_connect'},
                dataType: 'json',
                success: function(json){

                    if(json.type='success'){
                        $jqr('#comment_form').html(json.message);
                        FB.XFBML.parse(document.getElementById('comment_form'));
                    } 

                }
            });


        } else if (response.status === 'not_authorized') {
            // the user is logged in to Facebook, but not connected to the app
        } else {
        // the user isn't even logged in to Facebook.

        }
    });

};


function loginGUser(){

  var article   = $jqr('#comment_form').attr('data-article');
  var email     = $jqr('#email').val();
  var password  = $jqr('#password').val();
  var comment   = $jqr('#expired_comment').val();
  
  $jqr('#user_status').remove();          //clear any error messages for the user

  $jqr.ajax({
        url:'/login_comments.php',
        type: 'post',
        data: { article: article, email: email, password: password, action: 'login_g_user'},
        dataType: 'json',
        success: function(json){

            if(json.type=='success'){
                $jqr('#comment_form').html(json.message);//display the comment form
                $jqr('#comment_input').val(comment);    //fill textarea if there is an expired comment
                FB.XFBML.parse(document.getElementById('comment_form'));
            } else if(json.message=='auth') {
                show_activation_modal(email);
            } else {
                $jqr('#comment_form_div').prepend("<div id='user_status'><em>"+json.message+"</em></div>");   //displaay session timeout msg to user
            }

        },

        //Ajax Error Handling
        error: function(){
            $jqr('#comment_form_div').prepend("<div id='user_status'><em>We could not log you in at this moment. Please try again shortly.</em></div>");   //displaay session timeout msg to user
        }
    });


}

//executes after FB Log In button is pressed, logs user in and generates comment form
function loginFUser(article) {
    var comment   = $jqr('#expired_comment').val();
    
    $jqr('#facebook_login').append(loading);

    FB.getLoginStatus(function(response) {
        if (response.authResponse) {
       
            $jqr.ajax({
                url:'/login_comments.php',
                type: 'post',
                data: { article: article, action: 'fb_connect'},
                dataType: 'json',
                success: function(json){

                    if(json.type='success'){

                        $jqr('#comment_form').html(json.message);//display the comment form
                        $jqr('#user_status').remove();           //remove any messages for the user
                        $jqr('#comment_input').val(comment);     //fill textarea if there is an expired comment
                        FB.XFBML.parse(document.getElementById('comment_form'));

                    } else {
                        $jqr('#user_status').html(json.message);//display login error message to user
                    }
                },

                //Ajax Error Handling
                error: function(data, textStatus, errorThrown){
                    ajax_error(data, textStatus, errorThrown);
                }
            });
        }
    });
};



//kills session variables and displays login form
function logoutUser(){

    var article = $jqr('#comment_form').attr('data-article');
    var comment = $jqr('#comment_input').val();           //grab expired comment if exists

    $jqr.ajax({
        url:'/login_comments.php',
        type: 'post',      
        data: { article: article, action: 'logout_user'},
        dataType: 'json',
        success: function(json){

            if(json.type=='success'){
                $jqr('#comment_form').html(json.message);
                $jqr('#expired_comment').val(comment);     //save expired comment to hidden field
                FB.XFBML.parse(document.getElementById('comment_form'));
            } 

        }
    });


};




function processComment(){
    
    var article   = $jqr('#comment_form').attr('data-article');
    var comment   = $jqr("#comment_form textarea").val();

    if(comment=='') { $jqr('#comment_submit').prepend('<em>Please enter a comment</em><br/>'); return false; }

    $jqr('#comment_submit').html(loading);  //replace post comment button with loading gif

    $jqr.ajax({
        url:'/login_comments.php',
        type: 'post',      
        data: { article: article, comment:comment, action: 'process_comment'},
        dataType: 'json',
        success: function(json){
            
            if(json.type=='success'){
                //all good, simply manipulate the display
                $jqr('#comment_input').hide();                              //hide the textarea
                $jqr('#comment_result').html('<em>'+json.message+'</em>');  //show confirmation to user
                FB.XFBML.parse(document.getElementById('comment_form'));    //reparse the XFBML

            } else {

                if(typeof(json.html) !== 'undefined'){  //session has expired

                    FB.getLoginStatus(function(response) {  //check if it was a facebook user

                    if (response.authResponse) {
                        //completely disconnect from facebook and regenerate the login form
                        FB.logout(function(response){   
                            FB.XFBML.parse(document.getElementById('facebook_login'));
                        });
                    //otherwise simply regenerate login form
                    } else logoutUser();

                });
                    
                    $jqr('#comment_form_div').prepend("<div id='user_status'><em>"+json.message+"</em></div>");   //displaay session timeout msg to user

                } else { //error processing comment
                    $jqr('#comment_result').html('<em>'+json.message+'</em>'); //tell user there was an error, we have been notified
                }

                
            }

        },

        //Ajax Error Handling
        error: function(){
            $jqr('#comment_result').html('<em>We could not process your comment at this moment. Please try again shortly.</em>');
        }
    });
   
    

}

//stream publish method
function streamPublish(name, description, title, link, pic_url){
    FB.ui(
    {
        method: 'feed',
        name: title,
        link: link,        
        picture: pic_url,
        description: description
    },
    function(response) {
        return true;
    });

}
function showStream(){
    var article   = $jqr('#comment_form').attr('data-article');

    $jqr.ajax({
        url:'/login_comments.php',
        type: 'post',
        data: { article: article, action: 'article_details_fb'},
        dataType: 'json',
        success: function(json){
            if(json.type=='success'){
                FB.api('/me', function(response) {
                    streamPublish(response.name, json.message.ar_summary, json.message.ar_title, json.message.ar_link, json.message.pic_url);
                });
                
            } else {
                $jqr('#comment_form .blueLinks').html('<em>'+json.message+'</em>'); //tell user there was an error
            }
        },

        //Ajax Error Handling
        error: function(){
            $jqr('#comment_result').html('<em>We could not send this information to Facebook at this time. Please try again shortly.</em>');
        }
    });

    return false;
    
    
}


function show_activation_modal(email){ //show moodal window telling them to activate subscription
    
    var container_exists = $jqr('#activation_msg').length;
    
    if(!container_exists){  //if this is the first time seeing this msg
        
        var activation_modal = build_activation_modal(email);
        
        $jqr('#comment_form_div').append('<div id="activation_msg" class="jqmWindow">'+activation_modal+'</div>');
        $jqr('#activation_msg').jqm();                  //attach jqModal window to this div
    }
    
    $jqr('#activation_msg').jqmShow();                  //show the modal window
    
}

//build the html string to display in the modal window
function build_activation_modal(email){
    
    //building long html strings is yucky but not too bad here because its not complex
    var activation_modal = '<div class=\"overlay_inner\"><div class=\"overlay_content\">';
        activation_modal+= '<h1>This account is not active</h1>';
        activation_modal+='<p>When you first registered, an activation email was sent to your email address verify your account. </p>';
        activation_modal+='<p>Please follow the link in this email before you log in. </p>';
        activation_modal+='<p><span class=\"link\" onClick=\"sndReqArg(\'send_activation_email\', \''+email+'\')\">Click here to re-send the activation email</span>.</p>';
        activation_modal+='<div id=\"result\"></div>';
        activation_modal+='</div></div>';
        
    return activation_modal;
}
