var MAX_ITEMS_PER_PAGE = 20;
var hashtag_length = 0;
var LOADER = "<img src='/images/loader.gif'>";

TweetQueue=function(){
    this.items=[];
    this.delay=2000;
    this.timeout=undefined;
};

TweetQueue.prototype.start=function(){
    if(!this.timeout){
        this.schedule();
    }
};

TweetQueue.prototype.stop=function(){
    if(this.timeout){
        clearTimeout(this.timeout);
        this.timeout=undefined;
    }
};

TweetQueue.prototype.pause_toggle=function(){
    if(this.timeout){
        this.stop();
        return true;
    }
    else{
        this.start();
        return false;
    }
};

TweetQueue.prototype.schedule=function(){
    var t=this;
    this.timeout=setTimeout(function(){
        t.schedule();
        t.update();
    } ,this.delay);
};

TweetQueue.prototype.update=function(){
    var scroll_offset=($('#popoutinner').length>0)?'-105px':'-138px';
    if($('#streams-body > ul').size()>MAX_ITEMS_PER_PAGE){
        $('#streams-body > ul.twitupdate:last').fadeOut(3000,function(){
            $(this).remove();
        });
    }

    var item=this.items.shift();
    if(item){
        var element=$("#streams-update > #"+item);
        $('.streamscroll').css('top',scroll_offset);
		$('#empty_timeline_msg').remove();
        $('#streams-body').prepend(element.html());
        $('.streamscroll').animate({
            top:0
        },1500,'easeInOutQuad');
        element.remove();
    }
};

TweetQueue.prototype.add=function(id){
    this.items.push(id);
};

var TweetSpy=function(since,url){
    this.since=since;
    this.delay=25000;
    this.timeout=undefined;
    this.queue=new TweetQueue();
    this.url=url;
};

TweetSpy.prototype.start=function(){
    if(!this.timeout){
        this.schedule();
        this.queue.start();
    }
};

TweetSpy.prototype.schedule=function(){
    var t=this;
    this.timeout=setTimeout(function(){
        t.schedule();
        t.update();
    },this.delay);
};

TweetSpy.prototype.update=function(){
    var t=this;
    $('#loading').show();
    $.get(t.url+'/'+t.since,function(data){
        data = JSON.parse(data);
        for (var tweet in data["results"])
            $('#streams-update').prepend(data["results"][tweet]);
		
        var since_parsed = data["max_tweet_id"];
        if(!isNaN(since_parsed)){
            t.since=since_parsed;
        }
        $('#streams-update > div:not(.ready)').each(function(index,element){
            element=$(element);
            var localTime = getTime($(".timestamp", element).attr("unixtime"));
            $(".timestamp", element).html(localTime);
            $(".author", element).attr('title', $(".author", element).attr('title') + ' ' + localTime);
            element.addClass('ready');
            t.queue.add(element.attr('id'));

        });
        $('#loading').hide();
    }, "json");
};

TweetSpy.prototype.pause_toggle=function(){
    return this.queue.pause_toggle();
};


jQuery.extend(jQuery.easing,{
    def:'easeOutQuad',
    easeInOutQuad:function(x,t,b,c,d){
        if((t/=d/2)<1)return c/2*t*t+b;return-c/2*((--t)*(t-2)-1)+b;
    }
}
);

function getTime(atime)
{
    var time = new Date();
    time.setTime(parseInt(atime) * 1000);

    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    var month = months[time.getMonth()];
    var ampm = 'am';
    var hours = time.getHours();
 
    if(hours > 12)
    {
        hours = hours - 12;
        ampm = 'pm';
    }
    if(hours == 0)
    {
        hours = 12;
    }

    var ttime = month + '. ' + time.getDate() + ' at ' + hours + ':' + ((time.getMinutes()<10)? "0":"") + time.getMinutes()  + ampm;
    return ttime;
}

