/* TOC
 *   1.0 Service Proxy
 *   2.0 Ideation Wrappers
 *   3.0 UI Drawing
 *   4.0 Voting
 *   5.0 Properties
 *   6.0 Date Formatting
 *************************************/

/* 1.0 Service Proxy */
function serviceProxy(serviceUrl) {
    var me = this;
    this.serviceUrl = serviceUrl;

    this.invoke = function(method, data, callback, error, bare) {
        // convert object to JSON
        var json = JSON2.stringify(data);
        // build method URL based on base service path
        var url = me.serviceUrl + method;

        $.ajax({
            url: url,
            data: json,
            type: 'POST',
            processData: false,
            contentType: 'application/json',
            timeout: 1000,
            dataType: 'json',
            success: function(result) {
                // if no callback defined, do nothing
                if (!callback) return;
                // if object returned is the result, use it
                if (bare) {
                    callback(result);
                    return;
                }
                // wrapped message contains top object node - strip it off
                for (var property in result) {
                    callback(result[property]);
                    break;
                }
            },
            error: function(xhr) {
                // if no error callback defined, do nothing
                if (!error) return;
                // if error message set
                if (xhr.responseText) {
                    // parse message
                    var err = JSON2.parse(xhr.responseText);
                    // send error message on
                    if (err) {
                        error(err);
                    } else {
                        error({ Message: 'Unknown server error' });
                    }
                }
            }
        });
    }
}

/* 2.0 Ideation Wrappers */
function getPagedIdeations(pageIndex, pageSize, callback, state) {
    var url = DOMAIN + '/services/ideations.svc/ideations/paged/?p=' + pageIndex + '&s=' + pageSize;
    if (state && state != '') {
        url = DOMAIN + '/services/ideations.svc/ideations/state/?p=' + pageIndex + '&s=' + pageSize + '&state=' + state;
    }
    $.getJSON(url, callback);
}

function addIdeation(summary, callback, error) {
    var proxy = new serviceProxy(DOMAIN + '/services/ideations.svc/');
    proxy.invoke('ideations/add', summary, callback, error, true);
}

function getIdeation(id, callback) {
    var url = DOMAIN + '/services/ideations.svc/ideations/?id=' + id;
    $.getJSON(url, callback);
}

/* 3.0 UI Drawing */
function writeNumber(num, size) {
    var result = '';

    var value = String(num);
    for (var i = 0; i < value.length; i++) {
        result += getNumber(value.charAt(i), size);
    }

    return result;
}

function getNumber(num, size) {
    var imgName = '';

    switch (num) {
        case '1': imgName = (size == SIZE_SMALL ? 's1' : 'l1'); break;
        case '2': imgName = (size == SIZE_SMALL ? 's2' : 'l2'); break;
        case '3': imgName = (size == SIZE_SMALL ? 's3' : 'l3'); break;
        case '4': imgName = (size == SIZE_SMALL ? 's4' : 'l4'); break;
        case '5': imgName = (size == SIZE_SMALL ? 's5' : 'l5'); break;
        case '6': imgName = (size == SIZE_SMALL ? 's6' : 'l6'); break;
        case '7': imgName = (size == SIZE_SMALL ? 's7' : 'l8'); break;
        case '8': imgName = (size == SIZE_SMALL ? 's8' : 'l8'); break;
        case '9': imgName = (size == SIZE_SMALL ? 's9' : 'l9'); break;
        case '0': imgName = (size == SIZE_SMALL ? 's0' : 'l0'); break;
    }

    var imgPath = '';
    var isIe6 = /msie|MSIE 6/.test(navigator.userAgent);
    if (!isIe6) {
        imgPath = '<img src="/Images/Ideation/' + imgName + '.png" alt="" />';
    } else {
        imgPath = '<img src="/Images/Ideation/blank.gif" alt="" style="filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'/Images/Ideation/' + imgName + '.png\', sizingMethod=\'image\');" />';
    }
    return imgPath;
}

