var MAX_ITEMS_PER_PAGE = 10;
var WIDGET_NUM_ITEMS = 5;
var loader = '<img src="/images/small_loader.gif"/>';
var GALLERY_PRE_LOADING_FACTOR = 5;
var followQueue = new Array();
var followSize = 0;
var followedSize = 0;
var cur_filter = '';

$(document).ready(function () {

    $(".navigator").change(function() {
        window.location.href = $(this).attr('baseurl')+'/'+$(this).val();
    });

   $('.more_data').click(moreHandler);

   translate(get_site_lang());
  
});

function translate(lang)
{
    var jp_tweets = $('.non_trans .message');
    if (jp_tweets.length==0)
        return;
    tweet = $(jp_tweets[0]);

    tweet_lang_code =$('#language').val();
    dest_lang = $('#tweet_lang').val();
    site_lang =lang; 

    tweet.after(loader);
    google.language.translate({
        text: tweet.html(),
        type: 'html'
    }, "", dest_lang, function(result) { //dont provide source language first
        if (!result.error) {
            transHandler(result, tweet, dest_lang);

            tweet.next('img').remove();
            translate(lang);
        }
        else
        {
            //if it failed, pass source language and translate
            google.language.translate({
                text: tweet.html(),
                type: 'html'
            }, "ja", dest_lang, function(result) {
                if (!result.error) {
                    transHandler(result, tweet, dest_lang);
                }

                tweet.next('img').remove();
                translate(lang);
            });
        }
    });

    
}

var transHandler = function(result, tweet, dest_lang) {
    if(result.detectedSourceLanguage != dest_lang)
        tweet.html(result.translation);

    tweet.parent().removeClass('non_trans');
    //store the translated text in system
    $.ajax({
        type: 'post',
        url: '/' + site_lang + '/profile/save_trans/' + tweet.attr('id') + '/' + tweet_lang_code,
        data: {text: tweet.text()}
    });
};

var moreHandler = function(dummy, element,parent_element) {
    var anchor = element || $(this);
    $.ajax({
        beforeSend:function(request){
            anchor.after(loader);
        },
        complete:function(request){
            anchor.show();
            anchor.next('img').remove();
        },
        dataType:'json',
        type:'get',
        url: anchor.attr('href')+'/?ajax=true',
        success:function(data, textStatus) {
            //data = JSON.parse(data);
            if (data.error)
                anchor.after(data.error);
            else
            {
                $('.more_item:last',$(parent_element)).after(data['items']);
                //remove the more link, if all the tweets have been fetched
                if (data['more_exists']!=true)
                {
                    anchor.next('img').remove();
                    anchor.remove();
                }
                else //update the link otherwise
                {
                    anchor.attr('href', data['next_page']);
                }

                translate(get_site_lang());

            }
        },
        error:function(XMLHttpRequest, textStatus, errorThrown) {
            anchor.after(textStatus);
        }
    });
    return false;
};

var processHandler = function(dummy, element) {
    var anchor = element || $(this);
    $.ajax({
        beforeSend:function(request){
            anchor.after(loader);
        },
        complete:function(request){
            anchor.show();
            anchor.next('img').remove();
        },
        dataType:'json',
        type:'get',
        url: anchor.attr('href')+'/?ajax=true',
        success:function(data, textStatus) {
            //data = JSON.parse(data);
            if (data.error)
                anchor.after(data.error);
            else
            {
                $('#'+data['id']).remove();
            }
        },
        error:function(XMLHttpRequest, textStatus, errorThrown) {
            anchor.after(textStatus);
        }
    });
    return false;
};

