﻿/* 0.0 Constants */
var VOTE_ICE_COLD = 0, VOTE_CRAZY_HOT = 1;

/* 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 Errors */
function pageError(msg) {
    alert('Error! ' + JSON2.stringify(msg));
}

/* 3.0 Voting */
function getVoterId(callback) {
    var voter = {}
    var proxy = new serviceProxy('/Services/Voter.asmx/');
    proxy.invoke('GetVoterId', voter, callback, pageError);
}
function saveVoterId(voterId, callback) {
    var voter = { voterId: voterId }
    var proxy = new serviceProxy('/Services/Voter.asmx/');
    proxy.invoke('SaveVoter', voter, callback, pageError);
}
function vote(jobId, status) {
    // get method for voting
    var voteFunctionName = 'VoteCrazyHot';
    if (status == VOTE_ICE_COLD) {
        voteFunctionName = 'VoteIceCold';
    }
    // get voter id
    var voterId = 0;
    getVoterId(function(result) {
        var detail = {
            voterId: result,
            jobId: jobId
        }
        // vote for job (either status)
        var proxy = new serviceProxy('/Services/Voter.asmx/');
        proxy.invoke(voteFunctionName, detail, function(result) {
            // save voter's id for future votes
            saveVoterId(result.VoterId, function(msg) {
                // update voting display
                updateDisplay(jobId, status, result.VoteSuccess);
            });
        },
        pageError);
    });
}

function voteCrazyHot(jobId) {
    vote(jobId, VOTE_CRAZY_HOT);
}
function voteIceCold(jobId) {
    vote(jobId, VOTE_ICE_COLD);
}

/* 4.0 UI Changes */
function updateDisplay(jobId, status, success) {
    if (success) {
        var tempClass = 'coldVotes';
        if (status == VOTE_CRAZY_HOT) {
            tempClass = 'hotVotes';
        }
        var spanUpdate = $('.rate' + jobId + ' .' + tempClass + ' span').get(0);
        var count = parseInt(spanUpdate.innerHTML);
        spanUpdate.innerHTML = (count + 1);
    } else {
        $('#alreadyVoted').dialog('open');
    }
    showPromotion(jobId);
}

/* 5.0 Window */
function openWindow(url, width, height, showScroll, windowName) {
    var leftVal = (screen.width - width) / 2;
    var topVal = (screen.height - height) / 2;

    var args = 'height=' + height + ',width=' + width + ',left=' + leftVal + ',top=' + topVal
            + ',location=0,scrollbars=' + ((showScroll == true) ? '1' : '0')
            + ',toolbar=0,directories=0,status=0,menubar=0,resizable=1';

    var popWin = window.open(url, windowName, args);
    if (popWin != null) {
        popWin.focus();
    }
}

/* 6.0 Validation */
function validateEmail(emailAddress) {
    var reg1 = /(@.*@)|(\.\.)|(@\.)|(\.@)|(^\.)/; // not valid
    var reg2 = /^.+\@(\[?)[a-zA-Z0-9\-\.]+\.([a-zA-Z]{2,3}|[0-9]{1,3})(\]?)$/; // valid

    var validEmail = !reg1.test(emailAddress) && reg2.test(emailAddress);

    return (emailAddress.length != 0) && (emailAddress.length <= 200) && validEmail;
}