$(document).ready(function () {
    /*$('#streams-body > .message').each(function(index, element){
		var localTime = getTime($(".timestamp", element).attr("unixtime"));
		$(".timestamp", element).html(localTime);
		$(".author", element).attr('title', $(".author", element).attr('title') + ' ' + localTime);
	});*/ //Local time is not required as of now

    $(".message_head").click(function(){
        $(".message_body", $(this).parent()).slideToggle(500)
        $(".toggleimg", $(this).parent()).attr('src',
            ($("img", $(this).parent()).attr('src')=='/images/arrowcllopse.png')? '/images/arrowexpand.png':'/images/arrowcllopse.png');
        return false;
    });

	$(".inline_help").tooltip({ 
		bodyHandler: function() { 
			return $($(this).attr("href")).html(); 
		}, 
		showURL: false 
	});
	$(".inline_help").click(function(){return false;}); //disable the links

    $(".inline_edit").editable("/profile/edit", {
        indicator : "<img src='/images/loader.gif'>",
        tooltip   : "Click to edit...",
        width: 80,
        height: 18,
        style		: "inherit",
        placeholder :'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
        onblur: 'submit'
    });

    $(".inline_select_sex").editable("/profile/edit", {
        indicator : '<img src="/images/loader.gif">',
        data   : "{'':'', 'Male':'Male','Female':'Female'}",
        type   : "select",
        submit : "",
        width: 80,
        style  : "inherit",
        placeholder :'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
        onblur: 'submit'
    });

    $(".inline_select_degree").editable("/profile/edit", {
        indicator : '<img src="/images/loader.gif">',
        data   : "{'':'', 'High School':'High School','Associate':'Associate','Bachelor':'Bachelor','Master':'Master','Ph.D':'Ph.D','Certification':'Certification','License':'License'}",
        type   : "select",
        submit : "",
        width: 80,
        style  : "inherit",
        placeholder :'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
        onblur: 'submit'
    });
	
    $(".inline_select_color").editable("/profile/edit", {
        indicator : '<img src="/images/loader.gif">',
        data   : "{'':'', 'Red':'Red','Orange':'Orange','Yellow':'Yellow','Green':'Green','Blue':'Blue','Purple':'Purple','Brown':'Brown','Black':'Black','White':'White','Gray':'Gray','Pink':'Pink'}",
        type   : "select",
        submit : "",
        width: 80,
        style  : "inherit",
        placeholder :'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
        onblur: 'submit'
    });

    $(".inline_select_status").editable("/profile/edit", {
        indicator : '<img src="/images/loader.gif">',
        data   : "{'':'', 'Single':'Single','Dating':'Dating','Engaged':'Engaged','Married':'Married','Married w/ children':'Married w/ children'}",
        type   : "select",
        submit : "",
        width: 65,
        style  : "inherit",
        placeholder :'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
        onblur: 'submit'
    });

    $(".inline_select_tshirt").editable("/profile/edit", {
        indicator : '<img src="/images/loader.gif">',
        data   : "{'':'', 'XS':'XS','S':'S','S-M':'S-M','M-L':'M-L','L':'L','L-XL':'L-XL','XL':'XL','XL+':'XL+'}",
        type   : "select",
        submit : "",
        width: 80,
        style  : "inherit",
        placeholder :'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
        onblur: 'submit'
    });
	
    size = "{'':'', '< 5':'< 5',";
    for (i=5;i<=15;i+=.5)
        size += "'" + i + "':'" + i + "',";
    size += "'> 15':'> 15'}";

    $(".inline_select_shoe").editable("/profile/edit", {
        indicator : '<img src="/images/loader.gif">',
        data   : size,
        type   : "select",
        submit : "",
        width: 80,
        style  : "inherit",
        placeholder :'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;',
        onblur: 'submit'
    });

    $(".inline_add").keydown(function(event){
        return inline_add(event, this);
    });

    $(".inline_edit_date").editable("/profile/edit", {
        indicator : "<img src='/images/loader.gif'>",
        tooltip   : "Click to edit...",
        width: 80,
        height: 20,
        style		: "inherit",
        placeholder :'<span class="inline_placeholder">MM/DD/YYYY(opt)</span>',
        data: function(value, settings) {
            return $(this).attr('plain');
        },
        onsubmit: function(settings, original) {
            user_date = $('input', $(this)).val();
            digits = user_date.split("/");
			if (user_date.length==0)	
			{
				//accept empty entries, which means user is unsetting this field
			}
			else if (digits.length!=2 && digits.length!=3) //year is optional
				return false;
			else {
				digits[0] = parseInt(digits[0]);
				digits[1] = parseInt(digits[1]);
				if (digits[0] < 0 || digits[0] > 12 || digits[1] < 0 || digits[1] > 31)
						return false;
				if (digits.length == 3)
				{
					digits[2] = parseInt(digits[2]);
					if (digits[2] < 0 || digits[2] > 2050)
						return false;
					user_date = digits[0]+'/'+digits[1]+'/'+digits[2];
				}
				else
				{
					user_date = digits[0]+'/'+digits[1];
				}
			}
            $(original).attr('plain', user_date);
            $('input', $(this)).val(user_date);
            return true;
        },
        onreset: function(settings, original) {
            return $(original).attr('ui');
        },
        callback: function(modified, settings){
			modified = modified.split('|');
			if (modified.length==2)
			{
				$(this).html(modified[0]);
				$(this).attr('ui', modified[0]);
				$('#userage').html(modified[1]);
			}
			else
			{
				$(this).attr('ui', '');
				$('#userage').html('');
			}

        },
        onblur: 'submit'
    });

    $(".inline_edit_month").editable("/profile/edit", {
        indicator : "<img src='/images/loader.gif'>",
        tooltip   : "Click to edit...",
        width: 80,
        height: 20,
        style		: "inherit",
        placeholder :'<span class="inline_placeholder">MM/YYYY</span>',
        data: function(value, settings) {
            return $(this).attr('plain');
        },
        onsubmit: function(settings, original) {
            user_date = $('input', $(this)).val();
            digits = user_date.split("/");
			if (user_date.length==0)	
			{
				//accept empty entries, which means user is unsetting this field
			}
			else if (digits.length!=2)
				return false;
			else {
				digits[0] = parseInt(digits[0]);
				digits[1] = parseInt(digits[1]);
				if (digits[0] < 0 || digits[0] > 12 || digits[1] < 0 || digits[1] > 2050)
					return false;
				user_date = digits[0]+'/'+digits[1];
			}
            $(original).attr('plain', user_date);
            $('input', $(this)).val(user_date);
            return true;
        },
        onreset: function(settings, original) {
            return $(original).attr('ui');
        },
        callback: function(modified, settings){
            $(this).attr('ui', modified);
        },
        onblur: 'submit'
    });

    $(".inline_edit_location").editable("/profile/edit", {
        indicator : "<img src='/images/loader.gif'>",
        tooltip   : "Enter Zip...",
        width: 80,
        height: 20,
        style		: "inherit",
        placeholder :'<span class="inline_placeholder">Enter Zip...</span>',
        data: function(value, settings) {
            return $(this).attr('plain');
        },
        onsubmit: function(settings, original) {
            zipcode = $('input', $(this)).val();
            nzipcode = parseInt(zipcode);
            if ((zipcode.length!=0) && (!nzipcode || nzipcode <= 0 || nzipcode > 100000)) //excuse empty entries, as user is unsetting the field value
			{
                return false;
			}
			
            $(original).attr('plain', zipcode);
            $('input', $(this)).val(zipcode);
            return true;
        },
        onreset: function(settings, original) {
            return $(original).attr('ui');
        },
        callback: function(modified, settings){
            $(this).attr('ui', modified);
        },
        onblur: 'submit'
    });

    hashtag_length = ($('#hashtag').text() && $('#hashtag').text().length>0)? ($('#hashtag').text().length+1):0;

    $('#postfield').twitterCounter(
    {
        limit: (140-hashtag_length),
        counter: '#textcounter',
        okSize: (140-hashtag_length),
        okStyle: '.ok',
        watchSize: 20,
        watchStyle: '.watch',
        warningSize: 10,
        warningStyle: '.limitwarning',
        errorSize: 0,
        errorStyle: '.limitexceeded'
    }
    );

    $('.labelled').blur(function(){
        if ($(this).val()=='')
            $(this).val($(this).attr('blurvalue'));
    }).focus(function(){
        if ($(this).val()==$(this).attr('blurvalue'))
            $(this).val('');
    });

    $('#sighting_link').fancybox({
        modal : true,
        frameHeight : 300,
        frameWidth : 440,
        autoDimensions	: false,
        callbackOnClosed : function(){
            $('#modal_box #modal_tweet_help').slideUp();
        }
    });

    $('#tweetthis_link').fancybox({
        modal : true,
        frameHeight : 230,
        frameWidth : 440,
        autoDimensions	: false,
        callbackOnClosed : function(){
            $('#modal_box #modal_tweet_help').slideUp();
        }
    });

    $('#alertbox_link').fancybox({
        modal : true,
        frameHeight : 150,
        frameWidth : 300,
        autoDimensions	: false,
        callbackOnClosed : function(){
            $('#modal_box #modal_tweet_help').slideUp();
            $('#modal_box .main_area').show();
        }
    });


});