function onPost(form)
{
    if ($('#postfield').val().length > 140) {
        twitterStyleAlert('Length of the tweet should be within 140 characters!');
        return false;
    }

    if ($('#postfield').val().length == 0) {
        twitterStyleAlert('Please enter a valid message');
        return false;
    }

    $.ajax({
        beforeSend:function(request){
            $('#twitter_update_submit').attr('disabled','true');
            $('#tweetbox_submit').after(loader);
        },
        complete:function(request){
            $('#twitter_update_submit').removeAttr('disabled');
            $('#tweetbox_submit').next().remove();
            
        },
        data:$.param($(form).serializeArray()),
        dataType:'json',
        type:'post',
        url:$(form).attr('action'),
        success:function(data, textStatus) {
            if (data.error)
                twitterStyleAlert(data.error);
            else
            {
                twitterStyleAlert('Your comment has been posted to twitter');
                //$('#comments').prepend(data['tweet']);
                //increment the counts
               // $('.cur_tweets').text($('.comment').length);
               // $('.num_tweets').text(parseInt($('.num_tweets:first').text()) + 1);

                $('#postfield').val($('#postfield').attr('default'));
                //$('#textcounter').html(140 - $('#postfield').val().length);
                //Clear the hidden field of "reply to status id"
                $('#reply_to').val("0");
            }
        },
        error:function(XMLHttpRequest, textStatus, errorThrown) {
            twitterStyleAlert(textStatus);
        }
    });
    return false;
}

function followProfile(a, callback)
{
    var anchor = a;
    var context = $(anchor).parent().parent().parent();
    if (!anchor.length)
    {
        callback(false);
        return;
    }
    var followStatus = false;
    $.ajax({
        beforeSend:function(request){
            anchor.after(loader);
        },
        complete:function(request){
            anchor.show();
            anchor.next('img').remove();
            if (followStatus)
            {
                // remove the check box
                context.find('.list_checkbox input')
                    .attr('checked', false)
                    .css('visibility', 'hidden');
            }
            if (callback) callback(followStatus);
        },
        url: anchor.attr('href'),
        dataType: 'json',
        success:function(data, textStatus) {
            anchor.next('img').remove();
            if (data['following']==true)
            {
                a.before('Following this user');
                a.remove();
                followStatus = true;
            }
            else if (data['limited']==true)
            {
                twitterStyleAlert("You've been rate limited by Twitter. Please try later");
                a.after('Error');
            }
            else
            {
                a.after('Error');
            }
        }
    });

    return false;
}

function update_bio_verification(a, callback)
{
    var anchor = $(a);
    var context = $(anchor).parent().parent().parent();
    if (!anchor.length)
    {
        callback(false);
        return;
    }
    var followStatus = false;
    $.ajax({
        beforeSend:function(request){
            anchor.after(loader);
        },
        complete:function(request){
            anchor.show();
            anchor.next('img').remove();
            if (followStatus)
            {
                // remove the check box
                context.find('.list_checkbox input')
                    .attr('checked', false)
                    .css('visibility', 'hidden');
            }
            if (callback) callback(followStatus);
        },
        url: anchor.attr('href'),
        dataType: 'json',
        success:function(data, textStatus) {
            anchor.next('img').remove();
            if (data['updated']==true)
            {
                //anchor.before('Verified');
                $(anchor.parent()).removeClass('unreview');
                anchor.remove();
            }
            else
            {
                a.after('Error');
            }
        }
    });

    return false;
}

function twitterStyleAlert(message)
{
    var $alert = $('#alert');
    var alerttimer = window.setTimeout(function () {
        $alert.trigger('click');
    }, 3000);
    $alert.html(message);
    $alert.animate({height: $alert.css('line-height') || '50px'}, 200)
    .click(function () {
        window.clearTimeout(alerttimer);
        $alert.animate({height: '0'}, 200, function(){
            $alert.html('');
        });
    });
}

function get_site_lang()
{
   var url_str = window.location.href;
   var url_arr = url_str.split("/");
   cur_lang = "en";
   if(url_arr.length > 4)
      cur_lang = url_arr[3];

  return cur_lang;
}

//refer: http://radio.javaranch.com/pascarello/2005/01/09/1105293729000.html
function ScrollToElement(theElement){

  var selectedPosX = 0;
  var selectedPosY = 0;

  while(theElement != null){
    selectedPosX += theElement.offsetLeft;
    selectedPosY += theElement.offsetTop;
    theElement = theElement.offsetParent;
  }

 window.scrollTo(selectedPosX,selectedPosY);
}

function searchPost(form)
{
	var search = $('#search').val();
        var url_str = window.location.href;
        var url_arr = url_str.split("/");
        if(url_arr.length > 4)
            window.location.href = '/'+url_arr[3]+'/search/' + escape(search);
        else
            window.location.href = 'en/search/' + escape(search);

	
	return false;
}

