var Tweetmas = {

    timerPointer: null,
    updaterPointer: null,
    latestTweetmas: 0,
    maxSize: 140,
    updating: false,
    months: new Array( "Jan", "Feb", "Mar", "Apr", "May", "Jun",  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"  ),
    
    sendTweetmas: function() {
        
      if( Tweetmas.validateUpdate() == false ) return;
        
      Tweetmas.showPosting();
      $("#global_errors").hide();
      $("#global_errors").html( '' );
      
      $.post( "/ajax/" ,"call=Contributed.postTweetmas&"+$('#twitter_form').serialize(), function(response) {
             Tweetmas.hidePosting();
             if( response.documentElement.tagName == 'error') {
                 $("#global_errors").html( response.documentElement.firstChild.nodeValue );
                 $("#global_errors").show();
             } else if ( response.documentElement.firstChild.nodeValue == 'ok' ) {
                 $('#twitter_form').hide();
                 $('#twitter_congrat').show();
             }
             //$('#'+product_id+'_actions a.deactivate').after("<span class='deactivated'>deactivated</span>").remove();
      });        
        
    },
    
    sendAnotherOne: function() {
        $('#twitter_congrat').hide();        
        $('#twitter_form').show();
    },    
    
    auth: function() {
      Tweetmas.showAuthing();
      $("#auth_global_error").hide();
      $("#auth_global_error").html( '' );
      
      $.post( "/ajax/" ,"call=Contributed.authTweetmas&"+$('#auth_form').serialize(), function(response) {
             Tweetmas.hideAuthing();
             if( response.documentElement.tagName == 'error') {
                 $("#auth_global_error").html( response.documentElement.firstChild.nodeValue );
                 $("#auth_global_error").show();
             } else if ( response.documentElement.firstChild.nodeValue == 'ok' ) {
                $("h1.what_box").before('<div class="logged_in">You\'re logged in as <strong>'+$('#twitter_username').val()+'</strong> / <a href="/logout" title="log out">log out</a></div>')
                var code = '';
                code += '<p id="auth_global_error"></p>';
                code += '<h1 style="margin-bottom:9px;font-size:115%"><strong style="color:#00AD3D">Hurray</strong>, Your credentials were authenticated successfully.<br/>Now you can use Tweetmas.</h1>';
                code += '<input id="follow_tweetmas" type="checkbox" checked="checked"/><label class="follow_tweetmas">Follow Tweetmas?</label><br/>';
                code += '<input id="show_friends" type="checkbox" checked="checked"/><label class="follow_tweetmas">See tweetmases from your twitter friends </label>';
                code += '<fieldset class="actions"><input type="button" value="Close this box and start to use Tweetmas" style="display:block;" onclick="Tweetmas.hideAuthBox()"/></fieldset>';
                $("#auth_form").html( code );
                $('#twitter_form').show();
                $('#not_auth_form').remove();
                
             }
             //$('#'+product_id+'_actions a.deactivate').after("<span class='deactivated'>deactivated</span>").remove();
      });        
        
    },    
    
    updateList: function() {
        
        if( Tweetmas.updating == false ) {
          Tweetmas.updating = true;
          Tweetmas.showUpdating();
          $.post( "/ajax/" ,"call=Contributed.getTweetmasUpdate&latest_id="+ Tweetmas.latestTweetmas, function(response) {
                 
                 Tweetmas.updating = false;
                 if( response.documentElement.tagName == 'error') {
                     //alert( response.documentElement.firstChild.nodeValue );
                 } else if ( response.documentElement.tagName == 'ok' ) {
                     //alert('updated');
                     var number = response.documentElement.getAttribute('number_of_updates');
                     if(number>0) {
                         Tweetmas.latestTweetmas = response.documentElement.getAttribute('last_id');
                         $("#tweetmas_list").css('top','-'+ 50 * number +'px');
                         $("#tweetmas_list .first").removeClass("first");
                         $("#tweetmas_list").prepend(response.documentElement.firstChild.nodeValue);
                         $('#tweetmas_list').animate({ top: "0"}, 1000 );
                         $('#tweetmas_list .entry:gt(19)').remove();
                     }
                     Tweetmas.hideUpdating();
                     
                     Tweetmas.updaterPointer = setTimeout("Tweetmas.updateList()", 4500);
                     
                 }
                 //$('#'+product_id+'_actions a.deactivate').after("<span class='deactivated'>deactivated</span>").remove();
          });  
        }
    },    
    /*
    updateList: function() {
       
       $('<li><img src="http://static.twitter.com/images/default_profile_normal.png" alt="sobek"/><a rel="nofollow" href="http://twitter.com/sobek/">xxx</a> @tweetmastest update  <span title="2008/11/12 12:50:52" class="creation_date">yesterday 12:50 PM</span></li>').prepend("#tweetmas_list");
       
    },*/
    
    searchUser: function() {
      $('#user_search_result_box').hide();
      
      if( Tweetmas.validateSearcher() == false ) return;
      
      Tweetmas.showSearching();
      $.post( "/ajax/" ,"call=Contributed.searchUserTweetmases&"+$('#search_form').serialize(), function(response) {
             if( response.documentElement.tagName == 'error') {
                 //alert( response.documentElement.firstChild.nodeValue );
             } else if ( response.documentElement.getAttribute('status') == 'ok' ) {
                 Tweetmas.hideSearching();
                 $('#user_search_result_box').html( response.documentElement.firstChild.nodeValue );
                 $('#user_search_result_box').append( 
                 '<div class="bottom_line"><div class="rss"><a href="http://www.tweetmas.com/feed/'+$('#search_twitter_username').val()+'/" rel="nofollow"><img alt="Tweetmas Feed" src="/media/imgs/tweetmas/rss_icon.gif" width="19" height="20"/></a>'
                 +'<a href="http://www.tweetmas.com/feed/'+$('#search_twitter_username').val()+'/" rel="nofollow">'+$('#search_twitter_username').val()+' Feed</a> ( <a href="http://fusion.google.com/add?source=atgs&feedurl=http%3A//www.tweetmas.com/feed/'+$('#search_twitter_username').val()+'/" rel="nofollow"><img src="/media/imgs/tweetmas/google_reader_button.gif" border="0" alt="Add to Google" width="62" height="19" style="margin-top:-2px"></a> )'
                 +'</div><a onclick="Tweetmas.hideSearchResult();return false;" href="#" class="close_searcher">hide results</a></div>' );
                 $('#user_search_result_box').show();
             }
             //$('#'+product_id+'_actions a.deactivate').after("<span class='deactivated'>deactivated</span>").remove();
      });        
        
    },
    
    hideSearchResult: function() {
        
        $('#user_search_result_box').hide();
        $('#user_search_result_box').html('');
        
        return false;
    },
    
    updateTextLength: function(event) {
        $('#text_lenght_counter').html( Tweetmas.maxSize - $('#message').val().length );
    },
    
    showAuthBox: function() {
        $('.lightbox').show();
        $('.loginbox').show(); 
    },    
    
    hideAuthBox: function() {
      Tweetmas.showFollowing();
        
      
      if( $('#follow_tweetmas').attr('checked') ) {
           $.post( "/ajax/" ,"call=Contributed.followTweetmas", function(response) {
             Tweetmas.hideFollowing();
             if( response.documentElement.tagName == 'error') {
                 $("#auth_global_error").html( response.documentElement.firstChild.nodeValue );
                 $("#auth_global_error").show();
             } else if ( response.documentElement.firstChild.nodeValue == 'ok' ) {
                 $('.lightbox').hide();
                 $('.loginbox').hide();
             }
      });     
        } else {
            $('.lightbox').hide();
            $('.loginbox').hide();
        }
      
      
        
      if( $('#follow_tweetmas').attr('checked') ) {
          var expiredate=new Date();
          expiredate.setDate(expiredate.getDate()+ 32 );
          document.cookie= "show_friends=1;expires="+ expiredate.toGMTString();
          Tweetmas.getFriendBox();
      }          
      
        
    },     
    
    getFriendBox: function() {
    
      $.post( "/ajax/" ,"call=Contributed.getFriendTweetmasBox", function(response) {
             if( response.documentElement.tagName == 'error') {
                 //alert( response.documentElement.firstChild.nodeValue );
             } else if ( response.documentElement.tagName == 'ok' ) {
                 //console.log( response.documentElement.firstChild.nodeValue );
                 //$('#user_search_result_box').show();
                 $('.search_box').after( response.documentElement.firstChild.nodeValue );
             }
             //$('#'+product_id+'_actions a.deactivate').after("<span class='deactivated'>deactivated</span>").remove();
      });        
        
    },    
    
    hideAuthBoxWithoutSave: function() {
        $('.lightbox').hide();
        $('.loginbox').hide();
    },
    
    recalcDate: function() {
        $("span.creation_date").each( function (i,el) {
        $(el).html( Tweetmas.calcDateDiff( $(el).attr('title') ) );
        });
        Tweetmas.timerPointer = setTimeout("Tweetmas.recalcDate()", 10000);
    },
    
    calcDateDiff: function( date ) {
       var timezone = new Date();
       var d = Date.parse( new Date() );
       //var td = "2008/11/20 12:10:36";
       var d1 = Date.parse(date);
       
       d1 = d1 - (timezone.getTimezoneOffset() * 60 * 1000);
       var A = new Date(date);
       var txt = '';
       diff = (d-d1) / 1000;

        if ( 1 > diff / 60   ) {
          txt = 'less then a minute ago';
        } else if ( 1 < diff / 60 && 60 > diff / 60 ) {
            txt = Math.round(diff / 60) + ' minutes ago';
        } else if ( 60 > diff / 60 ) { 
         txt = 'less then a hour ago';
        } else if ( 24 > diff / 3600  ) { 
         txt = Math.round(diff / 3600) + ' hours ago';
        } else if ( 48 > diff / 3600 ) {
         txt = 'yesterday '+ Tweetmas.correctHour(A.getHours()).toString()+":"+
          Tweetmas.correctNumber(A.getMinutes())+" "+Tweetmas.getMeridiem( A.getHours() );
        } else {
         txt = Tweetmas.correctHour(  A.getHours() ).toString()  
         +":"+ Tweetmas.correctNumber(A.getMinutes()).toString()+" "+
         Tweetmas.getMeridiem( A.getHours() )+" "+Tweetmas.correctMonth(A.getMonth())+" "+Tweetmas.getOrdinalNumber(A.getDate());
        }
        
        return txt;
        
    },
    
    correctNumber: function(number) {
        if ( number < 10 ) {
            return '0' + number;
        } else {
            return number;
        }
        
    },

    getMeridiem: function(hour) {
        if(hour>=12) {
            return "PM";
        }else {
            return "AM";
        }
    }, 

    correctHour: function(hour) {
        if(hour>12) {
          hour = hour - 12;
        } else if ( 0 == hour) {
          hour = 12
        }
        return hour;
    },     
    
    correctMonth: function(number) {
        return Tweetmas.months[number];
    },    
    
    getOrdinalNumber: function(number) {
        var ordinal = 'th';
        var txt = number.toString();
        var i = txt[txt.length-1];
        if( number < 10 && numer > 20  ) {
            switch (i) {
               case "1":
                   ordinal = 'st';
               break;
               case "2":
                   ordinal = 'nd';
               break;
               case "3":
                   ordinal = 'rd';
               break;
               default:
                   ordinal = 'th';
               break;
            }
        }
        return txt+ordinal;
    },      
    
    showAuthing: function() {
        $("#auth_form .action .auth_button").hide();
        $("#auth_form .action").append("<span id='authing' class='activity'>Working  <img style='display: inline; margin-left:15px;' src='/media/imgs/activity.gif'/></span>");
    },
    
    hideAuthing: function() {
        $('#authing').remove();
        $("#auth_form .action .auth_button").show();
    },    
    
    showFollowing: function() {
        $("#auth_form .actions input").hide();
        $("#auth_form .actions").append("<span id='following' class='activity'>Working  <img style='display: inline; margin-left:15px;' src='/media/imgs/activity.gif'/></span>");
    },
    
    hideFollowing: function() {
        $('#following').remove();
        $("#auth_form .actions input").show();
    },     
    
    showSearching: function() {
        $("#search_button_container input").hide();
        $("#search_button_container").append("<span id='searching' class='activity'>Working  <img style='display: inline; margin-left:15px;' src='/media/imgs/activity.gif'/></span>");
    },
    
    hideSearching: function() {
        $('#searching').remove();
        $("#search_button_container input").show();
    },
    
    showUpdating: function() {
        $('#updating').show();
    },
    
    hideUpdating: function() {
        $('#updating').hide();
    },    
    
    showPosting: function() {
        $("#update_button_container input").hide();
        $("#update_button_container").append("<span id='posting' class='activity'>Posting  <img style='display: inline; margin-left:15px;' src='/media/imgs/activity.gif'/></span>");;
    },
    
    hidePosting: function() {
        $('#posting').remove();
        $("#update_button_container input").show();
    },        
    
    validateUpdate: function() {
        
        var message = $('#message').val();
        var wrongMessage = false;
        //var wrongCredentials = false;
        $('#message').removeClass('error');
        $('#message').next('p.error').html('');
        $('#message').next('p.error').hide();
        //$('#credentials_error_box').html('');
        //$('#credentials_error_box').hide();
        
        if( 140 <  message.length ) {
            $('#message').next('p.error').append('<span>Message must be less then 140 characters. Please make the text shorter.</span>');
            var wrongMessage = true;
        }
        
        if( !/@tweetmas/.test(message) && !/#tweetmas/.test(message) ) {
            $('#message').next('p.error').append('<span>Message must contain @tweetmas/#tweetmas. Please put any into text.</span>');
            var wrongMessage = true;
        }
        
        
        if( '@tweetmas' == trim(message) ) {
            $('#message').next('p.error').append('<span>Message doesn\t contain any text. Please add a text after "@tweetmas".</span>');
            var wrongMessage = true;
        }
        
        /*
        if( '' == $('#twitter_username').val() ) {
            $('#credentials_error_box').append('<span>Username is empty. Please fill the field.</span>');
            var wrongCredentials = true;
            var wrongUsername = true;
        }
        
        if( '' == $('#twitter_password').val() ) {
            $('#credentials_error_box').append('<span>Password is empty. Please fill the field.</span>');
            var wrongCredentials = true;
            var wrongPassword = true;
        }*/        
        
        if(wrongMessage) {
            $('#message').next('p.error').show();
            $('#message').addClass('error');
        }

        /*
        if(wrongCredentials) {
            $('#credentials_error_box').show();
        }
        
        
        if(wrongUsername) {
            $('#twitter_username').addClass('error');
        }
        
        if(wrongPassword) {
            $('#twitter_password').addClass('error');
        }        
        */
        if( wrongMessage ) {
            return false;
        } else {
            return true;
        }
    },
    
    validateSearcher: function() {
        $('#searcher_error_box').hide();
        $('#search_twitter_username').removeClass('error');
        
        
        if( '' == $('#search_twitter_username').val() ) {
            $('#searcher_error_box').append('<span>Username is empty. Please fill the field.</span>');
            $('#search_twitter_username').addClass('error');
            $('#searcher_error_box').show();
            return false;
        }  
        
        return true;
        
    }
    
}

function form_sent(event) {

}

function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