function showCategoryAccessories(category, voteStatus, voteTotal) {
    var content = '';
    
    content += '<a class="hlFindMore" href="#" onclick="showIdeas(); return false;" title="Find More Great Ideas">Find More Great Ideas</a>';
    // add common
    if (voteStatus == PRE_VOTE) {
        content += '<a class="likeIt" title="Like it!" href="javascript:categoryVote(' + category.IdeationId + ');">Like it!</a>';
        content += '<div class="saidYes">' + writeNumber(voteTotal, SIZE_SMALL) + '</div>';
        
    } else if (voteStatus == POST_VOTE) {
        content += '<div class="saidYes">' + writeNumber(voteTotal, SIZE_LARGE) + '</div>';
    }

    // add category specific
    switch (category.Id) {
        case CATEGORY_REDUCE:
            content += '<a id="hlStartSpendingLess" href="http://instoresnow.walmart.com/sustainability-article_ektid68682.aspx" title="Start Spending Less" target="_top">Start Spending Less</a>';
            if (voteStatus == POST_VOTE) {
                content += '<a id="hlWaterFilters" href="http://www.walmart.com/reflect.gsp?adid=1500000000000007128660&dest=140900" title="Water Filters" target="_top">Water Filters</a>';
                content += '<a id="hlWaterBottles" href="http://www.walmart.com/reflect.gsp?adid=1500000000000007128630&dest=140897" title="Water Bottles &amp; Pitchers" target="_top">Water Bottles &amp; Pitchers</a>';
            }
            break;
        case CATEGORY_SAVE_MONEY:
            content += '<a id="hlCutEnergyExpenses" href="http://instoresnow.walmart.com/sustainability2-article_ektid47000.aspx" title="Cut Energy Expenses" target="_top">Cut Energy Expenses</a>';
            if (voteStatus == POST_VOTE) {
                content += '<a id="hlLightBulbs" href="http://www.walmart.com/reflect.gsp?adid=1500000000000007128590&dest=140893" title="Light Bulbs" target="_top">Light Bulbs</a>';
                content += '<a id="hlEnergyEfficientAppliances" href="http://www.walmart.com/reflect.gsp?adid=1500000000000007128540&dest=140888" title="Energy-Efficient Appliances" target="_top">Energy-Efficient Appliances</a>';
            }
            break;
        case CATEGORY_START_AT_HOME:
            content += '<a id="hlGet10SimpleSteps" href="http://instoresnow.walmart.com/sustainability2-article_ektid47000.aspx" title="Get 10 Simple Steps" target="_top">Get 10 Simple Steps</a>';
            if (voteStatus == POST_VOTE) {
                content += '<a id="hlEarthFriendlyLaundry" href="http://www.walmart.com/reflect.gsp?adid=1500000000000007128640&dest=140898" title="Earth-Friendly Laundry" target="_top">Earth-Friendly Laundry</a>';
                content += '<a id="hlEarthFriendlyApparel" href="http://www.walmart.com/reflect.gsp?adid=1500000000000007128530&dest=140887" title="Earth-Friendly Apparel" target="_top">Earth-Friendly Apparel</a>';
            }
            break;
    }

    return content;
}

function showCategoryPane(category, voteTotal) {
    // check to see if splash already shown
    if (!getSplashShown()) {
        // show splash screen
        $('#impactSplash').attr({
            src: category.SplashImage,
            title: category.Name,
            alt: category.Name
        }).show();
        $('#impactSplash').pause(500).fadeOut(500);
        setSplashShown();
    } else {
        $('#impactSplash').hide();
    }

    var voteStatus = PRE_VOTE;
    if (category.Voted) {
        voteStatus = POST_VOTE;
    }

    if (!category.Voted) {
        // show pre-vote view
        $('#impactPost').hide();
        $('#impactPre').css({ background: 'url(' + category.PreImage + ') no-repeat' });
        $('#impactPre').html(showCategoryAccessories(category, voteStatus, voteTotal)).hide().fadeIn();
    } else {
        // show voted view
        $('#impactPre').hide();
        $('#impactPost').css({ background: 'url(' + category.PostImage + ') no-repeat' });
        $('#impactPost').html(showCategoryAccessories(category, voteStatus, voteTotal)).hide().fadeIn();
    }
}

