Skip to content

Instantly share code, notes, and snippets.

@say2joe
Last active October 11, 2015 18:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save say2joe/3903256 to your computer and use it in GitHub Desktop.
Save say2joe/3903256 to your computer and use it in GitHub Desktop.
R4A: Utilizes messaging, modals, native error object, cookies, etc.
/**
* T*****: Racing For Awareness Contest and Sweepstakes.
* @author Joe Johnson (joe.johnson@icrossing.com)
* @requires jQuery
* @namespace
*/
var R4A = {
hasContestEnded: true,
Shirts: {}, places: [],
sweepstakes: "forms.html",
isOneColumn: ($(window).width() < 640),
Paths: {
preview: "img/shirts/preview/"
},
Services: {
Voting: {url:"/<masked>Site/racing/submit####.do"},
Sweeps: {url:"/<masked>Site/racing/submit####.do"}
},
Messages: {
SweepsLimit: "You have already registered for a chance to win! Be sure to come back tomorrow or in the near future to increase your chances of winning.",
VoteLimit: "<h4>You have already voted today!</h4><p>Be sure to come back tomorrow or in the near future for an opportunity to vote again.<br><br></p>",
Error: "There has been a problem. If you see this message repeatedly, please try again at a later time.",
Incomplete: '<div class="clearfix">Please complete all fields in the form to enter the sweepstakes.</div>'
},
User: {
setCookie: function(vos,days,value){
var d = new Date(new Date().setHours(0,0,0,0));
document.cookie = vos +"="+ (value||"entered") +"; expires="+
new Date(d.setDate(d.getDate()+days)).toUTCString() +';';
},
hasEnteredToday: function(){
if (this.hasSweepsCookie()) {
var ts = (/R4ASweeps=(\d+)/).exec(document.cookie)[1];
return ($.now() < ts);
} return false;
},
hasJustVoted: function(){
if ((/R4AJustVoted/).test(document.cookie)) {
this.setCookie("R4AJustVoted",0);
return true;
} return false;
},
hasVotedCookie: function(){
return (/R4AVoted=(TS\d)/).exec(document.cookie);
},
hasSweepsCookie: function(){
return (/R4ASweeps/).test(document.cookie);
}
},
setPlacements: function(n){
for (var places = new Array(n); n--;)
places[n] = 1+n+(n>2?"th":n>1?"rd":n>0?"nd":"st")+" Place";
return (this.places = places);
},
vote: function(event){
var shirt = R4A.DOM.$shirts.has(this)[0] || {id: this.id};
if (R4A.User.hasVotedCookie()) R4A.loadSweepstakes();
R4A.getVoteData(shirt.id).done(
function(d){ R4A.processVoteData(d,shirt.id); }
);
event.stopPropagation();
},
renderShirts: function(size,path){
var places = this.setPlacements(this.Shirts.length);
if (!path) path = this.Paths.preview;
if (!size) size = "320/";
$.each( this.Shirts, function(i){
var $coll = $('#'+ (this.id||i)).find("img,h4,h5");
$coll.filter("img")[0].src = path+size+this.image;
$coll.filter("h4").html(this.designer);
/* if (i < 3) { // 1st, 2nd, and 3rd place.
$coll.filter("h5").html(places[i]);
} else { // Remove all other placements. */
$coll.filter("h5").prevAll().remove();
//}
});
Retina.render();
},
renderDetails: function(){
var IDs = "#designer,#tagline,#large-shirt,#small-shirt,#place,#quote,#authored-by,#locale,#track,#memory,#hobbies,#info,.vote",
path = "img/type/" + ((this.isOneColumn)? "320/" : "960/"),
places = this.setPlacements(this.Shirts.length),
shirtID = (/TS(\d)/).exec(location.search)[0],
$thumbnails = this.DOM.$carousel.find("li"),
$coll = this.DOM.$details.find(IDs),
sObj = this.ShirtData[shirtID],
l = this.Shirts.length, $p;
$thumbnails.each(function(){ var $t=$(this); if ($("img",$t).data("sid")==shirtID) return $t.remove(); });
$(".jCarouselLite").jCarouselLite({ btnNext: ".next", btnPrev: ".prev" });
while (l--) if (this.Shirts[l].id === shirtID) break;
$.each( $coll, function(){
if (this.className == "vote") { this.id = shirtID; return; }
switch (this.id) {
case "place": this.innerHTML = places[l]; break;
case "authored-by": this.innerHTML += sObj.designer; break;
case "small-shirt": case "large-shirt":
this.src = path.replace("type","shirts/details") + sObj.image; break;
case "info": var $t=$(this); $.each(sObj.headshots,function(){
$t.append( $('<img align="right"/>').data("scale","retina")
.attr({ src: "img/headshots/320/"+this }) );
}); break;
case "locale": var locale = (/\[(Hometown|Residence)\](.+)/).exec(sObj[this.id]);
if (locale) { $(this).prev().html(locale[1]); sObj[this.id] = locale[2]; }
default:
if (sObj[this.id]!=="") this.innerHTML = sObj[this.id];
else if (($p = $(this).prev()).is("span")) $p.remove();
}
});
if (!this.isOneColumn) $(".shirt").first().load(function(){
var $d = $("#details-column"); $d.height(Math.max($("#shirt-holder").height()-175,$d.height()));
});
Retina.render();
},
renderVotingResult: function(){
var shirts = R4A.Shirts, l = shirts.length,
shirtID = R4A.User.hasVotedCookie()[1]||0;
while (l) if (shirts[--l].id == shirtID) break;
$("form").find(".result-name").html(R4A.Shirts[l].designer);
//.find(".result-place").html(R4A.places[l]).end()
},
processVoteData: function(d,id){
if (!d.shirts) {
R4A.Shirts = R4A.ShirtData;
} else {
var s = d.shirts, l = s.length;
while (l--) $.extend(s[l],R4A.ShirtData[s[l].id]);
R4A.Shirts = s.sort(function(o1,o2){ return o2.votes - o1.votes; });
}
if (!(/shirts/).test(location.href) && !$(".SubmitForm").length) R4A.renderShirts();
if (d.status === "success") {
if (!R4A.User.hasVotedCookie()) {
R4A.User.setCookie("R4AVoted",1,id);
R4A.User.setCookie("R4AJustVoted",1);
}
R4A.loadSweepstakes();
}
},
getVoteData: function(shirtID){
return $.post(
R4A.Services.Voting.url,
{ pollResponseCode: (shirtID||'') }
);
},
validateSweeps: function(event){
var valid = true, $f = $(this), $terms = $f.find("[name=termsFlag]"), setMessage = function(){
$f.find("header p").first().addClass("pink").html(R4A.Messages.Incomplete);
return false;
};
if ($terms.length && !$terms[0].checked) return setMessage();
$f.find("input[type=text]").each(function(){
switch (this.name) {
case "emailAddress":
valid = (/^[0-9a-zA-Z]+@[0-9a-zA-Z]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$/).test(this.value); break;
case "zipCode":
valid = (/^\d{5}$/).test(this.value); break;
default:
valid = (this.name)? (/\w+/).test(this.value) : true;
}
if (!valid) return false;
});
return (valid ? R4A.enterSweeps.call(this,event) : setMessage());
},
enterSweeps: function(event){
var $f = $(this), $resp = $.post(
R4A.Services.Sweeps.url, $f.serializeArray()
)
.error(function(d){
$f.load(R4A.sweepstakes+" #ErrorForm",function(){
$("header p").html(R4A.Messages.Error);
$("form").show();
});
})
.done(function(dataResponse){
var section, message;
switch (dataResponse.status) {
case "success": // Set the value of the Sweeps cookie to one day in the future.
R4A.User.setCookie("R4ASweeps",90,new Date().setTime(3600000*24+$.now()));
section = "#ThankYouSweeps"; break;
case "incomplete":
$.extend(dataResponse,{form:"Enter",msg:R4A.Messages.Incomplete}); break;
case "invalid":
message = R4A.Messages.SweepsLimit; break;
case "error":
message = R4A.Messages.Error; break;
}
if (dataResponse.form) return R4A.loadSweepstakes(dataResponse);
$f.load(R4A.sweepstakes+' '+(section||"#ErrorForm"),function(){
if (message) $("header p").html(message);
$("form").show().find("section").show();
});
});
return false;
},
loadSweepstakes: function(data){
var idPrefix = (data)? data.form : (R4A.User.hasSweepsCookie()? "Reenter" : "Enter"),
isSameLocation = (location.href.indexOf("forms.html")>0),
formSection = '#'+ idPrefix +"Sweeps",
parseData = function parseData(){
if (data.msg) $("header p").first().addClass("pink").html(data.msg);
if (data.email) $("input").filter("[name^='email']").val(data.email);
};
if (R4A.isOneColumn && !isSameLocation) {
location.href = this.sweepstakes + formSection;
} else {
var $container = $(R4A.isOneColumn ? "form" : "#modal");
$container.load(this.sweepstakes+" #Sweepstakes",function(){
R4A.showSweepsForm(formSection);
if (data) parseData();
});
if (!R4A.isOneColumn) $container.modal("show");
}
},
showSweepsForm: function(sid){
var $forms = $("form").on("submit",R4A.validateSweeps).find("section"),
$sid = $((sid) ? sid : location.hash), $f = $sid.parent();
if (R4A.User.hasVotedCookie() && !R4A.User.hasJustVoted()) {
$f.find("header h3").replaceWith(R4A.Messages.VoteLimit);
}
if (R4A.isOneColumn) $(".returnButton").hide();
$forms.not($sid.show()).remove();
R4A.renderVotingResult();
},
goToShirt: function(event){
var $t = $(this), sid = $t.data("sid"), $shirtLink = $t.siblings("a");
location.href = (sid)? "shirts.html?"+sid : $shirtLink[0].href;
},
bindEvents: function(){
if (!this.hasContestEnded) {
$(".SubmitForm").on("click",".close",function(){ location.href="./"; });
this.DOM.$carousel.on("click","img",this.goToShirt);
this.DOM.$shirts.on("click","img",this.goToShirt);
this.DOM.$vote.on("click",this.vote);
} else {
$("#ContestEndedMessage").show();
}
return this;
},
error: function(err){
var $m = $("#modal").load(R4A.sweepstakes+" #ErrorForm",function(){
$m.find("#ErrorForm").show().find("p").html(err.replace(/.+: /,''));
}).modal("show");
return false;
},
init: function(){
this.DOM = {
$shirts: $(".shirt-tout"),
$carousel: $("#carousel"),
$details: $("#details"),
$vote: $(".vote")
};
$(".shirt-thumb").after('<img src="img/vertical-line.png" class="vertical-line"/>');
if (this.DOM.$details.length) this.renderDetails();
if ($("form").length) this.showSweepsForm();
return this.bindEvents();
}
};
$.ajaxSetup({
type: "post", dataType: "json", data: { pollCode: "TRTS", survey_id: 20100 }
});
$.getJSON("js/shirts.json")
.pipe(function(d){ return R4A.ShirtData = d; })
.pipe(function(d){ return R4A.getVoteData(); })
.always(function(d){ return R4A.processVoteData(d); })
.always(function(){ $(function(){ R4A.init(); }); });
window.onerror = R4A.error;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment