Advertisement
Guest User

Untitled

a guest
Jun 29th, 2011
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.  * dragdrop.js
  3.  * Author: Casey Flynn
  4.  * June 10, 2011
  5.  * Global variables available to all functions
  6.  */
  7.  
  8. //Keeps track of elements present in droppable and corresponding offsets/positions
  9. var base_url = 'http://www.messageamplify.com/projects/velcro/';
  10. var global_positions = new Array();
  11. var current_item_group = 0;
  12. var loaded = new Array();
  13. var preloading = true;
  14. var sound = null;
  15. var items = new Array(
  16.     new Array(
  17.         new Array(0, '2-Dollar'),
  18.         new Array(1, 'Cards'),
  19.         new Array(2, 'Cheese'),
  20.         new Array(3, 'Coupons'),
  21.         new Array(4, 'DogTags')),
  22.     new Array(
  23.         new Array(5, 'Doodle'),
  24.         new Array(6, 'Dreamcatcher'),
  25.         new Array(7, 'Fish'),
  26.         new Array(8, 'Fortune'),
  27.         new Array(9, 'Groucho')),
  28.     new Array(
  29.         new Array(10, 'HandTurkey'),
  30.         new Array(11, 'Key'),
  31.         new Array(12, 'Lolipop'),
  32.         new Array(13, 'LotteryTicket'),
  33.         new Array(14, 'Map')),
  34.     new Array(
  35.         new Array(15, 'Napkin'),
  36.         new Array(16, 'Notepad'),
  37.         new Array(17, 'OldPhoto'),
  38.         new Array(18, 'Oragami'),
  39.         new Array(19, 'Photo_Baby')),
  40.     new Array(
  41.         new Array(20, 'Photo_DJ'),
  42.         new Array(21, 'Photo_Dogs'),
  43.         new Array(22, 'Photo_Moustache'),
  44.         new Array(23, 'Pick'),
  45.         new Array(24, 'RabitsFoot')),
  46.     new Array(
  47.         new Array(25, 'Recipe'),
  48.         new Array(26, 'Reminder'),
  49.         new Array(27, 'Ribbon'),
  50.         new Array(28, 'SheetMusic'),
  51.         new Array(29, 'Smiley')),
  52.     new Array(
  53.         new Array(30, 'Spork'),
  54.         new Array(31, 'Tape'),
  55.         new Array(32, 'Ticket'),
  56.         new Array(33, 'USB'),
  57.         new Array(34, 'Viewmaster')
  58.     )
  59. );
  60.  
  61. /*
  62.  * jQuery 'ready' handler, executes after DOM is ready and
  63.  * sets draggable/droppable properties of associated elements
  64.  */
  65. $(function(){  
  66.     for(var i = 0; i < items.length; i++)
  67.         loaded[i] = false;
  68.     load_elements(0);
  69.    
  70.     $('#drop_area').droppable({
  71.         //accept: '.draggable',
  72.         //hoverClass: 'vel_content_active',        
  73.         drop: on_element_drop
  74.     });
  75.    
  76.     $('#countdown').html((10 - global_positions.length)+'');
  77.     soundManager.debugMode = false;
  78.     soundManager.url = base_url + 'application/assets/swf/';
  79.     soundManager.flashVersion = 8; // optional: shiny features (default = 8)
  80.     soundManager.useFlashBlock = false; // optionally, enable when you're ready to dive in
  81.     // enable HTML5 audio support, if you're feeling adventurous. iPad/iPhone will always get this.
  82.     // soundManager.useHTML5Audio = true;
  83.     soundManager.onready(function() {
  84.       // Ready to use; soundManager.createSound() etc. can now be called.
  85.       sound = soundManager.createSound({
  86.         id: 'velcro1',
  87.         url: base_url + 'application/assets/sound/velcro1.mp3'
  88.         // onload: [ event handler function object ],
  89.         // other options here..
  90.         });
  91.     });
  92.    
  93. });
  94.  
  95. // preloads an array of images
  96. function preload(arrayOfImages) {
  97.     $(arrayOfImages).each(function(){
  98.         console.log('Preloading ' + this);
  99.         $('<img/>')[0].src = this;
  100.         // Alternatively you could use:
  101.         // (new Image()).src = this;
  102.     });
  103. }
  104.  
  105.  
  106. /*
  107.  * Loads the first set of elements from 'items'
  108.  */
  109. function load_elements(arg0){
  110.     set = items[arg0];
  111.     box_handle = $('.bottom_content');
  112.     elements = '';
  113.  
  114.     //construct html for elements to be added
  115.     for(i=0; i<set.length; i++){
  116.         elements += '<div class="draggable"><img alt="' + set[i][0] + '" src="' + base_url + 'application/assets/images/items/' + set[i][1] + '.png" /></div>';
  117.     }
  118.  
  119.     //clear whatever was in there
  120.     box_handle.empty();
  121.  
  122.     // element parent container
  123.     box_handle.html(elements);
  124.  
  125.     //assign draggable status
  126.     $('.draggable').draggable({
  127.         revert: true,
  128.         revertDuration: 0,
  129.         helper: 'clone'
  130.     });
  131.     loaded[arg0] = true;
  132.     if(preloading){
  133.         var prev = next_elements(-1);
  134.         var next = next_elements(1);
  135.         if(!loaded[prev]){
  136.             preload(items[prev])
  137.             loaded[prev] = true;
  138.         }
  139.         if(!loaded[next]){
  140.             preload(items[next])
  141.             loaded[prev] = true;
  142.         }
  143.     }
  144.    
  145. }
  146.  
  147. function next_elements(arg0){
  148.     if((current_item_group + arg0) == -1){
  149.         return 6;
  150.     }else{
  151.         return ((current_item_group + arg0) % 7);
  152.     }
  153. }
  154. /*
  155.  * Cycles through element groups presented in .bottom_content
  156. -1 to the left 1 to the right
  157.  */
  158. function cycle_elements(arg0){
  159.    
  160.     if((current_item_group + arg0) == -1){
  161.         current_item_group = 6;
  162.     }else{
  163.         current_item_group = ((current_item_group + arg0) % 7);
  164.     }
  165.    
  166.     load_elements(current_item_group);
  167. }
  168.  
  169. /*
  170.  * Callback function on drop event for droppable
  171.  * Determines position of dropped element in droppable
  172.  */
  173. function on_element_drop(event, ui){
  174.     console.log(typeof ui);
  175.     drop_area = $('div#drop_area');
  176.     element = ui.helper;
  177.  
  178.     //Find relative x/y position of element inside drop_area
  179.     var x = Math.floor((element.offset().left - drop_area.offset().left) / drop_area.width() * 100);
  180.     var y = Math.floor((element.offset().top - drop_area.offset().top) / drop_area.height() * 100);
  181.    
  182.     //console.log(ui); return;
  183.    
  184.     //console.log(ui.draggable.context.className.indexOf('draggable_dropped'));
  185.    
  186.     if(ui.draggable.context.className.indexOf('draggable_dropped') == -1){
  187.         if(global_positions.length >= 10)
  188.             return;
  189.            
  190.         //record element position and id
  191.         row = new Array(parseInt($(ui.draggable).find("img").attr('alt')),
  192.                         x,
  193.                         y);
  194.  
  195.         //Add copy of item to drop_area at same x/y position where it was dropped
  196.         add_element_copy_to_div(row);
  197.        
  198.         add_element_copy_to_global_positions(row);
  199.        
  200.     }else{
  201.         //Item has already been dropped and is being adjusted, update global_positions
  202.         //update global_positions
  203.         id = ui.draggable.context.id;
  204.         update_global_positions(id, x, y);
  205.     }
  206.     //$('#countdown').html((10 - global_positions.length)+'');
  207.     console.log(global_positions);
  208.     sound.play();
  209.     console.log('Played sound?');
  210. }
  211.  
  212. /*
  213.  * Finds element in global_positions and updates x & y values
  214.  */
  215. function update_global_positions(id, newX, newY){
  216.    
  217.     image_id = global_positions[id][0];
  218.    
  219.     global_positions[id] = new Array(image_id, newX, newY);
  220.    
  221.     /*
  222.     var old_array = global_positions[find_index(global_positions, index)];
  223.     var new_array = new Array(old_array[0], newX, newY);
  224.    
  225.     //.splice(i,1,pos) -- remove 1 element at index i and replace with pos
  226.     global_positions.splice(index,1,new_array);
  227.     */
  228. }
  229.  
  230. /*
  231.  * Helper function, determines if element is already present in 'global_positions'
  232.  * Replaces if present, adds otherwise
  233.  */
  234. function add_element_copy_to_global_positions(pos){
  235.    
  236.     global_positions.push(pos);
  237.    
  238.     /*
  239.     var found = false;
  240.    
  241.     for(i=0;i<global_positions.length;i++){
  242.         if(global_positions[i][0] == pos[0]){
  243.             //.splice(i,1,pos) -- remove 1 element at index i and replace with pos
  244.             global_positions.splice(i,1,pos);
  245.             found = true;
  246.         }
  247.     }
  248.    
  249.     if(!found)
  250.         global_positions.push(pos);
  251.     */
  252. }
  253.  
  254. /*
  255.  * Helper function, adds a copy of the draggable that was dropped into the droppable
  256.  * for user visualization
  257.  */
  258. function add_element_copy_to_div(pos){
  259.     drop_area = $('#drop_area');
  260.     id = global_positions.length;
  261.    
  262.     console.log('id: ' + id);
  263.    
  264.     //Convert % x&y offsets into absolute pixel offsets based on div size
  265.     x = Math.floor(drop_area.width() * (pos[1] / 100));
  266.     y = Math.floor(drop_area.height() * (pos[2] / 100));
  267.    
  268.     /*------- Find filename of image that has been dropped ------*/
  269.     index = find_index(items[current_item_group], pos[0]);
  270.     filename = items[current_item_group][index][1];
  271.    
  272.     drop_area.append('<div style="position:absolute;" class="draggable_dropped" id="' +  id  + '"><img src="' + base_url + 'application/assets/images/items/' + filename  + '.png" /></div>');
  273.     $('#'+id).css('left', x);
  274.     $('#'+id).css('top', y);
  275.    
  276.     //Set the newly dropped element to draggable so it can be repositioned
  277.     $('#'+id).draggable({
  278.         stop:function(event, ui){
  279.             if(!is_valid_position(ui)) //invalid drop
  280.                 delete_item(ui);
  281.         }
  282.     });
  283. }
  284.  
  285. /*
  286.  * deletes element from global_positions and #drop_area when user drops item outside #drop_area
  287.  *  also adjusts id attributes of all items
  288.  */
  289. function delete_item(ui){
  290.     id = ui.helper.context.id;
  291.     $('#'+id).remove();
  292.    
  293.     global_positions.splice(id, 1);
  294.    
  295.     $('#drop_area div').each(function(index){
  296.         if(parseInt($(this).attr('id')) > parseInt(id))
  297.             $(this).attr('id', parseInt($(this).attr('id')) - 1);
  298.     });
  299.    
  300.     console.log(global_positions);
  301. }
  302.  
  303. /*
  304.  * helper for add_element_copy_to_div
  305.  */
  306. function is_valid_position(ui){
  307.     drop_area = $('#drop_area');
  308.     element = ui.helper;
  309.  
  310.     //Find relative x/y position of element inside drop_area
  311.     var x = Math.floor((element.offset().left - drop_area.offset().left) / drop_area.width() * 100);
  312.     var y = Math.floor((element.offset().top - drop_area.offset().top) / drop_area.height() * 100);
  313.    
  314.     if( (x < -5)  ||
  315.         (x > 105) ||
  316.         (y < -5)  ||
  317.         (y > 105))
  318.         return false;
  319.     return true;
  320. }
  321.  
  322. /*
  323.  * helper for add_element_copy_to_div
  324.  */
  325. function find_index(items, search_index){
  326.     for(i=0; i < items.length; i++){
  327.         if(items[i][0] == search_index)
  328.             return i;
  329.     }
  330. }
  331.  
  332. /*
  333.  * Convert global_position array to JSON and submit to server via ajax along with csrf_token
  334.  */
  335. function update_layout(){
  336.     $.ajax({
  337.         url: '/projects/velcro/index.php/welcome/update_layout',
  338.         type: 'post',
  339.         data: {'layout_json' : $.toJSON(global_positions), 'ci_csrf_token' : $('input[name=ci_csrf_token]').val()},
  340.         success: function(data, textStatus, jqXHR){
  341.             //Redirect user to next page here...
  342.             if(data == '1'){
  343.                 //alert('Layout successfully saved');
  344.             }else{
  345.                 //alert('Layout save failed');
  346.             }
  347.             location.href = 'http://www.messageamplify.com/projects/velcro/index.php/welcome/create2';
  348.         },
  349.         error: function(jqXHR, textStatus, errorThrown){
  350.             console.log('error: '+jqXHR);
  351.             console.log(textStatus);
  352.             console.log(errorThrown);
  353.         }
  354.     });
  355. }
  356.  
  357. //End file 'dragdrop.js'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement