<commit_before>'use strict';

function rpg_character_affect(character, stat, effect){
    rpg_characters[character]['stats'][stat]['current'] -= effect;
    if(rpg_characters[character]['stats'][stat]['current'] <= 0){
        rpg_characters[character]['stats'][stat]['current'] = 0;

        if(stat === 'health'){
            rpg_characters[character]['dead'] = true;
        }

    }else if(rpg_characters[character]['stats'][stat]['current'] >= rpg_characters[character]['stats'][stat]['max']){
        rpg_characters[character]['stats'][stat]['current'] = rpg_characters[character]['stats'][stat]['max'];
        rpg_characters[character]['stats'][stat]['regeneration']['current'] = 0;
    }
}

function rpg_character_create(properties){
    properties = properties || {};

    properties['color'] = properties['color'] || '#fff';
    properties['dead'] = false;
    properties['equipment'] = properties['equipment'] || {
      'feet': void 0,
      'head': void 0,
      'legs': void 0,
      'main-hand': void 0,
      'neck': void 0,
      'off-hand': void 0,
      'torso': void 0,
    };
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 20;
    properties['height-half'] = properties['height'] / 2;
    properties['inventory'] = properties['inventory'] || [];
    properties['player'] = properties['player'] || false;
    properties['selected'] = properties['selected'] || 1;
    properties['spellbar'] = properties['spellbar'] || {
      0: void 0,
      1: void 0,
      2: void 0,
      3: void 0,
      4: void 0,
      5: void 0,
      6: void 0,
      7: void 0,
      8: void 0,
      9: void 0,
    };
    properties['spellbook'] = properties['spellbook'] || {};
    properties['team'] = properties['team'] !== void 0
      ? properties['team']
      : 1;
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 20;
    properties['width-half'] = properties['width'] / 2;
    properties['x'] = properties['x'] || 0;
    properties['x-velocity'] = properties['x-velocity'] || 0;
    properties['y'] = properties['y'] || 0;
    properties['y-velocity'] = properties['y-velocity'] || 0;

    properties['stats'] = properties['stats'] || {};
      properties['stats']['health'] = properties['stats']['health'] || {};
        properties['stats']['health']['current'] = properties['stats']['health']['current'] !== void 0
          ? properties['stats']['health']['current']
          : 1;
        properties['stats']['health']['max'] = properties['stats']['health']['max'] || 1;

    rpg_characters.push(properties);
}

function rpg_character_handle(){
    for(var character in rpg_characters){
        if(rpg_characters[character]['dead']){
            continue;
        }

        // Regenerate character stats.
        for(var stat in rpg_characters[character]['stats']){
            if(rpg_characters[character]['stats'][stat]['regeneration'] === void 0
              || rpg_characters[character]['stats'][stat]['current'] >= rpg_characters[character]['stats'][stat]['max']){
                continue;
            }

            rpg_characters[character]['stats'][stat]['regeneration']['current'] += 1;
            if(rpg_characters[character]['stats'][stat]['regeneration']['current'] >= rpg_characters[character]['stats'][stat]['regeneration']['max']){
                rpg_characters[character]['stats'][stat]['current'] += 1;
                rpg_characters[character]['stats'][stat]['regeneration']['current'] = 0;
            }
        }

        for(var spell in rpg_characters[character]['spellbook']){
            if(rpg_characters[character]['spellbook'][spell]['current'] < rpg_characters[character]['spellbook'][spell]['reload']){
                rpg_characters[character]['spellbook'][spell]['current'] += 1;
                continue;
            }

            if(rpg_characters[character]['spellbar'][rpg_characters[character]['selected']] !== spell){
                continue;
            }

            var selected = rpg_characters[character]['spellbook'][rpg_characters[character]['spellbar'][rpg_characters[character]['selected']]];

            if(selected['cost'] !== 0
              && rpg_characters[character]['stats'][selected['costs']]['current'] < selected['cost']){
                continue;
            }

            var dx = 0;
            var dy = 0;
            var speeds = 0;
            var target_x = 0;
            var target_y = 0;

            if(character === '0'){
                if(mouse_lock_x < 0){
                    continue;
                }

                target_x = rpg_characters[character]['x'] + mouse_x - canvas_x;
                target_y = rpg_characters[character]['y'] + mouse_y - canvas_y;

                speeds = math_movement_speed(
                  rpg_characters[character]['x'],
                  rpg_characters[character]['y'],
                  target_x,
                  target_y
                );

                dx = mouse_x > canvas_x ? speeds[0] : -speeds[0];
                dy = mouse_y > canvas_y ? speeds[1] : -speeds[1];

            }else{
                speeds = math_movement_speed(
                  rpg_characters[character]['x'],
                  rpg_characters[character]['y'],
                  rpg_characters[0]['x'],
                  rpg_characters[0]['y']
                );

                dx = rpg_characters[0]['x'] > rpg_characters[character]['x'] ? speeds[0] : -speeds[0];
                dy = rpg_characters[0]['y'] > rpg_characters[character]['y'] ? speeds[1] : -speeds[1];
            }

            selected['current'] = 0;
            rpg_character_affect(
              character,
              selected['costs'],
              selected['cost']
            );

            // Handle particle-creating spells.
            if(selected['type'] === 'particle'){
                var particle = {};
                for(var property in selected['particle']){
                    particle[property] = selected['particle'][property];
                }
                particle['dx'] = dx;
                particle['dy'] = dy;
                particle['owner'] = character;
                particle['x'] = rpg_characters[character]['x'];
                particle['y'] = rpg_characters[character]['y'];

                rpg_particle_create(particle);

            }else if(selected['type'] === 'stat'){
                rpg_character_affect(
                  character,
                  selected['effect']['stat'],
                  selected['effect']['damage']
                );

            }else if(selected['type'] === 'world-dynamic'){
                var worlddynamic = {};
                for(var property in selected['world-dynamic']){
                    worlddynamic[property] = selected['world-dynamic'][property];
                }
                worlddynamic['x'] = Math.round(target_x - 12.5);
                worlddynamic['y'] = Math.round(target_y - 12.5);

                rpg_world_dynamic_create(worlddynamic);
            }

            break;
        }
    }
}

function rpg_item_create(properties, type){
    properties = properties || {};
    type = type || 'any';

    properties['equipped'] = properties['equipped'] || false;
    properties['owner'] = properties['owner'] || 'player';

    rpg_items.push(properties);
}

function rpg_item_toggle(id){
    if(rpg_items[id]['owner'] === false){
        return;
    }

    // Toggle item on character.
    rpg_items[id]['equipped'] = !rpg_items[id]['equipped'];
}

function rpg_particle_create(properties){
    properties = properties || {};

    properties['color'] = properties['color'] || '#fff';
    properties['damage'] = properties['damage'] || 0;
    properties['dx'] = properties['dx'] || 0;
    properties['dy'] = properties['dy'] || 0;
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 10;
    properties['height-half'] = properties['height'] / 2;
    properties['lifespan'] = properties['lifespan'] !== void 0
      ? properties['lifespan']
      : 10;
    properties['owner'] = properties['owner'] !== void 0
      ? properties['owner']
      : -1;
    properties['speed-x'] = properties['speed-x'] !== void 0
      ? properties['speed-x']
      : 1;
    properties['speed-y'] = properties['speed-y'] !== void 0
      ? properties['speed-y']
      : 1;
    properties['stat'] = properties['stat'] || 'health';
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 10;
    properties['width-half'] = properties['width'] / 2;
    properties['x'] = properties['x'] || 0;
    properties['y'] = properties['y'] || 0;

    rpg_particles.push(properties);
}

function rpg_particle_handle(){
    particleloop:
    for(var particle in rpg_particles){
        rpg_particles[particle]['x'] += rpg_particles[particle]['dx'] * rpg_particles[particle]['speed-x'];
        rpg_particles[particle]['y'] += rpg_particles[particle]['dy'] * rpg_particles[particle]['speed-y'];

        if(rpg_particles[particle]['lifespan'] < 0){
            rpg_particles.splice(
              particle,
              1
            );
            continue;
        }
        rpg_particles[particle]['lifespan'] -= 1;

        for(var object in rpg_world_dynamic){
            if(!rpg_world_dynamic[object]['collision']
              || rpg_particles[particle]['x'] <= rpg_world_dynamic[object]['x']
              || rpg_particles[particle]['x'] >= rpg_world_dynamic[object]['x'] + rpg_world_dynamic[object]['width']
              || rpg_particles[particle]['y'] <= rpg_world_dynamic[object]['y']
              || rpg_particles[particle]['y'] >= rpg_world_dynamic[object]['y'] + rpg_world_dynamic[object]['height']){
                continue;
            }

            rpg_particles.splice(
              particle,
              1
            );
            continue particleloop;
        }

        // Handle collisions with characters.
        for(var character in rpg_characters){
            if(rpg_particles[particle]['owner'] == character
              || rpg_particles[particle]['x'] <= rpg_characters[character]['x'] - rpg_characters[character]['width'] / 2
              || rpg_particles[particle]['x'] >= rpg_characters[character]['x'] + rpg_characters[character]['width'] / 2
              || rpg_particles[particle]['y'] <= rpg_characters[character]['y'] - rpg_characters[character]['height'] / 2
              || rpg_particles[particle]['y'] >= rpg_characters[character]['y'] + rpg_characters[character]['height'] / 2){
                continue;
            }

            rpg_character_affect(
              character,
              rpg_particles[particle]['stat'],
              rpg_particles[particle]['damage']
            );

            rpg_particles.splice(
              particle,
              1
            );

            continue particleloop;
        }
    }
}

function rpg_spell_select(character, id){
    character = character || 0;

    if(id < 1){
        id = 10;

    }else if(id > 10){
        id = 1;
    }

    rpg_characters[character]['selected'] = id;

    if(character === 0){
        document.getElementById('canvas').style.cursor =
          rpg_characters[0]['spellbook'][rpg_characters[0]['spellbar'][id]]['cursor'] || 'auto';
    }
}

function rpg_world_dynamic_create(properties){
    properties = properties || {};

    properties['collision'] = properties['collision'] === void 0;
    properties['color'] = properties['color'] || '#fff';
    properties['effect'] = properties['effect'] || {};
    properties['effect-stat'] = properties['effect-stat'] || 'health';
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 25;
    properties['type'] = properties['type'] || 'stone';
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 25;
    properties['x'] = properties['x'] || 0;
    properties['y'] = properties['y'] || 0;

    rpg_world_dynamic.push(properties);
}

var rpg_characters = [];
var rpg_items = [];
var rpg_particles = [];
var rpg_ui = 0;
var rpg_world_dynamic = [];
var rpg_world_static = [];
<commit_msg>started combining items and spells<commit_after>'use strict';

