// JavaScript Document
(function ($) {


    var day_state = {
        "Su":0,
        "M":0,
        "Tu":0,
        "W":0,
        "Th":0,
        "F":0,
        "Sa":0
    };

    var log = function(msg) {
        if (console != undefined) {
            console.log(msg)
        }
    }

    /*
    Object.prototype.convertToArray = function(n) {
       if (! this.length) {return [];} // length must be set on the object, or it is not iterable
       var a = [];
       try {
           a = Array.prototype.slice.call(this, n);
       }
       // IE 6 and posssibly other browsers will throw an exception, so catch it and use brute force
       catch(e) {
           Core.batch(this, function(o, i) {
               if (n <= i) {
                   a[i - n] = o;
               }
           });
       }
       return a;
    };*/


    function checkdays(d)
    {
        c=0;
        for (var k in day_state) {
            if (day_state[k] > 0 || k==d) {
                if (k!=d) {
                    c++;
                } else if (day_state[d]==0) {
                    c++;
                }
            } else {
                c=0;
            }
            if (c>2) {
                return false;
            }
        }
        return true;
    }

    function show_response(responseText, statusText)  {
        jQuery.each(responseText, function(k,v) {
            if (k=='feedback'){
                $('#feedback').removeClass("hide").html(v);
            } else {
                /*$('#'+k).qtip({
                                    content: {text: v},
                                    show: {ready: true},
                                    style: {name: 'red'}
                            });*/
                $('#'+k).css('background-color', '#F79992');
            }
        });
    }

    function clear_errors(formData, jqForm, options) {
        jQuery.each(formData, function(i, o) {
            $('#'+o.name+'').css('background-color', '#FFFFFF');
        //$('#'+o.name+'').qtip("destroy");
        });
        return true;
    }



    // Create the tooltips only on document load
    $(document).ready(function()
    {

        if($.fn.qtip) {
            $.fn.qtip.styles.mystyle = { // Last part is the name of the style
                width: 400,
                background: '#fff',
                color: '#133636',
                textSize: '14px',
                textAlign: 'left',
                fontFamily: 'Arial, Helvetica, sans-serif',
                border: {
                    width: 7,
                    radius: 10,
                    color: '#999'
                },
                tip: 'bottomLeft',
                name: 'dark' // Inherit the rest of the attributes from the preset dark style
            }

            $.fn.qtip.styles.errstyle = { // Last part is the name of the style
                width: 200,
                background: '#fff',
                color: '#FF0000',
                textSize: '14px',
                textAlign: 'left',
                fontFamily: 'Arial, Helvetica, sans-serif',
                cursor: 'pointer',
                border: {
                    width: 7,
                    radius: 10,
                    color: '#F00'
                },
                tip: 'bottomRight',
                name: 'dark' // Inherit the rest of the attributes from the preset dark style
            }
        }

        // redirect ajax requests that are redirected, not found (404), or forbidden (403.)
        $('body').bind('ajaxComplete', function(event,request,settings){
            switch(request.status) {
                case 301: case 404: case 403:
                    window.location.replace('/user/login');
                    break;
                default:
                    log('passed ajax success event with status: '+request.status);
            }
        });

        if($.fn.qtip) {
            // By suppling no content attribute, the library uses each elements title attribute by default
            $('.footerAnchor a[href][title]').qtip({
                content: {
                    text: false // Use each elements title attribute
                },
                position: {
                    corner: {
                        target: 'topMiddle',
                        tooltip: 'bottomLeft'
                    }
                },

                style: 'mystyle' // Give it some style
            });

            $('#errorBox a[title]').qtip({
                content: {
                    text: false // Use each elements title attribute
                },
                position: {
                    corner: {
                        target: 'topMiddle',
                        tooltip: 'bottomRight'
                    }
                },

                style: 'errstyle' // Give it some style
            });
        }

        if($.fn.ajaxSubmit) {
            // handle forms on account page.
            var options = {
                beforeSubmit:  	clear_errors,  // pre-submit callback
                success:	show_response,  // post-submit callback
                dataType:      	'json',
                url:       	'/user/account/ajax'
            };
            $('#feedback').addClass("hide");
            $('#frm_personal_info').ajaxForm(options);
            $('#frm_password').ajaxForm(options);
            $('#frm_creditcard').ajaxForm(options);
        }

        // NOTE: You can even omit all options and simply replace the regular title tooltips like so:
        // $('#content a[href]').qtip();

        $('#headerLogin #password').hide();
        $('#headerLogin #email').focus(function () {
            $(this).val("");
            $('#headerLogin #email').focus();
        });

        $('#headerLogin #passwordMoc').focus(function () {
            //$(this).val("");
            $(this).hide();
            $('#headerLogin #password').show();
            $('#headerLogin #password').focus();
        });

        $('#oneRepMaxTip').click(function (){
            $('#footerNotes').slideToggle("slow");

        });

        //	$('#workoutDaysContainer span').each(function(i){
        //		day_state[$(this).text()] = ($(this).hasClass('selected'))?1:0;
        //	});
        //
        //	$('#AltWorkoutDaysContainer span').each(function(i){
        //		if ( $(this).hasClass('selected') ) {
        //			day_state[$(this).text()] = 2;
        //		}
        //	});

        var update_day_state = function() {
            // reset object array
            day_state = {
                "Su":0,
                "M":0,
                "Tu":0,
                "W":0,
                "Th":0,
                "F":0,
                "Sa":0
            };
            $('#workoutDaysContainer').find('span').each(function(i){
                if ( $(this).hasClass('selected') ){
                    day_state[$(this).text()] = 1;
                }
            });
            $('#AltWorkoutDaysContainer').find('span').each(function(i){
                if ( $(this).hasClass('selected') ){
                    day_state[$(this).text()] = 2;
                }
            });
        //log(day_state);
        }

        $('#workoutDaysContainer span').click(function (){
            var d=$(this).text();
            $(this).toggleClass('selected')
            .toggleClass('notSelected');
            // remove rest day if they match.
            $("#AltWorkoutDaysContainer").find("span:contains('"+d+"')")
            .removeClass('selected')
            .addClass('notSelected');
        //update_day_state();
        });

        $('#AltWorkoutDaysContainer span').click(function (){
            var d=$(this).text();
            // remove day selected for gym days if match
            $("#workoutDaysContainer").find("span:contains('"+d+"')")
            .removeClass('selected')
            .addClass('notSelected');
            // only one rest day allowed, remove any others.
            $(this).parent().find("span")
            .removeClass('selected')
            .addClass('notSelected');
            // toggle current span.
            $(this).toggleClass('selected')
            .toggleClass('notSelected');
        //update_day_state();
        });

        $('.h1iconPreferences').click(function (){
            $(this).parents('.secondBox').find('.innerBox').toggle('fast');
        });

        $("#formPrefs").submit(function() {
            update_day_state();
            $(this).append("<input type='hidden' name='workout_days' value='"+$.param(day_state)+"'>");
        });        
    });
})(jQuery);

