$.fn.stars = function() {
    $(this).each(function() {
        // Get the value
        var val = parseFloat($(this).html());
        // Make sure that the value is in 0 - 5 range
        val = val > 5 ? 5 : (val < 0 ? 0 : val);
        // Calculate physical size
        var size = 16 * val;
        // Create stars holder
        var stars = $('<span class="stars"><span></span></span>');
        // Adjust yellow stars' width
        stars.find('span').width(size);
        // Replace the numerical value with stars
        $(this).replaceWith(stars);
    });
}

var twUserId = null;
var twUserName = null;
var twUserImageUrl = null;
var timerId = null;
var loggedInTW = null;
var loggedInFB = null;
var isWritingReview = null;

$(document).ready(function() { 
    
    $('div.guru').alternate({odd:'guruDark', even:'guruLight'});
    $('span.rating').stars();
    $('#btn_get_quote').click(function(){
        $('#dialog_get_quote').dialog('open');
    });

    $('#dialog_get_quote').dialog({
        modal: true,
        title: 'Request a quote.',
        width: 675,
        height: 510,
        position: 'middle',
        autoOpen: false,
        resizable:false,
        buttons: { "Close": function() { $(this).dialog("close"); }}
    });
    
    $('#dialog_login').dialog({
        modal: true,
        title: 'First, tell us who you are.',
        width: 600,
        height: 320,
        position: 'middle',
        autoOpen: false,
        resizable:false,
        buttons: { "Close": function() { $(this).dialog("close"); }}
    });

    $('#btn_ask_question').click(function(){
        $('#dialog_ask_question').dialog('open');
    });
  
    $('#dialog_ask_question').dialog({
        modal: true,
        title: 'Ask a technical question.',
        width: 675,
        height: 510,
        position: 'middle',
        autoOpen: false,
        resizable:false,
        buttons: { "Close": function() { $(this).dialog("close"); }}
    });
    
    $("input[name=poster_email]").watermark();
    $("textarea[name=post]").watermark();
    $("textarea[name=message]").watermark();
    
    checkTwitterExistingLogin();
    $('.twLoginButton').click(
        function(){
            window.open('/twitter_auth/',
            'OAuthTwitterRequest',
            'menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=yes,width=800,height=400');

            timerId = setInterval( 'checkTwitterLoginSuccess()', 1000 );
        }
    );
    
    $('#writeReview').click(function(){
        if( loggedInFB || loggedInTW ){
            redirectToReviewForm();
        }
        else{
            isWritingReview = 1;
            $('#dialog_login').dialog('open');
        }
    });
    
    $('a.deleteReview').click(function(event) {
        event.preventDefault();
        var el = this;
        var href = $(el).attr('href');
        $("#dialog-confirm").dialog({
            resizable: true,
            height:140,
            width: 320,
            modal: true,
            title: 'Deleting Review',
            buttons: {
                'Delete Review': function() {
                    $.get(href, {}, function(data, textStatus, xhr) {
                        $(this).dialog('close');
                        window.location.reload();
                    });
                },
                Cancel: function() {
                    $(this).dialog('close');
                }
            }
        });

    });
    
});

function checkTwitterExistingLogin(){
    twUserId = $('#twitter_id').val();
    if( twUserId ){
        twUserImageUrl =  $('#twitter_profile_image_url').val();
        twUserName = $('#twitter_username').val();
        showTwitterLoggedIn();
    }
}

function checkTwitterLoginSuccess(){
    // user found
    if(twUserId){ 
        clearInterval(timerId);  
        if(isWritingReview){
            redirectToReviewForm();
        }
        showTwitterLoggedIn();
    }
}

function showTwitterLoggedIn(){
    loggedInTW = true;
    $('.fbLoginButton').hide();
    $('.twLoginButton').hide();
    var loginMessage = '<img id="twLoginImage" src=' + twUserImageUrl + ' />' + 
                       '<span class="TWLoginText bodyCopy">' + 
                       'Signed in as: ' + twUserName + '</span><span style="">' + twLogoutLink() + '</span>';
    $('#loggedInStatus').html( loginMessage ); // twitter login message
}

function twLogoutLink () {
    var logoutUrl = $('#logoutUrl').val() ;
    return '<span class="logout_link bodyCopy">&nbsp;&nbsp;<a href="' + logoutUrl + '">[Log out]</a></span>';
    
}

function updateFbContainer() { 
    if(isWritingReview){
        redirectToReviewForm();
    }
    loggedInFB = true;
    $('.fbLoginButton').hide();
    $('.twLoginButton').hide();
    var loginMessage = "<fb:profile-pic uid='loggedinuser' facebook-logo='true'></fb:profile-pic>" + 
                       '<span class="FBLoginText bodyCopy">' + 
                       "Welcome, <fb:name uid='loggedinuser' useyou='false'></fb:name>." + 
                       "</span>" + "<span>" +  fbLogoutLink() + "</span>";
    $('#loggedInStatus').html( loginMessage ); // because this is XFBML, we need to tell Facebook to re-process the document 
    FB.XFBML.Host.parseDomTree(); 
    var api = FB.Facebook.apiClient;
    var currentUserId = api.get_session().uid;
    $('#facebook_uid').val(currentUserId);
} 

function fbLogoutLink () {
    return '<span class="logout_link bodyCopy">&nbsp;&nbsp;<a href="#" onClick="fbLogout();">[Log out]</a></span>';
}

function fbLogout(){
    $('#facebook_uid').val('');
    FB.Connect.logout();
    setTimeout('redirectToLogoutUrl();', 3000);
}

function redirectToLogoutUrl(){
    var logoutUrl = $('#logoutUrl').val();
    window.location.href = logoutUrl;
}

function redirectToCurrentUrl (){
    var currentUrl = window.location.href;
    window.location.reload();
}

function redirectToReviewForm (){
    var currentUrl = window.location.href;
    var reviewUrl = currentUrl + '/write-review';
    window.location.href = reviewUrl;
}

function markReviewHelpful(review_id) {
    $.ajax({
        type: "GET",
        url: "/buscar/equipment_review_helpful?review_id="+review_id,
        success: function(msg){
            var helpful_el_msg = $("#review_helpful_" + review_id + " > span.message" );
            var helpful_el_count = $("#review_helpful_" + review_id + " > span.helpful_count" );
            var user_msg = "Thank you";
            var current_count_html = helpful_el_count.html();
            if (msg == 'denied') {
                user_msg = 'Your voted has already been counted.';
            }
            else{
                current_count_html = "Helpful(" + msg + ")";
            }
            
            helpful_el_count.hide(1).html(current_count_html).delay(2000).fadeIn('slow');
            helpful_el_msg.html(user_msg).fadeIn('fast').delay(1200).fadeOut('slow');
        }
    });
}