function rpg_character_affect(character, stat, effect){
    rpg_characters[character]['stats'][stat]['current'] -= effect;
    if(rpg_characters[character]['stats'][stat]['current'] <= 0){
        rpg_characters[character]['stats'][stat]['current'] = 0;

        if(stat === 'health'){
            rpg_characters[character]['dead'] = true;
        }

    }else if(rpg_characters[character]['stats'][stat]['current'] >= rpg_characters[character]['stats'][stat]['max']){
        rpg_characters[character]['stats'][stat]['current'] = rpg_characters[character]['stats'][stat]['max'];
        rpg_characters[character]['stats'][stat]['regeneration']['current'] = 0;
    }
}

function rpg_character_create(properties){
    properties = properties || {};

    properties['color'] = properties['color'] || '#fff';
    properties['dead'] = false;
    properties['equipment'] = properties['equipment'] || {
      'feet': void 0,
      'head': void 0,
      'legs': void 0,
      'main-hand': void 0,
      'neck': void 0,
      'off-hand': void 0,
      'torso': void 0,
    };
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 20;
    properties['height-half'] = properties['height'] / 2;
    properties['inventory'] = properties['inventory'] || [];
    properties['player'] = properties['player'] || false;
    properties['selected'] = properties['selected'] || 0;
    properties['team'] = properties['team'] !== void 0
      ? properties['team']
      : 1;
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 20;
    properties['width-half'] = properties['width'] / 2;
    properties['x'] = properties['x'] || 0;
    properties['x-velocity'] = properties['x-velocity'] || 0;
    properties['y'] = properties['y'] || 0;
    properties['y-velocity'] = properties['y-velocity'] || 0;

    properties['stats'] = properties['stats'] || {};
      properties['stats']['health'] = properties['stats']['health'] || {};
        properties['stats']['health']['current'] = properties['stats']['health']['current'] !== void 0
          ? properties['stats']['health']['current']
          : 1;
        properties['stats']['health']['max'] = properties['stats']['health']['max'] || 1;

    rpg_characters.push(properties);
}

function rpg_character_handle(){
    for(var character in rpg_characters){
        if(rpg_characters[character]['dead']){
            continue;
        }

        // Regenerate character stats.
        for(var stat in rpg_characters[character]['stats']){
            if(rpg_characters[character]['stats'][stat]['regeneration'] === void 0
              || rpg_characters[character]['stats'][stat]['current'] >= rpg_characters[character]['stats'][stat]['max']){
                continue;
            }

            rpg_characters[character]['stats'][stat]['regeneration']['current'] += 1;
            if(rpg_characters[character]['stats'][stat]['regeneration']['current'] >= rpg_characters[character]['stats'][stat]['regeneration']['max']){
                rpg_characters[character]['stats'][stat]['current'] += 1;
                rpg_characters[character]['stats'][stat]['regeneration']['current'] = 0;
            }
        }

        // Handle character inventory.
        for(var item in rpg_characters[character]['inventory']){
            var selected = rpg_characters[character]['inventory'][item];

            if(selected['current'] < selected['reload']){
                selected['current'] += 1;
                continue;
            }

            if(rpg_characters[character]['selected'] != item){
                continue;
            }

            if(selected['cost'] !== 0
              && rpg_characters[character]['stats'][selected['costs']]['current'] < selected['cost']){
                continue;
            }

            var dx = 0;
            var dy = 0;
            var speeds = 0;
            var target_x = 0;
            var target_y = 0;

            if(character === '0'){
                if(mouse_lock_x < 0){
                    continue;
                }

                target_x = rpg_characters[character]['x'] + mouse_x - canvas_x;
                target_y = rpg_characters[character]['y'] + mouse_y - canvas_y;

                speeds = math_movement_speed(
                  rpg_characters[character]['x'],
                  rpg_characters[character]['y'],
                  target_x,
                  target_y
                );

                dx = mouse_x > canvas_x ? speeds[0] : -speeds[0];
                dy = mouse_y > canvas_y ? speeds[1] : -speeds[1];

            }else{
                speeds = math_movement_speed(
                  rpg_characters[character]['x'],
                  rpg_characters[character]['y'],
                  rpg_characters[0]['x'],
                  rpg_characters[0]['y']
                );

                dx = rpg_characters[0]['x'] > rpg_characters[character]['x'] ? speeds[0] : -speeds[0];
                dy = rpg_characters[0]['y'] > rpg_characters[character]['y'] ? speeds[1] : -speeds[1];
            }

            selected['current'] = 0;
            rpg_character_affect(
              character,
              selected['costs'],
              selected['cost']
            );

            // Handle particle-creating spells.
            if(selected['type'] === 'particle'){
                var particle = {};
                for(var property in selected['particle']){
                    particle[property] = selected['particle'][property];
                }
                particle['dx'] = dx;
                particle['dy'] = dy;
                particle['owner'] = character;
                particle['x'] = rpg_characters[character]['x'];
                particle['y'] = rpg_characters[character]['y'];

                rpg_particle_create(particle);

            }else if(selected['type'] === 'stat'){
                rpg_character_affect(
                  character,
                  selected['effect']['stat'],
                  selected['effect']['damage']
                );

            }else if(selected['type'] === 'world-dynamic'){
                var worlddynamic = {};
                for(var property in selected['world-dynamic']){
                    worlddynamic[property] = selected['world-dynamic'][property];
                }
                worlddynamic['x'] = Math.round(target_x - 12.5);
                worlddynamic['y'] = Math.round(target_y - 12.5);

                rpg_world_dynamic_create(worlddynamic);
            }

            break;
        }
    }
}

function rpg_item_create(properties, type){
    properties = properties || {};
    type = type || 'any';

    properties['equipped'] = properties['equipped'] || false;
    properties['owner'] = properties['owner'] || 'player';

    rpg_items.push(properties);
}

function rpg_item_select(character, id){
    character = character || 0;

    var length = rpg_characters[character]['inventory'].length - 1;
    if(id < 0){
        id = length;

    }else if(id > length){
        id = 0;
    }

    rpg_characters[character]['selected'] = id;

    if(character === 0){
        document.getElementById('canvas').style.cursor =
          rpg_characters[0]['inventory'][id]['cursor'] || 'auto';
    }
}

function rpg_item_toggle(id){
    if(rpg_items[id]['owner'] === false){
        return;
    }

    // Toggle item on character.
    rpg_items[id]['equipped'] = !rpg_items[id]['equipped'];
}

function rpg_particle_create(properties){
    properties = properties || {};

    properties['color'] = properties['color'] || '#fff';
    properties['damage'] = properties['damage'] || 0;
    properties['dx'] = properties['dx'] || 0;
    properties['dy'] = properties['dy'] || 0;
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 10;
    properties['height-half'] = properties['height'] / 2;
    properties['lifespan'] = properties['lifespan'] !== void 0
      ? properties['lifespan']
      : 10;
    properties['owner'] = properties['owner'] !== void 0
      ? properties['owner']
      : -1;
    properties['speed-x'] = properties['speed-x'] !== void 0
      ? properties['speed-x']
      : 1;
    properties['speed-y'] = properties['speed-y'] !== void 0
      ? properties['speed-y']
      : 1;
    properties['stat'] = properties['stat'] || 'health';
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 10;
    properties['width-half'] = properties['width'] / 2;
    properties['x'] = properties['x'] || 0;
    properties['y'] = properties['y'] || 0;

    rpg_particles.push(properties);
}

function rpg_particle_handle(){
    particleloop:
    for(var particle in rpg_particles){
        rpg_particles[particle]['x'] += rpg_particles[particle]['dx'] * rpg_particles[particle]['speed-x'];
        rpg_particles[particle]['y'] += rpg_particles[particle]['dy'] * rpg_particles[particle]['speed-y'];

        if(rpg_particles[particle]['lifespan'] < 0){
            rpg_particles.splice(
              particle,
              1
            );
            continue;
        }
        rpg_particles[particle]['lifespan'] -= 1;

        for(var object in rpg_world_dynamic){
            if(!rpg_world_dynamic[object]['collision']
              || rpg_particles[particle]['x'] <= rpg_world_dynamic[object]['x']
              || rpg_particles[particle]['x'] >= rpg_world_dynamic[object]['x'] + rpg_world_dynamic[object]['width']
              || rpg_particles[particle]['y'] <= rpg_world_dynamic[object]['y']
              || rpg_particles[particle]['y'] >= rpg_world_dynamic[object]['y'] + rpg_world_dynamic[object]['height']){
                continue;
            }

            rpg_particles.splice(
              particle,
              1
            );
            continue particleloop;
        }

        // Handle collisions with characters.
        for(var character in rpg_characters){
            if(rpg_particles[particle]['owner'] == character
              || rpg_particles[particle]['x'] <= rpg_characters[character]['x'] - rpg_characters[character]['width'] / 2
              || rpg_particles[particle]['x'] >= rpg_characters[character]['x'] + rpg_characters[character]['width'] / 2
              || rpg_particles[particle]['y'] <= rpg_characters[character]['y'] - rpg_characters[character]['height'] / 2
              || rpg_particles[particle]['y'] >= rpg_characters[character]['y'] + rpg_characters[character]['height'] / 2){
                continue;
            }

            rpg_character_affect(
              character,
              rpg_particles[particle]['stat'],
              rpg_particles[particle]['damage']
            );

            rpg_particles.splice(
              particle,
              1
            );

            continue particleloop;
        }
    }
}

function rpg_world_dynamic_create(properties){
    properties = properties || {};

    properties['collision'] = properties['collision'] === void 0;
    properties['color'] = properties['color'] || '#fff';
    properties['effect'] = properties['effect'] || {};
    properties['effect-stat'] = properties['effect-stat'] || 'health';
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 25;
    properties['type'] = properties['type'] || 'stone';
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 25;
    properties['x'] = properties['x'] || 0;
    properties['y'] = properties['y'] || 0;

    rpg_world_dynamic.push(properties);
}

var rpg_characters = [];
var rpg_items = [];
var rpg_particles = [];
var rpg_world_dynamic = [];
var rpg_world_static = [];
<|endoftext|>


<commit_before>'use strict';

function rpg_character_affect(character, stat, effect){
    rpg_characters[character]['stats'][stat]['current'] -= effect;
    if(rpg_characters[character]['stats'][stat]['current'] <= 0){
        rpg_characters[character]['stats'][stat]['current'] = 0;

        if(stat === 'health'){
            rpg_characters[character]['dead'] = true;
        }

    }else if(rpg_characters[character]['stats'][stat]['current'] >= rpg_characters[character]['stats'][stat]['max']){
        rpg_characters[character]['stats'][stat]['current'] = rpg_characters[character]['stats'][stat]['max'];
        rpg_characters[character]['stats'][stat]['regeneration']['current'] = 0;
    }
}

function rpg_character_create(properties){
    properties = properties || {};

    properties['color'] = properties['color'] || '#fff';
    properties['dead'] = false;
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 20;
    properties['height-half'] = properties['height'] / 2;
    properties['inventory'] = properties['inventory'] || [];
    properties['player'] = properties['player'] || false;
    properties['selected'] = properties['selected'] || 0;
    properties['target-x'] = properties['target-x'] || 0;
    properties['target-y'] = properties['target-y'] || 0;
    properties['team'] = properties['team'] !== void 0
      ? properties['team']
      : 1;
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 20;
    properties['width-half'] = properties['width'] / 2;
    properties['x'] = properties['x'] || 0;
    properties['x-velocity'] = properties['x-velocity'] || 0;
    properties['y'] = properties['y'] || 0;
    properties['y-velocity'] = properties['y-velocity'] || 0;

    properties['stats'] = properties['stats'] || {};
      properties['stats']['health'] = properties['stats']['health'] || {};
        properties['stats']['health']['current'] = properties['stats']['health']['current'] !== void 0
          ? properties['stats']['health']['current']
          : 10;
        properties['stats']['health']['max'] = properties['stats']['health']['max'] || properties['stats']['health']['current'];
        properties['stats']['health']['regeneration'] = properties['stats']['health']['regeneration'] || {};
          properties['stats']['health']['regeneration']['current'] = properties['stats']['health']['regeneration']['current'] !== void 0
            ? properties['stats']['health']['regeneration']['current']
            : 0;
          properties['stats']['health']['regeneration']['max'] = properties['stats']['health']['regeneration']['max'] || 1000;
      properties['stats']['mana'] = properties['stats']['mana'] || {};
        properties['stats']['mana']['current'] = properties['stats']['mana']['current'] !== void 0
          ? properties['stats']['mana']['current']
          : 10;
        properties['stats']['mana']['max'] = properties['stats']['mana']['max'] || properties['stats']['mana']['current'];
        properties['stats']['mana']['regeneration'] = properties['stats']['mana']['regeneration'] || {};
          properties['stats']['mana']['regeneration']['current'] = properties['stats']['mana']['regeneration']['current'] !== void 0
            ? properties['stats']['mana']['regeneration']['current']
            : 0;
          properties['stats']['mana']['regeneration']['max'] = properties['stats']['mana']['regeneration']['max'] || 100;

    rpg_characters.push(properties);
}

function rpg_character_handle(){
    for(var character in rpg_characters){
        if(rpg_characters[character]['dead']){
            continue;
        }

        // Regenerate character stats.
        for(var stat in rpg_characters[character]['stats']){
            if(rpg_characters[character]['stats'][stat]['regeneration'] === void 0
              || rpg_characters[character]['stats'][stat]['current'] >= rpg_characters[character]['stats'][stat]['max']){
                continue;
            }

            rpg_characters[character]['stats'][stat]['regeneration']['current'] += 1;
            if(rpg_characters[character]['stats'][stat]['regeneration']['current'] >= rpg_characters[character]['stats'][stat]['regeneration']['max']){
                rpg_characters[character]['stats'][stat]['current'] += 1;
                rpg_characters[character]['stats'][stat]['regeneration']['current'] = 0;
            }
        }

        // Update target.
        if(character === '0'){
            rpg_characters[character]['target-x'] = rpg_characters[character]['x'] + mouse_x - canvas_x;
            rpg_characters[character]['target-y'] = rpg_characters[character]['y'] + mouse_y - canvas_y;

        }else{
            rpg_characters[character]['target-x'] = rpg_characters[0]['x'];
            rpg_characters[character]['target-y'] = rpg_characters[0]['y'];
        }

        // Handle character inventory item spells.
        for(var item in rpg_characters[character]['inventory']){
            var selected = rpg_characters[character]['inventory'][item]['spell'];

            if(selected['reload-current'] < selected['reload']){
                selected['reload-current'] += 1;
                continue;
            }

            if(rpg_characters[character]['selected'] != item){
                continue;
            }

            if(selected['cost'] !== 0
              && rpg_characters[character]['stats'][selected['costs']]['current'] < selected['cost']){
                continue;
            }

            if(character === '0'
              && mouse_lock_x < 0){
                continue;
            }

            var speeds = math_movement_speed(
              rpg_characters[character]['x'],
              rpg_characters[character]['y'],
              rpg_characters[character]['target-x'],
              rpg_characters[character]['target-y']
            );
            var dx = rpg_characters[character]['target-x'] > rpg_characters[character]['x'] ? speeds[0] : -speeds[0];
            var dy = rpg_characters[character]['target-y'] > rpg_characters[character]['y'] ? speeds[1] : -speeds[1];

            selected['reload-current'] = 0;
            rpg_character_affect(
              character,
              selected['costs'],
              selected['cost']
            );

            // Handle particle-creating spells.
            if(selected['type'] === 'particle'){
                var particle = {};
                for(var property in selected){
                    particle[property] = selected[property];
                }
                particle['dx'] = dx;
                particle['dy'] = dy;
                particle['owner'] = character;
                particle['x'] = rpg_characters[character]['x'];
                particle['y'] = rpg_characters[character]['y'];

                rpg_particle_create(particle);

            }else if(selected['type'] === 'stat'){
                rpg_character_affect(
                  character,
                  selected['damages'],
                  selected['damage']
                );

            }else if(selected['type'] === 'character'){
                rpg_character_create({
                  'x': rpg_characters[character]['target-x'],
                  'y': rpg_characters[character]['target-y'],
                });
            }

            break;
        }
    }
}

function rpg_item_create(properties, type){
    properties = properties || {};
    type = type || 'any';

    properties['cursor'] = properties['cursor'] || 'auto';
    properties['equipped'] = properties['equipped'] || false;
    properties['label'] = properties['label'] || '';
    properties['owner'] = properties['owner'] || 0;
    properties['slot'] = properties['slot'] || 'spellbook';
    properties['spell'] = properties['spell'] || {};
      properties['spell']['cost'] = properties['spell']['cost'] || 0;
      properties['spell']['costs'] = properties['spell']['costs'] || 'mana';
      properties['spell']['color'] = properties['spell']['color'] || '#fff';
      properties['spell']['damage'] = properties['spell']['damage'] || 0;
      properties['spell']['damages'] = properties['spell']['damages'] || 'health';
      properties['spell']['lifespan'] = properties['spell']['lifespan'] || 50;
      properties['spell']['reload'] = properties['spell']['reload'] || 0;
      properties['spell']['reload-current'] = properties['spell']['reload-current'] || properties['spell']['reload'];
      properties['spell']['speed-x'] = properties['spell']['speed-x'] || 5;
      properties['spell']['speed-y'] = properties['spell']['speed-y'] || 5;
      properties['spell']['type'] = properties['spell']['type'] || 'particle';

    return properties;
}

function rpg_item_select(character, id){
    character = character || 0;

    var length = rpg_characters[character]['inventory'].length - 1;
    if(id < 0){
        id = length;

    }else if(id > length){
        id = 0;
    }

    rpg_characters[character]['selected'] = id;

    if(character === 0){
        document.getElementById('canvas').style.cursor =
          rpg_characters[0]['inventory'][id]['cursor'] || 'auto';
    }
}

/*
function rpg_item_toggle(id){
    if(rpg_items[id]['owner'] === false){
        return;
    }

    // Toggle item on character.
    rpg_items[id]['equipped'] = !rpg_items[id]['equipped'];
}
*/

function rpg_particle_create(properties){
    properties = properties || {};

    properties['color'] = properties['color'] || '#fff';
    properties['damage'] = properties['damage'] || 0;
    properties['dx'] = properties['dx'] || 0;
    properties['dy'] = properties['dy'] || 0;
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 10;
    properties['height-half'] = properties['height'] / 2;
    properties['lifespan'] = properties['lifespan'] !== void 0
      ? properties['lifespan']
      : 10;
    properties['owner'] = properties['owner'] !== void 0
      ? properties['owner']
      : -1;
    properties['speed-x'] = properties['speed-x'] !== void 0
      ? properties['speed-x']
      : 1;
    properties['speed-y'] = properties['speed-y'] !== void 0
      ? properties['speed-y']
      : 1;
    properties['stat'] = properties['stat'] || 'health';
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 10;
    properties['width-half'] = properties['width'] / 2;
    properties['x'] = properties['x'] || 0;
    properties['y'] = properties['y'] || 0;

    rpg_particles.push(properties);
}

function rpg_particle_handle(){
    particleloop:
    for(var particle in rpg_particles){
        rpg_particles[particle]['x'] += rpg_particles[particle]['dx'] * rpg_particles[particle]['speed-x'];
        rpg_particles[particle]['y'] += rpg_particles[particle]['dy'] * rpg_particles[particle]['speed-y'];

        if(rpg_particles[particle]['lifespan'] < 0){
            rpg_particles.splice(
              particle,
              1
            );
            continue;
        }
        rpg_particles[particle]['lifespan'] -= 1;

        for(var object in rpg_world_dynamic){
            if(!rpg_world_dynamic[object]['collision']
              || rpg_particles[particle]['x'] <= rpg_world_dynamic[object]['x']
              || rpg_particles[particle]['x'] >= rpg_world_dynamic[object]['x'] + rpg_world_dynamic[object]['width']
              || rpg_particles[particle]['y'] <= rpg_world_dynamic[object]['y']
              || rpg_particles[particle]['y'] >= rpg_world_dynamic[object]['y'] + rpg_world_dynamic[object]['height']){
                continue;
            }

            rpg_particles.splice(
              particle,
              1
            );
            continue particleloop;
        }

        // Handle collisions with characters.
        for(var character in rpg_characters){
            if(rpg_particles[particle]['owner'] == character
              || rpg_particles[particle]['x'] <= rpg_characters[character]['x'] - rpg_characters[character]['width'] / 2
              || rpg_particles[particle]['x'] >= rpg_characters[character]['x'] + rpg_characters[character]['width'] / 2
              || rpg_particles[particle]['y'] <= rpg_characters[character]['y'] - rpg_characters[character]['height'] / 2
              || rpg_particles[particle]['y'] >= rpg_characters[character]['y'] + rpg_characters[character]['height'] / 2){
                continue;
            }

            rpg_character_affect(
              character,
              rpg_particles[particle]['stat'],
              rpg_particles[particle]['damage']
            );

            rpg_particles.splice(
              particle,
              1
            );

            continue particleloop;
        }
    }
}

function rpg_world_dynamic_create(properties){
    properties = properties || {};

    properties['collision'] = properties['collision'] === void 0;
    properties['color'] = properties['color'] || '#fff';
    properties['effect'] = properties['effect'] || {};
    properties['effect-stat'] = properties['effect-stat'] || 'health';
    properties['height'] = properties['height'] !== void 0
      ? properties['height']
      : 25;
    properties['type'] = properties['type'] || 'stone';
    properties['width'] = properties['width'] !== void 0
      ? properties['width']
      : 25;
    properties['x'] = properties['x'] || 0;
    properties['y'] = properties['y'] || 0;

    rpg_world_dynamic.push(properties);
}

var rpg_characters = [];
var rpg_particles = [];
var rpg_world_dynamic = [];
var rpg_world_static = [];
<commit_msg>switched rpg.js to args<commit_after>'use strict';

// Required args: character, effect, stat
function rpg_character_affect(args){
    rpg_characters[args['character']]['stats'][args['stat']]['current'] -= args['effect'];
    if(rpg_characters[args['character']]['stats'][args['stat']]['current'] <= 0){
        rpg_characters[args['character']]['stats'][args['stat']]['current'] = 0;

        if(args['stat'] === 'health'){
            rpg_characters[args['character']]['dead'] = true;
        }

    }else if(rpg_characters[args['character']]['stats'][args['stat']]['current'] >= rpg_characters[args['character']]['stats'][args['stat']]['max']){
        rpg_characters[args['character']]['stats'][args['stat']]['current'] = rpg_characters[args['character']]['stats'][args['stat']]['max'];
        rpg_characters[args['character']]['stats'][args['stat']]['regeneration']['current'] = 0;
    }
}

// Optional args: properties
function rpg_character_create(args){
    args = args || {};
    args['properties'] = args['properties'] || {};

    args['properties']['color'] = args['properties']['color'] || '#fff';
    args['properties']['dead'] = false;
    args['properties']['height'] = args['properties']['height'] !== void 0
      ? args['properties']['height']
      : 20;
    args['properties']['height-half'] = args['properties']['height'] / 2;
    args['properties']['inventory'] = args['properties']['inventory'] || [];
    args['properties']['player'] = args['properties']['player'] || false;
    args['properties']['selected'] = args['properties']['selected'] || 0;
    args['properties']['target-x'] = args['properties']['target-x'] || 0;
    args['properties']['target-y'] = args['properties']['target-y'] || 0;
    args['properties']['team'] = args['properties']['team'] !== void 0
      ? args['properties']['team']
      : 1;
    args['properties']['width'] = args['properties']['width'] !== void 0
      ? args['properties']['width']
      : 20;
    args['properties']['width-half'] = args['properties']['width'] / 2;
    args['properties']['x'] = args['properties']['x'] || 0;
    args['properties']['x-velocity'] = args['properties']['x-velocity'] || 0;
    args['properties']['y'] = args['properties']['y'] || 0;
    args['properties']['y-velocity'] = args['properties']['y-velocity'] || 0;

    args['properties']['stats'] = args['properties']['stats'] || {};
      args['properties']['stats']['health'] = args['properties']['stats']['health'] || {};
        args['properties']['stats']['health']['current'] = args['properties']['stats']['health']['current'] !== void 0
          ? args['properties']['stats']['health']['current']
          : 10;
        args['properties']['stats']['health']['max'] = args['properties']['stats']['health']['max'] || args['properties']['stats']['health']['current'];
        args['properties']['stats']['health']['regeneration'] = args['properties']['stats']['health']['regeneration'] || {};
          args['properties']['stats']['health']['regeneration']['current'] = args['properties']['stats']['health']['regeneration']['current'] !== void 0
            ? args['properties']['stats']['health']['regeneration']['current']
            : 0;
          args['properties']['stats']['health']['regeneration']['max'] = args['properties']['stats']['health']['regeneration']['max'] || 1000;
      args['properties']['stats']['mana'] = args['properties']['stats']['mana'] || {};
        args['properties']['stats']['mana']['current'] = args['properties']['stats']['mana']['current'] !== void 0
          ? args['properties']['stats']['mana']['current']
          : 10;
        args['properties']['stats']['mana']['max'] = args['properties']['stats']['mana']['max'] || args['properties']['stats']['mana']['current'];
        args['properties']['stats']['mana']['regeneration'] = args['properties']['stats']['mana']['regeneration'] || {};
          args['properties']['stats']['mana']['regeneration']['current'] = args['properties']['stats']['mana']['regeneration']['current'] !== void 0
            ? args['properties']['stats']['mana']['regeneration']['current']
            : 0;
          args['properties']['stats']['mana']['regeneration']['max'] = args['properties']['stats']['mana']['regeneration']['max'] || 100;

    rpg_characters.push(args['properties']);
}

function rpg_character_handle(){
    for(var character in rpg_characters){
        if(rpg_characters[character]['dead']){
            continue;
        }

        // Regenerate character stats.
        for(var stat in rpg_characters[character]['stats']){
            if(rpg_characters[character]['stats'][stat]['regeneration'] === void 0
              || rpg_characters[character]['stats'][stat]['current'] >= rpg_characters[character]['stats'][stat]['max']){
                continue;
            }

            rpg_characters[character]['stats'][stat]['regeneration']['current'] += 1;
            if(rpg_characters[character]['stats'][stat]['regeneration']['current'] >= rpg_characters[character]['stats'][stat]['regeneration']['max']){
                rpg_characters[character]['stats'][stat]['current'] += 1;
                rpg_characters[character]['stats'][stat]['regeneration']['current'] = 0;
            }
        }

        // Update target.
        if(character === '0'){
            rpg_characters[character]['target-x'] = rpg_characters[character]['x'] + mouse_x - canvas_x;
            rpg_characters[character]['target-y'] = rpg_characters[character]['y'] + mouse_y - canvas_y;

        }else{
            rpg_characters[character]['target-x'] = rpg_characters[0]['x'];
            rpg_characters[character]['target-y'] = rpg_characters[0]['y'];
        }

        // Handle character inventory item spells.
        for(var item in rpg_characters[character]['inventory']){
            var selected = rpg_characters[character]['inventory'][item]['spell'];

            if(selected['reload-current'] < selected['reload']){
                selected['reload-current'] += 1;
                continue;
            }

            if(rpg_characters[character]['selected'] != item){
                continue;
            }

            if(selected['cost'] !== 0
              && rpg_characters[character]['stats'][selected['costs']]['current'] < selected['cost']){
                continue;
            }

            if(character === '0'
              && mouse_lock_x < 0){
                continue;
            }

            var speeds = math_movement_speed(
              rpg_characters[character]['x'],
              rpg_characters[character]['y'],
              rpg_characters[character]['target-x'],
              rpg_characters[character]['target-y']
            );
            var dx = rpg_characters[character]['target-x'] > rpg_characters[character]['x'] ? speeds[0] : -speeds[0];
            var dy = rpg_characters[character]['target-y'] > rpg_characters[character]['y'] ? speeds[1] : -speeds[1];

            selected['reload-current'] = 0;
            rpg_character_affect({
              'character': character,
              'effect': selected['cost'],
              'stat': selected['costs'],
            });

            // Handle particle-creating spells.
            if(selected['type'] === 'particle'){
                var particle = {};
                for(var property in selected){
                    particle[property] = selected[property];
                }
                particle['dx'] = dx;
                particle['dy'] = dy;
                particle['owner'] = character;
                particle['x'] = rpg_characters[character]['x'];
                particle['y'] = rpg_characters[character]['y'];

                rpg_particle_create({
                  'properties': particle,
                });

            }else if(selected['type'] === 'stat'){
                rpg_character_affect({
                  'character': character,
                  'effect': selected['damage'],
                  'stat': selected['damages'],
                });

            }else if(selected['type'] === 'character'){
                rpg_character_create({
                  'properties': {
                    'x': rpg_characters[character]['target-x'],
                    'y': rpg_characters[character]['target-y'],
                  },
                });
            }

            break;
        }
    }
}

// Optional args: properties, type
function rpg_item_create(args){
    args = args || {};
    args['properties'] = args['properties'] || {};
    args['type'] = args['type'] || 'any';

    args['properties']['cursor'] = args['properties']['cursor'] || 'auto';
    args['properties']['equipped'] = args['properties']['equipped'] || false;
    args['properties']['label'] = args['properties']['label'] || '';
    args['properties']['owner'] = args['properties']['owner'] || 0;
    args['properties']['slot'] = args['properties']['slot'] || 'spellbook';
    args['properties']['spell'] = args['properties']['spell'] || {};
      args['properties']['spell']['cost'] = args['properties']['spell']['cost'] || 0;
      args['properties']['spell']['costs'] = args['properties']['spell']['costs'] || 'mana';
      args['properties']['spell']['color'] = args['properties']['spell']['color'] || '#fff';
      args['properties']['spell']['damage'] = args['properties']['spell']['damage'] || 0;
      args['properties']['spell']['damages'] = args['properties']['spell']['damages'] || 'health';
      args['properties']['spell']['lifespan'] = args['properties']['spell']['lifespan'] || 50;
      args['properties']['spell']['reload'] = args['properties']['spell']['reload'] || 0;
      args['properties']['spell']['reload-current'] = args['properties']['spell']['reload-current'] || args['properties']['spell']['reload'];
      args['properties']['spell']['speed-x'] = args['properties']['spell']['speed-x'] || 5;
      args['properties']['spell']['speed-y'] = args['properties']['spell']['speed-y'] || 5;
      args['properties']['spell']['type'] = args['properties']['spell']['type'] || 'particle';

    return args['properties'];
}

// Required args: id
// Optional args: character
function rpg_item_select(args){
    args['character'] = args['character'] || 0;

    var length = rpg_characters[args['character']]['inventory'].length - 1;
    if(args['id'] < 0){
        args['id'] = length;

    }else if(args['id'] > length){
        args['id'] = 0;
    }

    rpg_characters[args['character']]['selected'] = args['id'];

    if(args['character'] === 0){
        document.getElementById('canvas').style.cursor =
          rpg_characters[0]['inventory'][args['id']]['cursor'] || 'auto';
    }
}

/*
function rpg_item_toggle(id){
    if(rpg_items[id]['owner'] === false){
        return;
    }

    // Toggle item on character.
    rpg_items[id]['equipped'] = !rpg_items[id]['equipped'];
}
*/

// Optional args: properties
function rpg_particle_create(args){
    args = args || {};
    args['properties'] = args['properties'] || {};

    args['properties']['color'] = args['properties']['color'] || '#fff';
    args['properties']['damage'] = args['properties']['damage'] || 0;
    args['properties']['dx'] = args['properties']['dx'] || 0;
    args['properties']['dy'] = args['properties']['dy'] || 0;
    args['properties']['height'] = args['properties']['height'] !== void 0
      ? args['properties']['height']
      : 10;
    args['properties']['height-half'] = args['properties']['height'] / 2;
    args['properties']['lifespan'] = args['properties']['lifespan'] !== void 0
      ? args['properties']['lifespan']
      : 10;
    args['properties']['owner'] = args['properties']['owner'] !== void 0
      ? args['properties']['owner']
      : -1;
    args['properties']['speed-x'] = args['properties']['speed-x'] !== void 0
      ? args['properties']['speed-x']
      : 1;
    args['properties']['speed-y'] = args['properties']['speed-y'] !== void 0
      ? args['properties']['speed-y']
      : 1;
    args['properties']['stat'] = args['properties']['stat'] || 'health';
    args['properties']['width'] = args['properties']['width'] !== void 0
      ? args['properties']['width']
      : 10;
    args['properties']['width-half'] = args['properties']['width'] / 2;
    args['properties']['x'] = args['properties']['x'] || 0;
    args['properties']['y'] = args['properties']['y'] || 0;

    rpg_particles.push(args['properties']);
}

