<commit_before>/*!
 * treejo v0.001
 *
 * (c) 2015 David Schmidt <davewood@gmx.at>
 * Released under the Artistic License 2.0 (see LICENSE file for details)
 */

(function( treejo, undefined ) {
    'use strict';

    var options = {
        "selector":           '#treejo',
        "window_top_offset":  30,
        "url":                '/api',
        "highlight_duration": 5000,
        "scroll_duration":    500,
        "slide_duration":     500,
        "max_counter":        30,
        "req_param_key":      'node_id',
        "html_node_toggle":   '
+
 ',
        "html_node_closed":   '+',
        "html_node_open":     '-',
        "html_node_show_all": '
a
 ',
    };

    function node_load(node) {
        var node_id = node.data('node-id');

        var content = node.children('.node-content');
        if ( content.length === 0 ) {
            var data = {};
            data[options.req_param_key] = node.data('node-id');
            content = $('

');
            $.ajax({
                url:      options.url,
                async:    false,
                type:     'GET',
                data:     data,
                dataType: 'json',
                error:    function(jqXHR, textStatus, errorThrown) { console.warn(errorThrown); alert('Ajax Error: ' + textStatus); },
                success:  function( data ) {
                              content.append('

');
                              $.each( data.child_nodes, function(index, value) {
                                  content.append(build_node(value));
                              })
                          }
            });
            node.append(content);
        }
    }

    function node_show_all(nodes) {
        var counter          = 0;
        var continue_loading = 1;

        do {
            if (nodes.length) {
                nodes.each(
                    function(index, value) {
                        if ( counter >= options.max_counter ) {
                            if (confirm("Do you want to open " + options.max_counter + " more nodes?")) {
                                counter = 0;
                            }
                            else {
                                continue_loading = 0;
                                return false; // stop each() loop
                            }
                        }
                        node_show($(value));
                        counter = counter + 1;
                    }
                );
                nodes = nodes.children('.node-content').children('.node').has('.node-panel > .node-heading > .node-closed');
            }
            else {
                continue_loading = 0;
            }
        } while( continue_loading );
    }

    function node_show(node) {
        node_load(node);
        node.children('.node-content').slideDown({ duration: options.slide_duration });
        var node_toggle = node.children('.node-panel').children('.node-heading').children('.node-toggle');
        node_toggle.removeClass('node-closed');
        node_toggle.addClass('node-open');
        node_toggle.html(options.html_node_open);
    }
    function node_hide(node) {
        node.children('.node-content').slideUp({ duration: options.slide_duration });
        var node_toggle = node.children('.node-panel').children('.node-heading').children('.node-toggle');
        node_toggle.removeClass('node-open');
        node_toggle.addClass('node-closed');
        node_toggle.html(options.html_node_closed);
    }

    function find_node_by_path(path) {
        var parts = path.split('.');
        if ( parts.shift() !== '1' ) { // materialized path always starts with '1'
            console.warn('materialized paths always have to begin with "1". ('+ path + ')');
            return;
        }
        var current = $(options.selector + ' > .node').first();
        for (var i = 0; i < parts.length; i++) {
            var index = parts[i] - 1;
            node_show(current);
            current = $( current.children('.node-content').children('.node').get(index) );
            if (current.length === 0) {
                console.warn('Path does not exist: ' + path);
                return;
            }
        }
        scroll_to_node(current);
    }

    function scroll_to_node(node) {
        $('html, body').animate(
            {
                scrollTop: node.offset().top - options.window_top_offset
            },
            options.scroll_duration
        );
        highlight_panel(node);
    }
    function highlight_panel(node) {
        var panel = node.children('.node-panel');
        panel.addClass('node-highlight');
        setTimeout(
          function() {
              panel.removeClass('node-highlight');
          },
          options.highlight_duration
        );
    }
    function is_visible(node) {
        var view_top     = window.pageYOffset + options.window_top_offset;
        var view_bottom  = view_top + $(window).height();
        var panel        = node.children('.node-panel');
        var panel_top    = panel.offset().top;
        var panel_bottom = panel_top + panel.height();

        if ( panel_top > view_top && panel_bottom < view_bottom ) {
            return true;
        }
        else {
            return false;
        }
    }

    function build_node(data) {
        return '
'
             +   '
'
             +       data.title
             +     '
'
             +       ( data.has_children /* only show buttons if node has children */
                       ? options.html_node_toggle + options.html_node_show_all
                       : '')
             +     '
'
             +     ( data.body !== ''
                     ? '
' + data.body + '
'
                     : '')
             +   '
'
             + '
';
    }
    // looks for a child element with init data for a root node
    // and replaces it with a proper node element.
    function build_root_node(tree) {
        var root_node = tree.find('.node-init');
        if ( root_node.length > 0 ) {
            var node = $(
                          build_node({
                                    id:           root_node.data('node-id'),
                                    title:        root_node.data('title'),
                                    body:         root_node.data('body'),
                                    has_children: true
                                  })
                       );
            node.addClass( root_node.removeClass('node-init').attr('class') );
            root_node.replaceWith(node);
        }
    }

    // looks for elements with data for a quicklink
    // and adds a clickhandler for finding a node.
    function build_quicklinks(tree) {
        var quicklinks = tree.find('.quicklink-init');
        quicklinks.each( function( index, value ) {
            var val = $(value);
            val.removeClass('quicklink-init');
            val.click(function() { find_node_by_path( String(val.data('path')) ); })
        });
    }

    treejo.init = function(_options) {
        $.extend( options, _options ); /* override options */

        var tree = $(options.selector);
        if ( tree.length === 0 ) {
            console.warn('No elements found using selector: "' + options.selector + '"');
        }
        else {
            build_quicklinks(tree);
            build_root_node(tree);

            tree.on('click',
                    '.node-toggle.node-closed',
                    function(event) {
                        node_show( $(event.target).closest('.node') );
                    });
            tree.on('click',
                    '.node-toggle.node-open',
                    function(event) {
                        node_hide( $(event.target).closest('.node') );
                    });
            tree.on('click',
                    '.node-show-all',
                    function(event) {
                        node_show_all( $(event.target).closest('.node') );
                    });
            tree.on('click',
                    '.node-closer',
                    function(event) {
                        var node = $(event.target).closest('.node');
                        node_hide(node);
                        if( !is_visible(node) ) {
                            scroll_to_node(node);
                        }
                        else {
                            highlight_panel(node);
                        }
                    });
        }
    };

    return treejo;
}( window.treejo = window.treejo || {} ));
<commit_msg>wrap title in element with class .node-title<commit_after>/*!
 * treejo v0.001
 *
 * (c) 2015 David Schmidt <davewood@gmx.at>
 * Released under the Artistic License 2.0 (see LICENSE file for details)
 */

(function( treejo, undefined ) {
    'use strict';

    var options = {
        "selector":           '#treejo',
        "window_top_offset":  30,
        "url":                '/api',
        "highlight_duration": 5000,
        "scroll_duration":    500,
        "slide_duration":     500,
        "max_counter":        30,
        "req_param_key":      'node_id',
        "html_node_toggle":   '
+
 ',
        "html_node_closed":   '+',
        "html_node_open":     '-',
        "html_node_show_all": '
a
 ',
    };

    function node_load(node) {
        var node_id = node.data('node-id');

        var content = node.children('.node-content');
        if ( content.length === 0 ) {
            var data = {};
            data[options.req_param_key] = node.data('node-id');
            content = $('

');
            $.ajax({
                url:      options.url,
                async:    false,
                type:     'GET',
                data:     data,
                dataType: 'json',
                error:    function(jqXHR, textStatus, errorThrown) { console.warn(errorThrown); alert('Ajax Error: ' + textStatus); },
                success:  function( data ) {
                              content.append('

');
                              $.each( data.child_nodes, function(index, value) {
                                  content.append(build_node(value));
                              })
                          }
            });
            node.append(content);
        }
    }

    function node_show_all(nodes) {
        var counter          = 0;
        var continue_loading = 1;

        do {
            if (nodes.length) {
                nodes.each(
                    function(index, value) {
                        if ( counter >= options.max_counter ) {
                            if (confirm("Do you want to open " + options.max_counter + " more nodes?")) {
                                counter = 0;
                            }
                            else {
                                continue_loading = 0;
                                return false; // stop each() loop
                            }
                        }
                        node_show($(value));
                        counter = counter + 1;
                    }
                );
                nodes = nodes.children('.node-content').children('.node').has('.node-panel > .node-heading > .node-closed');
            }
            else {
                continue_loading = 0;
            }
        } while( continue_loading );
    }

    function node_show(node) {
        node_load(node);
        node.children('.node-content').slideDown({ duration: options.slide_duration });
        var node_toggle = node.children('.node-panel').children('.node-heading').children('.node-toggle');
        node_toggle.removeClass('node-closed');
        node_toggle.addClass('node-open');
        node_toggle.html(options.html_node_open);
    }
    function node_hide(node) {
        node.children('.node-content').slideUp({ duration: options.slide_duration });
        var node_toggle = node.children('.node-panel').children('.node-heading').children('.node-toggle');
        node_toggle.removeClass('node-open');
        node_toggle.addClass('node-closed');
        node_toggle.html(options.html_node_closed);
    }

    function find_node_by_path(path) {
        var parts = path.split('.');
        if ( parts.shift() !== '1' ) { // materialized path always starts with '1'
            console.warn('materialized paths always have to begin with "1". ('+ path + ')');
            return;
        }
        var current = $(options.selector + ' > .node').first();
        for (var i = 0; i < parts.length; i++) {
            var index = parts[i] - 1;
            node_show(current);
            current = $( current.children('.node-content').children('.node').get(index) );
            if (current.length === 0) {
                console.warn('Path does not exist: ' + path);
                return;
            }
        }
        scroll_to_node(current);
    }

    function scroll_to_node(node) {
        $('html, body').animate(
            {
                scrollTop: node.offset().top - options.window_top_offset
            },
            options.scroll_duration
        );
        highlight_panel(node);
    }
    function highlight_panel(node) {
        var panel = node.children('.node-panel');
        panel.addClass('node-highlight');
        setTimeout(
          function() {
              panel.removeClass('node-highlight');
          },
          options.highlight_duration
        );
    }
    function is_visible(node) {
        var view_top     = window.pageYOffset + options.window_top_offset;
        var view_bottom  = view_top + $(window).height();
        var panel        = node.children('.node-panel');
        var panel_top    = panel.offset().top;
        var panel_bottom = panel_top + panel.height();

        if ( panel_top > view_top && panel_bottom < view_bottom ) {
            return true;
        }
        else {
            return false;
        }
    }

    function build_node(data) {
        return '
'
             +   '
'
             +     '
'
             +       ( data.has_children /* only show buttons if node has children */
                       ? options.html_node_toggle + options.html_node_show_all
                       : '')
             +       '' + data.title + ''
             +     '
'
             +     ( data.body !== ''
                     ? '
' + data.body + '
'
                     : '')
             +   '
'
             + '
';
    }
    // looks for a child element with init data for a root node
    // and replaces it with a proper node element.
    function build_root_node(tree) {
        var root_node = tree.find('.node-init');
        if ( root_node.length > 0 ) {
            var node = $(
                          build_node({
                                    id:           root_node.data('node-id'),
                                    title:        root_node.data('title'),
                                    body:         root_node.data('body'),
                                    has_children: true
                                  })
                       );
            node.addClass( root_node.removeClass('node-init').attr('class') );
            root_node.replaceWith(node);
        }
    }

    // looks for elements with data for a quicklink
    // and adds a clickhandler for finding a node.
    function build_quicklinks(tree) {
        var quicklinks = tree.find('.quicklink-init');
        quicklinks.each( function( index, value ) {
            var val = $(value);
            val.removeClass('quicklink-init');
            val.click(function() { find_node_by_path( String(val.data('path')) ); })
        });
    }

    treejo.init = function(_options) {
        $.extend( options, _options ); /* override options */

        var tree = $(options.selector);
        if ( tree.length === 0 ) {
            console.warn('No elements found using selector: "' + options.selector + '"');
        }
        else {
            build_quicklinks(tree);
            build_root_node(tree);

            tree.on('click',
                    '.node-toggle.node-closed',
                    function(event) {
                        node_show( $(event.target).closest('.node') );
                    });
            tree.on('click',
                    '.node-toggle.node-open',
                    function(event) {
                        node_hide( $(event.target).closest('.node') );
                    });
            tree.on('click',
                    '.node-show-all',
                    function(event) {
                        node_show_all( $(event.target).closest('.node') );
                    });
            tree.on('click',
                    '.node-closer',
                    function(event) {
                        var node = $(event.target).closest('.node');
                        node_hide(node);
                        if( !is_visible(node) ) {
                            scroll_to_node(node);
                        }
                        else {
                            highlight_panel(node);
                        }
                    });
        }
    };

    return treejo;
}( window.treejo = window.treejo || {} ));
<|endoftext|>


<commit_before>/**
 * Created with IntelliJ IDEA.
 * User: bbhagan
 * Date: 6/26/13
 * Time: 1:33 PM
 * To change this template use File | Settings | File Templates.
 */

//http://stackoverflow.com/questions/5937339/ipad-safari-make-keyboard-disappear
var hideKeyboard = function() {
   document.activeElement.blur();
   $("input").blur();
};

$(document).ready(function() {
   $('#tour').bind('resize', function(event) {
      $('#tour').css({'height': 768});
      $('#tour').css({'width': 1024});
      //alert('orientation change');
   });
   // Set so birthday can't be past today
   $("#getStartedFormChildBirthday").attr("max", dateToYMD(new Date()));

   $('#getStartedFormChildBirthday').on('click', function(e) {
      hideKeyboard();
      $('#getStartedFormChildBirthday').focus();
   });

   $("#getStartedForm").submit(function(e){
      transitionToStartTasks(e);
      $.mobile.navigate( "#startTasks" );
      return false;
   });

   $("#doneWithTasksButton").on("click", function(e){
      transitionToStartGoals(e);
   });

   $('#configureTasksRepeats').on('change', function(e) {
      swapConfigureTasksRepeats(e);
   })

   $('#configureRepeatPayment').on('change', function(e) {
      swapConfigureRepeatPayment(e);
   });
   $('#configureNonRepeatPayment').on('change', function(e) {
      swapConfigureNonRepeatPayment(e);
   });
   $("#configureTaskForm").submit( function(e) {
     $("#configureTaskForm .error").hide();
     addConfiguredTaskToChild(e);
     return false;
   });
});

var tykoonData = {
   parent: {
      children: []
   },
   currentChildIndex : 0
};
var currentChild;

var transitionToStartTasks = function(e) {

   // populate main data object
   var name = $('#getStartedFormChildFirstName').val();
   var birthdayString = $('#getStartedFormChildBirthday').val();
   // -1 on month, apparently 0-based for months
   var birthday = new Date(parseInt(birthdayString.substring(0,4)), parseInt(birthdayString.substring(5,7))-1, parseInt(birthdayString.substring(8)));
   var gender = $("input:radio[name='getStartedFormChildGender']:checked").val();
   var child = new Child(0, name, '', '', '', birthday, 0, gender);
   tykoonData.parent.children.push(child);

   currentChild = child;
   populateTasksForChild(child);
};

var configureTasks = function(e) {
   // FInd the task clicked on and collect it's data
   var taskltem = $(e.currentTarget),
      taskName = $(taskltem).find(".title").text(),
      taskId = $(taskltem).find(".title").attr("data-taskId");

   // populate the popup disclosure and show it
   $('#configureTasks .taskTitle').html(taskName).attr("data-taskId",taskId);
   // set due date of today or later
   $("#configureTasksDueDate").attr("min", dateToYMD(new Date()));

   $("#configureTasks").popup().popup("open", {transition: "pop"} );

   // reset the form before opening
   $("#configureTaskRepeatsYes, #configureRepeatPaymentAllow, #configureNonRepeatPaymentMoney" ).prop( "checked", true ).checkboxradio( "refresh" );
   $("#configureTaskRepeatsNo, #configureRepeatPaymentResp, #configureNonRepeatPaymentResp, #configureTasksWeeklyOn input[type='checkbox']" ).prop( "checked", false ).checkboxradio( "refresh" );
   $("#configureTasksHowMuch, #configureTasksDueDate").val("");
   swapConfigureTasksRepeats();
};

function dateToYMD(date) {
    var d = date.getDate();
    var m = date.getMonth() + 1;
    var y = date.getFullYear();
    return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}

var addConfiguredTaskToChild = function(e) {
  var taskTitle = $("#configureTasks .taskTitle").html(),
    taskId = $("#configureTasks .taskTitle").attr("data-taskId"),
    currentTask = new Task(taskId, taskTitle, [], '', '', '');  // new Task(id, name, repeatDays, payType, payAmt, dueDate);

  // If repeating task, collect repeatDays and paymentType
  var repeats = $("input:radio[name='configureTasksRepeats']:checked").val();
  if ( repeats == "1") {

    // add to 'repeatDays' array the days it repeats
    var weekDays = $("#configureTasksWeeklyOn input[type='checkbox']");
    for (i in weekDays) {
      var day = weekDays[i];
      if (day.hasOwnProperty('type') && day.checked) {
        currentTask.repeatDays.push($(day).val());
      }
    }
    // check for length of repeatDays
    if  (!currentTask.repeatDays.length) {
      $("#pickADay").show("fast");
      return false;
    }

    var paymentType = $("input:radio[name='configureRepeatPayment']:checked").val();
    currentTask.payType = paymentType;

  // Otherwise just collect payment type/amount and optional due date
  } else {
    var paymentType = $("input:radio[name='configureNonRepeatPayment']:checked").val();
    currentTask.payType = paymentType;
    if (paymentType == "money") {
      var moneyAmount = $("#configureTasksHowMuch").val();
      if (moneyAmount == "" || moneyAmount == "0") {
        $("#enterTaskMoney").show("fast");
        return false;
      }
      currentTask.payAmt = moneyAmount;
    }

    // due date
    var dueDateString = $('#configureTasksDueDate').val();
    if (dueDateString != "") {
      var dueDate = new Date(parseInt(dueDateString.substring(0,4)), parseInt(dueDateString.substring(5,7))-1, parseInt(dueDateString.substring(8)));
      currentTask.dueDate = dueDate;
    }
  }

  currentChild.tasks.push(currentTask);
}

var populateTasksForChild = function(child) {
  //populate page with child data
  $(".childFirstName").html(child.name);
  $(".childAge").html(child.getAge());
  $(".childGender").html(child.getGenderNoun());

  //clean page and populate page with tasks from catalog
 $('#startTasks .taskCatalog .tasks').empty();
 var taskTemplate = $("#startTasks .taskCatalog .taskTemplate .taskItem")[0];
  for(var i in cannedTasks.tasks) {
    var task = cannedTasks.tasks[i];
    if ((task.gender == "b" || task.gender == child.gender) && (child.getAge() >= task.ageRange.min && child.getAge() <= task.ageRange.max)) {
      var taskItem = $(taskTemplate).clone()
      $(taskItem).find(".title").html(task.name).attr("data-taskId", task.id);
      $(taskItem).find(".numKids span").html(task.numPeople);
      $('#startTasks .taskCatalog .tasks').append($(taskItem));
    }
  }

  // hook up the taps on taskItems to configure them
  $("#startTasks .taskCatalog .taskItem").on("click", function(e){
     configureTasks(e);
  });
};

var swapConfigureTasksRepeats = function(e) {
   if ($("input:radio[name='configureTasksRepeats']:checked").val() == 1) {
      $('#configureTasks .hideNonRepeat').hide();
      $('#configureTasks .hideRepeat').show();
   } else {
      $('#configureTasks .hideNonRepeat').show();
      $('#configureTasks .hideRepeat').hide();
   }
};

var swapConfigureRepeatPayment = function(e) {
   if ($("input:radio[name='configureRepeatPayment']:checked").val() == 'allowance') {
      $('#configureTasks .taskRepeatPaymentDetails .resp').hide();
      $('#configureTasks .taskRepeatPaymentDetails .allow').show();
   } else {
     $('#configureTasks .taskRepeatPaymentDetails .resp').show();
     $('#configureTasks .taskRepeatPaymentDetails .allow').hide();
   }
};
var swapConfigureNonRepeatPayment = function(e) {
   if ($("input:radio[name='configureNonRepeatPayment']:checked").val() == 'money') {
      $('#configureTasks .taskNonRepeatPaymentDetails .resp').hide();
      $('#configureTasks .taskNonRepeatPaymentDetails .money').show();
   } else {
     $('#configureTasks .taskNonRepeatPaymentDetails .resp').show();
     $('#configureTasks .taskNonRepeatPaymentDetails .money').hide();
   }
};

/* ADD GOALS section */

var transitionToStartGoals = function(e) {

  populateProductsForChild(currentChild);
  $(".addTaskContent, .startTasksFooter").fadeOut(200);

  // move the cover
  $(".cover").addClass("leftCover"); //.css("left","0");

  $(".addGoalContent, .startGoalsFooter").delay(400).fadeIn(200);
}

var populateProductsForChild = function(child) {

  //clean page and populate page with tasks from catalog
 $('#startTasks .productCatalog .goals').empty();
 var productTemplate = $("#startTasks .productCatalog .productTemplate .productItem")[0];
  for(var i in cannedProducts.products) {
    var product = cannedProducts.products[i];
    if ((product.gender == "b" || product.gender == child.gender) && (child.getAge() >= product.ageRange.min && child.getAge() <= product.ageRange.max)) {
      var productItem = $(productTemplate).clone();
      $(productItem).find(".title").html(product.name);
      $(productItem).find(".numKids span").html(product.numPeople);
      $(productItem).find(".thumbnail").attr({src: product.imgURL, alt: product.name});
      $('#startTasks .productCatalog .products').append($(productItem));
    }
  }

  // hook up the taps on productItems to configure them
  $("#startTasks .productCatalog .productItem").on("click", function(e){
     showProductDetails(e);
  });
};

var showProductDetails = function(e) {
  var productItem = $(e.currentTarget),
      productName = $(productItem).find(".title").text();
  alert("tapped on: " + productName);
}

/* ======== TEST DATA, comment me out to run for real ===========  */

var testBdayString = '2006-10-29';
var testBirthday = new Date(parseInt(testBdayString.substring(0,4)), parseInt(testBdayString.substring(5,7))-1, parseInt(testBdayString.substring(8)));
currentChild = new Child(0, 'Kaiya', '', '', '', testBirthday, 0, 'f');
tykoonData.parent.children.push(currentChild);
populateTasksForChild(currentChild);

/* ======== END TEST DATA  ============================ */
<commit_msg>removing tasks from the taskCatalog when they're fully configured and added<commit_after>/**
 * Created with IntelliJ IDEA.
 * User: bbhagan
 * Date: 6/26/13
 * Time: 1:33 PM
 * To change this template use File | Settings | File Templates.
 */

//http://stackoverflow.com/questions/5937339/ipad-safari-make-keyboard-disappear
var hideKeyboard = function() {
   document.activeElement.blur();
   $("input").blur();
};

$(document).ready(function() {
   $('#tour').bind('resize', function(event) {
      $('#tour').css({'height': 768});
      $('#tour').css({'width': 1024});
      //alert('orientation change');
   });
   // Set so birthday can't be past today
   $("#getStartedFormChildBirthday").attr("max", dateToYMD(new Date()));

   $('#getStartedFormChildBirthday').on('click', function(e) {
      hideKeyboard();
      $('#getStartedFormChildBirthday').focus();
   });

   $("#getStartedForm").submit(function(e){
      transitionToStartTasks(e);
      $.mobile.navigate( "#startTasks" );
      return false;
   });

   $("#doneWithTasksButton").on("click", function(e){
      transitionToStartGoals(e);
   });

   $('#configureTasksRepeats').on('change', function(e) {
      swapConfigureTasksRepeats(e);
   })

   $('#configureRepeatPayment').on('change', function(e) {
      swapConfigureRepeatPayment(e);
   });
   $('#configureNonRepeatPayment').on('change', function(e) {
      swapConfigureNonRepeatPayment(e);
   });
   $("#configureTaskForm").submit( function(e) {
     $("#configureTaskForm .error").hide();
     addConfiguredTaskToChild(e);
     return false;
   });
});

var tykoonData = {
   parent: {
      children: []
   },
   currentChildIndex : 0
};
var currentChild;

var transitionToStartTasks = function(e) {

   // populate main data object
   var name = $('#getStartedFormChildFirstName').val();
   var birthdayString = $('#getStartedFormChildBirthday').val();
   // -1 on month, apparently 0-based for months
   var birthday = new Date(parseInt(birthdayString.substring(0,4)), parseInt(birthdayString.substring(5,7))-1, parseInt(birthdayString.substring(8)));
   var gender = $("input:radio[name='getStartedFormChildGender']:checked").val();
   var child = new Child(0, name, '', '', '', birthday, 0, gender);
   tykoonData.parent.children.push(child);

   currentChild = child;
   populateTasksForChild(child);
};

var configureTasks = function(e) {
   // FInd the task clicked on and collect it's data
   var taskltem = $(e.currentTarget),
      taskName = $(taskltem).find(".title").text(),
      taskId = $(taskltem).attr("data-taskId");

   // populate the popup disclosure and show it
   $('#configureTasks .taskTitle').html(taskName).attr("data-taskId",taskId);
   // set due date of today or later
   $("#configureTasksDueDate").attr("min", dateToYMD(new Date()));

   $("#configureTasks").popup().popup("open", {transition: "pop"} );

   // reset the form before opening
   $("#configureTaskRepeatsYes, #configureRepeatPaymentAllow, #configureNonRepeatPaymentMoney" ).prop( "checked", true ).checkboxradio( "refresh" );
   $("#configureTaskRepeatsNo, #configureRepeatPaymentResp, #configureNonRepeatPaymentResp, #configureTasksWeeklyOn input[type='checkbox']" ).prop( "checked", false ).checkboxradio( "refresh" );
   $("#configureTasksHowMuch, #configureTasksDueDate").val("");
   swapConfigureTasksRepeats();
};

function dateToYMD(date) {
    var d = date.getDate();
    var m = date.getMonth() + 1;
    var y = date.getFullYear();
    return '' + y + '-' + (m<=9 ? '0' + m : m) + '-' + (d <= 9 ? '0' + d : d);
}

var addConfiguredTaskToChild = function(e) {
  var taskTitle = $("#configureTasks .taskTitle").html(),
    taskId = $("#configureTasks .taskTitle").attr("data-taskId"),
    currentTask = new Task(taskId, taskTitle, [], '', '', '');  // new Task(id, name, repeatDays, payType, payAmt, dueDate);

  // If repeating task, collect repeatDays and paymentType
  var repeats = $("input:radio[name='configureTasksRepeats']:checked").val();
  if ( repeats == "1") {

    // add to 'repeatDays' array the days it repeats
    var weekDays = $("#configureTasksWeeklyOn input[type='checkbox']");
    for (i in weekDays) {
      var day = weekDays[i];
      if (day.hasOwnProperty('type') && day.checked) {
        currentTask.repeatDays.push($(day).val());
      }
    }
    // check for length of repeatDays
    if  (!currentTask.repeatDays.length) {
      $("#pickADay").show("fast");
      return false;
    }

    var paymentType = $("input:radio[name='configureRepeatPayment']:checked").val();
    currentTask.payType = paymentType;

  // Otherwise just collect payment type/amount and optional due date
  } else {
    var paymentType = $("input:radio[name='configureNonRepeatPayment']:checked").val();
    currentTask.payType = paymentType;
    if (paymentType == "money") {
      var moneyAmount = $("#configureTasksHowMuch").val();
      if (moneyAmount == "" || moneyAmount == "0") {
        $("#enterTaskMoney").show("fast");
        return false;
      }
      currentTask.payAmt = moneyAmount;
    }

    // due date
    var dueDateString = $('#configureTasksDueDate').val();
    if (dueDateString != "") {
      var dueDate = new Date(parseInt(dueDateString.substring(0,4)), parseInt(dueDateString.substring(5,7))-1, parseInt(dueDateString.substring(8)));
      currentTask.dueDate = dueDate;
    }
  }

  currentChild.tasks.push(currentTask);
  $("#configureTasks" ).popup( "close" );
  $(".taskItem[data-taskId = '" + taskId + "']").slideUp();
}

var populateTasksForChild = function(child) {
  //populate page with child data
  $(".childFirstName").html(child.name);
  $(".childAge").html(child.getAge());
  $(".childGender").html(child.getGenderNoun());

  //clean page and populate page with tasks from catalog
 $('#startTasks .taskCatalog .tasks').empty();
 var taskTemplate = $("#startTasks .taskCatalog .taskTemplate .taskItem")[0];
  for(var i in cannedTasks.tasks) {
    var task = cannedTasks.tasks[i];
    if ((task.gender == "b" || task.gender == child.gender) && (child.getAge() >= task.ageRange.min && child.getAge() <= task.ageRange.max)) {
      var taskItem = $(taskTemplate).clone();
      $(taskItem).attr("data-taskId", task.id);
      $(taskItem).find(".title").html(task.name);
      $(taskItem).find(".numKids span").html(task.numPeople);
      $('#startTasks .taskCatalog .tasks').append($(taskItem));
    }
  }

  // hook up the taps on taskItems to configure them
  $("#startTasks .taskCatalog .taskItem").on("click", function(e){
     configureTasks(e);
  });
};

var swapConfigureTasksRepeats = function(e) {
   if ($("input:radio[name='configureTasksRepeats']:checked").val() == 1) {
      $('#configureTasks .hideNonRepeat').hide();
      $('#configureTasks .hideRepeat').show();
   } else {
      $('#configureTasks .hideNonRepeat').show();
      $('#configureTasks .hideRepeat').hide();
   }
};

var swapConfigureRepeatPayment = function(e) {
   if ($("input:radio[name='configureRepeatPayment']:checked").val() == 'allowance') {
      $('#configureTasks .taskRepeatPaymentDetails .resp').hide();
      $('#configureTasks .taskRepeatPaymentDetails .allow').show();
   } else {
     $('#configureTasks .taskRepeatPaymentDetails .resp').show();
     $('#configureTasks .taskRepeatPaymentDetails .allow').hide();
   }
};
var swapConfigureNonRepeatPayment = function(e) {
   if ($("input:radio[name='configureNonRepeatPayment']:checked").val() == 'money') {
      $('#configureTasks .taskNonRepeatPaymentDetails .resp').hide();
      $('#configureTasks .taskNonRepeatPaymentDetails .money').show();
   } else {
     $('#configureTasks .taskNonRepeatPaymentDetails .resp').show();
     $('#configureTasks .taskNonRepeatPaymentDetails .money').hide();
   }
};

/* ADD GOALS section */

var transitionToStartGoals = function(e) {

  populateProductsForChild(currentChild);
  $(".addTaskContent, .startTasksFooter").fadeOut(200);

  // move the cover
  $(".cover").addClass("leftCover"); //.css("left","0");

  $(".addGoalContent, .startGoalsFooter").delay(400).fadeIn(200);
}

var populateProductsForChild = function(child) {

  //clean page and populate page with tasks from catalog
 $('#startTasks .productCatalog .goals').empty();
 var productTemplate = $("#startTasks .productCatalog .productTemplate .productItem")[0];
  for(var i in cannedProducts.products) {
    var product = cannedProducts.products[i];
    if ((product.gender == "b" || product.gender == child.gender) && (child.getAge() >= product.ageRange.min && child.getAge() <= product.ageRange.max)) {
      var productItem = $(productTemplate).clone();
      $(productItem).attr("data-productId", product.id);
      $(productItem).find(".title").html(product.name);
      $(productItem).find(".numKids span").html(product.numPeople);
      $(productItem).find(".thumbnail").attr({src: product.imgURL, alt: product.name});
      $('#startTasks .productCatalog .products').append($(productItem));
    }
  }

  // hook up the taps on productItems to configure them
  $("#startTasks .productCatalog .productItem").on("click", function(e){
     showProductDetails(e);
  });
};

var showProductDetails = function(e) {
  var productItem = $(e.currentTarget),
      productName = $(productItem).find(".title").text();
  alert("tapped on: " + productName);
}

/* ======== TEST DATA, comment me out to run for real ===========  */

var testBdayString = '2006-10-29';
var testBirthday = new Date(parseInt(testBdayString.substring(0,4)), parseInt(testBdayString.substring(5,7))-1, parseInt(testBdayString.substring(8)));
currentChild = new Child(0, 'Kaiya', '', '', '', testBirthday, 0, 'f');
tykoonData.parent.children.push(currentChild);
populateTasksForChild(currentChild);

/* ======== END TEST DATA  ============================ */
<|endoftext|>


<commit_before>/**
 * Created with IntelliJ IDEA.
 * User: bbhagan
 * Date: 6/26/13
 * Time: 1:33 PM
 * To change this template use File | Settings | File Templates.
 */

$(document).ready(function() {
   $("#getStartedFormSubmit").on("click", function(){

   });
});

var tykoonData = {

};
<commit_msg>pushing children<commit_after>/**
 * Created with IntelliJ IDEA.
 * User: bbhagan
 * Date: 6/26/13
 * Time: 1:33 PM
 * To change this template use File | Settings | File Templates.
 */

$(document).ready(function() {
   $("#getStartedFormSubmit").on("click", function(e){
      var name = $('#getStartedFormChildFirstName').val();
      var birthday = $('#getStartedFormChildBirthday').val();
      var child = new Child(0, name, '', '', birthday, 0);
      tykoonData.parent.children.push(child);
   });
});

var tykoonData = {
   parent: {
      children: []
   }
};
<|endoftext|>


<commit_before>var sfs;
var config = {};
var roomid = "MainLobby#_@LocalVoip#_@0655795e-9916-4cfc-be1e-81f544d1d7cb#_@public";
var file = new Int8Array(64000);
var startTime = 0;
var audioCtx = new AudioContext();

// This is a port directly from the USpeak C# source code
function MuLawDecode( mulaw )
{
	var BIAS = 0x84;
	mulaw = ~mulaw;
	var sign = mulaw & 0x80;
	var exponent = ( mulaw & 0x70 ) >> 4;
	var data = mulaw & 0x0F;
	data = data | 0x10;
	data = data << 1;
	data = data + 1;
	data = data << (exponent + 2);
	data = data - BIAS;
	if( sign == 0 )
		return data;
	else
		return -data;
}

function playPCMclip( buffer )
{
	var sampleRate = 8000;
	var audioBuffer = audioCtx.createBuffer(1, buffer.length, sampleRate);
	var source = audioCtx.createBufferSource();
	audioBuffer.getChannelData(0).set(buffer);
	source.buffer = audioBuffer;
	source.connect(audioCtx.destination);
	var delay = 0.1;
	if( startTime == 0 || audioCtx.currentTime > startTime )
	{
		document.getElementById("speaker").style.backgroundColor = "gray";
		startTime = audioCtx.currentTime + delay;
	}
	setTimeout(function() { document.getElementById("speaker").style.backgroundColor = "green"; }, delay*1000);
	source.start(startTime);
	startTime = startTime + audioBuffer.duration;
	setTimeout(function() { document.getElementById("speaker").style.backgroundColor = "gray"; }, (delay+audioBuffer.duration)*1000);
}

function playMuLawClip( data )
{
	var vcdata = new Uint8Array(data.length);
	for( i=0; i<data.length; i++ )
	{
		vcdata[i] = data[i];
	}
	var offset = 0;
	while( offset < vcdata.length )
	{
		var len = vcdata[offset];

		var frame = new Int16Array(len);
		for( i=0; i < frame.length; i++ )
		{
			frame[i] = MuLawDecode(vcdata[offset+i+6]);
		}
		offset = offset+i+6;
		var buffer = new Float32Array(frame.length);
		var divisor = 3267;
		for( i=0; i < frame.length; i++ )
		{
			buffer[i] = frame[i]/divisor;
		}
		playPCMclip(buffer);
	}
}

// SFS handler for connection event
function onConnection(evtParams)
{
	if (evtParams.success)
	{
		console.log("Connected to SmartFoxServer 2X!");
		sfs.send(new SFS2X.Requests.System.LoginRequest("","",config.zone));
	}
	else
		console.log("Connection failed. Is the server running at all?");
}

// SFS handler for connection lost event
function onConnectionLost( evt )
{
	alert("Connection Lost!");
}

// SFS handler for login event
function onLogin( evt )
{
	console.log("Logged In!");
	sfs.send( new SFS2X.Requests.System.JoinRoomRequest(roomid));
}

// SFS handler for login error event
function onLoginError( evt )
{
	alert("Login Error!");
}

// SFS handler for room join event
function onRoomJoin( evt )
{
	console.log("Room Joined!");
	document.getElementById("connect").innerHTML = "Joined Room: '"+roomid+"'";
}

// SFS handler for room join error event
function onRoomJoinError( evt )
{
	alert("Room Not Joined");
}

// SFS handler for Extension Response event
function onExtensionResponse( evt )
{
	setTimeout(function() { document.getElementById("speaker").style.backgroundColor = "green"; }, startTime);
	var requestType = evt.cmd;
	if( requestType == "VoipVCRequest" )
	{
		var params = evt.params;
		var userid = params["ui"];
		var data = params["VCData"];
		playMuLawClip(data);
	}
}

// initialization function for this code, used in onload() in the HTML
function connect( host, port, zone, voipRoom )
{
	roomid = voipRoom;
	// Create configuration object
	config.host = host;
	config.port = parseInt(port);
	config.useSSL = false;
	config.zone = zone;
	config.debug = false;

	// Create SmartFox client instance
	sfs = new SmartFox(config);

	// Register for events and assign callbacks
	sfs.addEventListener(SFS2X.SFSEvent.CONNECTION, onConnection, this);
	sfs.addEventListener(SFS2X.SFSEvent.CONNECTION_LOST, onConnectionLost, this);
	sfs.addEventListener(SFS2X.SFSEvent.LOGIN_ERROR, onLoginError, this);
	sfs.addEventListener(SFS2X.SFSEvent.LOGIN, onLogin, this);
//	sfs.addEventListener(SFS2X.SFSEvent.LOGOUT, onLogout, this);
	sfs.addEventListener(SFS2X.SFSEvent.ROOM_JOIN_ERROR, onRoomJoinError, this);
	sfs.addEventListener(SFS2X.SFSEvent.ROOM_JOIN, onRoomJoin, this);
	sfs.addEventListener(SFS2X.SFSEvent.EXTENSION_RESPONSE, onExtensionResponse, this);

	// connect to SFS
	sfs.connect(config.host, config.port );
}

function init()
{
	var host = document.getElementById("host").value;
	var port = document.getElementById("port").value;
	var zone = document.getElementById("zone").value;
	var room = document.getElementById("room").value;
	console.log(host, port, zone, room);
	connect(host, port, zone, room);
}

<commit_msg>Convert typed array to a normal array before you send it via smartfox API<commit_after>var sfs;
var config = {};
var roomid = "MainLobby#_@LocalVoip#_@0655795e-9916-4cfc-be1e-81f544d1d7cb#_@public";
var startTime = 0;
var sampleSize = 256;
var userid="1";

var audioCtx = new AudioContext();

navigator.getUserMedia = (
	navigator.getUserMedia ||
	navigator.webkitGetUserMedia ||
	navigator.mozGetUserMedia ||
	navigator.msGetUserMedia
);

// adapted from http://stackoverflow.com/questions/35234551/javascript-converting-from-int16-to-float32
function float32To16Bit(inputArray)
{
	var output = new Int16Array(inputArray.length);
	for (var i = 0; i < inputArray.length; i++)
	{
		var s = Math.max(-1, Math.min(1, inputArray[i]));
		output[i] = s < 0 ? s * 0x8000 : s * 0x7FFF;
	}
	return output;
}

// adapted from http://stackoverflow.com/questions/35234551/javascript-converting-from-int16-to-float32
function int16ToFloat32(inputArray)
{
	var output = new Float32Array(inputArray.length);
	for (var i = 0; i < inputArray.length; i++)
	{
		var int = inputArray[i];
		// If the high bit is on, then it is a negative number, and actually counts backwards.
		var float = (int >= 0x8000) ? -(0x10000 - int) / 0x8000 : int / 0x7FFF;
		output[i] = float;
	}
	return output;
}

// This is a port directly from the USpeak C# source code
function MuLawDecode( mulaw )
{
	var BIAS = 0x84;
	mulaw = ~mulaw;
	var sign = mulaw & 0x80;
	var exponent = ( mulaw & 0x70 ) >> 4;
	var data = mulaw & 0x0F;
	data = data | 0x10;
	data = data << 1;
	data = data + 1;
	data = data << (exponent + 2);
	data = data - BIAS;
	if( sign == 0 )
		return data;
	else
		return -data;
}

function MuLawEncode( /* int32 */ pcm )
{
	var BIAS = 0x84;
	var MAX = 32635;

	var sign = ( pcm & 0x8000 ) >> 8;
	if( sign != 0 )
		pcm = -pcm;
	if( pcm > MAX )
		pcm = MAX;
	pcm += BIAS;
	var exponent = 7;
	for( expMask = 0x4000; ( pcm & expMask ) == 0; exponent--, expMask >>= 1 )
	{
	}
	var mantissa = ( pcm >> ( exponent + 3 ) ) & 0x0f;
	var mulaw = ( sign | exponent << 4 | mantissa );
	return ~mulaw;
}

function playPCMclip( buffer )
{
	var sampleRate = 8000;
	var audioBuffer = audioCtx.createBuffer(1, buffer.length, sampleRate);
	var source = audioCtx.createBufferSource();
	audioBuffer.getChannelData(0).set(buffer);
	source.buffer = audioBuffer;
	source.connect(audioCtx.destination);
	var delay = 0.1;
	if( startTime == 0 || audioCtx.currentTime > startTime )
	{
		document.getElementById("speaker").style.backgroundColor = "gray";
		startTime = audioCtx.currentTime + delay;
	}
	setTimeout(function() { document.getElementById("speaker").style.backgroundColor = "green"; }, delay*1000);
	source.start(startTime);
	startTime = startTime + audioBuffer.duration;
	setTimeout(function() { document.getElementById("speaker").style.backgroundColor = "gray"; }, (delay+audioBuffer.duration)*1000);
}

function playMuLawClip( data )
{
	var vcdata = new Uint8Array(data.length);
	for( i=0; i<data.length; i++ )
	{
		vcdata[i] = data[i];
	}
	var offset = 0;
	while( offset < vcdata.length )
	{
		var len = vcdata[offset];

		var frame = new Int16Array(len);
		for( i=0; i < frame.length; i++ )
		{
			frame[i] = MuLawDecode(vcdata[offset+i+6]);
		}
		offset = offset+i+6;
		var buffer = new Float32Array(frame.length);
		var divisor = 3267;
		for( i=0; i < frame.length; i++ )
		{
			buffer[i] = frame[i]/divisor;
		}
		playPCMclip(buffer);
	}
}

// SFS handler for connection event
function onConnection(evtParams)
{
	if (evtParams.success)
	{
		console.log("Connected to SmartFoxServer 2X!");
		sfs.send(new SFS2X.Requests.System.LoginRequest("","",config.zone));
	}
	else
		console.log("Connection failed. Is the server running at all?");
}

// SFS handler for connection lost event
function onConnectionLost( evt )
{
	alert("Connection Lost!");
}

// SFS handler for login event
function onLogin( evt )
{
	console.log("Logged In!");
	sfs.send( new SFS2X.Requests.System.JoinRoomRequest(roomid));
}

// SFS handler for login error event
function onLoginError( evt )
{
	alert("Login Error!");
}

// SFS handler for room join event
function onRoomJoin( evt )
{
	console.log("Room Joined!");
	document.getElementById("connect").innerHTML = "Joined Room: '"+roomid+"'";
}

// SFS handler for room join error event
function onRoomJoinError( evt )
{
	alert("Room Not Joined");
}

// SFS handler for Extension Response event
function onExtensionResponse( evt )
{
	setTimeout(function() { document.getElementById("speaker").style.backgroundColor = "green"; }, startTime);
	var requestType = evt.cmd;
	if( requestType == "VoipVCRequest" )
	{
		var params = evt.params;
		if( true ) // params["ui"] != userid )
		{
			var data = params["VCData"];
			console.log(data);
			playMuLawClip(data);
		}
	}
}

// initialization function for this code, used in onload() in the HTML
function connect( host, port, zone, voipRoom )
{
	roomid = voipRoom;
	// Create configuration object
	config.host = host;
	config.port = parseInt(port);
	config.useSSL = false;
	config.zone = zone;
	config.debug = false;

	// Create SmartFox client instance
	sfs = new SmartFox(config);

	// Register for events and assign callbacks
	sfs.addEventListener(SFS2X.SFSEvent.CONNECTION, onConnection, this);
	sfs.addEventListener(SFS2X.SFSEvent.CONNECTION_LOST, onConnectionLost, this);
	sfs.addEventListener(SFS2X.SFSEvent.LOGIN_ERROR, onLoginError, this);
	sfs.addEventListener(SFS2X.SFSEvent.LOGIN, onLogin, this);
//	sfs.addEventListener(SFS2X.SFSEvent.LOGOUT, onLogout, this);
	sfs.addEventListener(SFS2X.SFSEvent.ROOM_JOIN_ERROR, onRoomJoinError, this);
	sfs.addEventListener(SFS2X.SFSEvent.ROOM_JOIN, onRoomJoin, this);
	sfs.addEventListener(SFS2X.SFSEvent.EXTENSION_RESPONSE, onExtensionResponse, this);

	// connect to SFS
	sfs.connect(config.host, config.port );
}

function sendAudio( floats )
{
	var data = new Uint8Array(floats.length+6);
	data[0] = sampleSize-1;
	data[1] = 0;
	data[2] = 0;
	data[3] = 0;
	data[4] = 0;
	data[5] = 0;
	for( i=0; i<floats.length; i++ )
	{
		data[i+6] = MuLawEncode(Math.round(floats[i]*3267));
	}
	var params = {};
	params["ui"] = userid;
	params["VCData"] = Array.prototype.slice.call(data);
	sfs.send(new SFS2X.Requests.System.ExtensionRequest("VoipVCRequest", params));
}

function setupAudioNode( stream )
{
	sourceNode = audioContext.createMediaStreamSource(stream);
	javascriptNode = audioContext.createScriptProcessor(sampleSize, 1, 1);
	javascriptNode.onaudioprocess = function(e)
	{
		sendAudio( new Float32Array(e.inputBuffer.getChannelData(0)));
	}
	sourceNode.connect(javascriptNode);
	javascriptNode.connect(audioContext.destination);
}

function onAudioError(e)
{
	console.log(e);
	alert(e);
}

function initializeMic()
{
	try
	{
		audioContext = new AudioContext();
	}
	catch(e)
	{
		alert('Web Audio API is not supported in this browser');
	}

	try
	{
		navigator.getUserMedia(
			{ video: false, audio: true},
			setupAudioNode,
			onAudioError
		);
	}
	catch (e)
	{
		alert('webkitGetUserMedia threw exception :' + e);
	}
}

function init()
{
	var host = document.getElementById("host").value;
	var port = document.getElementById("port").value;
	var zone = document.getElementById("zone").value;
	var room = document.getElementById("room").value;
	console.log(host, port, zone, room);
	connect(host, port, zone, room);

	initializeMic();
}

<|endoftext|>


<commit_before>/**
 * @author Daniel Desira
 * @version 0.4.2
 */

(function () {

'use strict';

var currentImage, imageDescription, delay, photos, touchStartX,
  galleryActivated = true,
  photoIndex = 0,
  Switcher = (function () {
    var interval,
      Switcher = {};

    Switcher.next = function () {
      photoIndex = (++photoIndex) % photos.length;
      changePhoto();
    };

    Switcher.prev = function () {
      photoIndex = ((--photoIndex) === -1 ? photos.length - 1 : photoIndex);
      changePhoto();
    };

    Switcher.goto = function () {
      setTimeout(changePhoto, 1000);
    };

    Switcher.slideshow = function () {
      interval = setInterval(Switcher.next, delay * 4);
    };

    Switcher.stopSlideshow = function () {
      clearInterval(interval);
    };

    function changePhoto () {
      currentImage.classList.remove('view');
      setTimeout(function() {
        currentImage.src = photos[ photoIndex ].src;
        currentImage.onload = function() {
          currentImage.classList.add('view');
          if (imageDescription) {
            imageDescription.textContent = photos[ photoSwitcher.getPhotoIndex() ].description;
          }
        };

        //Chrome appears to not support <img> alt text.
        currentImage.onerror = function() {
          imageDescription.textContent = 'Unable to fetch image!';
        };
      }, delay);
    }

    return Switcher;
  })();

function _activateGallery(gallery) {
  document.documentElement.addEventListener('click', function (event) {
    if (event.target === gallery) {
      galleryActivated = true;
    } else {
      galleryActivated = false;
    }
  });
}

function handleKeyDown(event) {
  if (galleryActivated) {
    if (event.keyCode === 37) {
      Switcher.prev();
    } else if (event.keyCode === 39) {
      Switcher.next();
    }
  }
}

function handleTouchStart(event) {
  touchStartX = event.touches[0].pageX;
}

function handleTouchEnd(event) {
  if (event.touches[0].pageX > touchStartX) {
    Switcher.prev();
  } else if (event.touches[0].pageX < touchStartX) {
    Switcher.next();
  }
  event.preventDefault();
}

function registerHandler(property, callback) {
  if (typeof property === 'function') {
    property(callback);
  } else if (property) {
    throw 'Property not a function!';
  }
}

window.awesomeGallery = function (options) {
  var $ = document.querySelector;

  currentImage = $(options.imageSelector);
  if (options.imagesSelector) {
    photos = document.querySelectorAll(options.imagesSelector);
    for (photoIndex = 0; photoIndex < photos.length; photoIndex++) {
      (function (i) {
        photos[photoIndex].addEventListener('click', function () {
          photoIndex = i;
          Switcher.goto();
        });
      })(photoIndex);
    }
    photoIndex = 0;
  } else {
    photos = options.photos;
  }
  currentImage.src = photos[0].src;
  currentImage.classList.add('view');

  if (options.descriptionSelector) {
    imageDescription = $(options.descriptionSelector);
  }

  delay = options.delay ?
    options.delay :
    (function () {
      var transitionDuration = getComputedStyle(currentImage).transitionDuration;
      return parseFloat(transitionDuration.substring(0, transitionDuration.length - 1)) * 1000;
    })();

  currentImage.addEventListener('click', Switcher.next);
  document.addEventListener('keydown' , handleKeyDown);
  currentImage.addEventListener('touchstart', handleTouchStart);
  currentImage.addEventListener('touchend', handleTouchEnd);
  registerHandler(options.slideshow, Switcher.slideshow);
  registerHandler(options.stopSlideshow, Switcher.stopSlideshow);
  registerHandler(options.next, Switcher.next);
  registerHandler(options.prev, Switcher.prev);

  if (options.gallerySelector) {
    _activateGallery($(options.gallerySelector));
    galleryActivated = false;
  }

  if (options.quickSetup) {
    Switcher.slideshow();
  }
};

})();
<commit_msg>alt attribute value now displayed for users of Chrome, Opera and Chromium only<commit_after>/**
 * @author Daniel Desira
 * @version 0.4.2
 */

(function () {

'use strict';

var currentImage, imageDescription, delay, photos, touchStartX,
  galleryActivated = true,
  photoIndex = 0,
  Switcher = (function () {
    var interval,
      Switcher = {};

    Switcher.next = function () {
      photoIndex = (++photoIndex) % photos.length;
      changePhoto();
    };

    Switcher.prev = function () {
      photoIndex = ((--photoIndex) === -1 ? photos.length - 1 : photoIndex);
      changePhoto();
    };

    Switcher.goto = function () {
      setTimeout(changePhoto, 1000);
    };

    Switcher.slideshow = function () {
      interval = setInterval(Switcher.next, delay * 4);
    };

    Switcher.stopSlideshow = function () {
      clearInterval(interval);
    };

    function changePhoto () {
      currentImage.classList.remove('view');
      setTimeout(function() {
        currentImage.src = photos[ photoIndex ].src;
        currentImage.onload = function() {
          currentImage.classList.add('view');
          if (imageDescription) {
            imageDescription.textContent = photos[ photoSwitcher.getPhotoIndex() ].description;
          }
        };

        //Chrome appears to not support <img> alt text.
        currentImage.onerror = function() {
          if (/Chrome|Opera/.test( navigator.userAgent )) {
            imageDescription.textContent = 'Unable to fetch image!';
          }
        };
      }, delay);
    }

    return Switcher;
  })();

function _activateGallery(gallery) {
  document.documentElement.addEventListener('click', function (event) {
    if (event.target === gallery) {
      galleryActivated = true;
    } else {
      galleryActivated = false;
    }
  });
}

function handleKeyDown(event) {
  if (galleryActivated) {
    if (event.keyCode === 37) {
      Switcher.prev();
    } else if (event.keyCode === 39) {
      Switcher.next();
    }
  }
}

function handleTouchStart(event) {
  touchStartX = event.touches[0].pageX;
}

function handleTouchEnd(event) {
  if (event.touches[0].pageX > touchStartX) {
    Switcher.prev();
  } else if (event.touches[0].pageX < touchStartX) {
    Switcher.next();
  }
  event.preventDefault();
}

function registerHandler(property, callback) {
  if (typeof property === 'function') {
    property(callback);
  } else if (property) {
    throw 'Property not a function!';
  }
}

window.awesomeGallery = function (options) {
  var $ = document.querySelector;

  currentImage = $(options.imageSelector);
  if (options.imagesSelector) {
    photos = document.querySelectorAll(options.imagesSelector);
    for (photoIndex = 0; photoIndex < photos.length; photoIndex++) {
      (function (i) {
        photos[photoIndex].addEventListener('click', function () {
          photoIndex = i;
          Switcher.goto();
        });
      })(photoIndex);
    }
    photoIndex = 0;
  } else {
    photos = options.photos;
  }
  currentImage.src = photos[0].src;
  currentImage.classList.add('view');

  if (options.descriptionSelector) {
    imageDescription = $(options.descriptionSelector);
  }

  delay = options.delay ?
    options.delay :
    (function () {
      var transitionDuration = getComputedStyle(currentImage).transitionDuration;
      return parseFloat(transitionDuration.substring(0, transitionDuration.length - 1)) * 1000;
    })();

  currentImage.addEventListener('click', Switcher.next);
  document.addEventListener('keydown' , handleKeyDown);
  currentImage.addEventListener('touchstart', handleTouchStart);
  currentImage.addEventListener('touchend', handleTouchEnd);
  registerHandler(options.slideshow, Switcher.slideshow);
  registerHandler(options.stopSlideshow, Switcher.stopSlideshow);
  registerHandler(options.next, Switcher.next);
  registerHandler(options.prev, Switcher.prev);

  if (options.gallerySelector) {
    _activateGallery($(options.gallerySelector));
    galleryActivated = false;
  }

  if (options.quickSetup) {
    Switcher.slideshow();
  }
};

})();
<|endoftext|>


<commit_before>/**
* @author Daniel Desira
* @version 0.5
*/

(function () {

'use strict';

var SELECTION_CLASS = 'selected';

var currentImage, photoIndex, imageDescription, delay, photos, touchStartX, prev, next, startSlideshow, stopSlideshow,

  Switcher = (function () {
    var interval,
      Switcher = {};

    Switcher.next = function () {
      flipPhoto(function (index) {
        return (++index) % photos.length;
      });
    };

    Switcher.prev = function () {
      flipPhoto(function (index) {
        return (--index) === -1 ? photos.length - 1 : index;
      });
    };

    Switcher.goto = function ( index ) {
      photoIndex = index;
      setTimeout( changePhoto, delay );
    };

    Switcher.slideshow = function () {
      interval = setInterval( Switcher.next, delay * 4 );
    };

    Switcher.stopSlideshow = function () {
      clearInterval( interval );
    };

    function changePhoto() {
      currentImage.classList.remove( 'view' );
      setTimeout(function() {
        currentImage.src = photos[ photoIndex ].src;
        currentImage.onload = function () {
          currentImage.classList.add( 'view' );
          if (imageDescription) {
            imageDescription.textContent = photos[ photoSwitcher.getPhotoIndex() ].alt;
          }
        };

        //Work-around: WebKit and Blink do not display <img> alt text.
        currentImage.onerror = function () {
          imageDescription.textContent = (/WebKit/.test( navigator.userAgent ) ?
                imageDescription.textContent : '') + ' Unable to fetch image!';
        };
      }, delay );
    }

    function flipPhoto( callback ) {
      var index = photoIndex;
      index = callback( index );
      selectImage( photos[index] );
      photoIndex = index;
      changePhoto();
    }

    return Switcher;
  })(),

  exports = {
    Switcher: Switcher,
    dom: {
      prev: prev,
      next: next,
      slideshowStart: startSlideshow,
      slideshowEnd: stopSlideshow,
      image: currentImage,
      description: imageDescription,
      images: !Array.isArray( photos ) ? photos : null,
      galleryActivated: true
    }
  };

function _activateGallery( gallery ) {
  document.documentElement.addEventListener( 'click', function ( event ) {
    exports.dom.galleryActivated = (event.target === gallery);
  });
}

function handleKeyDown( event ) {
  if (exports.dom.galleryActivated) {
    if (event.keyCode === 37) {
      Switcher.prev();
    } else if (event.keyCode === 39) {
      Switcher.next();
    }
  }
}

function handleTouchStart( event ) {
  touchStartX = event.touches[0].pageX;
}

function handleTouchEnd( event ) {
  if (event.touches[0].pageX > touchStartX) {
    Switcher.prev();
  } else if (event.touches[0].pageX < touchStartX) {
    Switcher.next();
  }
  event.preventDefault();
}

function registerButtonClick( action, selector ) {
  var element = (selector ? $( selector ) : document.createElement( 'a' ));
  element.addEventListener( 'click', function () {
    Switcher[action];
  });
  return element;
}

function $( selector ) {
  return document.querySelector( selector );
}

function selectImage( image ) {
  if (image.classList) {
    image.classList.add( SELECTION_CLASS );
    image !== photos[photoIndex] ? photos[photoIndex].classList.remove( SELECTION_CLASS ) : undefined;
  }
}

window.AG = {};

AG.init = function ( options ) {
  currentImage = $( options.$image );
  if (options.$$images) {
    photos = document.querySelectorAll( options.$$images );
    for (photoIndex = 0; photoIndex < photos.length; photoIndex++) {
      (function (i) {
        photos[photoIndex].addEventListener( 'click', function () {
          selectImage( photos[i] );
          Switcher.goto( i );
        });
      })( photoIndex );
    }
    photoIndex = 0;
  } else {
    photos = options.photos;
  }

  selectImage( photos[0] );
  currentImage.src = photos[0].src;
  currentImage.classList.add( 'view' );

  if (options.$description) {
    imageDescription = $( options.$description );
  }

  delay = options.delay ?
    options.delay :
    (function () {
      var transitionDuration = getComputedStyle( currentImage ).transitionDuration;
      return parseFloat( transitionDuration.substring( 0, transitionDuration.length - 1 ) ) * 1000;
    })();

  currentImage.addEventListener( 'click', Switcher.next );
  document.addEventListener( 'keydown', handleKeyDown );
  currentImage.addEventListener( 'touchstart', handleTouchStart );
  currentImage.addEventListener( 'touchend', handleTouchEnd );
  prev = registerButtonClick( 'prev', options.$prev );
  next = registerButtonClick( 'next', options.$next );
  startSlideshow = registerButtonClick( 'slideshow', options.$slideshow );
  stopSlideshow = registerButtonClick( 'stopslideshow', options.$stopSlideshow );

  if (options.$gallery) {
    _activateGallery( $( options.$gallery ) );
    exports.dom.galleryActivated = false;
  }

  if (options.quickSetup) {
    Switcher.slideshow();
    prev = registerButtonClick( 'prev' );
    next = registerButtonClick( 'next' );
    startSlideshow = registerButtonClick( 'slideshow' );
    stopSlideshow = registerButtonClick( 'stopslideshow' );
  }

  return AG;
};

AG.extend = function ( callback, methodName ) {
  methodName ? (AG[methodName] = function () {
    callback( exports );
  }) : callback( exports );

  return AG;
};

})();
<commit_msg>Calling Switcher.goto() now sets SELECTION_CLASS as required<commit_after>/**
* @author Daniel Desira
* @version 0.5
*/

(function () {

'use strict';

var SELECTION_CLASS = 'selected',
  TRANSITION_CLASS = 'view';

var currentImage, photoIndex, imageDescription, delay, photos, touchStartX, prev, next, startSlideshow, stopSlideshow,

  Switcher = (function () {
    var interval,
      Switcher = {};

    Switcher.next = function () {
      flipPhoto(function (index) {
        return (++index) % photos.length;
      });
    };

    Switcher.prev = function () {
      flipPhoto(function (index) {
        return (--index) === -1 ? photos.length - 1 : index;
      });
    };

    Switcher.goto = function ( index ) {
      photoIndex = index;
      setTimeout( changePhoto, delay );
    };

    Switcher.slideshow = function () {
      interval = setInterval( Switcher.next, delay * 4 );
    };

    Switcher.stopSlideshow = function () {
      clearInterval( interval );
    };

    function changePhoto() {
      currentImage.classList.remove( TRANSITION_CLASS );
      setTimeout(function() {
        currentImage.src = photos[ photoIndex ].src;
        currentImage.onload = function () {
          currentImage.classList.add( TRANSITION_CLASS );
          if (imageDescription) {
            imageDescription.textContent = photos[ photoSwitcher.getPhotoIndex() ].alt;
          }
        };

        //Work-around: WebKit and Blink do not display <img> alt text.
        currentImage.onerror = function () {
          imageDescription.textContent = (/WebKit/.test( navigator.userAgent ) ?
                imageDescription.textContent : '') + ' Unable to fetch image!';
        };
      }, delay );
    }

    function flipPhoto( callback ) {
      var index = photoIndex;
      index = callback( index );
      selectImage( photos[index] );
      photoIndex = index;
      changePhoto();
    }

    return Switcher;
  })(),

  exports = {
    Switcher: Switcher,
    dom: {
      prev: prev,
      next: next,
      slideshowStart: startSlideshow,
      slideshowEnd: stopSlideshow,
      image: currentImage,
      description: imageDescription,
      images: !Array.isArray( photos ) ? photos : null,
      galleryActivated: true
    }
  };

function _activateGallery( gallery ) {
  document.documentElement.addEventListener( 'click', function ( event ) {
    exports.dom.galleryActivated = (event.target === gallery);
  });
}

function handleKeyDown( event ) {
  if (exports.dom.galleryActivated) {
    if (event.keyCode === 37) {
      Switcher.prev();
    } else if (event.keyCode === 39) {
      Switcher.next();
    }
  }
}

function handleTouchStart( event ) {
  touchStartX = event.touches[0].pageX;
}

function handleTouchEnd( event ) {
  if (event.touches[0].pageX > touchStartX) {
    Switcher.prev();
  } else if (event.touches[0].pageX < touchStartX) {
    Switcher.next();
  }
  event.preventDefault();
}

function registerButtonClick( action, selector ) {
  var element = (selector ? $( selector ) : document.createElement( 'a' ));
  element.addEventListener( 'click', function () {
    Switcher[action];
  });
  return element;
}

function $( selector ) {
  return document.querySelector( selector );
}

function selectImage( image ) {
  if (image.classList) {
    image.classList.add( SELECTION_CLASS );
    image !== photos[photoIndex] ? photos[photoIndex].classList.remove( SELECTION_CLASS ) : undefined;
  }
}

window.AG = {};

AG.init = function ( options ) {
  currentImage = $( options.$image );
  if (options.$$images) {
    photos = document.querySelectorAll( options.$$images );
    for (photoIndex = 0; photoIndex < photos.length; photoIndex++) {
      (function (i) {
        photos[photoIndex].addEventListener( 'click', function () {
          selectImage( photos[i] );
          Switcher.goto( i );
        });
      })( photoIndex );
    }
    photoIndex = 0;
  } else {
    photos = options.photos;
  }

  selectImage( photos[0] );
  currentImage.src = photos[0].src;
  currentImage.classList.add( TRANSITION_CLASS );

  if (options.$description) {
    imageDescription = $( options.$description );
  }

  delay = options.delay ?
    options.delay :
    (function () {
      var transitionDuration = getComputedStyle( currentImage ).transitionDuration;
      return parseFloat( transitionDuration.substring( 0, transitionDuration.length - 1 ) ) * 1000;
    })();

  currentImage.addEventListener( 'click', Switcher.next );
  document.addEventListener( 'keydown', handleKeyDown );
  currentImage.addEventListener( 'touchstart', handleTouchStart );
  currentImage.addEventListener( 'touchend', handleTouchEnd );
  prev = registerButtonClick( 'prev', options.$prev );
  next = registerButtonClick( 'next', options.$next );
  startSlideshow = registerButtonClick( 'slideshow', options.$slideshow );
  stopSlideshow = registerButtonClick( 'stopslideshow', options.$stopSlideshow );

  if (options.$gallery) {
    _activateGallery( $( options.$gallery ) );
    exports.dom.galleryActivated = false;
  }

  if (options.quickSetup) {
    Switcher.slideshow();
    prev = registerButtonClick( 'prev' );
    next = registerButtonClick( 'next' );
    startSlideshow = registerButtonClick( 'slideshow' );
    stopSlideshow = registerButtonClick( 'stopslideshow' );
  }

  return AG;
};

AG.extend = function ( callback, methodName ) {
  methodName ? (AG[methodName] = function () {
    callback( exports );
  }) : callback( exports );

  return AG;
};

})();
<|endoftext|>


<commit_before>function draw(){
    if(settings['clear']){
        buffer.clearRect(
          0,
          0,
          width,
          height
        );
    }

    buffer.lineWidth = settings['line-width'];
    for(var object in objects){
        // Draw rectangles if not in lines mode.
        if(mode != 1){
            buffer.fillStyle = 'rgb('
              + objects[object][2] + ', '
              + objects[object][3] + ', '
              + objects[object][4] + ')';

            buffer.fillRect(
              objects[object][0],
              objects[object][1],
              objects[object][0] - mouse_x,
              objects[object][1] - mouse_y
            );
        }

        // Draw lines if not in rectangles mode.
        if(mode != 2){
            buffer.beginPath();
            buffer.moveTo(
              objects[object][0],
              objects[object][1]
            );
            buffer.lineTo(
              mouse_x,
              mouse_y
            );
            buffer.closePath();
            buffer.strokeStyle = 'rgb('
              + objects[object][2] + ', '
              + objects[object][3] + ', '
              + objects[object][4] + ')';
            buffer.stroke();
        }
    }

    if(settings['clear']){
        canvas.clearRect(
          0,
          0,
          width,
          height
        );
    }
    canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );
}

function randomize_objects(){
    objects.length = 0;

    var loop_counter = settings['number-of-objects'] - 1;
    do{
        // Create randomized object.
        objects.push([
          Math.floor(Math.random() * width),// X
          Math.floor(Math.random() * height),// Y
          Math.floor(Math.random() * 255),// (Red)GB
          Math.floor(Math.random() * 255),// R(Green)B
          Math.floor(Math.random() * 255),// RG(Blue)
        ]);
    }while(loop_counter--);

    draw();
}

function reset(){
    if(!confirm('Reset settings?')){
        return;
    }

    document.getElementById('clear').checked = true;
    document.getElementById('line-width').value = 1;
    document.getElementById('mouse-lock').checked = true;
    document.getElementById('number-of-objects').value = 100;
    document.getElementById('randomize-key').value = 'R';

    save();
}

function resize(){
    if(mode <= 0){
        return;
    }

    height = window.innerHeight;
    document.getElementById('buffer').height = height;
    document.getElementById('canvas').height = height;
    y = height / 2;
    mouse_y = y;

    width = window.innerWidth;
    document.getElementById('buffer').width = width;
    document.getElementById('canvas').width = width;
    x = width / 2;
    mouse_x = x;

    randomize_objects();
}

// Save settings into window.localStorage if they differ from default.
function save(){
    if(document.getElementById('clear').checked){
        window.localStorage.removeItem('Warped.htm-clear');
        settings['clear'] = true;

    }else{
        settings['clear'] = false;
        window.localStorage.setItem(
          'Warped.htm-clear',
          1
        );
    }

    if(isNaN(document.getElementById('line-width').value)
      || document.getElementById('line-width').value < 2){
        window.localStorage.removeItem('Warped.htm-line-width');
        settings['line-width'] = 1;

    }else{
        settings['line-width'] = parseInt(document.getElementById('line-width').value);
        window.localStorage.setItem(
          'Warped.htm-line-width',
          settings['line-width']
        );
    }

    if(document.getElementById('randomize-key').value === 'R'){
        window.localStorage.removeItem('Warped.htm-randomize-key');
        settings['randomize-key'] = 'R';

    }else{
        settings['randomize-key'] = document.getElementById('randomize-key').value;
        window.localStorage.setItem(
          'Warped.htm-randomize-key',
          settings['randomize-key']
        );
    }

    if(document.getElementById('mouse-lock').checked){
        window.localStorage.removeItem('Warped.htm-mouse-lock');
        settings['mouse-lock'] = true;

    }else{
        settings['mouse-lock'] = false;
        window.localStorage.setItem(
          'Warped.htm-mouse-lock',
          1
        );
    }

    if(document.getElementById('number-of-objects').value == 100
      || isNaN(document.getElementById('number-of-objects').value)
      || document.getElementById('number-of-objects').value < 1){
        window.localStorage.removeItem('Warped.htm-number-of-objects');
        settings['number-of-objects'] = 100;

    }else{
        settings['number-of-objects'] = parseInt(document.getElementById('number-of-objects').value);
        window.localStorage.setItem(
          'Warped.htm-number-of-objects',
          settings['number-of-objects']
        );
    }
}

function setmode(newmode){
    mode = newmode;

    // Visualization mode.
    if(mode > 0){
        save();

        document.getElementById('page').innerHTML = '<canvas id=canvas></canvas><canvas id=buffer style=display:none></canvas>';

        buffer = document.getElementById('buffer').getContext('2d');
        canvas = document.getElementById('canvas').getContext('2d');

        resize();

    // Main menu mode.
    }else{
        buffer = 0;
        canvas = 0;

        document.getElementById('page').innerHTML = '

Both
Lines
Rectangles

<input disabled style=border:0 value=ESC>Main Menu
<input id=randomize-key maxlength=1 value='
          + settings['randomize-key'] + '>Randomize

<input '
          + (settings['clear'] ? 'checked ' : '') + 'id=clear type=checkbox>Clear
<input id=line-width value='
          + settings['line-width'] + '>Line Width
<input '
          + (settings['mouse-lock'] ? 'checked ' : '') + 'id=mouse-lock type=checkbox>Mouse Lock
<input id=number-of-objects value='
          + settings['number-of-objects'] + '>Objects
Reset Settings

';
    }
}

var buffer = 0;
var canvas = 0;
var height = 0;
var objects = [];
var mode = 0;
var mouse_x = 0;
var mouse_y = 0;
var settings = {
  'clear': window.localStorage.getItem('Warped.htm-clear') === null,
  'line-width' : window.localStorage.getItem('Warped.htm-line-width') === null
    ? 1
    : parseInt(window.localStorage.getItem('Warped.htm-line-width')),
  'randomize-key': window.localStorage.getItem('Warped.htm-randomize-key') === null
    ? 'R'
    : window.localStorage.getItem('Warped.htm-randomize-key'),
  'mouse-lock': window.localStorage.getItem('Warped.htm-mouse-lock') === null,
  'number-of-objects': window.localStorage.getItem('Warped.htm-number-of-objects') === null
    ? 100
    : parseInt(window.localStorage.getItem('Warped.htm-number-of-objects')),
};
var x = 0;
var width = 0;
var y = 0;

resize();
setmode(0);

window.onkeydown = function(e){
    if(mode <= 0){
        return;
    }

    var key = e.keyCode || e.which;

    // settings['randomize-key']: randomize current objects.
    if(String.fromCharCode(key) === settings['randomize-key']){
        randomize_objects();

    // ESC: return to the main menu.
    }else if(key === 27){
        setmode(0);
    }
};

window.onmousedown =
  window.ontouchstart = function(e){
    if(mode <= 0){
        return;
    }

    mouse_x = e.pageX;
    mouse_y = e.pageY;

    draw();
};

window.onmousemove = function(e){
    if(mode <= 0
      || !settings['mouse-lock']){
        return;
    }

    mouse_x = e.pageX;
    mouse_y = e.pageY;

    draw();
};

window.onresize = resize;
<commit_msg>added window prefix<commit_after>function draw(){
    if(settings['clear']){
        buffer.clearRect(
          0,
          0,
          width,
          height
        );
    }

    buffer.lineWidth = settings['line-width'];
    for(var object in objects){
        // Draw rectangles if not in lines mode.
        if(mode != 1){
            buffer.fillStyle = 'rgb('
              + objects[object][2] + ', '
              + objects[object][3] + ', '
              + objects[object][4] + ')';

            buffer.fillRect(
              objects[object][0],
              objects[object][1],
              objects[object][0] - mouse_x,
              objects[object][1] - mouse_y
            );
        }

        // Draw lines if not in rectangles mode.
        if(mode != 2){
            buffer.beginPath();
            buffer.moveTo(
              objects[object][0],
              objects[object][1]
            );
            buffer.lineTo(
              mouse_x,
              mouse_y
            );
            buffer.closePath();
            buffer.strokeStyle = 'rgb('
              + objects[object][2] + ', '
              + objects[object][3] + ', '
              + objects[object][4] + ')';
            buffer.stroke();
        }
    }

    if(settings['clear']){
        canvas.clearRect(
          0,
          0,
          width,
          height
        );
    }
    canvas.drawImage(
      document.getElementById('buffer'),
      0,
      0
    );
}

function randomize_objects(){
    objects.length = 0;

    var loop_counter = settings['number-of-objects'] - 1;
    do{
        // Create randomized object.
        objects.push([
          Math.floor(Math.random() * width),// X
          Math.floor(Math.random() * height),// Y
          Math.floor(Math.random() * 255),// (Red)GB
          Math.floor(Math.random() * 255),// R(Green)B
          Math.floor(Math.random() * 255),// RG(Blue)
        ]);
    }while(loop_counter--);

    draw();
}

function reset(){
    if(!window.confirm('Reset settings?')){
        return;
    }

    document.getElementById('clear').checked = true;
    document.getElementById('line-width').value = 1;
    document.getElementById('mouse-lock').checked = true;
    document.getElementById('number-of-objects').value = 100;
    document.getElementById('randomize-key').value = 'R';

    save();
}

function resize(){
    if(mode <= 0){
        return;
    }

    height = window.innerHeight;
    document.getElementById('buffer').height = height;
    document.getElementById('canvas').height = height;
    y = height / 2;
    mouse_y = y;

    width = window.innerWidth;
    document.getElementById('buffer').width = width;
    document.getElementById('canvas').width = width;
    x = width / 2;
    mouse_x = x;

    randomize_objects();
}

// Save settings into window.localStorage if they differ from default.
function save(){
    if(document.getElementById('clear').checked){
        window.localStorage.removeItem('Warped.htm-clear');
        settings['clear'] = true;

    }else{
        settings['clear'] = false;
        window.localStorage.setItem(
          'Warped.htm-clear',
          1
        );
    }

    if(isNaN(document.getElementById('line-width').value)
      || document.getElementById('line-width').value < 2){
        window.localStorage.removeItem('Warped.htm-line-width');
        settings['line-width'] = 1;

    }else{
        settings['line-width'] = parseInt(document.getElementById('line-width').value);
        window.localStorage.setItem(
          'Warped.htm-line-width',
          settings['line-width']
        );
    }

    if(document.getElementById('randomize-key').value === 'R'){
        window.localStorage.removeItem('Warped.htm-randomize-key');
        settings['randomize-key'] = 'R';

    }else{
        settings['randomize-key'] = document.getElementById('randomize-key').value;
        window.localStorage.setItem(
          'Warped.htm-randomize-key',
          settings['randomize-key']
        );
    }

    if(document.getElementById('mouse-lock').checked){
        window.localStorage.removeItem('Warped.htm-mouse-lock');
        settings['mouse-lock'] = true;

    }else{
        settings['mouse-lock'] = false;
        window.localStorage.setItem(
          'Warped.htm-mouse-lock',
          1
        );
    }

    if(document.getElementById('number-of-objects').value == 100
      || isNaN(document.getElementById('number-of-objects').value)
      || document.getElementById('number-of-objects').value < 1){
        window.localStorage.removeItem('Warped.htm-number-of-objects');
        settings['number-of-objects'] = 100;

    }else{
        settings['number-of-objects'] = parseInt(document.getElementById('number-of-objects').value);
        window.localStorage.setItem(
          'Warped.htm-number-of-objects',
          settings['number-of-objects']
        );
    }
}

function setmode(newmode){
    mode = newmode;

    // Visualization mode.
    if(mode > 0){
        save();

        document.getElementById('page').innerHTML = '<canvas id=canvas></canvas><canvas id=buffer style=display:none></canvas>';

        buffer = document.getElementById('buffer').getContext('2d');
        canvas = document.getElementById('canvas').getContext('2d');

        resize();

    // Main menu mode.
    }else{
        buffer = 0;
        canvas = 0;

        document.getElementById('page').innerHTML = '

Both
Lines
Rectangles

<input disabled style=border:0 value=ESC>Main Menu
<input id=randomize-key maxlength=1 value='
          + settings['randomize-key'] + '>Randomize

<input '
          + (settings['clear'] ? 'checked ' : '') + 'id=clear type=checkbox>Clear
<input id=line-width value='
          + settings['line-width'] + '>Line Width
<input '
          + (settings['mouse-lock'] ? 'checked ' : '') + 'id=mouse-lock type=checkbox>Mouse Lock
<input id=number-of-objects value='
          + settings['number-of-objects'] + '>Objects
Reset Settings

';
    }
}

var buffer = 0;
var canvas = 0;
var height = 0;
var objects = [];
var mode = 0;
var mouse_x = 0;
var mouse_y = 0;
var settings = {
  'clear': window.localStorage.getItem('Warped.htm-clear') === null,
  'line-width' : window.localStorage.getItem('Warped.htm-line-width') === null
    ? 1
    : parseInt(window.localStorage.getItem('Warped.htm-line-width')),
  'randomize-key': window.localStorage.getItem('Warped.htm-randomize-key') === null
    ? 'R'
    : window.localStorage.getItem('Warped.htm-randomize-key'),
  'mouse-lock': window.localStorage.getItem('Warped.htm-mouse-lock') === null,
  'number-of-objects': window.localStorage.getItem('Warped.htm-number-of-objects') === null
    ? 100
    : parseInt(window.localStorage.getItem('Warped.htm-number-of-objects')),
};
var x = 0;
var width = 0;
var y = 0;

resize();
setmode(0);

window.onkeydown = function(e){
    if(mode <= 0){
        return;
    }

    var key = e.keyCode || e.which;

    // settings['randomize-key']: randomize current objects.
    if(String.fromCharCode(key) === settings['randomize-key']){
        randomize_objects();

    // ESC: return to the main menu.
    }else if(key === 27){
        setmode(0);
    }
};

window.onmousedown =
  window.ontouchstart = function(e){
    if(mode <= 0){
        return;
    }

    mouse_x = e.pageX;
    mouse_y = e.pageY;

    draw();
};

window.onmousemove = function(e){
    if(mode <= 0
      || !settings['mouse-lock']){
        return;
    }

    mouse_x = e.pageX;
    mouse_y = e.pageY;

    draw();
};

window.onresize = resize;
<|endoftext|>


<commit_before>var zindex = 0;
var screenHeight = window.innerHeight;
var screenWidth = window.innerWidth;
var maxHeight = Math.floor(screenHeight / 3), minHeight = Math.floor(screenHeight / 5);
var maxWidth = Math.floor(screenWidth / 3), minWidth = Math.floor(screenWidth / 5);

// square-window mappings
var relations = {
    "home": {
        "windId": "home_window",
        "dims": {
            "initHeight": "",
            "initWidth": "",
            "prevHeight": "",
            "prevWidth": ""
        },
    },
    "internet": {
        "windId": "internet_window",
        "dims": {
            "initHeight": "",
            "initWidth": "",
            "prevHeight": "",
            "prevWidth": ""
        },
    },
    "pictures": {
        "windId": "pic_window",
        "dims": {
            "initHeight": 340,
            "initWidth": 420,
            "prevHeight": 340,
            "prevWidth": 420
        },
    },
    "videos": {
        "windId": "vid_window",
        "dims": {
            "initHeight": 485,
            "initWidth": 625,
            "prevHeight": 485,
            "prevWidth": 625
        },
    },
    "game": {
        "windId": "game_window",
        "dims": {
            "initHeight": 675,
            "initWidth": 750,
            "prevHeight": 675,
            "prevWidth": 750
        },
    },
    "folder": {
        "windId": "folder_window",
        "dims": {
            "initHeight": 470,
            "initWidth": 620,
            "prevHeight": 470,
            "prevWidth": 620
        },
    }
}

var tempId;
$(document).ready(function() {
    $(".window").addClass("new");

    $(".resize-drag").draggable({
        drag: function(event) { bringForward(this); }/*,
        containment: "window"*/
    });

    // for(var squareId in relations) {
    //     var windId = "#" + relations[squareId].windId;
    //     $(windId).resizable({
    //         resize: function(event) {
    //             relations[squareId].dims.prevHeight = $(this).height();
    //             relations[squareId].dims.prevWidth = $(this).width();
    //         },
    //         minHeight: relations[squareId].dims.initHeight,
    //         minWidth: relations[squareId].dims.initWidth
    //     })
    // }

    $(".square").click(function() {
        $(this).css("background-color", "Red");
        var squareId = $(this).attr("id");
        openWindow(relations[squareId].windId);
    });

    $(".exit, .min").click(function() {
        var windId = "#" + $(this).parent().parent().attr("id");
        hideWindow(windId);
        if($(this).attr("class") === "exit") {
            if(windId === "#vid_window") { $("#vid").get(0).load(); }
            $(windId).removeClass("opened");
            var squareId = "#" + getSquare($(windId).attr("id"));
            $(squareId).css("background-color", "rgba(255, 255, 255, 0.6)");
        }
    });

    $(".window").click(function() {
        bringForward(this);
    });
});

function openWindow(windId) {
    zindex++;
    windId = "#" + windId;
    var css = { "display": "block", "position": "absolute", "z-index": zindex };

    if(!($(windId).hasClass("opened"))) {
        // open closed window
        $(windId).addClass("opened");
        $(windId).addClass("active");

        if(windId === "#pic_window") {
            $("#image_slider").css({"width": "5460px"});
        }

        // randomize position only when opened the first time
        if($(windId).hasClass("new")) {
            css.top = Math.floor(Math.random() * (maxHeight - minHeight + 1)) + minHeight + "px";
            css.left = Math.floor(Math.random() * (maxWidth - minWidth + 1)) + minWidth + "px";
            $(windId).removeClass("new");
        }
        $(windId).css(css);
    } else if(!$(windId).hasClass("active")) {
        // reactivate minimized window
        $(windId).addClass("active");
        $(windId).css(css);
    } else {
        // minimize active window
        hideWindow(windId);
    }
}

function getSquare(windId) {
    for(var squareId in relations) {
        if(relations[squareId].windId === windId) { return squareId; }
    }
}

function bringForward(wind) {
    zindex++;
    $(wind).css({"z-index": zindex});
}

function hideWindow(windId) {
    $(windId).css("display", "none");
    $(windId).removeClass("active");
}<commit_msg>fixed logic bug in window.js in which sidebar button would not change colors when its corresponding window was closed<commit_after>var zindex = 0;
var screenHeight = window.innerHeight;
var screenWidth = window.innerWidth;
var maxHeight = Math.floor(screenHeight / 3), minHeight = Math.floor(screenHeight / 5);
var maxWidth = Math.floor(screenWidth / 3), minWidth = Math.floor(screenWidth / 5);

// square-window mappings
var relations = {
    "home": {
        "windId": "home_window",
        "dims": {
            "initHeight": "",
            "initWidth": "",
            "prevHeight": "",
            "prevWidth": ""
        },
    },
    "internet": {
        "windId": "internet_window",
        "dims": {
            "initHeight": "",
            "initWidth": "",
            "prevHeight": "",
            "prevWidth": ""
        },
    },
    "pictures": {
        "windId": "pic_window",
        "dims": {
            "initHeight": 340,
            "initWidth": 420,
            "prevHeight": 340,
            "prevWidth": 420
        },
    },
    "videos": {
        "windId": "vid_window",
        "dims": {
            "initHeight": 485,
            "initWidth": 625,
            "prevHeight": 485,
            "prevWidth": 625
        },
    },
    "game": {
        "windId": "game_window",
        "dims": {
            "initHeight": 675,
            "initWidth": 750,
            "prevHeight": 675,
            "prevWidth": 750
        },
    },
    "folder": {
        "windId": "folder_window",
        "dims": {
            "initHeight": 470,
            "initWidth": 620,
            "prevHeight": 470,
            "prevWidth": 620
        },
    }
}

var tempId;
$(document).ready(function() {
    $(".window").addClass("new");

    $(".resize-drag").draggable({
        drag: function(event) { bringForward(this); }/*,
        containment: "window"*/
    });

    // for(var squareId in relations) {
    //     var windId = "#" + relations[squareId].windId;
    //     $(windId).resizable({
    //         resize: function(event) {
    //             relations[squareId].dims.prevHeight = $(this).height();
    //             relations[squareId].dims.prevWidth = $(this).width();
    //         },
    //         minHeight: relations[squareId].dims.initHeight,
    //         minWidth: relations[squareId].dims.initWidth
    //     })
    // }

    $(".square").click(function() {
        $(this).css("background-color", "Red");
        var squareId = $(this).attr("id");
        openWindow(relations[squareId].windId);
    });

    $(".exit, .min").click(function() {
        var windId = "#" + $(this).parent().parent().attr("id");
        hideWindow(windId);
        if($(this).hasClass("exit")) {
            if(windId === "#vid_window") { $("#vid").get(0).load(); }
            $(windId).removeClass("opened");
            var squareId = "#" + getSquare($(windId).attr("id"));
            $(squareId).css("background-color", "rgba(255, 255, 255, 0.6)");
        }
    });

    $(".window").click(function() {
        bringForward(this);
    });
});

function openWindow(windId) {
    zindex++;
    windId = "#" + windId;
    var css = { "display": "block", "position": "absolute", "z-index": zindex };

    if(!($(windId).hasClass("opened"))) {
        // open closed window
        $(windId).addClass("opened");
        $(windId).addClass("active");

        if(windId === "#pic_window") {
            $("#image_slider").css({"width": "5460px"});
        }

        // randomize position only when opened the first time
        if($(windId).hasClass("new")) {
            css.top = Math.floor(Math.random() * (maxHeight - minHeight + 1)) + minHeight + "px";
            css.left = Math.floor(Math.random() * (maxWidth - minWidth + 1)) + minWidth + "px";
            $(windId).removeClass("new");
        }
        $(windId).css(css);
    } else if(!$(windId).hasClass("active")) {
        // reactivate minimized window
        $(windId).addClass("active");
        $(windId).css(css);
    } else {
        // minimize active window
        hideWindow(windId);
    }
}

function getSquare(windId) {
    for(var squareId in relations) {
        if(relations[squareId].windId === windId) { return squareId; }
    }
}

function bringForward(wind) {
    zindex++;
    $(wind).css({"z-index": zindex});
}

function hideWindow(windId) {
    $(windId).css("display", "none");
    $(windId).removeClass("active");
}<|endoftext|>