function toggle()
{
    $('#togglelink').attr("src", tu.pause_toggle()? "/img/break.png":"/img/break.png");
}

jQuery.fn.twitterCounter = function(options)
{
    if(!$(this)[0])
        return false;
    var curSize=$(this).val().length;
    var charsLeft=options['limit']-curSize;
    var types=['ok','watch','warning','error'];
    var x={};$.each(types,function(){
        var el=this.toString();
        x[el]={
            'Max':options[el+'Size'],
            'Style':options[el+'Style'].substring(0,1)=='.'||options[el+'Style'].substring(0,1)=='#'?options[el+'Style'].substring(1,options[el+'Style'].length):options[el+'Style'],
            'Type':options[el+'Style'].substring(0,1)=='.'?'class':'id'
            };
    });
    for(var i=0;i<types.length;i++)
    {
        var el=types[i].toString();
        if(i+1<types.length){
            var nextEl=types[i+1].toString();
            if(charsLeft>x[nextEl]['Max']&&charsLeft<x[el]['Max']+1){
                clean();
            }
        }
        else
        {
            if(charsLeft<x[el]['Max'])
                clean();
        }
    }
    $(options['counter']).text(charsLeft);
    $(this).one('keyup',function(){
        $(this).twitterCounter(options);
    });

    function clean(){
        if(x[el]['Type']=='class'){
            $.each(types,function(){
                var temp=this.toString();
                if($(options['counter']).hasClass(temp)){
                    $(options['counter']).removeClass(temp);
                }
            });
            $(options['counter']).addClass(x[el]['Style']);
        }
        else
        {
            $(options['counter']).id(x[el]['Style']);
        }
    }
};

