$(document).ready(function() {
     //makes buttons buttons
     $("button").button();
     console.log('document ready');
    //makes datepickers
    $( ".datepicker" ).datepicker();
    //$('#newworkout').find('input.datepicker').datepicker();
    $('.datepicker').datepicker('setDate', new Date());
    //$('.datepicker').datepicker("hide");


    jQuery.extend({
        getValues: function(url) {
            var result = null;
            $.ajax({
                url: url,
                type: 'get',
                dataType: 'json',
                async: false,
                success: function(data) {
                    result = data;
                }
            });
           return result;
        }
    });

    originalExerciselist = $.getValues("/api/exerciselist");


     $("button#addExercise").click(function() {
        console.log("click!");
        var newElem = $('<li class=ui-state-default ><label for="element">elements[0][exerciseID]<br /></label><input name="elements[][exerciseID]" class="element"><button type="button" class="addSet">Add Set</button><button type="button" class="delete">Delete Exercise</button><ul class="sets"></ul></li>');
        $(newElem).appendTo('ul#exercises');
        $("button").button();
        $( "ul#exercises" ).sortable( "refresh" );
        $('#newworkout').trigger('sortupdate');
        });

    $(document).on('click', '.addSet',(function() {
        var newElem = $('<li class="set"><label for="element" name="elements[0][splits][0][reps]">elements[0][splits][0][reps]<br /></label><input name="elements[0][splits][0][reps]" class="element"><label for="element" name="elements[0][splits][0][weight]"><br />elements[0][splits][0][weight]<br /></label><input name="elements[0][splits][0][weight]" class="element"><button type="button" class="delete">Delete Set</button></li>');
        $(this).siblings('ul.sets').append(newElem);
        $("button").button();
        $("ul.sets").sortable({
                items: "> li",
                cancel: ':input, button' ,
                placeholder: "ui-state-highlight",
                revert: true,
                start: function(e, ui){
                    ui.placeholder.height(ui.item.height());
                },
                stop: function(event, ui) {
                    $('#newworkout').trigger('sortupdate');
                }
            });
        $( "#exercises" ).sortable( "refresh" );
        $( ".sets" ).sortable( "refresh" );
        $('#newworkout').trigger('sortupdate');
        }));

     $(document).on('click', '.delete',function() {
           $(this).closest('li').remove();
           $('#newworkout').trigger('sortupdate');
     });



    $("#newworkout").bind('sortupdate', function(event, ui) {
        $('#exercises > li').each(function(){
            var itemindex= $(this).index();
            // var newname = $(this).find('input, select').attr('name').replace(/elements\[[0-9]*\]/,'elements[' + itemindex  + ']');
            $(this).find('input, select').each(function() {
               var newname =  $(this).attr('name').replace(/elements\[[0-9]*\]/,'elements[' + itemindex  + ']');
               $(this).attr('name', newname);
            });
            // $(this).find('label').each(function() {
            //     var value = $(this).attr('href');
            //     console.log ('value -' + value);
            //     $(this).attr('href', value.replace(/elements\[[0-9]*\]/,'elements[' + itemindex  + ']'));

            //    //var newname =  $(this).html.replace(/elements\[[0-9]*\]/,'elements[' + itemindex  + ']');
            //    //$(this).html(newname);
            // });

                $(this).find('ul li').each(function(){
                    var itemindex2= $(this).index();

                    $(this).children('input').each(function(){
                        var newname2 = $(this).attr('name').replace(/\[splits\]\[[0-9]*\]/,'[splits][' + itemindex2  + ']');
                        newname2 = newname2.replace(/elements\[[0-9]*\]/,'elements[' + itemindex  + ']');
                        $(this).attr('name', newname2);
                    });

                    $(this).children('label').each(function(){
                         //var newname2 = $(this).attr('name').replace(/\[splits\]\[[0-9]*\]/,'[splits][' + itemindex2  + ']');
                         //newname2 = newname2.replace(/elements\[[0-9]*\]/,'elements[' + itemindex  + ']');
                         var newname2 = 'Set '+ (itemindex2 + 1 ) + '';
                         $(this).html(newname2);
                    });

                 //Only show delete if more than 1 set
                 if ( $(this).siblings('.set').length > 0 ) {
                   $(this).children('.delete').show();
                 } else {
                    $(this).children('.delete').hide();
                }

            });



        });
        //return false;
    });


        $("ul#exercises").sortable({
                items: "> li",
                cancel: ':input, button' ,
                placeholder: "ui-state-highlight",
                revert: true,
                start: function(e, ui){
                    ui.placeholder.height(ui.item.height());
                },
                stop: function(event, ui) {
                    $('#newworkout').trigger('sortupdate');
                }
            });


       //$('#newworkout').trigger('sortupdate');

        $("button.map-link").click(function () {
        console.log('mapclick');
        var id = $(this).attr('value');
        console.log(id);
        $('div#Rightpane').empty().load(id, function(){
            PopulateExerciseList(originalExerciselist);
            });
        });

    $(document).on('click', '.addthisExercise',(function() {
    // $("button.addthisExercise").click(function() {
        console.log("This exercise name li" + JSON.stringify($(this).closest('li').data()));
        var newElem = $('<li class=ui-state-default ><label for="element">Name</label><input name="exercisename" class="element" value="' + $(this).closest('li').data('name') + '"><input name="elements[][exerciseID]" class="hiddenelement" value="' + $(this).closest('li').data('exid') + '"><input name="elements[][Modifier]" class="element" value="' + $(this).closest('li').data('musclearrayMod') + '"><button type="button" class="addSet">Add Set</button><button type="button" class="delete">Delete Exercise</button><ul class="sets"><li class="set"><label for="element" name="elements[0][splits][0][reps]">elements[0][splits][0][reps]<br /></label><input name="elements[0][splits][0][reps]" class="element"><label for="element" name="elements[0][splits][0][weight]"><br />elements[0][splits][0][weight]<br /></label><input name="elements[0][splits][0][weight]" class="element"><button type="button" class="delete">Delete Set</button></li></ul></li>');
        $(newElem).data('musclearray', $(this).closest('li').data('musclearray'));
        $(newElem).data('musclearrayMod', $(this).closest('li').data('musclearrayMod'));
        $(newElem).appendTo('ul#exercises');
        $( ".hiddenelement" ).hide();
        $("button").button();
        $( "ul#exercises" ).sortable( "refresh" );
        $( "ul#sets" ).sortable( "refresh" );
        $('#newworkout').trigger('sortupdate');
      })
    );

    //filteredExerciseArray = filterarray(originalExerciselist);
    //PopulateExerciseList(arr);

            $(document).on('click', '.filter',(function (){
              var keyREGEX= "";
              if ($(".filter:checked").length > 0)
                {
                    // any one is checked
                    var len = $('.filter').length;
                    $(".filter").each(function(index, element) {

                        if ($(this).is (':checked'))
                        {
                            // Do stuff
                            keyREGEX += '('+ $(this).val() +')';
                        }
                        });
                    //keyREGEX += "'";
                    keyREGEX = keyREGEX.replace(")(", ")|(");
                } else {
                   // none is checked
                   keyREGEX = '(none is checked)';
                }

                console.log("Regex= " + keyREGEX);
                filteredExerciseArray = filterarray(originalExerciselist, keyREGEX);
                PopulateExerciseList(filteredExerciseArray);
                console.timeEnd('Filter');
            }));


            function  filterarray(input, regex){
                console.log('passed regex' + regex);
                var keyRE=new RegExp(regex);
                var arr = jQuery.grep(input, function(n, i){
                            return keyRE.test(n.keywords);
                            // return $.grep(n.keywords, function (item, i) {
                            //     return keyRE.test(item);
                            // });
                });
                console.log("arr " +  arr.length);
                return arr;
            }

/////////////////////////////////
//  Pseudocode for  1RM calcs

// for each exercise in workout
//   get H1RM for exercise
//   C1RMsum = 0 
//   for each set in exercise
//     calculate C1RM and store in array
//   find highest C1RM in array
//   if C1RM > H1RM then
//     H1RM = C1RM
//     set comment to "yay"
//   for each value in array
//     set[index] = value/H1RM
//    C1RMsum += value/H1RM
//   Done


//  assume  sum sumarray * each in musclearray



////// Make below standalone funtion "updateExerciselistDIV"
function PopulateExerciseList(exerciselist) {
    console.time('PopulateExList');
     var newExerciselist  = $('<div></div>');
        $.each(exerciselist,  function (i, item) {
            //console.log("Exercisename = " + item.name);
             var newElem = $('<li>'+item.name + ' - ' + item.description + ' - ' + item.keywords +'<button type="button" class="addthisExercise">+</li>');
             $(newElem).data('name', item.name);
             $(newElem).data('exid', item._id);
             $(newElem).data('musclearray', item.musclearray);
             //$(newElem).data('musclearrayMod', item.musclearrayMod);
             $(newElem).data('datafields', item.datafields);
             newExerciselist.append(newElem);
        });
        console.log("newexlist outside= " + newExerciselist);
        $('#exerciselist').empty();
        $(newExerciselist).appendTo('#exerciselist');
        $("button").button();
        console.timeEnd('PopulateExList');
    }


});