function rpg_particle_handle(){
    particleloop:
    for(var particle in rpg_particles){
        rpg_particles[particle]['x'] += rpg_particles[particle]['dx'] * rpg_particles[particle]['speed-x'];
        rpg_particles[particle]['y'] += rpg_particles[particle]['dy'] * rpg_particles[particle]['speed-y'];

        if(rpg_particles[particle]['lifespan'] < 0){
            rpg_particles.splice(
              particle,
              1
            );
            continue;
        }
        rpg_particles[particle]['lifespan'] -= 1;

        for(var object in rpg_world_dynamic){
            if(!rpg_world_dynamic[object]['collision']
              || rpg_particles[particle]['x'] <= rpg_world_dynamic[object]['x']
              || rpg_particles[particle]['x'] >= rpg_world_dynamic[object]['x'] + rpg_world_dynamic[object]['width']
              || rpg_particles[particle]['y'] <= rpg_world_dynamic[object]['y']
              || rpg_particles[particle]['y'] >= rpg_world_dynamic[object]['y'] + rpg_world_dynamic[object]['height']){
                continue;
            }

            rpg_particles.splice(
              particle,
              1
            );
            continue particleloop;
        }

        // Handle collisions with characters.
        for(var character in rpg_characters){
            if(rpg_particles[particle]['owner'] == character
              || rpg_particles[particle]['x'] <= rpg_characters[character]['x'] - rpg_characters[character]['width'] / 2
              || rpg_particles[particle]['x'] >= rpg_characters[character]['x'] + rpg_characters[character]['width'] / 2
              || rpg_particles[particle]['y'] <= rpg_characters[character]['y'] - rpg_characters[character]['height'] / 2
              || rpg_particles[particle]['y'] >= rpg_characters[character]['y'] + rpg_characters[character]['height'] / 2){
                continue;
            }

            rpg_character_affect({
              'character': character,
              'effect': rpg_particles[particle]['damage'],
              'stat': rpg_particles[particle]['stat'],
            });

            rpg_particles.splice(
              particle,
              1
            );

            continue particleloop;
        }
    }
}

// Optional args: properties
function rpg_world_dynamic_create(args){
    args = args || {};
    args['properties'] = args['properties'] || {};

    args['properties']['collision'] = args['properties']['collision'] === void 0;
    args['properties']['color'] = args['properties']['color'] || '#fff';
    args['properties']['effect'] = args['properties']['effect'] || {};
    args['properties']['effect-stat'] = args['properties']['effect-stat'] || 'health';
    args['properties']['height'] = args['properties']['height'] !== void 0
      ? args['properties']['height']
      : 25;
    args['properties']['type'] = args['properties']['type'] || 'stone';
    args['properties']['width'] = args['properties']['width'] !== void 0
      ? args['properties']['width']
      : 25;
    args['properties']['x'] = args['properties']['x'] || 0;
    args['properties']['y'] = args['properties']['y'] || 0;

    rpg_world_dynamic.push(args['properties']);
}

var rpg_characters = [];
var rpg_particles = [];
var rpg_world_dynamic = [];
var rpg_world_static = [];
<|endoftext|>


<commit_before>var numAdsToDisplay = 6;

var adList = [];
var urlPrefix = "http://www.wilderhood.com/trip/";
var imgURLPrefix = "http://az741737.vo.msecnd.net/wilderhood-public/medium/";
adList.push({link: "HERPING AND MACRO PHOTOGRAPHY WORKSHOP - AGUMBE", image: "BikeNHike/Trip/Agumbe/BikeNHike_Agumbe_1.jpg", text: "HERPING AND MACRO PHOTOGRAPHY WORKSHOP", keywords: ["Agumbe", "Reptiles", "Monsoon Destinations"]});
adList.push({link: "GOA - IN RAINS", image: "BirdWing/Trip/Goa/Goa.jpg", text: "GOA - IN RAINS", keywords: ["Chorla Ghats", "Monsoon Destinations", "Reptiles"]});
adList.push({link: "Explore Wayanad", image: "MysticWild/Trip/Wayanad/1.jpg", text: "EXPLORE WAYANAD", keywords: ["Wayanad", "Monsoon Destinations", "Reptiles"]});
adList.push({link: "BHANDHAVGARH PHOTO TOUR", image: "MysticWild/Trip/Bandhavgarh/1.jpg", text: "BHANDHAVGARH PHOTO TOUR", keywords: ["Bandhavgarh", "Tiger Destinations", "Mammal Destinations", "Wildlife Destinations"]});
adList.push({link: "RAINFOREST RENDEZVOUS - PHOTOGRAPHY TOUR OF GOA", image: "Darter/Trip/Goa/Goa.jpg", text: "RAINFOREST RENDEZVOUS - PHOTOGRAPHY TOUR OF GOA", keywords: ["Chorla Ghats", "Monsoon Destinations", "Reptiles"]});
adList.push({link: "HERPING AND MACRO PHOTOGRAPHY WORKSHOP - COORG", image: "BikeNHike/Trip/Coorg/BikeNHike_Coorg_1.jpg", text: "HERPING AND MACRO PHOTOGRAPHY WORKSHOP - COORG", keywords: ["Coorg", "Monsoon Destinations", "Reptiles"]});
adList.push({link: "MOUNTAINS AND MONASTERIES - A PHOTOGRAPHY TOUR OF LADAKH", image: "Darter/Trip/Ladakh/Ladakh.jpg", text: "MOUNTAINS AND MONASTERIES - A PHOTOGRAPHY TOUR OF LADAKH", keywords: ["Ladakh", "Travel Destinations", "Landscape Destinations"]});
adList.push({link: "HEART OF THE HIMALAYAS - PHOTOGRAPHY TOUR IN LAHAUL & SPITI", image: "Darter/Trip/Lahaul/Spiti.jpg", text: "HEART OF THE HIMALAYAS - PHOTOGRAPHY TOUR IN LAHAUL & SPITI", keywords: ["Lahaul and Spiti", "Travel Destinations"]});
adList.push({link: "CAMBODIA PHOTOGRAPHY TOUR - TEMPLES OF ANGKOR WAT & BEYOND", image: "Darter/Trip/Cambodia/Cambodia.jpg", text: "CAMBODIA PHOTOGRAPHY TOUR - TEMPLES OF ANGKOR WAT & BEYOND", keywords: ["Cambodia", "Travel Destinations", "Landscape Destinations"]});

var sponsoredList = [];
/*sponsoredList.push({link: "http://wilderhood.com", image: "Banner.jpg", text: "Ad Text"});
sponsoredList.push({link: "http://wilderhood.com", image: "bml.jpg", text: "Ad Text1"});
sponsoredList.push({link: "http://wilderhood.com", image: "jlr.jpg", text: "Ad Text1"});*/

function toTitleCase(str)
{
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

function preprocess(dataList)
{
	for(var ii=0; ii<dataList.length; ++ii)
	{
		var data = dataList[ii];
		data.text = toTitleCase(data.text);
	}
}

function getBaseURL() {
   return location.protocol + "//" + location.hostname +
      (location.port && ":" + location.port) + "/";
}

function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}

function createElementWithString(htmlStr)
{
	var divNode = document.createElement("div");
	divNode.innerHTML = htmlStr;
	return divNode;
}

function createElementWithDataObj(data, compiledTemplate, localImage)
{
	if(localImage)
		data.image = getBaseURL() + "img/seo/" + data.image;
	else
		data.image = imgURLPrefix + data.image;

	var renderedTemplate = compiledTemplate.render(data);
	return createElementWithString(renderedTemplate);
}

function filterListByKeywords(dataList, keywordsList)
{
	for(var jj=0; jj < keywordsList.length; ++jj)
	{
		keywordsList[jj] = keywordsList[jj].toLowerCase();
	}

	var filteredDataList = [];
	var excludedDataList = [];

	for(var ii=0; ii<dataList.length; ++ii)
	{
		var data = dataList[ii];
		var found = false;
		for(var kk=0; (kk < data.keywords.length) && !found; ++kk)
		{
			var keyword = data.keywords[kk].toLowerCase();
			for(var jj=0; jj < keywordsList.length; ++jj)
			{
				if(keyword == keywordsList[jj])
				{
					found = true;
					break;
				}
			}
		}
		if(found)
			filteredDataList.push(data);
		else
			excludedDataList.push(data);
	}

	var newList = shuffleArray(filteredDataList).slice(0, numAdsToDisplay);
	if(newList.length < numAdsToDisplay)
	{
		newList = newList.concat(shuffleArray(excludedDataList).slice(0, numAdsToDisplay - newList.length));
	}

	return newList;
}