function draftTweet(screen_name, message){
    var text=$('#postfield').val("@"+screen_name+" "+message);    
    $('#reply_to').val(0);
	$('#mvp_to').val(screen_name);
    $('#postfield').trigger('keyup');
    $("#postfield").focus();
	window.scroll(0,0);
}

function replyTo(screen_name, status_id){
	$('#postfield').val("@"+screen_name);
    window.scroll(0,0);
    //limitChars('postfield',140,'length');
    $('#reply_to').val((status_id==null)? 0:status_id); //Set the reply_to_status_id here. This will be sent to server while posting the form
	$('#mvp_to').val('');
    $('#postfield').trigger('keyup');
    $("#postfield").focus();
}

function rtreplyTo(screen_name, container){
    $('#postfield').val("RT @"+screen_name+" "+$('.leftnormaltxt', container).text());
    window.scroll(0,0);
    $('#postfield').trigger('keyup');
    $("#postfield").focus();
}

function showSightingBox(screen_name, status_id, image)
{
    var box = $('#modal_box');
    $('.title', box).html('MallTweets Sighting?');
    $('.heading', box).html('You are about to tweet that you saw '+
           screen_name+' on MallTweets. <br/><br/><img src="'+unescape(image)+'"/><br/><br/>');

    $('#sighted_username_input', box).val(screen_name);
    $('#sighting_tweet_id', box).val(status_id);

    $('.main_area textarea', box).val('@' + screen_name + ' #MallTweetsSighting http://malltweets.com'); //show original URL to user
    $('#tweet', box).val('@' + screen_name + ' #MallTweetsSighting http://bit.ly/95eVPE'); //this is for tracking

    $('.cancel', box).val('Cancel');
    $('#modal_tweet_help').html('Please use the <strong>Reply</strong> link if you want to add a personal message.');

    $('.form', box).submit(function () { return tweetSighting()});
    $('#sighting_link').trigger('click');
}

