// When the DOM is ready, initialize the script.
$(function(){

    /**
     * Initialize
     */

    /**
     * Blocks
     */
    var spinner = '<div class="spinner visible"></div>';

    /**
     * Calls being made right now
     */
    var $beingMadeRightNow = $('.beingMadeRightNow');
    if ($beingMadeRightNow.length) {
        var scroll = function() {
            var $first = $beingMadeRightNow.find('li:first');
            var $last = $beingMadeRightNow.find('li:last');
            $first.fadeOut(500,function(){
                $last.after($first);
                $first.fadeIn(500);
            });
        }

        setInterval(scroll, 4000);
    }

    /**
     * Blocks
     */
    if ($('#newBadge').length) {
        $('#newBadge').dialog({
            resizable:  false,
            modal:      true,
            autoOpen:   true,
            buttons: {
                "Ok": function() {
                    $(this).dialog('close');
                }
            }
        });
    }

    /**
     * Inputs
     */
    $('.focusable').focus(function(){$(this).addClass('focused')})
                    .blur(function(){$(this).removeClass('focused')})


    /**
     * Friend Requests
     */

    if ($('#friendRequests').hasClass('active')) {
        var $friendsRequests = $('#friendRequests');
        var $friendsRequestsIcon = $friendsRequests.children('.icon');
        var $friendsCount = $friendsRequestsIcon.html();

        // clicking on icon
        $friendsRequestsIcon.click(function(){
            if ($friendsRequests.hasClass('active')) {
                $friendsRequests.toggleClass('opened');
                $friendsRequests.children('.requests').toggle();
                if ($friendsCount < 1) {
                    $friendsRequests.removeClass('active')
                }
                $friendsRequests.find('li.toRemove').remove();
            }
        });

        // clicking on buttons
        $friendsRequests.click(function(e){
            $target = $(e.target);
            if($target.hasClass('button')) {
                var $requestContainer = $target.parent();
                $requestContainer.empty().append(spinner);
                $.ajax({
                    type:       'POST',
                    url:        $target.attr('href'),
                    success:    function(data){
                        // icon
                        $friendsRequestsIcon.html($friendsCount-1);
                        $friendsCount -= 1;
                        if ($friendsCount< 1) {
                            $friendsRequestsIcon.empty();
                        }
                        // request container
                        $requestContainer.html(data);
                        $requestContainer.addClass('toRemove');
                    }
                });
                return false;
            }
        });
    }

    /**
     * Shouts
     */
    if ($('#shoutform')) {
        var $form = $('#shoutform').children('form');
        var $textarea = $form.children('textarea');
        var $counter = $('#counter');

        function syncCounter() {
            if ($textarea.val() != $textarea.attr('title')) {
                $counter.html(100-$textarea.val().length);
            } else {
                $counter.html(100);
            }
        }

        $textarea.focus(function(){
            syncCounter();
            // Textarea value
            if ($textarea.val() == $textarea.attr('title'))
                $textarea.val('');
            // style
            $textarea.addClass('focused');
        });
        $textarea.blur(function(){
            syncCounter();
            // Textarea value
            if (!$textarea.val())
                $textarea.val($textarea.attr('title'));
            // style
            $textarea.removeClass('focused');
        });
        $textarea.keydown(function(){
            syncCounter();
        })

        $form.submit(function(){
            // Data validation
            if (!$textarea.val() || $textarea.val() == $textarea.attr('title')) {
                alert('Please enter text.');
                return false;
            } else if ($textarea.val().length > 100) {
                alert('Your text is longer than 100 s   ymbols.');
                return false;
            }

            // Spinner
            $('.spinner').addClass('visible');

            // Request
            $.ajax({
                type:       'POST',
                url:        $form.attr('action'),
                data:       $form.serialize(),
                success:    function(data){
                    $('#shouts').html(data)
                },
                complete:   function(){
                    $textarea.val($textarea.attr('title'));
                    $('.spinner').removeClass('visible');
                    syncCounter();
                }
            });

            return false;
        })
    }

    /**
     * User friends
     */
    if ($('#myFriends')) {
        // When user clicks to remove button
        $(this).find('.remove').click(function(e){
            $("#dialog-confirm-remove").dialog('open');
            // Url to remove friend
            removeFriendTarget = e.currentTarget;
            return false;
        });

        // Dialog box
        $("#dialog-confirm-remove").dialog({
			resizable:  false,
			modal:      true,
            autoOpen:   false,
			buttons: {
				"Yes": function() {
					$.ajax({
                        type:       'POST',
                        url:        removeFriendTarget.href,
                        success:    function(data){
                            $(removeFriendTarget).parent().remove()
                        }
                    });
                    $("#dialog-confirm-remove").dialog('close');
				},
				"No": function() {
					$(this).dialog('close');
				}
			}
		});

        // Dialog box
        $("#dialog-confirm-invitation").dialog({
			resizable:  false,
			modal:      true,
            autoOpen:   true,
			buttons: {
				"Yes": function() {
					$.ajax({
                        type:       'POST',
                        url:        $("#dialog-confirm-invitation a").attr('href'),
                        success:    function(data){
                            $('.response .success').html(data).show();
                        }
                    });
                    $("#dialog-confirm-invitation").dialog('close');
				},
				"No": function() {
					$(this).dialog('close');
				}
			}
		});

        // Scroll friends calls
        var $scrollableArea = $('#friendsCalls').data('jsp');
        if ($scrollableArea) {
            scrollFriendsCalls = function() {
                $scrollableArea.scrollByY(20,true);
                setTimeout('scrollFriendsCalls()', 1000);
            }
            setTimeout('scrollFriendsCalls()', 1000);

            $('.scroll-pane').bind(
                'jsp-arrow-change',
                function(event, isAtTop, isAtBottom, isAtLeft, isAtRight){
                   if (isAtBottom) {
                       scrollFriendsCalls = function(){};
                   }
                }
            );

            $('#friendsCalls').mouseover(function(){
                scrollFriendsCalls = function(){};
            });
        }
    }

    /**
     * Settings
     */
    if ($('#photoSection').length) {
        var $dialogImages = $('#dialog-images');
        var $images = $dialogImages.find('li');

        $dialogImages.dialog({
            resizable:  false,
            modal:      true,
            autoOpen:   false,
            buttons: {
                "Ok": function() {
                    var answer = confirm('Do you really want to change your picture?');
                    if (answer) {
                        $('#userpic').attr('src',$('#selectedId').val());
                        $(this).dialog('close');
                    }
                },
                "Cancel": function() {
                    $(this).dialog('close');
                }
            }
        });

        $('.changeimage').click(function(){
            $dialogImages.dialog('open');
            return false;
        });

        $images.click(function(){
            $images.removeClass('selected');
            $(this).addClass('selected');
            $('#selectedId').val($(this).find('img').attr('src'));
        });
    }

    /**
     * profileSetup/setup
     */
    $("#zipCodeWindow").dialog({
        resizable:  false,
        modal:      true,
        autoOpen:   true,
        buttons: {
            "Ok": function() {
                $.ajax({
                    type:       'POST',
                    data:       "zipCode=" + $("#zipCodeWindow #zipCode").val(),
                    url:        $("#zipCodeWindow a").attr('href'),
                    success:    function(data){
                        if (data)
                            $("#zipCodeWindow .response").html(data).show();
                        else
                            $("#zipCodeWindow").dialog('close');
                    }
                });
            },
            "Cancel": function() {
                $(this).dialog('close');
            }
        }
    });


    /**
     * Challenge
     */
    if ($('#challengefriends').length) {

        var sliderDefaultMin = 1;
        var sliderDefaultMax = 100;

        var $slider = $("#slider-range-max");
        var $submitButton = $('.startthechallenge');
        var credPoints = document.getElementById('amount');

        // Slider
        $slider.slider({
            range: "min",
            min: sliderDefaultMin,
            max: sliderDefaultMax,
            value: 10,
            slide: function(event, ui) {
                credPoints.value = ui.value;
            },
            change: function(event, ui) {
                credPoints.value = ui.value;
            }
        });
        // Slider input
        credPoints.value = $slider.slider("option", "value");
        $(credPoints).change(function(){
            $slider.slider("option", "value", this.value);
        });

        // Select friends to challenge
        $('#friendsToChallenge').click(function(e){
            var $target = $(e.target); // event target

            if($target.is('img')) {
                var targetPoints = parseInt($target.parent().children('.points').html());
                var userId = parseInt($target.parent().children('.userId').html());
                var sliderValue = $slider.slider("option", "value");

                $target.parent().appendTo("#friendsChallenging"); // move friend <LI> to challenging friends list
                $('<input type="hidden" name="friendid" value="' + userId + '">').appendTo("#challengefriends"); // move friend <LI> to challenging friends list
                $('#friendsChallenging .message').hide(); // hide "There are no selected friends" from challenging friends list
                $submitButton.removeClass('disabled'); // make submit button active (clickable)

                // Slider maximum value
                if (targetPoints < $slider.slider("option", "max")) {
                    $slider.slider("option", "max", targetPoints);

                    if (targetPoints < sliderValue) {
                        $slider.slider("option", "value", targetPoints);
                    } else {
                        // jQuery UI bug. It doesn't change the slider's position after changing slider's MaxValue
                        // We are setting value, to avoid this problem.
                        $slider.slider("option", "value", sliderValue);
                    }
                }

                // Show "All your friends are selected"
                if ($('#friendsToChallenge li').length < 2) {
                    $('#friendsToChallenge .message').show();
                }
            }
        });

        // Friends you are challenging
        $('#friendsChallenging').click(function(e){
            $target = $(e.target); // event target

            if($target.is('img')) {
                var targetPoints = parseInt($target.parent().children('.points').html());
                var userId = parseInt($target.parent().children('.userId').html());
                var sliderValue = $slider.slider("option", "value");

                $target.parent().appendTo("#friendsList ul:first"); // move friend <LI> to friends list"
                $('#challengefriends input[value="' + userId + '"]').remove();
                $('#friendsList .message').hide(); // hide "All your friends are selected" from challenging friends list

                // Slider maximum value
                if (targetPoints == $slider.slider("option", "max")) {
                    var max = sliderDefaultMax;
                    $('#challengefriends').find('.points').each(function(){
                        if ($(this).html() < max) max = $(this).html();
                    });

                    $slider.slider("option", "max", max);

                    // jQuery UI bug. It doesn't change the slider's position after changing slider's MaxValue
                    // We are setting value, to avoid this problem.
                    $slider.slider("option", "value", sliderValue);
                }

                // show "There are no selected friends
                if ($('#friendsChallenging li').length < 2) {
                    $('#friendsChallenging .message').show();
                    $submitButton.addClass('disabled'); // make submit button inactive
                }
            }
        });
        /**
         * Sharing
         */
        $('.socialBox input:checkbox').removeAttr('checked'); // for FF

        $('.socialBox').click(function(e){
            $target = $(e.target); // event target

            if($target.is('input:checkbox')){
                $(this).children('.hidden').toggle();
            }
        })

        var $textareas = $('.socialBox textarea');

        $textareas.focus(function(){$(this).addClass('focused')})
        $textareas.blur(function(){$(this).removeClass('focused')})

        $('#challengeEmails').change(function(){
            if ($(this).val())
                $submitButton.removeClass('disabled');
        });

        // Button
        $submitButton.click(function(){
            if ($submitButton.hasClass('disabled')) {
                return false;
            }
        });
    }

    // Scrollbars
    $('.scroll-pane').jScrollPane({
        showArrows: true
    });
    $('.scroll-pane-arrows').jScrollPane(
		{
			showArrows: true,
			horizontalGutter: 10
		}
	);

    // Inputs
    $('.input').focus(function(){
        $(this).addClass('focus');
    });
    $('.input').blur(function(){
        $(this).removeClass('focus');
    });

});


