﻿/* TOC
 * 0.0 Constants 
 * 1.0 Utilities
 * 2.0 Popup 
 * 3.0 Validation
 * 4.0 Getter/Setter
 * 5.0 Ideation Display
 * 6.0 Page Load
 *************************************************************/

/* 0.0 Constants */

var WM_TITLE = 'Title', WM_DESCRIPTION = 'Description', WM_FIRST_NAME = 'First Name',
    WM_LAST_NAME = 'Last Name', WM_CITY = 'City (Optional)', WM_EMAIL_ADDRESS = 'Email Address',
    WM_YOUTUBE = 'YouTube URL (Optional)';
var WM_COLOR = '#666';

/* 1.0 Utilities */
function stripHtml(original) {
    return original.replace(/<[^>]+>/g, '');
}
function showWatermarks() {
    $('#txtTitle').Watermark(WM_TITLE, WM_COLOR);
    $('#txtDescription').Watermark(WM_DESCRIPTION, WM_COLOR);
    $('#txtFirstName').Watermark(WM_FIRST_NAME, WM_COLOR);
    $('#txtLastName').Watermark(WM_LAST_NAME, WM_COLOR);
    $('#txtCity').Watermark(WM_CITY, WM_COLOR);
    $('#txtEmailAddress').Watermark(WM_EMAIL_ADDRESS, WM_COLOR);
    $('#txtYouTube').Watermark(WM_YOUTUBE, WM_COLOR);
}
function clearFields() {
    $('#txtTitle').val('');
    $('#txtDescription').val('');
    $('#txtYouTube').val('');
    $('#txtFirstName').val('');
    $('#txtLastName').val('');
    $('#txtCity').val('');
    $('#txtEmailAddress').val('');
    $('#ddlState').val(0);
    $('#cbUserAgreement').attr('checked', false);
    $('#cbWalmartAssociate').attr('checked', false);
}
function pageError(errMsg) {
    showErrorDisplay();
}

/* 2.0 Popups */
function showPopup(target) {
    $.blockUI({
        message: $(target),
        css: {
            width: $(target).width(),
            top: ($(window).height() - $(target).height()) / 2.5 + 'px',
            left: ($(window).width() - $(target).width()) / 2 + 'px',
            border: 'none',
            cursor: 'default'
        }
    });
}
function showErrorDisplay() {
    showPopup('#pageError');
}
function showAddErrorDisplay() {
    showPopup('#validationError');
}
function showSuccessDisplay() {
    showPopup('#ideaCreateSuccess');
}
function showAlreadyVotedDisplay() {
    showPopup('#alreadyVoted');
}
function showIdeationDisplay() {
    showPopup('#ideaInfo');
}

/* 3.0 Validation */
function validateIdeation() {
    var isValid = validateFields();
    if (isValid) {
        var txtTitle = $('#txtTitle');
        var txtDescription = $('#txtDescription');
        var txtYouTube = $('#txtYouTube');
        var txtFirstName = $('#txtFirstName');
        var txtLastName = $('#txtLastName');
        var txtCity = $('#txtCity');
        var txtEmailAddress = $('#txtEmailAddress');

        var title = $.trim(stripHtml(txtTitle.val()));
        var description = $.trim(stripHtml(txtDescription.val()));
        var youTube = $.trim(stripHtml(txtYouTube.val()));
        var firstName = $.trim(stripHtml(txtFirstName.val()));
        var lastName = $.trim(stripHtml(txtLastName.val()));
        var city = $.trim(stripHtml(txtCity.val()));
        var email = $.trim(stripHtml(txtEmailAddress.val()));

        txtTitle.val(title);
        txtDescription.val(description);
        txtYouTube.val(youTube);
        txtFirstName.val(firstName);
        txtLastName.val(lastName);
        txtCity.val(city);
        txtEmailAddress.val(email);

        // remove HTML
        isValid = validateFields();
    }
    return isValid;
}