function tweetSighting()
{
    var form = $('#modal_box form');
    $.ajax({
        beforeSend:function(request){
            $('#modal_box .submit').attr('disabled','true');
            $('#modal_box .submit').attr('value','Tweeting...');
        },
        complete:function(request){
            $('#modal_box .submit').removeAttr('disabled');
            $('#modal_box .submit').attr('value','Tweet');
			$.fancybox.close();
        },
        data:$.param($(form).serializeArray()),
        dataType:'json',
        type:'post',
        url:$(form).attr('action'),
        success:function(data, textStatus) {
            if (data.error)
                alert('<div id="errorMessage">' + data.error + '</div>');
            else
            {
				if (data['message'])
					alert(data['message']);
            }
        },
        error:function(XMLHttpRequest, textStatus, errorThrown) {
            alert('<div id="errorMessage">' + textStatus + '</div>');
        }
    });
    return false;
}


var EMP_ADD = 'employee_add';
var EMP_REMOVE = 'employee_remove';
var EMP_SUGGEST = 'employee_suggest';
var EMP_ALERT = 'employee_alert';

var FAN_ADD = 'fan_add';
var FAN_REMOVE = 'fan_remove';
var SHOPPER_ADD = 'shopper_add';
var SHOPPER_REMOVE = 'shopper_remove';


function employeeTweetBox(mode)
{
    var box = $('#modal_box');
    if (mode==EMP_ALERT)
    {
        $('.main_area', box).hide();
        $('.title', box).html('Already an Employee!');
        $('.heading', box).html($('#employee_alert').html() + '<br/><br/><input type="button" onclick="$.fancybox.close();return false;" class="cancel" value="OK"/>');
        $('#alertbox_link').trigger('click');
        return;
    }
    $('#action', box).val(mode);
    $('.title', box).html((mode==EMP_SUGGEST)? 'Suggest an Employee':
                         ((mode==EMP_ADD)? 'Are You An Employee Here?':'Are You Not An Employee Here?'));

    $('.heading', box).html((mode==EMP_SUGGEST)? 'Know someone who works here? Suggest that they add themselves!':
                         ((mode==EMP_ADD)? 'If so, then you must confirm by tweeting that you are an Employee here.':'If not, then you must confirm by tweeting that you are not an Employee here.'));

    $('.forminput', box).html('<br/><br/>' + 
                        ((mode==EMP_SUGGEST)? 'To: @ <input name="mention_user" type="text" value=""><br/><br/>':'') +
                        '<input type="hidden" name="mall_slug" value="'+$('#mall_slug').text()+'"/>' +
                        '<input type="hidden" name="business_slug" value="'+$('#business_slug').text()+'"/>');

    var biz_label = (($('#business_name').length > 0)? ($('#business_name').text() + ' at '):'') + $('#mall_name').text();
    var tweet = ((mode==EMP_SUGGEST)? 'You should add yourself as':((mode==EMP_ADD)? 'Is now':'Is no longer'));
    tweet += ' an Employee at '+biz_label+' on MallTweets.com';
    $('.main_area textarea', box).val(tweet);
    $('#tweet', box).val(tweet);
    $('.cancel', box).val('Cancel');

    $('#modal_tweet_help').html('Sorry, this tweet can not be edited.');

    $('.form', box).unbind('submit');
    $('.form', box).submit(function () { return employeeTweetHandler(mode);});
    $('#tweetthis_link').trigger('click');
}



