var sips = {
Twitter : function(){
    var twitterURL = 'http://twitter.com/status/user_timeline/FolloFlyklubb.json?callback=?&count=3';

    $.ajax({
        url: twitterURL,
        dataType: 'jsonp',
        timeout: 10000,
        error: function(data, err) {
            $('#tweets').hide().append('<li>' + err + '</li>');
            $('#twitterLoader').fadeOut("slow").remove();
            $('#tweets').fadeIn("slow");  
        },
        success: function(data) {
            $.each(data, function(i, tweets) {
                var twitterStatus = '<div class=\"twitterText\">' + tweets.text + '</div>'                    
                var twitterRelativeTime = relative_time(tweets.created_at);
                var twitterTimestamp = '<div class=\"twitterTimestamp\">'
                                    + twitterRelativeTime
                                    + '</div>';
                
                $('#tweets').hide().append('<li>' + twitterStatus + twitterTimestamp+ '</li>');
            });
            $('#twitterLoader').fadeOut("slow").remove();
            $('#tweets').fadeIn("slow");
        }
    });
},

WeatherAjax : function(){
    $("div [id='weatherBox']").hide().load("../modules/weather_load.php", function() {            
        $("div [id='weatherLoaderBox']").fadeOut("slow", function () {
            $("div [id='weatherBox']").fadeIn("slow");
            $(this).remove();
        });
    }); 
},

Tooltip : function(){
    $("div [id^='tooltip']").each(function(index) {
        $(this).hover(function (e) {
            $("#toolWin" + index).css("top", e.pageY + 6).css("left", e.pageX + 20).css("display", "block");
            $("#toolWin" + index).animate({ opacity: 1.0 }, 100);
        },
        function () {
            $("#toolWin" + index).animate({ opacity: 0.0}, 100, function() {
                $("#toolWin" + index).css("display", "none");
            });
        });
    
		$(this).mousemove(function(e) {
            $("#toolWin" + index).css("top", e.pageY + 6).css("left", e.pageX + 20);
        });
	});
},

Comment : function(){
    $("[id='submitComment']").click(function(e) {
        e.preventDefault();
        articleId = $('#articleId').val();
        userId = $('#userId').val();
        commentId = $('#commentId').val();
        comment = $('#comment').val();
        counter = $('#commentCounter').html() * 1;
       
        if (commentId == 0) {   // New comment
            $.post("modules/comment_insert.php", {articleId: articleId, userId: userId, commentId: commentId, comment: comment}, function (returnData) {			
                $("#commentBox-" + commentId).fadeOut("slow", function() {
                    $('#commentBox-' + commentId).replaceWith(returnData).hide().fadeIn("slow");
                    // update counter
                    $('#commentCounter').html(" " + (++counter));
                    
                    
                    // SET DELIGATE TO THE CLOSE BUTTON HERE!!!!!!
                    $('#commentId-0 div div img').live('click', function() {
                        commentId = $(this).attr('id');
                        commentId = commentId.substr(16) * 1;
                        var deleteConfirm = confirm("Vil du virkelig slette?");
                        if (deleteConfirm == true) {
                            $.post("modules/comment_delete.php", {commentId: commentId }, function (returnData) {	
                                $('#commentId-0').slideUp("slow", function() {
                                    $("#commentId-0 + li").remove();                   
                                    $("#commentId-0").remove();                                     
                                    // Insert the form again
                                    //$.post("modules/comment_form.php", {commentId: 0, userId: userId, articleId: articleId}, function (returnData) {

                                    //    $('#commentList').prepend(returnData).hide().fadeIn("slow");
                                    //});
                                });
                                // update counter
                                $('#commentCounter').html(" " + (--counter));
                                
                            });
                        }
                    });
                    
                    
                });
            });            
        } else {                // Update old comment
            
        }
        
        /**    
            If commentId = 0 then it is a new submittet comment
            * $post the new comment
            * hide/slide the comment form, when complete insert the new comment
            * update the commentId and unhide the toolbox
            
            If commentId is <> 0 the it is an update
            * $post / update the comment
            * hide/slide the comment form, when complete insert the new comment
        */

        
        
	});
},

CommentDelete : function(){
    $("[id^='commentDeleteId']").each(function(index) {
        $(this).click(function () {
            var deleteConfirm = confirm("Vil du virkelig slette?");
            if (deleteConfirm == true) {
                commentId = $(this).attr('id');
                commentId = commentId.substr(16) * 1;
                $.post("modules/comment_delete.php", {commentId: commentId }, function (returnData) {			
                    $("#commentId-" + commentId).slideUp("slow", function() {
                        $("#commentId-" + commentId + "+ li").remove();                   
                        $("#commentId-" + commentId).remove();                      
                    });
    
    
                    // update counter
                    counter = $('#commentCounter').html() * 1;
                    counter--;
                    $('#commentCounter').html(" " + counter);
                });
            }
        });
	});
},

CommentEdit : function(){
    $("div [id^='commentEditId']").each(function(index) {
        $(this).click(function () {
            comment = commentId = $(this).attr('id');
            commentId = commentId.substr(14) * 1;
            
            /*
            if ($("[id^='commentWrapper-']")) {
                $("[id^='commentWrapper-']").remove();
            }*/
            $.post("modules/comment_edit.php", {commentId: commentId}, function (returnData) {			
                $('#commentBox-' + commentId).slideUp("slow", function() {
                    $('#commentBox-' + commentId).replaceWith(returnData);
                
                
                });
                
            }); 
        });
	});
},

PollBox : function(){
    $("#pollBox #pollButton").click(function(e) {
		// stop normal link click
		e.preventDefault();

		var pollNr = $("#pollNr").val();
		var pollLanguage = $("#pollLanguage").val();
		var vote = $('input:radio[name=pollVote]:checked').val();

        // Check if any radio button was selected
        if (vote == null) {
            alert("Make a selection first");
			return false;
        }

		// send request
		$.post("modules/poll_vote.php", {pollNr: pollNr, pollLanguage: pollLanguage, pollVote: vote}, function (returnData) {			
			
			$("#pollBox").slideUp("slow", function() {
				
				$('#pollBox').load("modules/poll_stats_load.php", function() {
					$("#pollBox").slideDown("slow");
				});	
			});
		});
    });
},

UserFormValidation : function(){
    $("#userSubmitButton").click(function(e) {
        mt1 = $("#username").val();
        mt2 = $("#password").val();
        mt3 = $("#confirm_password").val();
        mt4 = $("#first_name").val();
        mt5 = $("#last_name").val();
        mt6 = $("#first_name").val();
        mt7 = $("#email").val();
        
        if ($("#agree:checked").length == false) {
          alert('In order to continue, please check the box to agree with the terms.');
          e.preventDefault();
        } else {
          if ((mt1.length < 1) || (mt2.length < 1) || (mt3.length < 1) || (mt4.length < 1) || (mt5.length < 1) || (mt6.length < 1) || (mt7.length < 1)) {
            alert('You must fill in all the required fields.');
            e.preventDefault();
          } else {
            if (mt2 != mt3) {
              alert('Password fields do not match!');
                e.preventDefault();
            } else {
              if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(f.email.value)){
              } else {
                alert('Use a valid email address please.');
                e.preventDefault();
              }
            }
          }
        }
    });
}

}