function displayAds()
{

	preprocess(sponsoredList);
	preprocess(adList);

	var seoKeywords = window.seoKeywords || [];

	var $adHolderDiv = $("#seoHolder");
	if(!$adHolderDiv.length)
		return;

	var template = $('#seoTemplate').html();
	var compiledTemplate = Hogan.compile(template);

	//randomize and pick first six
	var randomizedSponsoredList = shuffleArray(sponsoredList).slice(0, numAdsToDisplay);
	var randomizedAdList = filterListByKeywords(adList, seoKeywords);

	var fragment = document.createDocumentFragment();
	if(randomizedSponsoredList.length > 0)
	{
		$(fragment).append(createElementWithString("
SPONSORED

"));
		for(var ii=0; ii<randomizedSponsoredList.length; ++ii)
		{
			var data = randomizedSponsoredList[ii];
			fragment.appendChild(createElementWithDataObj(data, compiledTemplate, true));
		}
		$(fragment).append(createElementWithString("
"));
	}
	else
	{
		$(fragment).append(createElementWithString("
RECOMMENDED TRIPS

"));
	}
	for(var ii=0; ii<randomizedAdList.length; ++ii)
	{
		var data = randomizedAdList[ii];
		data.link = urlPrefix + data.link;
		fragment.appendChild(createElementWithDataObj(data, compiledTemplate, false));
	}
	$adHolderDiv.append(fragment);
}

displayAds();<commit_msg>- Added capability to filter ad list based on months - Prioritizing ads based on keyword order in the post<commit_after>var numAdsToDisplay = 6;

var adList = [];
var urlPrefix = "http://www.wilderhood.com/trip/";
var imgURLPrefix = "http://az741737.vo.msecnd.net/wilderhood-public/medium/";
//Add another key for restricting the ad to be displayed only in those months --> months:["Jan", "Feb"]
adList.push({link: "HERPING AND MACRO PHOTOGRAPHY WORKSHOP - AGUMBE", image: "BikeNHike/Trip/Agumbe/BikeNHike_Agumbe_1.jpg", text: "HERPING AND MACRO PHOTOGRAPHY WORKSHOP", keywords: ["Agumbe", "Reptiles", "Monsoon Destinations"]});
adList.push({link: "GOA - IN RAINS", image: "BirdWing/Trip/Goa/Goa.jpg", text: "GOA - IN RAINS", keywords: ["Chorla Ghats", "Monsoon Destinations", "Reptiles"]});
adList.push({link: "Explore Wayanad", image: "MysticWild/Trip/Wayanad/1.jpg", text: "EXPLORE WAYANAD", keywords: ["Wayanad", "Monsoon Destinations", "Reptiles"]});
adList.push({link: "BHANDHAVGARH PHOTO TOUR", image: "MysticWild/Trip/Bandhavgarh/1.jpg", text: "BHANDHAVGARH PHOTO TOUR", keywords: ["Bandhavgarh", "Tiger Destinations", "Mammal Destinations", "Wildlife Destinations"]});
adList.push({link: "RAINFOREST RENDEZVOUS - PHOTOGRAPHY TOUR OF GOA", image: "Darter/Trip/Goa/Goa.jpg", text: "RAINFOREST RENDEZVOUS - PHOTOGRAPHY TOUR OF GOA", keywords: ["Chorla Ghats", "Monsoon Destinations", "Reptiles"]});
adList.push({link: "HERPING AND MACRO PHOTOGRAPHY WORKSHOP - COORG", image: "BikeNHike/Trip/Coorg/BikeNHike_Coorg_1.jpg", text: "HERPING AND MACRO PHOTOGRAPHY WORKSHOP - COORG", keywords: ["Coorg", "Monsoon Destinations", "Reptiles"]});
adList.push({link: "MOUNTAINS AND MONASTERIES - A PHOTOGRAPHY TOUR OF LADAKH", image: "Darter/Trip/Ladakh/Ladakh.jpg", text: "MOUNTAINS AND MONASTERIES - A PHOTOGRAPHY TOUR OF LADAKH", keywords: ["Ladakh", "Travel Destinations", "Landscape Destinations"]});
adList.push({link: "HEART OF THE HIMALAYAS - PHOTOGRAPHY TOUR IN LAHAUL & SPITI", image: "Darter/Trip/Lahaul/Spiti.jpg", text: "HEART OF THE HIMALAYAS - PHOTOGRAPHY TOUR IN LAHAUL & SPITI", keywords: ["Lahaul and Spiti", "Travel Destinations"]});
adList.push({link: "CAMBODIA PHOTOGRAPHY TOUR - TEMPLES OF ANGKOR WAT & BEYOND", image: "Darter/Trip/Cambodia/Cambodia.jpg", text: "CAMBODIA PHOTOGRAPHY TOUR - TEMPLES OF ANGKOR WAT & BEYOND", keywords: ["Cambodia", "Travel Destinations", "Landscape Destinations"]});

var sponsoredList = [];
/*sponsoredList.push({link: "http://wilderhood.com", image: "Banner.jpg", text: "Ad Text"});
sponsoredList.push({link: "http://wilderhood.com", image: "bml.jpg", text: "Ad Text1"});
sponsoredList.push({link: "http://wilderhood.com", image: "jlr.jpg", text: "Ad Text1"});*/

function toTitleCase(str)
{
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

function toLowerCaseList(list)
{
	if(!list)
		return;

	for(var ii=0; ii < list.length; ++ii)
	{
		list[ii] = list[ii].toLowerCase();
	}
}

function preprocess(dataList)
{
	for(var ii=0; ii<dataList.length; ++ii)
	{
		var data = dataList[ii];
		data.text = toTitleCase(data.text);
		toLowerCaseList(data.keywords);
	}
}

function getBaseURL() {
   return location.protocol + "//" + location.hostname +
      (location.port && ":" + location.port) + "/";
}

function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }
    return array;
}

function createElementWithString(htmlStr)
{
	var divNode = document.createElement("div");
	divNode.innerHTML = htmlStr;
	return divNode;
}

function createElementWithDataObj(data, compiledTemplate, localImage)
{
	if(localImage)
		data.image = getBaseURL() + "img/seo/" + data.image;
	else
		data.image = imgURLPrefix + data.image;

	var renderedTemplate = compiledTemplate.render(data);
	return createElementWithString(renderedTemplate);
}

function filterListByMonths(dataList, currentDate)
{
	var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
	currentMonth = monthNames[currentDate.getMonth()];

	var retList = [];
	for(var ii=0; ii<dataList.length; ++ii)
	{
		var data = dataList[ii];
		var monthsList = data["months"];
		//considered for all months if entry is not present
		//or considered for the months if an entry is present
		if(!monthsList || (monthsList.indexOf(currentMonth) > -1))
			retList.push(data);
	}
	return retList;
}

function isKeywordInDataEntry(data, keyword)
{
	if(!data.keywords)
		return false;
	return data.keywords.indexOf(keyword) > -1;
}

function filterListByKeywords(dataList, keywordsList)
{
	toLowerCaseList(keywordsList);

	//using reverse keyword position in keywordsList as priority
	//if there are two keywords at indices 0, 1 (in a list of length 3)
	//for same data entry, then priority will be (3-0)+(3-1)=5
	var priorityList = [];	//each element is an object with data and priority keys

	function pushPriorityDataIntoPriorityList(iData, priority, priorityList)
	{
		var iDataLink = iData.link;

		//check if data is already present
		for(var ii=0; ii<priorityList.length; ++ii)
		{
			var dataObj = priorityList[ii];
			if(dataObj.data.link == iDataLink)
			{
				dataObj.priority += priority;
				return;
			}
		}

		//not found
		priorityList.push({data: iData, priority: priority});
	}

	//sort the priority list based on the priority index in each list entry
	//with randoming entries in same priority zone
	function getPriorityListSorted(priorityList)
	{
		var samePriorityLists = [];		//its a list of list --> priority as the key to list of data entries for that priority
		var lowestPriorityIndex = Number.POSITIVE_INFINITY;
		var highestPriorityIndex = Number.NEGATIVE_INFINITY;

		//update lowestPriorityIndex, highestPriorityIndex and samePriorityLists
		for(var ii=0; ii<priorityList.length; ++ii)
		{
			var dataObj = priorityList[ii];
			var priority = dataObj.priority;
			if(lowestPriorityIndex > priority)	lowestPriorityIndex = priority;
			if(highestPriorityIndex < priority)	highestPriorityIndex = priority;

			if(!samePriorityLists[priority])	samePriorityLists[priority] = [];
			samePriorityLists[priority].push(dataObj.data);
		}

		var retList = [];
		//shuffle same priority lists and update final list
		for(var ii=highestPriorityIndex; ii >= lowestPriorityIndex; --ii)
		{
			var priorityList = samePriorityLists[ii];
			if(!priorityList)
				continue;	//Might not be present as priorities might not be sequential

			retList = retList.concat(shuffleArray(priorityList));
		}

		return retList;
	}

	function getExcludedListFromPriorityList(totalList, priorityList)
	{
		var excludedList = [];
		for(var jj=0; jj<totalList.length; ++jj)
		{
			var found = false;
			var totalListData = totalList[jj];
			var totalListDataLink = totalListData.link;

			for(var ii=0; ii<priorityList.length; ++ii)
			{
				if(priorityList[ii].data.link == totalListDataLink)
				{
					found = true;
					break;
				}
			}

			if(!found)
				excludedList.push(totalListData);
		}
		return excludedList;
	}

	//keyword order in the post has priority
	var keywordsLength = keywordsList.length;
	for(var jj=0; jj < keywordsLength; ++jj)
	{
		var keyword = keywordsList[jj];
		for(var ii=0; ii<dataList.length; ++ii)
		{
			var data = dataList[ii];
			if(isKeywordInDataEntry(data, keyword))
			{
				//using reverse keyword position as priority
				//if there are two keywords at indices 0, 1 (in a list of length 3),
				//for same data entry, then priority will be (3-0)+(3-1)=5
				pushPriorityDataIntoPriorityList(data, keywordsLength - jj, priorityList);
			}
		}
	}

	var filteredDataList = getPriorityListSorted(priorityList);	//we got priority based shuffled list
	var newList = filteredDataList.slice(0, numAdsToDisplay);
	if(newList.length < numAdsToDisplay)
	{
		var excludedDataList = getExcludedListFromPriorityList(dataList, priorityList);
		newList = newList.concat(shuffleArray(excludedDataList).slice(0, numAdsToDisplay - newList.length));
	}

	return newList;
}

function displayAds()
{
	preprocess(sponsoredList);
	preprocess(adList);

	var seoKeywords = window.seoKeywords || [];
	var currentDate = new Date();

	var $adHolderDiv = $("#seoHolder");
	if(!$adHolderDiv.length)
		return;

	var template = $('#seoTemplate').html();
	var compiledTemplate = Hogan.compile(template);

	//randomize and pick first six
	var randomizedSponsoredList = shuffleArray(sponsoredList).slice(0, numAdsToDisplay);
	var randomizedAdList = filterListByKeywords(filterListByMonths(adList, currentDate), seoKeywords);

	var fragment = document.createDocumentFragment();
	if(randomizedSponsoredList.length > 0)
	{
		$(fragment).append(createElementWithString("
SPONSORED

"));
		for(var ii=0; ii<randomizedSponsoredList.length; ++ii)
		{
			var data = randomizedSponsoredList[ii];
			fragment.appendChild(createElementWithDataObj(data, compiledTemplate, true));
		}
		$(fragment).append(createElementWithString("
"));
	}
	else
	{
		$(fragment).append(createElementWithString("
RECOMMENDED

"));
	}
	for(var ii=0; ii<randomizedAdList.length; ++ii)
	{
		var data = randomizedAdList[ii];
		data.link = urlPrefix + data.link;
		fragment.appendChild(createElementWithDataObj(data, compiledTemplate, false));
	}
	$adHolderDiv.append(fragment);
}

displayAds();<|endoftext|>


<commit_before>/*globals $ */

function listImages(collection, item) {
	// TODO: Check for an initialized datatable & if it exists, destroy it
	//Clear away any existing contents of the table in the DOM
	$('tbody#page-images').empty();
	// Hide the item selector div and display a modal dialogue while the appropriate page image links are retrieved
	$('#itemSelector').hide();
	$('#loading_modal').ajaxStart(function(){
		$(this).modal('show');
	});

	// Check to see if a partial manifest already exists
	var checkServer = $.ajax({
		type: "HEAD",
		url: "/metadata/manifests/" + item + ".xml"
	});
	// If a partial manifest exists, GET it and construct a table with the data returned
	checkServer.done(function() {
		var manifestPromise = $.ajax({
			type: "GET",
			url: "/metadata/manifests/" + item + ".xml",
			dataType: "xml"
		});
		// Create table rows with info retrieved from the server: filename | link to page image | label
		manifestPromise.done(function(xml) {
			// Set the name of the item as the title for the table
			$('#imageTable > h2').append(item);
			// Parse the XML returned by AJAX and build html strings with the data. Add them to the table
			$(xml).find("item").each(function(){
				var tdString = '
'+$(this).children("filename").text()+'		'+$(this).children("label").text()+'
';
				$('#page-images').prepend(tdString);
			});
		});
		// Initialize jquery datatable from DOM table to add pagination, sorting, editing functionality
		manifestPromise.done(function() {
			// dataTable() takes an object with initialization parameters. See dataTable API
			var editableTable = $('#imageDataTable').dataTable({
				"bDestroy":true,
				"bStateSave": true,
				"sPaginationType": "full_numbers",
				"bAutoWidth": false
			});
			// Make the rows editable (this adds another dependency)
			$('td.editable', editableTable.fnGetNodes()).editable(function(value, settings) {
				var aPos = editableTable.fnGetPosition(this);
				editableTable.fnUpdate(value, aPos[0], aPos[1]);
			},
			{
				onblur : "submit"
			});
		});
		// Add an event handler to reset to item selection state
		$('#prev-to-manifest button').one('click', function() {
			// Hide the table, deactivate save, tear down data tables functionality & empty the table
			$('#imageTable').hide();
			$('#jsSave').off();
			$('#imageDataTable').dataTable().fnDestroy();
			$('tbody#page-images').empty();
			$('#imageTable > h2').empty();
			// Run getItems again to get the item list
			getItems($('#select-repo option:selected').attr('value'));
		});

		// When everything is constructed, add save handler, show the div with the table and clear the modal dialogue
		manifestPromise.done(function() {
			$('#jsSave').on("click", function(){
				saveManifest();
			});
			$('#imageTable').show();
			$('#loading_modal').ajaxStop(function(){
				$(this).modal('hide');
			});
		});
	}); // End of manifest exists block

	// If no manifest exists, GET the listing from the sga.mith.org/images directory & build the table from that
	checkServer.fail(function() {
		var remoteDirPromise = $.ajax({
			type: "GET",
			url: "/metadata/xq/image_getter.xquery?coll-id="+collection+"&item="+item,
			dataType: "xml"
		});
		remoteDirPromise.done(function(xml){
			$('#imageTable > h2').append(item);
			$(xml).find("a").each(function(){
				var tdString = '
'+$(this).text()+'
';
				$('#page-images').prepend(tdString);
			});
		});
		remoteDirPromise.done(function() {
			// dataTable() takes an object with initialization parameters. See dataTable API
			var editableTable = $('#imageDataTable').dataTable({
				"bDestroy":true,
				"bStateSave": true,
				"sPaginationType": "full_numbers",
				"bAutoWidth": false
			});
			// Make the rows editable (this adds another dependency)
			$('td.editable', editableTable.fnGetNodes()).editable(function(value, settings) {
				var aPos = editableTable.fnGetPosition(this);
				editableTable.fnUpdate(value, aPos[0], aPos[1]);
			},
			{
				onblur : "submit"
			});
		});
		// Add an event handler to reset to item selection state
		$('#prev-to-manifest button').one('click', function() {
			// Hide the table, deactivate save, tear down data tables functionality & empty the table
			$('#imageTable').hide();
			$('#jsSave').off();
			$('#imageDataTable').dataTable().fnDestroy();
			$('tbody#page-images').empty();
			$('#imageTable > h2').empty();
			// Run getItems again to get the item list
			getItems($('#select-repo option:selected').attr('value'));
		});

		// When everything is constructed, add save handler, show the div with the table and clear the modal dialogue
		remoteDirPromise.done(function() {
			$('#jsSave').on("click", function(){
				saveManifest();
			});
			$('#imageTable').show();
			$('#loading_modal').ajaxStop(function(){
				$(this).modal('hide');
			});
		});

	}); // End of manifest does not exist block
}

function getItems(param) {
	"use strict";
	$('#ajax-loader').ajaxStart(function () {
    	$(this).show();
    	// Make sure the list of items is empty
    	if ($('#ajax-file-manifest').children().length !== 0) {
    		$('#ajax-file-manifest').empty();
    	}
    });
	var getItemPromise = $.ajax({
		type: 'GET',
		url: '/metadata/xq/dir_parser.xquery?coll-id=' + param,
		dataType: 'xml',
		timeout: 30000
	});
	getItemPromise.done(function(xml) {
        if($(xml).find('error').length !== 0) {
            var errorMsg = '
×'+$(xml).find('error').text()+' Please make sure the correct holdings information has been selected. [HTTP status code '+$(xml).find('error').attr('http-status-code')+']
';
           $('.container').prepend(errorMsg);
           $(".alert").alert();
           // $('#next-to-manifest button').on("click", function() {
           //          window.getItems($('#institution-code .xforms-value').text());
           //      });
        }
        else {
        var arr = [];
        $(xml).find("a").each(function () {
            arr.push($(this).attr("href"));
        });
        arr.shift();
        var all_items = $.map(arr, function(n){
            return n.split("-")[1];
        });
        var i,
            len = all_items.length,
            out = [],
            obj = {};
        for (i=0;i < len; i++){
            obj[all_items[i]] = 0;
        }
        for (i in obj){
            out.push(i);
        }
        $.map(out, function(val){
            return $('#ajax-file-manifest').prepend('
'+ val + '
' );
        });
    }
    });
	// Create an event listener on each li in the newly-created list of items
	getItemPromise.done(function () {
		$('.sga-item').on('click', 'a', function() {
			listImages($('#select-repo option:selected').attr('value'), $(this).parent().attr('id'));
			});
	});
	// Clean-up and show the list of items returned
	getItemPromise.done(function() {
		// Don't show an empty list
		if ($('#ajax-file-manifest').children().length !== 0) {
			// Disable the library selector --- don't want to change collections now that we have items
			$('#itemSelector').show();
			$('#select-repo select').attr('disabled', 'disabled');
			/* Unload the event listener on the image manifest button
			Don't want to fetch items again unless the load action fails */
			$('#next-to-manifest button').off();
		} else {
			// Need some error catching here
		}
		$('#ajax-loader').ajaxStop(function() {
			$(this).hide()
			});
	});
}

function setImageEventListener() {
	"use strict";
// Add event listener for image manifest section
    $('#next-to-manifest button').on("click", function () {
    window.getItems($('#select-repo option:selected').attr('value'));
});
}

function saveManifest() {
    var xmlString = '<?xml version="1.0" encoding="UTF-8"?><items>';
    var data = $('#imageDataTable').dataTable().fnGetData();
    $.each(data, function(index, value){
        xmlString += '<item id="'+ $('#imageTable > h2').text()+'"><filename>'+value[0]+'</filename>'+value[2]+'</item>';
    });
    xmlString += '</items>';
    var savePromise = $.ajax({
        type: "PUT",
        url: "/metadata/manifests/"+$('#itemID').text()+".xml",
        contentType: "application/xml",
        data: xmlString
    });
    savePromise.done(function(){
         var saveMsg = '
×Saved!
';
         $('#msgPlaceHolder').append(saveMsg);
         $(".alert").alert();
         window.setTimeout(function() { $(".alert-success").alert('close'); }, 2000);
    });
}

$(document).ready(
    function () {
        "use strict";

        // Do some basic re-styling of the page---for aesthetic reasons only
        $("div.container").css("margin-top", "40px");
        $("textarea.xforms-value").addClass('input-xlarge').css('height', '150px');

        // Add classes to use Twitter bootstrap
        $("button").addClass('btn');
        $(".navbar button").addClass("btn-inverse");
        // Emphasize certain buttons
        $("#img-to-finish button").addClass("btn-large btn-success");
        $("#next-to-manifest button").addClass("btn-primary btn-large");
        $("#surrogate-to-finish button").addClass("btn-large btn-success");
        $('.xforms-submit button').addClass('btn btn-primary btn-large');

        // Substitute attractive Twitter bootstrap + FontAwesome tooltips for ugly XSLTForms ones
        $(".xforms-required-icon").replaceWith('');
        $(".xforms-alert-icon").replaceWith('');
        // Tweak the display of the new icons
        $(".icon-large").css("display", "inline");
        // Activate the tooltip function on links
        $("a").popover();

        // Add placeholder text to the form
        $("#main-title input").attr("placeholder", "e.g., Frankenstein Notebook A");
        $("#creation-date input").attr("placeholder", "e.g., 1815");
        $("#item-label textarea").attr("placeholder", "Fragment of manuscript of Frankenstein (1818) (Draft Notebook A) containing parts of chapters 3-14 (plus further chapters unidentified)");
        $("#lib-collection input").attr("placeholder", "The Abinger Papers, 1780-1937");
        $("#lib-idno input").attr("placeholder", "MS. Abinger c. 56 ");
        $("#physical-extent input").attr("placeholder", "163 leaves");
        $("#physical-support textarea").attr("placeholder", "Paper with watermark: anchor in a circle with star on top, countermark B-B with trefoil similar to Moschin, Anchor N 1680, 1570-1585.");
        $("#foliation-orig textarea").attr("placeholder", "Folio numbers were added in brown ink ca. 1720-1730 in the upper right corner of all recto-pages.");
        $('#physical-condition textarea').attr("placeholder", "The manuscript shows signs of damage from water and mould on its outermost leaves.");
        $("#manu-hands textarea").attr("placeholder", "The manuscript is written in two contemporary hands. Hand I writes ff. 1r-22v and hand II ff. 23 and 24.");
        $("#metadata-creator input").attr("placeholder", "Liz Denlinger");
        $("#source textarea").attr("placeholder", "Oxford, Bodleian Library, Finding aid for MS. Abinger c. 56");
        $("#surrogate1 textarea").attr("placeholder", "Shelley, Mary W, and Charles E. Robinson. The Frankenstein Notebooks. New York: Garland Pub, 1996. Print.");
        $("#who input").attr("placeholder", "Charles Carter");
        $("#revision textarea").attr("placeholder", "Added more detailed information about hands");
        $("#change-repeat input").attr("placeholder", "Click to edit");

        // Hide elements that will be used later for AJAX functionality
        $('#itemSelector').hide();
        $('#imageTable').hide();
        $('#ajax-loader').hide();

        $(".fancybox").fancybox();
        setImageEventListener();
    }
);

$(window).load(function() {
// If not a blank form (loading existing data), disable the repository selector
        if(location.pathname.search(/edit/) !== -1) {
            $('#select-repo select').attr('disabled', 'disabled');
	}
//Temporary hack to workaround cross browser XSLTForms bug(?)
        $('#metadata-creator').removeClass('xforms-disabled');
        $('#foliation-orig').removeClass('xforms-disabled');
        $('#foliation-mod').removeClass('xforms-disabled');

});<commit_msg>HOTFIX: restore lightbox functionality on image lists from new manifest<commit_after>/*globals $ */

function listImages(collection, item) {
	// TODO: Check for an initialized datatable & if it exists, destroy it
	//Clear away any existing contents of the table in the DOM
	$('tbody#page-images').empty();
	// Hide the item selector div and display a modal dialogue while the appropriate page image links are retrieved
	$('#itemSelector').hide();
	$('#loading_modal').ajaxStart(function(){
		$(this).modal('show');
	});

	// Check to see if a partial manifest already exists
	var checkServer = $.ajax({
		type: "HEAD",
		url: "/metadata/manifests/" + item + ".xml"
	});
	// If a partial manifest exists, GET it and construct a table with the data returned
	checkServer.done(function() {
		var manifestPromise = $.ajax({
			type: "GET",
			url: "/metadata/manifests/" + item + ".xml",
			dataType: "xml"
		});
		// Create table rows with info retrieved from the server: filename | link to page image | label
		manifestPromise.done(function(xml) {
			// Set the name of the item as the title for the table
			$('#imageTable > h2').append(item);
			// Parse the XML returned by AJAX and build html strings with the data. Add them to the table
			$(xml).find("item").each(function(){
				var tdString = '
'+$(this).children("filename").text()+'		'+$(this).children("label").text()+'
';
				$('#page-images').prepend(tdString);
			});
		});
		// Initialize jquery datatable from DOM table to add pagination, sorting, editing functionality
		manifestPromise.done(function() {
			// dataTable() takes an object with initialization parameters. See dataTable API
			var editableTable = $('#imageDataTable').dataTable({
				"bDestroy":true,
				"bStateSave": true,
				"sPaginationType": "full_numbers",
				"bAutoWidth": false
			});
			// Make the rows editable (this adds another dependency)
			$('td.editable', editableTable.fnGetNodes()).editable(function(value, settings) {
				var aPos = editableTable.fnGetPosition(this);
				editableTable.fnUpdate(value, aPos[0], aPos[1]);
			},
			{
				onblur : "submit"
			});
		});
		// Add an event handler to reset to item selection state
		$('#prev-to-manifest button').one('click', function() {
			// Hide the table, deactivate save, tear down data tables functionality & empty the table
			$('#imageTable').hide();
			$('#jsSave').off();
			$('#imageDataTable').dataTable().fnDestroy();
			$('tbody#page-images').empty();
			$('#imageTable > h2').empty();
			// Run getItems again to get the item list
			getItems($('#select-repo option:selected').attr('value'));
		});

		// When everything is constructed, add save handler, show the div with the table and clear the modal dialogue
		manifestPromise.done(function() {
			$('#jsSave').on("click", function(){
				saveManifest();
			});
			$('#imageTable').show();
			$('#loading_modal').ajaxStop(function(){
				$(this).modal('hide');
			});
		});
	}); // End of manifest exists block

	// If no manifest exists, GET the listing from the sga.mith.org/images directory & build the table from that
	checkServer.fail(function() {
		var remoteDirPromise = $.ajax({
			type: "GET",
			url: "/metadata/xq/image_getter.xquery?coll-id="+collection+"&item="+item,
			dataType: "xml"
		});
		remoteDirPromise.done(function(xml){
			$('#imageTable > h2').append(item);
			$(xml).find("a").each(function(){
				var tdString = '
'+$(this).text()+'
';
				$('#page-images').prepend(tdString);
			});
		});
		remoteDirPromise.done(function() {
			// dataTable() takes an object with initialization parameters. See dataTable API
			var editableTable = $('#imageDataTable').dataTable({
				"bDestroy":true,
				"bStateSave": true,
				"sPaginationType": "full_numbers",
				"bAutoWidth": false
			});
			// Make the rows editable (this adds another dependency)
			$('td.editable', editableTable.fnGetNodes()).editable(function(value, settings) {
				var aPos = editableTable.fnGetPosition(this);
				editableTable.fnUpdate(value, aPos[0], aPos[1]);
			},
			{
				onblur : "submit"
			});
		});
		// Add an event handler to reset to item selection state
		$('#prev-to-manifest button').one('click', function() {
			// Hide the table, deactivate save, tear down data tables functionality & empty the table
			$('#imageTable').hide();
			$('#jsSave').off();
			$('#imageDataTable').dataTable().fnDestroy();
			$('tbody#page-images').empty();
			$('#imageTable > h2').empty();
			// Run getItems again to get the item list
			getItems($('#select-repo option:selected').attr('value'));
		});

		// When everything is constructed, add save handler, show the div with the table and clear the modal dialogue
		remoteDirPromise.done(function() {
			$('#jsSave').on("click", function(){
				saveManifest();
			});
			$('#imageTable').show();
			$('#loading_modal').ajaxStop(function(){
				$(this).modal('hide');
			});
		});

	}); // End of manifest does not exist block
}

function getItems(param) {
	"use strict";
	$('#ajax-loader').ajaxStart(function () {
    	$(this).show();
    	// Make sure the list of items is empty
    	if ($('#ajax-file-manifest').children().length !== 0) {
    		$('#ajax-file-manifest').empty();
    	}
    });
	var getItemPromise = $.ajax({
		type: 'GET',
		url: '/metadata/xq/dir_parser.xquery?coll-id=' + param,
		dataType: 'xml',
		timeout: 30000
	});
	getItemPromise.done(function(xml) {
        if($(xml).find('error').length !== 0) {
            var errorMsg = '
×'+$(xml).find('error').text()+' Please make sure the correct holdings information has been selected. [HTTP status code '+$(xml).find('error').attr('http-status-code')+']
';
           $('.container').prepend(errorMsg);
           $(".alert").alert();
           // $('#next-to-manifest button').on("click", function() {
           //          window.getItems($('#institution-code .xforms-value').text());
           //      });
        }
        else {
        var arr = [];
        $(xml).find("a").each(function () {
            arr.push($(this).attr("href"));
        });
        arr.shift();
        var all_items = $.map(arr, function(n){
            return n.split("-")[1];
        });
        var i,
            len = all_items.length,
            out = [],
            obj = {};
        for (i=0;i < len; i++){
            obj[all_items[i]] = 0;
        }
        for (i in obj){
            out.push(i);
        }
        $.map(out, function(val){
            return $('#ajax-file-manifest').prepend('
'+ val + '
' );
        });
    }
    });
	// Create an event listener on each li in the newly-created list of items
	getItemPromise.done(function () {
		$('.sga-item').on('click', 'a', function() {
			listImages($('#select-repo option:selected').attr('value'), $(this).parent().attr('id'));
			});
	});
	// Clean-up and show the list of items returned
	getItemPromise.done(function() {
		// Don't show an empty list
		if ($('#ajax-file-manifest').children().length !== 0) {
			// Disable the library selector --- don't want to change collections now that we have items
			$('#itemSelector').show();
			$('#select-repo select').attr('disabled', 'disabled');
			/* Unload the event listener on the image manifest button
			Don't want to fetch items again unless the load action fails */
			$('#next-to-manifest button').off();
		} else {
			// Need some error catching here
		}
		$('#ajax-loader').ajaxStop(function() {
			$(this).hide()
			});
	});
}

function setImageEventListener() {
	"use strict";
// Add event listener for image manifest section
    $('#next-to-manifest button').on("click", function () {
    window.getItems($('#select-repo option:selected').attr('value'));
});
}

function saveManifest() {
    var xmlString = '<?xml version="1.0" encoding="UTF-8"?><items>';
    var data = $('#imageDataTable').dataTable().fnGetData();
    $.each(data, function(index, value){
        xmlString += '<item id="'+ $('#imageTable > h2').text()+'"><filename>'+value[0]+'</filename>'+value[2]+'</item>';
    });
    xmlString += '</items>';
    var savePromise = $.ajax({
        type: "PUT",
        url: "/metadata/manifests/"+$('#itemID').text()+".xml",
        contentType: "application/xml",
        data: xmlString
    });
    savePromise.done(function(){
         var saveMsg = '
×Saved!
';
         $('#msgPlaceHolder').append(saveMsg);
         $(".alert").alert();
         window.setTimeout(function() { $(".alert-success").alert('close'); }, 2000);
    });
}

$(document).ready(
    function () {
        "use strict";

        // Do some basic re-styling of the page---for aesthetic reasons only
        $("div.container").css("margin-top", "40px");
        $("textarea.xforms-value").addClass('input-xlarge').css('height', '150px');

        // Add classes to use Twitter bootstrap
        $("button").addClass('btn');
        $(".navbar button").addClass("btn-inverse");
        // Emphasize certain buttons
        $("#img-to-finish button").addClass("btn-large btn-success");
        $("#next-to-manifest button").addClass("btn-primary btn-large");
        $("#surrogate-to-finish button").addClass("btn-large btn-success");
        $('.xforms-submit button').addClass('btn btn-primary btn-large');

        // Substitute attractive Twitter bootstrap + FontAwesome tooltips for ugly XSLTForms ones
        $(".xforms-required-icon").replaceWith('');
        $(".xforms-alert-icon").replaceWith('');
        // Tweak the display of the new icons
        $(".icon-large").css("display", "inline");
        // Activate the tooltip function on links
        $("a").popover();

        // Add placeholder text to the form
        $("#main-title input").attr("placeholder", "e.g., Frankenstein Notebook A");
        $("#creation-date input").attr("placeholder", "e.g., 1815");
        $("#item-label textarea").attr("placeholder", "Fragment of manuscript of Frankenstein (1818) (Draft Notebook A) containing parts of chapters 3-14 (plus further chapters unidentified)");
        $("#lib-collection input").attr("placeholder", "The Abinger Papers, 1780-1937");
        $("#lib-idno input").attr("placeholder", "MS. Abinger c. 56 ");
        $("#physical-extent input").attr("placeholder", "163 leaves");
        $("#physical-support textarea").attr("placeholder", "Paper with watermark: anchor in a circle with star on top, countermark B-B with trefoil similar to Moschin, Anchor N 1680, 1570-1585.");
        $("#foliation-orig textarea").attr("placeholder", "Folio numbers were added in brown ink ca. 1720-1730 in the upper right corner of all recto-pages.");
        $('#physical-condition textarea').attr("placeholder", "The manuscript shows signs of damage from water and mould on its outermost leaves.");
        $("#manu-hands textarea").attr("placeholder", "The manuscript is written in two contemporary hands. Hand I writes ff. 1r-22v and hand II ff. 23 and 24.");
        $("#metadata-creator input").attr("placeholder", "Liz Denlinger");
        $("#source textarea").attr("placeholder", "Oxford, Bodleian Library, Finding aid for MS. Abinger c. 56");
        $("#surrogate1 textarea").attr("placeholder", "Shelley, Mary W, and Charles E. Robinson. The Frankenstein Notebooks. New York: Garland Pub, 1996. Print.");
        $("#who input").attr("placeholder", "Charles Carter");
        $("#revision textarea").attr("placeholder", "Added more detailed information about hands");
        $("#change-repeat input").attr("placeholder", "Click to edit");

        // Hide elements that will be used later for AJAX functionality
        $('#itemSelector').hide();
        $('#imageTable').hide();
        $('#ajax-loader').hide();

        $(".fancybox").fancybox();
        setImageEventListener();
    }
);

$(window).load(function() {
// If not a blank form (loading existing data), disable the repository selector
        if(location.pathname.search(/edit/) !== -1) {
            $('#select-repo select').attr('disabled', 'disabled');
	}
//Temporary hack to workaround cross browser XSLTForms bug(?)
        $('#metadata-creator').removeClass('xforms-disabled');
        $('#foliation-orig').removeClass('xforms-disabled');
        $('#foliation-mod').removeClass('xforms-disabled');

});<|endoftext|>