function employeeTweetHandler(mode)
{
    var form = $('#modal_box form');
    $.ajax({
        beforeSend:function(request){
            $('#modal_box .submit').attr('disabled','true');
            $('#modal_box .submit').attr('value','Tweeting...');
        },
        complete:function(request){
            $('#modal_box .submit').removeAttr('disabled');
            $('#modal_box .submit').attr('value','Tweet');
            $.fancybox.close();
        },
        data:$.param($(form).serializeArray()),
        dataType:'json',
        type:'post',
        url:$(form).attr('action'),
        success:function(data, textStatus) {
            if (data.error)
                alert('<div id="errorMessage">' + data.error + '</div>');
            else
            {
                $('#empty_timeline_msg').remove();
                if (typeof(tu) !== 'undefined')
                {
                    $('#streams-body').prepend(data['tweet']);
                    //update the since id
                    if (data['max_tweet_id'])
                        tu.since = data['max_tweet_id'];
                }

                if (data['message'])
                    alert(data['message']);
                if (data['reload']==true)
                {
                    $.fancybox.showActivity();
                    window.location.reload();
                }
            }
        },
        error:function(XMLHttpRequest, textStatus, errorThrown) {
            alert('<div id="errorMessage">' + textStatus + '</div>');
        }
    });
    return false;
}

function tweetThis(mode)
{
    var box = $('#modal_box');
    $('#action', box).val(mode);    //not handled
    $('.title', box).html('Want To Tweet This?');

    $('.heading', box).html('Click on Tweet to tell your friends on Twitter!');

    $('.forminput', box).html('<br/><br/>' +
                        '<input type="hidden" name="mall_slug" value="'+$('#mall_slug').text()+'"/>' +
                        '<input type="hidden" name="business_slug" value="'+$('#business_slug').text()+'"/>');

    var biz_label = (($('#business_name').length > 0)? ($('#business_name').text() + ' at '):'') + $('#mall_name').text();
    var tweet = '';
    if (mode==FAN_ADD)
        tweet = 'Is now a Fan of ';
    if (mode==SHOPPER_ADD)
        tweet = 'Is now a Shopper of ';
    if (mode==FAN_REMOVE)
        tweet = 'Is no longer a Fan of ';
    if (mode==SHOPPER_REMOVE)
        tweet = 'Is no longer a Shopper of ';
    tweet += biz_label+' on MallTweets.com';

    $('.main_area textarea', box).val(tweet);
    $('#tweet', box).val(tweet);


    $('.form', box)
        .unbind('submit')
        .submit(function () { return employeeTweetHandler(mode);});
    //Perform the action by a separate AJAX request, if user cancelled the tweet box
    $('.cancel', box)
        .val('No Tweet')
        .unbind('click')
        .click(function(){
            $.fancybox.showActivity();
            $.ajax({
                data:{action: mode, mall_slug: $('#mall_slug').text(), business_slug: $('#business_slug').text(),},
                dataType:'json',
                type:'post',
                url:'/streams/handleAction/',
                success:function(data, textStatus) {
                    if (data['reload']==true)
                        window.location.reload();
                }
            });
        })

    $('#tweetthis_link').trigger('click');

    return false;
}

function remove(anchor, status_id){
    $('#errorMessage').remove();
    $.get("/moderate.php?",{
        id:status_id
    },function(data){
        if (data.error)
            $('.yui-g').prepend('<div id="errorMessage">' + data.error + '</div>');
        else
        {
            $(anchor).remove();
            $('.yui-g').prepend('<div id="errorMessage">Tweet #' + status_id + ' has been removed</div>');
        }
    }, "json");
}