jQuery(function ($) {
    if($("[id='twitterBox']").length){sips.Twitter();}
    if($("[id='weatherBox']").length){sips.WeatherAjax();}
    if($("[id='message']").length){sips.MessageAjax();}
    if($("div [id^='tooltip']").length){sips.Tooltip();}
    if($("#pollBox #pollButton").length){sips.PollBox();}
    if($("[id='user_form']").length){sips.UserFormValidation();}
    if($("li [id^='commentId']").length){sips.Comment();}
    if($("[id^='commentDeleteId']").length){sips.CommentDelete();}
    if($("[id^='commentEditId']").length){sips.CommentEdit();}
});

function relative_time(time_value) {
  var parsed_date = Date.parse(time_value);
  var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
  var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
  if (delta < 60) {
    return 'less than a minute ago';
  } else if (delta < 120) {
    return 'about a minute ago';
  } else if (delta < (45 * 60)) {
    return (parseInt(delta / 60)).toString() + ' minutes ago';
  } else if (delta < (90*60)) {
    return 'about an hour ago';
  } else if (delta < (24*60*60)) {
    return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
  } else if (delta < (48*60*60)) {
    return '1 day ago';
  } else {
    return (parseInt(delta / 86400)).toString() + ' days ago';
  }
}

/*





*/