function validateFields() {
    var isValid = true;
    var errorMsg = '<ul>'

    // validation req's:
    //    need title
    var title = $.trim($('#txtTitle').val());
    if (title == '' || title == WM_TITLE) {
        isValid = false;
        errorMsg += '<li>Enter a title</li>';
    } else if (title.length > 100) {
        isValid = false;
        errorMsg += '<li>Limit your title to 100 characters.</li>';
    }

    //    need idea (< 255 chars)
    var description = $.trim($('#txtDescription').val());
    if (description == '' || description == WM_DESCRIPTION) {
        isValid = false;
        errorMsg += '<li>Enter a description.</li>';
    } else if (description.length > 255) {
        isValid = false;
        errorMsg += '<li>Limit your description to 255 characters.</li>';
    }

    //    enter name
    var firstName = $.trim($('#txtFirstName').val());
    if (firstName == '' || firstName == WM_FIRST_NAME) {
        isValid = false;
        errorMsg += '<li>Enter your first name.</li>';
    }
    var lastName = $.trim($('#txtLastName').val());
    if (lastName == '' || lastName == WM_LAST_NAME) {
        isValid = false;
        errorMsg += '<li>Enter your last name.</li>';
    }

    //    enter email
    var emailAddress = $.trim($('#txtEmailAddress').val());
    var emailRegex = /\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
    if (emailAddress == '' || emailAddress == WM_EMAIL_ADDRESS) {
        isValid = false;
        errorMsg += '<li>Enter your email address.</li>';
    } else if (!emailRegex.test(emailAddress)) {
        isValid = false;
        errorMsg += '<li>Enter a valid email address.</li>';
    }

    //    if youtube link, make it valid
    var youTube = $.trim($('#txtYouTube').val());
    if (youTube != '' && youTube != WM_YOUTUBE) {
        var urlRegex = /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;
        if (!urlRegex.test(youTube)) {
            isValid = false;
            errorMsg += '<li>Enter a valid YouTube URL.</li>';
        }
    }
    
    var cbUserAgreement = $('#cbUserAgreement');
    if (!cbUserAgreement.is(':checked')) {
        isValid = false;
        errorMsg += '<li>You must accept the Terms of Use.</li>';
    }

    errorMsg += '</ul>';

    var vsError = $('#vsError');
    if (!isValid) {
        vsError.html(errorMsg);
        showAddErrorDisplay();
    }
    return isValid;
}

/* 4.0 Getter/Setter */
function getPageIndex() {
    var index = $('#hPageIndex').val();
    if (index != '') {
        index = parseInt(index);
    } else {
        index = 0;
    }
    return index;
}
function getPageSize() {
    var size = $('#hPageSize').val();
    if (size != '') {
        size = parseInt(size);
    } else {
        size = 10;
    }
    return size;
}

/* 5.0 Ideation Display */
function getIdeationId(me) {
    var imgName = $(me).attr('id');
    var prefix = 'imgMore';

    return parseInt(imgName.substr(imgName.indexOf(prefix) + prefix.length));
}

function showIdeations(ideationResult) {
    var ideations = ideationResult.Ideations;

    $('#chart').setTemplateURL('/Templates/ideations.htm');
    $('#chart').processTemplate(ideations);
    $('#chart table tr').removeClass('alt');
    $('#chart table tr:even').addClass('alt');

    $('#chart table tr .more img').each(function(img) {
        var id = getIdeationId(this);

        $(this).click(function() {
            expandIdeation(id);
        });
    });

    var pageIndex = getPageIndex();
    var pageSize = getPageSize();
    var baseIndex = pageIndex * pageSize;

    $('#pgrPrev').show();
    $('#pgrNext').show();

    if (pageIndex == 0) {
        $('#pgrPrev').hide();
    }

    if (baseIndex + pageSize >= ideationResult.Count) {
        $('#pgrNext').hide();
    }

    $('#viewCount').html((baseIndex + 1) + '-' + (baseIndex + ideations.length));
    $('#itemCount').html(ideationResult.Count);

    $('#pager').show();
}
function loadIdeations(callback) {
    var pageIndex = $('#hPageIndex').val();
    var state = $('#hState').val();
    var pageSize = $('#hPageSize').val();

    getPagedIdeations(pageIndex, pageSize, function(result) {
        showIdeations(result);
        // if set to preload ideation, do so
        if (INITIAL_IDEATION != '') {
            expandIdeation(INITIAL_IDEATION);
        }
    },
    state);
}