function onPost(form)
{
    if ($('#postfield').val().length > (140-hashtag_length)) {
        alert('Length of the tweet should be within 140 characters!');
        return false;
    }

    if ($('#postfield').val().length == 0) {
        alert('Please enter a valid status');
        return false;
    }
	
    $.ajax({
        beforeSend:function(request){
            $('#twitter_update_submit').attr('disabled','true');
            $('#twitter_update_submit').attr('value','Posting...');
            $('#errorMessage').remove();
        },
        complete:function(request){
            $('#twitter_update_submit').removeAttr('disabled');
            $('#twitter_update_submit').attr('value','Post');
        },
        data:$.param($(form).serializeArray()),
        dataType:'json',
        type:'post',
        url:$(form).attr('action'),
        success:function(data, textStatus) {
            if (data.error)
                $('.message_container').html('<div id="errorMessage">' + data.error + '</div>');
            else
            {
                $('#empty_timeline_msg').remove();
                if (typeof(tu) !== 'undefined')
                        $('#streams-body').prepend(data['tweet']);

                if (data['message'])
                        alert(data['message']);

                if (data['clear_mvp'])
                        $('#mvp_button').remove();

                //update the since id
                if ((typeof(tu) !== 'undefined') && data['max_tweet_id'])
                        tu.since = data['max_tweet_id'];

                $('#postfield').val("");
                $('#textcounter').html((140 - hashtag_length));
                //Clear the hidden field of "reply to status id"
                $('#reply_to').val("0");
                $('#mvp_to').val('');
            }
        },
        error:function(XMLHttpRequest, textStatus, errorThrown) {
            $('.message_container').html('<div id="errorMessage">' + textStatus + '</div>');
        }
    });
    return false;
}

deleteEntry = function(entry)
{
    $.post('/profile/delete', {
        id: entry.attr('id')
        }, function(data, textStatus) {
        if (data=='')
            entry.parent().parent().fadeOut(500, function() {
                entry.parent().parent().remove();
            });
        else
            $('.message_container').html('<div id="errorMessage">' + data.error + '</div>');
    });
};

showHoursForm = function()
{
    $('#hours').hide();
    $('#hours_form').show();
    $('#hours_edit').hide();
};

cancelHoursForm = function()
{
    $('#hours').show();
    $('#hours_form').hide();
    $('#hours_form input').each(function(index,element){
        if ($(element).attr('type')=='text')
        {
            $(element).val($(element).attr('orig'));
        }
    });
    $('#hours_edit').show();
};

submitHoursForm = function()
{
    var form = $('#hours_form');
    $.ajax({
        beforeSend:function(request){
            //validate
            var from = $('.hours_from');
            var to = $('.hours_to');
            for(i=0;i<7;i++)
            {
                var matches1 = $(from[i]).val().match(new RegExp(/^([0-9]?[0-9])\s?(am|pm)$/i));
                var matches2 = $(to[i]).val().match(new RegExp(/^([0-9]?[0-9])\s?(am|pm)$/i));
                if (matches1 && matches2)
                {
                    from_time = parseInt(matches1[1]) + ((matches1[2].toLowerCase()=='pm')? 12:0);
                    to_time = parseInt(matches2[1]) + ((matches2[2].toLowerCase()=='pm')? 12:0);
                    if (from_time > to_time)
                        return false;
					//fix the format
					$(from[i]).val(matches1[1] + ' ' + matches1[2].toUpperCase());
					$(to[i]).val(matches2[1] + ' ' + matches2[2].toUpperCase());
                }
                else {
                    if (!matches1)
                        $(from[i]).focus();
                    else if (!matches2)
                        $(to[i]).focus();
                    alert('Please enter the working hours in this format \r\n 9 AM \t 11 PM');
                    return false;
                }

            }
            $('#hours_form').hide();
            $('#hours_container').append("<img src='/images/loader.gif'>");
			this.data = $.param($(form).serializeArray());
        },
        data:$.param($(form).serializeArray()),
        dataType:'html',
        type:'post',
        url:$(form).attr('action'),
        success:function(data, textStatus) {
            $('#hours_container').html(data);
            $('#hours_edit').show();
        },
        error:function(XMLHttpRequest, textStatus, errorThrown) {
            cancelHoursForm();
            $('#hours_container img:last').remove();
            $('#hours_container').append('An error occurred');
        }
    });
    return false;
};

