/*	race.js
 *  requires: joose, jquery
 *	by kenny shen, www.northpole.sg
 */
 
// Setup RaceMgr, and other stuff.

Class("SignPost", {
    has: {
        id: {
          is: "rw",
          init: ""  
        },
        title: {
          is: "rw",
          init: ""  
        },
        description: {
            is: "rw",
            init: ""
        },
        selected: {
            is: "rw",
            init: false
        },
        active_image: {
            is: "rw",
            init: ""
        },
        nonactive_image: {
            is: "rw",
            init: ""
        },
        detail_class: {
            is: "rw",
            init: []
        },
        map_id: {
            is: "rw",
            init: []
        },
        ridertypes: {
            is:"rw",
            init: []
        }
    } 
});

Class("RiderType", {
    has: {
        headline: {
          is: "rw",
          init: ""  
        },
        description: {
            is: "rw",
            init: ""
        },
        selected: {
            is: "rw",
            init: ""
        },
        active_image: {
            is: "rw",
            init: ""
        },
        nonactive_image: {
            is: "rw",
            init: ""
        },
        detail_class: {
            is: "rw",
            init: ""
        }
    } 
});

Class("RaceMgr", {
    has: {
        signposts: {
            is: "rw",
            init: []
        },
        ridertypes: {
            is: "rw",
            init: []
        },
        active_sign: {
            is: "rw",
            init: ""
        }
    },
    methods: {
        init: function(signposts, ridertypes) {
            var that = this;
            that.setSignposts(signposts);
            that.setRidertypes(ridertypes);
        },
        makeactive: function(object_id, type) {
            var that = this;
            // show reset button
            $('div.show_all_categories').fadeIn();
            $('p#all-categories-description').fadeOut();
            if(type == "signposts") {
                var signposts = that.getSignposts();
                $.each(signposts, function(i, val) {
                   (function() {
                       var sign = signposts[i];
                       var sub_title = "div." + sign.detail_class + ' h3';
                       var detail_class = 'div.' + sign.detail_class;
                       var map_id = 'div#' + sign.map_id;
                       if(sign.id == object_id) {
                           sign.setSelected(true);
                           that.setActive_sign(sign.id);
                           $(detail_class).fadeIn();
                           $(map_id).fadeIn();
                           $('div#all-categories h2').text(sign.getTitle());
                           $(sub_title).hide();
                           var ridertypes = sign.getRidertypes();
                           $('div#rider-types-information').empty().append('<h4 style="font-weight:bold;">Rider Type</h4><div id="ridertype-select"></div><div id="ridertype-infobox"></div>'); // clear out any previous iteration
                           $.each(ridertypes, function(i, val) {
                               (function() {
                                   try {
                                       $('div#ridertype-select').append("<div id='rider" + i  + "' class='left1'>" + ridertypes[i].getHeadline() + "</div>");
                                        $('div#rider'+i).click(function() {
                                            var that = this;
                                            // remove selected class
                                            $('.rider_selected').removeClass('rider_selected');
                                            // append selected class
                                            $(this).addClass('rider_selected');
                                            $('div#ridertype-infobox').empty();
                                            $('div#ridertype-infobox').append("<div>" + ridertypes[i].getDescription() + "</div>");
                                        });
                                        $('div#rider'+i).hover(function() {
                                            var that = this;
                                            $('.rider_selected').removeClass('rider_selected');
                                            $(this).addClass('rider_selected');
                                            $('div#ridertype-infobox').empty();
                                            $('div#ridertype-infobox').append("<div>" + ridertypes[i].getDescription() + "</div>");
                                        }, function() {

                                        });
                                   } catch(e) {}  
                               })(ridertypes[i]);
                           });
                           // set default info
                           $('div#rider0').addClass('rider_selected');
                           $('div#ridertype-infobox').append("<div>" + ridertypes[0].getDescription() + "</div>");
                           
                           $('<div class="clear"></div>').insertAfter("div#ridertype-select");
                       }
                       else {
                           sign.setSelected(false);
                           $(detail_class).fadeOut();
                           $(map_id).fadeOut();
                       }
                   })(signposts[i]);
                });
                // uncomment when entourage is ready.
                $('div#express-interest').show();
                that.register_race();
            }
        },
        makeallhover: function() {
            var that = this;
            var signposts = that.getSignposts();
            $.each(signposts, function(i, val) {
               (function() {
                   var sign = signposts[i];
                   var div_id = 'div#' + sign.id;
                   $(div_id).hover(function() {
                       
               	}, function() {
               	    
               	});
               })(signposts[i]);
            });
        },
        makehover: function(object_id) {
            
        },
        removehover: function(object_id) {
            
        },
        reset: function() {
            var that = this;
            // hide reset button
            $('div.show_all_categories').hide();
            $('p#all-categories-description').fadeIn();
            var signposts = that.getSignposts();
            var ridertypes = that.getRidertypes();
            $('div#all-categories h2').text('All Categories');
            $.each(signposts, function(i, val) {
               (function() {
                   var sign = signposts[i];
                   var sub_title = "div." + sign.detail_class + ' h3';
                   var detail_class = 'div.' + sign.detail_class;
                   var map_id = 'div#' + sign.map_id;
                   sign.setSelected(false);
                   $(detail_class).fadeIn();
                   $(map_id).hide();
                   $(sub_title).show();
               })(signposts[i]);
            });
            $('div#express-interest').hide();
        },
        show_info: function(object_id) {
            
        },
        submit_interest: function() {
            var that = this;
            var current_sign = that.getActive_sign();
            if(current_sign !== "") {
                $('div#express-msg').append('<img src="/site_media/images/common/loading.gif">');
                var url = "/entourage/send_interest/?interest=" + current_sign;
                $.ajax({
                   url: url,
                   dataType: 'json',
                   success: function(data) {
                       $('div#express-msg').hide().empty();
                       if(data.status == true) {
                           $('div#express-msg').text("Your interest has been registered!").fadeIn().delay(4000).fadeOut()
                       }else if (data.status == 'Fail') {
                           $('div#express-msg').text("You need to log in to your Entourage first!").fadeIn().delay(4000).fadeOut()
                       } else {
                           $('div#express-msg').text("Submission has failed, please try again later.").fadeIn().delay(4000).fadeOut()
                       }
                   },
                   error: function() {
                       $('div#express-msg').text("Submission has failed, please try again later.").fadeIn().delay(4000).fadeOut()
                   }
                });
            }
        },
        register_race: function() {
            var that = this;
            var current_sign = that.getActive_sign();
            if(current_sign !== "") {
                var url = "/entourage/send_registration/?race=" + current_sign;
                $('.register').attr('href',url)
            } 
        }
    }
});

