var Poly = function() {
    var ret = {
        viewport: $('#viewport'),
        viewlist: $('ul#viewlist'),
        listitems: $('#viewport li.viewitem'),
        panels: $('#viewport div.panel'),
        width: $('#viewport').width(),
        position: 0,
        ovulation: [0,0,0,0,0,0,0,5,7,10,22,33,35,35,33,28,24,12,5],
        women: [],
        results: [],
        ridcounter: 1,
        MINVIEWPORT: 640,
        MSPERDAY: 86400000,
        MAXDAYS: 32,
        AVGDAYS: 28,


        init: function() {
            var that = this;
            this.read_her();
            
            $.easing.def = "easeInOutQuad";
            
            this.resize();
            $(this.viewlist).css('left', (-1 * this.width * this.position));
            
            $(window).bind('resize', function() {
                that.resize();
                $(that.viewlist).css('left', (-1 * that.width * that.position));
            });
            
            $('#l_addher').bind('click', function() {
                that.add_her();
            });
            
            $('#l_herdate').datepicker({dateFormat: 'mm/dd/yy'});
            
            $('#l_gonext').bind('click', function(event) { that.move_right(); event.preventDefault(); });
            $('#l_goback').bind('click', function(event) { that.move_left(); event.preventDefault(); });
            
            $('#onemoredetail input').each(function() {
                $(this).removeAttr('checked');
                $(this).bind('click', function() { that.showresult(); });
            });

            $('.viewitem').each(function() { $(this).hide().css('visibility', 'visible').fadeIn("fast"); });
            this.recalculate();
        },

        showresult: function() {
            var r = null;
            var that = this;
            $('#onemoredetail input').each(function() {
                if ($(this).attr('checked')) {
                    r = $(this).attr('value');
                }
            });

            if (r == 'yes') {
                $('#results h1').html('Today, you should have sex with <span class="hername">' + this.women[this.women.length - 1].name + '.</span>');
            }

            if (r == 'maybe') {
                $('#results h1').html('Today, you should have sex with <span class="hername">' + this.women[0].name + '.</span>');
            }

            if (r == 'no') {
                $('#results h1').html('<span class="hername">' + "Don't have sex</span>.");
            }
        },

        read_her: function() {
            var her = $.cookie('women');
            if (her) {
                her = her.split('#');
                this.women = [];
                for(var i = 0; i < her.length; i++) {
                    var h = her[i].split('%');
                    var a = []
                    for(j = 1; j < h.length; j++) { a.push(h[j]); }
                    this.women.push({name: h[0], when: a});
                }
            }
        },

        write_her: function() {
            var ret = '';
            var her = [];
            for(var i = 0; i < this.women.length; i++) {
                var h = [];
                h.push(this.women[i].name)
                for(j = 0; j < this.women[i].when.length; j++) {
                    h.push(parseInt(this.women[i].when[j]));
                }
                her.push(h.join('%'));
            }
            $.cookie('women', her.join('#'), {'expires': 32});
        },
                

        add_her: function() {
            var name = $('#l_hername').attr('value');
            var when = $('#l_herdate').attr('value');

            name = name.replace(/^\s+/, "").replace(/\s+$/, "");
            when = when.replace(/^\s+/, "").replace(/\s+$/, "");
            if ((name.length == 0) || (when.length == 0)) { return false; }

            for(var i = 0; i < this.women.length; i++) {
                if (this.women[i].name == name) {
                    alert("You already have a lover with than name.");
                    return false;
                }
            };
            
            var now = new Date();
            when = when.split('/');

            var lwhen = new Date();
            lwhen.setFullYear(parseInt(when[2]),
                              parseInt(when[0] - 1),
                              parseInt(when[1]))
            when = lwhen.getTime();

            if ((lwhen > now) || ((now - lwhen) > (84 * this.MSPERDAY))) {
                alert("The date entered does not make sense");
                return false;
            }
            
            this.women.push({'name': name, 'when': [parseInt(when / this.MSPERDAY) + 1]});
            this.write_her();
            this.recalculate();
        },

        edit_her: function(e, row) {
            var wrow = parseInt($('input.dpi', row).attr('value'));

            var now = new Date();
            var when = e.split('/');
            var lwhen = new Date();
            lwhen.setFullYear(parseInt(when[2]),
                              parseInt(when[0] - 1),
                              parseInt(when[1]))
            when = lwhen.getTime();
            if ((lwhen > now) || ((now - lwhen) > (84 * this.MSPERDAY))) {
                alert("The date entered does not make sense");
                return false;
            }
            this.women[wrow].when = [parseInt(when / this.MSPERDAY) + 1];
            this.write_her();
            this.recalculate();
        },

        resize: function() {
            var that = this;
            this.width = $(this.viewport).width();

            if (this.width < this.MINVIEWPORT) {
                this.width = this.MINVIEWPORT;
            }

            $(this.viewlist).css('width', this.width * this.listitems.length);
            $(this.panels).each(function() {
                $(this).css('width', that.width + 'px')});
        },

        del_woman: function(event) {
            var that = this;
            var dpi = parseInt($('input.dpi', $(event.target).parent().parent()).attr('value'));
            ret = []
            for(i = 0; i < this.women.length; i++) {
                if (i == dpi) { continue; }
                ret.push(this.women[i]);
            }
            this.women = ret;
            this.write_her();
            this.recalculate();
        },
        
        retrigger: function() {
            var that = this;
            $('.trl').each(function() {

                var row = this;
                $('.wdel', $(this)).hide().css('visibility', 'visible');
                $('.wedit', $(this)).hide().css('visibility', 'visible');
                $(this).bind('mouseenter', function() {
                    $('.wdel', $(this)).fadeIn('fast');})
                $(this).bind('mouseleave', function() {
                    $('.wdel', $(this)).fadeOut('fast');})
                $(this).bind('mouseenter', function() {
                    $('.wedit', $(this)).fadeIn('fast');})
                $(this).bind('mouseleave', function() {
                    $('.wedit', $(this)).fadeOut('fast');})

                $('.wdel', $(this)).bind('click', function(event) {that.del_woman(event)});

                var d = parseInt($('.womandate', $(this)).attr('value')) * 86400000;
                var nd = new Date();
                nd.setTime(d)
                $('.womandate', $(this)).datepicker({ dateFormat: 'mm/dd/yy', 
                                                      defaultDate: nd, 
                                                      onSelect: function(e) {that.edit_her(e, row);}});
                $('.womandate', $(this)).attr('value', nd.format('mm/dd/yyyy'));
            });
        },

        recalculate: function() {
            var that = this;
            if (this.women.length > 0) {
                $('#wiylnone').fadeOut('fast');
                $('#l_gonext').css('color', 'blue').css('text-decoration', 'underline');
                $('#l_gonext').unbind();
                $('#l_gonext').bind('click', function() { that.move_right(); });

            } else {
                $('#wiylnone').fadeIn('fast');
                $('#l_gonext').css('color', 'lightgrey');
                $('#l_gonext').unbind();
            }

            $('#womeninyourlife').html("");
            for(var i = 0; i < this.women.length; i++) {
                $('#womeninyourlife').append('<tr class="trl"><td class="tdl" id="wiyltr' + 
                                             that.ridcounter + '" style="display: none">' + 
                                             this.women[i].name + '</td><td>' + 
                                             '<input type="text" class="womandate" value="' + this.women[i].when + '">' +  
                                             '</td><td>' +
                                             '<a href="#" class="wdel">[delete]</a> <input type="hidden" class="dpi" value="' + i + '">')
                

                $('#wiyltr' + that.ridcounter).fadeIn('fast');
                that.ridcounter++;
            }

            this.retrigger();

            var cr = [];

            /* For each women, get her name, the average length of her
            cycle, and the last recorded time.  Assume a cycle of 28 days 
            if only one input.  */

            var today = new Date();
            today = parseInt(today.getTime() / this.MSPERDAY);

            for(var i = 0; i < this.women.length; i++) {
                var r = 28;
                if (this.women[i].when.length > 1) {
                    var a = 0;
                    for(var j = 1; j < this.women[i].when.length; j++) {
                        a += (this.women[i].when[j - 1] + this.women[i].when[j] + 1);
                    }
                    r = parseInt(a / (this.women[i].when.length - 1));
                }

                /* From date of last period recorded, find where we are in "this" cycle */
                var l = today - parseInt(this.women[i].when[this.women[i].when.length - 1]);
                while(l > 32) { l = l - r; }

                var sc = 0;
                if (l < this.ovulation.length) { 
                    sc = this.ovulation[l];
                }

                cr.push({name: this.women[i].name, score: sc});
            }
            this.results = cr.sort(function (a, b) {return (a.score - b.score);});
        },

        move_left: function() {
            if (this.position > 0) {
                var that = this;
                this.position = this.position - 1;
	        $(that.viewlist)
                    .animate({left: (-1 * that.width * that.position) + "px"}, 1000);
            }
        },

        move_right: function() {
            if (this.position < 5) {
                var that = this;
                this.position = this.position + 1;
	        $(that.viewlist)
                    .animate({left: (-1 * that.width * that.position) + "px"}, 1000);
            }
        }
    }

    ret.init();
    return ret;
};

$(document).ready(function() {
    var p = Poly();
});