autoFillHours = function(cur)
{//todo
    index = $(cur).attr('index');
    css = $(cur).hasClass('hours_from')? 'hours_from':'hours_to';
    stop = false;
    $('.' + css + ':gt('+index+')').each(function(index, element) {
        if ($(element).attr('dirty')=='')
            stop = true;
        if (!stop)
            $(element).val($(cur).val());
    });
    $(cur).attr('dirty', '');
};

function showDoubleBoxes(pencil)
{
    var parent = $(pencil).parent().parent();
    var span = $('.double_display', parent);

    if ($('.double_input', span).length>0) //already in edit mode
        return;
	
    $(span.children()[0]).hide();
    span.append('<input class="main_input double_input" id="'+span.attr('id')+'" value="'+ span.text() +'"/>');
    span.append('<input class="other_input double_input" value="'+ $(span.children()[0]).attr('href') +'"/>');
    $('.double_input', span).each(function(i, e){
        $(e).keydown(function(event){
            if (event.keyCode==27)
            {
                //Show the original span
                $(span.children()[0]).show();
                $('.double_input', span).each(function(i, e){
                    $(e).remove()
                    });
                return false;
            }
            return inline_add(event, this, true);
        })
        .focus(function(a, b){
            var w = 34;
        })
        .blur(function(a, b){
            t = setTimeout(function() {
                e = $.Event('keydown');
                e.keyCode = 13;
                return inline_add(e, this, true);
            }, 500);
        });
    });
}

var inline_add = function(event, context, editMode) { 
    if (event.keyCode!=13)
        return true;

    event.returnValue = false; //for IE

    editMode = editMode || false;

    var parent = $(context).parent();
    var main_input = $('.main_input', parent);
    var other_input = $('.other_input', parent);

    var main_value = jQuery.trim(main_input.val());
    var other_value = '';
    if (other_input.length>0)
        other_value = jQuery.trim(other_input.val());
    if (main_value.length==0)
        return false;
    if (other_value!='' && !other_value.match(/((http:\/\/)?[a-z0-9.-?_&%-]*\.(.+?))/i))
        return false;
	
    //hide the add text box
    var table_row = editMode? main_input.parent().parent().parent():main_input.parent().parent();
    $(table_row).hide();
    $(table_row).after('<tr><td width="100%" colspan="3"><img src="/images/loader.gif"></td</tr>');
	
	
    //fire the request
    $.post(editMode? '/profile/edit':'/profile/add', {
        id:main_input.attr('id'),
        value:main_input.val(),
        other: other_value
    }, editMode? (function(data){
        //delete the loader
        $(table_row).next().remove();
        //show new entry
        $(table_row).before(data);
        //remove old entry
        $(table_row).remove();
    }):(function(data){
        //delete the loader
        $(table_row).next().remove();
        $(table_row).before(data);

        if (other_value)
            other_input.val('');
        else {
            $(".inline_edit").editable("/profile/edit", {
                indicator : "<img src='/images/loader.gif'>",
                tooltip   : "Click to edit...",
                width: 80,
                height: 18,
                style		: "inherit",
                placeholder :'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'
            });
        }

        main_input.val('');
        $(table_row).show();
        main_input.focus();
    })
    );
};


var newwindow;
function popitup(url) {                                                                                                                                               
    newwindow=window.open(url,'name','height=200,width=250');
    if (window.focus) {
        newwindow.focus();
    }
    return false;
}                                                                                  

/*Refer: http://briancray.com/2009/05/06/twitter-style-alert-jquery-cs-php/*/
function twitterStyleAlert(message)
{
    var $alert = $('#alert');
    var alerttimer = window.setTimeout(function () {
        $alert.trigger('click');
    }, 10000);
    $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('');
        });
    });
}
