var ideafolio = {
    setGlobals: function() {
        $editStyleLink = $('#edit-design-style');
        $rowSelector = $('div.row-selector');
        $rowSelectorClean = $rowSelector.clone();
        $rowLabels = $('div.row-label');
        viewAllHTML = '<div class="view-all">View All</div>';
        $projectNames = $('#project-info .name');
    },

    showStyles: function(data) {
        var $data = data;
        $header.after($data.hide().fadeIn(200, function() { ideafolio.setOptionsClose(); }));
    },

    hideStyles: function() {
        $('#design-styles').fadeOut().remove();
        $('#flyout-wrapper').remove();
    },

    hideCommentForm: function() {

    },

    getStyles: function() {
        $.ajax({
            url: '/includes/design-styles.html',
            success: function(data) {
                ideafolio.showStyles($(data));
            }
        });
    },

    setStyleEdit: function() {
        if ($editStyleLink.length) {
            $editStyleLink.click(function() {
                if (!$('#design-styles').length) {
                    ideafolio.getStyles();
                    ideafolio.captureClicks();
                }
                return false;
            });
        }
    },

    setOptionsClose: function() {
        $('p.options-close, #flyout-wrapper').click(function() {
            ideafolio.hideStyles();
        });
    },

    flipProjectName: function() {
        $('#project-name').insertBefore('#current-project');
    },

    flipStyleName: function() {
        $('#style-name').insertBefore('#your-style');
    },

    setShowHide: function() {
        if (!$('div.show-hide-bottom').hasClass('closed')) {
            $('div.show-hide-bottom').addClass('displayed');
            $('a.show-hide-head').addClass('selected');
        } else {
            $('div.show-hide-bottom').hide();
            $('div.show-hide-bottom').find('.grid-content-row').children().children().css({
                opacity: 0
            });
        };

        var $theSlider;
        var $theLink;
        var inMotion = false;

        $('#show-hide a').focus(function() {
            $(this).blur();
        });

        $('#show-hide a.show-hide-head').click(function() {

            $(this).blur();
            $theLink = $(this);
            $theSlider = $(this).next().children();

            if (inMotion === true) {
                return false;
            } else {
                inMotion = true;
                if ($theLink.hasClass('selected')) {
                    $theLink.removeClass('selected');
                } else {
                    $theLink.addClass('selected');
                };

                if ($theSlider.hasClass('displayed')) {
                    $theLink.removeClass('selected');
                    $theSlider.find('.grid-content-row').children().children().animate({
                        opacity: 0
                    }, 150, function() {
                        $theSlider.slideUp(500, function() {
                            inMotion = false;
                        });
                        $theSlider.removeClass('displayed');
                        $theLink.removeClass('selected');
                    });
                } else {
                    $theLink.addClass('selected');
                    inMotion = false;
                    $theSlider.slideDown(500, function() {
                        $(this).find('.grid-content-row').children().children().stop().animate({
                            opacity: 1
                        }, 500, function() {
                            $theSlider.addClass('displayed');
                            $theLink.addClass('selected');
                        });
                    });
                };
            }
            return false;
        });
    },

    switchViewAlls: function(elm) {
        var $elm = $(elm);
        if ($elm.data('state') === 'closed' || $elm.data('state') === undefined) {
            $elm.text('Compact View');
            $elm.data('state', 'open');
        } else {
            $elm.text('View All');
            $elm.data('state', 'closed');
        }
    },

    addCarousel: function(elm) {
        elm.jcarousel({
            buttonNextHTML: '<div class="right-arrow"></div>',
            buttonPrevHTML: '<div class="left-arrow"></div>'
        });
    },

    buildRowSelectors: function() {
        var $thisRow;
        if ($('body.ideafolio-preferences').length) {
            ideafolio.addCarousel($('div.row-selector ul'));
            $rowLabels.find('h4').after(viewAllHTML);
            $viewAlls = $('div.view-all');
            $viewAlls.each(function(i) {
                $(this).data('idx', i);
            });
            $('div.view-all').click(function() {
                var $this = $(this);
                $thisRow = $this.parents('div.row-wrapper').find('div.row-selector');
                if ($thisRow.find('div.jcarousel-container').length) {
                    ideafolio.switchViewAlls($this);
                    $this.parent().next().remove();
                    $this.parents('div.row-wrapper').append($rowSelectorClean[$this.data('idx')]);
                } else {
                    ideafolio.switchViewAlls($this);
                    ideafolio.addCarousel($thisRow.find('ul'));
                }
            });
        }
    },

    myDesignCarousel: function() {
        if ($('ul.carousel').length) {
            ideafolio.addCarousel($('div.row-selector ul'));
        }
    },

    setupPrefs: function() {
        if ($('body.ideafolio-preferences').length) {
            $('div.all').hide();

            var switchLabel = function(elm) {
                if (elm.text() === 'view all') {
                    $(elm).text('view suggested only');
                } else {
                    $(elm).text('view all');
                }
            };

            //Default selections

            $('div.suggested, div#doors-all').find('input:first').attr('checked', true).parents('li').addClass('selected');
            $('div.view-all').click(function() {
                var $all = $(this).parents('div.row-wrapper').find('div.all');
                if ($all.hasClass('showing')) {
                    $all.removeClass('showing').slideUp(300);
                    switchLabel($(this));
                } else {
                    $all.addClass('showing').slideDown(600);
                    switchLabel($(this));
                }
				ideafolio.setRowSelectorHeights();
            });

            $('div.row-wrapper li').live('click', function() {
                var $this = $(this);
                $this.parents('div.row-wrapper').find('li.selected').removeClass('selected');
                $this.addClass('selected').find('input[type="radio"]').attr('checked', 'checked');
            });
        }
    },

    setupProjectInfo: function() {
        var $curNameWidth = 0;
        var $overallNameWidth = 0;
        $projectNames.each(function() {
            $curNameWidth = parseFloat($(this).width());
            if ($curNameWidth >= $overallNameWidth) {
                $overallNameWidth = $curNameWidth;
            };
        });
        $overallNameWidth = $overallNameWidth + 2;
        $overallNameWidth = $overallNameWidth + 'px';
        $projectNames.css('width', $overallNameWidth);
    },

    isProjectNameUnique: function(value, element, params) {
        var matchingValue = $('#folioProjectID option').filter(function() {
            return this.text.toLowerCase() == value.toLowerCase();
        }).attr('value');

        if (matchingValue) {
            return false;
        }

        return true;
    },

    manageProjectSetup: function() {
        $('#rename-project-link').click(function() { $('#fRenameProject').submit(); });
        $('#copy-project-link').click(function() { $('#fCopyProject').submit(); });
        $('#add-project-link').click(function() { $('#fAddProject').submit(); });
        $('#switch-project-link').click(function() { $('#fSwitchProject').submit(); });
        $('#remove-project-link').click(function() {
            if (confirm("Are you sure you want to DELETE the project?")) {
                // Output when OK is clicked
                $('#fRemoveProject').submit();
            }
        });
    },

    isDesignNameUnique: function(value, element, params) {
        var matchingValue = $('#folioDesignID option').filter(function() {
            return this.text.toLowerCase() == value.toLowerCase();
        }).attr('value');

        if (matchingValue) {
            return false;
        }

        return true;
    },

    manageDesignSetup: function() {
        $('#rename-design-link').click(function() { $('#fRenameDesign').submit(); });
        $('#copy-design-link').click(function() { $('#fCopyDesign').submit(); });
        $('#folioDesignID').change(function() { $('#fSwitchDesign').submit(); });
        $('#remove-design-link').click(function() {
            if (confirm("Are you sure you wish to delete this design?")) {
                location.href = '/ideafolio/remove-design.html';
            }
        });
    },

    blockOffContentRows: function(selectorRow, selectorItem, count, height) {
        var i, totalCount = 0, curCount = 0, limit;
        $(selectorRow).each(function() { //'.show-hide-wrapper .container_3'
            i = 0;
            curCount = 0;
            totalCount = 0;
            totalCount = $(this).find(selectorItem).size();
            totalCount = totalCount - 1;
            limit = count - 1;
            $(this).find(selectorItem).each(function() { //'.grid_1'

                curCount = curCount + 1;

                if (i === limit) {
                    if (curCount !== totalCount) {
                        $(this).after('<div style="height: ' + height + 'px; clear: both;"></div>'); // 20
                    };
                    i = 0;
                } else {
                    i = i + 1;
                };
            });

        });
    },

    setupComments: function() {
        $('.show-hide-wrapper .comments-container').each(function() {
            $(this).find('.user-comments').css('display', 'none');
            $(this).find('.update_comment').css('display', 'none');

            if ($(this).find('.comment .comment-text').html() !== "") {
                $(this).parent().find('a.add-comment').html('Edit Comment');
            } else {
                $(this).find('.comment').css('display', 'none');
                $(this).find('.last-modified-date').css('display', 'none');
            };

            $(this).parent().find('a.add-comment').click(function() {

                // console.log($(this).html());
                if ($(this).hasClass('editing')) {
                    // console.log('yep i am editing');
                    $(this).removeClass('editing');
                    $(this).parent().next().children().find('.comment-container').css('display', 'block');
                    $(this).parent().next().children().find('.user-comments').css('display', 'none');
                    $(this).parent().next().children().find('.update_comment').css('display', 'none');
                } else {
                    $(this).addClass('editing');
                    $(this).parent().next().children().find('.comment-container').css('display', 'none');
                    $(this).parent().next().children().find('.user-comments').css('display', 'block');
                    $(this).parent().next().children().find('.update_comment').css('display', 'block');
                    $(this).parent().next().children().find('.user-comments textarea').focus();
                }
                return false;
            });
        });

        $('.update_comment a').each(function() {
            var params = this.id.split('-');
            $(this).bind('click', { folioDataTypeID: params[params.length - 2], folioDataItemID: params[params.length - 1] }, ideafolio.addUpdateComment);
            $(this).click(function() {
                $(this).parent().parent().find('.user-comments').css('display', 'none');
                $(this).parent().css('display', 'none');
                $(this).parent().parent().find('.comment-container').css('display', 'block');
                $(this).parent().parent().find('.comment-container .comment').css('display', 'block');
                $(this).parent().parent().find('.comment-container .last-modified-date').css('display', 'block');
                $(this).parent().parent().parent().parent().find('.add-comment').removeClass('editing');
                $(this).parent().parent().parent().parent().find('.add-comment').html('Edit Comment');
                if ($(this).parent().parent().find('.user-comments textarea').val() === '') {
                    $(this).parent().parent().parent().parent().find('.add-comment').html('Add Comment');
                    $(this).parent().parent().find('.comment-container').css('display', 'none');
                };
            });

        });
    },

    addUpdateComment: function(event) {
        var comment = $('#tComment-' + event.data.folioDataTypeID + '-' + event.data.folioDataItemID);
        var gJsonUpdateItemComment = '/ideafolio/update-item-comment.html';

        var jsonArgs = {};
        jsonArgs['folioDataTypeID'] = event.data.folioDataTypeID;
        jsonArgs['folioDataItemID'] = event.data.folioDataItemID;
        jsonArgs['comment'] = comment.val();
        jsonArgs['cacheBust'] = (new Date()).getTime();

        $.getJSON(gJsonUpdateItemComment, jsonArgs, function(data, status) {
            var comment = $('#tComment-' + data.FolioDataTypeID + '-' + data.FolioDataItemID);
            var commentDiv = $('#comment-text-' + data.FolioDataTypeID + '-' + data.FolioDataItemID);
            var lastmodifiedDiv = $('#comment-datemodified-' + data.FolioDataTypeID + '-' + data.FolioDataItemID);

            commentDiv.html(comment.val());
            lastmodifiedDiv.html(data.DateUpdated);

            // var commentParent = comment.parent();
            // 			var commentDivParent = commentDiv.parent();
            //
            // 			comment.parent().css('display', 'none');
            // 			commentDiv.parent().parent().css('display', 'block');
        });

        event.preventDefault();
    },

    /*
    * initialize login click handler for registration login control
    */
    loginConfig: function() {
        $('#registerLoginErrorMsg').hide();
        $('#registerLoginMsg').hide();

        merillat.initLoginClick('registerloginform', 'registerloginbutton', 'registerLogin_Email', 'registerLogin_Password', 'registerLoginMsg', 'registerLoginErrorMsg', '/ideafolio/login-register-submit.html');
    },

    /*
    * initialize login click handler for forgot password login control
    */
    forgotPasswordConfig: function() {
        $('#registerLoginErrorMsg').hide();
        $('#registerLoginMsg').hide();

        merillat.initForgotPasswordClick('registeriforgotmypwd', 'registerLogin_Email', 'registerLoginMsg', 'registerLoginErrorMsg');
    },

    // Set Prefs items to equal heights with their siblings	
    setRowSelectorHeights: function() {
			
        var $rows = $('div.row-wrapper').not('div#content-hider div.row-wrapper');
        $rows.each(function() {
			//console.log( $('h4', this).text() );
            var $cells = $(this).find('div.image-container');
            $cells.each(function() {
				$(this).css({ height:'auto' })  // added so that can recall this function when view all is clicked - ep
               // console.log('this.height: ', $(this).height());
            });
            lib.equalHeight($cells);
        });
    },

	fromWizardCloseButton: function() {
		$('#kitchen-planner-help-content .button-replacer').click(function() {
			$('#cboxClose').click();
		});
	}
};

$(document).ready(function() {
	ideafolio.setGlobals();
	ideafolio.setStyleEdit();
	ideafolio.flipProjectName();
	ideafolio.flipStyleName();
	ideafolio.setShowHide();
	ideafolio.hideCommentForm();
	ideafolio.myDesignCarousel();
	ideafolio.setupPrefs();
	ideafolio.setupProjectInfo();
	ideafolio.manageProjectSetup();
	ideafolio.manageDesignSetup();
	ideafolio.setupComments();
	ideafolio.blockOffContentRows('.show-hide-wrapper .container_3', '.grid_1', 3, 20);
	ideafolio.blockOffContentRows('div.row-selector', 'div.spacer', 3, 0);
	ideafolio.blockOffContentRows('div.door-row-selector', 'div.door-spacer', 5, 0);
	setTimeout(function(){
		ideafolio.setRowSelectorHeights();
	}, 2000);
	ideafolio.fromWizardCloseButton();
	
});