function showTopRated(result) {
    $('#ideaList').setTemplateURL('/Templates/TopRated.htm');
    $('#ideaList').processTemplate(result.Ideations);
}

function loadCategoryPane(id, loadStatus) {
    var category = { categoryId: id };

    var proxy = new serviceProxy(DOMAIN + '/IdeationServices/Category.asmx/');
    proxy.invoke('GetCategory', category, function(result) {
        // default to number of votes for ideation
        var voteCount = result.VoteCount;
        // override if set from vote function
        if (loadStatus != REGULAR_LOAD) {
            voteCount = result.VoteCount + 1;
        }
        // show panel
        showCategoryPane(result, voteCount);
    }, pageError);
}

function clearTabs() {
    $('#tabReduce').removeClass('active');
    $('#tabStartAtHome').removeClass('active');
    $('#tabSaveMoney').removeClass('active');
}

/* 4.0 Voting */
function voteForIdeation(detail, callback, error) {
    var proxy = new serviceProxy(DOMAIN + '/services/ideations.svc/');
    proxy.invoke('ideations/vote', detail, callback, error, true);
}

function getVoterId(callback) {
    var voter = {}
    var proxy = new serviceProxy(DOMAIN + '/IdeationServices/Voter.asmx/');
    proxy.invoke('GetVoter', voter, callback, pageError);
}

function saveVoterId(voterId, callback) {
    var voter = { voterId: voterId }
    var proxy = new serviceProxy(DOMAIN + '/IdeationServices/Voter.asmx/');
    proxy.invoke('SaveVoter', voter, callback, pageError);
}

function allVote(ideationId, callback) {
    var voterId = 0;
    // get voter id
    getVoterId(function(result) {
        voterId = result;
        var detail = {
            VoterId: voterId,
            SummaryId: ideationId
        }
        // vote and return to calling function
        voteForIdeation(detail, callback, pageError);
    });
}

function categoryVote(ideationId) {
    allVote(ideationId, function(result) {
        // save voter's id for future votes
        saveVoterId(result.VoterId, function(voteResult) {
            // load panel for category
            loadCategoryPane(getCategoryId(), VOTE_LOAD);
        });
    });
}

function ideaVote(ideationId) {
    allVote(ideationId, function(result) {
        if (result.VoteSuccess) {
            // save voter's id for future votes
            saveVoterId(result.VoterId);

            // update display total
            var tdVoteCount = $('#tr' + ideationId + ' .voteCount');
            var voteText = tdVoteCount.text();

            var index = voteText.indexOf('vote') - 1;
            var voteCount = parseInt(voteText.substring(0, index));
            voteCount += 1;
            voteText = voteCount + ' vote' + (voteCount != 1 ? 's' : '');
            tdVoteCount.text(voteText);
        } else {
            showAlreadyVotedDisplay();
        }
    });
}

/* 5.0 Properties */
function setCategoryId(id) {
    $('#hCategoryId').val(id);
}

function getCategoryId() {
    var val = $('#hCategoryId').val();
    if (val == '') {
        return CATEGORY_REDUCE;
    }
    return parseInt(val);
}

function getSplashShown() {
    return ($('#hSplash').val() != '');
}
function setSplashShown() {
    $('#hSplash').val('true');
}

/* 6.0 Date Formatting */
function getFormattedDate(dateStr) {
    var dt = getIdeationDate(dateStr);
    var formatted = '';
    if (dt != null) {
        var mo = dt.getMonth() + 1;
        var day = dt.getDate();
        var yr =  dt.getFullYear()
        var hr = (dt.getHours() + 1 > 12 ? (dt.getHours() + 1) - 12 : (dt.getHours() + 1));
        var min = dt.getMinutes();
        var dayPart = (dt.getHours() + 1 <= 12 ? 'a.m.' : 'p.m');

        formatted = mo + '/' + day + '/' + yr + ' ' + hr + ':' + min + ' ' + dayPart;
    }
    return formatted;
}

function getIdeationDate(dateStr) {
    var validDate = /Date\(([-+]?\d+[-+]?\d+)\)/.exec(dateStr);
    if (validDate) {
        dt = new Date(eval(validDate[1]));
        return dt;
    }
    return null;
}