// Bootup RaceMgr
$(document).ready(function() {
    // initialize RiderTypes
    var tri_rider1 = new RiderType({
        headline: "Individual",
        description:"Let your child try this ride on his or her own – with your encouragement along the way!"
    });
    var mighty_rider1 = new RiderType({
        headline: "Individual (ages 6 to 12)",
        description:"Let your children enjoy this ride all by themselves!"
    });
    var mighty_rider2 = new RiderType({
        headline: "Accompanying Adult Cycling With Child",
        description:"You can also choose to ride with your child and find time to bond while racing."
    });
    var mighty_rider3 = new RiderType({
        headline: "Family Package",
        description:"The whole family can cycle and save with the Family Package. The Family Package price includes 2 adults and up to 2 children (between the ages of 6 and 12)."
    });
    var community_rider1 = new RiderType({
        headline: "Individual",
        description:"Ride along with everyone in this event designed for anyone aged 10 and above."
    });
    var community_rider2 = new RiderType({
        headline: "Student",
        description:"Register as a student and enjoy an exclusive registration rate!"
    });
    var community_rider3 = new RiderType({
        headline: "4-Cyclist Promo Package",
        description:"Simply form a team with your friends and family and all of you enjoy a discount on registration fees!"
    });
    var challenge_rider1 = new RiderType({
        headline: "Individual",
        description:"Ready for more than a community ride? Take up this challenge, which is open to anyone aged 16 and above."
    });
    var challenge_rider2 = new RiderType({
        headline: "Student",
        description:"Register as a student and enjoy an exclusive registration rate!"
    });
    var challenge_rider3 = new RiderType({
        headline: "Corporate Team",
        description:"Bond with your colleagues by forming a team of 4 to represent your company/ organisation. The team with the fastest combined times win. Each member is required to complete 40km and the team with the fastest combined times wins. Team members are eligible for both team prizes and individual prizes."
    });
    var challenge_rider4 = new RiderType({
        headline: "School Team",
        description:"Get your buddies to form a team of 4 to represent your school/ organisation. Be the fastest school team to win. Each member is required to complete 40km and the team with the fastest combined times wins. Team members are eligible for both team prizes and individual prizes."
    });
    var challenge_rider5 = new RiderType({
        headline: "Club & Interest Group Team",
        description:"Build a team of 4 with your best pals in your club or organisation. The team with the fastest combined times win. Each member is required to complete 40km and the team with the fastest combined times wins. Team members are eligible for both team prizes and individual prizes."
    });
    var superchallenge_rider1 = new RiderType({
        headline: "Individual",
        description:"Push your limits by joining this ride, which is open to anyone aged 16 and above. Entry to this challenge is subject to qualification."
    });
    var crit_rider1 = new RiderType({
        headline: "Men’s Open",
        description:"With 80 slots available and open to males of ages 18 and above only, qualification for this challenge will be based on entrants’ results from past cycling events. You can still enter The Nissan Challenge – 40km or The Community Ride – 20km if you are not selected, and the difference in entry fees will be refunded to you. Should you choose not to join another event, you will receive a full refund, minus a $10 administration fee."
    });
    var crit_rider2 = new RiderType({
        headline: "Ladies' Open",
        description:"Open to females of ages 18 and above, qualification for this challenge will be based on entrants' results from past cycling events. You can opt to enter The Nissan Challenge – 40km or The Community Ride – 20km if you are not selected, and the difference in entry fees will be refunded to you. Should you choose not to join another event, you will receive a full refund, minus a $10 administration fee. <br />Please note that this event will be combined with the Masters' Criterium."
    });
    var crit_rider3 = new RiderType({
        headline: "Masters'",
        description:"With 80 slots available and open to riders of ages 40 and above, qualification for this challenge will be based on entrants’ results from past cycling events. You can still enter The Nissan Challenge – 40km or The Community Ride – 20km if you are not selected, and the difference in entry fees will be refunded to you. Should you choose not to join another event, you will receive a full refund, minus a $10 administration fee.<br />Please note that this event will be combined with the Ladies' Open Criterium."
    });
    var crit_rider4 = new RiderType({
        headline: "Professional",
        description:"Reserved for the cycling professional, this challenge is by invitation only. If you are interested and would like to be considered for participation, please email your previous race and cycling experience to info@cyclesingapore.com.sg and we will notify you of your eligibility."
    });
    
    var twitter_share_url = "http://twitter.com/home?status=";
    
 
    // initialize SignPosts
    var tricycle_signpost = new SignPost({
        id:"cat_tricycle",
        title: "Tricycle Ride (100m)",
        description: "Tricyclists are you ready? Get set, Go! The 100m Tricycle Ride at the F1 Pit Building is specially designed for children between the ages two(2) and five(5), so the whole family can ride together. Each child can be accompanied and guided on the track by an adult.",
        active_image: "/media/uploads/categories/signs_roll_01.jpg",
        nonactive_image: "/media/uploads/categories/signs_01.jpg",
        detail_class: "tricycle-ride",
        map_id: "map_tricycle",
        ridertypes: [tri_rider1,],
    }); 
    var kidsride_signpost = new SignPost({
           id:"cat_kids_ride",
           title: "Mighty Savers™ Kids Ride (5km)",
           description: "Designed to ensure a safe and fun experience, this special ride is open to all children between the ages of six(6) and twelve(12).  You can let your children enjoy this safe and fun ride on their own, join as a parent-child duo or cycle as a family by taking up the Family Package!",
           active_image: "/media/uploads/categories/signs_roll_02.jpg",
           nonactive_image: "/media/uploads/categories/signs_02.jpg",
           detail_class: "mighty-savers-kids-ride",
           map_id: "map_mightysavers",
           ridertypes: [mighty_rider1, mighty_rider2, mighty_rider3],
    });
    var juniorchallenge_signpost = new SignPost({
           id:"cat_junior_challenge",
           title: "The Junior Challenge (30 min)",
           description: "A more challenging category designed for older children, this ride is open to anyone between the ages of ten and twelve. The objective is to ride as fast as possible for 30 minutes.",
           active_image: "/media/uploads/categories/signs_roll_03.jpg",
           nonactive_image: "/media/uploads/categories/signs_03.jpg",
           detail_class: "the-junior-challenge",
           map_id: "map_junior",
           ridertypes: [mighty_rider1, mighty_rider2, mighty_rider3],
    });
    var communityride_signpost = new SignPost({
           id:"cat_community_ride",
           title: "The Community Ride (24km)",
           description: "Whether you are an amateur cyclist or just looking for a fun day out, join this non-competitive ride as an individual, as a student, or form your team of four(4) to enjoy the 4-Cyclist Promo Package. This ride is for everyone of ages ten(10) and above on event day.",
           active_image: "/media/uploads/categories/signs_roll_04.jpg",
           nonactive_image: "/media/uploads/categories/signs_04.jpg",
           detail_class: "community-ride",
           map_id: "map_community",
           ridertypes: [community_rider1, community_rider2, community_rider3],
    });
    var challenge_signpost = new SignPost({
           id:"cat_challenge",
           title: "The Challenge (39km)",
           description: "Ready for more than a community ride? Take up this challenge, which is open to anyone aged 14 and above.",
           active_image: "/media/uploads/categories/signs_roll_05.jpg",
           nonactive_image: "/media/uploads/categories/signs_05.jpg",
           detail_class: "challenge-ride",
           map_id: "map_challenge",
           ridertypes: [challenge_rider1, challenge_rider2, challenge_rider3, challenge_rider4, challenge_rider5],
    });
    var superchallenge_signpost = new SignPost({
           id:"cat_super_challenge",
           title: "The Super Challenge (59km)",
           description: "Designed for the true cycling enthusiast, this challenge is open to riders aged 16 and above, subject to qualification.",
           active_image: "/media/uploads/categories/signs_roll_06.jpg",
           nonactive_image: "/media/uploads/categories/signs_06.jpg",
           detail_class: "super-challenge-ride",
           map_id: "map_superchallenge",
           ridertypes: [superchallenge_rider1],
    });
    var criterium_signpost = new SignPost({
           id:"cat_criterium",
           title: "Criterium Events",
           description: "A criterium, or crit, is a bike race held on a short course. The event's duration is shorter than that of a traditional road race, with the average speed and intensity being appreciably higher. All entries to these events are subject to qualification.",
           active_image: "/media/uploads/categories/signs_roll_07.jpg",
           nonactive_image: "/media/uploads/categories/signs_07.jpg",
           detail_class: "criterium-events",
           map_id: "map_criterium",
           ridertypes: [crit_rider1,crit_rider2,crit_rider3,crit_rider4],
    });
    
    var signposts = [tricycle_signpost, kidsride_signpost, juniorchallenge_signpost, communityride_signpost, challenge_signpost, superchallenge_signpost, criterium_signpost];
    var ridertypes = [];
    
    var e_racemgr = new RaceMgr();
    // store instances
    e_racemgr.init(signposts, ridertypes);
    // bind mouseevents
    e_racemgr.makeallhover();
    
    // bind for signposts
    $('div#cat_tricycle').click(function() {
        e_racemgr.makeactive('cat_tricycle', 'signposts');
        var twitter_msg = twitter_share_url + escape('likes Tricycle Ride (100m) in OCBC Cycle Singapore 2012');
        $('#twitter_share_link a').attr('href', twitter_msg);
    });
    $('div#cat_kids_ride').click(function() {
        e_racemgr.makeactive('cat_kids_ride', 'signposts');
        var twitter_msg = twitter_share_url + escape('likes Mighty Savers Kids Ride (5km) in OCBC Cycle Singapore 2012');
        $('#twitter_share_link a').attr('href', twitter_msg);
    });
    $('div#cat_junior_challenge').click(function() {
        e_racemgr.makeactive('cat_junior_challenge', 'signposts');
        var twitter_msg = twitter_share_url + escape('likes The Junior Challenge (30mins) in OCBC Cycle Singapore 2012');
        $('#twitter_share_link a').attr('href', twitter_msg);
    });
    $('div#cat_community_ride').click(function() {
        e_racemgr.makeactive('cat_community_ride', 'signposts');
        var twitter_msg = twitter_share_url + escape('likes The Community Ride (19km) in OCBC Cycle Singapore 2012');
        $('#twitter_share_link a').attr('href', twitter_msg);
    });
    $('div#cat_challenge').click(function() {
        e_racemgr.makeactive('cat_challenge', 'signposts');
        var twitter_msg = twitter_share_url + escape('likes The Challenge (39km) in OCBC Cycle Singapore 2012');
        $('#twitter_share_link a').attr('href', twitter_msg);
    });
    $('div#cat_super_challenge').click(function() {
        e_racemgr.makeactive('cat_super_challenge', 'signposts');
        var twitter_msg = twitter_share_url + escape('likes The Super Challenge (61km) in OCBC Cycle Singapore 2012');
        $('#twitter_share_link a').attr('href', twitter_msg);
    });
    $('div#cat_criterium').click(function() {
        e_racemgr.makeactive('cat_criterium', 'signposts');
        var twitter_msg = twitter_share_url + escape('likes Criterium Events in OCBC Cycle Singapore 2012');
        $('#twitter_share_link a').attr('href', twitter_msg);
    });
    // reset
    $('div.show_all_categories').click(function() {
        var twitter_msg = twitter_share_url + escape('likes OCBC Cycle Singapore 2012');
        $('#twitter_share_link a').attr('href', twitter_msg);
        e_racemgr.reset(); 
    });
    $('div.show_all_categories').hide();
    $('div#express-interest').click(function() {
       e_racemgr.submit_interest(); 
    });

    // parse GET if any
    // code from http://stackoverflow.com/questions/439463/how-to-get-get-and-post-variables-with-jquery
    function getQueryParams(qs) {
        //qs = qs.split("+").join(" ");
        //var params = {};
        //var tokens;

        //while (tokens = /[?&]?([^=]+)=([^&]*)/g.exec(qs)) {
         //   params[decodeURIComponent(tokens[1])]
           //     = decodeURIComponent(tokens[2]);
        //}

        //return params;
        // -- freezes up in webkit
        qs = qs.split("=")[1];
        return qs;
    }

    //var $_GET = getQueryParams(document.location.search);
    var gets = getQueryParams(window.location.search);
    if(gets == 'tricycle') {
        e_racemgr.makeactive('cat_tricycle', 'signposts');
    } else if(gets == 'kids') {
        e_racemgr.makeactive('cat_kids_ride', 'signposts');
    } else if(gets == 'juniorchallenge') {
        e_racemgr.makeactive('cat_junior_challenge', 'signposts');
    }  else if(gets == 'community') {
        e_racemgr.makeactive('cat_community_ride', 'signposts');
    } else if(gets == 'challenge') {
        e_racemgr.makeactive('cat_challenge', 'signposts');
    } else if(gets == 'superchallenge') {
        e_racemgr.makeactive('cat_super_challenge', 'signposts');
    } else if(gets == 'criterium') {
        e_racemgr.makeactive('cat_criterium', 'signposts');
    }
});