function expandIdeation(id) {
    getIdeation(id, function(idea) {
        var infoText = '<p class="ideaDescription">' + idea.Description + '</p>';
        infoText += '<span class="ideaSubmitter">Submitted by ' + idea.FirstName + ' ' + idea.LastName + '</span>';
        if (idea.IsAssociate) {
            infoText += ' <img class="associateBadge" src="/Images/Ideation/associateBadge.png" alt="Walmart Asscociate" title="Walmart Associate" />';
        }
        infoText += '<div class="clear"><!-- --></div>';

        var trInfoText = '<tr id="trInfo' + id + '"><td colspan="4" class="ideaExpanded">' + infoText + '</td></tr>';

        var trIdea = $('#tr' + id);
        trIdea.after(trInfoText);

        // remove bottom border
        $('#tr' + id + ' td').addClass('selectedRecord');

        var imgToggle = $('#tr' + id + ' td.more img:first');

        imgToggle.attr({
            src: '/Images/Layout/ideation_less.png',
            alt: 'Hide',
            title: 'Hide'
        }).unbind('click').click(function() {
            hideIdeation(id); return false;
        });
    });
}
function hideIdeation(id) {
    // remove expanded row from display
    var ideationRows = $('#ideationList tr');
    ideationRows.remove('#trInfo' + id);
    // add border
    $('#tr' + id + ' td').removeClass('selectedRecord');
    // toggle expanded
    var imgToggle = $('#tr' + id + ' td.more img:first');

    imgToggle.attr({
        src: '/Images/Layout/ideation_more.png',
        alt: 'Expand',
        title: 'Expand'
    }).unbind('click').click(function() {
        expandIdeation(id); return false;
    });
}

/* 6.0 Page Load */
$(function() {
    $('#hlClose').click(function() {
        $('#container').fadeOut('1500', function() {
            window.close();
        });
        return false;
    });

    $('#pgrNext').click(function() {
        var pageIndex = parseInt($('#hPageIndex').val());
        pageIndex++;
        $('#hPageIndex').val(pageIndex);

        loadIdeations();
        return false;
    });

    $('#pgrPrev').click(function() {
        var pageIndex = parseInt($('#hPageIndex').val());
        pageIndex--;
        if (pageIndex < 0) {
            pageIndex = 0;
        }

        $('#hPageIndex').val(pageIndex);

        loadIdeations();
        return false;
    });

    $('#ibSubmit').click(function() {
        if (validateIdeation()) {
            var youTube = $('#txtYouTube').val();
            var city = $('#txtCity').val();

            var summary = {
                Title: $('#txtTitle').val(),
                Description: $('#txtDescription').val(),
                FirstName: $('#txtFirstName').val(),
                LastName: $('#txtLastName').val(),
                City: (city != WM_CITY ? city : ''),
                State: $('#ddlState option:selected').attr('value'),
                EmailAddress: $('#txtEmailAddress').val(),
                IsAssociate: $('#cbWalmartAssociate').is(':checked'),
                YouTubeUrl: (youTube != WM_YOUTUBE ? youTube : '')
            }

            addIdeation(summary, function(addResult) {
                if (addResult.AddSuccess) {
                    // show complete
                    showSuccessDisplay();
                }
            },
            pageError);
        }

        return false;
    });

    $('#hlErrorClose, #ibErrorClose, #hlVotedClose, #ibVotedClose, #hlPageErrorClose, #ibPageErrorClose, ' +
      '#hlIdeaInfoClose, #ibIdeaInfoClose').click(function() {
          $.unblockUI();
          return false;
      });

    $('#hlSuccessClose, #ibSuccessClose').click(function() {
        window.close();
    });

    showWatermarks();
    loadIdeations();
});