code
stringlengths
1
2.08M
language
stringclasses
1 value
/** * Login */ ahoy.page_login = { init: function() { ahoy.validate.bind($('#form_login'), 'partial_site_login_form', function() { return ahoy.post($('#form_login')).action('user:on_login').send(); }); $('#user_login').change(function() { $('#user_password').val(''); }) } }; /** * Register */ ahoy.page_register = { init: function() { ahoy.validate.bind($('#form_register'), 'partial_site_register_form', function() { return ahoy.post($('#form_register')).action('user:on_register').send(); }); } }; /** * Forgot password */ ahoy.page_forgot_pass = { init: function() { var self = ahoy.page_forgot_pass; // Initialize self.validate_form(); }, validate_form: function() { // Validation var on_success = function() { return ahoy.post($('#form_reset_pass')) .action('user:on_password_reset') .success(function(){ $('#reset_pass_form, #reset_pass_success').toggle(); $('#login').val($('#forgot_email').val()); }) .send(); }; var options = { messages: ahoy.page_forgot_password.validate_messages, rules: ahoy.page_forgot_password.validate_rules, submitHandler: on_success }; ahoy.validate.init($('#form_reset_pass'), options); } }; /** * Provide */ ahoy.page_provide = { init: function() { ahoy.validate.bind($('#form_register'), 'partial_site_register_form', function() { return ahoy.post($('#form_register')).action('user:on_register').send(); }); } }; /** * Provide Testimonial */ ahoy.page_provide_testimonial = { init: function() { ahoy.validate.bind($('#form_provide_testimonial_write'), 'partial_provide_write_testimonial_form', function() { return ahoy.post($('#form_provide_testimonial_write')).action('service:on_testimonial_submit') .success(function() { $('#p_provide_testimonial_write_form').hide(); $('#provide_testimonial_write_success').show(); }) .send(); }); } };
JavaScript
/* @require ../frameworks/utility/jquery.gmap3.js; @require ../frameworks/utility/jquery.utility.gmap.js; @require ../behaviors/behavior_upload.js; @require ../behaviors/behavior_provide_hours.js; @require ../behaviors/behavior_provide_radius.js; @require ../behaviors/behavior_field_editor.js; */ ahoy.page_provide_create = { logo_id: null, photo_id: null, init: function() { var self = ahoy.page_provide_create; // Profile field editing ahoy.behavior('#p_profile_form', 'field_editor') .act('apply_validation', [$('#form_provide_create'), 'partial_provide_profile_details', function() { // Success ahoy.post('#form_provide_create').action('bluebell:on_provider_submit') .data('provider_logo', self.logo_id) .data('provider_photo', self.photo_id) .data('redirect', root_url('provide/manage/%s')) .send(); } ]); // Provider work hours $('#p_work_hours_form').behavior(ahoy.behaviors.provide_hours); // Provider work radius $('#p_work_radius_form').provide_radius({ on_complete: function(obj) { $('#provider_service_codes').val('|' + obj.get_nearby_postcodes().join('|') + '|'); }, radius_max: $('#work_radius_max').val(), radius_unit: $('#work_radius_unit').val() }); // Role auto complete ahoy.behavior('#provide_role_name', 'role_select', { on_select: function(obj, value){ $('#provide_role_name').prev('label').text(value); } }); // Select country, populate state ahoy.behavior('#provide_country_id', 'select_country', { state_element_id:'#provide_state_id', after_update: function(obj) { obj.state_element = $('#provide_country_id').parent().next().children().first(); } }); // Marry provide_radius and field_editor functionality $('#profile_details_address').bind('field_editor.field_set', function(e, value) { $('#work_radius_address').val(value).trigger('change'); }); // Add image uploads $('#input_provide_photo').behavior(ahoy.behaviors.upload_image, { link_id: '#link_provide_photo', remove_id: '#link_provide_photo_remove', image_id: '#provide_photo', param_name:'provider_photo', on_success: function(obj, data) { $('#link_provide_photo').hide(); self.photo_id = data.result.id; }, on_remove: function() { $('#link_provide_photo').fadeIn(1000); } }); $('#input_provide_logo').behavior(ahoy.behaviors.upload_image, { link_id: '#link_provide_logo', remove_id: '#link_provide_logo_remove', image_id: '#provide_logo', param_name:'provider_logo', on_success: function(obj, data) { $('#link_provide_logo').hide(); self.logo_id = data.result.id; }, on_remove: function() { $('#link_provide_logo').fadeIn(1000); $('#provide_logo').hide(); return false; } }); } };
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Ahoy module */ var Ahoy = (function(ahoy, $){ ahoy.version = 1.1; return ahoy; }(Ahoy || {}, jQuery)) // Adapter for Ahoy v1.0 backward compatability // var ahoy = Ahoy; ahoy.validate = { }; ahoy.behaviors = { }; ahoy.validate.bind = function(form, code, on_success, extra_options) { extra_options = $.extend(true, ahoy.validate.default_options, extra_options); return ahoy.validation(form, code, extra_options).success(on_success).bind(); } ahoy.validate.add_rule = function(object, code) { return ahoy.form.define_field(code, object); } ahoy.validate.set_rules = function(form, code, is_remove) { if (is_remove) ahoy.validation(form).remove_rules(code); else ahoy.validation(form).add_rules(code); } ahoy.validate.init = function(element, set_options, ignore_defaults) { set_options = $.extend(true, ahoy.validate.default_options, set_options); var obj = ahoy.validation(element, null, set_options); if (ignore_defaults) obj._options = set_options; obj.bind(); }; /** * Behaviors * @deprecated in favour of jQuery.widget * * Usage: * ahoy.behavior('#element', 'behavior_name', { config: 'items' }) * .act('misbehave', [params]); * * ahoy.behavior('#element').act('misbehave'); */ ahoy.behavior = function(element, name, config) { element = $(element); if (!config) config = { }; // Assume this is already bound if (!name) return new ahoy.behavior_object(element); // Behavior exists, so use it if (ahoy.behaviors[name]) { element.behavior(ahoy.behaviors[name], config); return new ahoy.behavior_object(element); } // Behavior does not appear to exist, let's try a lazy load var script_path = 'javascript/behaviors/behavior_%s.js'; var script_file = asset_url(script_path.replace('%s', name)); return $.getScript(script_file, function() { element.behavior(ahoy.behaviors[name], config); }); }; ahoy.behavior_object = function(element) { this._element = element; this.act = function(action, params) { this._element.behavior(action, params); return this; }; }; /** * jquery.behavior JavaScript Library v2.0 * http://rodpetrovic.com/jquery/behavior * * Copyright 2010, Rodoljub Petrović * Licensed under the MIT * http://www.opensource.org/licenses/mit-license.php * * Contributors: * - Matjaž Lipuš * * Date: 2011-05-15 * * // 1. Create behavior: * function BadBehavior(element, config) { * this.misbehave = function () { * alert('Oh behave!'); * } * } * * // 2. Attach behavior: * $('.bad-behavior').behavior(BadBehavior); * * // 3. Use behavior: * $('.bad-behavior').behavior('misbehave'); // alert('Oh behave!') * */ (function ($, undef) { "use strict"; function attach($jq, Behavior, config) { $jq.each(function () { if (!this.behavior) { this.behavior = {}; } $.extend(this.behavior, new Behavior(this, config)); }); } function each($jq, property, attributes) { $jq.each(function () { var behavior = this.behavior; if (behavior && behavior[property] !== undef) { if (typeof behavior[property] === "function") { behavior[property].apply(behavior, attributes || []); } else { behavior[property] = attributes; } } }); } $.fn.behavior = function (a, b) { var type = typeof a; if (type === "function") { attach(this, a, b || {}); return this; } if (type === "string") { each(this, a, b); return this; } return this.get(a || 0).behavior; }; }(jQuery));
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Form Validation * * Overrides the core ahoy.validate default options, * adds inline error placement */ ahoy.validate.default_options = { ignore:":not(:visible, :disabled), .ignore_validate", highlight: function(element, errorClass, validClass) { $(element).removeClass('valid').addClass('error'); }, unhighlight: function(element, errorClass, validClass) { $(element).removeClass('error').addClass('valid'); }, success: function(label) { if (!label.closest('form').hasClass('nice')) label.closest('.form-field').removeClass('error'); label.remove(); }, onkeyup: false, errorClass: 'error', errorElement: 'small', errorPlacement: function(error, element) { var self = ahoy.validate; element.after(error); if (element.closest('form').hasClass('nice')) ahoy.validate.place_label(error, element, {left: 5, top: 8}); else element.closest('.form-field').addClass('error'); }, showErrors: function(errorMap, errorList) { var self = ahoy.validate; this.defaultShowErrors(); setTimeout(self.place_labels, 0); }, submitHandler: function(form) { form.submit(); } }; ahoy.validate.place_label = function(label, element, hard_offset) { var offset = label.offset(); hard_offset = (hard_offset) ? hard_offset : { top:0, left:0 }; offset.top = element.offset().top; offset.left = element.offset().left + (element.outerWidth()+hard_offset.left); label.offset(offset); }; ahoy.validate.place_labels = function() { jQuery('form.nice small.error').each(function() { var label = $(this); if (label.css('position')=="relative") return; var element = $(this).prev(); ahoy.validate.place_label(label, element, {left: 5, top: 8}); }); }; jQuery(window).resize(function(){ ahoy.validate.place_labels(); }); // Poll for dom changes var ahoyform_attributes = { body_height: 0, poll_interval: 1000 }; var ahoyform_poll = setInterval(ahoyform_is_dom_resized, ahoyform_attributes.poll_interval); function ahoyform_is_dom_resized() { $body = jQuery('body'); if(ahoyform_attributes.body_height != $body.height()) { ahoyform_attributes.body_height = $body.height(); jQuery(window).trigger('resize'); } } /** * IE Compatibility */ jQuery(document).ready(function($){ // Alternate placeholder script for IE8 and prior (sad) if ($("html").is(".lt-ie9")) { $("[placeholder]").focus(function() { var input = $(this); if (input.val() == input.attr("placeholder")) { input.val(""); input.removeClass("placeholder"); } }).blur(function() { var input = $(this); if (input.val() == "" || input.val() == input.attr("placeholder")) { input.addClass("placeholder"); input.val(input.attr("placeholder")); } }).blur(); $("[placeholder]").parents("form").submit(function() { $(this).find("[placeholder]").each(function() { var input = $(this); if (input.val() == input.attr("placeholder")) { input.val(""); } }) }); } });
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Provider work hours behavior */ ahoy.behaviors.provide_hours = function(element, config) { var self = this; self.element = element = $(element); var defaults = { specific_container:'#work_hours_specific', general_container:'#work_hours_general', general_select_class: 'general_select', toggle_link:'#link_work_hours', apply_all_link:'#link_apply_all', row_selector:'div.row', use_general: true }; self.config = config = $.extend(true, defaults, config); self.toggle_link = $(self.config.toggle_link); self.apply_all_link = $(self.config.apply_all_link); self.specific = $(self.config.specific_container); self.general = $(self.config.general_container); self.general_select = self.general.find('select.'+self.config.general_select_class); self.general_select_start = self.general.find('select.'+self.config.general_select_class+'_start'); self.general_select_end = self.general.find('select.'+self.config.general_select_class+'_end'); this.init = function() { if (self.config.use_general) { // Toggle link self.toggle_link.click(self.specific_toggle); // Bind general hours self.general_select.change(function() { self.select_general_days($(this).val()); }); self.select_general_days(self.general_select.val()); // Automatically apply all for general time dropdowns self.general_select_start.change(function() { $('#weekday_1').find('select:first').val($(this).val()); self.click_apply_all(); }); self.general_select_end.change(function() { $('#weekday_1').find('select:last').val($(this).val()); self.click_apply_all(); }); } else { self.specific.show(); self.general.hide(); self.validate_times(); } // Apply all self.apply_all_link.click(self.click_apply_all); // Bind specific hours self.check_all_days(); self.specific.find(self.config.row_selector + ' input[type=checkbox]').change(function() { self.check_day($(this).closest(self.config.row_selector)); }); }; this.check_all_days = function() { self.specific.find(self.config.row_selector).each(function() { self.check_day($(this)); }); }; this.check_day = function(row_element) { row_element = $(row_element); var checkbox = row_element.find('input[type=checkbox]'); if (checkbox.is(':checked')) row_element.find('div.hide').hide().end().find('div.show').show(); else { row_element.find('div.hide').show().end().find('div.show').hide().end().find('select').val(0); } }; this.select_general_days = function(value) { switch (value) { case '0': // Mon - Sun $('#weekday_1, #weekday_2, #weekday_3, #weekday_4, #weekday_5, #weekday_6, #weekday_7').find('input[type=checkbox]').attr('checked', true); break; case '1': // Mon - Fri $('#weekday_1, #weekday_2, #weekday_3, #weekday_4, #weekday_5').find('input[type=checkbox]').attr('checked', true); $('#weekday_6, #weekday_7').find('input[type=checkbox]').attr('checked', false); break; case '2': // Mon - Sat $('#weekday_1, #weekday_2, #weekday_3, #weekday_4, #weekday_5, #weekday_6').find('input[type=checkbox]').attr('checked', true); $('#weekday_7').find('input[type=checkbox]').attr('checked', false); break; case '3': // Sat - Sun $('#weekday_6, #weekday_7').find('input[type=checkbox]').attr('checked', true); $('#weekday_1, #weekday_2, #weekday_3, #weekday_4, #weekday_5').find('input[type=checkbox]').attr('checked', false); break; case '4': self.general_select.val(0); self.specific_toggle(); break; } self.check_all_days(); }; this.specific_toggle = function() { self.general.toggle(); self.specific.toggle(); self.toggle_link.toggleText(); }; this.click_apply_all = function() { var start_val = $('#weekday_1').find('select:first').val(); var last_val = $('#weekday_1').find('select:last').val(); self.specific.find(self.config.row_selector).each(function() { $(this).find('select:first:visible').val(start_val); $(this).find('select:last:visible').val(last_val); }); }; this.validate_times = function() { self.specific.find(self.config.row_selector).each(function() { var start = Math.round($(this).find('select:first').val().replace(/:/g, '')); var end = Math.round($(this).find('select:last').val().replace(/:/g, '')); if (start >= end) $(this).find('input[type=checkbox]').attr('checked', false); else $(this).find('input[type=checkbox]').attr('checked', true); }); }; this.init(); };
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Autogrow Textarea behavior * * Usage: ahoy.behavior('#textarea', 'autogrow'); * */ ahoy.behaviors.autogrow = function(element, config) { var self = this; element = $(element); var defaults = { offset: 30 // Height offset }; self.config = config = $.extend(true, defaults, config); this.min_height = element.height(); this.line_height = element.css('line-height'); this.shadow = $('<div></div>'); this.shadow.css({ position: 'absolute', top: -10000, left: -10000, width: element.width(), fontSize: element.css('font-size'), fontFamily: element.css('font-family'), lineHeight: element.css('line-height'), resize: 'none' }).appendTo(document.body); this.update = function () { var val = element.val().replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/&/g, '&amp;').replace(/\n/g, '<br/>'); self.shadow.html(val); $(this).css('height', Math.max(self.shadow.height() + self.config.offset, self.min_height)); }; element.change(self.update).keyup(self.update).keydown(self.update); this.update(); };
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Profile field editing behavior * * Hot swappable label / fields. * * HTML Example: * * <div class="form-field name"> * <!-- The label must come before the div.edit container --> * <?=form_label('Your name', 'name')?> * <div class="edit"><?=form_input('name', '', 'placeholder="Your name please" id="name"')?></div> * </div> * * Usage: * * ahoy.behavior('#form_or_container', 'field_editor'); * */ ahoy.behaviors.field_editor = function(element, config) { var self = this; self.element = element = $(element); var defaults = { edit_selector:'div.edit', // Edit input container field_selector:'div.form-field', // Form field container on_set_field: null, // Callback when field is set, for single field use event: field_editor.field_set implode_char: ', ' // The character to separate multiple inputs }; self.config = config = $.extend(true, defaults, config); this.form = $(config.form_id); this.active_field = null; this.is_loaded = false; this.init = function() { self.reset_profile_fields(); // Bind click label field // returns false to stop clickOutside plugin element.find('label').click(function() { self.click_profile_field(this); return false; }); self.populate_data(); self.is_loaded = true; }; this.populate_data = function() { element.find(config.edit_selector).each(function() { self.set_profile_field($(this)); }); }; this.click_profile_field = function(obj) { // If a field is currently being edited, // set it or prevent other field edits if (self.active_field) { if (self.set_profile_field(self.active_field)===false) return; } // Find the edit container, show, focus and cache var edit = $(obj).hide().parent().find(self.config.edit_selector).show(); edit.find('input:first').focus(); self.active_field = edit; // Use clickOutside plugin for autosave setTimeout(function() { edit.clickOutside(function() { self.set_profile_field(edit); }) }, 1); // Detect keypress events edit.find('input').bind('keypress', function(e){ var code = (e.keyCode ? e.keyCode : e.which); if (code == 13) // ENTER { self.set_profile_field($(this).closest(self.config.edit_selector)); return false; } else if (code == 9) // TAB { var next_field; var field = $(this).closest(self.config.field_selector); // Revert to standard tabbing for fields with multiple inputs if (field.find('input').length > 1) return; self.set_profile_field($(this).closest(self.config.edit_selector)); if (e.shiftKey) next_field = self.dom_shift(field, self.config.field_selector, -1); // Move back else next_field = self.dom_shift(field, self.config.field_selector, 1); // Move forward next_field.find('label').trigger('click'); return false; } }); }; // Find the next / previous field regardless of its DOM position this.dom_shift = function(obj, selector, shift) { var all_fields = element.find(selector); var field_index = all_fields.index(obj); var next_field = all_fields.eq(field_index + shift); return next_field; }; // Hides all fields and shows their labels this.reset_profile_fields = function() { self.element.find('label').each(function() { $(this).show().parent().find(self.config.edit_selector).hide(); }); }; // Determine a friendly value to display, // if we have multiple fields string them together nicely this.get_field_value = function(inputs) { var value = ""; if (inputs.length > 1) { jQuery.each(inputs, function(k,v) { if ($.trim($(this).val()) != "") { if ($(this).is('select')) { value += (k==0) ? $(this).find('option:selected').text() : self.config.implode_char + $(this).find('option:selected').text(); } else { value += (k==0) ? $(this).val() : self.config.implode_char + $(this).val(); } } }); } else value = $.trim(inputs.first().val()); return value; }; // Set a profile field, must return true // If fields do not validate, return false this.set_profile_field = function(obj) { self.reset_profile_fields(); var inputs = obj.find('input, select'); var field = inputs.first(); var label = field.closest('.edit').prev('label'); var value = self.get_field_value(inputs); // Has the field been populated or emptied? // Display value or placeholder for latter if (value != "") label.text(value).addClass('populated'); else label.text(field.attr('placeholder')).removeClass('populated'); // Reset cache variable self.active_field = null; // Cancel clickOutside plugin $('body').unbind('click'); // Events if (self.is_loaded) { obj.trigger('field_editor.field_set', [value]); self.config.on_set_field && self.config.on_set_field(self, obj, value); } // Validates true return true; }; // Apply validation to our fields using an ahoy.validate code // (Implement Wins: Flawless victory) this.apply_validation = function(form, code, on_success) { ahoy.validate.bind(form, code, on_success, { onfocusout: false, // Removed because it looks messy ignore: null, // Do not ignore hidden fields // Binding to the invalid handler here instead // of errorPlacement so we don't conflict invalidHandler: function(form, validator) { var errors = validator.numberOfInvalids(); if (errors) { // Only show the first error var el = validator.errorList[0].element; // Target the label that should perfectly preceed the .edit container var label = $(el).closest('div.edit').prev().trigger('click'); // Trash the other error labels because they are annoying setTimeout(function() { $('small.error').filter(':hidden').remove(); }, 500); } } }); }; this.init(); };
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Provider work hours behavior */ ;(function ($, window, document, undefined) { $.widget("utility.provide_radius", { version: '1.0', options: { radius_max: 100, radius_unit: 'km', map_id: '#work_radius_map', // Map object (see map behavior) address_field_id: '#work_radius_address', // Address field used for geocoding area_list_id: '#work_radius_area_list', // Unordered list to populate with nearby areas on_complete: null // Callback after lookup is complete }, // Internals _nearby_postcodes: [], _country: null, _postcode: null, _radius: 25, _map: null, _address_field: null, _address: null, _latlng: null, _area_list: null, _init: function() { var self = this; this._map = $(this.options.map_id); this._address_field = $(this.options.address_field_id); this._area_list = $(this.options.area_list_id); // Map self._map.gmap({ distance_type: this.options.radius_unit, allow_drag: false, allow_scrollwheel: false, alow_dbl_click_zoom: false }); // Slider self.bind_slider(); // Detect address changes self._address_field.change(function() { self.populate_address($(this).val()); }); }, bind_slider: function() { var self = this; $('#work_radius_slider').slider({ step:5, min:1, max:parseInt(self.options.radius_max)+1, value:20, change:function(event,ui) { if (self._address) { self._radius = (ui.value <= 1) ? 1 : ui.value-1; self._map .gmap('clear_circles') .gmap('show_circle_at_address_object', self._address, self._radius) .gmap('autofit'); $('#work_radius_radius span').text(self._radius); self.find_nearby_areas(self._postcode, self._country, self._radius); } }, slide:function(event,ui) { var radius = (ui.value <= 1) ? 1 : ui.value-1; $('#work_radius_radius span').text(radius); } }); }, populate_address: function(address_string) { var self = this; if ($.trim(address_string)=="") { self.disable_control(); return } self.enable_control(); $.waterfall( function() { var deferred = $.Deferred(); self._map.gmap('get_object_from_address_string', address_string, function(address){ self._address = address; self._latlng = self._map.gmap('get_latlng_from_address_object', self._address); deferred.resolve(); }); return deferred; }, function() { self._map .gmap('align_to_address_object', self._address) .gmap('add_marker_from_address_object', self._address, 'provider_tag') .gmap('show_circle_at_address_object', self._address, self._radius) .gmap('autofit'); self._country = self._map.gmap('get_value_from_address_object', self._address, 'country'); self._postcode = self._map.gmap('get_value_from_address_object', self._address, 'postal_code'); return $.Deferred().resolve(); }, function() { self.find_nearby_areas(self._postcode, self._country, self._radius); return $.Deferred().resolve(); } ); }, find_nearby_areas: function(postcode, country, radius) { var self = this; self._nearby_postcodes = []; // Reset main postal code array var cache = {}; // Cache for duplicates ahoy.post().action('location:on_get_nearby_areas').data({country:country, postcode:postcode, radius:radius, unit:self.options.radius_unit}).success(function(raw, data) { var result = $.parseJSON(data); if (result && result.postalCodes) { self._area_list.empty(); $.each(result.postalCodes, function(key, area){ // Add unique post code to array var duplicate_exists = false; for (var i=0; i < self._nearby_postcodes.length; i++) { if (self._nearby_postcodes[i]==area.postalcode) duplicate_exists = true; } if (!duplicate_exists) self._nearby_postcodes.push(area.postalcode); // Remove duplicates, add to area list if (!cache[area.adminCode1+area.name]) { cache[area.adminCode1+area.name] = true; var item = $('<li />').text(area.name+', '+area.adminCode1).appendTo(self._area_list); } }); } else self._area_list.empty().append($('<li />').text(self._area_list.attr('data-empty-text'))); // End point self.options.on_complete && self.options.on_complete(self); }).send(); }, get_nearby_postcodes: function() { return this._nearby_postcodes; }, disable_control: function() { $('#work_radius_disabled').fadeIn(); $('#work_radius').addClass('disabled'); }, enable_control: function() { $('#work_radius_disabled').fadeOut(); $('#work_radius').removeClass('disabled'); } }) })( jQuery, window, document );
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Request submit behavior */ ahoy.behaviors.request_submit = function(element, config) { var self = this; self.element = element = $(element); // Should be the form tag var defaults = { on_submit: null }; self.config = config = $.extend(true, defaults, config); this.init = function() { self.validate_form(); self.bind_required_by(); // Alternative time $('#link_request_alt_time').click(self.click_alt_time); // Remote location $('#location_remote').change(function() { self.click_location_remote(this); }); self.click_location_remote('#location_remote'); // Add photos $('#input_add_photos').behavior(ahoy.behaviors.upload_image_multi, {link_id:'#link_add_photos', param_name:'request_images[]'}); }; // Required by logic this.bind_required_by = function() { var required_by = element.find('section.required_by'); var checked = required_by.find('ul.radio_group label input:checked'); self.click_required_by(checked); required_by.find('label input').change(function() { self.click_required_by(this); }); }; this.click_required_by = function(element) { var label = $(element).parent(); var required_by = self.element.find('section.required_by'); required_by.find('label').removeClass('selected'); required_by.find('.radio_expand').hide(); label.addClass('selected').next('.radio_expand').show(); }; this.click_alt_time = function() { var container = self.element.find('.firm_date_secondary').toggle(); container.find('select').each(function() { $(this).trigger('change'); }); }; this.click_location_remote = function(obj) { var checked = $(obj).is(':checked'); var location = $('#request_location'); location.attr('disabled', checked); if (checked) { location.val('').removeClass('error valid').next('.float_error').remove(); } }; this.validate_form = function(extra_rules, extra_messages) { var options = { messages: ahoy.partial_request_simple_form.validate_messages, rules: ahoy.partial_request_simple_form.validate_rules, submitHandler: self.submit_form }; if (extra_rules) options.rules = $.extend(true, options.rules, extra_rules); if (extra_messages) options.messages = $.extend(true, options.messages, extra_messages); ahoy.validate.init(self.element, options); }; this.submit_form = function(form) { if (!config.on_submit) return false; self.check_category(function(result){ $('#request_category_id').val(result.id); $('#request_title').val(result.name); return config.on_submit(form, true); }, function() { return config.on_submit(form, false); }); }; this.check_category = function(success, fail) { ahoy.post($('#request_title')) .action('service:on_search_categories').data('name', $('#request_title').val()) .success(function(raw_data, data){ var result = $.parseJSON(data); var found_category = false; $.each(result, function(k,v){ if (v.parent_id) { // Only allow child categories found_category = true; } }); if (found_category) success(result[0]); else fail(); }) .send(); }; this.init(); };
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Upload single image behavior */ ahoy.behaviors.upload_image = function(element, config) { var self = this; element = $(element); var defaults = { link_id: null, remove_id: null, image_id:'#upload_image', param_name: 'image', on_remove: null, on_success: null, allow_reupload:true }; this.config = config = $.extend(true, defaults, config); this.image = $(config.image_id); this.remove = $(config.remove_id); this.init = function() { if (config.link_id) $(config.link_id).click(function() { $(element).trigger('click'); }); self.bind_file_upload(); self.bind_remove_image(); }; this.bind_file_upload = function() { element.fileupload({ dataType: 'json', //url: '', paramName: config.param_name, type: 'POST', done: function (e, data) { var old_src = self.image.attr('src'); self.image.attr('src', data.result.thumb).attr('data-blank-src', old_src).attr('data-image-id', data.result.id).fadeTo(1000, 1); config.on_success && config.on_success(self, data); if (self.config.allow_reupload) self.bind_file_upload(); self.remove.show(); }, add: function(e, data) { self.image.fadeTo(500, 0); data.submit(); }, fail: function(e, data) { alert('Oops! Looks like there was an error uploading your photo, try a different one or send us an email! (' + data.errorThrown + ')') self.image.fadeTo(1000, 1); } }); }; this.bind_remove_image = function() { self.remove.die('click').live('click', function(){ self.remove.hide(); var file_id = self.image.attr('data-image-id'); if (!self.config.on_remove || (self.config.on_remove && (self.config.on_remove(self, file_id))!==false)) { self.image.fadeTo(500, 0, function() { var blank_src = self.image.attr('data-blank-src'); self.image.attr('src', blank_src); self.image.fadeTo(1000, 1); }); } }); }; this.init(); }; /** * Upload multiple images behavior */ ahoy.behaviors.upload_image_multi = function(element, config) { var self = this; element = $(element); var defaults = { link_id: null, panel_id:'#panel_photos', param_name: 'images[]', on_remove: null, on_success: null, allow_reupload:true }; this.config = config = $.extend(true, defaults, config); var panel = $(config.panel_id); this.init = function() { // Bind additional link if (config.link_id) $(config.link_id).unbind('click').click(function() { $(element).trigger('click'); return false; }) self.bind_remove_image(); self.bind_file_upload(); }; this.bind_file_upload = function() { element.fileupload({ dataType: 'json', //url: '', paramName: config.param_name, type: 'POST', done: function (e, data) { panel.find('div.loading:first').removeClass('loading').css('background-image', 'url('+data.result.thumb+')').attr('data-image-id', data.result.id); config.on_success && config.on_success(self, data); if (self.config.allow_reupload) self.bind_file_upload(); }, add: function(e, data) { panel.show().children('ul:first').append('<li><div class="image loading"><a href="javascript:;" class="remove">Remove</a></div></li>'); data.submit(); } }); }; this.bind_remove_image = function() { panel.find('a.remove').die('click').live('click', function(){ var photo = $(this).parent(); $(this).closest('li').fadeOut(function() { $(this).remove() if (panel.find('li').length == 0) panel.hide(); var file_id = photo.attr('data-image-id'); config.on_remove && config.on_remove(self, file_id); }); }); }; this.init(); };
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Map Marker behavior (extension of Google Map behavior) * * Usage: * * <script> * $('#map') * .behavior(ahoy.behaviors.map, {allow_drag: true, allow_scroll:false}); * .behavior('use_behavior', [ahoy.behaviors.map_marker, { distance_type: 'km' }]); * .behavior('get_address', ['Pitt St Sydney 2000', { * callback: function(address){ * element.behavior('draw_marker', [address, { marker_id:'address_1', destroy:false } ]); * } * }]); * </script> * */ ahoy.behaviors.map_marker = function(element, config) { var self = this; self.element = element = $(element); var defaults = { distance_type:'km', // Calculate distance in Kilometers (km) or Miles (mi) circle_colour:'#ff0000', // Circle color marker_image: null, // Custom image for marker map_obj: null }; self.config = config = $.extend(true, defaults, config); this.map = config.map_obj; this.marker_manager; this.last_drawn_marker = null; this.marker_counter = 0; this.all_markers = {}; this.init = function() { self.marker_manager = new MarkerManager(self.map); }; this.get_marker = function(marker_id, callback) { if (self.all_markers[marker_id] && callback) callback(self.all_markers[marker_id]); }; this.object_length = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }; this.align_to_markers = function() { if (self.object_length(self.all_markers) <= 0) return; var bounds = new google.maps.LatLngBounds(); jQuery.each(self.all_markers, function(index, marker){ bounds.extend(marker.getPosition()); }); self.map.fitBounds(bounds); var center = bounds.getCenter(); self.map.setCenter(center); }; this.align_to_marker = function(marker_id) { var marker = self.all_markers[marker_id]; self.infobox_content[marker_id] = content; infowindow.open(self.map, marker); }; this.draw_marker = function(address, options) { options = $.extend(true, { destroy: false, // Destroy previous markers min_zoom: 5, // The minimum zoom for displaying marker (hide if far away eg: below 10) max_zoom: null // The maximum zoom for displaying marker (hide if too close eg: above 10) }, options); self.marker_counter++; var center = self.get_center_from_address(address); if (options.destroy && self.last_drawn_marker) self.destroy_markers(); var marker = new google.maps.Marker({ position: center, icon: config.marker_image }); self.last_drawn_marker = marker; if (options.marker_id) self.all_markers[options.marker_id] = marker; else self.all_markers[self.marker_counter] = marker; if (options.infobox_content) self.bind_infobox_content_to_marker(options.infobox_content, options.marker_id); self.marker_manager.addMarker(marker, options.min_zoom, options.max_zoom); if (options.callback) options.callback(self, marker); else return marker; }; this.destroy_markers = function() { self.marker_manager.clearMarkers(); self.all_markers = []; self.infobox_content = []; }; // Events can be: click, mouseover this.bind_event_to_marker = function(event_name, callback, marker_id) { var marker; if (marker_id) marker = self.all_markers[marker_id]; else marker = self.last_drawn_marker; google.maps.event.addListener(marker, event_name, callback); }; // Circles // this.draw_circle = function(address, radius, callback, options) { options = $.extend(true, {destroy:true}, options); var center = self.get_center_from_address(address); var bounds = new google.maps.LatLngBounds(); var circle_coords = Array(); with (Math) { // Set up radians var d; if (self.config.distance_type=="km") d = radius/ 6378.8; else d = radius / 3963.189; var latitude = (PI / 180) * center.lat(); var longitude = (PI / 180) * center.lng(); for (var a = 0; a < 361; a++) { var tc = (PI/180) * a; var y = asin(sin(latitude) * cos(d) + cos(latitude) * sin(d) * cos(tc)); var dlng = atan2(sin(tc) * sin(d) * cos(latitude), cos(d) - sin(latitude) * sin(y)); var x = ((longitude-dlng + PI) % (2 * PI)) - PI; // MOD function var point = new google.maps.LatLng(parseFloat(y * (180 / PI)), parseFloat(x * (180 / PI))); circle_coords.push(point); bounds.extend(point); } if (options.destroy && self.drawn_circle) self.remove_draw_object(self.drawn_circle); var circle = new google.maps.Polygon({ paths: circle_coords, strokeColor: self.config.circle_colour, strokeWeight: 2, strokeOpacity: 1, fillColor: self.config.circle_colour, fillOpacity: 0.4 }); circle.setMap(self.map); self.map.fitBounds(bounds); self.drawn_circle = circle; if (callback) callback(circle); else return circle; } }; // Helpers // this.get_center_from_address = function(address, options) { if (!address) return; options = $.extend(true, {set:0}, options); var set = options.set; if (!set) set = 0; var result = address[set].geometry.location; if (options.callback) options.callback(result); else return result; }; // Object can be: marker, circle this.remove_draw_object = function(object) { object.setMap(null); }; this.init(); }; /** * @name MarkerManager v3 * @version 1.1 * @copyright (c) 2007 Google Inc. * @author Doug Ricket, Bjorn Brala (port to v3), others, * @url http://google-maps-utility-library-v3.googlecode.com/svn/trunk * * @fileoverview Marker manager is an interface between the map and the user, * designed to manage adding and removing many points when the viewport changes. * <br /><br /> * <b>How it Works</b>:<br/> * The MarkerManager places its markers onto a grid, similar to the map tiles. * When the user moves the viewport, it computes which grid cells have * entered or left the viewport, and shows or hides all the markers in those * cells. * (If the users scrolls the viewport beyond the markers that are loaded, * no markers will be visible until the <code>EVENT_moveend</code> * triggers an update.) * In practical consequences, this allows 10,000 markers to be distributed over * a large area, and as long as only 100-200 are visible in any given viewport, * the user will see good performance corresponding to the 100 visible markers, * rather than poor performance corresponding to the total 10,000 markers. * Note that some code is optimized for speed over space, * with the goal of accommodating thousands of markers. */ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @name MarkerManagerOptions * @class This class represents optional arguments to the {@link MarkerManager} * constructor. * @property {Number} maxZoom Sets the maximum zoom level monitored by a * marker manager. If not given, the manager assumes the maximum map zoom * level. This value is also used when markers are added to the manager * without the optional {@link maxZoom} parameter. * @property {Number} borderPadding Specifies, in pixels, the extra padding * outside the map's current viewport monitored by a manager. Markers that * fall within this padding are added to the map, even if they are not fully * visible. * @property {Boolean} trackMarkers=false Indicates whether or not a marker * manager should track markers' movements. If you wish to move managed * markers using the {@link setPoint}/{@link setLatLng} methods, * this option should be set to {@link true}. */ /** * Creates a new MarkerManager that will show/hide markers on a map. * * Events: * @event changed (Parameters: shown bounds, shown markers) Notify listeners when the state of what is displayed changes. * @event loaded MarkerManager has succesfully been initialized. * * @constructor * @param {Map} map The map to manage. * @param {Object} opt_opts A container for optional arguments: * {Number} maxZoom The maximum zoom level for which to create tiles. * {Number} borderPadding The width in pixels beyond the map border, * where markers should be display. * {Boolean} trackMarkers Whether or not this manager should track marker * movements. */ function MarkerManager(map, opt_opts) { var me = this; me.map_ = map; me.mapZoom_ = map.getZoom(); me.projectionHelper_ = new ProjectionHelperOverlay(map); google.maps.event.addListener(me.projectionHelper_, 'ready', function () { me.projection_ = this.getProjection(); me.initialize(map, opt_opts); }); } MarkerManager.prototype.initialize = function (map, opt_opts) { var me = this; opt_opts = opt_opts || {}; me.tileSize_ = MarkerManager.DEFAULT_TILE_SIZE_; var mapTypes = map.mapTypes; // Find max zoom level var mapMaxZoom = 1; for (var sType in mapTypes ) { if (typeof map.mapTypes.get(sType) === 'object' && typeof map.mapTypes.get(sType).maxZoom === 'number') { var mapTypeMaxZoom = map.mapTypes.get(sType).maxZoom; if (mapTypeMaxZoom > mapMaxZoom) { mapMaxZoom = mapTypeMaxZoom; } } } me.maxZoom_ = opt_opts.maxZoom || 19; me.trackMarkers_ = opt_opts.trackMarkers; me.show_ = opt_opts.show || true; var padding; if (typeof opt_opts.borderPadding === 'number') { padding = opt_opts.borderPadding; } else { padding = MarkerManager.DEFAULT_BORDER_PADDING_; } // The padding in pixels beyond the viewport, where we will pre-load markers. me.swPadding_ = new google.maps.Size(-padding, padding); me.nePadding_ = new google.maps.Size(padding, -padding); me.borderPadding_ = padding; me.gridWidth_ = {}; me.grid_ = {}; me.grid_[me.maxZoom_] = {}; me.numMarkers_ = {}; me.numMarkers_[me.maxZoom_] = 0; google.maps.event.addListener(map, 'dragend', function () { me.onMapMoveEnd_(); }); google.maps.event.addListener(map, 'idle', function () { me.onMapMoveEnd_(); }); google.maps.event.addListener(map, 'zoom_changed', function () { me.onMapMoveEnd_(); }); /** * This closure provide easy access to the map. * They are used as callbacks, not as methods. * @param GMarker marker Marker to be removed from the map * @private */ me.removeOverlay_ = function (marker) { marker.setMap(null); me.shownMarkers_--; }; /** * This closure provide easy access to the map. * They are used as callbacks, not as methods. * @param GMarker marker Marker to be added to the map * @private */ me.addOverlay_ = function (marker) { if (me.show_) { marker.setMap(me.map_); me.shownMarkers_++; } }; me.resetManager_(); me.shownMarkers_ = 0; me.shownBounds_ = me.getMapGridBounds_(); google.maps.event.trigger(me, 'loaded'); }; /** * Default tile size used for deviding the map into a grid. */ MarkerManager.DEFAULT_TILE_SIZE_ = 1024; /* * How much extra space to show around the map border so * dragging doesn't result in an empty place. */ MarkerManager.DEFAULT_BORDER_PADDING_ = 100; /** * Default tilesize of single tile world. */ MarkerManager.MERCATOR_ZOOM_LEVEL_ZERO_RANGE = 256; /** * Initializes MarkerManager arrays for all zoom levels * Called by constructor and by clearAllMarkers */ MarkerManager.prototype.resetManager_ = function () { var mapWidth = MarkerManager.MERCATOR_ZOOM_LEVEL_ZERO_RANGE; for (var zoom = 0; zoom <= this.maxZoom_; ++zoom) { this.grid_[zoom] = {}; this.numMarkers_[zoom] = 0; this.gridWidth_[zoom] = Math.ceil(mapWidth / this.tileSize_); mapWidth <<= 1; } }; /** * Removes all markers in the manager, and * removes any visible markers from the map. */ MarkerManager.prototype.clearMarkers = function () { this.processAll_(this.shownBounds_, this.removeOverlay_); this.resetManager_(); }; /** * Gets the tile coordinate for a given latlng point. * * @param {LatLng} latlng The geographical point. * @param {Number} zoom The zoom level. * @param {google.maps.Size} padding The padding used to shift the pixel coordinate. * Used for expanding a bounds to include an extra padding * of pixels surrounding the bounds. * @return {GPoint} The point in tile coordinates. * */ MarkerManager.prototype.getTilePoint_ = function (latlng, zoom, padding) { var pixelPoint = this.projectionHelper_.LatLngToPixel(latlng, zoom); var point = new google.maps.Point( Math.floor((pixelPoint.x + padding.width) / this.tileSize_), Math.floor((pixelPoint.y + padding.height) / this.tileSize_) ); return point; }; /** * Finds the appropriate place to add the marker to the grid. * Optimized for speed; does not actually add the marker to the map. * Designed for batch-processing thousands of markers. * * @param {Marker} marker The marker to add. * @param {Number} minZoom The minimum zoom for displaying the marker. * @param {Number} maxZoom The maximum zoom for displaying the marker. */ MarkerManager.prototype.addMarkerBatch_ = function (marker, minZoom, maxZoom) { var me = this; var mPoint = marker.getPosition(); marker.MarkerManager_minZoom = minZoom; // Tracking markers is expensive, so we do this only if the // user explicitly requested it when creating marker manager. if (this.trackMarkers_) { google.maps.event.addListener(marker, 'changed', function (a, b, c) { me.onMarkerMoved_(a, b, c); }); } var gridPoint = this.getTilePoint_(mPoint, maxZoom, new google.maps.Size(0, 0, 0, 0)); for (var zoom = maxZoom; zoom >= minZoom; zoom--) { var cell = this.getGridCellCreate_(gridPoint.x, gridPoint.y, zoom); cell.push(marker); gridPoint.x = gridPoint.x >> 1; gridPoint.y = gridPoint.y >> 1; } }; /** * Returns whether or not the given point is visible in the shown bounds. This * is a helper method that takes care of the corner case, when shownBounds have * negative minX value. * * @param {Point} point a point on a grid. * @return {Boolean} Whether or not the given point is visible in the currently * shown bounds. */ MarkerManager.prototype.isGridPointVisible_ = function (point) { var vertical = this.shownBounds_.minY <= point.y && point.y <= this.shownBounds_.maxY; var minX = this.shownBounds_.minX; var horizontal = minX <= point.x && point.x <= this.shownBounds_.maxX; if (!horizontal && minX < 0) { // Shifts the negative part of the rectangle. As point.x is always less // than grid width, only test shifted minX .. 0 part of the shown bounds. var width = this.gridWidth_[this.shownBounds_.z]; horizontal = minX + width <= point.x && point.x <= width - 1; } return vertical && horizontal; }; /** * Reacts to a notification from a marker that it has moved to a new location. * It scans the grid all all zoom levels and moves the marker from the old grid * location to a new grid location. * * @param {Marker} marker The marker that moved. * @param {LatLng} oldPoint The old position of the marker. * @param {LatLng} newPoint The new position of the marker. */ MarkerManager.prototype.onMarkerMoved_ = function (marker, oldPoint, newPoint) { // NOTE: We do not know the minimum or maximum zoom the marker was // added at, so we start at the absolute maximum. Whenever we successfully // remove a marker at a given zoom, we add it at the new grid coordinates. var zoom = this.maxZoom_; var changed = false; var oldGrid = this.getTilePoint_(oldPoint, zoom, new google.maps.Size(0, 0, 0, 0)); var newGrid = this.getTilePoint_(newPoint, zoom, new google.maps.Size(0, 0, 0, 0)); while (zoom >= 0 && (oldGrid.x !== newGrid.x || oldGrid.y !== newGrid.y)) { var cell = this.getGridCellNoCreate_(oldGrid.x, oldGrid.y, zoom); if (cell) { if (this.removeFromArray_(cell, marker)) { this.getGridCellCreate_(newGrid.x, newGrid.y, zoom).push(marker); } } // For the current zoom we also need to update the map. Markers that no // longer are visible are removed from the map. Markers that moved into // the shown bounds are added to the map. This also lets us keep the count // of visible markers up to date. if (zoom === this.mapZoom_) { if (this.isGridPointVisible_(oldGrid)) { if (!this.isGridPointVisible_(newGrid)) { this.removeOverlay_(marker); changed = true; } } else { if (this.isGridPointVisible_(newGrid)) { this.addOverlay_(marker); changed = true; } } } oldGrid.x = oldGrid.x >> 1; oldGrid.y = oldGrid.y >> 1; newGrid.x = newGrid.x >> 1; newGrid.y = newGrid.y >> 1; --zoom; } if (changed) { this.notifyListeners_(); } }; /** * Removes marker from the manager and from the map * (if it's currently visible). * @param {GMarker} marker The marker to delete. */ MarkerManager.prototype.removeMarker = function (marker) { var zoom = this.maxZoom_; var changed = false; var point = marker.getPosition(); var grid = this.getTilePoint_(point, zoom, new google.maps.Size(0, 0, 0, 0)); while (zoom >= 0) { var cell = this.getGridCellNoCreate_(grid.x, grid.y, zoom); if (cell) { this.removeFromArray_(cell, marker); } // For the current zoom we also need to update the map. Markers that no // longer are visible are removed from the map. This also lets us keep the count // of visible markers up to date. if (zoom === this.mapZoom_) { if (this.isGridPointVisible_(grid)) { this.removeOverlay_(marker); changed = true; } } grid.x = grid.x >> 1; grid.y = grid.y >> 1; --zoom; } if (changed) { this.notifyListeners_(); } this.numMarkers_[marker.MarkerManager_minZoom]--; }; /** * Add many markers at once. * Does not actually update the map, just the internal grid. * * @param {Array of Marker} markers The markers to add. * @param {Number} minZoom The minimum zoom level to display the markers. * @param {Number} opt_maxZoom The maximum zoom level to display the markers. */ MarkerManager.prototype.addMarkers = function (markers, minZoom, opt_maxZoom) { var maxZoom = this.getOptMaxZoom_(opt_maxZoom); for (var i = markers.length - 1; i >= 0; i--) { this.addMarkerBatch_(markers[i], minZoom, maxZoom); } this.numMarkers_[minZoom] += markers.length; }; /** * Returns the value of the optional maximum zoom. This method is defined so * that we have just one place where optional maximum zoom is calculated. * * @param {Number} opt_maxZoom The optinal maximum zoom. * @return The maximum zoom. */ MarkerManager.prototype.getOptMaxZoom_ = function (opt_maxZoom) { return opt_maxZoom || this.maxZoom_; }; /** * Calculates the total number of markers potentially visible at a given * zoom level. * * @param {Number} zoom The zoom level to check. */ MarkerManager.prototype.getMarkerCount = function (zoom) { var total = 0; for (var z = 0; z <= zoom; z++) { total += this.numMarkers_[z]; } return total; }; /** * Returns a marker given latitude, longitude and zoom. If the marker does not * exist, the method will return a new marker. If a new marker is created, * it will NOT be added to the manager. * * @param {Number} lat - the latitude of a marker. * @param {Number} lng - the longitude of a marker. * @param {Number} zoom - the zoom level * @return {GMarker} marker - the marker found at lat and lng */ MarkerManager.prototype.getMarker = function (lat, lng, zoom) { var mPoint = new google.maps.LatLng(lat, lng); var gridPoint = this.getTilePoint_(mPoint, zoom, new google.maps.Size(0, 0, 0, 0)); var marker = new google.maps.Marker({position: mPoint}); var cellArray = this.getGridCellNoCreate_(gridPoint.x, gridPoint.y, zoom); if (cellArray !== undefined) { for (var i = 0; i < cellArray.length; i++) { if (lat === cellArray[i].getPosition().lat() && lng === cellArray[i].getPosition().lng()) { marker = cellArray[i]; } } } return marker; }; /** * Add a single marker to the map. * * @param {Marker} marker The marker to add. * @param {Number} minZoom The minimum zoom level to display the marker. * @param {Number} opt_maxZoom The maximum zoom level to display the marker. */ MarkerManager.prototype.addMarker = function (marker, minZoom, opt_maxZoom) { var maxZoom = this.getOptMaxZoom_(opt_maxZoom); this.addMarkerBatch_(marker, minZoom, maxZoom); var gridPoint = this.getTilePoint_(marker.getPosition(), this.mapZoom_, new google.maps.Size(0, 0, 0, 0)); if (this.isGridPointVisible_(gridPoint) && minZoom <= this.shownBounds_.z && this.shownBounds_.z <= maxZoom) { this.addOverlay_(marker); this.notifyListeners_(); } this.numMarkers_[minZoom]++; }; /** * Helper class to create a bounds of INT ranges. * @param bounds Array.<Object.<string, number>> Bounds object. * @constructor */ function GridBounds(bounds) { // [sw, ne] this.minX = Math.min(bounds[0].x, bounds[1].x); this.maxX = Math.max(bounds[0].x, bounds[1].x); this.minY = Math.min(bounds[0].y, bounds[1].y); this.maxY = Math.max(bounds[0].y, bounds[1].y); } /** * Returns true if this bounds equal the given bounds. * @param {GridBounds} gridBounds GridBounds The bounds to test. * @return {Boolean} This Bounds equals the given GridBounds. */ GridBounds.prototype.equals = function (gridBounds) { if (this.maxX === gridBounds.maxX && this.maxY === gridBounds.maxY && this.minX === gridBounds.minX && this.minY === gridBounds.minY) { return true; } else { return false; } }; /** * Returns true if this bounds (inclusively) contains the given point. * @param {Point} point The point to test. * @return {Boolean} This Bounds contains the given Point. */ GridBounds.prototype.containsPoint = function (point) { var outer = this; return (outer.minX <= point.x && outer.maxX >= point.x && outer.minY <= point.y && outer.maxY >= point.y); }; /** * Get a cell in the grid, creating it first if necessary. * * Optimization candidate * * @param {Number} x The x coordinate of the cell. * @param {Number} y The y coordinate of the cell. * @param {Number} z The z coordinate of the cell. * @return {Array} The cell in the array. */ MarkerManager.prototype.getGridCellCreate_ = function (x, y, z) { var grid = this.grid_[z]; if (x < 0) { x += this.gridWidth_[z]; } var gridCol = grid[x]; if (!gridCol) { gridCol = grid[x] = []; return (gridCol[y] = []); } var gridCell = gridCol[y]; if (!gridCell) { return (gridCol[y] = []); } return gridCell; }; /** * Get a cell in the grid, returning undefined if it does not exist. * * NOTE: Optimized for speed -- otherwise could combine with getGridCellCreate_. * * @param {Number} x The x coordinate of the cell. * @param {Number} y The y coordinate of the cell. * @param {Number} z The z coordinate of the cell. * @return {Array} The cell in the array. */ MarkerManager.prototype.getGridCellNoCreate_ = function (x, y, z) { var grid = this.grid_[z]; if (x < 0) { x += this.gridWidth_[z]; } var gridCol = grid[x]; return gridCol ? gridCol[y] : undefined; }; /** * Turns at geographical bounds into a grid-space bounds. * * @param {LatLngBounds} bounds The geographical bounds. * @param {Number} zoom The zoom level of the bounds. * @param {google.maps.Size} swPadding The padding in pixels to extend beyond the * given bounds. * @param {google.maps.Size} nePadding The padding in pixels to extend beyond the * given bounds. * @return {GridBounds} The bounds in grid space. */ MarkerManager.prototype.getGridBounds_ = function (bounds, zoom, swPadding, nePadding) { zoom = Math.min(zoom, this.maxZoom_); var bl = bounds.getSouthWest(); var tr = bounds.getNorthEast(); var sw = this.getTilePoint_(bl, zoom, swPadding); var ne = this.getTilePoint_(tr, zoom, nePadding); var gw = this.gridWidth_[zoom]; // Crossing the prime meridian requires correction of bounds. if (tr.lng() < bl.lng() || ne.x < sw.x) { sw.x -= gw; } if (ne.x - sw.x + 1 >= gw) { // Computed grid bounds are larger than the world; truncate. sw.x = 0; ne.x = gw - 1; } var gridBounds = new GridBounds([sw, ne]); gridBounds.z = zoom; return gridBounds; }; /** * Gets the grid-space bounds for the current map viewport. * * @return {Bounds} The bounds in grid space. */ MarkerManager.prototype.getMapGridBounds_ = function () { return this.getGridBounds_(this.map_.getBounds(), this.mapZoom_, this.swPadding_, this.nePadding_); }; /** * Event listener for map:movend. * NOTE: Use a timeout so that the user is not blocked * from moving the map. * * Removed this because a a lack of a scopy override/callback function on events. */ MarkerManager.prototype.onMapMoveEnd_ = function () { this.objectSetTimeout_(this, this.updateMarkers_, 0); }; /** * Call a function or evaluate an expression after a specified number of * milliseconds. * * Equivalent to the standard window.setTimeout function, but the given * function executes as a method of this instance. So the function passed to * objectSetTimeout can contain references to this. * objectSetTimeout(this, function () { alert(this.x) }, 1000); * * @param {Object} object The target object. * @param {Function} command The command to run. * @param {Number} milliseconds The delay. * @return {Boolean} Success. */ MarkerManager.prototype.objectSetTimeout_ = function (object, command, milliseconds) { return window.setTimeout(function () { command.call(object); }, milliseconds); }; /** * Is this layer visible? * * Returns visibility setting * * @return {Boolean} Visible */ MarkerManager.prototype.visible = function () { return this.show_ ? true : false; }; /** * Returns true if the manager is hidden. * Otherwise returns false. * @return {Boolean} Hidden */ MarkerManager.prototype.isHidden = function () { return !this.show_; }; /** * Shows the manager if it's currently hidden. */ MarkerManager.prototype.show = function () { this.show_ = true; this.refresh(); }; /** * Hides the manager if it's currently visible */ MarkerManager.prototype.hide = function () { this.show_ = false; this.refresh(); }; /** * Toggles the visibility of the manager. */ MarkerManager.prototype.toggle = function () { this.show_ = !this.show_; this.refresh(); }; /** * Refresh forces the marker-manager into a good state. * <ol> * <li>If never before initialized, shows all the markers.</li> * <li>If previously initialized, removes and re-adds all markers.</li> * </ol> */ MarkerManager.prototype.refresh = function () { if (this.shownMarkers_ > 0) { this.processAll_(this.shownBounds_, this.removeOverlay_); } // An extra check on this.show_ to increase performance (no need to processAll_) if (this.show_) { this.processAll_(this.shownBounds_, this.addOverlay_); } this.notifyListeners_(); }; /** * After the viewport may have changed, add or remove markers as needed. */ MarkerManager.prototype.updateMarkers_ = function () { this.mapZoom_ = this.map_.getZoom(); var newBounds = this.getMapGridBounds_(); // If the move does not include new grid sections, // we have no work to do: if (newBounds.equals(this.shownBounds_) && newBounds.z === this.shownBounds_.z) { return; } if (newBounds.z !== this.shownBounds_.z) { this.processAll_(this.shownBounds_, this.removeOverlay_); if (this.show_) { // performance this.processAll_(newBounds, this.addOverlay_); } } else { // Remove markers: this.rectangleDiff_(this.shownBounds_, newBounds, this.removeCellMarkers_); // Add markers: if (this.show_) { // performance this.rectangleDiff_(newBounds, this.shownBounds_, this.addCellMarkers_); } } this.shownBounds_ = newBounds; this.notifyListeners_(); }; /** * Notify listeners when the state of what is displayed changes. */ MarkerManager.prototype.notifyListeners_ = function () { google.maps.event.trigger(this, 'changed', this.shownBounds_, this.shownMarkers_); }; /** * Process all markers in the bounds provided, using a callback. * * @param {Bounds} bounds The bounds in grid space. * @param {Function} callback The function to call for each marker. */ MarkerManager.prototype.processAll_ = function (bounds, callback) { for (var x = bounds.minX; x <= bounds.maxX; x++) { for (var y = bounds.minY; y <= bounds.maxY; y++) { this.processCellMarkers_(x, y, bounds.z, callback); } } }; /** * Process all markers in the grid cell, using a callback. * * @param {Number} x The x coordinate of the cell. * @param {Number} y The y coordinate of the cell. * @param {Number} z The z coordinate of the cell. * @param {Function} callback The function to call for each marker. */ MarkerManager.prototype.processCellMarkers_ = function (x, y, z, callback) { var cell = this.getGridCellNoCreate_(x, y, z); if (cell) { for (var i = cell.length - 1; i >= 0; i--) { callback(cell[i]); } } }; /** * Remove all markers in a grid cell. * * @param {Number} x The x coordinate of the cell. * @param {Number} y The y coordinate of the cell. * @param {Number} z The z coordinate of the cell. */ MarkerManager.prototype.removeCellMarkers_ = function (x, y, z) { this.processCellMarkers_(x, y, z, this.removeOverlay_); }; /** * Add all markers in a grid cell. * * @param {Number} x The x coordinate of the cell. * @param {Number} y The y coordinate of the cell. * @param {Number} z The z coordinate of the cell. */ MarkerManager.prototype.addCellMarkers_ = function (x, y, z) { this.processCellMarkers_(x, y, z, this.addOverlay_); }; /** * Use the rectangleDiffCoords_ function to process all grid cells * that are in bounds1 but not bounds2, using a callback, and using * the current MarkerManager object as the instance. * * Pass the z parameter to the callback in addition to x and y. * * @param {Bounds} bounds1 The bounds of all points we may process. * @param {Bounds} bounds2 The bounds of points to exclude. * @param {Function} callback The callback function to call * for each grid coordinate (x, y, z). */ MarkerManager.prototype.rectangleDiff_ = function (bounds1, bounds2, callback) { var me = this; me.rectangleDiffCoords_(bounds1, bounds2, function (x, y) { callback.apply(me, [x, y, bounds1.z]); }); }; /** * Calls the function for all points in bounds1, not in bounds2 * * @param {Bounds} bounds1 The bounds of all points we may process. * @param {Bounds} bounds2 The bounds of points to exclude. * @param {Function} callback The callback function to call * for each grid coordinate. */ MarkerManager.prototype.rectangleDiffCoords_ = function (bounds1, bounds2, callback) { var minX1 = bounds1.minX; var minY1 = bounds1.minY; var maxX1 = bounds1.maxX; var maxY1 = bounds1.maxY; var minX2 = bounds2.minX; var minY2 = bounds2.minY; var maxX2 = bounds2.maxX; var maxY2 = bounds2.maxY; var x, y; for (x = minX1; x <= maxX1; x++) { // All x in R1 // All above: for (y = minY1; y <= maxY1 && y < minY2; y++) { // y in R1 above R2 callback(x, y); } // All below: for (y = Math.max(maxY2 + 1, minY1); // y in R1 below R2 y <= maxY1; y++) { callback(x, y); } } for (y = Math.max(minY1, minY2); y <= Math.min(maxY1, maxY2); y++) { // All y in R2 and in R1 // Strictly left: for (x = Math.min(maxX1 + 1, minX2) - 1; x >= minX1; x--) { // x in R1 left of R2 callback(x, y); } // Strictly right: for (x = Math.max(minX1, maxX2 + 1); // x in R1 right of R2 x <= maxX1; x++) { callback(x, y); } } }; /** * Removes value from array. O(N). * * @param {Array} array The array to modify. * @param {any} value The value to remove. * @param {Boolean} opt_notype Flag to disable type checking in equality. * @return {Number} The number of instances of value that were removed. */ MarkerManager.prototype.removeFromArray_ = function (array, value, opt_notype) { var shift = 0; for (var i = 0; i < array.length; ++i) { if (array[i] === value || (opt_notype && array[i] === value)) { array.splice(i--, 1); shift++; } } return shift; }; /** * Projection overlay helper. Helps in calculating * that markers get into the right grid. * @constructor * @param {Map} map The map to manage. **/ function ProjectionHelperOverlay(map) { this.setMap(map); var TILEFACTOR = 8; var TILESIDE = 1 << TILEFACTOR; var RADIUS = 7; this._map = map; this._zoom = -1; this._X0 = this._Y0 = this._X1 = this._Y1 = -1; } ProjectionHelperOverlay.prototype = new google.maps.OverlayView(); /** * Helper function to convert Lng to X * @private * @param {float} lng **/ ProjectionHelperOverlay.prototype.LngToX_ = function (lng) { return (1 + lng / 180); }; /** * Helper function to convert Lat to Y * @private * @param {float} lat **/ ProjectionHelperOverlay.prototype.LatToY_ = function (lat) { var sinofphi = Math.sin(lat * Math.PI / 180); return (1 - 0.5 / Math.PI * Math.log((1 + sinofphi) / (1 - sinofphi))); }; /** * Old school LatLngToPixel * @param {LatLng} latlng google.maps.LatLng object * @param {Number} zoom Zoom level * @return {position} {x: pixelPositionX, y: pixelPositionY} **/ ProjectionHelperOverlay.prototype.LatLngToPixel = function (latlng, zoom) { var map = this._map; var div = this.getProjection().fromLatLngToDivPixel(latlng); var abs = {x: ~~(0.5 + this.LngToX_(latlng.lng()) * (2 << (zoom + 6))), y: ~~(0.5 + this.LatToY_(latlng.lat()) * (2 << (zoom + 6)))}; return abs; }; /** * Draw function only triggers a ready event for * MarkerManager to know projection can proceed to * initialize. */ ProjectionHelperOverlay.prototype.draw = function () { if (!this.ready) { this.ready = true; google.maps.event.trigger(this, 'ready'); } };
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Google Maps behavior */ ahoy.behaviors.map = function(element, config) { var self = this; self.element = element = $(element); var defaults = { start_position: [-34.397, 150.644], // Australia ;) start_zoom: 2, // Initial map zoom allow_drag: false, // Allow user to drag map allow_scroll: false, // Allow mouse scrool to zoom show_default_ui: false, // Show default map controls show_pan_ui: false, // Show UI for pan show_zoom_ui: false, // Show UI for zoom show_type_ui: false, // Show UI for type show_scale_ui: false, // Show UI for scale show_overview_ui: false, // Show UI for overview show_street_view_ui: false // Show UI for street view }; self.config = config = $.extend(true, defaults, config); this.geocoder = null; // Geocoder object this.map = null; this.init = function() { self.geocoder = new google.maps.Geocoder(); var map_options = { zoom: config.start_zoom, center: new google.maps.LatLng(config.start_position[0], config.start_position[1]), disableDefaultUI: !config.show_default_ui, panControl: config.show_pan_ui, zoomControl: config.show_zoom_ui, mapTypeControl: config.show_type_ui, scaleControl: config.show_scale_ui, streetViewControl: config.show_overview_ui, overviewMapControl: config.show_street_view_ui, draggable: config.allow_drag, scrollwheel: config.allow_scroll, keyboardShortcuts: false, disableDoubleClickZoom: !config.allow_scroll, mapTypeId: google.maps.MapTypeId.ROADMAP }; self.map = new google.maps.Map(element.get(0), map_options); }; this.use_behavior = function(behavior, options) { if (!options) options = {}; options = $.extend(true, {map_obj:self.map}, options); self.element.behavior(behavior, options); } this.get_address = function(string, options) { self.geocoder.geocode( { 'address': string }, function(address, status) { if (status == google.maps.GeocoderStatus.OK) { options.callback && options.callback(address); return address; } // else // alert("Geocode was not successful for the following reason: " + status); }); }; this.set_zoom = function(zoom) { if (!zoom) return; self.map.setZoom(zoom); }; this.align_to_address = function(address, zoom) { var center = self.get_center_from_address(address); self.map.setCenter(center); self.set_zoom(zoom); }; // Value can be: country, postal_code this.get_value_from_address = function(address, value, options) { options = $.extend(true, {set:0}, options); var set = options.set; var result = null; for (i=0; i < address[set].address_components.length; i++){ for (j=0; j < address[set].address_components[i].types.length; j++){ if(address[set].address_components[i].types[j] == value) result = address[set].address_components[i].short_name; } } // If no result, check other data sets if (!result && address[set+1]) { options.set = set+1; return self.get_value_from_address(address, value, options); } if (options.callback) options.callback(result); else return result; }; this.get_center_from_address = function(address, options) { if (!address) return; options = $.extend(true, {set:0}, options); var set = options.set; if (!set) set = 0; var result = address[set].geometry.location; if (options.callback) options.callback(result); else return result; }; this.init(); };
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Request quotes behavior */ ahoy.behaviors.request_quotes = function(element, config) { var self = this; self.element = element = $(element); var defaults = { }; self.config = config = $.extend(true, defaults, config); var quote_list = element.find('.quote_list li'); var quotes = element.find('.quote_panel .quote'); // Init quote_list.first().addClass('active'); quotes.first().show(); // Events quote_list.click(function() { var id = $(this).attr('data-quote-id'); self.click_quote(id); }); this.click_quote = function(id) { quotes.hide(); quote_list.removeClass('active'); $('#p_quote_panel_'+id).show(); $('#quote_list_'+id).addClass('active'); }; // Popup this.bind_popup = function(id) { ahoy.behavior('#popup_quote_'+id, 'popup', { trigger: '#button_quote_'+id, move_to_element:'#page_request_manage', size:'large' }); ahoy.behavior('#popup_quote_'+id+'_country', 'select_country', { state_element_id: '#popup_quote_'+id+'_state', after_update: function(obj) { obj.state_element = $('#popup_quote_'+id+'_state'); } }); // Validate ahoy.validate.bind($('#form_quote_'+id), 'partial_request_quote_panel', function() { return ahoy.post($('#form_quote_'+id)).action('bluebell:on_request_accept_quote').send(); }); }; // Conversation this.bind_conversation = function(id) { var question_button = $('#button_question_'+id); var conversation_form = $('#form_conversation_'+id); var has_conversation = (conversation_form.find('.conv_message:first').length > 0); if (has_conversation) { question_button.closest('.conversation_question').hide().siblings('.info:first').hide(); } else { conversation_form.hide(); question_button.click(function() { question_button.closest('.conversation_question').hide().siblings('.info:first').hide(); conversation_form.show(); }); } self.validate_conversation(conversation_form); }; this.validate_conversation = function(form) { // Validate ahoy.validate.bind(form, 'partial_control_conversation', function() { return ahoy.post(form).action('bluebell:on_send_quote_message').update('#'+form.attr('id'), 'control:conversation').send(); }); }; // Suggest booking time this.bind_booking_time = function(id) { var booking_time_link = $('#link_booking_time_suggest_'+id); var booking_time_form = $('#form_booking_time_'+id); var booking_time_container = $('#booking_time_suggest_container_'+id); booking_time_link.click(function() { booking_time_container.show(); $('#booking_time_time_'+id).trigger('change'); }); // Validate ahoy.validate.bind(booking_time_form, 'partial_request_booking_time', function() { return ahoy.post(booking_time_form) .action('bluebell:on_request_booking_time') .update('#p_request_booking_time_'+id, 'request:booking_time') .success(function() { self.bind_booking_time(id); $.foundation.customForms.appendCustomMarkup(); }) .send(); }); }; // Bind events quotes.each(function(){ var id = $(this).attr('data-quote-id'); self.bind_popup(id); self.bind_conversation(id); self.bind_booking_time(id); }); };
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Select country behavior * * Usage: ahoy.behavior('#country_id', 'select_country', { state_element_id:'#state_id' }); * */ ahoy.behaviors.select_country = function(element, config) { var self = this; element = $(element); var defaults = { state_element_id: null, // Element ID or object to replace after_update: null, // Callback after state has updated }; config = $.extend(true, defaults, config); this.state_element = $(config.state_element_id); element.bind('change', function() { var post_obj = ahoy.post(element) .action('location:on_state_dropdown') .data('country_id', element.val()) .success(function(raw, data){ self.state_element.replaceWith(data); config.after_update && config.after_update(self); }); if (self.state_element.attr('name')) post_obj = post_obj.data('state_field_name', self.state_element.attr('name')) if (self.state_element.attr('id')) post_obj = post_obj.data('state_field_id', self.state_element.attr('id')); post_obj.send(); }); };
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Job quote behavior */ ahoy.behaviors.job_quote = function(element, config) { var self = this; self.element = element = $(element); var defaults = { type: null // Options: flat_rate, onsite }; self.config = config = $.extend(true, defaults, config); // Onsite this.bind_onsite_travel = function() { if ($('#quote_onsite_travel_required_yes').is(':checked')) $('#panel_travel_fee').show(); $('#quote_onsite_travel_required_yes').change(function() { if ($(this).is(':checked')) $('#panel_travel_fee').show(); }); $('#quote_onsite_travel_required_no').change(function() { if ($(this).is(':checked')) $('#panel_travel_fee').hide(); }); }; // Flat rate this.bind_flat_rate_add_item = function() { // Set up shell for duplication var item_table = element.find('.item_table'); var shell = item_table.find('tr.shell').hide(); self.flat_rate_populate(); // Create empty set for styling alternate rows item_table.prepend('<tr class="empty" style="display:none"><td colspan="'+shell.children('td').length+'">&nbsp;</td></tr>'); $('#link_add_line_item').click(function(){ self.click_flat_rate_add_item(); return false; }); }; this.flat_rate_populate = function() { if (!$('#quote_flat_items').length) self.click_flat_rate_add_item(); var data = $('#quote_flat_items').val(); if ($.trim(data) != "") { var result = $.parseJSON(data); $.each(result, function(key, val){ self.flat_rate_add_item(val.description, val.price); }); } else { self.click_flat_rate_add_item(); } }; this.click_flat_rate_add_item = function() { var item_table = element.find('.item_table'); var new_item = item_table.find('tr.shell').clone().removeClass('shell').show(); item_table.append(new_item); return new_item; }; this.flat_rate_add_item = function(line_item, price) { var new_item = self.click_flat_rate_add_item(); new_item.find('td.line_item input').val(line_item); new_item.find('td.price input').val(price); }; this.bind_flat_rate_update_total = function() { element.find('td.price input').live('change', function() { var fields = element.find('input'); var value = self.flat_rate_calculate_total(fields); ahoy.post().action('cms:on_get_currency').data('value', value).success(function(raw, result){ $('#total_cost_value').text(result); }).send(); }); }; this.flat_rate_calculate_total = function(fields) { var total = 0; $.each(fields, function(k,v){ var val = parseFloat($(this).val()); if (val) total += val; }); return total; }; // Personal message this.bind_personal_message = function() { var final_comment = element.find('.final_comment:first'); if (!final_comment.hasClass('use_message_builder')) return; var greeting = element.find('.message_greeting'); var description = element.find('.message_description'); var closer = element.find('.message_closer'); var parting = element.find('.message_parting'); element.find('input,select,textarea').change(function() { var comment = ""; comment += self.helper_strip_html(greeting, greeting.find('select').val()) + "\n\n"; comment += description.find('textarea').val() + "\n\n"; comment += self.helper_strip_html(closer, closer.find('select').val()) + "\n\n"; comment += self.helper_strip_html(parting, parting.find('select').val()); final_comment.val(comment); }); }; this.helper_strip_html = function(obj, param) { var text = $.trim(obj.clone().find('> select').replaceWith('%s').end().find('> *').remove().end().html()); return text.replace('%s', param); }; this.init = function() { switch (self.config.type) { case "onsite": self.bind_onsite_travel(); break; case "flat_rate": self.bind_flat_rate_add_item(); self.bind_flat_rate_update_total(); break; case "message": self.bind_personal_message(); break; } }; this.init(); };
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Portfolio behavior */ ahoy.behaviors.portfolio = function(element, config) { var self = this; self.element = element = $(element); var defaults = { thumb_width: 75, thumb_height: 75, use_popup: true // Display full size images in a popup }; self.config = config = $.extend(true, defaults, config); var element_id = element.attr('id'); var popup_id = element_id+'_popup'; // First lets clean up $('#'+popup_id).remove(); // Then dress up element.wrap($('<div />').attr('id', popup_id)); var popup = $('#'+popup_id); // Build thumbs var thumb_list = $('<ul />').attr('id', element_id+'_thumbs').addClass('jcarousel-skin-ahoy'); element.find('img').each(function(key, val){ var image_id = $(this).attr('data-image-id'); var thumb_src = $(this).attr('data-thumb-image'); var anchor = $('<a />').attr({ href: 'javascript:;', 'data-image-count': key }); var thumb = $('<img />').attr({ src: thumb_src, 'data-image-id': image_id, width: config.thumb_width, height: config.thumb_height }); var thumb_list_anchor = anchor.append(thumb); thumb_list.append($('<li />').append(thumb_list_anchor)); }); popup.after(thumb_list); // Init thumbs thumb_list.jcarousel({scroll: 1}); // If we have no images, do not proceed if (!element.find('img').length) return; // Init Orbit element.not('.orbit-enabled').addClass('orbit-enabled').orbit({ animation: 'horizontal-push', bullets: config.use_popup, captions: true, directionalNav: config.use_popup, fluid: true, timer: false }); // Popup if (config.use_popup) { ahoy.behavior(popup, 'popup', { trigger: '#'+element_id+'_thumbs a', move_to_element: 'body', size: 'portfolio', on_open: function(link) { self.click_thumb(link); } }); } else { $('#'+element_id+'_thumbs a').click(function() { self.click_thumb($(this)); }); } // When a thumb is clicked this.click_thumb = function(link) { var image_id = $(link).attr('data-image-count'); element.trigger('orbit.goto', [image_id]); }; this.destroy = function() { popup.remove(); }; }
JavaScript
/** * Popup behavior * * Usage: ahoy.behavior('#popup', 'popup', { trigger: '#button' }); * */ ahoy.behaviors.popup = function(element, config) { var self = this; element = $(element); var defaults = { on_open: null, // Callback when popup opens on_close: null, // Callback when popup closes trigger: null, // Trigger to open extra_close: '.popup_close', // Trigger to close show_close: true, // Show the X to close close_on_bg_click: true, // If you click background close popup? move_to_element: false, // Move the popup to another element size: null, // Options: small, medium, large, xlarge, expand animation: 'fadeAndPop', // Options: fade, fadeAndPop, none animation_speed: 300, // Animate speed in milliseconds auto_reveal: false, // Show popup when page opens? partial: null }; config = $.extend(true, defaults, config); this.partial_container_id = null; this.partial_name = config.partial; // Init reveal this.reveal_options = { animation: config.animation, animationspeed: config.animation_speed, closeOnBackgroundClick: config.close_on_bg_click, dismissModalClass: 'close-reveal-modal' }; this.init = function() { element.addClass('reveal-modal'); if (config.size) element.addClass(config.size); // Auto reveal if (config.auto_reveal) { $(window).load(function(){ self.open_popup(); }); } // Popup opening var trigger = $(config.trigger); trigger.die('click').live('click', function() { self.handle_partial($(this)); self.open_popup($(this)); }); // Popup closing element.find(config.extra_close).die('click').live('click', function() { element.trigger('reveal:close'); }); // Add close cross var close_cross = $('<a />').addClass('close-reveal-modal').html('&#215;'); close_cross.appendTo(element); // Move the popup to a more suitable position if (config.move_to_element) element.prependTo($(config.move_to_element)); }; // Service methods // this.open_popup = function(triggered_by) { // Open event config.on_open && element.unbind('reveal:open').bind('reveal:open', function() { config.on_open(triggered_by); }); // Close event config.on_close && element.unbind('reveal:close').bind('reveal:close', function() { config.on_close(triggered_by); }); element.reveal(self.reveal_options); }; this.close_popup = function() { element.trigger('reveal:close'); }; // Partial Loading // this.handle_partial = function(triggered_by) { var inline_partial = triggered_by.data('partial'); self.partial_name = (inline_partial) ? inline_partial : config.partial; if (self.partial_name) { self.create_partial_container(); ahoy.post().update('#'+self.partial_container_id, self.partial_name).send(); } }; this.create_partial_container = function() { // Container ID not found if (!self.partial_container_id) { var random_number = (Math.floor((Math.random() * 100)) % 94) + 33; self.partial_container_id = 'reveal-content'+random_number; } // Container not found, create if ($('#'+self.partial_container_id).length == 0) $('<div />').addClass('partial-reveal-modal').attr('id', self.partial_container_id).appendTo(element); }; this.init(); };
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Map Bubble behavior (extension of Google Map behavior) * * Usage: * * <script> * $('#map') * .behavior(ahoy.behaviors.map, {allow_drag: true, allow_scroll:false}); * .behavior('use_behavior', [ahoy.behaviors.map_bubble, { bubble_use_hover: false }]); * .behavior('get_address', ['Pitt St Sydney 2000', { * callback: function(address){ * element.behavior('draw_bubble', [address, { address_id:'address_1', content:'Hello world!' } ]); * } * }]); * </script> * */ ahoy.behaviors.map_bubble = function(element, config) { var self = this; self.element = element = $(element); var defaults = { bubble_use_hover: false, // Open Info Box on hover bubble_width: 600, // Info Box default width map_obj: null }; self.config = config = $.extend(true, defaults, config); this.map = config.map_obj; this.bubble; this.bubble_content = {}; this.init = function() { element.behavior('use_behavior', [ahoy.behaviors.map_marker]); var bubble_options = { maxWidth:self.config.bubble_width }; self.bubble = new InfoBubble(bubble_options); }; this.draw_bubble = function(address, options) { element.behavior('draw_marker', [address, { marker_id: options.bubble_id } ]); self.bind_bubble_content_to_marker(options.content, options.bubble_id); }; this.bind_bubble_content_to_marker = function(content, bubble_id) { element.behavior('get_marker', [bubble_id, function(marker) { self.bubble_content[bubble_id] = content; var func_display_bubble = function() { self.bubble.setContent(self.bubble_content[bubble_id]); self.bubble.open(self.map, marker); }; element.behavior('bind_event_to_marker', ['click', func_display_bubble, bubble_id]); if (config.bubble_use_hover) element.behavior('bind_event_to_marker', ['mouseover', func_display_bubble, bubble_id]); }]); }; this.display_bubble = function(bubble_id) { element.behavior('get_marker', [bubble_id, function(marker) { self.bubble.setContent(self.bubble_content[bubble_id]); self.bubble.open(self.map, marker); }]); }; this.init(); }; /** * @name CSS3 InfoBubble with tabs for Google Maps API V3 * @version 0.8 * @author Luke Mahe * @fileoverview * @url http://google-maps-utility-library-v3.googlecode.com/svn/trunk * This library is a CSS Infobubble with tabs. It uses css3 rounded corners and * drop shadows and animations. It also allows tabs */ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * A CSS3 InfoBubble v0.8 * @param {Object.<string, *>=} opt_options Optional properties to set. * @extends {google.maps.OverlayView} * @constructor */ function InfoBubble(opt_options) { this.extend(InfoBubble, google.maps.OverlayView); this.tabs_ = []; this.activeTab_ = null; this.baseZIndex_ = 100; this.isOpen_ = false; var options = opt_options || {}; if (options['backgroundColor'] == undefined) { options['backgroundColor'] = this.BACKGROUND_COLOR_; } if (options['borderColor'] == undefined) { options['borderColor'] = this.BORDER_COLOR_; } if (options['borderRadius'] == undefined) { options['borderRadius'] = this.BORDER_RADIUS_; } if (options['borderWidth'] == undefined) { options['borderWidth'] = this.BORDER_WIDTH_; } if (options['padding'] == undefined) { options['padding'] = this.PADDING_; } if (options['arrowPosition'] == undefined) { options['arrowPosition'] = this.ARROW_POSITION_; } if (options['disableAutoPan'] == undefined) { options['disableAutoPan'] = false; } if (options['disableAnimation'] == undefined) { options['disableAnimation'] = false; } if (options['minWidth'] == undefined) { options['minWidth'] = this.MIN_WIDTH_; } if (options['shadowStyle'] == undefined) { options['shadowStyle'] = this.SHADOW_STYLE_; } if (options['arrowSize'] == undefined) { options['arrowSize'] = this.ARROW_SIZE_; } if (options['arrowStyle'] == undefined) { options['arrowStyle'] = this.ARROW_STYLE_; } this.buildDom_(); this.setValues(options); } window['InfoBubble'] = InfoBubble; /** * Default arrow size * @const * @private */ InfoBubble.prototype.ARROW_SIZE_ = 15; /** * Default arrow style * @const * @private */ InfoBubble.prototype.ARROW_STYLE_ = 0; /** * Default shadow style * @const * @private */ InfoBubble.prototype.SHADOW_STYLE_ = 1; /** * Default min width * @const * @private */ InfoBubble.prototype.MIN_WIDTH_ = 50; /** * Default arrow position * @const * @private */ InfoBubble.prototype.ARROW_POSITION_ = 50; /** * Default padding * @const * @private */ InfoBubble.prototype.PADDING_ = 10; /** * Default border width * @const * @private */ InfoBubble.prototype.BORDER_WIDTH_ = 1; /** * Default border color * @const * @private */ InfoBubble.prototype.BORDER_COLOR_ = '#ccc'; /** * Default border radius * @const * @private */ InfoBubble.prototype.BORDER_RADIUS_ = 10; /** * Default background color * @const * @private */ InfoBubble.prototype.BACKGROUND_COLOR_ = '#fff'; /** * Extends a objects prototype by anothers. * * @param {Object} obj1 The object to be extended. * @param {Object} obj2 The object to extend with. * @return {Object} The new extended object. * @ignore */ InfoBubble.prototype.extend = function(obj1, obj2) { return (function(object) { for (var property in object.prototype) { this.prototype[property] = object.prototype[property]; } return this; }).apply(obj1, [obj2]); }; /** * Builds the InfoBubble dom * @private */ InfoBubble.prototype.buildDom_ = function() { var bubble = this.bubble_ = document.createElement('DIV'); bubble.style['position'] = 'absolute'; bubble.style['zIndex'] = this.baseZIndex_; var tabsContainer = this.tabsContainer_ = document.createElement('DIV'); tabsContainer.style['position'] = 'relative'; // Close button var close = this.close_ = document.createElement('IMG'); close.style['position'] = 'absolute'; close.style['width'] = this.px(12); close.style['height'] = this.px(12); close.style['border'] = 0; close.style['zIndex'] = this.baseZIndex_ + 1; close.style['cursor'] = 'pointer'; close.src = 'http://maps.gstatic.com/intl/en_us/mapfiles/iw_close.gif'; var that = this; google.maps.event.addDomListener(close, 'click', function() { that.close(); google.maps.event.trigger(that, 'closeclick'); }); // Content area var contentContainer = this.contentContainer_ = document.createElement('DIV'); contentContainer.style['overflowX'] = 'auto'; contentContainer.style['overflowY'] = 'auto'; contentContainer.style['cursor'] = 'default'; contentContainer.style['clear'] = 'both'; contentContainer.style['position'] = 'relative'; var content = this.content_ = document.createElement('DIV'); contentContainer.appendChild(content); // Arrow var arrow = this.arrow_ = document.createElement('DIV'); arrow.style['position'] = 'relative'; var arrowOuter = this.arrowOuter_ = document.createElement('DIV'); var arrowInner = this.arrowInner_ = document.createElement('DIV'); var arrowSize = this.getArrowSize_(); arrowOuter.style['position'] = arrowInner.style['position'] = 'absolute'; arrowOuter.style['left'] = arrowInner.style['left'] = '50%'; arrowOuter.style['height'] = arrowInner.style['height'] = '0'; arrowOuter.style['width'] = arrowInner.style['width'] = '0'; arrowOuter.style['marginLeft'] = this.px(-arrowSize); arrowOuter.style['borderWidth'] = this.px(arrowSize); arrowOuter.style['borderBottomWidth'] = 0; // Shadow var bubbleShadow = this.bubbleShadow_ = document.createElement('DIV'); bubbleShadow.style['position'] = 'absolute'; // Hide the InfoBubble by default bubble.style['display'] = bubbleShadow.style['display'] = 'none'; bubble.appendChild(this.tabsContainer_); bubble.appendChild(close); bubble.appendChild(contentContainer); arrow.appendChild(arrowOuter); arrow.appendChild(arrowInner); bubble.appendChild(arrow); var stylesheet = document.createElement('style'); stylesheet.setAttribute('type', 'text/css'); /** * The animation for the infobubble * @type {string} */ this.animationName_ = '_ibani_' + Math.round(Math.random() * 10000); var css = '.' + this.animationName_ + '{-webkit-animation-name:' + this.animationName_ + ';-webkit-animation-duration:0.5s;' + '-webkit-animation-iteration-count:1;}' + '@-webkit-keyframes ' + this.animationName_ + ' {from {' + '-webkit-transform: scale(0)}50% {-webkit-transform: scale(1.2)}90% ' + '{-webkit-transform: scale(0.95)}to {-webkit-transform: scale(1)}}'; stylesheet.textContent = css; document.getElementsByTagName('head')[0].appendChild(stylesheet); }; /** * Sets the background class name * * @param {string} className The class name to set. */ InfoBubble.prototype.setBackgroundClassName = function(className) { this.set('backgroundClassName', className); }; InfoBubble.prototype['setBackgroundClassName'] = InfoBubble.prototype.setBackgroundClassName; /** * changed MVC callback */ InfoBubble.prototype.backgroundClassName_changed = function() { this.content_.className = this.get('backgroundClassName'); }; InfoBubble.prototype['backgroundClassName_changed'] = InfoBubble.prototype.backgroundClassName_changed; /** * Sets the class of the tab * * @param {string} className the class name to set. */ InfoBubble.prototype.setTabClassName = function(className) { this.set('tabClassName', className); }; InfoBubble.prototype['setTabClassName'] = InfoBubble.prototype.setTabClassName; /** * tabClassName changed MVC callback */ InfoBubble.prototype.tabClassName_changed = function() { this.updateTabStyles_(); }; InfoBubble.prototype['tabClassName_changed'] = InfoBubble.prototype.tabClassName_changed; /** * Gets the style of the arrow * * @private * @return {number} The style of the arrow. */ InfoBubble.prototype.getArrowStyle_ = function() { return parseInt(this.get('arrowStyle'), 10) || 0; }; /** * Sets the style of the arrow * * @param {number} style The style of the arrow. */ InfoBubble.prototype.setArrowStyle = function(style) { this.set('arrowStyle', style); }; InfoBubble.prototype['setArrowStyle'] = InfoBubble.prototype.setArrowStyle; /** * Arrow style changed MVC callback */ InfoBubble.prototype.arrowStyle_changed = function() { this.arrowSize_changed(); }; InfoBubble.prototype['arrowStyle_changed'] = InfoBubble.prototype.arrowStyle_changed; /** * Gets the size of the arrow * * @private * @return {number} The size of the arrow. */ InfoBubble.prototype.getArrowSize_ = function() { return parseInt(this.get('arrowSize'), 10) || 0; }; /** * Sets the size of the arrow * * @param {number} size The size of the arrow. */ InfoBubble.prototype.setArrowSize = function(size) { this.set('arrowSize', size); }; InfoBubble.prototype['setArrowSize'] = InfoBubble.prototype.setArrowSize; /** * Arrow size changed MVC callback */ InfoBubble.prototype.arrowSize_changed = function() { this.borderWidth_changed(); }; InfoBubble.prototype['arrowSize_changed'] = InfoBubble.prototype.arrowSize_changed; /** * Set the position of the InfoBubble arrow * * @param {number} pos The position to set. */ InfoBubble.prototype.setArrowPosition = function(pos) { this.set('arrowPosition', pos); }; InfoBubble.prototype['setArrowPosition'] = InfoBubble.prototype.setArrowPosition; /** * Get the position of the InfoBubble arrow * * @private * @return {number} The position.. */ InfoBubble.prototype.getArrowPosition_ = function() { return parseInt(this.get('arrowPosition'), 10) || 0; }; /** * arrowPosition changed MVC callback */ InfoBubble.prototype.arrowPosition_changed = function() { var pos = this.getArrowPosition_(); this.arrowOuter_.style['left'] = this.arrowInner_.style['left'] = pos + '%'; this.redraw_(); }; InfoBubble.prototype['arrowPosition_changed'] = InfoBubble.prototype.arrowPosition_changed; /** * Set the zIndex of the InfoBubble * * @param {number} zIndex The zIndex to set. */ InfoBubble.prototype.setZIndex = function(zIndex) { this.set('zIndex', zIndex); }; InfoBubble.prototype['setZIndex'] = InfoBubble.prototype.setZIndex; /** * Get the zIndex of the InfoBubble * * @return {number} The zIndex to set. */ InfoBubble.prototype.getZIndex = function() { return parseInt(this.get('zIndex'), 10) || this.baseZIndex_; }; /** * zIndex changed MVC callback */ InfoBubble.prototype.zIndex_changed = function() { var zIndex = this.getZIndex(); this.bubble_.style['zIndex'] = this.baseZIndex_ = zIndex; this.close_.style['zIndex'] = zIndex + 1; }; InfoBubble.prototype['zIndex_changed'] = InfoBubble.prototype.zIndex_changed; /** * Set the style of the shadow * * @param {number} shadowStyle The style of the shadow. */ InfoBubble.prototype.setShadowStyle = function(shadowStyle) { this.set('shadowStyle', shadowStyle); }; InfoBubble.prototype['setShadowStyle'] = InfoBubble.prototype.setShadowStyle; /** * Get the style of the shadow * * @private * @return {number} The style of the shadow. */ InfoBubble.prototype.getShadowStyle_ = function() { return parseInt(this.get('shadowStyle'), 10) || 0; }; /** * shadowStyle changed MVC callback */ InfoBubble.prototype.shadowStyle_changed = function() { var shadowStyle = this.getShadowStyle_(); var display = ''; var shadow = ''; var backgroundColor = ''; switch (shadowStyle) { case 0: display = 'none'; break; case 1: shadow = '40px 15px 10px rgba(33,33,33,0.3)'; backgroundColor = 'transparent'; break; case 2: shadow = '0 0 2px rgba(33,33,33,0.3)'; backgroundColor = 'rgba(33,33,33,0.35)'; break; } this.bubbleShadow_.style['boxShadow'] = this.bubbleShadow_.style['webkitBoxShadow'] = this.bubbleShadow_.style['MozBoxShadow'] = shadow; this.bubbleShadow_.style['backgroundColor'] = backgroundColor; if (this.isOpen_) { this.bubbleShadow_.style['display'] = display; this.draw(); } }; InfoBubble.prototype['shadowStyle_changed'] = InfoBubble.prototype.shadowStyle_changed; /** * Show the close button */ InfoBubble.prototype.showCloseButton = function() { this.set('hideCloseButton', false); }; InfoBubble.prototype['showCloseButton'] = InfoBubble.prototype.showCloseButton; /** * Hide the close button */ InfoBubble.prototype.hideCloseButton = function() { this.set('hideCloseButton', true); }; InfoBubble.prototype['hideCloseButton'] = InfoBubble.prototype.hideCloseButton; /** * hideCloseButton changed MVC callback */ InfoBubble.prototype.hideCloseButton_changed = function() { this.close_.style['display'] = this.get('hideCloseButton') ? 'none' : ''; }; InfoBubble.prototype['hideCloseButton_changed'] = InfoBubble.prototype.hideCloseButton_changed; /** * Set the background color * * @param {string} color The color to set. */ InfoBubble.prototype.setBackgroundColor = function(color) { if (color) { this.set('backgroundColor', color); } }; InfoBubble.prototype['setBackgroundColor'] = InfoBubble.prototype.setBackgroundColor; /** * backgroundColor changed MVC callback */ InfoBubble.prototype.backgroundColor_changed = function() { var backgroundColor = this.get('backgroundColor'); this.contentContainer_.style['backgroundColor'] = backgroundColor; this.arrowInner_.style['borderColor'] = backgroundColor + ' transparent transparent'; this.updateTabStyles_(); }; InfoBubble.prototype['backgroundColor_changed'] = InfoBubble.prototype.backgroundColor_changed; /** * Set the border color * * @param {string} color The border color. */ InfoBubble.prototype.setBorderColor = function(color) { if (color) { this.set('borderColor', color); } }; InfoBubble.prototype['setBorderColor'] = InfoBubble.prototype.setBorderColor; /** * borderColor changed MVC callback */ InfoBubble.prototype.borderColor_changed = function() { var borderColor = this.get('borderColor'); var contentContainer = this.contentContainer_; var arrowOuter = this.arrowOuter_; contentContainer.style['borderColor'] = borderColor; arrowOuter.style['borderColor'] = borderColor + ' transparent transparent'; contentContainer.style['borderStyle'] = arrowOuter.style['borderStyle'] = this.arrowInner_.style['borderStyle'] = 'solid'; this.updateTabStyles_(); }; InfoBubble.prototype['borderColor_changed'] = InfoBubble.prototype.borderColor_changed; /** * Set the radius of the border * * @param {number} radius The radius of the border. */ InfoBubble.prototype.setBorderRadius = function(radius) { this.set('borderRadius', radius); }; InfoBubble.prototype['setBorderRadius'] = InfoBubble.prototype.setBorderRadius; /** * Get the radius of the border * * @private * @return {number} The radius of the border. */ InfoBubble.prototype.getBorderRadius_ = function() { return parseInt(this.get('borderRadius'), 10) || 0; }; /** * borderRadius changed MVC callback */ InfoBubble.prototype.borderRadius_changed = function() { var borderRadius = this.getBorderRadius_(); var borderWidth = this.getBorderWidth_(); this.contentContainer_.style['borderRadius'] = this.contentContainer_.style['MozBorderRadius'] = this.contentContainer_.style['webkitBorderRadius'] = this.bubbleShadow_.style['borderRadius'] = this.bubbleShadow_.style['MozBorderRadius'] = this.bubbleShadow_.style['webkitBorderRadius'] = this.px(borderRadius); this.tabsContainer_.style['paddingLeft'] = this.tabsContainer_.style['paddingRight'] = this.px(borderRadius + borderWidth); this.redraw_(); }; InfoBubble.prototype['borderRadius_changed'] = InfoBubble.prototype.borderRadius_changed; /** * Get the width of the border * * @private * @return {number} width The width of the border. */ InfoBubble.prototype.getBorderWidth_ = function() { return parseInt(this.get('borderWidth'), 10) || 0; }; /** * Set the width of the border * * @param {number} width The width of the border. */ InfoBubble.prototype.setBorderWidth = function(width) { this.set('borderWidth', width); }; InfoBubble.prototype['setBorderWidth'] = InfoBubble.prototype.setBorderWidth; /** * borderWidth change MVC callback */ InfoBubble.prototype.borderWidth_changed = function() { var borderWidth = this.getBorderWidth_(); this.contentContainer_.style['borderWidth'] = this.px(borderWidth); this.tabsContainer_.style['top'] = this.px(borderWidth); this.updateArrowStyle_(); this.updateTabStyles_(); this.borderRadius_changed(); this.redraw_(); }; InfoBubble.prototype['borderWidth_changed'] = InfoBubble.prototype.borderWidth_changed; /** * Update the arrow style * @private */ InfoBubble.prototype.updateArrowStyle_ = function() { var borderWidth = this.getBorderWidth_(); var arrowSize = this.getArrowSize_(); var arrowStyle = this.getArrowStyle_(); var arrowOuterSizePx = this.px(arrowSize); var arrowInnerSizePx = this.px(Math.max(0, arrowSize - borderWidth)); var outer = this.arrowOuter_; var inner = this.arrowInner_; this.arrow_.style['marginTop'] = this.px(-borderWidth); outer.style['borderTopWidth'] = arrowOuterSizePx; inner.style['borderTopWidth'] = arrowInnerSizePx; // Full arrow or arrow pointing to the left if (arrowStyle == 0 || arrowStyle == 1) { outer.style['borderLeftWidth'] = arrowOuterSizePx; inner.style['borderLeftWidth'] = arrowInnerSizePx; } else { outer.style['borderLeftWidth'] = inner.style['borderLeftWidth'] = 0; } // Full arrow or arrow pointing to the right if (arrowStyle == 0 || arrowStyle == 2) { outer.style['borderRightWidth'] = arrowOuterSizePx; inner.style['borderRightWidth'] = arrowInnerSizePx; } else { outer.style['borderRightWidth'] = inner.style['borderRightWidth'] = 0; } if (arrowStyle < 2) { outer.style['marginLeft'] = this.px(-(arrowSize)); inner.style['marginLeft'] = this.px(-(arrowSize - borderWidth)); } else { outer.style['marginLeft'] = inner.style['marginLeft'] = 0; } // If there is no border then don't show thw outer arrow if (borderWidth == 0) { outer.style['display'] = 'none'; } else { outer.style['display'] = ''; } }; /** * Set the padding of the InfoBubble * * @param {number} padding The padding to apply. */ InfoBubble.prototype.setPadding = function(padding) { this.set('padding', padding); }; InfoBubble.prototype['setPadding'] = InfoBubble.prototype.setPadding; /** * Set the padding of the InfoBubble * * @private * @return {number} padding The padding to apply. */ InfoBubble.prototype.getPadding_ = function() { return parseInt(this.get('padding'), 10) || 0; }; /** * padding changed MVC callback */ InfoBubble.prototype.padding_changed = function() { var padding = this.getPadding_(); this.contentContainer_.style['padding'] = this.px(padding); this.updateTabStyles_(); this.redraw_(); }; InfoBubble.prototype['padding_changed'] = InfoBubble.prototype.padding_changed; /** * Add px extention to the number * * @param {number} num The number to wrap. * @return {string|number} A wrapped number. */ InfoBubble.prototype.px = function(num) { if (num) { // 0 doesn't need to be wrapped return num + 'px'; } return num; }; /** * Add events to stop propagation * @private */ InfoBubble.prototype.addEvents_ = function() { // We want to cancel all the events so they do not go to the map var events = ['mousedown', 'mousemove', 'mouseover', 'mouseout', 'mouseup', 'mousewheel', 'DOMMouseScroll', 'touchstart', 'touchend', 'touchmove', 'dblclick', 'contextmenu', 'click']; var bubble = this.bubble_; this.listeners_ = []; for (var i = 0, event; event = events[i]; i++) { this.listeners_.push( google.maps.event.addDomListener(bubble, event, function(e) { e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } }) ); } }; /** * On Adding the InfoBubble to a map * Implementing the OverlayView interface */ InfoBubble.prototype.onAdd = function() { if (!this.bubble_) { this.buildDom_(); } this.addEvents_(); var panes = this.getPanes(); if (panes) { panes.floatPane.appendChild(this.bubble_); panes.floatShadow.appendChild(this.bubbleShadow_); } }; InfoBubble.prototype['onAdd'] = InfoBubble.prototype.onAdd; /** * Draw the InfoBubble * Implementing the OverlayView interface */ InfoBubble.prototype.draw = function() { var projection = this.getProjection(); if (!projection) { // The map projection is not ready yet so do nothing return; } var latLng = /** @type {google.maps.LatLng} */ (this.get('position')); if (!latLng) { this.close(); return; } var tabHeight = 0; if (this.activeTab_) { tabHeight = this.activeTab_.offsetHeight; } var anchorHeight = this.getAnchorHeight_(); var arrowSize = this.getArrowSize_(); var arrowPosition = this.getArrowPosition_(); arrowPosition = arrowPosition / 100; var pos = projection.fromLatLngToDivPixel(latLng); var width = this.contentContainer_.offsetWidth; var height = this.bubble_.offsetHeight; if (!width) { return; } // Adjust for the height of the info bubble var top = pos.y - (height + arrowSize); if (anchorHeight) { // If there is an anchor then include the height top -= anchorHeight; } var left = pos.x - (width * arrowPosition); this.bubble_.style['top'] = this.px(top); this.bubble_.style['left'] = this.px(left); var shadowStyle = parseInt(this.get('shadowStyle'), 10); switch (shadowStyle) { case 1: // Shadow is behind this.bubbleShadow_.style['top'] = this.px(top + tabHeight - 1); this.bubbleShadow_.style['left'] = this.px(left); this.bubbleShadow_.style['width'] = this.px(width); this.bubbleShadow_.style['height'] = this.px(this.contentContainer_.offsetHeight - arrowSize); break; case 2: // Shadow is below width = width * 0.8; if (anchorHeight) { this.bubbleShadow_.style['top'] = this.px(pos.y); } else { this.bubbleShadow_.style['top'] = this.px(pos.y + arrowSize); } this.bubbleShadow_.style['left'] = this.px(pos.x - width * arrowPosition); this.bubbleShadow_.style['width'] = this.px(width); this.bubbleShadow_.style['height'] = this.px(2); break; } }; InfoBubble.prototype['draw'] = InfoBubble.prototype.draw; /** * Removing the InfoBubble from a map */ InfoBubble.prototype.onRemove = function() { if (this.bubble_ && this.bubble_.parentNode) { this.bubble_.parentNode.removeChild(this.bubble_); } if (this.bubbleShadow_ && this.bubbleShadow_.parentNode) { this.bubbleShadow_.parentNode.removeChild(this.bubbleShadow_); } for (var i = 0, listener; listener = this.listeners_[i]; i++) { google.maps.event.removeListener(listener); } }; InfoBubble.prototype['onRemove'] = InfoBubble.prototype.onRemove; /** * Is the InfoBubble open * * @return {boolean} If the InfoBubble is open. */ InfoBubble.prototype.isOpen = function() { return this.isOpen_; }; InfoBubble.prototype['isOpen'] = InfoBubble.prototype.isOpen; /** * Close the InfoBubble */ InfoBubble.prototype.close = function() { if (this.bubble_) { this.bubble_.style['display'] = 'none'; // Remove the animation so we next time it opens it will animate again this.bubble_.className = this.bubble_.className.replace(this.animationName_, ''); } if (this.bubbleShadow_) { this.bubbleShadow_.style['display'] = 'none'; this.bubbleShadow_.className = this.bubbleShadow_.className.replace(this.animationName_, ''); } this.isOpen_ = false; }; InfoBubble.prototype['close'] = InfoBubble.prototype.close; /** * Open the InfoBubble (asynchronous). * * @param {google.maps.Map=} opt_map Optional map to open on. * @param {google.maps.MVCObject=} opt_anchor Optional anchor to position at. */ InfoBubble.prototype.open = function(opt_map, opt_anchor) { var that = this; window.setTimeout(function() { that.open_(opt_map, opt_anchor); }, 0); }; /** * Open the InfoBubble * @private * @param {google.maps.Map=} opt_map Optional map to open on. * @param {google.maps.MVCObject=} opt_anchor Optional anchor to position at. */ InfoBubble.prototype.open_ = function(opt_map, opt_anchor) { this.updateContent_(); if (opt_map) { this.setMap(opt_map); } if (opt_anchor) { this.set('anchor', opt_anchor); this.bindTo('anchorPoint', opt_anchor); this.bindTo('position', opt_anchor); } // Show the bubble and the show this.bubble_.style['display'] = this.bubbleShadow_.style['display'] = ''; var animation = !this.get('disableAnimation'); if (animation) { // Add the animation this.bubble_.className += ' ' + this.animationName_; this.bubbleShadow_.className += ' ' + this.animationName_; } this.redraw_(); this.isOpen_ = true; var pan = !this.get('disableAutoPan'); if (pan) { var that = this; window.setTimeout(function() { // Pan into view, done in a time out to make it feel nicer :) that.panToView(); }, 200); } }; InfoBubble.prototype['open'] = InfoBubble.prototype.open; /** * Set the position of the InfoBubble * * @param {google.maps.LatLng} position The position to set. */ InfoBubble.prototype.setPosition = function(position) { if (position) { this.set('position', position); } }; InfoBubble.prototype['setPosition'] = InfoBubble.prototype.setPosition; /** * Returns the position of the InfoBubble * * @return {google.maps.LatLng} the position. */ InfoBubble.prototype.getPosition = function() { return /** @type {google.maps.LatLng} */ (this.get('position')); }; InfoBubble.prototype['getPosition'] = InfoBubble.prototype.getPosition; /** * position changed MVC callback */ InfoBubble.prototype.position_changed = function() { this.draw(); }; InfoBubble.prototype['position_changed'] = InfoBubble.prototype.position_changed; /** * Pan the InfoBubble into view */ InfoBubble.prototype.panToView = function() { var projection = this.getProjection(); if (!projection) { // The map projection is not ready yet so do nothing return; } if (!this.bubble_) { // No Bubble yet so do nothing return; } var anchorHeight = this.getAnchorHeight_(); var height = this.bubble_.offsetHeight + anchorHeight; var map = this.get('map'); var mapDiv = map.getDiv(); var mapHeight = mapDiv.offsetHeight; var latLng = this.getPosition(); var centerPos = projection.fromLatLngToContainerPixel(map.getCenter()); var pos = projection.fromLatLngToContainerPixel(latLng); // Find out how much space at the top is free var spaceTop = centerPos.y - height; // Fine out how much space at the bottom is free var spaceBottom = mapHeight - centerPos.y; var needsTop = spaceTop < 0; var deltaY = 0; if (needsTop) { spaceTop *= -1; deltaY = (spaceTop + spaceBottom) / 2; } pos.y -= deltaY; latLng = projection.fromContainerPixelToLatLng(pos); if (map.getCenter() != latLng) { map.panTo(latLng); } }; InfoBubble.prototype['panToView'] = InfoBubble.prototype.panToView; /** * Converts a HTML string to a document fragment. * * @param {string} htmlString The HTML string to convert. * @return {Node} A HTML document fragment. * @private */ InfoBubble.prototype.htmlToDocumentFragment_ = function(htmlString) { htmlString = htmlString.replace(/^\s*([\S\s]*)\b\s*$/, '$1'); var tempDiv = document.createElement('DIV'); tempDiv.innerHTML = htmlString; if (tempDiv.childNodes.length == 1) { return /** @type {!Node} */ (tempDiv.removeChild(tempDiv.firstChild)); } else { var fragment = document.createDocumentFragment(); while (tempDiv.firstChild) { fragment.appendChild(tempDiv.firstChild); } return fragment; } }; /** * Removes all children from the node. * * @param {Node} node The node to remove all children from. * @private */ InfoBubble.prototype.removeChildren_ = function(node) { if (!node) { return; } var child; while (child = node.firstChild) { node.removeChild(child); } }; /** * Sets the content of the infobubble. * * @param {string|Node} content The content to set. */ InfoBubble.prototype.setContent = function(content) { this.set('content', content); }; InfoBubble.prototype['setContent'] = InfoBubble.prototype.setContent; /** * Get the content of the infobubble. * * @return {string|Node} The marker content. */ InfoBubble.prototype.getContent = function() { return /** @type {Node|string} */ (this.get('content')); }; InfoBubble.prototype['getContent'] = InfoBubble.prototype.getContent; /** * Sets the marker content and adds loading events to images */ InfoBubble.prototype.updateContent_ = function() { if (!this.content_) { // The Content area doesnt exist. return; } this.removeChildren_(this.content_); var content = this.getContent(); if (content) { if (typeof content == 'string') { content = this.htmlToDocumentFragment_(content); } this.content_.appendChild(content); var that = this; var images = this.content_.getElementsByTagName('IMG'); for (var i = 0, image; image = images[i]; i++) { // Because we don't know the size of an image till it loads, add a // listener to the image load so the marker can resize and reposition // itself to be the correct height. google.maps.event.addDomListener(image, 'load', function() { that.imageLoaded_(); }); } google.maps.event.trigger(this, 'domready'); } this.redraw_(); }; /** * Image loaded * @private */ InfoBubble.prototype.imageLoaded_ = function() { var pan = !this.get('disableAutoPan'); this.redraw_(); if (pan && (this.tabs_.length == 0 || this.activeTab_.index == 0)) { this.panToView(); } }; /** * Updates the styles of the tabs * @private */ InfoBubble.prototype.updateTabStyles_ = function() { if (this.tabs_ && this.tabs_.length) { for (var i = 0, tab; tab = this.tabs_[i]; i++) { this.setTabStyle_(tab.tab); } this.activeTab_.style['zIndex'] = this.baseZIndex_; var borderWidth = this.getBorderWidth_(); var padding = this.getPadding_() / 2; this.activeTab_.style['borderBottomWidth'] = 0; this.activeTab_.style['paddingBottom'] = this.px(padding + borderWidth); } }; /** * Sets the style of a tab * @private * @param {Element} tab The tab to style. */ InfoBubble.prototype.setTabStyle_ = function(tab) { var backgroundColor = this.get('backgroundColor'); var borderColor = this.get('borderColor'); var borderRadius = this.getBorderRadius_(); var borderWidth = this.getBorderWidth_(); var padding = this.getPadding_(); var marginRight = this.px(-(Math.max(padding, borderRadius))); var borderRadiusPx = this.px(borderRadius); var index = this.baseZIndex_; if (tab.index) { index -= tab.index; } // The styles for the tab var styles = { 'cssFloat': 'left', 'position': 'relative', 'cursor': 'pointer', 'backgroundColor': backgroundColor, 'border': this.px(borderWidth) + ' solid ' + borderColor, 'padding': this.px(padding / 2) + ' ' + this.px(padding), 'marginRight': marginRight, 'whiteSpace': 'nowrap', 'borderRadiusTopLeft': borderRadiusPx, 'MozBorderRadiusTopleft': borderRadiusPx, 'webkitBorderTopLeftRadius': borderRadiusPx, 'borderRadiusTopRight': borderRadiusPx, 'MozBorderRadiusTopright': borderRadiusPx, 'webkitBorderTopRightRadius': borderRadiusPx, 'zIndex': index, 'display': 'inline' }; for (var style in styles) { tab.style[style] = styles[style]; } var className = this.get('tabClassName'); if (className != undefined) { tab.className += ' ' + className; } }; /** * Add user actions to a tab * @private * @param {Object} tab The tab to add the actions to. */ InfoBubble.prototype.addTabActions_ = function(tab) { var that = this; tab.listener_ = google.maps.event.addDomListener(tab, 'click', function() { that.setTabActive_(this); }); }; /** * Set a tab at a index to be active * * @param {number} index The index of the tab. */ InfoBubble.prototype.setTabActive = function(index) { var tab = this.tabs_[index - 1]; if (tab) { this.setTabActive_(tab.tab); } }; InfoBubble.prototype['setTabActive'] = InfoBubble.prototype.setTabActive; /** * Set a tab to be active * @private * @param {Object} tab The tab to set active. */ InfoBubble.prototype.setTabActive_ = function(tab) { if (!tab) { this.setContent(''); this.updateContent_(); return; } var padding = this.getPadding_() / 2; var borderWidth = this.getBorderWidth_(); if (this.activeTab_) { var activeTab = this.activeTab_; activeTab.style['zIndex'] = this.baseZIndex_ - activeTab.index; activeTab.style['paddingBottom'] = this.px(padding); activeTab.style['borderBottomWidth'] = this.px(borderWidth); } tab.style['zIndex'] = this.baseZIndex_; tab.style['borderBottomWidth'] = 0; tab.style['marginBottomWidth'] = '-10px'; tab.style['paddingBottom'] = this.px(padding + borderWidth); this.setContent(this.tabs_[tab.index].content); this.updateContent_(); this.activeTab_ = tab; this.redraw_(); }; /** * Set the max width of the InfoBubble * * @param {number} width The max width. */ InfoBubble.prototype.setMaxWidth = function(width) { this.set('maxWidth', width); }; InfoBubble.prototype['setMaxWidth'] = InfoBubble.prototype.setMaxWidth; /** * maxWidth changed MVC callback */ InfoBubble.prototype.maxWidth_changed = function() { this.redraw_(); }; InfoBubble.prototype['maxWidth_changed'] = InfoBubble.prototype.maxWidth_changed; /** * Set the max height of the InfoBubble * * @param {number} height The max height. */ InfoBubble.prototype.setMaxHeight = function(height) { this.set('maxHeight', height); }; InfoBubble.prototype['setMaxHeight'] = InfoBubble.prototype.setMaxHeight; /** * maxHeight changed MVC callback */ InfoBubble.prototype.maxHeight_changed = function() { this.redraw_(); }; InfoBubble.prototype['maxHeight_changed'] = InfoBubble.prototype.maxHeight_changed; /** * Set the min width of the InfoBubble * * @param {number} width The min width. */ InfoBubble.prototype.setMinWidth = function(width) { this.set('minWidth', width); }; InfoBubble.prototype['setMinWidth'] = InfoBubble.prototype.setMinWidth; /** * minWidth changed MVC callback */ InfoBubble.prototype.minWidth_changed = function() { this.redraw_(); }; InfoBubble.prototype['minWidth_changed'] = InfoBubble.prototype.minWidth_changed; /** * Set the min height of the InfoBubble * * @param {number} height The min height. */ InfoBubble.prototype.setMinHeight = function(height) { this.set('minHeight', height); }; InfoBubble.prototype['setMinHeight'] = InfoBubble.prototype.setMinHeight; /** * minHeight changed MVC callback */ InfoBubble.prototype.minHeight_changed = function() { this.redraw_(); }; InfoBubble.prototype['minHeight_changed'] = InfoBubble.prototype.minHeight_changed; /** * Add a tab * * @param {string} label The label of the tab. * @param {string|Element} content The content of the tab. */ InfoBubble.prototype.addTab = function(label, content) { var tab = document.createElement('DIV'); tab.innerHTML = label; this.setTabStyle_(tab); this.addTabActions_(tab); this.tabsContainer_.appendChild(tab); this.tabs_.push({ label: label, content: content, tab: tab }); tab.index = this.tabs_.length - 1; tab.style['zIndex'] = this.baseZIndex_ - tab.index; if (!this.activeTab_) { this.setTabActive_(tab); } tab.className = tab.className + ' ' + this.animationName_; this.redraw_(); }; InfoBubble.prototype['addTab'] = InfoBubble.prototype.addTab; /** * Update a tab at a speicifc index * * @param {number} index The index of the tab. * @param {?string} opt_label The label to change to. * @param {?string} opt_content The content to update to. */ InfoBubble.prototype.updateTab = function(index, opt_label, opt_content) { if (!this.tabs_.length || index < 0 || index >= this.tabs_.length) { return; } var tab = this.tabs_[index]; if (opt_label != undefined) { tab.tab.innerHTML = tab.label = opt_label; } if (opt_content != undefined) { tab.content = opt_content; } if (this.activeTab_ == tab.tab) { this.setContent(tab.content); this.updateContent_(); } this.redraw_(); }; InfoBubble.prototype['updateTab'] = InfoBubble.prototype.updateTab; /** * Remove a tab at a specific index * * @param {number} index The index of the tab to remove. */ InfoBubble.prototype.removeTab = function(index) { if (!this.tabs_.length || index < 0 || index >= this.tabs_.length) { return; } var tab = this.tabs_[index]; tab.tab.parentNode.removeChild(tab.tab); google.maps.event.removeListener(tab.tab.listener_); this.tabs_.splice(index, 1); delete tab; for (var i = 0, t; t = this.tabs_[i]; i++) { t.tab.index = i; } if (tab.tab == this.activeTab_) { // Removing the current active tab if (this.tabs_[index]) { // Show the tab to the right this.activeTab_ = this.tabs_[index].tab; } else if (this.tabs_[index - 1]) { // Show a tab to the left this.activeTab_ = this.tabs_[index - 1].tab; } else { // No tabs left to sho this.activeTab_ = undefined; } this.setTabActive_(this.activeTab_); } this.redraw_(); }; InfoBubble.prototype['removeTab'] = InfoBubble.prototype.removeTab; /** * Get the size of an element * @private * @param {Node|string} element The element to size. * @param {number=} opt_maxWidth Optional max width of the element. * @param {number=} opt_maxHeight Optional max height of the element. * @return {google.maps.Size} The size of the element. */ InfoBubble.prototype.getElementSize_ = function(element, opt_maxWidth, opt_maxHeight) { var sizer = document.createElement('DIV'); sizer.style['display'] = 'inline'; sizer.style['position'] = 'absolute'; sizer.style['visibility'] = 'hidden'; if (typeof element == 'string') { sizer.innerHTML = element; } else { sizer.appendChild(element.cloneNode(true)); } document.body.appendChild(sizer); var size = new google.maps.Size(sizer.offsetWidth, sizer.offsetHeight); // If the width is bigger than the max width then set the width and size again if (opt_maxWidth && size.width > opt_maxWidth) { sizer.style['width'] = this.px(opt_maxWidth); size = new google.maps.Size(sizer.offsetWidth, sizer.offsetHeight); } // If the height is bigger than the max height then set the height and size // again if (opt_maxHeight && size.height > opt_maxHeight) { sizer.style['height'] = this.px(opt_maxHeight); size = new google.maps.Size(sizer.offsetWidth, sizer.offsetHeight); } document.body.removeChild(sizer); delete sizer; return size; }; /** * Redraw the InfoBubble * @private */ InfoBubble.prototype.redraw_ = function() { this.figureOutSize_(); this.positionCloseButton_(); this.draw(); }; /** * Figure out the optimum size of the InfoBubble * @private */ InfoBubble.prototype.figureOutSize_ = function() { var map = this.get('map'); if (!map) { return; } var padding = this.getPadding_(); var borderWidth = this.getBorderWidth_(); var borderRadius = this.getBorderRadius_(); var arrowSize = this.getArrowSize_(); var mapDiv = map.getDiv(); var gutter = arrowSize * 2; var mapWidth = mapDiv.offsetWidth - gutter; var mapHeight = mapDiv.offsetHeight - gutter - this.getAnchorHeight_(); var tabHeight = 0; var width = /** @type {number} */ (this.get('minWidth') || 0); var height = /** @type {number} */ (this.get('minHeight') || 0); var maxWidth = /** @type {number} */ (this.get('maxWidth') || 0); var maxHeight = /** @type {number} */ (this.get('maxHeight') || 0); maxWidth = Math.min(mapWidth, maxWidth); maxHeight = Math.min(mapHeight, maxHeight); var tabWidth = 0; if (this.tabs_.length) { // If there are tabs then you need to check the size of each tab's content for (var i = 0, tab; tab = this.tabs_[i]; i++) { var tabSize = this.getElementSize_(tab.tab, maxWidth, maxHeight); var contentSize = this.getElementSize_(tab.content, maxWidth, maxHeight); if (width < tabSize.width) { width = tabSize.width; } // Add up all the tab widths because they might end up being wider than // the content tabWidth += tabSize.width; if (height < tabSize.height) { height = tabSize.height; } if (tabSize.height > tabHeight) { tabHeight = tabSize.height; } if (width < contentSize.width) { width = contentSize.width; } if (height < contentSize.height) { height = contentSize.height; } } } else { var content = /** @type {string|Node} */ (this.get('content')); if (typeof content == 'string') { content = this.htmlToDocumentFragment_(content); } if (content) { var contentSize = this.getElementSize_(content, maxWidth, maxHeight); if (width < contentSize.width) { width = contentSize.width; } if (height < contentSize.height) { height = contentSize.height; } } } if (maxWidth) { width = Math.min(width, maxWidth); } if (maxHeight) { height = Math.min(height, maxHeight); } width = Math.max(width, tabWidth); if (width == tabWidth) { width = width + 2 * padding; } arrowSize = arrowSize * 2; width = Math.max(width, arrowSize); // Maybe add this as a option so they can go bigger than the map if the user // wants if (width > mapWidth) { width = mapWidth; } if (height > mapHeight) { height = mapHeight - tabHeight; } if (this.tabsContainer_) { this.tabHeight_ = tabHeight; this.tabsContainer_.style['width'] = this.px(tabWidth); } this.contentContainer_.style['width'] = this.px(width); this.contentContainer_.style['height'] = this.px(height); }; /** * Get the height of the anchor * * This function is a hack for now and doesn't really work that good, need to * wait for pixelBounds to be correctly exposed. * @private * @return {number} The height of the anchor. */ InfoBubble.prototype.getAnchorHeight_ = function() { var anchor = this.get('anchor'); if (anchor) { var anchorPoint = /** @type google.maps.Point */(this.get('anchorPoint')); if (anchorPoint) { return -1 * anchorPoint.y; } } return 0; }; InfoBubble.prototype.anchorPoint_changed = function() { this.draw(); }; InfoBubble.prototype['anchorPoint_changed'] = InfoBubble.prototype.anchorPoint_changed; /** * Position the close button in the right spot. * @private */ InfoBubble.prototype.positionCloseButton_ = function() { var br = this.getBorderRadius_(); var bw = this.getBorderWidth_(); var right = 2; var top = 2; if (this.tabs_.length && this.tabHeight_) { top += this.tabHeight_; } top += bw; right += bw; var c = this.contentContainer_; if (c && c.clientHeight < c.scrollHeight) { // If there are scrollbars then move the cross in so it is not over // scrollbar right += 15; } this.close_.style['right'] = this.px(right); this.close_.style['top'] = this.px(top); };
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Map Locator behavior (extension of Google Map behavior) * * Usage: * * <div id="map"></div> * * <div id="container"> * <ul> * <li data-id="address_1" data-address="Pitt St Sydney NSW 2000">Address</li> * <li data-id="address_2" data-address="Kent St Brisbane QLD 4000">Address</li> * </ul> * </div> * * <div style="display:none"> * <div id="location_address_1">Bubble content for Sydney!</div> * <div id="location_address_2">Bubble content for Brisvegas!</div> * </div> * * <script> * $('#map') * .behavior(ahoy.behaviors.map, {allow_drag: true, allow_scroll:true}) * .behavior('use_behavior', [ahoy.behaviors.map_locator, { container: '#container' }]); * </script> * * <a href="#" onclick="$('#map').behavior('focus_location', ['address_1'])">Focus address 1</a> */ ahoy.behaviors.map_locator = function(element, config) { var self = this; self.element = element = $(element); var defaults = { marker_image: null, content_id_prefix: '#location_', container: '#locations', // Container with locations map_obj: null }; self.config = config = $.extend(true, defaults, config); this.event_chain = []; this.container = $(config.container); this.map = config.map_obj; this.init = function() { // Locations element.behavior('use_behavior', [ahoy.behaviors.map_bubble]); self.build_locations(); self.bind_locations(); }; this.bind_locations = function() { self.event_chain.push(function() { element.behavior('align_to_markers'); }); $.waterfall.apply(this, self.event_chain).fail(function(){}).done(function(){}); }; this.build_locations = function(address, id) { // Loop each item self.container.find('ul li').each(function(){ var address_string = $(this).data('address'); var address_id = $(this).data('id'); var content_panel = $(config.content_id_prefix+address_id); var content_html = content_panel.html(); self.event_chain.push(function() { var deferred = $.Deferred(); element.behavior('get_address', [address_string, { callback: function(address){ element.behavior('draw_bubble', [address, { bubble_id:address_id, content:content_html } ]); deferred.resolve(); } }]); return deferred; }); }); }; this.focus_location = function(id) { element.behavior('display_bubble', [id]); }; this.init(); };
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Role select behavior */ ahoy.behaviors.role_select = function(element, config) { var self = this; element = $(element); var defaults = { on_select: null // Callback after selection }; config = $.extend(true, defaults, config); element.autocomplete({ minLength: 2, source: function(request, response) { ahoy.post(element).action('service:on_search_categories').data('search', request.term).success(function(raw_data, data){ if ($.trim(data) == "") return; var json = []; var result = $.parseJSON(data); $.each(result, function(k,v){ if (v.parent_id) { // Only add child categories json.push(v.name); } }); if (json) response(json); return; }).send(); }, select: function(event, ui) { config.on_select && config.on_select(self, ui.item.value); } }); };
JavaScript
/** * Ajax interface * * Usage: ahoy.post('#form').action('core:on_null').success(function(){ alert('Success!'); }).send(); */ var Ahoy = (function(ahoy, $){ ahoy.post = function(obj) { return new ahoy.post_object(obj); }; ahoy.post_object = function(obj) { this._data = { update: {}, extraFields: {}, selectorMode: true }; this._action = 'core:on_null'; this._form = null; // Manually sets a field/value this.set = function(field, value) { this._data[field] = value; return this; }; // Used at the end of chaining to fire the ajax call this.send = function() { var self = this; ahoy.self = self._form; return self._form.sendRequest(self._action, self._data); }; // Defines an ajax action (optional) this.action = function(value) { this._action = value; return this; }; this.confirm = function(value) { this._data.confirm = value; return this; }; this.success = function(func) { this._data.onSuccess = func; return this; }; this.error = function(func) { this._data.onFailure = func; return this; }; this.prepare = function(func, pre_check) { if (pre_check) this._data.preCheckFunction = func; else this._data.onBeforePost = func; return this; }; this.complete = function(func, after_update) { if (after_update) this._data.onAfterUpdate = func; else this._data.onComplete = func; return this; }; this.update = function(element, partial) { if (partial) this._data.update[element] = partial; else this._data.update = element; return this; }; this.data = function(field, value) { if (value !== undefined) this._data.extraFields[field] = value; else this._data.extraFields = field; return this; }; this.get_form = function(form) { form = (!form) ? jQuery('<form></form>') : form; form = (form instanceof jQuery) ? form : jQuery(form); form = (form.is('form')) ? form : form.closest('form'); form = (form.attr('id')) ? jQuery('form#'+form.attr('id')) : form.attr('id', 'form_element'); return form; }; this._form = this.get_form(obj); }; return ahoy; }(Ahoy || {}, jQuery))
JavaScript
// General // jQuery.validator.addMethod("phoneUS", function (phone_number, element) { phone_number = phone_number.replace(/\s+/g, ""); return this.optional(element) || phone_number.length >= 5 && phone_number.match(/^(1-?)?(\([2-9]\d{2}\)|[2-9]\d{2})-?[2-9]\d{2}-?\d{4}$/); }, "Please specify a valid phone number"); jQuery.validator.addMethod('phoneUK', function (phone_number, element) { phone_number = phone_number.replace(" ", ""); return this.optional(element) || phone_number.length > 9 && (phone_number.match(/^(\(?(0|\+?44)[1-9]{1}\d{1,4}?\)?\s?\d{3,4}\s?\d{3,4})$/) || phone_number.match(/^((0|\+?44)7(5|6|7|8|9){1}\d{2}\s?\d{6})$/)); }, 'Please specify a valid phone number'); jQuery.validator.addMethod("phoneAU", function (phone_number, element) { phone_number = phone_number.split(' ').join(''); return this.optional(element) || phone_number.length >= 5 && phone_number.match(/(^1300\d{6}$)|(^1800|1900|1902\d{6}$)|(^0[2|3|7|8]{1}[0-9]{8}$)|(^13\d{4}$)|(^04\d{2,3}\d{6}$)/); }, "Please specify a valid phone number"); jQuery.validator.addMethod("phone", function (phone_number, element) { phone_number = phone_number.replace(/[\s()+-]|ext\.?/gi, ""); return this.optional(element) || phone_number.length >= 5 && phone_number.match(/\d{6,}/); }, "Please specify a valid phone number"); jQuery.validator.addMethod("postCode", function (post_code, element) { post_code = post_code.replace(/\s+/g, ""); return this.optional(element) || post_code.length < 8 && post_code.length > 4 && post_code.match(/^[a-zA-Z]{1,2}[0-9]{1,3}([a-zA-Z]{1}[0-9]{1})*[a-zA-Z]{2}$/); }, "Please specify a valid post/zip code"); jQuery.validator.addMethod("minWord", function (value, element, param) { var words = value.split(/\s/gi); var result = this.optional(element) || words.length >= param; /* Don't be too picky */ if ($(element).attr("minword") == "true") return true; if (!result) $(element).attr("minword", "true"); return result; }, "Please type more words"); jQuery.validator.addMethod("maxWord", function (value, element, param) { var words = value.split(/\s/gi); return this.optional(element) || words.length <= param; }, "Please type less words"); jQuery.validator.addMethod("regExp", function (value, element, regexp) { var re = new RegExp(regexp); return this.optional(element) || value.match(re); }, "Please check your input."); jQuery.validator.addMethod("fullUrl", function(val, elem) { if (val.length == 0) { return true; } if(!/^(https?|ftp):\/\//i.test(val)) { val = 'http://'+val; $(elem).val(val); } return /^(https?|ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&amp;'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&amp;'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&amp;'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&amp;'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&amp;'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(val); }, "Please enter a valid URL"); jQuery.validator.addMethod('required_multi', function(value, element, options) { numberRequired = options[0]; selector = options[1]; var numberFilled = $(selector, element.form).filter(function() { return $(this).val(); }).length; var valid = numberFilled >= numberRequired; return valid; }); // Ahoy specific // jQuery.validator.addMethod("ahoyDate", function(value, element) { return Date.parse(value, ahoy.settings.date_format); }, "Please enter a valid date"); // Remote using AJAX engine jQuery.validator.addMethod("ahoyRemote", function(value, element, param) { if (jQuery(element).hasClass('ignore_validate')) return true; if ( this.optional(element) ) return "dependency-mismatch"; // Defaults param = jQuery.extend(true, { action: null }, param); var previous = this.previousValue(element); if (!this.settings.messages[element.name] ) this.settings.messages[element.name] = {}; previous.originalMessage = this.settings.messages[element.name].remote; this.settings.messages[element.name].remote = previous.message; param = typeof param == "string" && {action:param} || param; if ( this.pending[element.name] ) { return "pending"; } if ( previous.old === value ) { return previous.valid; } previous.old = value; var validator = this; this.startRequest(element); Ahoy.post(element) .action(param.action) .data('jquery_validate', true) .data(element.name, value) .success(function(data, response) { validator.settings.messages[element.name].remote = previous.originalMessage; var valid = response == "true"; if ( valid ) { var submitted = validator.formSubmitted; validator.prepareElement(element); validator.formSubmitted = submitted; validator.successList.push(element); validator.showErrors(); } else { var errors = {}; var message = response || validator.defaultMessage( element, "ahoyRemote" ); errors[element.name] = previous.message = $.isFunction(message) ? message(value) : message; validator.showErrors(errors); } previous.valid = valid; validator.stopRequest(element, valid); }) .send(); return "pending"; }, "Please fix this field.");
JavaScript
/** * Form helper * * Usage: * * // Define single field * Ahoy.form.define_field('user:register_form', 'email').required("This is required!"); * * // Define multiple fields * Ahoy.form.define_fields('user:register_form', function() { * this.define_field('email').required('This is required!').email('Enter a valid email address!'); * }); * * // Simple validation * Ahoy.validation('#form').code('user:login_form').success(function() { alert('Pass!'); }).bind(); * * // Validation + AJAX action * Ahoy.form.define_action('#form_reset_pass', 'user:on_password_reset', 'user:forgot_password_popup').success(function(){ alert('Done!'); }); * */ var Ahoy = (function(ahoy, $){ ahoy.form = { // Binds validation to a form with an ajax action. Returns a post object define_action: function(form_element, ajax_action, validate_code) { var post_object = ahoy.post(form_element).action(ajax_action); ahoy.validation(form_element, validate_code) .success(function(){ post_object.send(); }) .bind(); return post_object; }, define_fields: function(code, object) { object.prototype.define_field = function(name) { return ahoy.form.define_field(code, name); } new object(); }, // Creates a new rule instance define_field: function(code, field_name) { code = code.replace(/:/g, '_'); return new ahoy.form_field_definition(field_name, code); } }; // Validate object: binds an element (field) to a code // within the Ahoy namespace (ahoy.code) for use/reuse ahoy.form_field_definition = function(field, code) { this._rules = {}; this._messages = {}; this._field = field; this._object = code; if (ahoy[code] === undefined) { ahoy[code] = { validate_rules: {}, validate_messages: {} }; } // Manually sets a rule this.set_rule = function(field, value) { this._rules[field] = value; return this; }; // Manually sets a message this.set_message = function(field, value) { this._messages[field] = value; return this; }; // Chained rules this.required = function(message) { this._rules.required = true; this._messages.required = message; return this.set(); }; // Requires at least X (min_filled) inputs (element class) populated this.required_multi = function(min_filled, element_class, message) { this._rules.required_multi = [min_filled, element_class]; this._messages.required_multi = message; return this.set(); }; this.number = function(message) { this._rules.number = true; this._messages.number = message; return this.set(); }; this.phone = function(message) { this._rules.phone = true; this._messages.phone = message; return this.set(); }; this.email = function(message) { this._rules.email = true; this._messages.email = message; return this.set(); }; this.date = function(message) { this._rules.ahoyDate = true; this._messages.ahoyDate = message; return this.set(); }; this.url = function(message) { this._rules.fullUrl = true; this._messages.fullUrl = message; return this.set(); }; this.range = function(range, message) { this._rules.range = range; this._messages.range = message; return this.set(); }; this.min = function(min, message) { this._rules.min = min; this._messages.min = message; return this.set(); }; this.max = function(max, message) { this._rules.max = max; this._messages.max = message; return this.set(); }; this.min_words = function(words, message) { this._rules.minWord = words; this._messages.minWord = message; return this.set(); }; this.matches = function(field, message) { this._rules.equalTo = field; this._messages.equalTo = message; return this.set(); }; // Submits a remote action using ahoy.post this.action = function(action, message) { this._rules.ahoyRemote = { action:action }; this._messages.ahoyRemote = message; return this.set(); }; // Used at the end of chaining to lock in settings this.set = function() { ahoy[this._object].validate_rules[this._field] = this._rules; ahoy[this._object].validate_messages[this._field] = this._messages; return this; }; }; return ahoy; }(Ahoy || {}, jQuery))
JavaScript
/** * Form definition and validation * * ahoy.validation('#form').code('user:login_form').success(function() { alert('Pass!'); }).bind(); * * // Append rules to an exisiting form * ahoy.validation('#form').add_rules('user:register_form'); * */ var Ahoy = (function(ahoy, $){ ahoy.validation = function(form_element, code, options) { return new ahoy.validation_object(form_element, code, options); }; ahoy.validation_object = function(form_element, code, options) { var self = this; // Default options used for jQ validate this.default_options = { ignore:":not(:visible):not(:disabled)", errorElement: 'small', onkeyup: false, submitHandler: function(form) { form.submit(); } }; // Internals this._options = $.extend(true, this.default_options, options); this._form = null; this._on_success = null; this._code = null; // Binds a set of rules (code) to a form (form) this.bind = function() { if (this._code && ahoy[this._code]) { this._options.messages = ahoy[this._code].validate_messages; this._options.rules = ahoy[this._code].validate_rules; } this._form.validate(this._options); }; this.success = function(func) { this._options.submitHandler = func; this._on_success = func; return this; }; this.code = function(code) { code = code.replace(/:/g, '_'); this._code = code; return this; }; this.add_rules = function(code) { return this.set_rules(code); }; this.remove_rules = function(code) { return this.set_rules(code, true); }; // Adds or removes rules to an exisiting validation form this.set_rules = function(code, is_remove) { code = code.replace(/:/g, '_'); if (ahoy[code] === undefined) return; rules = ahoy[code].validate_rules; messages = ahoy[code].validate_messages; if (rules === undefined) return; $.each(rules, function(name, field){ var set_rules = (messages[name] !== undefined) ? $.extend(true, field, { messages: messages[name] }) : field; var field = self._form.find('[name="'+name+'"]'); if (field.length > 0) { if (is_remove) field.rules('remove'); else field.rules('add', set_rules); } }); return this; }; // Init this._form = $(form_element); if (code) this.code(code); }; return ahoy; }(Ahoy || {}, jQuery))
JavaScript
/* =require foundation/modernizr.foundation =require foundation/jquery.placeholder =require foundation/jquery.foundation.alerts =require foundation/jquery.foundation.accordion =require foundation/jquery.foundation.buttons =require foundation/jquery.foundation.tooltips =require foundation/jquery.foundation.forms =require foundation/jquery.foundation.tabs =require foundation/jquery.foundation.navigation =require foundation/jquery.foundation.topbar =require foundation/jquery.foundation.reveal =require foundation/jquery.foundation.orbit =require foundation/jquery.foundation.magellan =require foundation/jquery.foundation.joyride =require foundation/jquery.foundation.clearing =require foundation/jquery.foundation.mediaQueryToggle =require foundation/app */
JavaScript
;(function ($, window, undefined){ 'use strict'; $.fn.foundationAccordion = function (options) { var $accordion = $('.accordion'); if ($accordion.hasClass('hover') && !Modernizr.touch) { $('.accordion li', this).on({ mouseenter : function () { console.log('due'); var p = $(this).parent(), flyout = $(this).children('.content').first(); $('.content', p).not(flyout).hide().parent('li').removeClass('active'); //changed this flyout.show(0, function () { flyout.parent('li').addClass('active'); }); } }); } else { $('.accordion li', this).on('click.fndtn', function () { var li = $(this), p = $(this).parent(), flyout = $(this).children('.content').first(); if (li.hasClass('active')) { p.find('li').removeClass('active').end().find('.content').hide(); } else { $('.content', p).not(flyout).hide().parent('li').removeClass('active'); //changed this flyout.show(0, function () { flyout.parent('li').addClass('active'); }); } }); } }; })( jQuery, this );
JavaScript
/* * jQuery Foundation Tooltips 2.0.2 * http://foundation.zurb.com * Copyright 2012, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ /*jslint unparam: true, browser: true, indent: 2 */ ;(function ($, window, undefined) { 'use strict'; var settings = { bodyHeight : 0, selector : '.has-tip', additionalInheritableClasses : [], tooltipClass : '.tooltip', tipTemplate : function (selector, content) { return '<span data-selector="' + selector + '" class="' + settings.tooltipClass.substring(1) + '">' + content + '<span class="nub"></span></span>'; } }, methods = { init : function (options) { settings = $.extend(settings, options); // alias the old targetClass option settings.selector = settings.targetClass ? settings.targetClass : settings.selector; return this.each(function () { var $body = $('body'); if (Modernizr.touch) { $body.on('click.tooltip touchstart.tooltip touchend.tooltip', settings.selector, function (e) { e.preventDefault(); $(settings.tooltipClass).hide(); methods.showOrCreateTip($(this)); }); $body.on('click.tooltip touchstart.tooltip touchend.tooltip', settings.tooltipClass, function (e) { e.preventDefault(); $(this).fadeOut(150); }); } else { $body.on('mouseenter.tooltip mouseleave.tooltip', settings.selector, function (e) { var $this = $(this); if (e.type === 'mouseenter') { methods.showOrCreateTip($this); } else if (e.type === 'mouseleave') { methods.hide($this); } }); } $(this).data('tooltips', true); }); }, showOrCreateTip : function ($target) { var $tip = methods.getTip($target); if ($tip && $tip.length > 0) { methods.show($target); } else { methods.create($target); } }, getTip : function ($target) { var selector = methods.selector($target), tip = null; if (selector) { tip = $('span[data-selector=' + selector + ']' + settings.tooltipClass); } return (tip.length > 0) ? tip : false; }, selector : function ($target) { var id = $target.attr('id'), dataSelector = $target.data('selector'); if (id === undefined && dataSelector === undefined) { dataSelector = 'tooltip' + Math.random().toString(36).substring(7); $target.attr('data-selector', dataSelector); } return (id) ? id : dataSelector; }, create : function ($target) { var $tip = $(settings.tipTemplate(methods.selector($target), $('<div>').html($target.attr('title')).html())), classes = methods.inheritable_classes($target); $tip.addClass(classes).appendTo('body'); if (Modernizr.touch) { $tip.append('<span class="tap-to-close">tap to close </span>'); } $target.removeAttr('title'); methods.show($target); }, reposition : function (target, tip, classes) { var width, nub, nubHeight, nubWidth, column, objPos; tip.css('visibility', 'hidden').show(); width = target.data('width'); nub = tip.children('.nub'); nubHeight = nub.outerHeight(); nubWidth = nub.outerWidth(); objPos = function (obj, top, right, bottom, left, width) { return obj.css({ 'top' : top, 'bottom' : bottom, 'left' : left, 'right' : right, 'width' : (width) ? width : 'auto' }).end(); }; objPos(tip, (target.offset().top + target.outerHeight() + 10), 'auto', 'auto', target.offset().left, width); objPos(nub, -nubHeight, 'auto', 'auto', 10); if ($(window).width() < 767) { column = target.closest('.columns'); if (column.length < 0) { // if not using Foundation column = $('body'); } tip.width(column.outerWidth() - 25).css('left', 15).addClass('tip-override'); objPos(nub, -nubHeight, 'auto', 'auto', target.offset().left); } else { if (classes && classes.indexOf('tip-top') > -1) { objPos(tip, (target.offset().top - tip.outerHeight() - nubHeight), 'auto', 'auto', target.offset().left, width) .removeClass('tip-override'); objPos(nub, 'auto', 'auto', -nubHeight, 'auto'); } else if (classes && classes.indexOf('tip-left') > -1) { objPos(tip, (target.offset().top + (target.outerHeight() / 2) - nubHeight), 'auto', 'auto', (target.offset().left - tip.outerWidth() - 10), width) .removeClass('tip-override'); objPos(nub, (tip.outerHeight() / 2) - (nubHeight / 2), -nubHeight, 'auto', 'auto'); } else if (classes && classes.indexOf('tip-right') > -1) { objPos(tip, (target.offset().top + (target.outerHeight() / 2) - nubHeight), 'auto', 'auto', (target.offset().left + target.outerWidth() + 10), width) .removeClass('tip-override'); objPos(nub, (tip.outerHeight() / 2) - (nubHeight / 2), 'auto', 'auto', -nubHeight); } } tip.css('visibility', 'visible').hide(); }, inheritable_classes : function (target) { var inheritables = ['tip-top', 'tip-left', 'tip-bottom', 'tip-right', 'noradius'].concat(settings.additionalInheritableClasses), classes = target.attr('class'), filtered = classes ? $.map(classes.split(' '), function (el, i) { if ($.inArray(el, inheritables) !== -1) { return el; } }).join(' ') : ''; return $.trim(filtered); }, show : function ($target) { var $tip = methods.getTip($target); methods.reposition($target, $tip, $target.attr('class')); $tip.fadeIn(150); }, hide : function ($target) { var $tip = methods.getTip($target); $tip.fadeOut(150); }, reload : function () { var $self = $(this); return ($self.data('tooltips')) ? $self.foundationTooltips('destroy').foundationTooltips('init') : $self.foundationTooltips('init'); }, destroy : function () { return this.each(function () { $(window).off('.tooltip'); $(settings.selector).off('.tooltip'); $(settings.tooltipClass).each(function (i) { $($(settings.selector).get(i)).attr('title', $(this).text()); }).remove(); }); } }; $.fn.foundationTooltips = function (method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.foundationTooltips'); } }; }(jQuery, this));
JavaScript
/* * jQuery Foundation Clearing 1.1 * http://foundation.zurb.com * Copyright 2012, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ /*jslint unparam: true, browser: true, indent: 2 */ ;(function ($, window, undefined) { 'use strict'; var defaults = { templates : { viewing : '<a href="#" class="clearing-close">&times;</a>' + '<div class="visible-img" style="display: none"><img src="#">' + '<p class="clearing-caption"></p><a href="#" class="clearing-main-left"></a>' + '<a href="#" class="clearing-main-right"></a></div>' }, // comma delimited list of selectors that, on click, will close clearing, // add 'div.clearing-blackout, div.visible-img' to close on background click close_selectors : 'a.clearing-close', // event initializers and locks initialized : false, swipe_events : false, locked : false }, // original clearing methods will be stored here if // initialized with custom methods superMethods = {}, cl = { init : function (options, extendMethods) { return this.find('ul[data-clearing]').each(function () { var doc = $(document), $el = $(this), options = options || {}, extendMethods = extendMethods || {}, settings = $el.data('fndtn.clearing.settings'); if (!settings) { options.$parent = $el.parent(); $el.data('fndtn.clearing.settings', $.extend({}, defaults, options)); // developer goodness experiment cl.extend(cl, extendMethods); // if the gallery hasn't been built yet...build it cl.assemble($el.find('li')); if (!defaults.initialized) { cl.events($el); cl.swipe_events(); } } }); }, events : function (el) { var settings = el.data('fndtn.clearing.settings'); $(document) .on('click.fndtn.clearing', 'ul[data-clearing] li', function (e, current, target) { var current = current || $(this), target = target || current, settings = current.parent().data('fndtn.clearing.settings'); e.preventDefault(); if (!settings) { current.parent().foundationClearing(); } // set current and target to the clicked li if not otherwise defined. cl.open($(e.target), current, target); cl.update_paddles(target); }) .on('click.fndtn.clearing', '.clearing-main-right', function (e) { var clearing = $('.clearing-blackout').find('ul[data-clearing]'); e.preventDefault(); cl.go(clearing, 'next'); }) .on('click.fndtn.clearing', '.clearing-main-left', function (e) { var clearing = $('.clearing-blackout').find('ul[data-clearing]'); e.preventDefault(); cl.go(clearing, 'prev'); }) .on('click.fndtn.clearing', settings.close_selectors, function (e) { e.preventDefault(); var root = (function (target) { if (/blackout/.test(target.selector)) { return target; } else { return target.closest('.clearing-blackout'); } }($(this))), container, visible_image; if (this === e.target && root) { container = root.find('div:first'), visible_image = container.find('.visible-img'); defaults.prev_index = 0; root.find('ul[data-clearing]').attr('style', '') root.removeClass('clearing-blackout'); container.removeClass('clearing-container'); visible_image.hide(); } return false; }) .on('keydown.fndtn.clearing', function (e) { var clearing = $('.clearing-blackout').find('ul[data-clearing]'); // right if (e.which === 39) { cl.go(clearing, 'next'); } // left if (e.which === 37) { cl.go(clearing, 'prev'); } if (e.which === 27) { $('a.clearing-close').trigger('click'); } }); $(window).on('resize.fndtn.clearing', function () { var image = $('.clearing-blackout .visible-img').find('img'); if (image.length > 0) { cl.center(image); } }); defaults.initialized = true; }, swipe_events : function () { $(document) .bind('swipeleft', 'ul[data-clearing]', function (e) { var clearing = $('.clearing-blackout').find('ul[data-clearing]'); cl.go(clearing, 'next'); }) .bind('swiperight', 'ul[data-clearing]', function (e) { var clearing = $('.clearing-blackout').find('ul[data-clearing]'); cl.go(clearing, 'prev'); }) .bind('movestart', 'ul[data-clearing]', function (e) { if ((e.distX > e.distY && e.distX < -e.distY) || (e.distX < e.distY && e.distX > -e.distY)) { e.preventDefault(); } }); }, assemble : function ($li) { var $el = $li.parent(), settings = $el.data('fndtn.clearing.settings'), grid = $el.detach(), data = { grid: '<div class="carousel">' + this.outerHTML(grid[0]) + '</div>', viewing: settings.templates.viewing }, wrapper = '<div class="clearing-assembled"><div>' + data.viewing + data.grid + '</div></div>'; return settings.$parent.append(wrapper); }, open : function ($image, current, target) { var root = target.closest('.clearing-assembled'), container = root.find('div:first'), visible_image = container.find('.visible-img'), image = visible_image.find('img').not($image); if (!cl.locked()) { // set the image to the selected thumbnail image.attr('src', this.load($image)); image.is_good(function () { // toggle the gallery if not visible root.addClass('clearing-blackout'); container.addClass('clearing-container'); this.caption(visible_image.find('.clearing-caption'), $image); visible_image.show(); this.fix_height(target); this.center(image); // shift the thumbnails if necessary this.shift(current, target, function () { target.siblings().removeClass('visible'); target.addClass('visible'); }); }.bind(this)); } }, fix_height : function (target) { var lis = target.siblings(); target.siblings() .each(function () { var li = $(this), image = li.find('img'); if (li.height() > image.outerHeight()) { li.addClass('fix-height'); } }) .closest('ul').width(lis.length * 100 + '%'); }, update_paddles : function (target) { var visible_image = target.closest('.carousel').siblings('.visible-img'); if (target.next().length > 0) { visible_image.find('.clearing-main-right').removeClass('disabled'); } else { visible_image.find('.clearing-main-right').addClass('disabled'); } if (target.prev().length > 0) { visible_image.find('.clearing-main-left').removeClass('disabled'); } else { visible_image.find('.clearing-main-left').addClass('disabled'); } }, load : function ($image) { var href = $image.parent().attr('href'); this.preload($image); if (href) { return href; } return $image.attr('src'); }, preload : function ($image) { var next = $image.closest('li').next(), prev = $image.closest('li').prev(), next_a, prev_a, next_img, prev_img; if (next.length > 0) { next_img = new Image(); next_a = next.find('a'); if (next_a.length > 0) { next_img.src = next_a.attr('href'); } else { next_img.src = next.find('img').attr('src'); } } if (prev.length > 0) { prev_img = new Image(); prev_a = prev.find('a'); if (prev_a.length > 0) { prev_img.src = prev_a.attr('href'); } else { prev_img.src = prev.find('img').attr('src'); } } }, caption : function (container, $image) { var caption = $image.data('caption'); if (caption) { container.text(caption).show(); } else { container.text('').hide(); } }, go : function ($ul, direction) { var current = $ul.find('.visible'), target = current[direction](); if (target.length > 0) { target.find('img').trigger('click', [current, target]); } }, shift : function (current, target, callback) { var clearing = target.parent(), old_index = defaults.prev_index, direction = this.direction(clearing, current, target), left = parseInt(clearing.css('left'), 10), width = target.outerWidth(), skip_shift; // we use jQuery animate instead of CSS transitions because we // need a callback to unlock the next animation if (target.index() !== old_index && !/skip/.test(direction)){ if (/left/.test(direction)) { this.lock(); clearing.animate({left : left + width}, 300, this.unlock); } else if (/right/.test(direction)) { this.lock(); clearing.animate({left : left - width}, 300, this.unlock); } } else if (/skip/.test(direction)) { // the target image is not adjacent to the current image, so // do we scroll right or not skip_shift = target.index() - defaults.up_count; this.lock(); if (skip_shift > 0) { clearing.animate({left : -(skip_shift * width)}, 300, this.unlock); } else { clearing.animate({left : 0}, 300, this.unlock); } } callback(); }, lock : function () { defaults.locked = true; }, unlock : function () { defaults.locked = false; }, locked : function () { return defaults.locked; }, direction : function ($el, current, target) { var lis = $el.find('li'), li_width = lis.outerWidth() + (lis.outerWidth() / 4), up_count = Math.floor($('.clearing-container').outerWidth() / li_width) - 1, target_index = lis.index(target), response; defaults.up_count = up_count; if (this.adjacent(defaults.prev_index, target_index)) { if ((target_index > up_count) && target_index > defaults.prev_index) { response = 'right'; } else if ((target_index > up_count - 1) && target_index <= defaults.prev_index) { response = 'left'; } else { response = false; } } else { response = 'skip'; } defaults.prev_index = target_index; return response; }, adjacent : function (current_index, target_index) { if (target_index - 1 === current_index) { return true; } else if (target_index + 1 === current_index) { return true; } else if (target_index === current_index) { return true; } return false; }, center : function (target) { target.css({ marginLeft : -(target.outerWidth() / 2), marginTop : -(target.outerHeight() / 2) }); }, outerHTML : function (el) { // support FireFox < 11 return el.outerHTML || new XMLSerializer().serializeToString(el); }, // experimental functionality for overwriting or extending // clearing methods during initialization. // // ex $doc.foundationClearing({}, { // shift : function (current, target, callback) { // // modify arguments, etc. // this._super('shift', [current, target, callback]); // // do something else here. // } // }); extend : function (supers, extendMethods) { $.each(supers, function (name, method) { if (extendMethods.hasOwnProperty(name)) { superMethods[name] = method; } }); $.extend(cl, extendMethods); }, // you can call this._super('methodName', [args]) to call // the original method and wrap it in your own code _super : function (method, args) { return superMethods[method].apply(this, args); } }; $.fn.foundationClearing = function (method) { if (cl[method]) { return cl[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return cl.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.foundationClearing'); } }; // jquery.imageready.js // @weblinc, @jsantell, (c) 2012 (function( $ ) { $.fn.is_good = function ( callback, userSettings ) { var options = $.extend( {}, $.fn.is_good.defaults, userSettings ), $images = this.find( 'img' ).add( this.filter( 'img' ) ), unloadedImages = $images.length; function loaded () { unloadedImages -= 1; !unloadedImages && callback(); } function bindLoad () { this.one( 'load', loaded ); if ( $.browser.msie ) { var src = this.attr( 'src' ), param = src.match( /\?/ ) ? '&' : '?'; param += options.cachePrefix + '=' + ( new Date() ).getTime(); this.attr( 'src', src + param ); } } return $images.each(function () { var $this = $( this ); if ( !$this.attr( 'src' ) ) { loaded(); return; } this.complete || this.readyState === 4 ? loaded() : bindLoad.call( $this ); }); }; $.fn.is_good.defaults = { cachePrefix: 'random' }; }(jQuery)); }(jQuery, this));
JavaScript
/* * jQuery Foundation Magellan 0.0.1 * http://foundation.zurb.com * Copyright 2012, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ /*jslint unparam: true, browser: true, indent: 2 */ ;(function ($, window, undefined) { 'use strict'; $.fn.foundationMagellan = function(options) { var $fixedMagellan = $('[data-magellan-expedition=fixed]'), defaults = { threshold: ($fixedMagellan.length) ? $fixedMagellan.outerHeight(true) : 25, activeClass: 'active' }, options = $.extend({}, defaults, options); // Indicate we have arrived at a destination $(document).on('magellan.arrival', '[data-magellan-arrival]', function(e) { var $expedition = $(this).closest('[data-magellan-expedition]'), activeClass = $expedition.attr('data-magellan-active-class') || options.activeClass; $(this) .closest('[data-magellan-expedition]') .find('[data-magellan-arrival]') .not(this) .removeClass(activeClass); $(this).addClass(activeClass); }); // Set starting point as the current destination var $expedition = $('[data-magellan-expedition]'); $expedition.find('[data-magellan-arrival]:first') .addClass($expedition.attr('data-magellan-active-class') || options.activeClass); // Update fixed position $fixedMagellan.on('magellan.update-position', function(){ var $el = $(this); $el.data("magellan-fixed-position",""); $el.data("magellan-top-offset", ""); }); $fixedMagellan.trigger('magellan.update-position'); $(window).on('resize.magellan', function() { $fixedMagellan.trigger('magellan.update-position'); }); $(window).on('scroll.magellan', function() { var windowScrollTop = $(window).scrollTop(); $fixedMagellan.each(function() { var $expedition = $(this); if ($expedition.data("magellan-top-offset") === "") { $expedition.data("magellan-top-offset", $expedition.offset().top); } var fixed_position = (windowScrollTop + options.threshold) > $expedition.data("magellan-top-offset"); if ($expedition.data("magellan-fixed-position") != fixed_position) { $expedition.data("magellan-fixed-position", fixed_position); if (fixed_position) { $expedition.css({position:"fixed", top:0}); } else { $expedition.css({position:"", top:""}); } } }); }); // Determine when a destination has been reached, ah0y! $(window).on('scroll.magellan', function(e){ var windowScrollTop = $(window).scrollTop(); $('[data-magellan-destination]').each(function(){ var $destination = $(this), destination_name = $destination.attr('data-magellan-destination'), topOffset = $destination.offset().top - windowScrollTop; if (topOffset <= options.threshold) { $('[data-magellan-arrival=' + destination_name + ']') .trigger('magellan.arrival'); } }); }); }; }(jQuery, this));
JavaScript
;(function ($, window, undefined) { 'use strict'; $.fn.foundationAlerts = function (options) { var settings = $.extend({ callback: $.noop }, options); $(document).on("click", ".alert-box a.close", function (e) { e.preventDefault(); $(this).closest(".alert-box").fadeOut(function () { $(this).remove(); // Do something else after the alert closes settings.callback(); }); }); }; })(jQuery, this);
JavaScript
;(function ($, window, undefined) { 'use strict'; var $doc = $(document), Modernizr = window.Modernizr; $(document).ready(function() { $.fn.foundationAlerts ? $doc.foundationAlerts() : null; $.fn.foundationButtons ? $doc.foundationButtons() : null; $.fn.foundationAccordion ? $doc.foundationAccordion() : null; $.fn.foundationNavigation ? $doc.foundationNavigation() : null; $.fn.foundationTopBar ? $doc.foundationTopBar() : null; $.fn.foundationCustomForms ? $doc.foundationCustomForms() : null; $.fn.foundationMediaQueryViewer ? $doc.foundationMediaQueryViewer() : null; $.fn.foundationTabs ? $doc.foundationTabs({callback : $.foundation.customForms.appendCustomMarkup}) : null; $.fn.foundationTooltips ? $doc.foundationTooltips() : null; $.fn.foundationMagellan ? $doc.foundationMagellan() : null; $.fn.foundationClearing ? $doc.foundationClearing() : null; $.fn.placeholder ? $('input, textarea').placeholder() : null; }); // UNCOMMENT THE LINE YOU WANT BELOW IF YOU WANT IE8 SUPPORT AND ARE USING .block-grids $('.block-grid.two-up>li:nth-child(2n+1)').css({clear: 'both'}); $('.block-grid.three-up>li:nth-child(3n+1)').css({clear: 'both'}); $('.block-grid.four-up>li:nth-child(4n+1)').css({clear: 'both'}); $('.block-grid.five-up>li:nth-child(5n+1)').css({clear: 'both'}); // Hide address bar on mobile devices (except if #hash present, so we don't mess up deep linking). if (Modernizr.touch && !window.location.hash) { $(window).load(function () { setTimeout(function () { window.scrollTo(0, 1); }, 0); }); } })(jQuery, this);
JavaScript
/* * jQuery Reveal Plugin 1.1 * www.ZURB.com * Copyright 2010, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ /*globals jQuery */ (function ($) { 'use strict'; // // Global variable. // Helps us determine if the current modal is being queued for display. // var modalQueued = false; // // Bind the live 'click' event to all anchor elemnets with the data-reveal-id attribute. // $(document).on('click', 'a[data-reveal-id]', function ( event ) { // // Prevent default action of the event. // event.preventDefault(); // // Get the clicked anchor data-reveal-id attribute value. // var modalLocation = $( this ).attr( 'data-reveal-id' ); // // Find the element with that modalLocation id and call the reveal plugin. // $( '#' + modalLocation ).reveal( $( this ).data() ); }); /** * @module reveal * @property {Object} [options] Reveal options */ $.fn.reveal = function ( options ) { /* * Cache the document object. */ var $doc = $( document ), /* * Default property values. */ defaults = { /** * Possible options: fade, fadeAndPop, none * * @property animation * @type {String} * @default fadeAndPop */ animation: 'fadeAndPop', /** * Speed at which the reveal should show. How fast animtions are. * * @property animationSpeed * @type {Integer} * @default 300 */ animationSpeed: 300, /** * Should the modal close when the background is clicked? * * @property closeOnBackgroundClick * @type {Boolean} * @default true */ closeOnBackgroundClick: true, /** * Specify a class name for the 'close modal' element. * This element will close an open modal. * @example <a href='#close' class='close-reveal-modal'>Close Me</a> * * @property dismissModalClass * @type {String} * @default close-reveal-modal */ dismissModalClass: 'close-reveal-modal', /** * Specify a callback function that triggers 'before' the modal opens. * * @property open * @type {Function} * @default function(){} */ open: $.noop, /** * Specify a callback function that triggers 'after' the modal is opened. * * @property opened * @type {Function} * @default function(){} */ opened: $.noop, /** * Specify a callback function that triggers 'before' the modal prepares to close. * * @property close * @type {Function} * @default function(){} */ close: $.noop, /** * Specify a callback function that triggers 'after' the modal is closed. * * @property closed * @type {Function} * @default function(){} */ closed: $.noop } ; // // Extend the default options. // This replaces the passed in option (options) values with default values. // options = $.extend( {}, defaults, options ); // // Apply the plugin functionality to each element in the jQuery collection. // return this.not('.reveal-modal.open').each( function () { // // Cache the modal element // var modal = $( this ), // // Get the current css 'top' property value in decimal format. // topMeasure = parseInt( modal.css( 'top' ), 10 ), // // Calculate the top offset. // topOffset = modal.height() + topMeasure, // // Helps determine if the modal is locked. // This way we keep the modal from triggering while it's in the middle of animating. // locked = false, // // Get the modal background element. // modalBg = $( '.reveal-modal-bg' ), // // Show modal properties // cssOpts = { // // Used, when we show the modal. // open : { // // Set the 'top' property to the document scroll minus the calculated top offset. // 'top': 0, // // Opacity gets set to 0. // 'opacity': 0, // // Show the modal // 'visibility': 'visible', // // Ensure it's displayed as a block element. // 'display': 'block' }, // // Used, when we hide the modal. // close : { // // Set the default 'top' property value. // 'top': topMeasure, // // Has full opacity. // 'opacity': 1, // // Hide the modal // 'visibility': 'hidden', // // Ensure the elment is hidden. // 'display': 'none' } }, // // Initial closeButton variable. // $closeButton ; // // Do we have a modal background element? // if ( modalBg.length === 0 ) { // // No we don't. So, let's create one. // modalBg = $( '<div />', { 'class' : 'reveal-modal-bg' } ) // // Then insert it after the modal element. // .insertAfter( modal ); // // Now, fade it out a bit. // modalBg.fadeTo( 'fast', 0.8 ); } // // Helper Methods // /** * Unlock the modal for animation. * * @method unlockModal */ function unlockModal() { locked = false; } /** * Lock the modal to prevent further animation. * * @method lockModal */ function lockModal() { locked = true; } /** * Closes all open modals. * * @method closeOpenModal */ function closeOpenModals() { // // Get all reveal-modal elements with the .open class. // var $openModals = $( ".reveal-modal.open" ); // // Do we have modals to close? // if ( $openModals.length === 1 ) { // // Set the modals for animation queuing. // modalQueued = true; // // Trigger the modal close event. // $openModals.trigger( "reveal:close" ); } } /** * Animates the modal opening. * Handles the modal 'open' event. * * @method openAnimation */ function openAnimation() { // // First, determine if we're in the middle of animation. // if ( !locked ) { // // We're not animating, let's lock the modal for animation. // lockModal(); // // Close any opened modals. // closeOpenModals(); // // Now, add the open class to this modal. // modal.addClass( "open" ); // // Are we executing the 'fadeAndPop' animation? // if ( options.animation === "fadeAndPop" ) { // // Yes, we're doing the 'fadeAndPop' animation. // Okay, set the modal css properties. // // // Set the 'top' property to the document scroll minus the calculated top offset. // cssOpts.open.top = $doc.scrollTop() - topOffset; // // Flip the opacity to 0. // cssOpts.open.opacity = 0; // // Set the css options. // modal.css( cssOpts.open ); // // Fade in the background element, at half the speed of the modal element. // So, faster than the modal element. // modalBg.fadeIn( options.animationSpeed / 2 ); // // Let's delay the next animation queue. // We'll wait until the background element is faded in. // modal.delay( options.animationSpeed / 2 ) // // Animate the following css properties. // .animate( { // // Set the 'top' property to the document scroll plus the calculated top measure. // "top": $doc.scrollTop() + topMeasure + 'px', // // Set it to full opacity. // "opacity": 1 }, /* * Fade speed. */ options.animationSpeed, /* * End of animation callback. */ function () { // // Trigger the modal reveal:opened event. // This should trigger the functions set in the options.opened property. // modal.trigger( 'reveal:opened' ); }); // end of animate. } // end if 'fadeAndPop' // // Are executing the 'fade' animation? // if ( options.animation === "fade" ) { // // Yes, were executing 'fade'. // Okay, let's set the modal properties. // cssOpts.open.top = $doc.scrollTop() + topMeasure; // // Flip the opacity to 0. // cssOpts.open.opacity = 0; // // Set the css options. // modal.css( cssOpts.open ); // // Fade in the modal background at half the speed of the modal. // So, faster than modal. // modalBg.fadeIn( options.animationSpeed / 2 ); // // Delay the modal animation. // Wait till the modal background is done animating. // modal.delay( options.animationSpeed / 2 ) // // Now animate the modal. // .animate( { // // Set to full opacity. // "opacity": 1 }, /* * Animation speed. */ options.animationSpeed, /* * End of animation callback. */ function () { // // Trigger the modal reveal:opened event. // This should trigger the functions set in the options.opened property. // modal.trigger( 'reveal:opened' ); }); } // end if 'fade' // // Are we not animating? // if ( options.animation === "none" ) { // // We're not animating. // Okay, let's set the modal css properties. // // // Set the top property. // cssOpts.open.top = $doc.scrollTop() + topMeasure; // // Set the opacity property to full opacity, since we're not fading (animating). // cssOpts.open.opacity = 1; // // Set the css property. // modal.css( cssOpts.open ); // // Show the modal Background. // modalBg.css( { "display": "block" } ); // // Trigger the modal opened event. // modal.trigger( 'reveal:opened' ); } // end if animating 'none' }// end if !locked }// end openAnimation function openVideos() { var video = modal.find('.flex-video'), iframe = video.find('iframe'); if (iframe.length > 0) { iframe.attr("src", iframe.data("src")); video.fadeIn(100); } } // // Bind the reveal 'open' event. // When the event is triggered, openAnimation is called // along with any function set in the options.open property. // modal.bind( 'reveal:open.reveal', openAnimation ); modal.bind( 'reveal:open.reveal', openVideos); /** * Closes the modal element(s) * Handles the modal 'close' event. * * @method closeAnimation */ function closeAnimation() { // // First, determine if we're in the middle of animation. // if ( !locked ) { // // We're not animating, let's lock the modal for animation. // lockModal(); // // Clear the modal of the open class. // modal.removeClass( "open" ); // // Are we using the 'fadeAndPop' animation? // if ( options.animation === "fadeAndPop" ) { // // Yes, okay, let's set the animation properties. // modal.animate( { // // Set the top property to the document scrollTop minus calculated topOffset. // "top": $doc.scrollTop() - topOffset + 'px', // // Fade the modal out, by using the opacity property. // "opacity": 0 }, /* * Fade speed. */ options.animationSpeed / 2, /* * End of animation callback. */ function () { // // Set the css hidden options. // modal.css( cssOpts.close ); }); // // Is the modal animation queued? // if ( !modalQueued ) { // // Oh, the modal(s) are mid animating. // Let's delay the animation queue. // modalBg.delay( options.animationSpeed ) // // Fade out the modal background. // .fadeOut( /* * Animation speed. */ options.animationSpeed, /* * End of animation callback. */ function () { // // Trigger the modal 'closed' event. // This should trigger any method set in the options.closed property. // modal.trigger( 'reveal:closed' ); }); } else { // // We're not mid queue. // Trigger the modal 'closed' event. // This should trigger any method set in the options.closed propety. // modal.trigger( 'reveal:closed' ); } // end if !modalQueued } // end if animation 'fadeAndPop' // // Are we using the 'fade' animation. // if ( options.animation === "fade" ) { // // Yes, we're using the 'fade' animation. // modal.animate( { "opacity" : 0 }, /* * Animation speed. */ options.animationSpeed, /* * End of animation callback. */ function () { // // Set the css close options. // modal.css( cssOpts.close ); }); // end animate // // Are we mid animating the modal(s)? // if ( !modalQueued ) { // // Oh, the modal(s) are mid animating. // Let's delay the animation queue. // modalBg.delay( options.animationSpeed ) // // Let's fade out the modal background element. // .fadeOut( /* * Animation speed. */ options.animationSpeed, /* * End of animation callback. */ function () { // // Trigger the modal 'closed' event. // This should trigger any method set in the options.closed propety. // modal.trigger( 'reveal:closed' ); }); // end fadeOut } else { // // We're not mid queue. // Trigger the modal 'closed' event. // This should trigger any method set in the options.closed propety. // modal.trigger( 'reveal:closed' ); } // end if !modalQueued } // end if animation 'fade' // // Are we not animating? // if ( options.animation === "none" ) { // // We're not animating. // Set the modal close css options. // modal.css( cssOpts.close ); // // Is the modal in the middle of an animation queue? // if ( !modalQueued ) { // // It's not mid queueu. Just hide it. // modalBg.css( { 'display': 'none' } ); } // // Trigger the modal 'closed' event. // This should trigger any method set in the options.closed propety. // modal.trigger( 'reveal:closed' ); } // end if not animating // // Reset the modalQueued variable. // modalQueued = false; } // end if !locked } // end closeAnimation /** * Destroys the modal and it's events. * * @method destroy */ function destroy() { // // Unbind all .reveal events from the modal. // modal.unbind( '.reveal' ); // // Unbind all .reveal events from the modal background. // modalBg.unbind( '.reveal' ); // // Unbind all .reveal events from the modal 'close' button. // $closeButton.unbind( '.reveal' ); // // Unbind all .reveal events from the body. // $( 'body' ).unbind( '.reveal' ); } function closeVideos() { var video = modal.find('.flex-video'), iframe = video.find('iframe'); if (iframe.length > 0) { iframe.data("src", iframe.attr("src")); iframe.attr("src", ""); video.fadeOut(100); } } // // Bind the modal 'close' event // modal.bind( 'reveal:close.reveal', closeAnimation ); modal.bind( 'reveal:closed.reveal', closeVideos ); // // Bind the modal 'opened' + 'closed' event // Calls the unlockModal method. // modal.bind( 'reveal:opened.reveal reveal:closed.reveal', unlockModal ); // // Bind the modal 'closed' event. // Calls the destroy method. // modal.bind( 'reveal:closed.reveal', destroy ); // // Bind the modal 'open' event // Handled by the options.open property function. // modal.bind( 'reveal:open.reveal', options.open ); // // Bind the modal 'opened' event. // Handled by the options.opened property function. // modal.bind( 'reveal:opened.reveal', options.opened ); // // Bind the modal 'close' event. // Handled by the options.close property function. // modal.bind( 'reveal:close.reveal', options.close ); // // Bind the modal 'closed' event. // Handled by the options.closed property function. // modal.bind( 'reveal:closed.reveal', options.closed ); // // We're running this for the first time. // Trigger the modal 'open' event. // modal.trigger( 'reveal:open' ); // // Get the closeButton variable element(s). // $closeButton = $( '.' + options.dismissModalClass ) // // Bind the element 'click' event and handler. // .bind( 'click.reveal', function () { // // Trigger the modal 'close' event. // modal.trigger( 'reveal:close' ); }); // // Should we close the modal background on click? // if ( options.closeOnBackgroundClick ) { // // Yes, close the modal background on 'click' // Set the modal background css 'cursor' propety to pointer. // Adds a pointer symbol when you mouse over the modal background. // modalBg.css( { "cursor": "pointer" } ); // // Bind a 'click' event handler to the modal background. // modalBg.bind( 'click.reveal', function () { // // Trigger the modal 'close' event. // modal.trigger( 'reveal:close' ); }); } // // Bind keyup functions on the body element. // We'll want to close the modal when the 'escape' key is hit. // $( 'body' ).bind( 'keyup.reveal', function ( event ) { // // Did the escape key get triggered? // if ( event.which === 27 ) { // 27 is the keycode for the Escape key // // Escape key was triggered. // Trigger the modal 'close' event. // modal.trigger( 'reveal:close' ); } }); // end $(body) }); // end this.each }; // end $.fn } ( jQuery ) );
JavaScript
;(function (window, document, $) { // Set the negative margin on the top menu for slide-menu pages var $selector1 = $('#topMenu'), events = 'click.fndtn'; if ($selector1.length > 0) $selector1.css("margin-top", $selector1.height() * -1); // Watch for clicks to show the sidebar var $selector2 = $('#sidebarButton'); if ($selector2.length > 0) { $('#sidebarButton').on(events, function (e) { e.preventDefault(); $('body').toggleClass('active'); }); } // Watch for clicks to show the menu for slide-menu pages var $selector3 = $('#menuButton'); if ($selector3.length > 0) { $('#menuButton').on(events, function (e) { e.preventDefault(); $('body').toggleClass('active-menu'); }); } // // Adjust sidebars and sizes when resized // $(window).resize(function() { // // if (!navigator.userAgent.match(/Android/i)) $('body').removeClass('active'); // var $selector4 = $('#topMenu'); // if ($selector4.length > 0) $selector4.css("margin-top", $selector4.height() * -1); // }); // Switch panels for the paneled nav on mobile var $selector5 = $('#switchPanels'); if ($selector5.length > 0) { $('#switchPanels dd').on(events, function (e) { e.preventDefault(); var switchToPanel = $(this).children('a').attr('href'), switchToIndex = $(switchToPanel).index(); $(this).toggleClass('active').siblings().removeClass('active'); $(switchToPanel).parent().css("left", (switchToIndex * (-100) + '%')); }); } $('#nav li a').on(events, function (e) { e.preventDefault(); var href = $(this).attr('href'), $target = $(href); $('html, body').animate({scrollTop : $target.offset().top}, 300); }); }(this, document, jQuery));
JavaScript
;(function ($, window, document, undefined) { 'use strict'; var settings = { callback: $.noop, init: false }, methods = { init : function (options) { settings = $.extend({}, options, settings); return this.each(function () { if (!settings.init) methods.events(); }); }, events : function () { $(document).on('click.fndtn', '.tabs a', function (e) { methods.set_tab($(this).parent('dd, li'), e); }); settings.init = true; }, set_tab : function ($tab, e) { var $activeTab = $tab.closest('dl, ul').find('.active'), target = $tab.children('a').attr("href"), hasHash = /^#/.test(target), $content = $(target + 'Tab'); if (hasHash && $content.length > 0) { // Show tab content e.preventDefault(); $content.closest('.tabs-content').children('li').removeClass('active').hide(); $content.css('display', 'block').addClass('active'); } // Make active tab $activeTab.removeClass('active'); $tab.addClass('active'); settings.callback(); } } $.fn.foundationTabs = function (method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.foundationTabs'); } }; }(jQuery, this, this.document));
JavaScript
/* * jQuery Foundation Top Bar 2.0.2 * http://foundation.zurb.com * Copyright 2012, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ /*jslint unparam: true, browser: true, indent: 2 */ ;(function ($, window, undefined) { 'use strict'; var settings = { index : 0, initialized : false }, methods = { init : function (options) { return this.each(function () { settings = $.extend(settings, options); settings.$w = $(window), settings.$topbar = $('nav.top-bar'), settings.$section = settings.$topbar.find('section'), settings.$titlebar = settings.$topbar.children('ul:first'); var breakpoint = $("<div class='top-bar-js-breakpoint'/>").appendTo("body"); settings.breakPoint = breakpoint.width(); breakpoint.remove(); if (!settings.initialized) { methods.assemble(); settings.initialized = true; } if (!settings.height) { methods.largestUL(); } if (settings.$topbar.parent().hasClass('fixed')) { $('body').css('padding-top',settings.$topbar.outerHeight()) } $('.top-bar .toggle-topbar').die('click.fndtn').live('click.fndtn', function (e) { e.preventDefault(); if (methods.breakpoint()) { settings.$topbar.toggleClass('expanded'); settings.$topbar.css('min-height', ''); } if (!settings.$topbar.hasClass('expanded')) { settings.$section.css({left: '0%'}); settings.$section.find('>.name').css({left: '100%'}); settings.$section.find('li.moved').removeClass('moved'); settings.index = 0; } }); // Show the Dropdown Levels on Click $('.top-bar .has-dropdown>a').die('click.fndtn').live('click.fndtn', function (e) { if (Modernizr.touch || methods.breakpoint()) e.preventDefault(); if (methods.breakpoint()) { var $this = $(this), $selectedLi = $this.closest('li'), $nextLevelUl = $selectedLi.children('ul'), $nextLevelUlHeight = 0, $largestUl; settings.index += 1; $selectedLi.addClass('moved'); settings.$section.css({left: -(100 * settings.index) + '%'}); settings.$section.find('>.name').css({left: 100 * settings.index + '%'}); $this.siblings('ul').height(settings.height + settings.$titlebar.outerHeight(true)); settings.$topbar.css('min-height', settings.height + settings.$titlebar.outerHeight(true) * 2) } }); $(window).on('resize.fndtn.topbar',function() { if (!methods.breakpoint()) { settings.$topbar.css('min-height', ''); } }); // Go up a level on Click $('.top-bar .has-dropdown .back').die('click.fndtn').live('click.fndtn', function (e) { e.preventDefault(); var $this = $(this), $movedLi = $this.closest('li.moved'), $previousLevelUl = $movedLi.parent(); settings.index -= 1; settings.$section.css({left: -(100 * settings.index) + '%'}); settings.$section.find('>.name').css({'left': 100 * settings.index + '%'}); if (settings.index === 0) { settings.$topbar.css('min-height', 0); } setTimeout(function () { $movedLi.removeClass('moved'); }, 300); }); }); }, breakpoint : function () { return settings.$w.width() < settings.breakPoint; }, assemble : function () { // Pull element out of the DOM for manipulation settings.$section.detach(); settings.$section.find('.has-dropdown>a').each(function () { var $link = $(this), $dropdown = $link.siblings('.dropdown'), $titleLi = $('<li class="title back js-generated"><h5><a href="#"></a></h5></li>'); // Copy link to subnav $titleLi.find('h5>a').html($link.html()); $dropdown.prepend($titleLi); }); // Put element back in the DOM settings.$section.appendTo(settings.$topbar); }, largestUL : function () { var uls = settings.$topbar.find('section ul ul'), largest = uls.first(), total = 0; uls.each(function () { if ($(this).children('li').length > largest.children('li').length) { largest = $(this); } }); largest.children('li').each(function () { total += $(this).outerHeight(true); }); settings.height = total; } }; $.fn.foundationTopBar = function (method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.foundationTopBar'); } }; }(jQuery, this));
JavaScript
/* * jQuery Orbit Plugin 1.4.0 * www.ZURB.com/playground * Copyright 2010, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ (function ($) { 'use strict'; $.fn.findFirstImage = function () { return this.first() .find('img') .andSelf().filter('img') .first(); }; var ORBIT = { defaults: { animation: 'horizontal-push', // fade, horizontal-slide, vertical-slide, horizontal-push, vertical-push animationSpeed: 600, // how fast animations are timer: true, // display timer? advanceSpeed: 4000, // if timer is enabled, time between transitions pauseOnHover: false, // if you hover pauses the slider startClockOnMouseOut: false, // if clock should start on MouseOut startClockOnMouseOutAfter: 1000, // how long after MouseOut should the timer start again directionalNav: true, // manual advancing directional navs directionalNavRightText: 'Right', // text of right directional element for accessibility directionalNavLeftText: 'Left', // text of left directional element for accessibility captions: true, // do you want captions? captionAnimation: 'fade', // fade, slideOpen, none captionAnimationSpeed: 600, // if so how quickly should they animate in resetTimerOnClick: false, // true resets the timer instead of pausing slideshow progress on manual navigation bullets: false, // true or false to activate the bullet navigation bulletThumbs: false, // thumbnails for the bullets bulletThumbLocation: '', // relative path to thumbnails from this file afterSlideChange: $.noop, // callback to execute after slide changes afterLoadComplete: $.noop, // callback to execute after everything has been loaded fluid: true, centerBullets: true, // center bullet nav with js, turn this off if you want to position the bullet nav manually singleCycle: false, // cycles through orbit slides only once slideNumber: false, // display slide numbers? stackOnSmall: false // stack slides on small devices (i.e. phones) }, activeSlide: 0, numberSlides: 0, orbitWidth: null, orbitHeight: null, locked: null, timerRunning: null, degrees: 0, wrapperHTML: '<div class="orbit-wrapper" />', timerHTML: '<div class="timer"><span class="mask"><span class="rotator"></span></span><span class="pause"></span></div>', captionHTML: '<div class="orbit-caption"></div>', directionalNavHTML: '<div class="slider-nav hide-for-small"><span class="right"></span><span class="left"></span></div>', bulletHTML: '<ul class="orbit-bullets"></ul>', slideNumberHTML: '<span class="orbit-slide-counter"></span>', init: function (element, options) { var $imageSlides, imagesLoadedCount = 0, self = this; // Bind functions to correct context this.clickTimer = $.proxy(this.clickTimer, this); this.addBullet = $.proxy(this.addBullet, this); this.resetAndUnlock = $.proxy(this.resetAndUnlock, this); this.stopClock = $.proxy(this.stopClock, this); this.startTimerAfterMouseLeave = $.proxy(this.startTimerAfterMouseLeave, this); this.clearClockMouseLeaveTimer = $.proxy(this.clearClockMouseLeaveTimer, this); this.rotateTimer = $.proxy(this.rotateTimer, this); this.options = $.extend({}, this.defaults, options); if (this.options.timer === 'false') this.options.timer = false; if (this.options.captions === 'false') this.options.captions = false; if (this.options.directionalNav === 'false') this.options.directionalNav = false; this.$element = $(element); this.$wrapper = this.$element.wrap(this.wrapperHTML).parent(); this.$slides = this.$element.children('img, a, div, figure'); this.$element.on('movestart', function(e) { // If the movestart is heading off in an upwards or downwards // direction, prevent it so that the browser scrolls normally. if ((e.distX > e.distY && e.distX < -e.distY) || (e.distX < e.distY && e.distX > -e.distY)) { e.preventDefault(); } }); this.$element.bind('orbit.next swipeleft', function () { self.shift('next'); }); this.$element.bind('orbit.prev swiperight', function () { self.shift('prev'); }); this.$element.bind('orbit.goto', function (event, index) { self.shift(index); }); this.$element.bind('orbit.start', function (event, index) { self.startClock(); }); this.$element.bind('orbit.stop', function (event, index) { self.stopClock(); }); $imageSlides = this.$slides.filter('img'); if ($imageSlides.length === 0) { this.loaded(); } else { $imageSlides.bind('imageready', function () { imagesLoadedCount += 1; if (imagesLoadedCount === $imageSlides.length) { self.loaded(); } }); } }, loaded: function () { this.$element .addClass('orbit') .css({width: '1px', height: '1px'}); if (this.options.stackOnSmall) { this.$element.addClass('orbit-stack-on-small'); } this.$slides.addClass('orbit-slide'); this.setDimentionsFromLargestSlide(); this.updateOptionsIfOnlyOneSlide(); this.setupFirstSlide(); this.notifySlideChange(); if (this.options.timer) { this.setupTimer(); this.startClock(); } if (this.options.captions) { this.setupCaptions(); } if (this.options.directionalNav) { this.setupDirectionalNav(); } if (this.options.bullets) { this.setupBulletNav(); this.setActiveBullet(); } this.options.afterLoadComplete.call(this); Holder.run(); }, currentSlide: function () { return this.$slides.eq(this.activeSlide); }, notifySlideChange: function() { if (this.options.slideNumber) { var txt = (this.activeSlide+1) + ' of ' + this.$slides.length; this.$element.trigger("orbit.change", {slideIndex: this.activeSlide, slideCount: this.$slides.length}); if (this.$counter === undefined) { var $counter = $(this.slideNumberHTML).html(txt); this.$counter = $counter; this.$wrapper.append(this.$counter); } else { this.$counter.html(txt); } } }, setDimentionsFromLargestSlide: function () { //Collect all slides and set slider size of largest image var self = this, $fluidPlaceholder; self.$element.add(self.$wrapper).width(this.$slides.first().outerWidth()); self.$element.add(self.$wrapper).height(this.$slides.first().height()); self.orbitWidth = this.$slides.first().outerWidth(); self.orbitHeight = this.$slides.first().height(); $fluidPlaceholder = this.$slides.first().findFirstImage().clone(); this.$slides.each(function () { var slide = $(this), slideWidth = slide.outerWidth(), slideHeight = slide.height(); if (slideWidth > self.$element.outerWidth()) { self.$element.add(self.$wrapper).width(slideWidth); self.orbitWidth = self.$element.outerWidth(); } if (slideHeight > self.$element.height()) { self.$element.add(self.$wrapper).height(slideHeight); self.orbitHeight = self.$element.height(); $fluidPlaceholder = $(this).findFirstImage().clone(); } self.numberSlides += 1; }); if (this.options.fluid) { if (typeof this.options.fluid === "string") { // $fluidPlaceholder = $("<img>").attr("src", "http://placehold.it/" + this.options.fluid); $fluidPlaceholder = $("<img>").attr("data-src", "holder.js/" + this.options.fluid); //var inner = $("<div/>").css({"display":"inline-block", "width":"2px", "height":"2px"}); //$fluidPlaceholder = $("<div/>").css({"float":"left"}); //$fluidPlaceholder.wrapInner(inner); //$fluidPlaceholder = $("<div/>").css({"height":"1px", "width":"2px"}); //$fluidPlaceholder = $("<div style='display:inline-block;width:2px;height:1px;'></div>"); } self.$element.prepend($fluidPlaceholder); $fluidPlaceholder.addClass('fluid-placeholder'); self.$element.add(self.$wrapper).css({width: 'inherit'}); self.$element.add(self.$wrapper).css({height: 'inherit'}); $(window).bind('resize', function () { self.orbitWidth = self.$element.outerWidth(); self.orbitHeight = self.$element.height(); }); } }, //Animation locking functions lock: function () { this.locked = true; }, unlock: function () { this.locked = false; }, updateOptionsIfOnlyOneSlide: function () { if(this.$slides.length === 1) { this.options.directionalNav = false; this.options.timer = false; this.options.bullets = false; } }, setupFirstSlide: function () { //Set initial front photo z-index and fades it in var self = this; this.$slides.first() .css({"z-index" : 3, "opacity" : 1}) .fadeIn(function() { //brings in all other slides IF css declares a display: none self.$slides.css({"display":"block"}) }); }, startClock: function () { var self = this; if(!this.options.timer) { return false; } if (this.$timer.is(':hidden')) { this.clock = setInterval(function () { self.$element.trigger('orbit.next'); }, this.options.advanceSpeed); } else { this.timerRunning = true; this.$pause.removeClass('active'); this.clock = setInterval(this.rotateTimer, this.options.advanceSpeed / 180, false); } }, rotateTimer: function (reset) { var degreeCSS = "rotate(" + this.degrees + "deg)"; this.degrees += 2; this.$rotator.css({ "-webkit-transform": degreeCSS, "-moz-transform": degreeCSS, "-o-transform": degreeCSS, "-ms-transform": degreeCSS }); if (reset) { this.degrees = 0; this.$rotator.removeClass('move'); this.$mask.removeClass('move'); } if(this.degrees > 180) { this.$rotator.addClass('move'); this.$mask.addClass('move'); } if(this.degrees > 360) { this.$rotator.removeClass('move'); this.$mask.removeClass('move'); this.degrees = 0; this.$element.trigger('orbit.next'); } }, stopClock: function () { if (!this.options.timer) { return false; } else { this.timerRunning = false; clearInterval(this.clock); this.$pause.addClass('active'); } }, setupTimer: function () { this.$timer = $(this.timerHTML); this.$wrapper.append(this.$timer); this.$rotator = this.$timer.find('.rotator'); this.$mask = this.$timer.find('.mask'); this.$pause = this.$timer.find('.pause'); this.$timer.click(this.clickTimer); if (this.options.startClockOnMouseOut) { this.$wrapper.mouseleave(this.startTimerAfterMouseLeave); this.$wrapper.mouseenter(this.clearClockMouseLeaveTimer); } if (this.options.pauseOnHover) { this.$wrapper.mouseenter(this.stopClock); } }, startTimerAfterMouseLeave: function () { var self = this; this.outTimer = setTimeout(function() { if(!self.timerRunning){ self.startClock(); } }, this.options.startClockOnMouseOutAfter) }, clearClockMouseLeaveTimer: function () { clearTimeout(this.outTimer); }, clickTimer: function () { if(!this.timerRunning) { this.startClock(); } else { this.stopClock(); } }, setupCaptions: function () { this.$caption = $(this.captionHTML); this.$wrapper.append(this.$caption); this.setCaption(); }, setCaption: function () { var captionLocation = this.currentSlide().attr('data-caption'), captionHTML; if (!this.options.captions) { return false; } //Set HTML for the caption if it exists if (captionLocation) { //if caption text is blank, don't show captions if ($.trim($(captionLocation).text()).length < 1){ return false; } captionHTML = $(captionLocation).html(); //get HTML from the matching HTML entity this.$caption .attr('id', captionLocation) // Add ID caption TODO why is the id being set? .html(captionHTML); // Change HTML in Caption //Animations for Caption entrances switch (this.options.captionAnimation) { case 'none': this.$caption.show(); break; case 'fade': this.$caption.fadeIn(this.options.captionAnimationSpeed); break; case 'slideOpen': this.$caption.slideDown(this.options.captionAnimationSpeed); break; } } else { //Animations for Caption exits switch (this.options.captionAnimation) { case 'none': this.$caption.hide(); break; case 'fade': this.$caption.fadeOut(this.options.captionAnimationSpeed); break; case 'slideOpen': this.$caption.slideUp(this.options.captionAnimationSpeed); break; } } }, setupDirectionalNav: function () { var self = this, $directionalNav = $(this.directionalNavHTML); $directionalNav.find('.right').html(this.options.directionalNavRightText); $directionalNav.find('.left').html(this.options.directionalNavLeftText); this.$wrapper.append($directionalNav); this.$wrapper.find('.left').click(function () { self.stopClock(); if (self.options.resetTimerOnClick) { self.rotateTimer(true); self.startClock(); } self.$element.trigger('orbit.prev'); }); this.$wrapper.find('.right').click(function () { self.stopClock(); if (self.options.resetTimerOnClick) { self.rotateTimer(true); self.startClock(); } self.$element.trigger('orbit.next'); }); }, setupBulletNav: function () { this.$bullets = $(this.bulletHTML); this.$wrapper.append(this.$bullets); this.$slides.each(this.addBullet); this.$element.addClass('with-bullets'); if (this.options.centerBullets) this.$bullets.css('margin-left', -this.$bullets.outerWidth() / 2); }, addBullet: function (index, slide) { var position = index + 1, $li = $('<li>' + (position) + '</li>'), thumbName, self = this; if (this.options.bulletThumbs) { thumbName = $(slide).attr('data-thumb'); if (thumbName) { $li .addClass('has-thumb') .css({background: "url(" + this.options.bulletThumbLocation + thumbName + ") no-repeat"});; } } this.$bullets.append($li); $li.data('index', index); $li.click(function () { self.stopClock(); if (self.options.resetTimerOnClick) { self.rotateTimer(true); self.startClock(); } self.$element.trigger('orbit.goto', [$li.data('index')]) }); }, setActiveBullet: function () { if(!this.options.bullets) { return false; } else { this.$bullets.find('li') .removeClass('active') .eq(this.activeSlide) .addClass('active'); } }, resetAndUnlock: function () { this.$slides .eq(this.prevActiveSlide) .css({"z-index" : 1}); this.unlock(); this.options.afterSlideChange.call(this, this.$slides.eq(this.prevActiveSlide), this.$slides.eq(this.activeSlide)); }, shift: function (direction) { var slideDirection = direction; //remember previous activeSlide this.prevActiveSlide = this.activeSlide; //exit function if bullet clicked is same as the current image if (this.prevActiveSlide == slideDirection) { return false; } if (this.$slides.length == "1") { return false; } if (!this.locked) { this.lock(); //deduce the proper activeImage if (direction == "next") { this.activeSlide++; if (this.activeSlide == this.numberSlides) { this.activeSlide = 0; } } else if (direction == "prev") { this.activeSlide-- if (this.activeSlide < 0) { this.activeSlide = this.numberSlides - 1; } } else { this.activeSlide = direction; if (this.prevActiveSlide < this.activeSlide) { slideDirection = "next"; } else if (this.prevActiveSlide > this.activeSlide) { slideDirection = "prev" } } //set to correct bullet this.setActiveBullet(); this.notifySlideChange(); //set previous slide z-index to one below what new activeSlide will be this.$slides .eq(this.prevActiveSlide) .css({"z-index" : 2}); //fade if (this.options.animation == "fade") { this.$slides .eq(this.activeSlide) .css({"opacity" : 0, "z-index" : 3}) .animate({"opacity" : 1}, this.options.animationSpeed, this.resetAndUnlock); this.$slides .eq(this.prevActiveSlide) .animate({"opacity":0}, this.options.animationSpeed); } //horizontal-slide if (this.options.animation == "horizontal-slide") { if (slideDirection == "next") { this.$slides .eq(this.activeSlide) .css({"left": this.orbitWidth, "z-index" : 3}) .css("opacity", 1) .animate({"left" : 0}, this.options.animationSpeed, this.resetAndUnlock); } if (slideDirection == "prev") { this.$slides .eq(this.activeSlide) .css({"left": -this.orbitWidth, "z-index" : 3}) .css("opacity", 1) .animate({"left" : 0}, this.options.animationSpeed, this.resetAndUnlock); } this.$slides .eq(this.prevActiveSlide) .css("opacity", 0); } //vertical-slide if (this.options.animation == "vertical-slide") { if (slideDirection == "prev") { this.$slides .eq(this.activeSlide) .css({"top": this.orbitHeight, "z-index" : 3}) .css("opacity", 1) .animate({"top" : 0}, this.options.animationSpeed, this.resetAndUnlock); this.$slides .eq(this.prevActiveSlide) .css("opacity", 0); } if (slideDirection == "next") { this.$slides .eq(this.activeSlide) .css({"top": -this.orbitHeight, "z-index" : 3}) .css("opacity", 1) .animate({"top" : 0}, this.options.animationSpeed, this.resetAndUnlock); } this.$slides .eq(this.prevActiveSlide) .css("opacity", 0); } //horizontal-push if (this.options.animation == "horizontal-push") { if (slideDirection == "next") { this.$slides .eq(this.activeSlide) .css({"left": this.orbitWidth, "z-index" : 3}) .animate({"left" : 0, "opacity" : 1}, this.options.animationSpeed, this.resetAndUnlock); this.$slides .eq(this.prevActiveSlide) .animate({"left" : -this.orbitWidth}, this.options.animationSpeed, "", function(){ $(this).css({"opacity" : 0}); }); } if (slideDirection == "prev") { this.$slides .eq(this.activeSlide) .css({"left": -this.orbitWidth, "z-index" : 3}) .animate({"left" : 0, "opacity" : 1}, this.options.animationSpeed, this.resetAndUnlock); this.$slides .eq(this.prevActiveSlide) .animate({"left" : this.orbitWidth}, this.options.animationSpeed, "", function(){ $(this).css({"opacity" : 0}); }); } } //vertical-push if (this.options.animation == "vertical-push") { if (slideDirection == "next") { this.$slides .eq(this.activeSlide) .css({top: -this.orbitHeight, "z-index" : 3}) .css("opacity", 1) .animate({top : 0, "opacity":1}, this.options.animationSpeed, this.resetAndUnlock); this.$slides .eq(this.prevActiveSlide) .css("opacity", 0) .animate({top : this.orbitHeight}, this.options.animationSpeed, ""); } if (slideDirection == "prev") { this.$slides .eq(this.activeSlide) .css({top: this.orbitHeight, "z-index" : 3}) .css("opacity", 1) .animate({top : 0}, this.options.animationSpeed, this.resetAndUnlock); this.$slides .eq(this.prevActiveSlide) .css("opacity", 0) .animate({top : -this.orbitHeight}, this.options.animationSpeed); } } this.setCaption(); } if (this.$slides.last() && this.options.singleCycle) { this.stopClock(); } } }; $.fn.orbit = function (options) { return this.each(function () { var orbit = $.extend({}, ORBIT); orbit.init(this, options); }); }; })(jQuery); /*! * jQuery imageready Plugin * http://www.zurb.com/playground/ * * Copyright 2011, ZURB * Released under the MIT License */ (function ($) { var options = {}; $.event.special.imageready = { setup: function (data, namespaces, eventHandle) { options = data || options; }, add: function (handleObj) { var $this = $(this), src; if ( this.nodeType === 1 && this.tagName.toLowerCase() === 'img' && this.src !== '' ) { if (options.forceLoad) { src = $this.attr('src'); $this.attr('src', ''); bindToLoad(this, handleObj.handler); $this.attr('src', src); } else if ( this.complete || this.readyState === 4 ) { handleObj.handler.apply(this, arguments); } else { bindToLoad(this, handleObj.handler); } } }, teardown: function (namespaces) { $(this).unbind('.imageready'); } }; function bindToLoad(element, callback) { var $this = $(element); $this.bind('load.imageready', function () { callback.apply(element, arguments); $this.unbind('load.imageready'); }); } }(jQuery)); /* Holder - 1.3 - client side image placeholders (c) 2012 Ivan Malopinsky / http://imsky.co Provided under the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 Commercial use requires attribution. */ var Holder = Holder || {}; (function (app, win) { var preempted = false, fallback = false, canvas = document.createElement('canvas'); //http://javascript.nwbox.com/ContentLoaded by Diego Perini with modifications function contentLoaded(n,t){var l="complete",s="readystatechange",u=!1,h=u,c=!0,i=n.document,a=i.documentElement,e=i.addEventListener?"addEventListener":"attachEvent",v=i.addEventListener?"removeEventListener":"detachEvent",f=i.addEventListener?"":"on",r=function(e){(e.type!=s||i.readyState==l)&&((e.type=="load"?n:i)[v](f+e.type,r,u),!h&&(h=!0)&&t.call(n,null))},o=function(){try{a.doScroll("left")}catch(n){setTimeout(o,50);return}r("poll")};if(i.readyState==l)t.call(n,"lazy");else{if(i.createEventObject&&a.doScroll){try{c=!n.frameElement}catch(y){}c&&o()}i[e](f+"DOMContentLoaded",r,u),i[e](f+s,r,u),n[e](f+"load",r,u)}}; //https://gist.github.com/991057 by Jed Schmidt with modifications function selector(a){ a=a.match(/^(\W)?(.*)/);var b=document["getElement"+(a[1]?a[1]=="#"?"ById":"sByClassName":"sByTagName")](a[2]); var ret=[]; b!=null&&(b.length?ret=b:b.length==0?ret=b:ret=[b]); return ret; } //shallow object property extend function extend(a,b){var c={};for(var d in a)c[d]=a[d];for(var e in b)c[e]=b[e];return c} function draw(ctx, dimensions, template) { var dimension_arr = [dimensions.height, dimensions.width].sort(); var maxFactor = Math.round(dimension_arr[1] / 16), minFactor = Math.round(dimension_arr[0] / 16); var text_height = Math.max(template.size, maxFactor); canvas.width = dimensions.width; canvas.height = dimensions.height; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillStyle = template.background; ctx.fillRect(0, 0, dimensions.width, dimensions.height); ctx.fillStyle = template.foreground; ctx.font = "bold " + text_height + "px sans-serif"; var text = template.text ? template.text : (dimensions.width + "x" + dimensions.height); if (Math.round(ctx.measureText(text).width) / dimensions.width > 1) { text_height = Math.max(minFactor, template.size); } ctx.font = "bold " + text_height + "px sans-serif"; ctx.fillText(text, (dimensions.width / 2), (dimensions.height / 2), dimensions.width); return canvas.toDataURL("image/png"); } if (!canvas.getContext) { fallback = true; } else { if (canvas.toDataURL("image/png").indexOf("data:image/png") < 0) { //Android doesn't support data URI fallback = true; } else { var ctx = canvas.getContext("2d"); } } var settings = { domain: "holder.js", images: "img", themes: { "gray": { background: "#eee", foreground: "#aaa", size: 12 }, "social": { background: "#3a5a97", foreground: "#fff", size: 12 }, "industrial": { background: "#434A52", foreground: "#C2F200", size: 12 } } }; app.flags = { dimensions: { regex: /([0-9]+)x([0-9]+)/, output: function(val){ var exec = this.regex.exec(val); return { width: +exec[1], height: +exec[2] } } }, colors: { regex: /#([0-9a-f]{3,})\:#([0-9a-f]{3,})/i, output: function(val){ var exec = this.regex.exec(val); return { size: settings.themes.gray.size, foreground: "#" + exec[2], background: "#" + exec[1] } } }, text: { regex: /text\:(.*)/, output: function(val){ return this.regex.exec(val)[1]; } } } for(var flag in app.flags){ app.flags[flag].match = function (val){ return val.match(this.regex) } } app.add_theme = function (name, theme) { name != null && theme != null && (settings.themes[name] = theme); return app; }; app.add_image = function (src, el) { var node = selector(el); if (node.length) { for (var i = 0, l = node.length; i < l; i++) { var img = document.createElement("img") img.setAttribute("data-src", src); node[i].appendChild(img); } } return app; }; app.run = function (o) { var options = extend(settings, o), images = selector(options.images), preempted = true; for (var l = images.length, i = 0; i < l; i++) { var theme = settings.themes.gray; var src = images[i].getAttribute("data-src") || images[i].getAttribute("src"); if ( !! ~src.indexOf(options.domain)) { var render = false, dimensions = null, text = null; var flags = src.substr(src.indexOf(options.domain) + options.domain.length + 1).split("/"); for (sl = flags.length, j = 0; j < sl; j++) { if (app.flags.dimensions.match(flags[j])) { render = true; dimensions = app.flags.dimensions.output(flags[j]); } else if (app.flags.colors.match(flags[j])) { theme = app.flags.colors.output(flags[j]); } else if (options.themes[flags[j]]) { //If a theme is specified, it will override custom colors theme = options.themes[flags[j]]; } else if (app.flags.text.match(flags[j])) { text = app.flags.text.output(flags[j]); } } if (render) { images[i].setAttribute("data-src", src); var dimensions_caption = dimensions.width + "x" + dimensions.height; images[i].setAttribute("alt", text ? text : theme.text ? theme.text + " [" + dimensions_caption + "]" : dimensions_caption); // Fallback // images[i].style.width = dimensions.width + "px"; // images[i].style.height = dimensions.height + "px"; images[i].style.backgroundColor = theme.background; var theme = (text ? extend(theme, { text: text }) : theme); if (!fallback) { images[i].setAttribute("src", draw(ctx, dimensions, theme)); } } } } return app; }; contentLoaded(win, function () { preempted || app.run() }) })(Holder, window);
JavaScript
/*! http://mths.be/placeholder v2.0.7 by @mathias */ ;(function(window, document, $) { var isInputSupported = 'placeholder' in document.createElement('input'), isTextareaSupported = 'placeholder' in document.createElement('textarea'), prototype = $.fn, valHooks = $.valHooks, hooks, placeholder; if (isInputSupported && isTextareaSupported) { placeholder = prototype.placeholder = function() { return this; }; placeholder.input = placeholder.textarea = true; } else { placeholder = prototype.placeholder = function() { var $this = this; $this .filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]') .not('.placeholder') .bind({ 'focus.placeholder': clearPlaceholder, 'blur.placeholder': setPlaceholder }) .data('placeholder-enabled', true) .trigger('blur.placeholder'); return $this; }; placeholder.input = isInputSupported; placeholder.textarea = isTextareaSupported; hooks = { 'get': function(element) { var $element = $(element); return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value; }, 'set': function(element, value) { var $element = $(element); if (!$element.data('placeholder-enabled')) { return element.value = value; } if (value == '') { element.value = value; // Issue #56: Setting the placeholder causes problems if the element continues to have focus. if (element != document.activeElement) { // We can't use `triggerHandler` here because of dummy text/password inputs :( setPlaceholder.call(element); } } else if ($element.hasClass('placeholder')) { clearPlaceholder.call(element, true, value) || (element.value = value); } else { element.value = value; } // `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363 return $element; } }; isInputSupported || (valHooks.input = hooks); isTextareaSupported || (valHooks.textarea = hooks); $(function() { // Look for forms $(document).delegate('form', 'submit.placeholder', function() { // Clear the placeholder values so they don't get submitted var $inputs = $('.placeholder', this).each(clearPlaceholder); setTimeout(function() { $inputs.each(setPlaceholder); }, 10); }); }); // Clear placeholder values upon page reload $(window).bind('beforeunload.placeholder', function() { $('.placeholder').each(function() { this.value = ''; }); }); } function args(elem) { // Return an object of element attributes var newAttrs = {}, rinlinejQuery = /^jQuery\d+$/; $.each(elem.attributes, function(i, attr) { if (attr.specified && !rinlinejQuery.test(attr.name)) { newAttrs[attr.name] = attr.value; } }); return newAttrs; } function clearPlaceholder(event, value) { var input = this, $input = $(input); if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) { if ($input.data('placeholder-password')) { $input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id')); // If `clearPlaceholder` was called from `$.valHooks.input.set` if (event === true) { return $input[0].value = value; } $input.focus(); } else { input.value = ''; $input.removeClass('placeholder'); input == document.activeElement && input.select(); } } } function setPlaceholder() { var $replacement, input = this, $input = $(input), $origInput = $input, id = this.id; if (input.value == '') { if (input.type == 'password') { if (!$input.data('placeholder-textinput')) { try { $replacement = $input.clone().attr({ 'type': 'text' }); } catch(e) { $replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' })); } $replacement .removeAttr('name') .data({ 'placeholder-password': true, 'placeholder-id': id }) .bind('focus.placeholder', clearPlaceholder); $input .data({ 'placeholder-textinput': $replacement, 'placeholder-id': id }) .before($replacement); } $input = $input.removeAttr('id').hide().prev().attr('id', id).show(); // Note: `$input[0] != input` now! } $input.addClass('placeholder'); $input[0].value = $input.attr('placeholder'); } else { $input.removeClass('placeholder'); } } }(this, document, jQuery));
JavaScript
;(function ($, window, undefined) { 'use strict'; $.fn.foundationMediaQueryViewer = function (options) { var settings = $.extend(options,{toggleKey:77}), // Press 'M' $doc = $(document); $doc.on("keyup.mediaQueryViewer", ":input", function (e){ if (e.which === settings.toggleKey) { e.stopPropagation(); } }); $doc.on("keyup.mediaQueryViewer", function (e) { var $mqViewer = $('#fqv'); if (e.which === settings.toggleKey) { if ($mqViewer.length > 0) { $mqViewer.remove(); } else { $('body').prepend('<div id="fqv" style="position:fixed;top:4px;left:4px;z-index:999;color:#fff;"><p style="font-size:12px;background:rgba(0,0,0,0.75);padding:5px;margin-bottom:1px;line-height:1.2;"><span class="left">Media:</span> <span style="font-weight:bold;" class="show-for-xlarge">Extra Large</span><span style="font-weight:bold;" class="show-for-large">Large</span><span style="font-weight:bold;" class="show-for-medium">Medium</span><span style="font-weight:bold;" class="show-for-small">Small</span><span style="font-weight:bold;" class="show-for-landscape">Landscape</span><span style="font-weight:bold;" class="show-for-portrait">Portrait</span><span style="font-weight:bold;" class="show-for-touch">Touch</span></p></div>'); } } }); }; })(jQuery, this);
JavaScript
/* * jQuery Foundation Joyride Plugin 2.0.2 * http://foundation.zurb.com * Copyright 2012, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ /*jslint unparam: true, browser: true, indent: 2 */ ;(function ($, window, undefined) { 'use strict'; var defaults = { 'version' : '2.0.1', 'tipLocation' : 'bottom', // 'top' or 'bottom' in relation to parent 'nubPosition' : 'auto', // override on a per tooltip bases 'scrollSpeed' : 300, // Page scrolling speed in milliseconds 'timer' : 0, // 0 = no timer , all other numbers = timer in milliseconds 'startTimerOnClick' : true, // true or false - true requires clicking the first button start the timer 'startOffset' : 0, // the index of the tooltip you want to start on (index of the li) 'nextButton' : true, // true or false to control whether a next button is used 'tipAnimation' : 'fade', // 'pop' or 'fade' in each tip 'pauseAfter' : [], // array of indexes where to pause the tour after 'tipAnimationFadeSpeed': 300, // when tipAnimation = 'fade' this is speed in milliseconds for the transition 'cookieMonster' : false, // true or false to control whether cookies are used 'cookieName' : 'joyride', // Name the cookie you'll use 'cookieDomain' : false, // Will this cookie be attached to a domain, ie. '.notableapp.com' 'tipContainer' : 'body', // Where will the tip be attached 'postRideCallback' : $.noop, // A method to call once the tour closes (canceled or complete) 'postStepCallback' : $.noop, // A method to call after each step 'template' : { // HTML segments for tip layout 'link' : '<a href="#close" class="joyride-close-tip">X</a>', 'timer' : '<div class="joyride-timer-indicator-wrap"><span class="joyride-timer-indicator"></span></div>', 'tip' : '<div class="joyride-tip-guide"><span class="joyride-nub"></span></div>', 'wrapper' : '<div class="joyride-content-wrapper"></div>', 'button' : '<a href="#" class="small button joyride-next-tip"></a>' } }, Modernizr = Modernizr || false, settings = {}, methods = { init : function (opts) { return this.each(function () { if ($.isEmptyObject(settings)) { settings = $.extend(defaults, opts); // non configureable settings settings.document = window.document; settings.$document = $(settings.document); settings.$window = $(window); settings.$content_el = $(this); settings.body_offset = $(settings.tipContainer).position(); settings.$tip_content = $('> li', settings.$content_el); settings.paused = false; settings.attempts = 0; settings.tipLocationPatterns = { top: ['bottom'], bottom: [], // bottom should not need to be repositioned left: ['right', 'top', 'bottom'], right: ['left', 'top', 'bottom'] }; // are we using jQuery 1.7+ methods.jquery_check(); // can we create cookies? if (!$.isFunction($.cookie)) { settings.cookieMonster = false; } // generate the tips and insert into dom. if (!settings.cookieMonster || !$.cookie(settings.cookieName)) { settings.$tip_content.each(function (index) { methods.create({$li : $(this), index : index}); }); // show first tip if (!settings.startTimerOnClick && settings.timer > 0) { methods.show('init'); methods.startTimer(); } else { methods.show('init'); } } settings.$document.on('click.joyride', '.joyride-next-tip, .joyride-modal-bg', function (e) { e.preventDefault(); if (settings.$li.next().length < 1) { methods.end(); } else if (settings.timer > 0) { clearTimeout(settings.automate); methods.hide(); methods.show(); methods.startTimer(); } else { methods.hide(); methods.show(); } }); settings.$document.on('click.joyride', '.joyride-close-tip', function (e) { e.preventDefault(); methods.end(); }); settings.$window.bind('resize.joyride', function (e) { if (methods.is_phone()) { methods.pos_phone(); } else { methods.pos_default(); } }); } else { methods.restart(); } }); }, // call this method when you want to resume the tour resume : function () { methods.set_li(); methods.show(); }, tip_template : function (opts) { var $blank, content; opts.tip_class = opts.tip_class || ''; $blank = $(settings.template.tip).addClass(opts.tip_class); content = $.trim($(opts.li).html()) + methods.button_text(opts.button_text) + settings.template.link + methods.timer_instance(opts.index); $blank.append($(settings.template.wrapper)); $blank.first().attr('data-index', opts.index); $('.joyride-content-wrapper', $blank).append(content); return $blank[0]; }, timer_instance : function (index) { var txt; if ((index === 0 && settings.startTimerOnClick && settings.timer > 0) || settings.timer === 0) { txt = ''; } else { txt = methods.outerHTML($(settings.template.timer)[0]); } return txt; }, button_text : function (txt) { if (settings.nextButton) { txt = $.trim(txt) || 'Next'; txt = methods.outerHTML($(settings.template.button).append(txt)[0]); } else { txt = ''; } return txt; }, create : function (opts) { // backwards compatability with data-text attribute var buttonText = opts.$li.attr('data-button') || opts.$li.attr('data-text'), tipClass = opts.$li.attr('class'), $tip_content = $(methods.tip_template({ tip_class : tipClass, index : opts.index, button_text : buttonText, li : opts.$li })); $(settings.tipContainer).append($tip_content); }, show : function (init) { var opts = {}, ii, opts_arr = [], opts_len = 0, p, $timer = null; // are we paused? if (settings.$li === undefined || ($.inArray(settings.$li.index(), settings.pauseAfter) === -1)) { // don't go to the next li if the tour was paused if (settings.paused) { settings.paused = false; } else { methods.set_li(init); } settings.attempts = 0; if (settings.$li.length && settings.$target.length > 0) { opts_arr = (settings.$li.data('options') || ':').split(';'); opts_len = opts_arr.length; // parse options for (ii = opts_len - 1; ii >= 0; ii--) { p = opts_arr[ii].split(':'); if (p.length === 2) { opts[$.trim(p[0])] = $.trim(p[1]); } } settings.tipSettings = $.extend({}, settings, opts); settings.tipSettings.tipLocationPattern = settings.tipLocationPatterns[settings.tipSettings.tipLocation]; // scroll if not modal if (!/body/i.test(settings.$target.selector)) { methods.scroll_to(); } if (methods.is_phone()) { methods.pos_phone(true); } else { methods.pos_default(true); } $timer = $('.joyride-timer-indicator', settings.$next_tip); if (/pop/i.test(settings.tipAnimation)) { $timer.outerWidth(0); if (settings.timer > 0) { settings.$next_tip.show(); $timer.animate({ width: $('.joyride-timer-indicator-wrap', settings.$next_tip).outerWidth() }, settings.timer); } else { settings.$next_tip.show(); } } else if (/fade/i.test(settings.tipAnimation)) { $timer.outerWidth(0); if (settings.timer > 0) { settings.$next_tip.fadeIn(settings.tipAnimationFadeSpeed); settings.$next_tip.show(); $timer.animate({ width: $('.joyride-timer-indicator-wrap', settings.$next_tip).outerWidth() }, settings.timer); } else { settings.$next_tip.fadeIn(settings.tipAnimationFadeSpeed); } } settings.$current_tip = settings.$next_tip; // skip non-existant targets } else if (settings.$li && settings.$target.length < 1) { methods.show(); } else { methods.end(); } } else { settings.paused = true; } }, // detect phones with media queries if supported. is_phone : function () { if (Modernizr) { return Modernizr.mq('only screen and (max-width: 767px)'); } return (settings.$window.width() < 767) ? true : false; }, hide : function () { settings.postStepCallback(settings.$li.index(), settings.$current_tip); $('.joyride-modal-bg').hide(); settings.$current_tip.hide(); }, set_li : function (init) { if (init) { settings.$li = settings.$tip_content.eq(settings.startOffset); methods.set_next_tip(); settings.$current_tip = settings.$next_tip; } else { settings.$li = settings.$li.next(); methods.set_next_tip(); } methods.set_target(); }, set_next_tip : function () { settings.$next_tip = $('.joyride-tip-guide[data-index=' + settings.$li.index() + ']'); }, set_target : function () { var cl = settings.$li.attr('data-class'), id = settings.$li.attr('data-id'), $sel = function () { if (id) { return $(settings.document.getElementById(id)); } else if (cl) { return $('.' + cl).first(); } else { return $('body'); } }; settings.$target = $sel(); }, scroll_to : function () { var window_half, tipOffset; window_half = settings.$window.height() / 2; tipOffset = Math.ceil(settings.$target.offset().top - window_half + settings.$next_tip.outerHeight()); $("html, body").stop().animate({ scrollTop: tipOffset }, settings.scrollSpeed); }, paused : function () { if (($.inArray((settings.$li.index() + 1), settings.pauseAfter) === -1)) { return true; } return false; }, destroy : function () { settings.$document.off('.joyride'); $(window).off('.joyride'); $('.joyride-close-tip, .joyride-next-tip, .joyride-modal-bg').off('.joyride'); $('.joyride-tip-guide, .joyride-modal-bg').remove(); clearTimeout(settings.automate); settings = {}; }, restart : function () { methods.hide(); settings.$li = undefined; methods.show('init'); }, pos_default : function (init) { var half_fold = Math.ceil(settings.$window.height() / 2), tip_position = settings.$next_tip.offset(), $nub = $('.joyride-nub', settings.$next_tip), nub_height = Math.ceil($nub.outerHeight() / 2), toggle = init || false; // tip must not be "display: none" to calculate position if (toggle) { settings.$next_tip.css('visibility', 'hidden'); settings.$next_tip.show(); } if (!/body/i.test(settings.$target.selector)) { if (methods.bottom()) { settings.$next_tip.css({ top: (settings.$target.offset().top + nub_height + settings.$target.outerHeight()), left: settings.$target.offset().left}); methods.nub_position($nub, settings.tipSettings.nubPosition, 'top'); } else if (methods.top()) { settings.$next_tip.css({ top: (settings.$target.offset().top - settings.$next_tip.outerHeight() - nub_height), left: settings.$target.offset().left}); methods.nub_position($nub, settings.tipSettings.nubPosition, 'bottom'); } else if (methods.right()) { settings.$next_tip.css({ top: settings.$target.offset().top, left: (settings.$target.outerWidth() + settings.$target.offset().left)}); methods.nub_position($nub, settings.tipSettings.nubPosition, 'left'); } else if (methods.left()) { settings.$next_tip.css({ top: settings.$target.offset().top, left: (settings.$target.offset().left - settings.$next_tip.outerWidth() - nub_height)}); methods.nub_position($nub, settings.tipSettings.nubPosition, 'right'); } if (!methods.visible(methods.corners(settings.$next_tip)) && settings.attempts < settings.tipSettings.tipLocationPattern.length) { $nub.removeClass('bottom') .removeClass('top') .removeClass('right') .removeClass('left'); settings.tipSettings.tipLocation = settings.tipSettings.tipLocationPattern[settings.attempts]; settings.attempts++; methods.pos_default(true); } } else if (settings.$li.length) { methods.pos_modal($nub); } if (toggle) { settings.$next_tip.hide(); settings.$next_tip.css('visibility', 'visible'); } }, pos_phone : function (init) { var tip_height = settings.$next_tip.outerHeight(), tip_offset = settings.$next_tip.offset(), target_height = settings.$target.outerHeight(), $nub = $('.joyride-nub', settings.$next_tip), nub_height = Math.ceil($nub.outerHeight() / 2), toggle = init || false; $nub.removeClass('bottom') .removeClass('top') .removeClass('right') .removeClass('left'); if (toggle) { settings.$next_tip.css('visibility', 'hidden'); settings.$next_tip.show(); } if (!/body/i.test(settings.$target.selector)) { if (methods.top()) { settings.$next_tip.offset({top: settings.$target.offset().top - tip_height - nub_height}); $nub.addClass('bottom'); } else { settings.$next_tip.offset({top: settings.$target.offset().top + target_height + nub_height}); $nub.addClass('top'); } } else if (settings.$li.length) { methods.pos_modal($nub); } if (toggle) { settings.$next_tip.hide(); settings.$next_tip.css('visibility', 'visible'); } }, pos_modal : function ($nub) { methods.center(); $nub.hide(); if ($('.joyride-modal-bg').length < 1) { $('body').append('<div class="joyride-modal-bg">').show(); } if (/pop/i.test(settings.tipAnimation)) { $('.joyride-modal-bg').show(); } else { $('.joyride-modal-bg').fadeIn(settings.tipAnimationFadeSpeed); } }, center : function () { var $w = settings.$window; settings.$next_tip.css({ top : ((($w.height() - settings.$next_tip.outerHeight()) / 2) + $w.scrollTop()), left : ((($w.width() - settings.$next_tip.outerWidth()) / 2) + $w.scrollLeft()) }); return true; }, bottom : function () { return /bottom/i.test(settings.tipSettings.tipLocation); }, top : function () { return /top/i.test(settings.tipSettings.tipLocation); }, right : function () { return /right/i.test(settings.tipSettings.tipLocation); }, left : function () { return /left/i.test(settings.tipSettings.tipLocation); }, corners : function (el) { var w = settings.$window, right = w.width() + w.scrollLeft(), bottom = w.width() + w.scrollTop(); return [ el.offset().top <= w.scrollTop(), right <= el.offset().left + el.outerWidth(), bottom <= el.offset().top + el.outerHeight(), w.scrollLeft() >= el.offset().left ]; }, visible : function (hidden_corners) { var i = hidden_corners.length; while (i--) { if (hidden_corners[i]) return false; } return true; }, nub_position : function (nub, pos, def) { if (pos === 'auto') { nub.addClass(def); } else { nub.addClass(pos); } }, startTimer : function () { if (settings.$li.length) { settings.automate = setTimeout(function () { methods.hide(); methods.show(); methods.startTimer(); }, settings.timer); } else { clearTimeout(settings.automate); } }, end : function () { if (settings.cookieMonster) { $.cookie(settings.cookieName, 'ridden', { expires: 365, domain: settings.cookieDomain }); } if (settings.timer > 0) { clearTimeout(settings.automate); } $('.joyride-modal-bg').hide(); settings.$current_tip.hide(); settings.postStepCallback(settings.$li.index(), settings.$current_tip); settings.postRideCallback(settings.$li.index(), settings.$current_tip); }, jquery_check : function () { // define on() and off() for older jQuery if (!$.isFunction($.fn.on)) { $.fn.on = function (types, sel, fn) { return this.delegate(sel, types, fn); }; $.fn.off = function (types, sel, fn) { return this.undelegate(sel, types, fn); }; return false; } return true; }, outerHTML : function (el) { // support FireFox < 11 return el.outerHTML || new XMLSerializer().serializeToString(el); }, version : function () { return settings.version; } }; $.fn.joyride = function (method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.joyride'); } }; }(jQuery, this));
JavaScript
// jQuery.event.swipe // 0.5 // Stephen Band // Dependencies // jQuery.event.move 1.2 // One of swipeleft, swiperight, swipeup or swipedown is triggered on // moveend, when the move has covered a threshold ratio of the dimension // of the target node, or has gone really fast. Threshold and velocity // sensitivity changed with: // // jQuery.event.special.swipe.settings.threshold // jQuery.event.special.swipe.settings.sensitivity (function (module) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], module); } else { // Browser globals module(jQuery); } })(function(jQuery, undefined){ var add = jQuery.event.add, remove = jQuery.event.remove, // Just sugar, so we can have arguments in the same order as // add and remove. trigger = function(node, type, data) { jQuery.event.trigger(type, data, node); }, settings = { // Ratio of distance over target finger must travel to be // considered a swipe. threshold: 0.4, // Faster fingers can travel shorter distances to be considered // swipes. 'sensitivity' controls how much. Bigger is shorter. sensitivity: 6 }; function moveend(e) { var w, h, event; w = e.target.offsetWidth; h = e.target.offsetHeight; // Copy over some useful properties from the move event event = { distX: e.distX, distY: e.distY, velocityX: e.velocityX, velocityY: e.velocityY, finger: e.finger }; // Find out which of the four directions was swiped if (e.distX > e.distY) { if (e.distX > -e.distY) { if (e.distX/w > settings.threshold || e.velocityX * e.distX/w * settings.sensitivity > 1) { event.type = 'swiperight'; trigger(e.currentTarget, event); } } else { if (-e.distY/h > settings.threshold || e.velocityY * e.distY/w * settings.sensitivity > 1) { event.type = 'swipeup'; trigger(e.currentTarget, event); } } } else { if (e.distX > -e.distY) { if (e.distY/h > settings.threshold || e.velocityY * e.distY/w * settings.sensitivity > 1) { event.type = 'swipedown'; trigger(e.currentTarget, event); } } else { if (-e.distX/w > settings.threshold || e.velocityX * e.distX/w * settings.sensitivity > 1) { event.type = 'swipeleft'; trigger(e.currentTarget, event); } } } } function getData(node) { var data = jQuery.data(node, 'event_swipe'); if (!data) { data = { count: 0 }; jQuery.data(node, 'event_swipe', data); } return data; } jQuery.event.special.swipe = jQuery.event.special.swipeleft = jQuery.event.special.swiperight = jQuery.event.special.swipeup = jQuery.event.special.swipedown = { setup: function( data, namespaces, eventHandle ) { var data = getData(this); // If another swipe event is already setup, don't setup again. if (data.count++ > 0) { return; } add(this, 'moveend', moveend); return true; }, teardown: function() { var data = getData(this); // If another swipe event is still setup, don't teardown. if (--data.count > 0) { return; } remove(this, 'moveend', moveend); return true; }, settings: settings }; });
JavaScript
// jquery.event.move // // 1.3.1 // // Stephen Band // // Triggers 'movestart', 'move' and 'moveend' events after // mousemoves following a mousedown cross a distance threshold, // similar to the native 'dragstart', 'drag' and 'dragend' events. // Move events are throttled to animation frames. Move event objects // have the properties: // // pageX: // pageY: Page coordinates of pointer. // startX: // startY: Page coordinates of pointer at movestart. // distX: // distY: Distance the pointer has moved since movestart. // deltaX: // deltaY: Distance the finger has moved since last event. // velocityX: // velocityY: Average velocity over last few events. (function (module) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(['jquery'], module); } else { // Browser globals module(jQuery); } })(function(jQuery, undefined){ var // Number of pixels a pressed pointer travels before movestart // event is fired. threshold = 6, add = jQuery.event.add, remove = jQuery.event.remove, // Just sugar, so we can have arguments in the same order as // add and remove. trigger = function(node, type, data) { jQuery.event.trigger(type, data, node); }, // Shim for requestAnimationFrame, falling back to timer. See: // see http://paulirish.com/2011/requestanimationframe-for-smart-animating/ requestFrame = (function(){ return ( window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(fn, element){ return window.setTimeout(function(){ fn(); }, 25); } ); })(), ignoreTags = { textarea: true, input: true, select: true, button: true }, mouseevents = { move: 'mousemove', cancel: 'mouseup dragstart', end: 'mouseup' }, touchevents = { move: 'touchmove', cancel: 'touchend', end: 'touchend' }; // Constructors function Timer(fn){ var callback = fn, active = false, running = false; function trigger(time) { if (active){ callback(); requestFrame(trigger); running = true; active = false; } else { running = false; } } this.kick = function(fn) { active = true; if (!running) { trigger(); } }; this.end = function(fn) { var cb = callback; if (!fn) { return; } // If the timer is not running, simply call the end callback. if (!running) { fn(); } // If the timer is running, and has been kicked lately, then // queue up the current callback and the end callback, otherwise // just the end callback. else { callback = active ? function(){ cb(); fn(); } : fn ; active = true; } }; } // Functions function returnTrue() { return true; } function returnFalse() { return false; } function preventDefault(e) { e.preventDefault(); } function preventIgnoreTags(e) { // Don't prevent interaction with form elements. if (ignoreTags[ e.target.tagName.toLowerCase() ]) { return; } e.preventDefault(); } function isLeftButton(e) { // Ignore mousedowns on any button other than the left (or primary) // mouse button, or when a modifier key is pressed. return (e.which === 1 && !e.ctrlKey && !e.altKey); } function identifiedTouch(touchList, id) { var i, l; if (touchList.identifiedTouch) { return touchList.identifiedTouch(id); } // touchList.identifiedTouch() does not exist in // webkit yet… we must do the search ourselves... i = -1; l = touchList.length; while (++i < l) { if (touchList[i].identifier === id) { return touchList[i]; } } } function changedTouch(e, event) { var touch = identifiedTouch(e.changedTouches, event.identifier); // This isn't the touch you're looking for. if (!touch) { return; } // Chrome Android (at least) includes touches that have not // changed in e.changedTouches. That's a bit annoying. Check // that this touch has changed. if (touch.pageX === event.pageX && touch.pageY === event.pageY) { return; } return touch; } // Handlers that decide when the first movestart is triggered function mousedown(e){ var data; if (!isLeftButton(e)) { return; } data = { target: e.target, startX: e.pageX, startY: e.pageY, timeStamp: e.timeStamp }; add(document, mouseevents.move, mousemove, data); add(document, mouseevents.cancel, mouseend, data); } function mousemove(e){ var data = e.data; checkThreshold(e, data, e, removeMouse); } function mouseend(e) { removeMouse(); } function removeMouse() { remove(document, mouseevents.move, mousemove); remove(document, mouseevents.cancel, removeMouse); } function touchstart(e) { var touch, template; // Don't get in the way of interaction with form elements. if (ignoreTags[ e.target.tagName.toLowerCase() ]) { return; } touch = e.changedTouches[0]; // iOS live updates the touch objects whereas Android gives us copies. // That means we can't trust the touchstart object to stay the same, // so we must copy the data. This object acts as a template for // movestart, move and moveend event objects. template = { target: touch.target, startX: touch.pageX, startY: touch.pageY, timeStamp: e.timeStamp, identifier: touch.identifier }; // Use the touch identifier as a namespace, so that we can later // remove handlers pertaining only to this touch. add(document, touchevents.move + '.' + touch.identifier, touchmove, template); add(document, touchevents.cancel + '.' + touch.identifier, touchend, template); } function touchmove(e){ var data = e.data, touch = changedTouch(e, data); if (!touch) { return; } checkThreshold(e, data, touch, removeTouch); } function touchend(e) { var template = e.data, touch = identifiedTouch(e.changedTouches, template.identifier); if (!touch) { return; } removeTouch(template.identifier); } function removeTouch(identifier) { remove(document, '.' + identifier, touchmove); remove(document, '.' + identifier, touchend); } // Logic for deciding when to trigger a movestart. function checkThreshold(e, template, touch, fn) { var distX = touch.pageX - template.startX, distY = touch.pageY - template.startY; // Do nothing if the threshold has not been crossed. if ((distX * distX) + (distY * distY) < (threshold * threshold)) { return; } triggerStart(e, template, touch, distX, distY, fn); } function handled() { // this._handled should return false once, and after return true. this._handled = returnTrue; return false; } function flagAsHandled(e) { e._handled(); } function triggerStart(e, template, touch, distX, distY, fn) { var node = template.target, touches, time; touches = e.targetTouches; time = e.timeStamp - template.timeStamp; // Create a movestart object with some special properties that // are passed only to the movestart handlers. template.type = 'movestart'; template.distX = distX; template.distY = distY; template.deltaX = distX; template.deltaY = distY; template.pageX = touch.pageX; template.pageY = touch.pageY; template.velocityX = distX / time; template.velocityY = distY / time; template.targetTouches = touches; template.finger = touches ? touches.length : 1 ; // The _handled method is fired to tell the default movestart // handler that one of the move events is bound. template._handled = handled; // Pass the touchmove event so it can be prevented if or when // movestart is handled. template._preventTouchmoveDefault = function() { e.preventDefault(); }; // Trigger the movestart event. trigger(template.target, template); // Unbind handlers that tracked the touch or mouse up till now. fn(template.identifier); } // Handlers that control what happens following a movestart function activeMousemove(e) { var event = e.data.event, timer = e.data.timer; updateEvent(event, e, e.timeStamp, timer); } function activeMouseend(e) { var event = e.data.event, timer = e.data.timer; removeActiveMouse(); endEvent(event, timer, function() { // Unbind the click suppressor, waiting until after mouseup // has been handled. setTimeout(function(){ remove(event.target, 'click', returnFalse); }, 0); }); } function removeActiveMouse(event) { remove(document, mouseevents.move, activeMousemove); remove(document, mouseevents.end, activeMouseend); } function activeTouchmove(e) { var event = e.data.event, timer = e.data.timer, touch = changedTouch(e, event); if (!touch) { return; } // Stop the interface from gesturing e.preventDefault(); event.targetTouches = e.targetTouches; updateEvent(event, touch, e.timeStamp, timer); } function activeTouchend(e) { var event = e.data.event, timer = e.data.timer, touch = identifiedTouch(e.changedTouches, event.identifier); // This isn't the touch you're looking for. if (!touch) { return; } removeActiveTouch(event); endEvent(event, timer); } function removeActiveTouch(event) { remove(document, '.' + event.identifier, activeTouchmove); remove(document, '.' + event.identifier, activeTouchend); } // Logic for triggering move and moveend events function updateEvent(event, touch, timeStamp, timer) { var time = timeStamp - event.timeStamp; event.type = 'move'; event.distX = touch.pageX - event.startX; event.distY = touch.pageY - event.startY; event.deltaX = touch.pageX - event.pageX; event.deltaY = touch.pageY - event.pageY; // Average the velocity of the last few events using a decay // curve to even out spurious jumps in values. event.velocityX = 0.3 * event.velocityX + 0.7 * event.deltaX / time; event.velocityY = 0.3 * event.velocityY + 0.7 * event.deltaY / time; event.pageX = touch.pageX; event.pageY = touch.pageY; timer.kick(); } function endEvent(event, timer, fn) { timer.end(function(){ event.type = 'moveend'; trigger(event.target, event); return fn && fn(); }); } // jQuery special event definition function setup(data, namespaces, eventHandle) { // Stop the node from being dragged //add(this, 'dragstart.move drag.move', preventDefault); // Prevent text selection and touch interface scrolling //add(this, 'mousedown.move', preventIgnoreTags); // Tell movestart default handler that we've handled this add(this, 'movestart.move', flagAsHandled); // Don't bind to the DOM. For speed. return true; } function teardown(namespaces) { remove(this, 'dragstart drag', preventDefault); remove(this, 'mousedown touchstart', preventIgnoreTags); remove(this, 'movestart', flagAsHandled); // Don't bind to the DOM. For speed. return true; } function addMethod(handleObj) { // We're not interested in preventing defaults for handlers that // come from internal move or moveend bindings if (handleObj.namespace === "move" || handleObj.namespace === "moveend") { return; } // Stop the node from being dragged add(this, 'dragstart.' + handleObj.guid + ' drag.' + handleObj.guid, preventDefault, undefined, handleObj.selector); // Prevent text selection and touch interface scrolling add(this, 'mousedown.' + handleObj.guid, preventIgnoreTags, undefined, handleObj.selector); } function removeMethod(handleObj) { if (handleObj.namespace === "move" || handleObj.namespace === "moveend") { return; } remove(this, 'dragstart.' + handleObj.guid + ' drag.' + handleObj.guid); remove(this, 'mousedown.' + handleObj.guid); } jQuery.event.special.movestart = { setup: setup, teardown: teardown, add: addMethod, remove: removeMethod, _default: function(e) { var template, data; // If no move events were bound to any ancestors of this // target, high tail it out of here. if (!e._handled()) { return; } template = { target: e.target, startX: e.startX, startY: e.startY, pageX: e.pageX, pageY: e.pageY, distX: e.distX, distY: e.distY, deltaX: e.deltaX, deltaY: e.deltaY, velocityX: e.velocityX, velocityY: e.velocityY, timeStamp: e.timeStamp, identifier: e.identifier, targetTouches: e.targetTouches, finger: e.finger }; data = { event: template, timer: new Timer(function(time){ trigger(e.target, template); }) }; if (e.identifier === undefined) { // We're dealing with a mouse // Stop clicks from propagating during a move add(e.target, 'click', returnFalse); add(document, mouseevents.move, activeMousemove, data); add(document, mouseevents.end, activeMouseend, data); } else { // We're dealing with a touch. Stop touchmove doing // anything defaulty. e._preventTouchmoveDefault(); add(document, touchevents.move + '.' + e.identifier, activeTouchmove, data); add(document, touchevents.end + '.' + e.identifier, activeTouchend, data); } } }; jQuery.event.special.move = { setup: function() { // Bind a noop to movestart. Why? It's the movestart // setup that decides whether other move events are fired. add(this, 'movestart.move', jQuery.noop); }, teardown: function() { remove(this, 'movestart.move', jQuery.noop); } }; jQuery.event.special.moveend = { setup: function() { // Bind a noop to movestart. Why? It's the movestart // setup that decides whether other move events are fired. add(this, 'movestart.moveend', jQuery.noop); }, teardown: function() { remove(this, 'movestart.moveend', jQuery.noop); } }; add(document, 'mousedown.move', mousedown); add(document, 'touchstart.move', touchstart); // Make jQuery copy touch event properties over to the jQuery event // object, if they are not already listed. But only do the ones we // really need. IE7/8 do not have Array#indexOf(), but nor do they // have touch events, so let's assume we can ignore them. if (typeof Array.prototype.indexOf === 'function') { (function(jQuery, undefined){ var props = ["changedTouches", "targetTouches"], l = props.length; while (l--) { if (jQuery.event.props.indexOf(props[l]) === -1) { jQuery.event.props.push(props[l]); } } })(jQuery); }; });
JavaScript
/*! * jQuery Cookie Plugin v1.3 * https://github.com/carhartl/jquery-cookie * * Copyright 2011, Klaus Hartl * Dual licensed under the MIT or GPL Version 2 licenses. * http://www.opensource.org/licenses/mit-license.php * http://www.opensource.org/licenses/GPL-2.0 */ (function ($, document, undefined) { var pluses = /\+/g; function raw(s) { return s; } function decoded(s) { return decodeURIComponent(s.replace(pluses, ' ')); } var config = $.cookie = function (key, value, options) { // write if (value !== undefined) { options = $.extend({}, config.defaults, options); if (value === null) { options.expires = -1; } if (typeof options.expires === 'number') { var days = options.expires, t = options.expires = new Date(); t.setDate(t.getDate() + days); } value = config.json ? JSON.stringify(value) : String(value); return (document.cookie = [ encodeURIComponent(key), '=', config.raw ? value : encodeURIComponent(value), options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE options.path ? '; path=' + options.path : '', options.domain ? '; domain=' + options.domain : '', options.secure ? '; secure' : '' ].join('')); } // read var decode = config.raw ? raw : decoded; var cookies = document.cookie.split('; '); for (var i = 0, l = cookies.length; i < l; i++) { var parts = cookies[i].split('='); if (decode(parts.shift()) === key) { var cookie = decode(parts.join('=')); return config.json ? JSON.parse(cookie) : cookie; } } return null; }; config.defaults = {}; $.removeCookie = function (key, options) { if ($.cookie(key) !== null) { $.cookie(key, null, options); return true; } return false; }; })(jQuery, document);
JavaScript
/* * jQuery Custom Forms Plugin 1.0 * www.ZURB.com * Copyright 2010, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ (function( $ ){ /** * Helper object used to quickly adjust all hidden parent element's, display and visibility properties. * This is currently used for the custom drop downs. When the dropdowns are contained within a reveal modal * we cannot accurately determine the list-item elements width property, since the modal's display property is set * to 'none'. * * This object will help us work around that problem. * * NOTE: This could also be plugin. * * @function hiddenFix */ var hiddenFix = function() { return { /** * Sets all hidden parent elements and self to visibile. * * @method adjust * @param {jQuery Object} $child */ // We'll use this to temporarily store style properties. tmp : [], // We'll use this to set hidden parent elements. hidden : null, adjust : function( $child ) { // Internal reference. var _self = this; // Set all hidden parent elements, including this element. _self.hidden = $child.parents().andSelf().filter( ":hidden" ); // Loop through all hidden elements. _self.hidden.each( function() { // Cache the element. var $elem = $( this ); // Store the style attribute. // Undefined if element doesn't have a style attribute. _self.tmp.push( $elem.attr( 'style' ) ); // Set the element's display property to block, // but ensure it's visibility is hidden. $elem.css( { 'visibility' : 'hidden', 'display' : 'block' } ); }); }, // end adjust /** * Resets the elements previous state. * * @method reset */ reset : function() { // Internal reference. var _self = this; // Loop through our hidden element collection. _self.hidden.each( function( i ) { // Cache this element. var $elem = $( this ), _tmp = _self.tmp[ i ]; // Get the stored 'style' value for this element. // If the stored value is undefined. if( _tmp === undefined ) // Remove the style attribute. $elem.removeAttr( 'style' ); else // Otherwise, reset the element style attribute. $elem.attr( 'style', _tmp ); }); // Reset the tmp array. _self.tmp = []; // Reset the hidden elements variable. _self.hidden = null; } // end reset }; // end return }; jQuery.foundation = jQuery.foundation || {}; jQuery.foundation.customForms = jQuery.foundation.customForms || {}; $.foundation.customForms.appendCustomMarkup = function ( options ) { var defaults = { disable_class: "js-disable-custom" }; options = $.extend( defaults, options ); function appendCustomMarkup(idx, sel) { var $this = $(sel).hide(), type = $this.attr('type'), $span = $this.next('span.custom.' + type); if ($span.length === 0) { $span = $('<span class="custom ' + type + '"></span>').insertAfter($this); } $span.toggleClass('checked', $this.is(':checked')); $span.toggleClass('disabled', $this.is(':disabled')); } function appendCustomSelect(idx, sel) { var hiddenFixObj = hiddenFix(); // // jQueryify the <select> element and cache it. // var $this = $( sel ), // // Find the custom drop down element. // $customSelect = $this.next( 'div.custom.dropdown' ), // // Find the custom select element within the custom drop down. // $customList = $customSelect.find( 'ul' ), // // Find the custom a.current element. // $selectCurrent = $customSelect.find( ".current" ), // // Find the custom a.selector element (the drop-down icon). // $selector = $customSelect.find( ".selector" ), // // Get the <options> from the <select> element. // $options = $this.find( 'option' ), // // Filter down the selected options // $selectedOption = $options.filter( ':selected' ), // // Initial max width. // maxWidth = 0, // // We'll use this variable to create the <li> elements for our custom select. // liHtml = '', // // We'll use this to cache the created <li> elements within our custom select. // $listItems ; var $currentSelect = false; // // Should we not create a custom list? // if ( $this.hasClass( 'no-custom' ) ) return; // // Did we not create a custom select element yet? // if ( $customSelect.length === 0 ) { // // Let's create our custom select element! // // // Determine what select size to use. // var customSelectSize = $this.hasClass( 'small' ) ? 'small' : $this.hasClass( 'medium' ) ? 'medium' : $this.hasClass( 'large' ) ? 'large' : $this.hasClass( 'expand' ) ? 'expand' : '' ; // // Build our custom list. // $customSelect = $('<div class="' + ['custom', 'dropdown', customSelectSize ].join( ' ' ) + '"><a href="#" class="selector"></a><ul /></div>"'); // // Grab the selector element // $selector = $customSelect.find( ".selector" ); // // Grab the unordered list element from the custom list. // $customList = $customSelect.find( "ul" ); // // Build our <li> elements. // liHtml = $options.map( function() { return "<li>" + $( this ).html() + "</li>"; } ).get().join( '' ); // // Append our <li> elements to the custom list (<ul>). // $customList.append( liHtml ); // // Insert the the currently selected list item before all other elements. // Then, find the element and assign it to $currentSelect. // $currentSelect = $customSelect.prepend( '<a href="#" class="current">' + $selectedOption.html() + '</a>' ).find( ".current" ); // // Add the custom select element after the <select> element. // $this.after( $customSelect ) // //then hide the <select> element. // .hide(); } else { // // Create our list item <li> elements. // liHtml = $options.map( function() { return "<li>" + $( this ).html() + "</li>"; } ).get().join( '' ); // // Refresh the ul with options from the select in case the supplied markup doesn't match. // Clear what's currently in the <ul> element. // $customList.html( '' ) // // Populate the list item <li> elements. // .append( liHtml ); } // endif $customSelect.length === 0 // // Determine whether or not the custom select element should be disabled. // $customSelect.toggleClass( 'disabled', $this.is( ':disabled' ) ); // // Cache our List item elements. // $listItems = $customList.find( 'li' ); // // Determine which elements to select in our custom list. // $options.each( function ( index ) { if ( this.selected ) { // // Add the selected class to the current li element // $listItems.eq( index ).addClass( 'selected' ); // // Update the current element with the option value. // if ($currentSelect) { $currentSelect.html( $( this ).html() ); } } }); // // Update the custom <ul> list width property. // $customList.css( 'width', 'inherit' ); // // Set the custom select width property. // $customSelect.css( 'width', 'inherit' ); // // If we're not specifying a predetermined form size. // if ( !$customSelect.is( '.small, .medium, .large, .expand' ) ) { // ------------------------------------------------------------------------------------ // This is a work-around for when elements are contained within hidden parents. // For example, when custom-form elements are inside of a hidden reveal modal. // // We need to display the current custom list element as well as hidden parent elements // in order to properly calculate the list item element's width property. // ------------------------------------------------------------------------------------- // // Show the drop down. // This should ensure that the list item's width values are properly calculated. // $customSelect.addClass( 'open' ); // // Quickly, display all parent elements. // This should help us calcualate the width of the list item's within the drop down. // hiddenFixObj.adjust( $customList ); // // Grab the largest list item width. // maxWidth = ( $listItems.outerWidth() > maxWidth ) ? $listItems.outerWidth() : maxWidth; // // Okay, now reset the parent elements. // This will hide them again. // hiddenFixObj.reset(); // // Finally, hide the drop down. // $customSelect.removeClass( 'open' ); // // Set the custom list width. // $customSelect.width( maxWidth + 18); // // Set the custom list element (<ul />) width. // $customList.width( maxWidth + 16 ); } // endif } $('form.custom input:radio[data-customforms!=disabled]').each(appendCustomMarkup); $('form.custom input:checkbox[data-customforms!=disabled]').each(appendCustomMarkup); $('form.custom select[data-customforms!=disabled]').each(appendCustomSelect); }; var refreshCustomSelect = function($select) { var maxWidth = 0, $customSelect = $select.next(); $options = $select.find('option'); $customSelect.find('ul').html(''); $options.each(function () { $li = $('<li>' + $(this).html() + '</li>'); $customSelect.find('ul').append($li); }); // re-populate $options.each(function (index) { if (this.selected) { $customSelect.find('li').eq(index).addClass('selected'); $customSelect.find('.current').html($(this).html()); } }); // fix width $customSelect.removeAttr('style') .find('ul').removeAttr('style'); $customSelect.find('li').each(function () { $customSelect.addClass('open'); if ($(this).outerWidth() > maxWidth) { maxWidth = $(this).outerWidth(); } $customSelect.removeClass('open'); }); $customSelect.css('width', maxWidth + 18 + 'px'); $customSelect.find('ul').css('width', maxWidth + 16 + 'px'); }; var toggleCheckbox = function($element) { var $input = $element.prev(), input = $input[0]; if (false === $input.is(':disabled')) { input.checked = ((input.checked) ? false : true); $element.toggleClass('checked'); $input.trigger('change'); } }; var toggleRadio = function($element) { var $input = $element.prev(), $form = $input.closest('form.custom'), input = $input[0]; if (false === $input.is(':disabled')) { $form.find('input:radio[name="' + $input.attr('name') + '"]').next().not($element).removeClass('checked'); if ( !$element.hasClass('checked') ) { $element.toggleClass('checked'); } input.checked = $element.hasClass('checked'); $input.trigger('change'); } }; $(document).on('click', 'form.custom span.custom.checkbox', function (event) { event.preventDefault(); event.stopPropagation(); toggleCheckbox($(this)); }); $(document).on('click', 'form.custom span.custom.radio', function (event) { event.preventDefault(); event.stopPropagation(); toggleRadio($(this)); }); $(document).on('change', 'form.custom select[data-customforms!=disabled]', function (event) { refreshCustomSelect($(this)); }); $(document).on('click', 'form.custom label', function (event) { var $associatedElement = $('#' + $(this).attr('for') + '[data-customforms!=disabled]'), $customCheckbox, $customRadio; if ($associatedElement.length !== 0) { if ($associatedElement.attr('type') === 'checkbox') { event.preventDefault(); $customCheckbox = $(this).find('span.custom.checkbox'); toggleCheckbox($customCheckbox); } else if ($associatedElement.attr('type') === 'radio') { event.preventDefault(); $customRadio = $(this).find('span.custom.radio'); toggleRadio($customRadio); } } }); $(document).on('click', 'form.custom div.custom.dropdown a.current, form.custom div.custom.dropdown a.selector', function (event) { var $this = $(this), $dropdown = $this.closest('div.custom.dropdown'), $select = $dropdown.prev(); event.preventDefault(); $('div.dropdown').removeClass('open'); if (false === $select.is(':disabled')) { $dropdown.toggleClass('open'); if ($dropdown.hasClass('open')) { $(document).bind('click.customdropdown', function (event) { $dropdown.removeClass('open'); $(document).unbind('.customdropdown'); }); } else { $(document).unbind('.customdropdown'); } return false; } }); $(document).on('click', 'form.custom div.custom.dropdown li', function (event) { var $this = $(this), $customDropdown = $this.closest('div.custom.dropdown'), $select = $customDropdown.prev(), selectedIndex = 0; event.preventDefault(); event.stopPropagation(); $('div.dropdown').removeClass('open'); $this .closest('ul') .find('li') .removeClass('selected'); $this.addClass('selected'); $customDropdown .removeClass('open') .find('a.current') .html($this.html()); $this.closest('ul').find('li').each(function (index) { if ($this[0] == this) { selectedIndex = index; } }); $select[0].selectedIndex = selectedIndex; $select.trigger('change'); }); $.fn.foundationCustomForms = $.foundation.customForms.appendCustomMarkup; })( jQuery );
JavaScript
;(function ($, window, undefined) { 'use strict'; $.fn.foundationButtons = function (options) { var $doc = $(document), config = $.extend({ dropdownAsToggle:true, activeClass:'active' }, options), // close all dropdowns except for the dropdown passed closeDropdowns = function (dropdown) { $('.button.dropdown').find('ul').not(dropdown).removeClass('show-dropdown'); }, // reset all toggle states except for the button passed resetToggles = function (button) { var buttons = $('.button.dropdown').not(button); buttons.add($('> span.' + config.activeClass, buttons)).removeClass(config.activeClass); }; // Prevent event propagation on disabled buttons $doc.on('click.fndtn', '.button.disabled', function (e) { e.preventDefault(); }); $('.button.dropdown > ul', this).addClass('no-hover'); // reset other active states $doc.on('click.fndtn', '.button.dropdown:not(.split), .button.dropdown.split span', function (e) { var $el = $(this), button = $el.closest('.button.dropdown'), dropdown = $('> ul', button); // If the click is registered on an actual link then do not preventDefault which stops the browser from following the link if (e.target.nodeName !== "A"){ e.preventDefault(); } // close other dropdowns closeDropdowns(config.dropdownAsToggle ? dropdown : ''); dropdown.toggleClass('show-dropdown'); if (config.dropdownAsToggle) { resetToggles(button); $el.toggleClass(config.activeClass); } }); // close all dropdowns and deactivate all buttons $doc.on('click.fndtn', 'body, html', function (e) { if (undefined == e.originalEvent) { return; } // check original target instead of stopping event propagation to play nice with other events if (!$(e.originalEvent.target).is('.button.dropdown:not(.split), .button.dropdown.split span')) { closeDropdowns(); if (config.dropdownAsToggle) { resetToggles(); } } }); // Positioning the Flyout List var normalButtonHeight = $('.button.dropdown:not(.large):not(.small):not(.tiny):visible', this).outerHeight() - 1, largeButtonHeight = $('.button.large.dropdown:visible', this).outerHeight() - 1, smallButtonHeight = $('.button.small.dropdown:visible', this).outerHeight() - 1, tinyButtonHeight = $('.button.tiny.dropdown:visible', this).outerHeight() - 1; $('.button.dropdown:not(.large):not(.small):not(.tiny) > ul', this).css('top', normalButtonHeight); $('.button.dropdown.large > ul', this).css('top', largeButtonHeight); $('.button.dropdown.small > ul', this).css('top', smallButtonHeight); $('.button.dropdown.tiny > ul', this).css('top', tinyButtonHeight); $('.button.dropdown.up:not(.large):not(.small):not(.tiny) > ul', this).css('top', 'auto').css('bottom', normalButtonHeight - 2); $('.button.dropdown.up.large > ul', this).css('top', 'auto').css('bottom', largeButtonHeight - 2); $('.button.dropdown.up.small > ul', this).css('top', 'auto').css('bottom', smallButtonHeight - 2); $('.button.dropdown.up.tiny > ul', this).css('top', 'auto').css('bottom', tinyButtonHeight - 2); }; })( jQuery, this );
JavaScript
;(function ($, window, undefined) { 'use strict'; $.fn.foundationNavigation = function (options) { var lockNavBar = false; // Windows Phone, sadly, does not register touch events :( if (Modernizr.touch || navigator.userAgent.match(/Windows Phone/i)) { $(document).on('click.fndtn touchstart.fndtn', '.nav-bar a.flyout-toggle', function (e) { e.preventDefault(); var flyout = $(this).siblings('.flyout').first(); if (lockNavBar === false) { $('.nav-bar .flyout').not(flyout).slideUp(500); flyout.slideToggle(500, function () { lockNavBar = false; }); } lockNavBar = true; }); $('.nav-bar>li.has-flyout', this).addClass('is-touch'); } else { $('.nav-bar>li.has-flyout', this).on('mouseenter mouseleave', function (e) { if (e.type == 'mouseenter') { $('.nav-bar').find('.flyout').hide(); $(this).children('.flyout').show(); } if (e.type == 'mouseleave') { var flyout = $(this).children('.flyout'), inputs = flyout.find('input'), hasFocus = function (inputs) { var focus; if (inputs.length > 0) { inputs.each(function () { if ($(this).is(":focus")) { focus = true; } }); return focus; } return false; }; if (!hasFocus(inputs)) { $(this).children('.flyout').hide(); } } }); } }; })( jQuery, this );
JavaScript
/** * Popup widget * * Usage: * $('#popup').popup({ trigger: '#button' }); * $('body').popup({ trigger: '#button', partial: 'partial:name' }); */ ;(function ($, window, document, undefined) { $.widget("utility.popup", { version: '1.2.1', options: { on_open: null, // Callback when popup opens on_close: null, // Callback when popup closes trigger: null, // Trigger to open extra_close: '.popup_close', // Trigger to close show_close: true, // Show the X to close close_on_bg_click: true, // If you click background close popup? move_to_element: false, // Move the popup to another element size: null, // Options: small, medium, large, xlarge, expand animation: 'fadeAndPop', // Options: fade, fadeAndPop, none animation_speed: 300, // Animate speed in milliseconds auto_reveal: false, // Show popup when page opens? partial: null, // Dynamically load a partial partial_data: null // Data to send along with the partial request }, // Internals _partial_container_id: null, _partial_name: null, _reveal_options: { }, _init: function () { if (this.element.is('body')) { var new_element = $('<div />').appendTo('body'); new_element.popup(this.options); return; } this._reveal_options = { animation: this.options.animation, animationspeed: this.options.animation_speed, closeOnBackgroundClick: this.options.close_on_bg_click, dismissModalClass: 'close-reveal-modal' }; this._partial_name = this.options.partial; this._build(); }, destroy: function () { $.Widget.prototype.destroy.call(this); }, _build: function() { var self = this; this.element.addClass('reveal-modal'); if (this.options.size) this.element.addClass(this.options.size); // Popup opening if (this.options.trigger) { var trigger = $(this.options.trigger); trigger.die('click').live('click', function() { self._handle_partial($(this)); self.open_popup($(this)); }); } // Popup closing this.element.find(this.options.extra_close).die('click').live('click', function() { self.element.trigger('reveal:close'); }); // Add close cross var close_cross = $('<a />').addClass('close-reveal-modal').html('&#215;'); close_cross.appendTo(this.element); // Move the popup to a more suitable position if (this.options.move_to_element) this.element.prependTo($(this.options.move_to_element)); // Auto reveal if (this.options.auto_reveal) { self._handle_partial($(this)); self.open_popup($(this)); } }, // Service methods // open_popup: function(triggered_by) { // Open event this.options.on_open && this.element.unbind('reveal:open').bind('reveal:open', this.options.on_open.apply(this, [triggered_by])); // Close event this.options.on_close && this.element.unbind('reveal:close').bind('reveal:close', this.options.on_close.apply(this, [triggered_by])); this.element.reveal(this._reveal_options); }, close_popup: function() { this.element.trigger('reveal:close'); }, // Partial Loading // _handle_partial: function(triggered_by) { var inline_partial = triggered_by.data('partial'); this._partial_name = (inline_partial) ? inline_partial : this.options.partial; if (this._partial_name) { this._partial_build_container(); var container_id = '#' + this._partial_container_id, update_object = { }; update_object[container_id] = this._partial_name; // Add ajax loader $(container_id).empty().append($('<div />').addClass('reveal-loading')); // Request partial content $('<form />').sendRequest('core:on_null', { update: update_object, extraFields: this.options.partial_data }); } }, _partial_build_container: function() { // Container ID not found if (!this._partial_container_id) { var random_number = (Math.floor((Math.random() * 100)) % 94) + 33; this._partial_container_id = 'reveal-content'+random_number; } // Container not found, create if ($('#'+this._partial_container_id).length == 0) $('<div />').addClass('partial-reveal-modal').attr('id', this._partial_container_id).appendTo(this.element); } }); })( jQuery, window, document );
JavaScript
/** * Star widget * * Usage: * <div class="rating-selector"> * <select name="rating"> * <option value="0">0</option> * <option value="1">1</option> * <option value="2">2</option> * <option value="3">3</option> * <option value="4">4</option> * <option value="5">5</option> * </select> * </div> * $('.rating-selector').stars({ * input_type: "select", * cancel_value: 0, * cancel_show: false * }); * */ ;(function ($, window, document, undefined) { $.widget('utility.star_rating', { options: { version: '1.0.0', input_type: 'select', // Input element used (select, radio) split: 0, // Decrease number of stars by splitting each star into pieces [2|3|4|...] disabled: false, // Set to [true] to make the stars initially disabled cancel_title: 'Cancel Rating', // Cancel title value cancel_value: 0, // Default value of Cancel button cancel_show: false, // Show cancel disabled_value: false, // Set to [false] to not disable the hidden input when Cancel btn is clicked, so the value will present in POST data. default_value: false, // Default value one_vote_only: false, // Allow one vote only show_titles: false, // Show titles el_caption: null, // jQuery object - target for text captions callback: null, // function(ui, type, value, event) force_select: null, // CSS Classes star_width: 16, // width of the star image container_class: 'star-rating', cancel_class: 'cancel', star_off_class: 'star', star_on_class: 'star-on', star_hover_class: 'star-hover', star_disabled_class: 'star-disabled', cancel_hover_class: 'cancel-hover', cancel_disabled_class: 'cancel-disabled' }, // Internals _form: null, _select: null, _rboxes: null, _cancel: null, _stars: null, _value: null, _create: function() { var self = this; var o = this.options; var star_id = 0; this.element .data('former.stars', this.element.html()) .addClass(o.container_class); o.isSelect = o.input_type == 'select'; this._form = $(this.element).closest('form'); this._select = o.isSelect ? $('select', this.element) : null; this._rboxes = o.isSelect ? $('option', this._select) : $(':radio', this.element); // Map all inputs from rboxes array to Stars elements this._stars = this._rboxes.map(function(i) { var el = { value: this.value, title: (o.isSelect ? this.text : this.title) || this.value, is_default: (o.isSelect && this.defaultSelected) || this.defaultChecked }; if (i==0) { o.split = typeof o.split != 'number' ? 0 : o.split; o.val2id = []; o.id2val = []; o.id2title = []; o.name = o.isSelect ? self._select.get(0).name : this.name; o.disabled = o.disabled || (o.isSelect ? $(self._select).attr('disabled') : $(this).attr('disabled')); } // Consider it as a Cancel button? if (el.value == o.cancel_value) { o.cancel_title = el.title; return null; } o.val2id[el.value] = star_id; o.id2val[star_id] = el.value; o.id2title[star_id] = el.title; if (el.is_default) { o.checked = star_id; o.value = o.default_value = el.value; o.title = el.title; } var $s = $('<div/>').addClass(o.star_off_class); var $a = $('<a/>').attr('title', o.show_titles ? el.title : '').text(el.value); // Prepare division settings if (o.split) { var oddeven = (star_id % o.split); var stwidth = Math.floor(o.star_width / o.split); $s.width(stwidth); $a.css('margin-left', '-' + (oddeven * stwidth) + 'px'); } star_id++; return $s.append($a).get(0); }); // How many Stars? o.items = star_id; // Remove old content o.isSelect ? this._select.remove() : this._rboxes.remove(); // Append Stars interface this._cancel = $('<div/>').addClass(o.cancel_class).append( $('<a/>').attr('title', o.show_titles ? o.cancel_title : '').text(o.cancel_value) ); o.cancel_show &= !o.disabled && !o.one_vote_only; o.cancel_show && this.element.append(this._cancel); this.element.append(this._stars); // Initial selection if (o.checked === undefined) { o.checked = -1; o.value = o.default_value = o.cancel_value; o.title = ''; } // The only FORM element, that has been linked to the stars control. The value field is updated on each Star click event this._value = $('<input type="hidden" name="'+o.name+'" value="'+o.value+'" />'); this.element.append(this._value); // Attach stars event handler this._stars.bind('click.stars', function(e) { if (!o.force_select && o.disabled) return false; var i = self._stars.index(this); o.checked = i; o.value = o.id2val[i]; o.title = o.id2title[i]; self._value.attr({disabled: o.disabled ? 'disabled' : false, value: o.value}); fill_to(i, false); self._disable_cancel(); !o.force_select && self.callback(e, 'star'); }) .bind('mouseover.stars', function() { if (o.disabled) return false; var i = self._stars.index(this); fill_to(i, true); }) .bind('mouseout.stars', function() { if (o.disabled) return false; fill_to(self.options.checked, false); }); // Attach cancel event handler this._cancel.bind('click.stars', function(e) { if (!o.force_select && (o.disabled || o.value == o.cancel_value)) return false; o.checked = -1; o.value = o.cancel_value; o.title = ''; self._value.val(o.value); o.disabled_value && self._value.attr({disabled: 'disabled'}); fill_none(); self._disable_cancel(); !o.force_select && self.callback(e, 'cancel'); }) .bind('mouseover.stars', function() { if (self._disable_cancel()) return false; self._cancel.addClass(o.cancel_hover_class); fill_none(); self._showCap(o.cancel_title); }) .bind('mouseout.stars', function() { if (self._disable_cancel()) return false; self._cancel.removeClass(o.cancel_hover_class); self._stars.triggerHandler('mouseout.stars'); }); // Attach onReset event handler to the parent FORM this._form.bind('reset.stars', function(){ !o.disabled && self.select(o.default_value); }); // Star selection helpers function fill_to(index, hover) { if (index != -1) { var addClass = hover ? o.star_hover_class : o.star_on_class; var remClass = hover ? o.star_on_class : o.star_hover_class; self._stars.eq(index).prevAll('.' + o.star_off_class).andSelf().removeClass(remClass).addClass(addClass); self._stars.eq(index).nextAll('.' + o.star_off_class).removeClass(o.star_hover_class + ' ' + o.star_on_class); self._showCap(o.id2title[index]); } else fill_none(); }; function fill_none() { self._stars.removeClass(o.star_on_class + ' ' + o.star_hover_class); self._showCap(''); }; // Finally, set up the Stars this.select(o.value); o.disabled && this.disable(); }, // Private functions _disable_cancel: function() { var o = this.options, disabled = o.disabled || o.one_vote_only || (o.value == o.cancel_value); if (disabled) this._cancel.removeClass(o.cancel_hover_class).addClass(o.cancel_disabled_class); else this._cancel.removeClass(o.cancel_disabled_class); this._cancel.css('opacity', disabled ? 0.5 : 1); return disabled; }, _disable_all: function() { var o = this.options; this._disable_cancel(); if (o.disabled) this._stars.filter('div').addClass(o.star_disabled_class); else this._stars.filter('div').removeClass(o.star_disabled_class); }, _showCap: function(s) { var o = this.options; if (o.el_caption) o.el_caption.text(s); }, // Public functions value: function() { return this.options.value; }, select: function(val) { var o = this.options, e = (val == o.cancel_value) ? this._cancel : this._stars.eq(o.val2id[val]); o.force_select = true; e.triggerHandler('click.stars'); o.force_select = false; }, select_id: function(id) { var o = this.options, e = (id == -1) ? this._cancel : this._stars.eq(id); o.force_select = true; e.triggerHandler('click.stars'); o.force_select = false; }, enable: function() { this.options.disabled = false; this._disable_all(); }, disable: function() { this.options.disabled = true; this._disable_all(); }, destroy: function() { this._form.unbind('.stars'); this._cancel.unbind('.stars').remove(); this._stars.unbind('.stars').remove(); this._value.remove(); this.element.unbind('.stars').html(this.element.data('former.stars')).removeData('stars'); return this; }, callback: function(e, type) { var o = this.options; o.callback && o.callback(this, type, o.value, e); o.one_vote_only && !o.disabled && this.disable(); } }); })( jQuery, window, document );
JavaScript
;(function ($, window, document, undefined) { $.widget("utility.scrollbar", { version: '1.0', options: { axis: 'vertical', // Vertical or horizontal scrollbar? wheel: 40, // How many pixels to scroll at a time scroll: true, // Enable or disable the mousewheel lockscroll: true, // Return scrollwheel to browser if there is no more content size: 'auto', // Set the size of the scrollbar to auto or a fixed number sizethumb: 'auto', // Set the size of the thumb to auto or a fixed number invertscroll: false // Enable mobile invert style scrolling }, _viewport: null, _content: null, _scrollbar: null, _track: null, _thumb: null, _scroll_axis: null, _scroll_direction: null, _scroll_size: null, _scroll_obj: 0, _position_obj: { start: 0, now: 0 }, _mouse_obj: {}, _is_visible: false, _create: function () { var _this = this; this._build_elements(); this._scroll_axis = (this.options.axis === 'horizontal'); this._scroll_direction = this._scroll_axis ? 'left' : 'top'; this._scroll_size = this._scroll_axis ? 'Width' : 'Height'; this.update(); this._bind_events(); }, destroy: function () { $.Widget.prototype.destroy.call(this); }, update: function(scroll) { if (this._scroll_axis) { // Horizontal scroll this._content.obj.css({ height: (this.element.outerHeight() - 20) + "px" }); this._viewport.obj.css({ top: 20 + "px", width: this.element.outerWidth() + "px", height: (this.element.outerHeight() - 20) + "px" }); } else { // Vertical scroll this._content.obj.css({ width: this.element.outerWidth() + "px" }); this._viewport.obj.css({ width: this.element.outerWidth() + "px", height: this.element.outerHeight() + "px" }); } this._viewport[this.options.axis] = this._viewport.obj[0]['offset'+ this._scroll_size]; this._content[this.options.axis] = this._content.obj[0]['scroll'+ this._scroll_size]; this._content.ratio = this._viewport[this.options.axis] / this._content[this.options.axis]; this._scrollbar.obj.toggleClass('disable', this._content.ratio >= 1); this._track[this.options.axis] = this.options.size === 'auto' ? this._viewport[this.options.axis] : this.options.size; this._thumb[this.options.axis] = Math.min(this._track[this.options.axis], Math.max(0, (this.options.sizethumb === 'auto' ? (this._track[this.options.axis] * this._content.ratio) : this.options.sizethumb ) ) ); this._scrollbar.ratio = this.options.sizethumb === 'auto' ? (this._content[this.options.axis] / this._track[this.options.axis]) : (this._content[this.options.axis] - this._viewport[this.options.axis]) / (this._track[this.options.axis] - this._thumb[this.options.axis]); this._scroll_obj = (scroll === 'relative' && this._content.ratio <= 1) ? Math.min((this._content[this.options.axis] - this._viewport[this.options.axis]), Math.max(0, this._scroll_obj)) : 0; this._scroll_obj = (scroll === 'bottom' && this._content.ratio <= 1) ? (this._content[this.options.axis] - this._viewport[this.options.axis]) : isNaN( parseInt(scroll, 10)) ? this._scroll_obj : parseInt(scroll, 10); this.set_size(); }, set_size: function() { var css_size = this._scroll_size.toLowerCase(); this._thumb.obj.css(this._scroll_direction, this._scroll_obj / this._scrollbar.ratio); this._content.obj.css(this._scroll_direction, -this._scroll_obj ); this._mouse_obj.start = this._thumb.obj.offset()[this._scroll_direction]; this._scrollbar.obj.css(css_size, this._track[this.options.axis]); this._track.obj.css(css_size, this._track[this.options.axis]); this._thumb.obj.css(css_size, this._thumb[this.options.axis]); this._is_visible = (this._content.obj.height() > this._viewport.obj.height()); }, _build_elements: function() { var viewport = $('<div />').addClass('viewport'); var overview = $('<div />').addClass('overview'); var scrollbar = $('<div />').addClass('scrollbar'); var track = $('<div />').addClass('track').appendTo(scrollbar); var thumb = $('<div />').addClass('thumb').appendTo(track); var end = $('<div />').addClass('end').appendTo(thumb); this.element .addClass('scroll-bar') .addClass(this.options.axis) .wrapInner(overview) .wrapInner(viewport); this.element.css('position', 'relative').prepend(scrollbar); this._viewport = { obj: $('.viewport', this.element) }; this._content = { obj: $('.overview', this.element) }; this._scrollbar = { obj: scrollbar }; this._track = { obj: track }; this._thumb = { obj: thumb }; this._scrollbar.obj.hide(); }, _bind_events: function() { if (!Modernizr.touch) { this._thumb.obj.bind('mousedown', $.proxy(this._start_bar, this)); this._track.obj.bind('mouseup', $.proxy(this._drag_event, this)); } else { this._viewport.obj[0].ontouchstart = function(event) { if (1 === event.touches.length) { this._start_bar(event.touches[0]); event.stopPropagation(); } }; } if (this.options.scroll && window.addEventListener) { this.element.get(0).addEventListener('DOMMouseScroll', $.proxy(this._wheel_event, this), false); this.element.get(0).addEventListener('mousewheel', $.proxy(this._wheel_event, this), false); } else if (this.options.scroll) { this.element.get(0).onmousewheel = this._wheel_event; } this.element.hover( $.proxy(function(){ this._is_visible && this._scrollbar.obj.fadeIn('fast') }, this), $.proxy(function(){ this._scrollbar.obj.fadeOut('fast') }, this) ); }, _start_bar: function(event) { $('body').addClass('scroll-bar-noselect'); var _thumb_dir = parseInt(this._thumb.obj.css(this._scroll_direction), 10 ); this._mouse_obj.start = this._scroll_axis ? event.pageX : event.pageY; this._position_obj.start = _thumb_dir == 'auto' ? 0 : _thumb_dir; if (!Modernizr.touch) { $(document).bind('mousemove', $.proxy(this._drag_event, this)); $(document).bind('mouseup', $.proxy(this._stop_bar, this)); this._thumb.obj.bind('mouseup', $.proxy(this._stop_bar, this)); } else { document.ontouchmove = function(event) { event.preventDefault(); drag(event.touches[0]); }; document.ontouchend = this._stop_bar; } }, _stop_bar: function() { $('body').removeClass('scroll-bar-noselect'); $(document).unbind('mousemove', this._drag_event); $(document).unbind('mouseup', this._stop_bar); this._thumb.obj.unbind('mouseup', this._stop_bar); document.ontouchmove = document.ontouchend = null; }, _wheel_event: function(event) { if (this._content.ratio < 1) { var oEvent = event || window.event, iDelta = oEvent.wheelDelta ? oEvent.wheelDelta / 120 : -oEvent.detail / 3; this._scroll_obj -= iDelta * this.options.wheel; this._scroll_obj = Math.min( (this._content[this.options.axis] - this._viewport[this.options.axis]), Math.max(0, this._scroll_obj) ); this._thumb.obj.css(this._scroll_direction, this._scroll_obj / this._scrollbar.ratio); this._content.obj.css(this._scroll_direction, -this._scroll_obj); if (this.options.lockscroll || (this._scroll_obj !== (this._content[this.options.axis] - this._viewport[this.options.axis]) && this._scroll_obj !== 0) ) { oEvent = $.event.fix(oEvent); oEvent.preventDefault(); } } }, _drag_event: function(event) { if (this._content.ratio < 1) { if (this.options.invertscroll && Modernizr.touch) { this._position_obj.now = Math.min( (this._track[this.options.axis] - this._thumb[this.options.axis]), Math.max(0, (this._position_obj.start + (this._mouse_obj.start - (this._scroll_axis ? event.pageX : event.pageY))) ) ); } else { this._position_obj.now = Math.min( (this._track[this.options.axis] - this._thumb[this.options.axis]), Math.max(0, (this._position_obj.start + ((this._scroll_axis ? event.pageX : event.pageY) - this._mouse_obj.start)) ) ); } this._scroll_obj = this._position_obj.now * this._scrollbar.ratio; this._content.obj.css(this._scroll_direction, -this._scroll_obj); this._thumb.obj.css(this._scroll_direction, this._position_obj.now); } } }); })( jQuery, window, document );
JavaScript
(function($) { /** * Runs functions given in arguments in series, each functions passing their results to the next one. * Return jQuery Deferred object. * * @example * $.waterfall( * function() { return $.ajax({url : first_url}) }, * function() { return $.ajax({url : second_url}) }, * function() { return $.ajax({url : another_url}) } *).fail(function() { * console.log(arguments) *).done(function() { * console.log(arguments) *}) * * @example2 * event_chain = []; * event_chain.push(function() { var deferred = $.Deferred(); deferred.resolve(); return deferred; }); * $.waterfall.apply(this, event_chain).fail(function(){}).done(function(){}); * * @author Dmitry (dio) Levashov, dio@std42.ru * @return jQuery.Deferred */ $.waterfall = function() { var steps = [], dfrd = $.Deferred(), pointer = 0; $.each(arguments, function(i, a) { steps.push(function() { var args = [].slice.apply(arguments), d; if (typeof(a) == 'function') { if (!((d = a.apply(null, args)) && d.promise)) { d = $.Deferred()[d === false ? 'reject' : 'resolve'](d); } } else if (a && a.promise) { d = a; } else { d = $.Deferred()[a === false ? 'reject' : 'resolve'](a); } d.fail(function() { dfrd.reject.apply(dfrd, [].slice.apply(arguments)); }) .done(function(data) { pointer++; args.push(data); pointer == steps.length ? dfrd.resolve.apply(dfrd, args) : steps[pointer].apply(null, args); }); }); }); steps.length ? steps[0]() : dfrd.resolve(); return dfrd; } })(jQuery);
JavaScript
/** * Custom Forms Widget */ ;(function ($, window, document, undefined) { $.widget("utility.forms", { version: '1.0.0', options: { }, _create: function () { this.refresh(); }, refresh: function() { this.build_quantity_input(); }, // Quantity Control // build_quantity_input: function() { var _this = this; var inputs = $('input.input-quantity').not('.input-quantity-ready').addClass('input-quantity-ready'); inputs.each(function() { var element = $(this); var up_arrow = $('<a />') .addClass('arrow up') .append('<span>Up</span>') .attr('href', 'javascript:;'); var down_arrow = $('<a />') .addClass('arrow down') .append('<span>Down</span>') .attr('href', 'javascript:;'); element.wrap($('<span />').addClass('custom-input-quantity')) .after(down_arrow) .after(up_arrow); element.closest('span.custom-input-quantity') .find('.arrow') .click(_this._click_quantity_input); }); }, _click_quantity_input: function() { var element = $(this); var quantity = 1; var input_field = element .closest('span.custom-input-quantity') .find('input.input-quantity'); var value = parseInt(input_field.val()); if (isNaN(value)) value = 0; if (element.hasClass('up')) value++; else value--; input_field.val(Math.max(value,0)); input_field.trigger('change'); } }); })( jQuery, window, document );
JavaScript
;(function ($, window, undefined) { 'use strict'; var $doc = $(document), Modernizr = window.Modernizr; $(document).ready(function() { $.utility.statusbar && $doc.statusbar(); $.utility.forms && $doc.forms(); // Tweak to foundation's topbar.js $('.top-bar ul.dropdown a.link').click(function() { var dropdown = $(this).closest('.dropdown').hide(); setTimeout(function(){ dropdown.show(); }, 500); $('.top-bar .toggle-topbar > a').trigger('click'); }); }); })(jQuery, this);
JavaScript
// Toggle text between current and data-toggle-text contents $.fn.extend({ toggleText: function() { var self = $(this); var text = self.text(); var ttext = self.data('toggle-text'); var tclass = self.data('toggle-class'); self.text(ttext).data('toggle-text', text).toggleClass(tclass); } });
JavaScript
;(function ($, window, document, undefined) { $.widget("utility.gmap_locator", $.utility.gmap, { version: '1.0.4', options: { bubble_on_hover: true, autofit_markers: true, bubble_id_prefix: '#bubble_', container: '#browse_sidebar_content ul' // Container with locations }, // Internals _container: null, _event_chain: [], _address_list: [], // format {lat, lng, data: { zip:0000, city:"SYDNEY" }} _content: { }, // format { id: 1, content: '<strong>foobar</strong>' } _create: function () { this._reset(); // Call parent constructor $.utility.gmap.prototype._create.call(this); this._container = $(this.options.container); this.set_locations(); this._build(); }, destroy: function () { this._reset(); $.Widget.prototype.destroy.call(this); }, _build: function() { var self = this var events = { }; events.click = function (marker, event, data) { self.show_content(data.id, marker); }; if (this.options.bubble_on_hover) events.mouseover = function (marker, event, data) { self.show_content(data.id, marker); }; this.add_to_chain(function() { self.add_markers(self._address_list, events); if (self.options.autofit_markers) self.autofit(); }); this.execute_chain(); }, _reset: function() { this._address_list = []; this._event_chain = []; this._content = []; }, // Locations // set_locations: function() { var self = this; this._container.find('>li').each(function() { var address_id = $(this).data('id'); var content_panel = $(self.options.bubble_id_prefix+address_id); var address_string = $(this).data('address'); var address_latlng = $(this).data('latlng'); var data = { id: address_id, address: $(this).data('address'), content: content_panel.html() }; // Prevent duplication content_panel.remove(); self.set_content(data.id, data.content); if (address_latlng && address_latlng != "," && address_latlng != "") { var latlng = address_latlng.split(','); self.add_to_chain(self.add_location(latlng[0], latlng[1], data)); } else self.add_to_chain(self.add_location_from_string(data.address, data)); }); }, add_location: function(lat, lng, data) { this._address_list.push({lat:lat, lng:lng, data:data, id:data.id}); return $.Deferred().resolve(); }, add_location_from_string: function(string, data) { var self = this; var deferred = $.Deferred(); this.get_latlng_from_address_string(string, function(location) { self.add_location(location.lat, location.lng, data); deferred.resolve(); }); return deferred; }, focus_location: function(id) { this.show_content(id); }, // Waterfall chaining // add_to_chain: function(func) { this._event_chain.push(func); }, execute_chain: function() { $.waterfall.apply(this, this._event_chain).fail(function(){}).done(function(){}); }, // Content // set_content: function(id, content) { this._content[id] = { html: content }; }, get_content: function(id) { return this._content[id].html; }, show_content: function(id, marker) { if (!marker) marker = this.get_marker_by_id(id); this.element.trigger('show.gmap_locator', [id, marker]); this.clear_bubbles(); this.show_bubble_at_marker(marker, this.get_content(id)); } }); })( jQuery, window, document );
JavaScript
;(function ($, window, document, undefined) { $.widget("utility.gmap", { version: '1.0.1', options: { start_address: null, start_position: [-34.397, 150.644], // Australia ;) start_zoom: 2, // Initial map zoom allow_drag: true, // Allow user to drag map allow_scrollwheel: true, // Allow mouse scrool to zoom alow_dbl_click_zoom: true, // Allow double click to zoom show_default_ui: false, // Show default map controls show_pan_ui: false, // Show UI for pan show_type_ui: false, // Show UI for type show_scale_ui: false, // Show UI for scale show_overview_ui: false, // Show UI for overview show_street_view_ui: false, // Show UI for street view zoom_ui: false, // Show UI for zoom zoom_ui_position: 'top right', // Zoom UI Position zoom_ui_size: 'default', // Zoom size (default, large, small) on_idle: null, // This is triggered when the map is changed distance_type:'km', // Calculate distance in Kilometers (km) or Miles (mi) circle_colour:'#ff0000', // Circle color marker_image: null, // Custom image for marker bubble_min_width: 20, bubble_padding: 0 }, // Internals _map: null, // Google Map object _cluster_rules: { }, _create: function () { if (typeof google == 'undefined') throw "Google maps API not found. Please check that you are connected to the internet."; var map_options = { zoom: this.options.start_zoom, center: new google.maps.LatLng(this.options.start_position[0], this.options.start_position[1]), disableDefaultUI: !this.options.show_default_ui, panControl: this.options.show_pan_ui, mapTypeControl: this.options.show_type_ui, scaleControl: this.options.show_scale_ui, streetViewControl: this.options.show_overview_ui, overviewMapControl: this.options.show_street_view_ui, draggable: this.options.allow_drag, scrollwheel: this.options.allow_scrollwheel, keyboardShortcuts: false, disableDoubleClickZoom: !this.options.alow_dbl_click_zoom, zoomControl: this.options.zoom_ui, zoomControlOptions: { style: google.maps.ZoomControlStyle.SMALL, position: this._get_control_position(this.options.zoom_ui_position) }, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map_defaults = { classes: { InfoWindow: InfoBubble } }; if (this.element) this.__do('destroy'); var map_object = { options: map_options, events: { idle: $.proxy(function() { this.options.on_idle && this.options.on_idle(); }, this) } }; if (this.options.start_address) map_object.address = this.options.start_address; this.__call('map', map_object); this.__call('defaults', map_defaults); // Get Google map object this._map = this.__get('map'); }, destroy: function () { if (this.element) this.__do('destroy'); $.Widget.prototype.destroy.call(this); }, // General map functions // _get_control_position: function(pos_string) { var pos_return; switch (pos_string) { case "top center": pos_return = google.maps.ControlPosition.TOP_CENTER break; case "top left": pos_return = google.maps.ControlPosition.TOP_LEFT break; case "top right": pos_return = google.maps.ControlPosition.TOP_RIGHT break; case "left top": pos_return = google.maps.ControlPosition.LEFT_TOP break; case "right top": pos_return = google.maps.ControlPosition.RIGHT_TOP break; case "left center": pos_return = google.maps.ControlPosition.LEFT_CENTER break; case "right center": pos_return = google.maps.ControlPosition.RIGHT_CENTER break; case "left bottom": pos_return = google.maps.ControlPosition.LEFT_BOTTOM break; case "right bottom": pos_return = google.maps.ControlPosition.RIGHT_BOTTOM break; case "bottom center": pos_return = google.maps.ControlPosition.BOTTOM_CENTER break; case "bottom left": pos_return = google.maps.ControlPosition.BOTTOM_LEFT break; case "bottom right": pos_return = google.maps.ControlPosition.BOTTOM_RIGHT break; } return pos_return; }, // Converts a unit (km/mi) to meters _process_radius: function(radius) { if (this.options.distance_type == "km") return radius * 1000; else return radius * 1609.34; }, // Internals __get: function(name, options) { return this.element.gmap3({ get: $.extend(true, {name: name}, options) }); }, __call: function(name, options) { var call_object = {}; call_object[name] = options; return this.element.gmap3(call_object); }, __do: function(action) { return this.element.gmap3(action); }, get_latlng_object: function(lat, lng) { return new google.maps.LatLng(lat, lng); }, // Canvas // set_center: function(lat, lng) { this.__get('map').setCenter(this.get_latlng_object(lat, lng)); }, set_zoom: function(zoom) { if (!zoom) return; this.__get('map').setZoom(zoom); }, // Autofit to all elements autofit: function() { this.__do('autofit'); }, get_canvas_radius: function() { var bounds = this._map.getBounds(); var center = bounds.getCenter(); var ne = bounds.getNorthEast(); // r = radius of the earth in statute miles var r = (this.options.distance_type == "km") ? 6378.1370 : 3963.191; // Convert lat or lng from decimal degrees into radians (divide by 57.2958) var lat1 = center.lat() / 57.2958; var lon1 = center.lng() / 57.2958; var lat2 = ne.lat() / 57.2958; var lon2 = ne.lng() / 57.2958; // distance = circle radius from center to Northeast corner of bounds var distance = r * Math.acos(Math.sin(lat1) * Math.sin(lat2) + Math.cos(lat1) * Math.cos(lat2) * Math.cos(lon2 - lon1)); return distance; }, // Addresses // // Lookup, Returns array get_object_array_from_address_string: function(string, callback, options) { this.__call('getlatlng', $.extend(true, {address: string, callback:callback}, options)); }, // Lookup, Returns single address object get_object_from_address_string: function(string, callback, options) { this.get_object_array_from_address_string(string, function(address) { found_address = (address[0]) ? address[0] : null; callback && callback(found_address); }, options); }, // Lookup, Returns object {lat,lng} get_latlng_from_address_string: function(string, callback, options) { var self = this; this.get_object_from_address_string(string, function(address) { var result = { lat:false, lng: false }; if (address) result = self.get_latlng_from_address_object(address); callback && callback(result); }, options); }, // Filter, Returns object {lat,lng} get_latlng_from_address_object: function(address_object, callback, options) { var result = { lat:false, lng: false }; if (address_object.geometry && address_object.geometry.location) { result = { lat: address_object.geometry.location.lat(), lng: address_object.geometry.location.lng() }; } callback && callback(result); return result; }, // Value can be: country, postal_code get_value_from_address_object_array: function(address_object, value, options) { var self = this; options = $.extend(true, {set:0}, options); var set = options.set; var result = this.get_value_from_address_object(address_object[set]); // If no result, check other data sets if (!result && address_object[set+1]) { options.set = set + 1; return self.get_value_from_address_object_array(address_object, value, options); } return result; }, // Value can be: country, postal_code get_value_from_address_object: function(address_object, value, options) { var self = this; var result = null; for (i = 0; i < address_object.address_components.length; i++) { for (j = 0; j < address_object.address_components[i].types.length; j++) { if(address_object.address_components[i].types[j] == value) result = address_object.address_components[i].short_name; } } return result; }, // Helper align_to_address_object: function(address_object, zoom) { var latlng = this.get_latlng_from_address_object(address_object); this.set_center(latlng.lat, latlng.lng); if (zoom) this.set_zoom(zoom); }, // Markers // // Array format [{latlng:[1,1], id: 'address_1', data: { zip:0000, city:"SYDNEY" }}] add_markers: function(markers_array, marker_events) { var self = this; // Events var marker_events = $.extend(true, { click: function(marker, event, data) { }, mouseover: function(marker, event, data) { }, mouseout: function() { } }, marker_events); // Options var marker_options = { values: markers_array, options: { draggable: false, icon: this.options.marker_image }, events: marker_events }; // Clustering marker_options = $.extend(true, marker_options, this.get_cluster_rules()); this.__call('marker', marker_options); }, add_marker: function(marker_array, marker_events) { this.add_markers([marker_array], marker_events); }, add_marker_from_latlng: function(lat, lng, id, options) { var marker_array = { lat:lat, lng:lng, id:id }; var marker_events = (options && options.marker_events) ? options.marker_events : { }; if (options && options.marker_data) marker_array.data = options.marker_data; this.add_marker(marker_array, marker_events); }, add_marker_from_address_object: function(address_object, id, options) { var latlng = this.get_latlng_from_address_object(address_object); this.add_marker_from_latlng(latlng.lat, latlng.lng, id, options); }, get_markers: function() { return this.__get('marker', { all:true }); }, get_markers_by_id: function(id) { return this.__get('marker', { all:true, id:id }); }, get_marker_by_id: function(id) { return this.__get('marker', { first:true, id:id }); }, get_visible_markers: function() { var markers = this.get_markers(); for (var i = markers.length, bounds = this._map.getBounds(); i--;) { if (bounds.contains(markers[i].getPosition())) { // TODO: alert('found '+i); } } }, // Clusters // get_cluster_rules: function() { return (!$.isEmptyObject(this._cluster_rules)) ? { cluster: this._cluster_rules } : { }; }, add_cluster_rule: function(number, width, height, css_class) { this._cluster_rules[number] = { content: '<div class="cluster cluster-'+number+' '+css_class+'">CLUSTER_COUNT</div>', width: width, height: height }; }, // Bubbles // show_bubble_at_marker: function(marker, content) { var position = marker.getPosition(); this.show_bubble_at_latlng(position.lat(), position.lng(), content); infowindow = this.__get('infowindow'); infowindow.open(this._map, marker); }, show_bubble_at_latlng: function(lat, lng, content) { this.__call('infowindow', { latLng: this.get_latlng_object(lat,lng), options: { content: content, minWidth: this.options.bubble_min_width, padding: this.options.bubble_padding } }); }, clear_bubbles: function() { this.__call('clear', {name:'infowindow'}); }, // Overlay // show_overlay_at_marker: function(marker, content) { var position = marker.getPosition(); this.show_overlay_at_latlng(position.lat(), position.lng(), content); }, show_overlay_at_latlng: function(lat, lng, content) { this.__call('overlay', { latLng: this.get_latlng_object(lat,lng), content: content }); }, clear_overlays: function() { this.__call('clear', {name:'overlay'}); }, // Circle // show_circle_at_address_object: function(address_object, radius) { var latlng = this.get_latlng_from_address_object(address_object); this.show_circle_at_latlng(latlng.lat, latlng.lng, radius); }, show_circle_at_marker: function(marker, radius) { var position = marker.getPosition(); this.show_circle_at_latlng(position.lat(), position.lng(), radius); }, show_circle_at_latlng: function(lat, lng, radius) { this.__call('circle', { options: { center: [lat, lng], radius: this._process_radius(radius), fillColor : "#FFAF9F", strokeColor : "#FF512F" } }); }, clear_circles: function() { this.__call('clear', {name:'circle'}); } }) })( jQuery, window, document ); /** * @name CSS3 InfoBubble with tabs for Google Maps API V3 * @version 0.8 * @author Luke Mahe * @fileoverview * This library is a CSS Infobubble with tabs. It uses css3 rounded corners and * drop shadows and animations. It also allows tabs */ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * A CSS3 InfoBubble v0.8 * @param {Object.<string, *>=} opt_options Optional properties to set. * @extends {google.maps.OverlayView} * @constructor */ function InfoBubble(opt_options) { this.extend(InfoBubble, google.maps.OverlayView); this.tabs_ = []; this.activeTab_ = null; this.baseZIndex_ = 100; this.isOpen_ = false; var options = opt_options || {}; if (options['backgroundColor'] == undefined) { options['backgroundColor'] = this.BACKGROUND_COLOR_; } if (options['borderColor'] == undefined) { options['borderColor'] = this.BORDER_COLOR_; } if (options['borderRadius'] == undefined) { options['borderRadius'] = this.BORDER_RADIUS_; } if (options['borderWidth'] == undefined) { options['borderWidth'] = this.BORDER_WIDTH_; } if (options['padding'] == undefined) { options['padding'] = this.PADDING_; } if (options['arrowPosition'] == undefined) { options['arrowPosition'] = this.ARROW_POSITION_; } if (options['disableAutoPan'] == undefined) { options['disableAutoPan'] = false; } if (options['disableAnimation'] == undefined) { options['disableAnimation'] = false; } if (options['minWidth'] == undefined) { options['minWidth'] = this.MIN_WIDTH_; } if (options['shadowStyle'] == undefined) { options['shadowStyle'] = this.SHADOW_STYLE_; } if (options['arrowSize'] == undefined) { options['arrowSize'] = this.ARROW_SIZE_; } if (options['arrowStyle'] == undefined) { options['arrowStyle'] = this.ARROW_STYLE_; } this.buildDom_(); this.setValues(options); } window['InfoBubble'] = InfoBubble; /** * Default arrow size * @const * @private */ InfoBubble.prototype.ARROW_SIZE_ = 15; /** * Default arrow style * @const * @private */ InfoBubble.prototype.ARROW_STYLE_ = 0; /** * Default shadow style * @const * @private */ InfoBubble.prototype.SHADOW_STYLE_ = 1; /** * Default min width * @const * @private */ InfoBubble.prototype.MIN_WIDTH_ = 50; /** * Default arrow position * @const * @private */ InfoBubble.prototype.ARROW_POSITION_ = 50; /** * Default padding * @const * @private */ InfoBubble.prototype.PADDING_ = 10; /** * Default border width * @const * @private */ InfoBubble.prototype.BORDER_WIDTH_ = 1; /** * Default border color * @const * @private */ InfoBubble.prototype.BORDER_COLOR_ = '#ccc'; /** * Default border radius * @const * @private */ InfoBubble.prototype.BORDER_RADIUS_ = 10; /** * Default background color * @const * @private */ InfoBubble.prototype.BACKGROUND_COLOR_ = '#fff'; /** * Extends a objects prototype by anothers. * * @param {Object} obj1 The object to be extended. * @param {Object} obj2 The object to extend with. * @return {Object} The new extended object. * @ignore */ InfoBubble.prototype.extend = function(obj1, obj2) { return (function(object) { for (var property in object.prototype) { this.prototype[property] = object.prototype[property]; } return this; }).apply(obj1, [obj2]); }; /** * Builds the InfoBubble dom * @private */ InfoBubble.prototype.buildDom_ = function() { var bubble = this.bubble_ = document.createElement('DIV'); bubble.style['position'] = 'absolute'; bubble.style['zIndex'] = this.baseZIndex_; var tabsContainer = this.tabsContainer_ = document.createElement('DIV'); tabsContainer.style['position'] = 'relative'; // Close button var close = this.close_ = document.createElement('IMG'); close.style['position'] = 'absolute'; close.style['width'] = this.px(12); close.style['height'] = this.px(12); close.style['border'] = 0; close.style['zIndex'] = this.baseZIndex_ + 1; close.style['cursor'] = 'pointer'; close.src = 'http://maps.gstatic.com/intl/en_us/mapfiles/iw_close.gif'; var that = this; google.maps.event.addDomListener(close, 'click', function() { that.close(); google.maps.event.trigger(that, 'closeclick'); }); // Content area var contentContainer = this.contentContainer_ = document.createElement('DIV'); contentContainer.style['overflowX'] = 'auto'; contentContainer.style['overflowY'] = 'auto'; contentContainer.style['cursor'] = 'default'; contentContainer.style['clear'] = 'both'; contentContainer.style['position'] = 'relative'; var content = this.content_ = document.createElement('DIV'); contentContainer.appendChild(content); // Arrow var arrow = this.arrow_ = document.createElement('DIV'); arrow.style['position'] = 'relative'; var arrowOuter = this.arrowOuter_ = document.createElement('DIV'); var arrowInner = this.arrowInner_ = document.createElement('DIV'); var arrowSize = this.getArrowSize_(); arrowOuter.style['position'] = arrowInner.style['position'] = 'absolute'; arrowOuter.style['left'] = arrowInner.style['left'] = '50%'; arrowOuter.style['height'] = arrowInner.style['height'] = '0'; arrowOuter.style['width'] = arrowInner.style['width'] = '0'; arrowOuter.style['marginLeft'] = this.px(-arrowSize); arrowOuter.style['borderWidth'] = this.px(arrowSize); arrowOuter.style['borderBottomWidth'] = 0; // Shadow var bubbleShadow = this.bubbleShadow_ = document.createElement('DIV'); bubbleShadow.style['position'] = 'absolute'; // Hide the InfoBubble by default bubble.style['display'] = bubbleShadow.style['display'] = 'none'; bubble.appendChild(this.tabsContainer_); bubble.appendChild(close); bubble.appendChild(contentContainer); arrow.appendChild(arrowOuter); arrow.appendChild(arrowInner); bubble.appendChild(arrow); var stylesheet = document.createElement('style'); stylesheet.setAttribute('type', 'text/css'); /** * The animation for the infobubble * @type {string} */ this.animationName_ = '_ibani_' + Math.round(Math.random() * 10000); var css = '.' + this.animationName_ + '{-webkit-animation-name:' + this.animationName_ + ';-webkit-animation-duration:0.5s;' + '-webkit-animation-iteration-count:1;}' + '@-webkit-keyframes ' + this.animationName_ + ' {from {' + '-webkit-transform: scale(0)}50% {-webkit-transform: scale(1.2)}90% ' + '{-webkit-transform: scale(0.95)}to {-webkit-transform: scale(1)}}'; stylesheet.textContent = css; document.getElementsByTagName('head')[0].appendChild(stylesheet); }; /** * Sets the background class name * * @param {string} className The class name to set. */ InfoBubble.prototype.setBackgroundClassName = function(className) { this.set('backgroundClassName', className); }; InfoBubble.prototype['setBackgroundClassName'] = InfoBubble.prototype.setBackgroundClassName; /** * changed MVC callback */ InfoBubble.prototype.backgroundClassName_changed = function() { this.content_.className = this.get('backgroundClassName'); }; InfoBubble.prototype['backgroundClassName_changed'] = InfoBubble.prototype.backgroundClassName_changed; /** * Sets the class of the tab * * @param {string} className the class name to set. */ InfoBubble.prototype.setTabClassName = function(className) { this.set('tabClassName', className); }; InfoBubble.prototype['setTabClassName'] = InfoBubble.prototype.setTabClassName; /** * tabClassName changed MVC callback */ InfoBubble.prototype.tabClassName_changed = function() { this.updateTabStyles_(); }; InfoBubble.prototype['tabClassName_changed'] = InfoBubble.prototype.tabClassName_changed; /** * Gets the style of the arrow * * @private * @return {number} The style of the arrow. */ InfoBubble.prototype.getArrowStyle_ = function() { return parseInt(this.get('arrowStyle'), 10) || 0; }; /** * Sets the style of the arrow * * @param {number} style The style of the arrow. */ InfoBubble.prototype.setArrowStyle = function(style) { this.set('arrowStyle', style); }; InfoBubble.prototype['setArrowStyle'] = InfoBubble.prototype.setArrowStyle; /** * Arrow style changed MVC callback */ InfoBubble.prototype.arrowStyle_changed = function() { this.arrowSize_changed(); }; InfoBubble.prototype['arrowStyle_changed'] = InfoBubble.prototype.arrowStyle_changed; /** * Gets the size of the arrow * * @private * @return {number} The size of the arrow. */ InfoBubble.prototype.getArrowSize_ = function() { return parseInt(this.get('arrowSize'), 10) || 0; }; /** * Sets the size of the arrow * * @param {number} size The size of the arrow. */ InfoBubble.prototype.setArrowSize = function(size) { this.set('arrowSize', size); }; InfoBubble.prototype['setArrowSize'] = InfoBubble.prototype.setArrowSize; /** * Arrow size changed MVC callback */ InfoBubble.prototype.arrowSize_changed = function() { this.borderWidth_changed(); }; InfoBubble.prototype['arrowSize_changed'] = InfoBubble.prototype.arrowSize_changed; /** * Set the position of the InfoBubble arrow * * @param {number} pos The position to set. */ InfoBubble.prototype.setArrowPosition = function(pos) { this.set('arrowPosition', pos); }; InfoBubble.prototype['setArrowPosition'] = InfoBubble.prototype.setArrowPosition; /** * Get the position of the InfoBubble arrow * * @private * @return {number} The position.. */ InfoBubble.prototype.getArrowPosition_ = function() { return parseInt(this.get('arrowPosition'), 10) || 0; }; /** * arrowPosition changed MVC callback */ InfoBubble.prototype.arrowPosition_changed = function() { var pos = this.getArrowPosition_(); this.arrowOuter_.style['left'] = this.arrowInner_.style['left'] = pos + '%'; this.redraw_(); }; InfoBubble.prototype['arrowPosition_changed'] = InfoBubble.prototype.arrowPosition_changed; /** * Set the zIndex of the InfoBubble * * @param {number} zIndex The zIndex to set. */ InfoBubble.prototype.setZIndex = function(zIndex) { this.set('zIndex', zIndex); }; InfoBubble.prototype['setZIndex'] = InfoBubble.prototype.setZIndex; /** * Get the zIndex of the InfoBubble * * @return {number} The zIndex to set. */ InfoBubble.prototype.getZIndex = function() { return parseInt(this.get('zIndex'), 10) || this.baseZIndex_; }; /** * zIndex changed MVC callback */ InfoBubble.prototype.zIndex_changed = function() { var zIndex = this.getZIndex(); this.bubble_.style['zIndex'] = this.baseZIndex_ = zIndex; this.close_.style['zIndex'] = zIndex + 1; }; InfoBubble.prototype['zIndex_changed'] = InfoBubble.prototype.zIndex_changed; /** * Set the style of the shadow * * @param {number} shadowStyle The style of the shadow. */ InfoBubble.prototype.setShadowStyle = function(shadowStyle) { this.set('shadowStyle', shadowStyle); }; InfoBubble.prototype['setShadowStyle'] = InfoBubble.prototype.setShadowStyle; /** * Get the style of the shadow * * @private * @return {number} The style of the shadow. */ InfoBubble.prototype.getShadowStyle_ = function() { return parseInt(this.get('shadowStyle'), 10) || 0; }; /** * shadowStyle changed MVC callback */ InfoBubble.prototype.shadowStyle_changed = function() { var shadowStyle = this.getShadowStyle_(); var display = ''; var shadow = ''; var backgroundColor = ''; switch (shadowStyle) { case 0: display = 'none'; break; case 1: shadow = '40px 15px 10px rgba(33,33,33,0.3)'; backgroundColor = 'transparent'; break; case 2: shadow = '0 0 2px rgba(33,33,33,0.3)'; backgroundColor = 'rgba(33,33,33,0.35)'; break; } this.bubbleShadow_.style['boxShadow'] = this.bubbleShadow_.style['webkitBoxShadow'] = this.bubbleShadow_.style['MozBoxShadow'] = shadow; this.bubbleShadow_.style['backgroundColor'] = backgroundColor; if (this.isOpen_) { this.bubbleShadow_.style['display'] = display; this.draw(); } }; InfoBubble.prototype['shadowStyle_changed'] = InfoBubble.prototype.shadowStyle_changed; /** * Show the close button */ InfoBubble.prototype.showCloseButton = function() { this.set('hideCloseButton', false); }; InfoBubble.prototype['showCloseButton'] = InfoBubble.prototype.showCloseButton; /** * Hide the close button */ InfoBubble.prototype.hideCloseButton = function() { this.set('hideCloseButton', true); }; InfoBubble.prototype['hideCloseButton'] = InfoBubble.prototype.hideCloseButton; /** * hideCloseButton changed MVC callback */ InfoBubble.prototype.hideCloseButton_changed = function() { this.close_.style['display'] = this.get('hideCloseButton') ? 'none' : ''; }; InfoBubble.prototype['hideCloseButton_changed'] = InfoBubble.prototype.hideCloseButton_changed; /** * Set the background color * * @param {string} color The color to set. */ InfoBubble.prototype.setBackgroundColor = function(color) { if (color) { this.set('backgroundColor', color); } }; InfoBubble.prototype['setBackgroundColor'] = InfoBubble.prototype.setBackgroundColor; /** * backgroundColor changed MVC callback */ InfoBubble.prototype.backgroundColor_changed = function() { var backgroundColor = this.get('backgroundColor'); this.contentContainer_.style['backgroundColor'] = backgroundColor; this.arrowInner_.style['borderColor'] = backgroundColor + ' transparent transparent'; this.updateTabStyles_(); }; InfoBubble.prototype['backgroundColor_changed'] = InfoBubble.prototype.backgroundColor_changed; /** * Set the border color * * @param {string} color The border color. */ InfoBubble.prototype.setBorderColor = function(color) { if (color) { this.set('borderColor', color); } }; InfoBubble.prototype['setBorderColor'] = InfoBubble.prototype.setBorderColor; /** * borderColor changed MVC callback */ InfoBubble.prototype.borderColor_changed = function() { var borderColor = this.get('borderColor'); var contentContainer = this.contentContainer_; var arrowOuter = this.arrowOuter_; contentContainer.style['borderColor'] = borderColor; arrowOuter.style['borderColor'] = borderColor + ' transparent transparent'; contentContainer.style['borderStyle'] = arrowOuter.style['borderStyle'] = this.arrowInner_.style['borderStyle'] = 'solid'; this.updateTabStyles_(); }; InfoBubble.prototype['borderColor_changed'] = InfoBubble.prototype.borderColor_changed; /** * Set the radius of the border * * @param {number} radius The radius of the border. */ InfoBubble.prototype.setBorderRadius = function(radius) { this.set('borderRadius', radius); }; InfoBubble.prototype['setBorderRadius'] = InfoBubble.prototype.setBorderRadius; /** * Get the radius of the border * * @private * @return {number} The radius of the border. */ InfoBubble.prototype.getBorderRadius_ = function() { return parseInt(this.get('borderRadius'), 10) || 0; }; /** * borderRadius changed MVC callback */ InfoBubble.prototype.borderRadius_changed = function() { var borderRadius = this.getBorderRadius_(); var borderWidth = this.getBorderWidth_(); this.contentContainer_.style['borderRadius'] = this.contentContainer_.style['MozBorderRadius'] = this.contentContainer_.style['webkitBorderRadius'] = this.bubbleShadow_.style['borderRadius'] = this.bubbleShadow_.style['MozBorderRadius'] = this.bubbleShadow_.style['webkitBorderRadius'] = this.px(borderRadius); this.tabsContainer_.style['paddingLeft'] = this.tabsContainer_.style['paddingRight'] = this.px(borderRadius + borderWidth); this.redraw_(); }; InfoBubble.prototype['borderRadius_changed'] = InfoBubble.prototype.borderRadius_changed; /** * Get the width of the border * * @private * @return {number} width The width of the border. */ InfoBubble.prototype.getBorderWidth_ = function() { return parseInt(this.get('borderWidth'), 10) || 0; }; /** * Set the width of the border * * @param {number} width The width of the border. */ InfoBubble.prototype.setBorderWidth = function(width) { this.set('borderWidth', width); }; InfoBubble.prototype['setBorderWidth'] = InfoBubble.prototype.setBorderWidth; /** * borderWidth change MVC callback */ InfoBubble.prototype.borderWidth_changed = function() { var borderWidth = this.getBorderWidth_(); this.contentContainer_.style['borderWidth'] = this.px(borderWidth); this.tabsContainer_.style['top'] = this.px(borderWidth); this.updateArrowStyle_(); this.updateTabStyles_(); this.borderRadius_changed(); this.redraw_(); }; InfoBubble.prototype['borderWidth_changed'] = InfoBubble.prototype.borderWidth_changed; /** * Update the arrow style * @private */ InfoBubble.prototype.updateArrowStyle_ = function() { var borderWidth = this.getBorderWidth_(); var arrowSize = this.getArrowSize_(); var arrowStyle = this.getArrowStyle_(); var arrowOuterSizePx = this.px(arrowSize); var arrowInnerSizePx = this.px(Math.max(0, arrowSize - borderWidth)); var outer = this.arrowOuter_; var inner = this.arrowInner_; this.arrow_.style['marginTop'] = this.px(-borderWidth); outer.style['borderTopWidth'] = arrowOuterSizePx; inner.style['borderTopWidth'] = arrowInnerSizePx; // Full arrow or arrow pointing to the left if (arrowStyle == 0 || arrowStyle == 1) { outer.style['borderLeftWidth'] = arrowOuterSizePx; inner.style['borderLeftWidth'] = arrowInnerSizePx; } else { outer.style['borderLeftWidth'] = inner.style['borderLeftWidth'] = 0; } // Full arrow or arrow pointing to the right if (arrowStyle == 0 || arrowStyle == 2) { outer.style['borderRightWidth'] = arrowOuterSizePx; inner.style['borderRightWidth'] = arrowInnerSizePx; } else { outer.style['borderRightWidth'] = inner.style['borderRightWidth'] = 0; } if (arrowStyle < 2) { outer.style['marginLeft'] = this.px(-(arrowSize)); inner.style['marginLeft'] = this.px(-(arrowSize - borderWidth)); } else { outer.style['marginLeft'] = inner.style['marginLeft'] = 0; } // If there is no border then don't show thw outer arrow if (borderWidth == 0) { outer.style['display'] = 'none'; } else { outer.style['display'] = ''; } }; /** * Set the padding of the InfoBubble * * @param {number} padding The padding to apply. */ InfoBubble.prototype.setPadding = function(padding) { this.set('padding', padding); }; InfoBubble.prototype['setPadding'] = InfoBubble.prototype.setPadding; /** * Set the padding of the InfoBubble * * @private * @return {number} padding The padding to apply. */ InfoBubble.prototype.getPadding_ = function() { return parseInt(this.get('padding'), 10) || 0; }; /** * padding changed MVC callback */ InfoBubble.prototype.padding_changed = function() { var padding = this.getPadding_(); this.contentContainer_.style['padding'] = this.px(padding); this.updateTabStyles_(); this.redraw_(); }; InfoBubble.prototype['padding_changed'] = InfoBubble.prototype.padding_changed; /** * Add px extention to the number * * @param {number} num The number to wrap. * @return {string|number} A wrapped number. */ InfoBubble.prototype.px = function(num) { if (num) { // 0 doesn't need to be wrapped return num + 'px'; } return num; }; /** * Add events to stop propagation * @private */ InfoBubble.prototype.addEvents_ = function() { // We want to cancel all the events so they do not go to the map var events = ['mousedown', 'mousemove', 'mouseover', 'mouseout', 'mouseup', 'mousewheel', 'DOMMouseScroll', 'touchstart', 'touchend', 'touchmove', 'dblclick', 'contextmenu', 'click']; var bubble = this.bubble_; this.listeners_ = []; for (var i = 0, event; event = events[i]; i++) { this.listeners_.push( google.maps.event.addDomListener(bubble, event, function(e) { e.cancelBubble = true; if (e.stopPropagation) { e.stopPropagation(); } }) ); } }; /** * On Adding the InfoBubble to a map * Implementing the OverlayView interface */ InfoBubble.prototype.onAdd = function() { if (!this.bubble_) { this.buildDom_(); } this.addEvents_(); var panes = this.getPanes(); if (panes) { panes.floatPane.appendChild(this.bubble_); panes.floatShadow.appendChild(this.bubbleShadow_); } }; InfoBubble.prototype['onAdd'] = InfoBubble.prototype.onAdd; /** * Draw the InfoBubble * Implementing the OverlayView interface */ InfoBubble.prototype.draw = function() { var projection = this.getProjection(); if (!projection) { // The map projection is not ready yet so do nothing return; } var latLng = /** @type {google.maps.LatLng} */ (this.get('position')); if (!latLng) { this.close(); return; } var tabHeight = 0; if (this.activeTab_) { tabHeight = this.activeTab_.offsetHeight; } var anchorHeight = this.getAnchorHeight_(); var arrowSize = this.getArrowSize_(); var arrowPosition = this.getArrowPosition_(); arrowPosition = arrowPosition / 100; var pos = projection.fromLatLngToDivPixel(latLng); var width = this.contentContainer_.offsetWidth; var height = this.bubble_.offsetHeight; if (!width) { return; } // Adjust for the height of the info bubble var top = pos.y - (height + arrowSize); if (anchorHeight) { // If there is an anchor then include the height top -= anchorHeight; } var left = pos.x - (width * arrowPosition); this.bubble_.style['top'] = this.px(top); this.bubble_.style['left'] = this.px(left); var shadowStyle = parseInt(this.get('shadowStyle'), 10); switch (shadowStyle) { case 1: // Shadow is behind this.bubbleShadow_.style['top'] = this.px(top + tabHeight - 1); this.bubbleShadow_.style['left'] = this.px(left); this.bubbleShadow_.style['width'] = this.px(width); this.bubbleShadow_.style['height'] = this.px(this.contentContainer_.offsetHeight - arrowSize); break; case 2: // Shadow is below width = width * 0.8; if (anchorHeight) { this.bubbleShadow_.style['top'] = this.px(pos.y); } else { this.bubbleShadow_.style['top'] = this.px(pos.y + arrowSize); } this.bubbleShadow_.style['left'] = this.px(pos.x - width * arrowPosition); this.bubbleShadow_.style['width'] = this.px(width); this.bubbleShadow_.style['height'] = this.px(2); break; } }; InfoBubble.prototype['draw'] = InfoBubble.prototype.draw; /** * Removing the InfoBubble from a map */ InfoBubble.prototype.onRemove = function() { if (this.bubble_ && this.bubble_.parentNode) { this.bubble_.parentNode.removeChild(this.bubble_); } if (this.bubbleShadow_ && this.bubbleShadow_.parentNode) { this.bubbleShadow_.parentNode.removeChild(this.bubbleShadow_); } for (var i = 0, listener; listener = this.listeners_[i]; i++) { google.maps.event.removeListener(listener); } }; InfoBubble.prototype['onRemove'] = InfoBubble.prototype.onRemove; /** * Is the InfoBubble open * * @return {boolean} If the InfoBubble is open. */ InfoBubble.prototype.isOpen = function() { return this.isOpen_; }; InfoBubble.prototype['isOpen'] = InfoBubble.prototype.isOpen; /** * Close the InfoBubble */ InfoBubble.prototype.close = function() { if (this.bubble_) { this.bubble_.style['display'] = 'none'; // Remove the animation so we next time it opens it will animate again this.bubble_.className = this.bubble_.className.replace(this.animationName_, ''); } if (this.bubbleShadow_) { this.bubbleShadow_.style['display'] = 'none'; this.bubbleShadow_.className = this.bubbleShadow_.className.replace(this.animationName_, ''); } this.isOpen_ = false; }; InfoBubble.prototype['close'] = InfoBubble.prototype.close; /** * Open the InfoBubble (asynchronous). * * @param {google.maps.Map=} opt_map Optional map to open on. * @param {google.maps.MVCObject=} opt_anchor Optional anchor to position at. */ InfoBubble.prototype.open = function(opt_map, opt_anchor) { var that = this; window.setTimeout(function() { that.open_(opt_map, opt_anchor); }, 0); }; /** * Open the InfoBubble * @private * @param {google.maps.Map=} opt_map Optional map to open on. * @param {google.maps.MVCObject=} opt_anchor Optional anchor to position at. */ InfoBubble.prototype.open_ = function(opt_map, opt_anchor) { this.updateContent_(); if (opt_map) { this.setMap(opt_map); } if (opt_anchor) { this.set('anchor', opt_anchor); this.bindTo('anchorPoint', opt_anchor); this.bindTo('position', opt_anchor); } // Show the bubble and the show this.bubble_.style['display'] = this.bubbleShadow_.style['display'] = ''; var animation = !this.get('disableAnimation'); if (animation) { // Add the animation this.bubble_.className += ' ' + this.animationName_; this.bubbleShadow_.className += ' ' + this.animationName_; } this.redraw_(); this.isOpen_ = true; var pan = !this.get('disableAutoPan'); if (pan) { var that = this; window.setTimeout(function() { // Pan into view, done in a time out to make it feel nicer :) that.panToView(); }, 200); } }; InfoBubble.prototype['open'] = InfoBubble.prototype.open; /** * Set the position of the InfoBubble * * @param {google.maps.LatLng} position The position to set. */ InfoBubble.prototype.setPosition = function(position) { if (position) { this.set('position', position); } }; InfoBubble.prototype['setPosition'] = InfoBubble.prototype.setPosition; /** * Returns the position of the InfoBubble * * @return {google.maps.LatLng} the position. */ InfoBubble.prototype.getPosition = function() { return /** @type {google.maps.LatLng} */ (this.get('position')); }; InfoBubble.prototype['getPosition'] = InfoBubble.prototype.getPosition; /** * position changed MVC callback */ InfoBubble.prototype.position_changed = function() { this.draw(); }; InfoBubble.prototype['position_changed'] = InfoBubble.prototype.position_changed; /** * Pan the InfoBubble into view */ InfoBubble.prototype.panToView = function() { var projection = this.getProjection(); if (!projection) { // The map projection is not ready yet so do nothing return; } if (!this.bubble_) { // No Bubble yet so do nothing return; } var anchorHeight = this.getAnchorHeight_(); var height = this.bubble_.offsetHeight + anchorHeight; var map = this.get('map'); var mapDiv = map.getDiv(); var mapHeight = mapDiv.offsetHeight; var latLng = this.getPosition(); var centerPos = projection.fromLatLngToContainerPixel(map.getCenter()); var pos = projection.fromLatLngToContainerPixel(latLng); // Find out how much space at the top is free var spaceTop = centerPos.y - height; // Fine out how much space at the bottom is free var spaceBottom = mapHeight - centerPos.y; var needsTop = spaceTop < 0; var deltaY = 0; if (needsTop) { spaceTop *= -1; deltaY = (spaceTop + spaceBottom) / 2; } pos.y -= deltaY; latLng = projection.fromContainerPixelToLatLng(pos); if (map.getCenter() != latLng) { map.panTo(latLng); } }; InfoBubble.prototype['panToView'] = InfoBubble.prototype.panToView; /** * Converts a HTML string to a document fragment. * * @param {string} htmlString The HTML string to convert. * @return {Node} A HTML document fragment. * @private */ InfoBubble.prototype.htmlToDocumentFragment_ = function(htmlString) { htmlString = htmlString.replace(/^\s*([\S\s]*)\b\s*$/, '$1'); var tempDiv = document.createElement('DIV'); tempDiv.innerHTML = htmlString; if (tempDiv.childNodes.length == 1) { return /** @type {!Node} */ (tempDiv.removeChild(tempDiv.firstChild)); } else { var fragment = document.createDocumentFragment(); while (tempDiv.firstChild) { fragment.appendChild(tempDiv.firstChild); } return fragment; } }; /** * Removes all children from the node. * * @param {Node} node The node to remove all children from. * @private */ InfoBubble.prototype.removeChildren_ = function(node) { if (!node) { return; } var child; while (child = node.firstChild) { node.removeChild(child); } }; /** * Sets the content of the infobubble. * * @param {string|Node} content The content to set. */ InfoBubble.prototype.setContent = function(content) { this.set('content', content); }; InfoBubble.prototype['setContent'] = InfoBubble.prototype.setContent; /** * Get the content of the infobubble. * * @return {string|Node} The marker content. */ InfoBubble.prototype.getContent = function() { return /** @type {Node|string} */ (this.get('content')); }; InfoBubble.prototype['getContent'] = InfoBubble.prototype.getContent; /** * Sets the marker content and adds loading events to images */ InfoBubble.prototype.updateContent_ = function() { if (!this.content_) { // The Content area doesnt exist. return; } this.removeChildren_(this.content_); var content = this.getContent(); if (content) { if (typeof content == 'string') { content = this.htmlToDocumentFragment_(content); } this.content_.appendChild(content); var that = this; var images = this.content_.getElementsByTagName('IMG'); for (var i = 0, image; image = images[i]; i++) { // Because we don't know the size of an image till it loads, add a // listener to the image load so the marker can resize and reposition // itself to be the correct height. google.maps.event.addDomListener(image, 'load', function() { that.imageLoaded_(); }); } google.maps.event.trigger(this, 'domready'); } this.redraw_(); }; /** * Image loaded * @private */ InfoBubble.prototype.imageLoaded_ = function() { var pan = !this.get('disableAutoPan'); this.redraw_(); if (pan && (this.tabs_.length == 0 || this.activeTab_.index == 0)) { this.panToView(); } }; /** * Updates the styles of the tabs * @private */ InfoBubble.prototype.updateTabStyles_ = function() { if (this.tabs_ && this.tabs_.length) { for (var i = 0, tab; tab = this.tabs_[i]; i++) { this.setTabStyle_(tab.tab); } this.activeTab_.style['zIndex'] = this.baseZIndex_; var borderWidth = this.getBorderWidth_(); var padding = this.getPadding_() / 2; this.activeTab_.style['borderBottomWidth'] = 0; this.activeTab_.style['paddingBottom'] = this.px(padding + borderWidth); } }; /** * Sets the style of a tab * @private * @param {Element} tab The tab to style. */ InfoBubble.prototype.setTabStyle_ = function(tab) { var backgroundColor = this.get('backgroundColor'); var borderColor = this.get('borderColor'); var borderRadius = this.getBorderRadius_(); var borderWidth = this.getBorderWidth_(); var padding = this.getPadding_(); var marginRight = this.px(-(Math.max(padding, borderRadius))); var borderRadiusPx = this.px(borderRadius); var index = this.baseZIndex_; if (tab.index) { index -= tab.index; } // The styles for the tab var styles = { 'cssFloat': 'left', 'position': 'relative', 'cursor': 'pointer', 'backgroundColor': backgroundColor, 'border': this.px(borderWidth) + ' solid ' + borderColor, 'padding': this.px(padding / 2) + ' ' + this.px(padding), 'marginRight': marginRight, 'whiteSpace': 'nowrap', 'borderRadiusTopLeft': borderRadiusPx, 'MozBorderRadiusTopleft': borderRadiusPx, 'webkitBorderTopLeftRadius': borderRadiusPx, 'borderRadiusTopRight': borderRadiusPx, 'MozBorderRadiusTopright': borderRadiusPx, 'webkitBorderTopRightRadius': borderRadiusPx, 'zIndex': index, 'display': 'inline' }; for (var style in styles) { tab.style[style] = styles[style]; } var className = this.get('tabClassName'); if (className != undefined) { tab.className += ' ' + className; } }; /** * Add user actions to a tab * @private * @param {Object} tab The tab to add the actions to. */ InfoBubble.prototype.addTabActions_ = function(tab) { var that = this; tab.listener_ = google.maps.event.addDomListener(tab, 'click', function() { that.setTabActive_(this); }); }; /** * Set a tab at a index to be active * * @param {number} index The index of the tab. */ InfoBubble.prototype.setTabActive = function(index) { var tab = this.tabs_[index - 1]; if (tab) { this.setTabActive_(tab.tab); } }; InfoBubble.prototype['setTabActive'] = InfoBubble.prototype.setTabActive; /** * Set a tab to be active * @private * @param {Object} tab The tab to set active. */ InfoBubble.prototype.setTabActive_ = function(tab) { if (!tab) { this.setContent(''); this.updateContent_(); return; } var padding = this.getPadding_() / 2; var borderWidth = this.getBorderWidth_(); if (this.activeTab_) { var activeTab = this.activeTab_; activeTab.style['zIndex'] = this.baseZIndex_ - activeTab.index; activeTab.style['paddingBottom'] = this.px(padding); activeTab.style['borderBottomWidth'] = this.px(borderWidth); } tab.style['zIndex'] = this.baseZIndex_; tab.style['borderBottomWidth'] = 0; tab.style['marginBottomWidth'] = '-10px'; tab.style['paddingBottom'] = this.px(padding + borderWidth); this.setContent(this.tabs_[tab.index].content); this.updateContent_(); this.activeTab_ = tab; this.redraw_(); }; /** * Set the max width of the InfoBubble * * @param {number} width The max width. */ InfoBubble.prototype.setMaxWidth = function(width) { this.set('maxWidth', width); }; InfoBubble.prototype['setMaxWidth'] = InfoBubble.prototype.setMaxWidth; /** * maxWidth changed MVC callback */ InfoBubble.prototype.maxWidth_changed = function() { this.redraw_(); }; InfoBubble.prototype['maxWidth_changed'] = InfoBubble.prototype.maxWidth_changed; /** * Set the max height of the InfoBubble * * @param {number} height The max height. */ InfoBubble.prototype.setMaxHeight = function(height) { this.set('maxHeight', height); }; InfoBubble.prototype['setMaxHeight'] = InfoBubble.prototype.setMaxHeight; /** * maxHeight changed MVC callback */ InfoBubble.prototype.maxHeight_changed = function() { this.redraw_(); }; InfoBubble.prototype['maxHeight_changed'] = InfoBubble.prototype.maxHeight_changed; /** * Set the min width of the InfoBubble * * @param {number} width The min width. */ InfoBubble.prototype.setMinWidth = function(width) { this.set('minWidth', width); }; InfoBubble.prototype['setMinWidth'] = InfoBubble.prototype.setMinWidth; /** * minWidth changed MVC callback */ InfoBubble.prototype.minWidth_changed = function() { this.redraw_(); }; InfoBubble.prototype['minWidth_changed'] = InfoBubble.prototype.minWidth_changed; /** * Set the min height of the InfoBubble * * @param {number} height The min height. */ InfoBubble.prototype.setMinHeight = function(height) { this.set('minHeight', height); }; InfoBubble.prototype['setMinHeight'] = InfoBubble.prototype.setMinHeight; /** * minHeight changed MVC callback */ InfoBubble.prototype.minHeight_changed = function() { this.redraw_(); }; InfoBubble.prototype['minHeight_changed'] = InfoBubble.prototype.minHeight_changed; /** * Add a tab * * @param {string} label The label of the tab. * @param {string|Element} content The content of the tab. */ InfoBubble.prototype.addTab = function(label, content) { var tab = document.createElement('DIV'); tab.innerHTML = label; this.setTabStyle_(tab); this.addTabActions_(tab); this.tabsContainer_.appendChild(tab); this.tabs_.push({ label: label, content: content, tab: tab }); tab.index = this.tabs_.length - 1; tab.style['zIndex'] = this.baseZIndex_ - tab.index; if (!this.activeTab_) { this.setTabActive_(tab); } tab.className = tab.className + ' ' + this.animationName_; this.redraw_(); }; InfoBubble.prototype['addTab'] = InfoBubble.prototype.addTab; /** * Update a tab at a speicifc index * * @param {number} index The index of the tab. * @param {?string} opt_label The label to change to. * @param {?string} opt_content The content to update to. */ InfoBubble.prototype.updateTab = function(index, opt_label, opt_content) { if (!this.tabs_.length || index < 0 || index >= this.tabs_.length) { return; } var tab = this.tabs_[index]; if (opt_label != undefined) { tab.tab.innerHTML = tab.label = opt_label; } if (opt_content != undefined) { tab.content = opt_content; } if (this.activeTab_ == tab.tab) { this.setContent(tab.content); this.updateContent_(); } this.redraw_(); }; InfoBubble.prototype['updateTab'] = InfoBubble.prototype.updateTab; /** * Remove a tab at a specific index * * @param {number} index The index of the tab to remove. */ InfoBubble.prototype.removeTab = function(index) { if (!this.tabs_.length || index < 0 || index >= this.tabs_.length) { return; } var tab = this.tabs_[index]; tab.tab.parentNode.removeChild(tab.tab); google.maps.event.removeListener(tab.tab.listener_); this.tabs_.splice(index, 1); delete tab; for (var i = 0, t; t = this.tabs_[i]; i++) { t.tab.index = i; } if (tab.tab == this.activeTab_) { // Removing the current active tab if (this.tabs_[index]) { // Show the tab to the right this.activeTab_ = this.tabs_[index].tab; } else if (this.tabs_[index - 1]) { // Show a tab to the left this.activeTab_ = this.tabs_[index - 1].tab; } else { // No tabs left to sho this.activeTab_ = undefined; } this.setTabActive_(this.activeTab_); } this.redraw_(); }; InfoBubble.prototype['removeTab'] = InfoBubble.prototype.removeTab; /** * Get the size of an element * @private * @param {Node|string} element The element to size. * @param {number=} opt_maxWidth Optional max width of the element. * @param {number=} opt_maxHeight Optional max height of the element. * @return {google.maps.Size} The size of the element. */ InfoBubble.prototype.getElementSize_ = function(element, opt_maxWidth, opt_maxHeight) { var sizer = document.createElement('DIV'); sizer.style['display'] = 'inline'; sizer.style['position'] = 'absolute'; sizer.style['visibility'] = 'hidden'; if (typeof element == 'string') { sizer.innerHTML = element; } else { sizer.appendChild(element.cloneNode(true)); } document.body.appendChild(sizer); var size = new google.maps.Size(sizer.offsetWidth, sizer.offsetHeight); // If the width is bigger than the max width then set the width and size again if (opt_maxWidth && size.width > opt_maxWidth) { sizer.style['width'] = this.px(opt_maxWidth); size = new google.maps.Size(sizer.offsetWidth, sizer.offsetHeight); } // If the height is bigger than the max height then set the height and size // again if (opt_maxHeight && size.height > opt_maxHeight) { sizer.style['height'] = this.px(opt_maxHeight); size = new google.maps.Size(sizer.offsetWidth, sizer.offsetHeight); } document.body.removeChild(sizer); delete sizer; return size; }; /** * Redraw the InfoBubble * @private */ InfoBubble.prototype.redraw_ = function() { this.figureOutSize_(); this.positionCloseButton_(); this.draw(); }; /** * Figure out the optimum size of the InfoBubble * @private */ InfoBubble.prototype.figureOutSize_ = function() { var map = this.get('map'); if (!map) { return; } var padding = this.getPadding_(); var borderWidth = this.getBorderWidth_(); var borderRadius = this.getBorderRadius_(); var arrowSize = this.getArrowSize_(); var mapDiv = map.getDiv(); var gutter = arrowSize * 2; var mapWidth = mapDiv.offsetWidth - gutter; var mapHeight = mapDiv.offsetHeight - gutter - this.getAnchorHeight_(); var tabHeight = 0; var width = /** @type {number} */ (this.get('minWidth') || 0); var height = /** @type {number} */ (this.get('minHeight') || 0); var maxWidth = /** @type {number} */ (this.get('maxWidth') || 0); var maxHeight = /** @type {number} */ (this.get('maxHeight') || 0); maxWidth = Math.min(mapWidth, maxWidth); maxHeight = Math.min(mapHeight, maxHeight); var tabWidth = 0; if (this.tabs_.length) { // If there are tabs then you need to check the size of each tab's content for (var i = 0, tab; tab = this.tabs_[i]; i++) { var tabSize = this.getElementSize_(tab.tab, maxWidth, maxHeight); var contentSize = this.getElementSize_(tab.content, maxWidth, maxHeight); if (width < tabSize.width) { width = tabSize.width; } // Add up all the tab widths because they might end up being wider than // the content tabWidth += tabSize.width; if (height < tabSize.height) { height = tabSize.height; } if (tabSize.height > tabHeight) { tabHeight = tabSize.height; } if (width < contentSize.width) { width = contentSize.width; } if (height < contentSize.height) { height = contentSize.height; } } } else { var content = /** @type {string|Node} */ (this.get('content')); if (typeof content == 'string') { content = this.htmlToDocumentFragment_(content); } if (content) { var contentSize = this.getElementSize_(content, maxWidth, maxHeight); if (width < contentSize.width) { width = contentSize.width; } if (height < contentSize.height) { height = contentSize.height; } } } if (maxWidth) { width = Math.min(width, maxWidth); } if (maxHeight) { height = Math.min(height, maxHeight); } width = Math.max(width, tabWidth); if (width == tabWidth) { width = width + 2 * padding; } arrowSize = arrowSize * 2; width = Math.max(width, arrowSize); // Maybe add this as a option so they can go bigger than the map if the user // wants if (width > mapWidth) { width = mapWidth; } if (height > mapHeight) { height = mapHeight - tabHeight; } if (this.tabsContainer_) { this.tabHeight_ = tabHeight; this.tabsContainer_.style['width'] = this.px(tabWidth); } this.contentContainer_.style['width'] = this.px(width); this.contentContainer_.style['height'] = this.px(height); }; /** * Get the height of the anchor * * This function is a hack for now and doesn't really work that good, need to * wait for pixelBounds to be correctly exposed. * @private * @return {number} The height of the anchor. */ InfoBubble.prototype.getAnchorHeight_ = function() { var anchor = this.get('anchor'); if (anchor) { var anchorPoint = /** @type google.maps.Point */(this.get('anchorPoint')); if (anchorPoint) { return -1 * anchorPoint.y; } } return 0; }; InfoBubble.prototype.anchorPoint_changed = function() { this.draw(); }; InfoBubble.prototype['anchorPoint_changed'] = InfoBubble.prototype.anchorPoint_changed; /** * Position the close button in the right spot. * @private */ InfoBubble.prototype.positionCloseButton_ = function() { var br = this.getBorderRadius_(); var bw = this.getBorderWidth_(); var right = 2; var top = 2; if (this.tabs_.length && this.tabHeight_) { top += this.tabHeight_; } top += bw; right += bw; var c = this.contentContainer_; if (c && c.clientHeight < c.scrollHeight) { // If there are scrollbars then move the cross in so it is not over // scrollbar right += 15; } this.close_.style['right'] = this.px(right); this.close_.style['top'] = this.px(top); };
JavaScript
/** * Portfolio behavior * * Usage: * <div id="portfolio"> * <img src="fullsize.jpg" data-image-id="1" data-image-thumb="thumb.jpg" /> * <img src="fullsize2.jpg" data-image-id="1" data-image-thumb="thumb2.jpg" /> * </div> * <script> $('portfolio').portfolio(); </script> * */ ;(function ($, window, document, undefined) { $.widget("utility.portfolio", { version: '1.0.0', options: { thumb_mode: 'carousel', // carousel|orbit thumb_width: 75, thumb_height: 75, use_popup: true // Display full size images in a popup }, _element_id: null, _popup: null, _popup_id: null, _thumb_list: null, // Object to store thumb list _create: function () { var _this = this; this._element_id = this.element.attr('id'); this._popup_id = this._element_id+'_popup'; // First lets clean up $('#'+this._popup_id).remove(); // Then dress up this.element.wrap($('<div />').attr('id', this._popup_id)); this._popup = $('#'+this._popup_id); // Init thumbs if (this.options.thumb_mode == 'carousel') _this._init_carousel_thumbs(); else if (this.options.thumb_mode == 'orbit') _this._init_orbit_thumbs(); // If we have no images, do not proceed if (!this.element.find('img').length) return; // Init Orbit this.element.not('.orbit-enabled').addClass('orbit-enabled').orbit({ animation: 'horizontal-push', bullets: this.options.use_popup, captions: true, directionalNav: this.options.use_popup, fluid: true, timer: false }); // Popup this._init_popup(); }, // Build thumbs for carousel _init_carousel_thumbs: function() { var _this = this; this._thumb_list = $('<ul />').attr('id', this._element_id+'_thumbs').addClass('jcarousel-skin-ahoy'); this.element.find('img').each(function(key, val){ var image_id = $(this).attr('data-image-id'); var thumb_src = $(this).attr('data-image-thumb'); var anchor = $('<a />').attr({ href: 'javascript:;', 'data-image-count': key }); var thumb = $('<img />').attr({ src: thumb_src, 'data-image-id': image_id, width: _this.options.thumb_width, height: _this.options.thumb_height }); var thumb_list_anchor = anchor.append(thumb); _this._thumb_list.append($('<li />').append(thumb_list_anchor)); }); this._popup.after(this._thumb_list); _this._thumb_list.jcarousel({ scroll: 1 }); }, // Build thumbs for orbit _init_orbit_thumbs: function() { var _this = this; this._thumb_list = $('<div />').attr('id', this._element_id+'_thumbs'); this.element.find('img').each(function(key, val){ var image_id = $(this).attr('data-image-id'); var thumb_src = $(this).attr('data-image-thumb'); var anchor = $('<a />').attr({ href: 'javascript:;', 'data-image-count': key }); var thumb = $('<img />').attr({ src: thumb_src, 'data-image-id': image_id //width: _this.options.thumb_width, //height: _this.options.thumb_height }); var thumb_list_anchor = anchor.append(thumb); _this._thumb_list.append(thumb_list_anchor); }); this._popup.after(this._thumb_list); _this._thumb_list.orbit({ timer:true, directionalNav:false, bullets:true }); }, _init_popup: function() { var _this = this; if (this.options.use_popup) { this._popup.popup({ trigger: '#'+this._element_id+'_thumbs a', move_to_element: 'body', size: 'portfolio', on_open: function(link) { _this.click_thumb(link); } }); } else { $('#'+this._element_id+'_thumbs a').click(function() { _this.click_thumb($(this)); }); } }, // When a thumb is clicked click_thumb: function(link) { var image_id = $(link).attr('data-image-count'); if (image_id) this.element.trigger('orbit.goto', [image_id]); }, destroy: function() { $.Widget.prototype.destroy.call(this); this._popup.remove(); } }); })( jQuery, window, document );
JavaScript
/*! * GMAP3 Plugin for JQuery * Version : 5.0b * Date : 2012-11-17 * Licence : GPL v3 : http://www.gnu.org/licenses/gpl.html * Author : DEMONTE Jean-Baptiste * Contact : jbdemonte@gmail.com * Web site : http://gmap3.net * * Copyright (c) 2010-2012 Jean-Baptiste DEMONTE * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * - Neither the name of the author nor the names of its contributors * may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ ;(function ($, undef) { /***************************************************************************/ /* GMAP3 DEFAULTS */ /***************************************************************************/ // defaults are defined later in the code to pass the rails asset pipeline and //jasmine while google library is not loaded var defaults, gId = 0; function initDefaults() { if (!defaults) { defaults = { verbose: false, queryLimit: { attempt: 5, delay: 250, // setTimeout(..., delay + random); random: 250 }, classes: { Map : google.maps.Map, Marker : google.maps.Marker, InfoWindow : google.maps.InfoWindow, Circle : google.maps.Circle, Rectangle : google.maps.Rectangle, OverlayView : google.maps.OverlayView, StreetViewPanorama: google.maps.StreetViewPanorama, KmlLayer : google.maps.KmlLayer, TrafficLayer : google.maps.TrafficLayer, BicyclingLayer : google.maps.BicyclingLayer, GroundOverlay : google.maps.GroundOverlay, StyledMapType : google.maps.StyledMapType, ImageMapType : google.maps.ImageMapType }, map: { mapTypeId : google.maps.MapTypeId.ROADMAP, center: [46.578498, 2.457275], zoom: 2 }, overlay: { pane: "floatPane", content: "", offset: { x: 0, y: 0 } }, geoloc: { getCurrentPosition: { maximumAge: 60000, timeout: 5000 } } } } } function globalId(id, simulate){ return id !== undef ? id : "gmap3_" + (simulate ? gId + 1 : ++gId); } /** * attach events from a container to a sender * todo[ * events => { eventName => function, } * onces => { eventName => function, } * data => mixed data * ] **/ function attachEvents($container, args, sender, id, senders){ if (args.todo.events || args.todo.onces){ var context = { id: id, data: args.todo.data, tag: args.todo.tag }; } if (args.todo.events){ $.each(args.todo.events, function(name, f){ google.maps.event.addListener(sender, name, function(event) { f.apply($container, [senders ? senders : sender, event, context]); }); }); } if (args.todo.onces){ $.each(args.todo.onces, function(name, f){ google.maps.event.addListenerOnce(sender, name, function(event) { f.apply($container, [senders ? senders : sender, event, context]); }); }); } } /***************************************************************************/ /* STACK */ /***************************************************************************/ function Stack (){ var st = []; this.empty = function (){ return !st.length; }; this.add = function(v){ st.push(v); }; this.get = function (){ return st.length ? st[0] : false; }; this.ack = function (){ st.shift(); }; } /***************************************************************************/ /* TASK */ /***************************************************************************/ function Task(ctx, onEnd, todo){ var session = {}, that = this, current, resolve = { latLng:{ // function => bool (=> address = latLng) map:false, marker:false, infowindow:false, circle:false, overlay: false, getlatlng: false, getmaxzoom: false, getelevation: false, streetviewpanorama: false, getaddress: true }, geoloc:{ getgeoloc: true } }; if (typeof todo === "string"){ todo = unify(todo); } function unify(todo){ var result = {}; result[todo] = {}; return result; } function next(){ var k; for(k in todo){ if (k in session){ // already run continue; } return k; } } this.run = function (){ var k, opts; while(k = next()){ if (typeof ctx[k] === "function"){ current = k; opts = $.extend(true, {}, defaults[k] || {}, todo[k].options || {}); if (k in resolve.latLng){ if (todo[k].values){ resolveAllLatLng(todo[k].values, ctx, ctx[k], {todo:todo[k], opts:opts, session:session}); } else { resolveLatLng(ctx, ctx[k], resolve.latLng[k], {todo:todo[k], opts:opts, session:session}); } } else if (k in resolve.geoloc){ geoloc(ctx, ctx[k], {todo:todo[k], opts:opts, session:session}); } else { ctx[k].apply(ctx, [{todo:todo[k], opts:opts, session:session}]); } return; // wait until ack } else { session[k] = null; } } onEnd.apply(ctx, [todo, session]); }; this.ack = function(result){ session[current] = result; that.run.apply(that, []); }; } function getKeys(obj){ var k, keys = []; for(k in obj){ keys.push(k); } return keys; } function tuple(args, value){ var todo = {}; // "copy" the common data if (args.todo){ for(var k in args.todo){ if ((k !== "options") && (k !== "values")){ todo[k] = args.todo[k]; } } } // "copy" some specific keys from value first else args.todo var i, keys = ["data", "tag", "id", "events", "onces"]; for(i=0; i<keys.length; i++){ copyKey(todo, keys[i], value, args.todo); } // create an extended options todo.options = $.extend({}, args.opts || {}, value.options || {}); return todo; } /** * copy a key content **/ function copyKey(target, key){ for(var i=2; i<arguments.length; i++){ if (key in arguments[i]){ target[key] = arguments[i][key]; return; } } } /***************************************************************************/ /* GEOCODERCACHE */ /***************************************************************************/ function GeocoderCache(){ var cache = []; this.get = function(request){ if (cache.length){ var i, j, k, item, eq, keys = getKeys(request); for(i=0; i<cache.length; i++){ item = cache[i]; eq = keys.length == item.keys.length; for(j=0; (j<keys.length) && eq; j++){ k = keys[j]; eq = k in item.request; if (eq){ if ((typeof request[k] === "object") && ("equals" in request[k]) && (typeof request[k] === "function")){ eq = request[k].equals(item.request[k]); } else{ eq = request[k] === item.request[k]; } } } if (eq){ return item.results; } } } }; this.store = function(request, results){ cache.push({request:request, keys:getKeys(request), results:results}); }; } /***************************************************************************/ /* OVERLAYVIEW */ /***************************************************************************/ function OverlayView(map, opts, latLng, $div) { var that = this, listeners = []; defaults.classes.OverlayView.call(this); this.setMap(map); this.onAdd = function() { var panes = this.getPanes(); if (opts.pane in panes) { $(panes[opts.pane]).append($div); } $.each("dblclick click mouseover mousemove mouseout mouseup mousedown".split(" "), function(i, name){ listeners.push( google.maps.event.addDomListener($div[0], name, function(e) { $.Event(e).stopPropagation(); google.maps.event.trigger(that, name, [e]); }) ); }); listeners.push( google.maps.event.addDomListener($div[0], "contextmenu", function(e) { $.Event(e).stopPropagation(); google.maps.event.trigger(that, "rightclick", [e]); }) ); this.draw(); }; this.getPosition = function(){ return latLng; }; this.draw = function() { this.draw = function() { var ps = this.getProjection().fromLatLngToDivPixel(latLng); $div .css("left", (ps.x+opts.offset.x) + "px") .css("top" , (ps.y+opts.offset.y) + "px"); } }; this.onRemove = function() { for (var i = 0; i < listeners.length; i++) { google.maps.event.removeListener(listeners[i]); } $div.remove(); }; this.hide = function() { $div.hide(); }; this.show = function() { $div.show(); }; this.toggle = function() { if ($div) { if ($div.is(":visible")){ this.show(); } else { this.hide(); } } }; this.toggleDOM = function() { if (this.getMap()) { this.setMap(null); } else { this.setMap(map); } }; this.getDOMElement = function() { return $div[0]; }; } /***************************************************************************/ /* CLUSTERING */ /***************************************************************************/ /** * Usefull to get a projection * => done in a function, to let dead-code analyser works without google library loaded **/ function newEmptyOverlay(map){ function Overlay(){ this.onAdd = function(){}; this.onRemove = function(){}; this.draw = function(){}; return defaults.classes.OverlayView.apply(this, []); } Overlay.prototype = defaults.classes.OverlayView.prototype; var obj = new Overlay(); obj.setMap(map); return obj; } /** * Class InternalClusterer * This class manage clusters thanks to "todo" objects * * Note: * Individuals marker are created on the fly thanks to the todo objects, they are * first set to null to keep the indexes synchronised with the todo list * This is the "display" function, set by the gmap3 object, which uses theses data * to create markers when clusters are not required * To remove a marker, the objects are deleted and set not null in arrays * markers[key] * = null : marker exist but has not been displayed yet * = false : marker has been removed **/ function InternalClusterer($container, map, radius, maxZoom){ var updating = false, updated = false, redrawing = false, ready = false, enabled = true, that = this, events = [], store = {}, // combin of index (id1-id2-...) => object ids = {}, // unique id => index markers = [], // index => marker todos = [], // index => todo or null if removed values = [], // index => value overlay = newEmptyOverlay(map), timer, projection, ffilter, fdisplay, ferror; // callback function main(); /** * return a marker by its id, null if not yet displayed and false if no exist or removed **/ this.getById = function(id){ return id in ids ? markers[ids[id]] : false; }; /** * remove a marker by its id **/ this.clearById = function(id){ if (id in ids){ var index = ids[id]; if (markers[index]){ // can be null markers[index].setMap(null); } delete markers[index]; markers[index] = false; delete todos[index]; todos[index] = false; delete values[index]; values[index] = false; delete ids[id]; updated = true; } }; // add a "marker todo" to the cluster this.add = function(todo, value){ todo.id = globalId(todo.id); this.clearById(todo.id); ids[todo.id] = markers.length; markers.push(null); // null = marker not yet created / displayed todos.push(todo); values.push(value); updated = true; }; // add a real marker to the cluster this.addMarker = function(marker, todo){ todo = todo || {}; todo.id = globalId(todo.id); this.clearById(todo.id); if (!todo.options){ todo.options = {}; } todo.options.position = marker.getPosition(); attachEvents($container, {todo:todo}, marker, todo.id); ids[todo.id] = markers.length; markers.push(marker); todos.push(todo); values.push(todo.data || {}); updated = true; }; // return a "marker todo" by its index this.todo = function(index){ return todos[index]; }; // return a "marker value" by its index this.value = function(index){ return values[index]; }; // return a marker by its index this.marker = function(index){ return markers[index]; }; // store a new marker instead if the default "false" this.setMarker = function(index, marker){ markers[index] = marker; }; // link the visible overlay to the logical data (to hide overlays later) this.store = function(cluster, obj, shadow){ store[cluster.ref] = {obj:obj, shadow:shadow}; }; // free all objects this.free = function(){ for(var i = 0; i < events.length; i++){ google.maps.event.removeListener(events[i]); } events = []; $.each(store, function(key){ flush(key); }); store = {}; $.each(todos, function(i){ todos[i] = null; }); todos = []; $.each(markers, function(i){ if (markers[i]){ // false = removed markers[i].setMap(null); delete markers[i]; } }); markers = []; $.each(values, function(i){ delete values[i]; }); values = []; ids = {}; }; // link the display function this.filter = function(f){ ffilter = f; redraw(); }; // enable/disable the clustering feature this.enable = function(value){ if (enabled != value){ enabled = value; redraw(); } }; // link the display function this.display = function(f){ fdisplay = f; }; // link the errorfunction this.error = function(f){ ferror = f; }; // lock the redraw this.beginUpdate = function(){ updating = true; }; // unlock the redraw this.endUpdate = function(){ updating = false; if (updated){ redraw(); } }; // extends current bounds with internal markers this.autofit = function(bounds){ for(var i=0; i<todos.length; i++){ if (todos[i]){ bounds.extend(todos[i].options.position); } } } // bind events function main(){ projection = overlay.getProjection(); if (!projection){ setTimeout(function(){ main.apply(that, []); }, 25); return; } ready = true; events.push(google.maps.event.addListener(map, "zoom_changed", function(){delayRedraw();})); events.push(google.maps.event.addListener(map, "bounds_changed", function(){delayRedraw();})); redraw(); } // flush overlays function flush(key){ if (typeof store[key] === "object"){ // is overlay if (typeof(store[key].obj.setMap) === "function") { store[key].obj.setMap(null); } if (typeof(store[key].obj.remove) === "function") { store[key].obj.remove(); } if (typeof(store[key].shadow.remove) === "function") { store[key].obj.remove(); } if (typeof(store[key].shadow.setMap) === "function") { store[key].shadow.setMap(null); } delete store[key].obj; delete store[key].shadow; } else if (markers[key]){ // marker not removed markers[key].setMap(null); // don't remove the marker object, it may be displayed later } delete store[key]; } /** * return the distance between 2 latLng couple into meters * Params : * Lat1, Lng1, Lat2, Lng2 * LatLng1, Lat2, Lng2 * Lat1, Lng1, LatLng2 * LatLng1, LatLng2 **/ function distanceInMeter(){ var lat1, lat2, lng1, lng2, e, f, g, h; if (arguments[0] instanceof google.maps.LatLng){ lat1 = arguments[0].lat(); lng1 = arguments[0].lng(); if (arguments[1] instanceof google.maps.LatLng){ lat2 = arguments[1].lat(); lng2 = arguments[1].lng(); } else { lat2 = arguments[1]; lng2 = arguments[2]; } } else { lat1 = arguments[0]; lng1 = arguments[1]; if (arguments[2] instanceof google.maps.LatLng){ lat2 = arguments[2].lat(); lng2 = arguments[2].lng(); } else { lat2 = arguments[2]; lng2 = arguments[3]; } } e = Math.PI*lat1/180; f = Math.PI*lng1/180; g = Math.PI*lat2/180; h = Math.PI*lng2/180; return 1000*6371 * Math.acos(Math.min(Math.cos(e)*Math.cos(g)*Math.cos(f)*Math.cos(h)+Math.cos(e)*Math.sin(f)*Math.cos(g)*Math.sin(h)+Math.sin(e)*Math.sin(g),1)); } // extend the visible bounds function extendsMapBounds(){ var radius = distanceInMeter(map.getCenter(), map.getBounds().getNorthEast()), circle = new google.maps.Circle({ center: map.getCenter(), radius: 1.25 * radius // + 25% }); return circle.getBounds(); } // return an object where keys are store keys function getStoreKeys(){ var keys = {}, k; for(k in store){ keys[k] = true; } return keys; } // async the delay function function delayRedraw(){ clearTimeout(timer); timer = setTimeout(function(){ redraw(); }, 25); } // generate bounds extended by radius function extendsBounds(latLng) { var p = projection.fromLatLngToDivPixel(latLng), ne = projection.fromDivPixelToLatLng(new google.maps.Point(p.x+radius, p.y-radius)), sw = projection.fromDivPixelToLatLng(new google.maps.Point(p.x-radius, p.y+radius)); return new google.maps.LatLngBounds(sw, ne); } // run the clustering process and call the display function function redraw(){ if (updating || redrawing || !ready){ return; } var keys = [], used = {}, zoom = map.getZoom(), forceDisabled = (maxZoom !== undef) && (zoom > maxZoom), previousKeys = getStoreKeys(), i, j, k, lat, lng, indexes, previous, check = false, bounds, cluster; // reset flag updated = false; if (zoom > 3){ // extend the bounds of the visible map to manage clusters near the boundaries bounds = extendsMapBounds(); // check contain only if boundaries are valid check = bounds.getSouthWest().lng() < bounds.getNorthEast().lng(); } // calculate positions of "visibles" markers (in extended bounds) for(i=0; i<todos.length; i++){ if (todos[i] && (!check || bounds.contains(todos[i].options.position)) && (!ffilter || ffilter(values[i]))){ keys.push(i); } } // for each "visible" marker, search its neighbors to create a cluster // we can't do a classical "for" loop, because, analysis can bypass a marker while focusing on cluster while(1){ i=0; while(used[i] && (i<keys.length)){ // look for the next marker not used i++; } if (i == keys.length){ break; } indexes = []; if (enabled && !forceDisabled){ do{ previous = indexes; indexes = []; if (previous.length){ // re-evaluates center lat = lng = 0; for(k=0; k<previous.length; k++){ lat += todos[ keys[previous[k]] ].options.position.lat(); lng += todos[ keys[previous[k]] ].options.position.lng(); } lat /= previous.length; lng /= previous.length; bounds = extendsBounds(new google.maps.LatLng(lat, lng)); } else { bounds = extendsBounds(todos[ keys[i] ].options.position); } for(j=i; j<keys.length; j++){ if (used[j]){ continue; } if (bounds.contains(todos[ keys[j] ].options.position)){ indexes.push(j); } } } while( (previous.length < indexes.length) && (indexes.length > 1) ); } else { for(j=i; j<keys.length; j++){ if (used[j]){ continue; } indexes.push(j); break; } } cluster = {latLng:bounds.getCenter(), indexes:[], ref:[]}; for(k=0; k<indexes.length; k++){ used[ indexes[k] ] = true; cluster.indexes.push(keys[indexes[k]]); cluster.ref.push(keys[indexes[k]]); } cluster.ref = cluster.ref.join("-"); if (cluster.ref in previousKeys){ // cluster doesn't change delete previousKeys[cluster.ref]; // remove this entry, these still in this array will be removed } else { // cluster is new if (indexes.length === 1){ // alone markers are not stored, so need to keep the key (else, will be displayed every time and marker will blink) store[cluster.ref] = true; } // use a closure to async the display call make faster the process of cle clustering (function(cl){ setTimeout(function(){ fdisplay(cl); // while displaying, will use store to link object }, 1); })(cluster); } } // flush the previous overlays which are not still used $.each(previousKeys, function(key){ flush(key); }); redrawing = false; } } /** * Class Clusterer * a facade with limited method for external use **/ function Clusterer(id, internalClusterer){ this.id = function(){ return id; }; this.filter = function(f){ internalClusterer.filter(f); }; this.enable = function(){ internalClusterer.enable(true); }; this.disable = function(){ internalClusterer.enable(false); }; this.add = function(marker, todo, lock){ if (!lock) { internalClusterer.beginUpdate(); } internalClusterer.addMarker(marker, todo); if (!lock) { internalClusterer.endUpdate(); } }; this.getById = function(id){ return internalClusterer.getById(id); }; this.clearById = function(id, lock){ if (!lock) { internalClusterer.beginUpdate(); } internalClusterer.clearById(id); if (!lock) { internalClusterer.endUpdate(); } }; } /***************************************************************************/ /* STORE */ /***************************************************************************/ function Store(){ var store = {}, // name => [id, ...] objects = {}; // id => object function ftag(tag){ if (tag){ if (typeof tag === "function"){ return tag; } tag = array(tag); return function(val){ if (val === undef){ return false; } if (typeof val === "object"){ for(var i=0; i<val.length; i++){ if($.inArray(val[i], tag) >= 0){ return true; } } return false; } return $.inArray(val, tag) >= 0; } } } function normalize(res) { return { id: res.id, name: res.name, object:res.obj, tag:res.tag, data:res.data }; } /** * add a mixed to the store **/ this.add = function(args, name, obj, sub){ var todo = args.todo || {}, id = globalId(todo.id); if (!store[name]){ store[name] = []; } if (id in objects){ // object already exists: remove it this.clearById(id); } objects[id] = {obj:obj, sub:sub, name:name, id:id, tag:todo.tag, data:todo.data}; store[name].push(id); return id; }; /** * return a stored object by its id **/ this.getById = function(id, sub, full){ if (id in objects){ if (sub) { return objects[id].sub } else if (full) { return normalize(objects[id]); } return objects[id].obj; } return false; }; /** * return a stored value **/ this.get = function(name, last, tag, full){ var n, id, check = ftag(tag); if (!store[name] || !store[name].length){ return null; } n = store[name].length; while(n){ n--; id = store[name][last ? n : store[name].length - n - 1]; if (id && objects[id]){ if (check && !check(objects[id].tag)){ continue; } return full ? normalize(objects[id]) : objects[id].obj; } } return null; }; /** * return all stored values **/ this.all = function(name, tag, full){ var result = [], check = ftag(tag), find = function(n){ var i, id; for(i=0; i<store[n].length; i++){ id = store[n][i]; if (id && objects[id]){ if (check && !check(objects[id].tag)){ continue; } result.push(full ? normalize(objects[id]) : objects[id].obj); } } }; if (name in store){ find(name); } else if (name === undef){ // internal use only for(name in store){ find(name); } } return result; }; /** * hide and remove an object **/ function rm(obj){ // Google maps element if (typeof(obj.setMap) === "function") { obj.setMap(null); } // jQuery if (typeof(obj.remove) === "function") { obj.remove(); } // internal (cluster) if (typeof(obj.free) === "function") { obj.free(); } obj = null; } /** * remove one object from the store **/ this.rm = function(name, check, pop){ var idx, id; if (!store[name]) { return false; } if (check){ if (pop){ for(idx = store[name].length - 1; idx >= 0; idx--){ id = store[name][idx]; if ( check(objects[id].tag) ){ break; } } } else { for(idx = 0; idx < store[name].length; idx++){ id = store[name][idx]; if (check(objects[id].tag)){ break; } } } } else { idx = pop ? store[name].length - 1 : 0; } if ( !(idx in store[name]) ) { return false; } return this.clearById(store[name][idx], idx); }; /** * remove object from the store by its id **/ this.clearById = function(id, idx){ if (id in objects){ var i, name = objects[id].name; for(i=0; idx === undef && i<store[name].length; i++){ if (id === store[name][i]){ idx = i; } } rm(objects[id].obj); if(objects[id].sub){ rm(objects[id].sub); } delete objects[id]; store[name].splice(idx, 1); return true; } return false; }; /** * return an object from a container object in the store by its id * ! for now, only cluster manage this feature **/ this.objGetById = function(id){ var result; if (store["clusterer"]) { for(var idx in store["clusterer"]){ if ((result = objects[store["clusterer"][idx]].obj.getById(id)) !== false){ return result; } } } return false; }; /** * remove object from a container object in the store by its id * ! for now, only cluster manage this feature **/ this.objClearById = function(id){ if (store["clusterer"]) { for(var idx in store["clusterer"]){ if (objects[store["clusterer"][idx]].obj.clearById(id)){ return true; } } } return null; }; /** * remove objects from the store **/ this.clear = function(list, last, first, tag){ var k, i, name, check = ftag(tag); if (!list || !list.length){ list = []; for(k in store){ list.push(k); } } else { list = array(list); } for(i=0; i<list.length; i++){ if (list[i]){ name = list[i]; if (!store[name]){ continue; } if (last){ this.rm(name, check, true); } else if (first){ this.rm(name, check, false); } else { // all while(this.rm(name, check, false)); } } } }; } /***************************************************************************/ /* GMAP3 GLOBALS */ /***************************************************************************/ var services = {}, geocoderCache = new GeocoderCache(); //-----------------------------------------------------------------------// // Service tools //-----------------------------------------------------------------------// function geocoder(){ if (!services.geocoder) { services.geocoder = new google.maps.Geocoder(); } return services.geocoder; } function directionsService(){ if (!services.directionsService) { services.directionsService = new google.maps.DirectionsService(); } return services.directionsService; } function elevationService(){ if (!services.elevationService) { services.elevationService = new google.maps.ElevationService(); } return services.elevationService; } function maxZoomService(){ if (!services.maxZoomService) { services.maxZoomService = new google.maps.MaxZoomService(); } return services.maxZoomService; } function distanceMatrixService(){ if (!services.distanceMatrixService) { services.distanceMatrixService = new google.maps.DistanceMatrixService(); } return services.distanceMatrixService; } //-----------------------------------------------------------------------// // Unit tools //-----------------------------------------------------------------------// function error(){ if (defaults.verbose){ var i, err = []; if (window.console && (typeof console.error === "function") ){ for(i=0; i<arguments.length; i++){ err.push(arguments[i]); } console.error.apply(console, err); } else { err = ""; for(i=0; i<arguments.length; i++){ err += arguments[i].toString() + " " ; } alert(err); } } } /** * return true if mixed is usable as number **/ function numeric(mixed){ return (typeof(mixed) === "number" || typeof(mixed) === "string") && mixed !== "" && !isNaN(mixed); } /** * convert data to array **/ function array(mixed){ var k, a = []; if (mixed !== undef){ if (typeof(mixed) === "object"){ if (typeof(mixed.length) === "number") { a = mixed; } else { for(k in mixed) { a.push(mixed[k]); } } } else{ a.push(mixed); } } return a; } /** * convert mixed [ lat, lng ] objet to google.maps.LatLng **/ function toLatLng (mixed, emptyReturnMixed, noFlat){ var empty = emptyReturnMixed ? mixed : null; if (!mixed || (typeof mixed === "string")){ return empty; } // defined latLng if (mixed.latLng) { return toLatLng(mixed.latLng); } // google.maps.LatLng object if (mixed instanceof google.maps.LatLng) { return mixed; } // {lat:X, lng:Y} object else if ( numeric(mixed.lat) ) { return new google.maps.LatLng(mixed.lat, mixed.lng); } // [X, Y] object else if ( !noFlat && $.isArray(mixed)){ if ( !numeric(mixed[0]) || !numeric(mixed[1]) ) { return empty; } return new google.maps.LatLng(mixed[0], mixed[1]); } return empty; } /** * convert mixed [ sw, ne ] object by google.maps.LatLngBounds **/ function toLatLngBounds(mixed){ var ne, sw; if (!mixed || mixed instanceof google.maps.LatLngBounds) { return mixed || null; } if ($.isArray(mixed)){ if (mixed.length == 2){ ne = toLatLng(mixed[0]); sw = toLatLng(mixed[1]); } else if (mixed.length == 4){ ne = toLatLng([mixed[0], mixed[1]]); sw = toLatLng([mixed[2], mixed[3]]); } } else { if ( ("ne" in mixed) && ("sw" in mixed) ){ ne = toLatLng(mixed.ne); sw = toLatLng(mixed.sw); } else if ( ("n" in mixed) && ("e" in mixed) && ("s" in mixed) && ("w" in mixed) ){ ne = toLatLng([mixed.n, mixed.e]); sw = toLatLng([mixed.s, mixed.w]); } } if (ne && sw){ return new google.maps.LatLngBounds(sw, ne); } return null; } /** * resolveLatLng **/ function resolveLatLng(ctx, method, runLatLng, args, attempt){ var latLng = runLatLng ? toLatLng(args.todo, false, true) : false, conf = latLng ? {latLng:latLng} : (args.todo.address ? (typeof(args.todo.address) === "string" ? {address:args.todo.address} : args.todo.address) : false), cache = conf ? geocoderCache.get(conf) : false, that = this; if (conf){ attempt = attempt || 0; // convert undefined to int if (cache){ args.latLng = cache.results[0].geometry.location; args.results = cache.results; args.status = cache.status; method.apply(ctx, [args]); } else { if (conf.location){ conf.location = toLatLng(conf.location); } if (conf.bounds){ conf.bounds = toLatLngBounds(conf.bounds); } geocoder().geocode( conf, function(results, status) { if (status === google.maps.GeocoderStatus.OK){ geocoderCache.store(conf, {results:results, status:status}); args.latLng = results[0].geometry.location; args.results = results; args.status = status; method.apply(ctx, [args]); } else if ( (status === google.maps.GeocoderStatus.OVER_QUERY_LIMIT) && (attempt < defaults.queryLimit.attempt) ){ setTimeout( function(){ resolveLatLng.apply(that, [ctx, method, runLatLng, args, attempt+1]); }, defaults.queryLimit.delay + Math.floor(Math.random() * defaults.queryLimit.random) ); } else { error("geocode failed", status, conf); args.latLng = args.results = false; args.status = status; method.apply(ctx, [args]); } } ); } } else { args.latLng = toLatLng(args.todo, false, true); method.apply(ctx, [args]); } } function resolveAllLatLng(list, ctx, method, args){ var that = this, i = -1; function resolve(){ // look for next address to resolve do{ i++; }while( (i < list.length) && !("address" in list[i]) ); // no address found, so run method if (i >= list.length){ method.apply(ctx, [args]); return; } resolveLatLng( that, function(args){ delete args.todo; $.extend(list[i], args); resolve.apply(that, []); // resolve next (using apply avoid too much recursion) }, true, {todo:list[i]} ); } resolve(); } /** * geolocalise the user and return a LatLng **/ function geoloc(ctx, method, args){ var is_echo = false; // sometime, a kind of echo appear, this trick will notice once the first call is run to ignore the next one if (navigator && navigator.geolocation){ navigator.geolocation.getCurrentPosition( function(pos) { if (is_echo){ return; } is_echo = true; args.latLng = new google.maps.LatLng(pos.coords.latitude,pos.coords.longitude); method.apply(ctx, [args]); }, function() { if (is_echo){ return; } is_echo = true; args.latLng = false; method.apply(ctx, [args]); }, args.opts.getCurrentPosition ); } else { args.latLng = false; method.apply(ctx, [args]); } } /***************************************************************************/ /* GMAP3 */ /***************************************************************************/ function Gmap3($this){ var that = this, stack = new Stack(), store = new Store(), map = null, task; //-----------------------------------------------------------------------// // Stack tools //-----------------------------------------------------------------------// /** * store actions to execute in a stack manager **/ this._plan = function(list){ for(var k = 0; k < list.length; k++) { stack.add(new Task(that, end, list[k])); } run(); }; /** * if not running, start next action in stack **/ function run(){ if (!task && (task = stack.get())){ task.run(); } } /** * called when action in finished, to acknoledge the current in stack and start next one **/ function end(){ task = null; stack.ack(); run.call(that); // restart to high level scope } //-----------------------------------------------------------------------// // Tools //-----------------------------------------------------------------------// /** * execute callback functions **/ function callback(args){ var i, params = []; for(i=1; i<arguments.length; i++){ params.push(arguments[i]); } if (typeof args.todo.callback === "function") { args.todo.callback.apply($this, params); } else if (typeof args.todo.callback === "object") { $.each(args.todo.callback, function(i, cb){ if (typeof cb === "function") { cb.apply($this, params); } }); } } /** * execute ending functions **/ function manageEnd(args, obj, id){ if (id){ attachEvents($this, args, obj, id); } callback(args, obj); task.ack(obj); } /** * initialize the map if not yet initialized **/ function newMap(latLng, args){ args = args || {}; if (map) { if (args.todo && args.todo.options){ map.setOptions(args.todo.options); } } else { var opts = args.opts || $.extend(true, {}, defaults.map, args.todo && args.todo.options ? args.todo.options : {}); opts.center = latLng || toLatLng(opts.center); map = new defaults.classes.Map($this.get(0), opts); } } /* = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = => function with latLng resolution = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = */ /** * Initialize google.maps.Map object **/ this.map = function(args){ newMap(args.latLng, args); attachEvents($this, args, map); manageEnd(args, map); }; /** * destroy an existing instance **/ this.destroy = function(args){ store.clear(); $this.empty(); if (map){ map = null; } manageEnd(args, true); }; /** * add an infowindow **/ this.infowindow = function(args){ var objs = [], multiple = "values" in args.todo; if (!multiple){ if (args.latLng) { args.opts.position = args.latLng; } else if (args.opts.position){ args.opts.position = toLatLng(args.opts.position); } args.todo.values = [{options:args.opts}]; } $.each(args.todo.values, function(i, value){ var id, obj, todo = tuple(args, value); if (!map){ newMap(todo.options.position); } obj = new defaults.classes.InfoWindow(todo.options); if (obj && ((todo.open === undef) || todo.open)){ if (multiple){ obj.open(map, todo.anchor ? todo.anchor : undef); } else { obj.open(map, todo.anchor ? todo.anchor : (args.latLng ? undef : (args.session.marker ? args.session.marker : undef))); } } objs.push(obj); id = store.add({todo:todo}, "infowindow", obj); attachEvents($this, {todo:todo}, obj, id); }); manageEnd(args, multiple ? objs : objs[0]); }; /** * add a circle **/ this.circle = function(args){ var objs = [], multiple = "values" in args.todo; if (!multiple){ args.opts.center = args.latLng || toLatLng(args.opts.center); args.todo.values = [{options:args.opts}]; } if (!args.todo.values.length){ manageEnd(args, false); return; } $.each(args.todo.values, function(i, value){ var id, obj, todo = tuple(args, value); todo.options.center = todo.options.center ? toLatLng(todo.options.center) : toLatLng(value); if (!map){ newMap(todo.options.center); } todo.options.map = map; obj = new defaults.classes.Circle(todo.options); objs.push(obj); id = store.add({todo:todo}, "circle", obj); attachEvents($this, {todo:todo}, obj, id); }); manageEnd(args, multiple ? objs : objs[0]); }; /** * add an overlay **/ this.overlay = function(args, internal){ var objs = [], multiple = "values" in args.todo; if (!multiple){ args.todo.values = [{latLng: args.latLng, options: args.opts}]; } if (!args.todo.values.length){ manageEnd(args, false); return; } if (!OverlayView.__initialised) { OverlayView.prototype = new defaults.classes.OverlayView(); OverlayView.__initialised = true; } $.each(args.todo.values, function(i, value){ var id, obj, todo = tuple(args, value), $div = $(document.createElement("div")).css({ border: "none", borderWidth: "0px", position: "absolute" }); $div.append(todo.options.content); obj = new OverlayView(map, todo.options, toLatLng(todo) || toLatLng(value), $div); objs.push(obj); $div = null; // memory leak if (!internal){ id = store.add(args, "overlay", obj); attachEvents($this, {todo:todo}, obj, id); } }); if (internal){ return objs[0]; } manageEnd(args, multiple ? objs : objs[0]); }; /** * returns address structure from latlng **/ this.getaddress = function(args){ callback(args, args.results, args.status); task.ack(); }; /** * returns latlng from an address **/ this.getlatlng = function(args){ callback(args, args.results, args.status); task.ack(); }; /** * return the max zoom of a location **/ this.getmaxzoom = function(args){ maxZoomService().getMaxZoomAtLatLng( args.latLng, function(result) { callback(args, result.status === google.maps.MaxZoomStatus.OK ? result.zoom : false, status); task.ack(); } ); }; /** * return the elevation of a location **/ this.getelevation = function(args){ var i, locations = [], f = function(results, status){ callback(args, status === google.maps.ElevationStatus.OK ? results : false, status); task.ack(); }; if (args.latLng){ locations.push(args.latLng); } else { locations = array(args.todo.locations || []); for(i=0; i<locations.length; i++){ locations[i] = toLatLng(locations[i]); } } if (locations.length){ elevationService().getElevationForLocations({locations:locations}, f); } else { if (args.todo.path && args.todo.path.length){ for(i=0; i<args.todo.path.length; i++){ locations.push(toLatLng(args.todo.path[i])); } } if (locations.length){ elevationService().getElevationAlongPath({path:locations, samples:args.todo.samples}, f); } else { task.ack(); } } }; /* = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = => function without latLng resolution = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = */ /** * define defaults values **/ this.defaults = function(args){ $.each(args.todo, function(name, value){ if (typeof defaults[name] === "object"){ defaults[name] = $.extend({}, defaults[name], value); } else { defaults[name] = value; } }); task.ack(true); }; /** * add a rectangle **/ this.rectangle = function(args){ var objs = [], multiple = "values" in args.todo; if (!multiple){ args.todo.values = [{options:args.opts}]; } if (!args.todo.values.length){ manageEnd(args, false); return; } $.each(args.todo.values, function(i, value){ var id, obj, todo = tuple(args, value); todo.options.bounds = todo.options.bounds ? toLatLngBounds(todo.options.bounds) : toLatLngBounds(value); if (!map){ newMap(todo.options.bounds.getCenter()); } todo.options.map = map; obj = new defaults.classes.Rectangle(todo.options); objs.push(obj); id = store.add({todo:todo}, "rectangle", obj); attachEvents($this, {todo:todo}, obj, id); }); manageEnd(args, multiple ? objs : objs[0]); }; /** * add a polygone / polyline **/ function poly(args, poly, path){ var objs = [], multiple = "values" in args.todo; if (!multiple){ args.todo.values = [{options:args.opts}]; } if (!args.todo.values.length){ manageEnd(args, false); return; } newMap(); $.each(args.todo.values, function(_, value){ var id, i, j, obj, todo = tuple(args, value); if (todo.options[path]){ if (todo.options[path][0][0] && $.isArray(todo.options[path][0][0])){ for(i=0; i<todo.options[path].length; i++){ for(j=0; j<todo.options[path][i].length; j++){ todo.options[path][i][j] = toLatLng(todo.options[path][i][j]); } } } else { for(i=0; i<todo.options[path].length; i++){ todo.options[path][i] = toLatLng(todo.options[path][i]); } } } todo.options.map = map; obj = new google.maps[poly](todo.options); objs.push(obj); id = store.add({todo:todo}, poly.toLowerCase(), obj); attachEvents($this, {todo:todo}, obj, id); }); manageEnd(args, multiple ? objs : objs[0]); } this.polyline = function(args){ poly(args, "Polyline", "path"); }; this.polygon = function(args){ poly(args, "Polygon", "paths"); }; /** * add a traffic layer **/ this.trafficlayer = function(args){ newMap(); var obj = store.get("trafficlayer"); if (!obj){ obj = new defaults.classes.TrafficLayer(); obj.setMap(map); store.add(args, "trafficlayer", obj); } manageEnd(args, obj); }; /** * add a bicycling layer **/ this.bicyclinglayer = function(args){ newMap(); var obj = store.get("bicyclinglayer"); if (!obj){ obj = new defaults.classes.BicyclingLayer(); obj.setMap(map); store.add(args, "bicyclinglayer", obj); } manageEnd(args, obj); }; /** * add a ground overlay **/ this.groundoverlay = function(args){ args.opts.bounds = toLatLngBounds(args.opts.bounds); if (args.opts.bounds){ newMap(args.opts.bounds.getCenter()); } var id, obj = new defaults.classes.GroundOverlay(args.opts.url, args.opts.bounds, args.opts.opts); obj.setMap(map); id = store.add(args, "groundoverlay", obj); manageEnd(args, obj, id); }; /** * set a streetview **/ this.streetviewpanorama = function(args){ if (!args.opts.opts){ args.opts.opts = {}; } if (args.latLng){ args.opts.opts.position = args.latLng; } else if (args.opts.opts.position){ args.opts.opts.position = toLatLng(args.opts.opts.position); } if (args.todo.divId){ args.opts.container = document.getElementById(args.todo.divId) } else if (args.opts.container){ args.opts.container = $(args.opts.container).get(0); } var id, obj = new defaults.classes.StreetViewPanorama(args.opts.container, args.opts.opts); if (obj){ map.setStreetView(obj); } id = store.add(args, "streetviewpanorama", obj); manageEnd(args, obj, id); }; this.kmllayer = function(args){ var objs = [], multiple = "values" in args.todo; if (!multiple){ args.todo.values = [{options:args.opts}]; } if (!args.todo.values.length){ manageEnd(args, false); return; } $.each(args.todo.values, function(i, value){ var id, obj, todo = tuple(args, value); if (!map){ newMap(); } todo.options.opts.map = map; obj = new defaults.classes.KmlLayer(todo.options.url, todo.options.opts); objs.push(obj); id = store.add({todo:todo}, "kmllayer", obj); attachEvents($this, {todo:todo}, obj, id); }); manageEnd(args, multiple ? objs : objs[0]); }; /** * add a fix panel **/ this.panel = function(args){ newMap(); var id, x= 0, y=0, $content, $div = $(document.createElement("div")); $div.css({ position: "absolute", zIndex: 1000, visibility: "hidden" }); if (args.opts.content){ $content = $(args.opts.content); $div.append($content); $this.first().prepend($div); if (args.opts.left !== undef){ x = args.opts.left; } else if (args.opts.right !== undef){ x = $this.width() - $content.width() - args.opts.right; } else if (args.opts.center){ x = ($this.width() - $content.width()) / 2; } if (args.opts.top !== undef){ y = args.opts.top; } else if (args.opts.bottom !== undef){ y = $this.height() - $content.height() - args.opts.bottom; } else if (args.opts.middle){ y = ($this.height() - $content.height()) / 2 } $div.css({ top: y, left: x, visibility: "visible" }); } id = store.add(args, "panel", $div); manageEnd(args, $div, id); $div = null; // memory leak }; /** * Create an InternalClusterer object **/ function createClusterer(raw){ var internalClusterer = new InternalClusterer($this, map, raw.radius, raw.maxZoom), todo = {}, styles = {}, isInt = /^[0-9]+$/, calculator, k; for(k in raw){ if (isInt.test(k)){ styles[k] = raw[k]; styles[k].width = styles[k].width || 0; styles[k].height = styles[k].height || 0; } else { todo[k] = raw[k]; } } // external calculator if (todo.calculator){ calculator = function(indexes){ var data = []; $.each(indexes, function(i, index){ data.push(internalClusterer.value(index)); }); return todo.calculator.apply($this, [data]); }; } else { calculator = function(indexes){ return indexes.length; }; } // set error function internalClusterer.error(function(){ error.apply(that, arguments); }); // set display function internalClusterer.display(function(cluster){ var k, style, n = 0, atodo, obj, offset, cnt = calculator(cluster.indexes); // look for the style to use if (cnt > 1){ for(k in styles){ k = 1 * k; // cast to int if (k > n && k <= cnt){ n = k; } } style = styles[n]; } if (style){ offset = style.offset || [-style.width/2, -style.height/2]; // create a custom overlay command // nb: 2 extends are faster that a deeper extend atodo = $.extend({}, todo); atodo.options = $.extend({ pane: "overlayLayer", content:style.content ? style.content.replace("CLUSTER_COUNT", cnt) : "", offset:{ x: ("x" in offset ? offset.x : offset[0]) || 0, y: ("y" in offset ? offset.y : offset[1]) || 0 } }, todo.options || {}); obj = that.overlay({todo:atodo, opts:atodo.options, latLng:toLatLng(cluster)}, true); atodo.options.pane = "floatShadow"; atodo.options.content = $(document.createElement("div")).width(style.width+"px").height(style.height+"px"); shadow = that.overlay({todo:atodo, opts:atodo.options, latLng:toLatLng(cluster)}, true); // store data to the clusterer todo.data = { latLng: toLatLng(cluster), markers:[] }; $.each(cluster.indexes, function(i, index){ todo.data.markers.push(internalClusterer.value(index)); if (internalClusterer.marker(index)){ internalClusterer.marker(index).setMap(null); } }); attachEvents($this, {todo:todo}, shadow, undef, {main:obj, shadow:shadow}); internalClusterer.store(cluster, obj, shadow); } else { $.each(cluster.indexes, function(i, index){ if (internalClusterer.marker(index)){ internalClusterer.marker(index).setMap(map); } else { var todo = internalClusterer.todo(index), marker = new defaults.classes.Marker(todo.options); internalClusterer.setMarker(index, marker); attachEvents($this, {todo:todo}, marker, todo.id); } }); } }); return internalClusterer; } /** * add a marker **/ this.marker = function(args){ var multiple = "values" in args.todo, init = !map; if (!multiple){ args.opts.position = args.latLng || toLatLng(args.opts.position); args.todo.values = [{options:args.opts}]; } if (!args.todo.values.length){ manageEnd(args, false); return; } if (init){ newMap(); } if (args.todo.cluster && !map.getBounds()){ // map not initialised => bounds not available : wait for map if clustering feature is required google.maps.event.addListenerOnce(map, "bounds_changed", function() { that.marker.apply(that, [args]); }); return; } if (args.todo.cluster){ var clusterer, internalClusterer; if (args.todo.cluster instanceof Clusterer){ clusterer = args.todo.cluster; internalClusterer = store.getById(clusterer.id(), true); } else { internalClusterer = createClusterer(args.todo.cluster); clusterer = new Clusterer(globalId(args.todo.id, true), internalClusterer); store.add(args, "clusterer", clusterer, internalClusterer); } internalClusterer.beginUpdate(); $.each(args.todo.values, function(i, value){ var todo = tuple(args, value); todo.options.position = todo.options.position ? toLatLng(todo.options.position) : toLatLng(value); todo.options.map = map; if (init){ map.setCenter(todo.options.position); init = false; } internalClusterer.add(todo, value); }); internalClusterer.endUpdate(); manageEnd(args, clusterer); } else { var objs = []; $.each(args.todo.values, function(i, value){ var id, obj, todo = tuple(args, value); todo.options.position = todo.options.position ? toLatLng(todo.options.position) : toLatLng(value); todo.options.map = map; if (init){ map.setCenter(todo.options.position); init = false; } obj = new defaults.classes.Marker(todo.options); objs.push(obj); id = store.add({todo:todo}, "marker", obj); attachEvents($this, {todo:todo}, obj, id); }); manageEnd(args, multiple ? objs : objs[0]); } }; /** * return a route **/ this.getroute = function(args){ args.opts.origin = toLatLng(args.opts.origin, true); args.opts.destination = toLatLng(args.opts.destination, true); directionsService().route( args.opts, function(results, status) { callback(args, status == google.maps.DirectionsStatus.OK ? results : false, status); task.ack(); } ); }; /** * add a direction renderer **/ this.directionsrenderer = function(args){ args.opts.map = map; var id, obj = new google.maps.DirectionsRenderer(args.opts); if (args.todo.divId){ obj.setPanel(document.getElementById(args.todo.divId)); } else if (args.todo.container){ obj.setPanel($(args.todo.container).get(0)); } id = store.add(args, "directionrenderer", obj); manageEnd(args, obj, id); }; /** * returns latLng of the user **/ this.getgeoloc = function(args){ manageEnd(args, args.latLng); }; /** * add a style **/ this.styledmaptype = function(args){ newMap(); var obj = new defaults.classes.StyledMapType(args.todo.styles, args.opts); map.mapTypes.set(args.todo.id, obj); manageEnd(args, obj); }; /** * add an imageMapType **/ this.imagemaptype = function(args){ newMap(); var obj = new defaults.classes.ImageMapType(args.opts); map.mapTypes.set(args.todo.id, obj); manageEnd(args, obj); }; /** * autofit a map using its overlays (markers, rectangles ...) **/ this.autofit = function(args){ var bounds = new google.maps.LatLngBounds(); $.each(store.all(), function(i, obj){ if (obj.getPosition){ bounds.extend(obj.getPosition()); } else if (obj.getBounds){ bounds.extend(obj.getBounds().getNorthEast()); bounds.extend(obj.getBounds().getSouthWest()); } else if (obj.getPaths){ obj.getPaths().forEach(function(path){ path.forEach(function(latLng){ bounds.extend(latLng); }); }); } else if (obj.getPath){ obj.getPath().forEach(function(latLng){ bounds.extend(latLng);"" }); } else if (obj.getCenter){ bounds.extend(obj.getCenter()); } else if (obj instanceof Clusterer){ obj = store.getById(obj.id(), true); if (obj){ obj.autofit(bounds); } } }); if (!bounds.isEmpty() && (!map.getBounds() || !map.getBounds().equals(bounds))){ if ("maxZoom" in args.todo){ // fitBouds Callback event => detect zoom level and check maxZoom google.maps.event.addListenerOnce( map, "bounds_changed", function() { if (this.getZoom() > args.todo.maxZoom){ this.setZoom(args.todo.maxZoom); } } ); } map.fitBounds(bounds); } manageEnd(args, true); }; /** * remove objects from a map **/ this.clear = function(args){ if (typeof args.todo === "string"){ if (store.clearById(args.todo) || store.objClearById(args.todo)){ manageEnd(args, true); return; } args.todo = {name:args.todo}; } if (args.todo.id){ $.each(array(args.todo.id), function(i, id){ store.clearById(id); }); } else { store.clear(array(args.todo.name), args.todo.last, args.todo.first, args.todo.tag); } manageEnd(args, true); }; /** * run a function on each items selected **/ this.exec = function(args){ var that = this; $.each(array(args.todo.func), function(i, func){ $.each(that.get(args.todo, true, args.todo.hasOwnProperty("full") ? args.todo.full : true), function(j, res){ func.call($this, res); }); }); manageEnd(args, true); }; /** * return objects previously created **/ this.get = function(args, direct, full){ var name, res, todo = direct ? args : args.todo; if (!direct) { full = todo.full; } if (typeof todo === "string"){ res = store.getById(todo, false, full) || store.objGetById(todo); if (res === false){ name = todo; todo = {}; } } else { name = todo.name; } if (name === "map"){ res = map; } if (!res){ res = []; if (todo.id){ $.each(array(todo.id), function(i, id) { res.push(store.getById(id, false, full) || store.objGetById(id)); }); if (!$.isArray(todo.id)) { res = res[0]; } } else { $.each(name ? array(name) : [undef], function(i, aName) { var result; if (todo.first){ result = store.get(aName, false, todo.tag, full); if (result) res.push(result); } else if (todo.all){ $.each(store.all(aName, todo.tag, full), function(i, result){ res.push(result); }); } else { result = store.get(aName, true, todo.tag, full); if (result) res.push(result); } }); if (!todo.all && !$.isArray(name)) { res = res[0]; } } } res = $.isArray(res) || !todo.all ? res : [res]; if (direct){ return res; } else { manageEnd(args, res); } }; /** * return the distance between an origin and a destination * **/ this.getdistance = function(args){ var i; args.opts.origins = array(args.opts.origins); for(i=0; i<args.opts.origins.length; i++){ args.opts.origins[i] = toLatLng(args.opts.origins[i], true); } args.opts.destinations = array(args.opts.destinations); for(i=0; i<args.opts.destinations.length; i++){ args.opts.destinations[i] = toLatLng(args.opts.destinations[i], true); } distanceMatrixService().getDistanceMatrix( args.opts, function(results, status) { callback(args, status === google.maps.DistanceMatrixStatus.OK ? results : false, status); task.ack(); } ); }; /** * trigger events on the map **/ this.trigger = function(args){ if (typeof args.todo === "string"){ google.maps.event.trigger(map, args.todo); } else { var options = [map, args.todo.eventName]; if (args.todo.var_args) { $.each(args.todo.var_args, function(i, v){ options.push(v); }); } google.maps.event.trigger.apply(google.maps.event, options); } callback(args); task.ack(); }; } /** * Return true if get is a direct call * it means : * - get is the only key * - get has no callback * @param obj {Object} The request to check * @return {Boolean} */ function isDirectGet(obj) { var k; if (!typeof obj === "object" || !obj.hasOwnProperty("get")){ return false; } for(k in obj) { if (k !== "get") { return false; } } return !obj.get.hasOwnProperty("callback"); } //-----------------------------------------------------------------------// // jQuery plugin //-----------------------------------------------------------------------// $.fn.gmap3 = function(){ var i, list = [], empty = true, results = []; // init library initDefaults(); // store all arguments in a todo list for(i=0; i<arguments.length; i++){ if (arguments[i]){ list.push(arguments[i]); } } // resolve empty call - run init if (!list.length) { list.push("map"); } // loop on each jQuery object $.each(this, function() { var $this = $(this), gmap3 = $this.data("gmap3"); empty = false; if (!gmap3){ gmap3 = new Gmap3($this); $this.data("gmap3", gmap3); } if (list.length === 1 && (list[0] === "get" || isDirectGet(list[0]))){ results.push(gmap3.get(list[0] === "get" ? "map" : list[0].get, true)); } else { gmap3._plan(list); } }); // return for direct call only if (results.length){ if (results.length === 1){ // 1 css selector return results[0]; } else { return results; } } return this; } })(jQuery);
JavaScript
/** * Popup widget * * Usage: * $('#popup').popup({ trigger: '#button' }); * $('body').popup({ trigger: '#button', partial: 'partial:name' }); */ ;(function ($, window, document, undefined) { $.widget("utility.statusbar", { version: '1.0.2', options: { inject_to: 'body', // Element to prepend bar to message: '', // Message to display in bar context: 'info', // Message context (info, error, success, notice) position: 'top', // Bar location show_close: false, // Show the X to close time: 5000 // Duration }, _timer: null, _bar: null, _message: null, _close_link: null, _is_visible: false, _create: function () { var _this = this; this._message = $('<span />') .addClass('bar-content'); this._bar = $('<div />') .addClass('status-bar') .addClass(this.options.context) .addClass((this.options.position == 'bottom') ? 'bar-bottom' : 'bar-top'); if (this.options.show_close) { this._close_link = $('<a />') .addClass('bar-close') .click(function() { _this.remove_message(); }); } else { this._bar .css('cursor', 'pointer') .click(function() { _this.remove_message(); }); } this._bar .append(this._message) .append(this._close_link) .hide() .prependTo(this.options.inject_to); }, _setOption: function(key, value) { switch (key) { case "context": this._bar .removeClass('info success warning error') .addClass(value); break; case "message": this.show_message(value); break; } this.options[key] = value; }, destroy: function () { $.Widget.prototype.destroy.call(this); }, show_message: function(message, params) { var _this = this; this._set_timer(); this._message.html(message); // if (_this._is_visible) // return; _this._is_visible = true; this._bar.stop(true, true).fadeIn('fast', function() { _this._is_visible = true; }); }, _set_timer: function() { var _this = this; if (this._timer) this._clear_timer(); this._timer = setTimeout(function() { _this.remove_message(); }, this.options.time); }, _clear_timer: function() { clearTimeout(this._timer); }, remove_message: function() { var _this = this; if (_this._is_visible) { _this._clear_timer(); _this._bar.stop(true, true).fadeOut('fast', function() { _this._is_visible = false; }); } } }); })( jQuery, window, document );
JavaScript
/* Masked Input plugin for jQuery Copyright (c) 2007-@Year Josh Bush (digitalbush.com) Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license) Version: @version */ (function($) { var pasteEventName = ($.browser.msie ? 'paste' : 'input') + ".mask"; var iPhone = (window.orientation != undefined); $.mask = { //Predefined character definitions definitions: { '9': "[0-9]", 'a': "[A-Za-z]", '*': "[A-Za-z0-9]" }, dataName:"rawMaskFn" }; $.fn.extend({ //Helper Function for Caret positioning caret: function(begin, end) { if (this.length == 0) return; if (typeof begin == 'number') { end = (typeof end == 'number') ? end : begin; return this.each(function() { if (this.setSelectionRange) { this.setSelectionRange(begin, end); } else if (this.createTextRange) { var range = this.createTextRange(); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', begin); range.select(); } }); } else { if (this[0].setSelectionRange) { begin = this[0].selectionStart; end = this[0].selectionEnd; } else if (document.selection && document.selection.createRange) { var range = document.selection.createRange(); begin = 0 - range.duplicate().moveStart('character', -100000); end = begin + range.text.length; } return { begin: begin, end: end }; } }, unmask: function() { return this.trigger("unmask"); }, mask: function(mask, settings) { if (!mask && this.length > 0) { var input = $(this[0]); return input.data($.mask.dataName)(); } settings = $.extend({ placeholder: "_", completed: null }, settings); var defs = $.mask.definitions; var tests = []; var partialPosition = mask.length; var firstNonMaskPos = null; var len = mask.length; $.each(mask.split(""), function(i, c) { if (c == '?') { len--; partialPosition = i; } else if (defs[c]) { tests.push(new RegExp(defs[c])); if(firstNonMaskPos==null) firstNonMaskPos = tests.length - 1; } else { tests.push(null); } }); return this.trigger("unmask").each(function() { var input = $(this); var buffer = $.map(mask.split(""), function(c, i) { if (c != '?') return defs[c] ? settings.placeholder : c }); var focusText = input.val(); function seekNext(pos) { while (++pos <= len && !tests[pos]); return pos; }; function seekPrev(pos) { while (--pos >= 0 && !tests[pos]); return pos; }; function shiftL(begin,end) { if(begin<0) return; for (var i = begin,j = seekNext(end); i < len; i++) { if (tests[i]) { if (j < len && tests[i].test(buffer[j])) { buffer[i] = buffer[j]; buffer[j] = settings.placeholder; } else break; j = seekNext(j); } } writeBuffer(); input.caret(Math.max(firstNonMaskPos, begin)); }; function shiftR(pos) { for (var i = pos, c = settings.placeholder; i < len; i++) { if (tests[i]) { var j = seekNext(i); var t = buffer[i]; buffer[i] = c; if (j < len && tests[j].test(t)) c = t; else break; } } }; function keydownEvent(e) { var k=e.which; //backspace, delete, and escape get special treatment if(k == 8 || k == 46 || (iPhone && k == 127)){ var pos = input.caret(), begin = pos.begin, end = pos.end; if(end-begin==0){ begin=k!=46?seekPrev(begin):(end=seekNext(begin-1)); end=k==46?seekNext(end):end; } clearBuffer(begin, end); shiftL(begin,end-1); return false; } else if (k == 27) {//escape input.val(focusText); input.caret(0, checkVal()); return false; } }; function keypressEvent(e) { var k = e.which, pos = input.caret(); if (e.ctrlKey || e.altKey || e.metaKey || k<32) {//Ignore return true; } else if (k) { if(pos.end-pos.begin!=0){ clearBuffer(pos.begin, pos.end); shiftL(pos.begin, pos.end-1); } var p = seekNext(pos.begin - 1); if (p < len) { var c = String.fromCharCode(k); if (tests[p].test(c)) { shiftR(p); buffer[p] = c; writeBuffer(); var next = seekNext(p); input.caret(next); if (settings.completed && next >= len) settings.completed.call(input); } } return false; } }; function clearBuffer(start, end) { for (var i = start; i < end && i < len; i++) { if (tests[i]) buffer[i] = settings.placeholder; } }; function writeBuffer() { return input.val(buffer.join('')).val(); }; function checkVal(allow) { //try to place characters where they belong var test = input.val(); var lastMatch = -1; for (var i = 0, pos = 0; i < len; i++) { if (tests[i]) { buffer[i] = settings.placeholder; while (pos++ < test.length) { var c = test.charAt(pos - 1); if (tests[i].test(c)) { buffer[i] = c; lastMatch = i; break; } } if (pos > test.length) break; } else if (buffer[i] == test.charAt(pos) && i!=partialPosition) { pos++; lastMatch = i; } } if (!allow && lastMatch + 1 < partialPosition) { input.val(""); clearBuffer(0, len); } else if (allow || lastMatch + 1 >= partialPosition) { writeBuffer(); if (!allow) input.val(input.val().substring(0, lastMatch + 1)); } return (partialPosition ? i : firstNonMaskPos); }; input.data($.mask.dataName,function(){ return $.map(buffer, function(c, i) { return tests[i]&&c!=settings.placeholder ? c : null; }).join(''); }) if (!input.attr("readonly")) input .one("unmask", function() { input .unbind(".mask") .removeData($.mask.dataName); }) .bind("focus.mask", function() { focusText = input.val(); var pos = checkVal(); writeBuffer(); var moveCaret=function(){ if (pos == mask.length) input.caret(0, pos); else input.caret(pos); }; ($.browser.msie ? moveCaret:function(){setTimeout(moveCaret,0)})(); }) .bind("blur.mask", function() { checkVal(); if (input.val() != focusText) input.change(); }) .bind("keydown.mask", keydownEvent) .bind("keypress.mask", keypressEvent) .bind(pasteEventName, function() { setTimeout(function() { input.caret(checkVal(true)); }, 0); }); checkVal(); //Perform initial check for existing values }); } }); })(jQuery);
JavaScript
/* =require foundation/modernizr.foundation =require foundation/jquery.placeholder =require foundation/jquery.foundation.alerts =require foundation/jquery.foundation.accordion =require foundation/jquery.foundation.buttons =require foundation/jquery.foundation.tooltips =require foundation/jquery.foundation.forms =require foundation/jquery.foundation.tabs =require foundation/jquery.foundation.navigation =require foundation/jquery.foundation.topbar =require foundation/jquery.foundation.reveal =require foundation/jquery.foundation.orbit =require foundation/jquery.foundation.mediaQueryToggle =require foundation/app */
JavaScript
;(function ($, window, undefined){ 'use strict'; $.fn.foundationAccordion = function (options) { var $accordion = $('.accordion'); if ($accordion.hasClass('hover') && !Modernizr.touch) { $('.accordion li', this).on({ mouseenter : function () { console.log('due'); var p = $(this).parent(), flyout = $(this).children('.content').first(); $('.content', p).not(flyout).hide().parent('li').removeClass('active'); //changed this flyout.show(0, function () { flyout.parent('li').addClass('active'); }); } }); } else { $('.accordion li', this).on('click.fndtn', function () { var p = $(this).parent(), flyout = $(this).children('.content').first(); $('.content', p).not(flyout).hide().parent('li').removeClass('active'); //changed this flyout.show(0, function () { flyout.parent('li').addClass('active'); }); }); } }; })( jQuery, this );
JavaScript
/* * jQuery Foundation Tooltips 2.0.1 * http://foundation.zurb.com * Copyright 2012, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ /*jslint unparam: true, browser: true, indent: 2 */ ;(function ($, window, undefined) { 'use strict'; var settings = { bodyHeight : 0, targetClass : '.has-tip', tooltipClass : '.tooltip', tipTemplate : function (selector, content) { return '<span data-selector="' + selector + '" class="' + settings.tooltipClass.substring(1) + '">' + content + '<span class="nub"></span></span>'; } }, methods = { init : function (options) { settings = $.extend(settings, options); return this.each(function () { var $body = $('body'); if (Modernizr.touch) { $body.on('click.tooltip touchstart.tooltip touchend.tooltip', settings.targetClass, function (e) { e.preventDefault(); $(settings.tooltipClass).hide(); methods.showOrCreateTip($(this)); }); $body.on('click.tooltip touchstart.tooltip touchend.tooltip', settings.tooltipClass, function (e) { e.preventDefault(); $(this).fadeOut(150); }); } else { $body.on('mouseenter.tooltip mouseleave.tooltip', settings.targetClass, function (e) { var $this = $(this); if (e.type === 'mouseenter') { methods.showOrCreateTip($this); } else if (e.type === 'mouseleave') { methods.hide($this); } }); } $(this).data('tooltips', true); }); }, showOrCreateTip : function ($target) { var $tip = methods.getTip($target); if ($tip && $tip.length > 0) { methods.show($target); } else { methods.create($target); } }, getTip : function ($target) { var selector = methods.selector($target), tip = null; if (selector) { tip = $('span[data-selector=' + selector + ']' + settings.tooltipClass); } return (tip.length > 0) ? tip : false; }, selector : function ($target) { var id = $target.attr('id'), dataSelector = $target.data('selector'); if (id === undefined && dataSelector === undefined) { dataSelector = 'tooltip' + Math.random().toString(36).substring(7); $target.attr('data-selector', dataSelector); } return (id) ? id : dataSelector; }, create : function ($target) { var $tip = $(settings.tipTemplate(methods.selector($target), $('<div>').text($target.attr('title')).html())), classes = methods.inheritable_classes($target); $tip.addClass(classes).appendTo('body'); if (Modernizr.touch) { $tip.append('<span class="tap-to-close">tap to close </span>'); } $target.removeAttr('title'); methods.show($target); }, reposition : function (target, tip, classes) { var width, nub, nubHeight, nubWidth, column, objPos; tip.css('visibility', 'hidden').show(); width = target.data('width'); nub = tip.children('.nub'); nubHeight = nub.outerHeight(); nubWidth = nub.outerWidth(); objPos = function (obj, top, right, bottom, left, width) { return obj.css({ 'top' : top, 'bottom' : bottom, 'left' : left, 'right' : right, 'width' : (width) ? width : 'auto' }).end(); }; objPos(tip, (target.offset().top + target.outerHeight() + 10), 'auto', 'auto', target.offset().left, width); objPos(nub, -nubHeight, 'auto', 'auto', 10); if ($(window).width() < 767) { column = target.closest('.columns'); if (column.length < 0) { // if not using Foundation column = $('body'); } tip.width(column.outerWidth() - 25).css('left', 15).addClass('tip-override'); objPos(nub, -nubHeight, 'auto', 'auto', target.offset().left); } else { if (classes.indexOf('tip-top') > -1) { objPos(tip, (target.offset().top - tip.outerHeight() - nubHeight), 'auto', 'auto', target.offset().left, width) .removeClass('tip-override'); objPos(nub, 'auto', 'auto', -nubHeight, 'auto'); } else if (classes.indexOf('tip-left') > -1) { objPos(tip, (target.offset().top + (target.outerHeight() / 2) - nubHeight), 'auto', 'auto', (target.offset().left - tip.outerWidth() - 10), width) .removeClass('tip-override'); objPos(nub, (tip.outerHeight() / 2) - (nubHeight / 2), -nubHeight, 'auto', 'auto'); } else if (classes.indexOf('tip-right') > -1) { objPos(tip, (target.offset().top + (target.outerHeight() / 2) - nubHeight), 'auto', 'auto', (target.offset().left + target.outerWidth() + 10), width) .removeClass('tip-override'); objPos(nub, (tip.outerHeight() / 2) - (nubHeight / 2), 'auto', 'auto', -nubHeight); } } tip.css('visibility', 'visible').hide(); }, inheritable_classes : function (target) { var inheritables = ['tip-top', 'tip-left', 'tip-bottom', 'tip-right', 'noradius'], filtered = $.map(target.attr('class').split(' '), function (el, i) { if ($.inArray(el, inheritables) !== -1) { return el; } }).join(' '); return $.trim(filtered); }, show : function ($target) { var $tip = methods.getTip($target); methods.reposition($target, $tip, $target.attr('class')); $tip.fadeIn(150); }, hide : function ($target) { var $tip = methods.getTip($target); $tip.fadeOut(150); }, reload : function () { var $self = $(this); return ($self.data('tooltips')) ? $self.foundationTooltips('destroy').foundationTooltips('init') : $self.foundationTooltips('init'); }, destroy : function () { return this.each(function () { $(window).off('.tooltip'); $(settings.targetClass).off('.tooltip'); $(settings.tooltipClass).each(function (i) { $($(settings.targetClass).get(i)).attr('title', $(this).text()); }).remove(); }); } }; $.fn.foundationTooltips = function (method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.foundationTooltips'); } }; }(jQuery, this));
JavaScript
;(function ($, window, undefined) { 'use strict'; $.fn.foundationAlerts = function (options) { var settings = $.extend({ callback: $.noop }, options); $(document).on("click", ".alert-box a.close", function (e) { e.preventDefault(); $(this).closest(".alert-box").fadeOut(function () { $(this).remove(); // Do something else after the alert closes settings.callback(); }); }); }; })(jQuery, this);
JavaScript
;jQuery(document).ready(function($) { 'use strict'; var $doc = $(document), Modernizr = window.Modernizr; $.fn.foundationAlerts ? $doc.foundationAlerts() : null; $.fn.foundationButtons ? $doc.foundationButtons() : null; $.fn.foundationAccordion ? $doc.foundationAccordion() : null; $.fn.foundationNavigation ? $doc.foundationNavigation() : null; $.fn.foundationTopBar ? $doc.foundationTopBar() : null; $.fn.foundationCustomForms ? $doc.foundationCustomForms() : null; $.fn.foundationMediaQueryViewer ? $doc.foundationMediaQueryViewer() : null; $.fn.foundationTabs ? $doc.foundationTabs({callback : $.foundation.customForms.appendCustomMarkup}) : null; $.fn.foundationTooltips ? $doc.foundationTooltips() : null; $('input, textarea').placeholder(); // UNCOMMENT THE LINE YOU WANT BELOW IF YOU WANT IE8 SUPPORT AND ARE USING .block-grids $('.block-grid.two-up>li:nth-child(2n+1)').css({clear: 'both'}); $('.block-grid.three-up>li:nth-child(3n+1)').css({clear: 'both'}); $('.block-grid.four-up>li:nth-child(4n+1)').css({clear: 'both'}); $('.block-grid.five-up>li:nth-child(5n+1)').css({clear: 'both'}); // Hide address bar on mobile devices if (Modernizr.touch) { $(window).load(function () { setTimeout(function () { window.scrollTo(0, 1); }, 0); }); } });
JavaScript
/* * jQuery Reveal Plugin 1.1 * www.ZURB.com * Copyright 2010, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ /*globals jQuery */ (function ($) { 'use strict'; // // Global variable. // Helps us determine if the current modal is being queued for display. // var modalQueued = false; // // Bind the live 'click' event to all anchor elemnets with the data-reveal-id attribute. // $(document).on('click', 'a[data-reveal-id]', function ( event ) { // // Prevent default action of the event. // event.preventDefault(); // // Get the clicked anchor data-reveal-id attribute value. // var modalLocation = $( this ).attr( 'data-reveal-id' ); // // Find the element with that modalLocation id and call the reveal plugin. // $( '#' + modalLocation ).reveal( $( this ).data() ); }); /** * @module reveal * @property {Object} [options] Reveal options */ $.fn.reveal = function ( options ) { /* * Cache the document object. */ var $doc = $( document ), /* * Default property values. */ defaults = { /** * Possible options: fade, fadeAndPop, none * * @property animation * @type {String} * @default fadeAndPop */ animation: 'fadeAndPop', /** * Speed at which the reveal should show. How fast animtions are. * * @property animationSpeed * @type {Integer} * @default 300 */ animationSpeed: 300, /** * Should the modal close when the background is clicked? * * @property closeOnBackgroundClick * @type {Boolean} * @default true */ closeOnBackgroundClick: true, /** * Specify a class name for the 'close modal' element. * This element will close an open modal. * @example <a href='#close' class='close-reveal-modal'>Close Me</a> * * @property dismissModalClass * @type {String} * @default close-reveal-modal */ dismissModalClass: 'close-reveal-modal', /** * Specify a callback function that triggers 'before' the modal opens. * * @property open * @type {Function} * @default function(){} */ open: $.noop, /** * Specify a callback function that triggers 'after' the modal is opened. * * @property opened * @type {Function} * @default function(){} */ opened: $.noop, /** * Specify a callback function that triggers 'before' the modal prepares to close. * * @property close * @type {Function} * @default function(){} */ close: $.noop, /** * Specify a callback function that triggers 'after' the modal is closed. * * @property closed * @type {Function} * @default function(){} */ closed: $.noop } ; // // Extend the default options. // This replaces the passed in option (options) values with default values. // options = $.extend( {}, defaults, options ); // // Apply the plugin functionality to each element in the jQuery collection. // return this.not('.reveal-modal.open').each( function () { // // Cache the modal element // var modal = $( this ), // // Get the current css 'top' property value in decimal format. // topMeasure = parseInt( modal.css( 'top' ), 10 ), // // Calculate the top offset. // topOffset = modal.height() + topMeasure, // // Helps determine if the modal is locked. // This way we keep the modal from triggering while it's in the middle of animating. // locked = false, // // Get the modal background element. // modalBg = $( '.reveal-modal-bg' ), // // Show modal properties // cssOpts = { // // Used, when we show the modal. // open : { // // Set the 'top' property to the document scroll minus the calculated top offset. // 'top': 0, // // Opacity gets set to 0. // 'opacity': 0, // // Show the modal // 'visibility': 'visible', // // Ensure it's displayed as a block element. // 'display': 'block' }, // // Used, when we hide the modal. // close : { // // Set the default 'top' property value. // 'top': topMeasure, // // Has full opacity. // 'opacity': 1, // // Hide the modal // 'visibility': 'hidden', // // Ensure the elment is hidden. // 'display': 'none' } }, // // Initial closeButton variable. // $closeButton ; // // Do we have a modal background element? // if ( modalBg.length === 0 ) { // // No we don't. So, let's create one. // modalBg = $( '<div />', { 'class' : 'reveal-modal-bg' } ) // // Then insert it after the modal element. // .insertAfter( modal ); // // Now, fade it out a bit. // modalBg.fadeTo( 'fast', 0.8 ); } // // Helper Methods // /** * Unlock the modal for animation. * * @method unlockModal */ function unlockModal() { locked = false; } /** * Lock the modal to prevent further animation. * * @method lockModal */ function lockModal() { locked = true; } /** * Closes all open modals. * * @method closeOpenModal */ function closeOpenModals() { // // Get all reveal-modal elements with the .open class. // var $openModals = $( ".reveal-modal.open" ); // // Do we have modals to close? // if ( $openModals.length === 1 ) { // // Set the modals for animation queuing. // modalQueued = true; // // Trigger the modal close event. // $openModals.trigger( "reveal:close" ); } } /** * Animates the modal opening. * Handles the modal 'open' event. * * @method openAnimation */ function openAnimation() { // // First, determine if we're in the middle of animation. // if ( !locked ) { // // We're not animating, let's lock the modal for animation. // lockModal(); // // Close any opened modals. // closeOpenModals(); // // Now, add the open class to this modal. // modal.addClass( "open" ); // // Are we executing the 'fadeAndPop' animation? // if ( options.animation === "fadeAndPop" ) { // // Yes, we're doing the 'fadeAndPop' animation. // Okay, set the modal css properties. // // // Set the 'top' property to the document scroll minus the calculated top offset. // cssOpts.open.top = $doc.scrollTop() - topOffset; // // Flip the opacity to 0. // cssOpts.open.opacity = 0; // // Set the css options. // modal.css( cssOpts.open ); // // Fade in the background element, at half the speed of the modal element. // So, faster than the modal element. // modalBg.fadeIn( options.animationSpeed / 2 ); // // Let's delay the next animation queue. // We'll wait until the background element is faded in. // modal.delay( options.animationSpeed / 2 ) // // Animate the following css properties. // .animate( { // // Set the 'top' property to the document scroll plus the calculated top measure. // "top": $doc.scrollTop() + topMeasure + 'px', // // Set it to full opacity. // "opacity": 1 }, /* * Fade speed. */ options.animationSpeed, /* * End of animation callback. */ function () { // // Trigger the modal reveal:opened event. // This should trigger the functions set in the options.opened property. // modal.trigger( 'reveal:opened' ); }); // end of animate. } // end if 'fadeAndPop' // // Are executing the 'fade' animation? // if ( options.animation === "fade" ) { // // Yes, were executing 'fade'. // Okay, let's set the modal properties. // cssOpts.open.top = $doc.scrollTop() + topMeasure; // // Flip the opacity to 0. // cssOpts.open.opacity = 0; // // Set the css options. // modal.css( cssOpts.open ); // // Fade in the modal background at half the speed of the modal. // So, faster than modal. // modalBg.fadeIn( options.animationSpeed / 2 ); // // Delay the modal animation. // Wait till the modal background is done animating. // modal.delay( options.animationSpeed / 2 ) // // Now animate the modal. // .animate( { // // Set to full opacity. // "opacity": 1 }, /* * Animation speed. */ options.animationSpeed, /* * End of animation callback. */ function () { // // Trigger the modal reveal:opened event. // This should trigger the functions set in the options.opened property. // modal.trigger( 'reveal:opened' ); }); } // end if 'fade' // // Are we not animating? // if ( options.animation === "none" ) { // // We're not animating. // Okay, let's set the modal css properties. // // // Set the top property. // cssOpts.open.top = $doc.scrollTop() + topMeasure; // // Set the opacity property to full opacity, since we're not fading (animating). // cssOpts.open.opacity = 1; // // Set the css property. // modal.css( cssOpts.open ); // // Show the modal Background. // modalBg.css( { "display": "block" } ); // // Trigger the modal opened event. // modal.trigger( 'reveal:opened' ); } // end if animating 'none' }// end if !locked }// end openAnimation function openVideos() { var video = modal.find('.flex-video'), iframe = video.find('iframe'); if (iframe.length > 0) { iframe.attr("src", iframe.data("src")); video.fadeIn(100); } } // // Bind the reveal 'open' event. // When the event is triggered, openAnimation is called // along with any function set in the options.open property. // modal.bind( 'reveal:open.reveal', openAnimation ); modal.bind( 'reveal:open.reveal', openVideos); /** * Closes the modal element(s) * Handles the modal 'close' event. * * @method closeAnimation */ function closeAnimation() { // // First, determine if we're in the middle of animation. // if ( !locked ) { // // We're not animating, let's lock the modal for animation. // lockModal(); // // Clear the modal of the open class. // modal.removeClass( "open" ); // // Are we using the 'fadeAndPop' animation? // if ( options.animation === "fadeAndPop" ) { // // Yes, okay, let's set the animation properties. // modal.animate( { // // Set the top property to the document scrollTop minus calculated topOffset. // "top": $doc.scrollTop() - topOffset + 'px', // // Fade the modal out, by using the opacity property. // "opacity": 0 }, /* * Fade speed. */ options.animationSpeed / 2, /* * End of animation callback. */ function () { // // Set the css hidden options. // modal.css( cssOpts.close ); }); // // Is the modal animation queued? // if ( !modalQueued ) { // // Oh, the modal(s) are mid animating. // Let's delay the animation queue. // modalBg.delay( options.animationSpeed ) // // Fade out the modal background. // .fadeOut( /* * Animation speed. */ options.animationSpeed, /* * End of animation callback. */ function () { // // Trigger the modal 'closed' event. // This should trigger any method set in the options.closed property. // modal.trigger( 'reveal:closed' ); }); } else { // // We're not mid queue. // Trigger the modal 'closed' event. // This should trigger any method set in the options.closed propety. // modal.trigger( 'reveal:closed' ); } // end if !modalQueued } // end if animation 'fadeAndPop' // // Are we using the 'fade' animation. // if ( options.animation === "fade" ) { // // Yes, we're using the 'fade' animation. // modal.animate( { "opacity" : 0 }, /* * Animation speed. */ options.animationSpeed, /* * End of animation callback. */ function () { // // Set the css close options. // modal.css( cssOpts.close ); }); // end animate // // Are we mid animating the modal(s)? // if ( !modalQueued ) { // // Oh, the modal(s) are mid animating. // Let's delay the animation queue. // modalBg.delay( options.animationSpeed ) // // Let's fade out the modal background element. // .fadeOut( /* * Animation speed. */ options.animationSpeed, /* * End of animation callback. */ function () { // // Trigger the modal 'closed' event. // This should trigger any method set in the options.closed propety. // modal.trigger( 'reveal:closed' ); }); // end fadeOut } else { // // We're not mid queue. // Trigger the modal 'closed' event. // This should trigger any method set in the options.closed propety. // modal.trigger( 'reveal:closed' ); } // end if !modalQueued } // end if animation 'fade' // // Are we not animating? // if ( options.animation === "none" ) { // // We're not animating. // Set the modal close css options. // modal.css( cssOpts.close ); // // Is the modal in the middle of an animation queue? // if ( !modalQueued ) { // // It's not mid queueu. Just hide it. // modalBg.css( { 'display': 'none' } ); } // // Trigger the modal 'closed' event. // This should trigger any method set in the options.closed propety. // modal.trigger( 'reveal:closed' ); } // end if not animating // // Reset the modalQueued variable. // modalQueued = false; } // end if !locked } // end closeAnimation /** * Destroys the modal and it's events. * * @method destroy */ function destroy() { // // Unbind all .reveal events from the modal. // modal.unbind( '.reveal' ); // // Unbind all .reveal events from the modal background. // modalBg.unbind( '.reveal' ); // // Unbind all .reveal events from the modal 'close' button. // $closeButton.unbind( '.reveal' ); // // Unbind all .reveal events from the body. // $( 'body' ).unbind( '.reveal' ); } function closeVideos() { var video = modal.find('.flex-video'), iframe = video.find('iframe'); if (iframe.length > 0) { iframe.data("src", iframe.attr("src")); iframe.attr("src", ""); video.fadeOut(100); } } // // Bind the modal 'close' event // modal.bind( 'reveal:close.reveal', closeAnimation ); modal.bind( 'reveal:closed.reveal', closeVideos ); // // Bind the modal 'opened' + 'closed' event // Calls the unlockModal method. // modal.bind( 'reveal:opened.reveal reveal:closed.reveal', unlockModal ); // // Bind the modal 'closed' event. // Calls the destroy method. // modal.bind( 'reveal:closed.reveal', destroy ); // // Bind the modal 'open' event // Handled by the options.open property function. // modal.bind( 'reveal:open.reveal', options.open ); // // Bind the modal 'opened' event. // Handled by the options.opened property function. // modal.bind( 'reveal:opened.reveal', options.opened ); // // Bind the modal 'close' event. // Handled by the options.close property function. // modal.bind( 'reveal:close.reveal', options.close ); // // Bind the modal 'closed' event. // Handled by the options.closed property function. // modal.bind( 'reveal:closed.reveal', options.closed ); // // We're running this for the first time. // Trigger the modal 'open' event. // modal.trigger( 'reveal:open' ); // // Get the closeButton variable element(s). // $closeButton = $( '.' + options.dismissModalClass ) // // Bind the element 'click' event and handler. // .bind( 'click.reveal', function () { // // Trigger the modal 'close' event. // modal.trigger( 'reveal:close' ); }); // // Should we close the modal background on click? // if ( options.closeOnBackgroundClick ) { // // Yes, close the modal background on 'click' // Set the modal background css 'cursor' propety to pointer. // Adds a pointer symbol when you mouse over the modal background. // modalBg.css( { "cursor": "pointer" } ); // // Bind a 'click' event handler to the modal background. // modalBg.bind( 'click.reveal', function () { // // Trigger the modal 'close' event. // modal.trigger( 'reveal:close' ); }); } // // Bind keyup functions on the body element. // We'll want to close the modal when the 'escape' key is hit. // $( 'body' ).bind( 'keyup.reveal', function ( event ) { // // Did the escape key get triggered? // if ( event.which === 27 ) { // 27 is the keycode for the Escape key // // Escape key was triggered. // Trigger the modal 'close' event. // modal.trigger( 'reveal:close' ); } }); // end $(body) }); // end this.each }; // end $.fn } ( jQuery ) );
JavaScript
;(function (window, document, $) { // Set the negative margin on the top menu for slide-menu pages var $selector1 = $('#topMenu'), events = 'click.fndtn'; if ($selector1.length > 0) $selector1.css("margin-top", $selector1.height() * -1); // Watch for clicks to show the sidebar var $selector2 = $('#sidebarButton'); if ($selector2.length > 0) { $('#sidebarButton').on(events, function (e) { e.preventDefault(); $('body').toggleClass('active'); }); } // Watch for clicks to show the menu for slide-menu pages var $selector3 = $('#menuButton'); if ($selector3.length > 0) { $('#menuButton').on(events, function (e) { e.preventDefault(); $('body').toggleClass('active-menu'); }); } // // Adjust sidebars and sizes when resized // $(window).resize(function() { // // if (!navigator.userAgent.match(/Android/i)) $('body').removeClass('active'); // var $selector4 = $('#topMenu'); // if ($selector4.length > 0) $selector4.css("margin-top", $selector4.height() * -1); // }); // Switch panels for the paneled nav on mobile var $selector5 = $('#switchPanels'); if ($selector5.length > 0) { $('#switchPanels dd').on(events, function (e) { e.preventDefault(); var switchToPanel = $(this).children('a').attr('href'), switchToIndex = $(switchToPanel).index(); $(this).toggleClass('active').siblings().removeClass('active'); $(switchToPanel).parent().css("left", (switchToIndex * (-100) + '%')); }); } $('#nav li a').on(events, function (e) { e.preventDefault(); var href = $(this).attr('href'), $target = $(href); $('html, body').animate({scrollTop : $target.offset().top}, 300); }); }(this, document, jQuery));
JavaScript
;(function ($, window, undefined) { 'use strict'; $.fn.foundationTabs = function (options) { var settings = $.extend({ callback: $.noop }, options); var activateTab = function ($tab) { var $activeTab = $tab.closest('dl').find('dd.active'), target = $tab.children('a').attr("href"), hasHash = /^#/.test(target), contentLocation = ''; if (hasHash) { contentLocation = target + 'Tab'; // Strip off the current url that IE adds contentLocation = contentLocation.replace(/^.+#/, '#'); //Show Tab Content $(contentLocation).closest('.tabs-content').children('li').removeClass('active').hide(); $(contentLocation).css('display', 'block').addClass('active'); } //Make Tab Active $activeTab.removeClass('active'); $tab.addClass('active'); }; $(document).on('click.fndtn', 'dl.tabs dd a', function (event){ activateTab($(this).parent('dd')); }); if (window.location.hash) { activateTab($('a[href="' + window.location.hash + '"]').parent('dd')); settings.callback(); } }; })(jQuery, this);
JavaScript
/* * jQuery Foundation Top Bar 2.0.1 * http://foundation.zurb.com * Copyright 2012, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ /*jslint unparam: true, browser: true, indent: 2 */ ;(function ($, window, undefined) { 'use strict'; var settings = { index : 0, initialized : false }, methods = { init : function (options) { return this.each(function () { settings = $.extend(settings, options); settings.$w = $(window), settings.$topbar = $('nav.top-bar'); settings.$titlebar = settings.$topbar.children('ul:first'); var breakpoint = $("<div class='top-bar-js-breakpoint'/>").appendTo("body"); settings.breakPoint = breakpoint.width(); breakpoint.remove(); if (!settings.initialized) { methods.assemble(); settings.initialized = true; } if (!settings.height) { methods.largestUL(); } $('.top-bar .toggle-topbar').live('click.fndtn', function (e) { e.preventDefault(); if (methods.breakpoint()) { settings.$topbar.toggleClass('expanded'); settings.$topbar.css('min-height', ''); } }); // Show the Dropdown Levels on Click $('.top-bar .has-dropdown>a').live('click.fndtn', function (e) { e.preventDefault(); if (methods.breakpoint()) { var $this = $(this), $selectedLi = $this.closest('li'), $nextLevelUl = $selectedLi.children('ul'), $section = $this.closest('section'), $nextLevelUlHeight = 0, $largestUl; settings.index += 1; $selectedLi.addClass('moved'); $section.css({'left': -(100 * settings.index) + '%'}); $section.find('>.name').css({'left': 100 * settings.index + '%'}); $this.siblings('ul').height(settings.height + settings.$titlebar.outerHeight(true)); settings.$topbar.css('min-height', settings.height + settings.$titlebar.outerHeight(true) * 2) } }); // Go up a level on Click $('.top-bar .has-dropdown .back').live('click.fndtn', function (e) { e.preventDefault(); var $this = $(this), $movedLi = $this.closest('li.moved'), $section = $this.closest('section'), $previousLevelUl = $movedLi.parent(); settings.index -= 1; $section.css({'left': -(100 * settings.index) + '%'}); $section.find('>.name').css({'left': 100 * settings.index + '%'}); if (settings.index === 0) { settings.$topbar.css('min-height', 0); } setTimeout(function () { $movedLi.removeClass('moved'); }, 300); }); }); }, breakpoint : function () { return settings.$w.width() < settings.breakPoint; }, assemble : function () { var $section = settings.$topbar.children('section'); // Pull element out of the DOM for manipulation $section.detach(); $section.find('.has-dropdown>a').each(function () { var $link = $(this), $dropdown = $link.siblings('.dropdown'), $titleLi = $('<li class="title back js-generated"><h5><a href="#"></a></h5></li>'); // Copy link to subnav $titleLi.find('h5>a').html($link.html()); $dropdown.prepend($titleLi); }); // Put element back in the DOM $section.appendTo(settings.$topbar); }, largestUL : function () { var uls = settings.$topbar.find('section ul ul'), largest = uls.first(), total = 0; uls.each(function () { if ($(this).children('li').length > largest.children('li').length) { largest = $(this); } }); largest.children('li').each(function () { total += $(this).outerHeight(true); }); settings.height = total; } }; $.fn.foundationTopBar = function (method) { if (methods[method]) { return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); } else if (typeof method === 'object' || !method) { return methods.init.apply(this, arguments); } else { $.error('Method ' + method + ' does not exist on jQuery.foundationTopBar'); } }; }(jQuery, this));
JavaScript
/* * jQuery Orbit Plugin 1.4.0 * www.ZURB.com/playground * Copyright 2010, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ (function ($) { 'use strict'; $.fn.findFirstImage = function () { return this.first() .find('img') .andSelf().filter('img') .first(); }; var ORBIT = { defaults: { animation: 'horizontal-push', // fade, horizontal-slide, vertical-slide, horizontal-push, vertical-push animationSpeed: 600, // how fast animtions are timer: true, // true or false to have the timer advanceSpeed: 4000, // if timer is enabled, time between transitions pauseOnHover: false, // if you hover pauses the slider startClockOnMouseOut: false, // if clock should start on MouseOut startClockOnMouseOutAfter: 1000, // how long after MouseOut should the timer start again directionalNav: true, // manual advancing directional navs directionalNavRightText: 'Right', // text of right directional element for accessibility directionalNavLeftText: 'Left', // text of left directional element for accessibility captions: true, // do you want captions? captionAnimation: 'fade', // fade, slideOpen, none captionAnimationSpeed: 600, // if so how quickly should they animate in resetTimerOnClick: false, // true resets the timer instead of pausing slideshow progress on manual navigation bullets: false, // true or false to activate the bullet navigation bulletThumbs: false, // thumbnails for the bullets bulletThumbLocation: '', // location from this file where thumbs will be afterSlideChange: $.noop, // empty function afterLoadComplete: $.noop, //callback to execute after everything has been loaded fluid: true, centerBullets: true, // center bullet nav with js, turn this off if you want to position the bullet nav manually singleCycle: false // cycles through orbit slides only once }, activeSlide: 0, numberSlides: 0, orbitWidth: null, orbitHeight: null, locked: null, timerRunning: null, degrees: 0, wrapperHTML: '<div class="orbit-wrapper" />', timerHTML: '<div class="timer"><span class="mask"><span class="rotator"></span></span><span class="pause"></span></div>', captionHTML: '<div class="orbit-caption"></div>', directionalNavHTML: '<div class="slider-nav"><span class="right"></span><span class="left"></span></div>', bulletHTML: '<ul class="orbit-bullets"></ul>', init: function (element, options) { var $imageSlides, imagesLoadedCount = 0, self = this; // Bind functions to correct context this.clickTimer = $.proxy(this.clickTimer, this); this.addBullet = $.proxy(this.addBullet, this); this.resetAndUnlock = $.proxy(this.resetAndUnlock, this); this.stopClock = $.proxy(this.stopClock, this); this.startTimerAfterMouseLeave = $.proxy(this.startTimerAfterMouseLeave, this); this.clearClockMouseLeaveTimer = $.proxy(this.clearClockMouseLeaveTimer, this); this.rotateTimer = $.proxy(this.rotateTimer, this); this.options = $.extend({}, this.defaults, options); if (this.options.timer === 'false') this.options.timer = false; if (this.options.captions === 'false') this.options.captions = false; if (this.options.directionalNav === 'false') this.options.directionalNav = false; this.$element = $(element); this.$wrapper = this.$element.wrap(this.wrapperHTML).parent(); this.$slides = this.$element.children('img, a, div, figure'); this.$element.bind('orbit.next', function () { self.shift('next'); }); this.$element.bind('orbit.prev', function () { self.shift('prev'); }); this.$element.bind('orbit.goto', function (event, index) { self.shift(index); }); this.$element.bind('orbit.start', function (event, index) { self.startClock(); }); this.$element.bind('orbit.stop', function (event, index) { self.stopClock(); }); $imageSlides = this.$slides.filter('img'); if ($imageSlides.length === 0) { this.loaded(); } else { $imageSlides.bind('imageready', function () { imagesLoadedCount += 1; if (imagesLoadedCount === $imageSlides.length) { self.loaded(); } }); } }, loaded: function () { this.$element .addClass('orbit') .css({width: '1px', height: '1px'}); this.$slides.addClass('orbit-slide'); this.setDimentionsFromLargestSlide(); this.updateOptionsIfOnlyOneSlide(); this.setupFirstSlide(); if (this.options.timer) { this.setupTimer(); this.startClock(); } if (this.options.captions) { this.setupCaptions(); } if (this.options.directionalNav) { this.setupDirectionalNav(); } if (this.options.bullets) { this.setupBulletNav(); this.setActiveBullet(); } this.options.afterLoadComplete.call(this); Holder.run(); }, currentSlide: function () { return this.$slides.eq(this.activeSlide); }, setDimentionsFromLargestSlide: function () { //Collect all slides and set slider size of largest image var self = this, $fluidPlaceholder; self.$element.add(self.$wrapper).width(this.$slides.first().outerWidth()); self.$element.add(self.$wrapper).height(this.$slides.first().height()); self.orbitWidth = this.$slides.first().outerWidth(); self.orbitHeight = this.$slides.first().height(); $fluidPlaceholder = this.$slides.first().findFirstImage().clone(); this.$slides.each(function () { var slide = $(this), slideWidth = slide.outerWidth(), slideHeight = slide.height(); if (slideWidth > self.$element.outerWidth()) { self.$element.add(self.$wrapper).width(slideWidth); self.orbitWidth = self.$element.outerWidth(); } if (slideHeight > self.$element.height()) { self.$element.add(self.$wrapper).height(slideHeight); self.orbitHeight = self.$element.height(); $fluidPlaceholder = $(this).findFirstImage().clone(); } self.numberSlides += 1; }); if (this.options.fluid) { if (typeof this.options.fluid === "string") { // $fluidPlaceholder = $("<img>").attr("src", "http://placehold.it/" + this.options.fluid); $fluidPlaceholder = $("<img>").attr("data-src", "holder.js/" + this.options.fluid); //var inner = $("<div/>").css({"display":"inline-block", "width":"2px", "height":"2px"}); //$fluidPlaceholder = $("<div/>").css({"float":"left"}); //$fluidPlaceholder.wrapInner(inner); //$fluidPlaceholder = $("<div/>").css({"height":"1px", "width":"2px"}); //$fluidPlaceholder = $("<div style='display:inline-block;width:2px;height:1px;'></div>"); } self.$element.prepend($fluidPlaceholder); $fluidPlaceholder.addClass('fluid-placeholder'); self.$element.add(self.$wrapper).css({width: 'inherit'}); self.$element.add(self.$wrapper).css({height: 'inherit'}); $(window).bind('resize', function () { self.orbitWidth = self.$element.outerWidth(); self.orbitHeight = self.$element.height(); }); } }, //Animation locking functions lock: function () { this.locked = true; }, unlock: function () { this.locked = false; }, updateOptionsIfOnlyOneSlide: function () { if(this.$slides.length === 1) { this.options.directionalNav = false; this.options.timer = false; this.options.bullets = false; } }, setupFirstSlide: function () { //Set initial front photo z-index and fades it in var self = this; this.$slides.first() .css({"z-index" : 3}) .fadeIn(function() { //brings in all other slides IF css declares a display: none self.$slides.css({"display":"block"}) }); }, startClock: function () { var self = this; if(!this.options.timer) { return false; } if (this.$timer.is(':hidden')) { this.clock = setInterval(function () { self.$element.trigger('orbit.next'); }, this.options.advanceSpeed); } else { this.timerRunning = true; this.$pause.removeClass('active'); this.clock = setInterval(this.rotateTimer, this.options.advanceSpeed / 180, false); } }, rotateTimer: function (reset) { var degreeCSS = "rotate(" + this.degrees + "deg)"; this.degrees += 2; this.$rotator.css({ "-webkit-transform": degreeCSS, "-moz-transform": degreeCSS, "-o-transform": degreeCSS, "-ms-transform": degreeCSS }); if(this.degrees > 180) { this.$rotator.addClass('move'); this.$mask.addClass('move'); } if(this.degrees > 360 || reset) { this.$rotator.removeClass('move'); this.$mask.removeClass('move'); this.degrees = 0; this.$element.trigger('orbit.next'); } }, stopClock: function () { if (!this.options.timer) { return false; } else { this.timerRunning = false; clearInterval(this.clock); this.$pause.addClass('active'); } }, setupTimer: function () { this.$timer = $(this.timerHTML); this.$wrapper.append(this.$timer); this.$rotator = this.$timer.find('.rotator'); this.$mask = this.$timer.find('.mask'); this.$pause = this.$timer.find('.pause'); this.$timer.click(this.clickTimer); if (this.options.startClockOnMouseOut) { this.$wrapper.mouseleave(this.startTimerAfterMouseLeave); this.$wrapper.mouseenter(this.clearClockMouseLeaveTimer); } if (this.options.pauseOnHover) { this.$wrapper.mouseenter(this.stopClock); } }, startTimerAfterMouseLeave: function () { var self = this; this.outTimer = setTimeout(function() { if(!self.timerRunning){ self.startClock(); } }, this.options.startClockOnMouseOutAfter) }, clearClockMouseLeaveTimer: function () { clearTimeout(this.outTimer); }, clickTimer: function () { if(!this.timerRunning) { this.startClock(); } else { this.stopClock(); } }, setupCaptions: function () { this.$caption = $(this.captionHTML); this.$wrapper.append(this.$caption); this.setCaption(); }, setCaption: function () { var captionLocation = this.currentSlide().attr('data-caption'), captionHTML; if (!this.options.captions) { return false; } //Set HTML for the caption if it exists if (captionLocation) { //if caption text is blank, don't show captions if ($.trim($(captionLocation).text()).length < 1){ return false; } captionHTML = $(captionLocation).html(); //get HTML from the matching HTML entity this.$caption .attr('id', captionLocation) // Add ID caption TODO why is the id being set? .html(captionHTML); // Change HTML in Caption //Animations for Caption entrances switch (this.options.captionAnimation) { case 'none': this.$caption.show(); break; case 'fade': this.$caption.fadeIn(this.options.captionAnimationSpeed); break; case 'slideOpen': this.$caption.slideDown(this.options.captionAnimationSpeed); break; } } else { //Animations for Caption exits switch (this.options.captionAnimation) { case 'none': this.$caption.hide(); break; case 'fade': this.$caption.fadeOut(this.options.captionAnimationSpeed); break; case 'slideOpen': this.$caption.slideUp(this.options.captionAnimationSpeed); break; } } }, setupDirectionalNav: function () { var self = this, $directionalNav = $(this.directionalNavHTML); $directionalNav.find('.right').html(this.options.directionalNavRightText); $directionalNav.find('.left').html(this.options.directionalNavLeftText); this.$wrapper.append($directionalNav); this.$wrapper.find('.left').click(function () { self.stopClock(); if (self.options.resetTimerOnClick) { self.rotateTimer(true); self.startClock(); } self.$element.trigger('orbit.prev'); }); this.$wrapper.find('.right').click(function () { self.stopClock(); if (self.options.resetTimerOnClick) { self.rotateTimer(true); self.startClock(); } self.$element.trigger('orbit.next'); }); }, setupBulletNav: function () { this.$bullets = $(this.bulletHTML); this.$wrapper.append(this.$bullets); this.$slides.each(this.addBullet); this.$element.addClass('with-bullets'); if (this.options.centerBullets) this.$bullets.css('margin-left', -this.$bullets.outerWidth() / 2); }, addBullet: function (index, slide) { var position = index + 1, $li = $('<li>' + (position) + '</li>'), thumbName, self = this; if (this.options.bulletThumbs) { thumbName = $(slide).attr('data-thumb'); if (thumbName) { $li .addClass('has-thumb') .css({background: "url(" + this.options.bulletThumbLocation + thumbName + ") no-repeat"});; } } this.$bullets.append($li); $li.data('index', index); $li.click(function () { self.stopClock(); if (self.options.resetTimerOnClick) { self.rotateTimer(true); self.startClock(); } self.$element.trigger('orbit.goto', [$li.data('index')]) }); }, setActiveBullet: function () { if(!this.options.bullets) { return false; } else { this.$bullets.find('li') .removeClass('active') .eq(this.activeSlide) .addClass('active'); } }, resetAndUnlock: function () { this.$slides .eq(this.prevActiveSlide) .css({"z-index" : 1}); this.unlock(); this.options.afterSlideChange.call(this, this.$slides.eq(this.prevActiveSlide), this.$slides.eq(this.activeSlide)); }, shift: function (direction) { var slideDirection = direction; //remember previous activeSlide this.prevActiveSlide = this.activeSlide; //exit function if bullet clicked is same as the current image if (this.prevActiveSlide == slideDirection) { return false; } if (this.$slides.length == "1") { return false; } if (!this.locked) { this.lock(); //deduce the proper activeImage if (direction == "next") { this.activeSlide++; if (this.activeSlide == this.numberSlides) { this.activeSlide = 0; } } else if (direction == "prev") { this.activeSlide-- if (this.activeSlide < 0) { this.activeSlide = this.numberSlides - 1; } } else { this.activeSlide = direction; if (this.prevActiveSlide < this.activeSlide) { slideDirection = "next"; } else if (this.prevActiveSlide > this.activeSlide) { slideDirection = "prev" } } //set to correct bullet this.setActiveBullet(); //set previous slide z-index to one below what new activeSlide will be this.$slides .eq(this.prevActiveSlide) .css({"z-index" : 2}); //fade if (this.options.animation == "fade") { this.$slides .eq(this.activeSlide) .css({"opacity" : 0, "z-index" : 3}) .animate({"opacity" : 1}, this.options.animationSpeed, this.resetAndUnlock); } //horizontal-slide if (this.options.animation == "horizontal-slide") { if (slideDirection == "next") { this.$slides .eq(this.activeSlide) .css({"left": this.orbitWidth, "z-index" : 3}) .animate({"left" : 0}, this.options.animationSpeed, this.resetAndUnlock); } if (slideDirection == "prev") { this.$slides .eq(this.activeSlide) .css({"left": -this.orbitWidth, "z-index" : 3}) .animate({"left" : 0}, this.options.animationSpeed, this.resetAndUnlock); } } //vertical-slide if (this.options.animation == "vertical-slide") { if (slideDirection == "prev") { this.$slides .eq(this.activeSlide) .css({"top": this.orbitHeight, "z-index" : 3}) .animate({"top" : 0}, this.options.animationSpeed, this.resetAndUnlock); } if (slideDirection == "next") { this.$slides .eq(this.activeSlide) .css({"top": -this.orbitHeight, "z-index" : 3}) .animate({"top" : 0}, this.options.animationSpeed, this.resetAndUnlock); } } //horizontal-push if (this.options.animation == "horizontal-push") { if (slideDirection == "next") { this.$slides .eq(this.activeSlide) .css({"left": this.orbitWidth, "z-index" : 3}) .animate({"left" : 0}, this.options.animationSpeed, this.resetAndUnlock); this.$slides .eq(this.prevActiveSlide) .animate({"left" : -this.orbitWidth}, this.options.animationSpeed); } if (slideDirection == "prev") { this.$slides .eq(this.activeSlide) .css({"left": -this.orbitWidth, "z-index" : 3}) .animate({"left" : 0}, this.options.animationSpeed, this.resetAndUnlock); this.$slides .eq(this.prevActiveSlide) .animate({"left" : this.orbitWidth}, this.options.animationSpeed); } } //vertical-push if (this.options.animation == "vertical-push") { if (slideDirection == "next") { this.$slides .eq(this.activeSlide) .css({top: -this.orbitHeight, "z-index" : 3}) .animate({top : 0}, this.options.animationSpeed, this.resetAndUnlock); this.$slides .eq(this.prevActiveSlide) .animate({top : this.orbitHeight}, this.options.animationSpeed); } if (slideDirection == "prev") { this.$slides .eq(this.activeSlide) .css({top: this.orbitHeight, "z-index" : 3}) .animate({top : 0}, this.options.animationSpeed, this.resetAndUnlock); this.$slides .eq(this.prevActiveSlide) .animate({top : -this.orbitHeight}, this.options.animationSpeed); } } this.setCaption(); } if (this.$slides.last() && this.options.singleCycle) { this.stopClock(); } } }; $.fn.orbit = function (options) { return this.each(function () { var orbit = $.extend({}, ORBIT); orbit.init(this, options); }); }; })(jQuery); /*! * jQuery imageready Plugin * http://www.zurb.com/playground/ * * Copyright 2011, ZURB * Released under the MIT License */ (function ($) { var options = {}; $.event.special.imageready = { setup: function (data, namespaces, eventHandle) { options = data || options; }, add: function (handleObj) { var $this = $(this), src; if ( this.nodeType === 1 && this.tagName.toLowerCase() === 'img' && this.src !== '' ) { if (options.forceLoad) { src = $this.attr('src'); $this.attr('src', ''); bindToLoad(this, handleObj.handler); $this.attr('src', src); } else if ( this.complete || this.readyState === 4 ) { handleObj.handler.apply(this, arguments); } else { bindToLoad(this, handleObj.handler); } } }, teardown: function (namespaces) { $(this).unbind('.imageready'); } }; function bindToLoad(element, callback) { var $this = $(element); $this.bind('load.imageready', function () { callback.apply(element, arguments); $this.unbind('load.imageready'); }); } }(jQuery)); /* Holder - 1.3 - client side image placeholders (c) 2012 Ivan Malopinsky / http://imsky.co Provided under the Apache 2.0 License: http://www.apache.org/licenses/LICENSE-2.0 Commercial use requires attribution. */ var Holder = Holder || {}; (function (app, win) { var preempted = false, fallback = false, canvas = document.createElement('canvas'); //http://javascript.nwbox.com/ContentLoaded by Diego Perini with modifications function contentLoaded(n,t){var l="complete",s="readystatechange",u=!1,h=u,c=!0,i=n.document,a=i.documentElement,e=i.addEventListener?"addEventListener":"attachEvent",v=i.addEventListener?"removeEventListener":"detachEvent",f=i.addEventListener?"":"on",r=function(e){(e.type!=s||i.readyState==l)&&((e.type=="load"?n:i)[v](f+e.type,r,u),!h&&(h=!0)&&t.call(n,null))},o=function(){try{a.doScroll("left")}catch(n){setTimeout(o,50);return}r("poll")};if(i.readyState==l)t.call(n,"lazy");else{if(i.createEventObject&&a.doScroll){try{c=!n.frameElement}catch(y){}c&&o()}i[e](f+"DOMContentLoaded",r,u),i[e](f+s,r,u),n[e](f+"load",r,u)}}; //https://gist.github.com/991057 by Jed Schmidt with modifications function selector(a){ a=a.match(/^(\W)?(.*)/);var b=document["getElement"+(a[1]?a[1]=="#"?"ById":"sByClassName":"sByTagName")](a[2]); var ret=[]; b!=null&&(b.length?ret=b:b.length==0?ret=b:ret=[b]); return ret; } //shallow object property extend function extend(a,b){var c={};for(var d in a)c[d]=a[d];for(var e in b)c[e]=b[e];return c} function draw(ctx, dimensions, template) { var dimension_arr = [dimensions.height, dimensions.width].sort(); var maxFactor = Math.round(dimension_arr[1] / 16), minFactor = Math.round(dimension_arr[0] / 16); var text_height = Math.max(template.size, maxFactor); canvas.width = dimensions.width; canvas.height = dimensions.height; ctx.textAlign = "center"; ctx.textBaseline = "middle"; ctx.fillStyle = template.background; ctx.fillRect(0, 0, dimensions.width, dimensions.height); ctx.fillStyle = template.foreground; ctx.font = "bold " + text_height + "px sans-serif"; var text = template.text ? template.text : (dimensions.width + "x" + dimensions.height); if (Math.round(ctx.measureText(text).width) / dimensions.width > 1) { text_height = Math.max(minFactor, template.size); } ctx.font = "bold " + text_height + "px sans-serif"; ctx.fillText(text, (dimensions.width / 2), (dimensions.height / 2), dimensions.width); return canvas.toDataURL("image/png"); } if (!canvas.getContext) { fallback = true; } else { if (canvas.toDataURL("image/png").indexOf("data:image/png") < 0) { //Android doesn't support data URI fallback = true; } else { var ctx = canvas.getContext("2d"); } } var settings = { domain: "holder.js", images: "img", themes: { "gray": { background: "#eee", foreground: "#aaa", size: 12 }, "social": { background: "#3a5a97", foreground: "#fff", size: 12 }, "industrial": { background: "#434A52", foreground: "#C2F200", size: 12 } } }; app.flags = { dimensions: { regex: /([0-9]+)x([0-9]+)/, output: function(val){ var exec = this.regex.exec(val); return { width: +exec[1], height: +exec[2] } } }, colors: { regex: /#([0-9a-f]{3,})\:#([0-9a-f]{3,})/i, output: function(val){ var exec = this.regex.exec(val); return { size: settings.themes.gray.size, foreground: "#" + exec[2], background: "#" + exec[1] } } }, text: { regex: /text\:(.*)/, output: function(val){ return this.regex.exec(val)[1]; } } } for(var flag in app.flags){ app.flags[flag].match = function (val){ return val.match(this.regex) } } app.add_theme = function (name, theme) { name != null && theme != null && (settings.themes[name] = theme); return app; }; app.add_image = function (src, el) { var node = selector(el); if (node.length) { for (var i = 0, l = node.length; i < l; i++) { var img = document.createElement("img") img.setAttribute("data-src", src); node[i].appendChild(img); } } return app; }; app.run = function (o) { var options = extend(settings, o), images = selector(options.images), preempted = true; for (var l = images.length, i = 0; i < l; i++) { var theme = settings.themes.gray; var src = images[i].getAttribute("data-src") || images[i].getAttribute("src"); if ( !! ~src.indexOf(options.domain)) { var render = false, dimensions = null, text = null; var flags = src.substr(src.indexOf(options.domain) + options.domain.length + 1).split("/"); for (sl = flags.length, j = 0; j < sl; j++) { if (app.flags.dimensions.match(flags[j])) { render = true; dimensions = app.flags.dimensions.output(flags[j]); } else if (app.flags.colors.match(flags[j])) { theme = app.flags.colors.output(flags[j]); } else if (options.themes[flags[j]]) { //If a theme is specified, it will override custom colors theme = options.themes[flags[j]]; } else if (app.flags.text.match(flags[j])) { text = app.flags.text.output(flags[j]); } } if (render) { images[i].setAttribute("data-src", src); var dimensions_caption = dimensions.width + "x" + dimensions.height; images[i].setAttribute("alt", text ? text : theme.text ? theme.text + " [" + dimensions_caption + "]" : dimensions_caption); // Fallback // images[i].style.width = dimensions.width + "px"; // images[i].style.height = dimensions.height + "px"; images[i].style.backgroundColor = theme.background; var theme = (text ? extend(theme, { text: text }) : theme); if (!fallback) { images[i].setAttribute("src", draw(ctx, dimensions, theme)); } } } } return app; }; contentLoaded(win, function () { preempted || app.run() }) })(Holder, window);
JavaScript
/*! http://mths.be/placeholder v2.0.7 by @mathias */ ;(function(window, document, $) { var isInputSupported = 'placeholder' in document.createElement('input'), isTextareaSupported = 'placeholder' in document.createElement('textarea'), prototype = $.fn, valHooks = $.valHooks, hooks, placeholder; if (isInputSupported && isTextareaSupported) { placeholder = prototype.placeholder = function() { return this; }; placeholder.input = placeholder.textarea = true; } else { placeholder = prototype.placeholder = function() { var $this = this; $this .filter((isInputSupported ? 'textarea' : ':input') + '[placeholder]') .not('.placeholder') .bind({ 'focus.placeholder': clearPlaceholder, 'blur.placeholder': setPlaceholder }) .data('placeholder-enabled', true) .trigger('blur.placeholder'); return $this; }; placeholder.input = isInputSupported; placeholder.textarea = isTextareaSupported; hooks = { 'get': function(element) { var $element = $(element); return $element.data('placeholder-enabled') && $element.hasClass('placeholder') ? '' : element.value; }, 'set': function(element, value) { var $element = $(element); if (!$element.data('placeholder-enabled')) { return element.value = value; } if (value == '') { element.value = value; // Issue #56: Setting the placeholder causes problems if the element continues to have focus. if (element != document.activeElement) { // We can't use `triggerHandler` here because of dummy text/password inputs :( setPlaceholder.call(element); } } else if ($element.hasClass('placeholder')) { clearPlaceholder.call(element, true, value) || (element.value = value); } else { element.value = value; } // `set` can not return `undefined`; see http://jsapi.info/jquery/1.7.1/val#L2363 return $element; } }; isInputSupported || (valHooks.input = hooks); isTextareaSupported || (valHooks.textarea = hooks); $(function() { // Look for forms $(document).delegate('form', 'submit.placeholder', function() { // Clear the placeholder values so they don't get submitted var $inputs = $('.placeholder', this).each(clearPlaceholder); setTimeout(function() { $inputs.each(setPlaceholder); }, 10); }); }); // Clear placeholder values upon page reload $(window).bind('beforeunload.placeholder', function() { $('.placeholder').each(function() { this.value = ''; }); }); } function args(elem) { // Return an object of element attributes var newAttrs = {}, rinlinejQuery = /^jQuery\d+$/; $.each(elem.attributes, function(i, attr) { if (attr.specified && !rinlinejQuery.test(attr.name)) { newAttrs[attr.name] = attr.value; } }); return newAttrs; } function clearPlaceholder(event, value) { var input = this, $input = $(input); if (input.value == $input.attr('placeholder') && $input.hasClass('placeholder')) { if ($input.data('placeholder-password')) { $input = $input.hide().next().show().attr('id', $input.removeAttr('id').data('placeholder-id')); // If `clearPlaceholder` was called from `$.valHooks.input.set` if (event === true) { return $input[0].value = value; } $input.focus(); } else { input.value = ''; $input.removeClass('placeholder'); input == document.activeElement && input.select(); } } } function setPlaceholder() { var $replacement, input = this, $input = $(input), $origInput = $input, id = this.id; if (input.value == '') { if (input.type == 'password') { if (!$input.data('placeholder-textinput')) { try { $replacement = $input.clone().attr({ 'type': 'text' }); } catch(e) { $replacement = $('<input>').attr($.extend(args(this), { 'type': 'text' })); } $replacement .removeAttr('name') .data({ 'placeholder-password': true, 'placeholder-id': id }) .bind('focus.placeholder', clearPlaceholder); $input .data({ 'placeholder-textinput': $replacement, 'placeholder-id': id }) .before($replacement); } $input = $input.removeAttr('id').hide().prev().attr('id', id).show(); // Note: `$input[0] != input` now! } $input.addClass('placeholder'); $input[0].value = $input.attr('placeholder'); } else { $input.removeClass('placeholder'); } } }(this, document, jQuery));
JavaScript
;(function ($, window, undefined) { 'use strict'; $.fn.foundationMediaQueryViewer = function (options) { var settings = $.extend(options,{toggleKey:77}), // Press 'M' $doc = $(document); $doc.on("keyup.mediaQueryViewer", ":input", function (e){ if (e.which === settings.toggleKey) { e.stopPropagation(); } }); $doc.on("keyup.mediaQueryViewer", function (e) { var $mqViewer = $('#fqv'); if (e.which === settings.toggleKey) { if ($mqViewer.length > 0) { $mqViewer.remove(); } else { $('body').prepend('<div id="fqv" style="position:fixed;top:4px;left:4px;z-index:999;color:#fff;"><p style="font-size:12px;background:rgba(0,0,0,0.75);padding:5px;margin-bottom:1px;line-height:1.2;"><span class="left">Media:</span> <span style="font-weight:bold;" class="show-for-xlarge">Extra Large</span><span style="font-weight:bold;" class="show-for-large">Large</span><span style="font-weight:bold;" class="show-for-medium">Medium</span><span style="font-weight:bold;" class="show-for-small">Small</span><span style="font-weight:bold;" class="show-for-landscape">Landscape</span><span style="font-weight:bold;" class="show-for-portrait">Portrait</span><span style="font-weight:bold;" class="show-for-touch">Touch</span></p></div>'); } } }); }; })(jQuery, this);
JavaScript
/* * jQuery Custom Forms Plugin 1.0 * www.ZURB.com * Copyright 2010, ZURB * Free to use under the MIT license. * http://www.opensource.org/licenses/mit-license.php */ (function( $ ){ /** * Helper object used to quickly adjust all hidden parent element's, display and visibility properties. * This is currently used for the custom drop downs. When the dropdowns are contained within a reveal modal * we cannot accurately determine the list-item elements width property, since the modal's display property is set * to 'none'. * * This object will help us work around that problem. * * NOTE: This could also be plugin. * * @function hiddenFix */ var hiddenFix = function() { return { /** * Sets all hidden parent elements and self to visibile. * * @method adjust * @param {jQuery Object} $child */ // We'll use this to temporarily store style properties. tmp : [], // We'll use this to set hidden parent elements. hidden : null, adjust : function( $child ) { // Internal reference. var _self = this; // Set all hidden parent elements, including this element. _self.hidden = $child.parents().andSelf().filter( ":hidden" ); // Loop through all hidden elements. _self.hidden.each( function() { // Cache the element. var $elem = $( this ); // Store the style attribute. // Undefined if element doesn't have a style attribute. _self.tmp.push( $elem.attr( 'style' ) ); // Set the element's display property to block, // but ensure it's visibility is hidden. $elem.css( { 'visibility' : 'hidden', 'display' : 'block' } ); }); }, // end adjust /** * Resets the elements previous state. * * @method reset */ reset : function() { // Internal reference. var _self = this; // Loop through our hidden element collection. _self.hidden.each( function( i ) { // Cache this element. var $elem = $( this ), _tmp = _self.tmp[ i ]; // Get the stored 'style' value for this element. // If the stored value is undefined. if( _tmp === undefined ) // Remove the style attribute. $elem.removeAttr( 'style' ); else // Otherwise, reset the element style attribute. $elem.attr( 'style', _tmp ); }); // Reset the tmp array. _self.tmp = []; // Reset the hidden elements variable. _self.hidden = null; } // end reset }; // end return }; jQuery.foundation = jQuery.foundation || {}; jQuery.foundation.customForms = jQuery.foundation.customForms || {}; $.foundation.customForms.appendCustomMarkup = function ( options ) { var defaults = { disable_class: "js-disable-custom" }; options = $.extend( defaults, options ); function appendCustomMarkup(idx, sel) { var $this = $(sel).hide(), type = $this.attr('type'), $span = $this.next('span.custom.' + type); if ($span.length === 0) { $span = $('<span class="custom ' + type + '"></span>').insertAfter($this); } $span.toggleClass('checked', $this.is(':checked')); $span.toggleClass('disabled', $this.is(':disabled')); } function appendCustomSelect(idx, sel) { var hiddenFixObj = hiddenFix(); // // jQueryify the <select> element and cache it. // var $this = $( sel ), // // Find the custom drop down element. // $customSelect = $this.next( 'div.custom.dropdown' ), // // Find the custom select element within the custom drop down. // $customList = $customSelect.find( 'ul' ), // // Find the custom a.current element. // $selectCurrent = $customSelect.find( ".current" ), // // Find the custom a.selector element (the drop-down icon). // $selector = $customSelect.find( ".selector" ), // // Get the <options> from the <select> element. // $options = $this.find( 'option' ), // // Filter down the selected options // $selectedOption = $options.filter( ':selected' ), // // Initial max width. // maxWidth = 0, // // We'll use this variable to create the <li> elements for our custom select. // liHtml = '', // // We'll use this to cache the created <li> elements within our custom select. // $listItems ; var $currentSelect = false; // // Should we not create a custom list? // if ( $this.hasClass( 'no-custom' ) ) return; // // Did we not create a custom select element yet? // if ( $customSelect.length === 0 ) { // // Let's create our custom select element! // // // Determine what select size to use. // var customSelectSize = $this.hasClass( 'small' ) ? 'small' : $this.hasClass( 'medium' ) ? 'medium' : $this.hasClass( 'large' ) ? 'large' : $this.hasClass( 'expand' ) ? 'expand' : '' ; // // Build our custom list. // $customSelect = $('<div class="' + ['custom', 'dropdown', customSelectSize ].join( ' ' ) + '"><a href="#" class="selector"></a><ul /></div>"'); // // Grab the selector element // $selector = $customSelect.find( ".selector" ); // // Grab the unordered list element from the custom list. // $customList = $customSelect.find( "ul" ); // // Build our <li> elements. // liHtml = $options.map( function() { return "<li>" + $( this ).html() + "</li>"; } ).get().join( '' ); // // Append our <li> elements to the custom list (<ul>). // $customList.append( liHtml ); // // Insert the the currently selected list item before all other elements. // Then, find the element and assign it to $currentSelect. // $currentSelect = $customSelect.prepend( '<a href="#" class="current">' + $selectedOption.html() + '</a>' ).find( ".current" ); // // Add the custom select element after the <select> element. // $this.after( $customSelect ) // //then hide the <select> element. // .hide(); } else { // // Create our list item <li> elements. // liHtml = $options.map( function() { return "<li>" + $( this ).html() + "</li>"; } ).get().join( '' ); // // Refresh the ul with options from the select in case the supplied markup doesn't match. // Clear what's currently in the <ul> element. // $customList.html( '' ) // // Populate the list item <li> elements. // .append( liHtml ); } // endif $customSelect.length === 0 // // Determine whether or not the custom select element should be disabled. // $customSelect.toggleClass( 'disabled', $this.is( ':disabled' ) ); // // Cache our List item elements. // $listItems = $customList.find( 'li' ); // // Determine which elements to select in our custom list. // $options.each( function ( index ) { if ( this.selected ) { // // Add the selected class to the current li element // $listItems.eq( index ).addClass( 'selected' ); // // Update the current element with the option value. // if ($currentSelect) { $currentSelect.html( $( this ).html() ); } } }); // // Update the custom <ul> list width property. // $customList.css( 'width', 'inherit' ); // // Set the custom select width property. // $customSelect.css( 'width', 'inherit' ); // // If we're not specifying a predetermined form size. // if ( !$customSelect.is( '.small, .medium, .large, .expand' ) ) { // ------------------------------------------------------------------------------------ // This is a work-around for when elements are contained within hidden parents. // For example, when custom-form elements are inside of a hidden reveal modal. // // We need to display the current custom list element as well as hidden parent elements // in order to properly calculate the list item element's width property. // ------------------------------------------------------------------------------------- // // Show the drop down. // This should ensure that the list item's width values are properly calculated. // $customSelect.addClass( 'open' ); // // Quickly, display all parent elements. // This should help us calcualate the width of the list item's within the drop down. // hiddenFixObj.adjust( $customList ); // // Grab the largest list item width. // maxWidth = ( $listItems.outerWidth() > maxWidth ) ? $listItems.outerWidth() : maxWidth; // // Okay, now reset the parent elements. // This will hide them again. // hiddenFixObj.reset(); // // Finally, hide the drop down. // $customSelect.removeClass( 'open' ); // // Set the custom list width. // $customSelect.width( maxWidth + 18); // // Set the custom list element (<ul />) width. // $customList.width( maxWidth + 16 ); } // endif } $('form.custom input:radio[data-customforms!=disabled]').each(appendCustomMarkup); $('form.custom input:checkbox[data-customforms!=disabled]').each(appendCustomMarkup); $('form.custom select[data-customforms!=disabled]').each(appendCustomSelect); }; var refreshCustomSelect = function($select) { var maxWidth = 0, $customSelect = $select.next(); $options = $select.find('option'); $customSelect.find('ul').html(''); $options.each(function () { $li = $('<li>' + $(this).html() + '</li>'); $customSelect.find('ul').append($li); }); // re-populate $options.each(function (index) { if (this.selected) { $customSelect.find('li').eq(index).addClass('selected'); $customSelect.find('.current').html($(this).html()); } }); // fix width $customSelect.removeAttr('style') .find('ul').removeAttr('style'); $customSelect.find('li').each(function () { $customSelect.addClass('open'); if ($(this).outerWidth() > maxWidth) { maxWidth = $(this).outerWidth(); } $customSelect.removeClass('open'); }); $customSelect.css('width', maxWidth + 18 + 'px'); $customSelect.find('ul').css('width', maxWidth + 16 + 'px'); }; var toggleCheckbox = function($element) { var $input = $element.prev(), input = $input[0]; if (false === $input.is(':disabled')) { input.checked = ((input.checked) ? false : true); $element.toggleClass('checked'); $input.trigger('change'); } }; var toggleRadio = function($element) { var $input = $element.prev(), input = $input[0]; if (false === $input.is(':disabled')) { $('input:radio[name="' + $input.attr('name') + '"]').next().not($element).removeClass('checked'); if ($element.hasClass('checked')) { // Do Nothing } else { $element.toggleClass('checked'); } input.checked = $element.hasClass('checked'); $input.trigger('change'); } }; $(document).on('click', 'form.custom span.custom.checkbox', function (event) { event.preventDefault(); event.stopPropagation(); toggleCheckbox($(this)); }); $(document).on('click', 'form.custom span.custom.radio', function (event) { event.preventDefault(); event.stopPropagation(); toggleRadio($(this)); }); $(document).on('change', 'form.custom select[data-customforms!=disabled]', function (event) { refreshCustomSelect($(this)); }); $(document).on('click', 'form.custom label', function (event) { var $associatedElement = $('#' + $(this).attr('for')), $customCheckbox, $customRadio; if ($associatedElement.length !== 0) { if ($associatedElement.attr('type') === 'checkbox') { event.preventDefault(); $customCheckbox = $(this).find('span.custom.checkbox'); toggleCheckbox($customCheckbox); } else if ($associatedElement.attr('type') === 'radio') { event.preventDefault(); $customRadio = $(this).find('span.custom.radio'); toggleRadio($customRadio); } } }); $(document).on('click', 'form.custom div.custom.dropdown a.current, form.custom div.custom.dropdown a.selector', function (event) { var $this = $(this), $dropdown = $this.closest('div.custom.dropdown'), $select = $dropdown.prev(); event.preventDefault(); $('div.dropdown').removeClass('open'); if (false === $select.is(':disabled')) { $dropdown.toggleClass('open'); if ($dropdown.hasClass('open')) { $(document).bind('click.customdropdown', function (event) { $dropdown.removeClass('open'); $(document).unbind('.customdropdown'); }); } else { $(document).unbind('.customdropdown'); } return false; } }); $(document).on('click', 'form.custom div.custom.dropdown li', function (event) { var $this = $(this), $customDropdown = $this.closest('div.custom.dropdown'), $select = $customDropdown.prev(), selectedIndex = 0; event.preventDefault(); event.stopPropagation(); $('div.dropdown').removeClass('open'); $this .closest('ul') .find('li') .removeClass('selected'); $this.addClass('selected'); $customDropdown .removeClass('open') .find('a.current') .html($this.html()); $this.closest('ul').find('li').each(function (index) { if ($this[0] == this) { selectedIndex = index; } }); $select[0].selectedIndex = selectedIndex; $select.trigger('change'); }); $.fn.foundationCustomForms = $.foundation.customForms.appendCustomMarkup; })( jQuery );
JavaScript
;(function ($, window, undefined) { 'use strict'; $.fn.foundationButtons = function(options) { var $doc = $(document); // Prevent event propagation on disabled buttons $doc.on('click.fndtn', '.button.disabled', function (e) { e.preventDefault(); }); $('.button.dropdown > ul', this).addClass('no-hover'); $doc.on('click.fndtn', '.button.dropdown, .button.dropdown.split span', function (e) { // Stops further propagation of the event up the DOM tree when clicked on the button. // Events fired by its descendants are not being blocked. $('.button.dropdown').children('ul').removeClass('show-dropdown'); if (e.target === this) { e.stopPropagation(); } }); $doc.on('click.fndtn', '.button.dropdown.split span', function (e) { e.preventDefault(); $('.button.dropdown', this).not($(this).parent()).children('ul').removeClass('show-dropdown'); $(this).siblings('ul').toggleClass('show-dropdown'); }); $doc.on('click.fndtn', '.button.dropdown:not(.split)', function (e) { $('.button.dropdown', this).not(this).children('ul').removeClass('show-dropdown'); $(this).children('ul').toggleClass('show-dropdown'); }); $doc.on('click.fndtn', 'body, html', function () { $('.button.dropdown ul').removeClass('show-dropdown'); }); // Positioning the Flyout List var normalButtonHeight = $('.button.dropdown:not(.large):not(.small):not(.tiny)', this).outerHeight() - 1, largeButtonHeight = $('.button.large.dropdown', this).outerHeight() - 1, smallButtonHeight = $('.button.small.dropdown', this).outerHeight() - 1, tinyButtonHeight = $('.button.tiny.dropdown', this).outerHeight() - 1; $('.button.dropdown:not(.large):not(.small):not(.tiny) > ul', this).css('top', normalButtonHeight); $('.button.dropdown.large > ul', this).css('top', largeButtonHeight); $('.button.dropdown.small > ul', this).css('top', smallButtonHeight); $('.button.dropdown.tiny > ul', this).css('top', tinyButtonHeight); $('.button.dropdown.up:not(.large):not(.small):not(.tiny) > ul', this).css('top', 'auto').css('bottom', normalButtonHeight - 2); $('.button.dropdown.up.large > ul', this).css('top', 'auto').css('bottom', largeButtonHeight - 2); $('.button.dropdown.up.small > ul', this).css('top', 'auto').css('bottom', smallButtonHeight - 2); $('.button.dropdown.up.tiny > ul', this).css('top', 'auto').css('bottom', tinyButtonHeight - 2); }; })( jQuery, this );
JavaScript
;(function ($, window, undefined) { 'use strict'; $.fn.foundationNavigation = function (options) { var lockNavBar = false; // Windows Phone, sadly, does not register touch events :( if (Modernizr.touch || navigator.userAgent.match(/Windows Phone/i)) { $(document).on('click.fndtn touchstart.fndtn', '.nav-bar a.flyout-toggle', function (e) { e.preventDefault(); var flyout = $(this).siblings('.flyout').first(); if (lockNavBar === false) { $('.nav-bar .flyout').not(flyout).slideUp(500); flyout.slideToggle(500, function () { lockNavBar = false; }); } lockNavBar = true; }); $('.nav-bar>li.has-flyout', this).addClass('is-touch'); } else { $('.nav-bar>li.has-flyout', this).hover(function () { $(this).children('.flyout').show(); }, function () { $(this).children('.flyout').hide(); }); } }; })( jQuery, this );
JavaScript
// Toggle text between current and data-toggle-text contents $.fn.extend({ toggleText: function() { var self = $(this); var text = self.text(); var ttext = self.data('toggle-text'); var tclass = self.data('toggle-class'); self.text(ttext).data('toggle-text', text).toggleClass(tclass); } });
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ ahoy.common = {}; /** * Settings */ ahoy.settings = { date_format: "dd/mm/yy" } /** * User Menu */ ahoy.common.user_menu = { init: function() { $('#user_menu .user > li').click(function(){ $(this).children('ul:first').slideToggle().end().closest('#user_menu').toggleClass('expanded'); }); } }; /** * Auto init expander plugin */ jQuery(document).ready(function($) { $('.expander').each(function() { var slice_at = $(this).data('slice-point'); var expand_text = $(this).data('expand-text'); $(this).expander({ slicePoint: slice_at, expandText: expand_text, userCollapseText: '' }); }); }); /** * "Click Outside" plugin */ $.fn.extend({ // Calls the handler function if the user has clicked outside the object (and not on any of the exceptions) clickOutside: function(handler, exceptions) { var $this = this; $("body").bind("click", function(event) { if (exceptions && $.inArray(event.target, exceptions) > -1) { return; } else if ($.contains($this[0], event.target)) { return; } else { handler(event, $this); } }); return this; } });
JavaScript
/** * Loading Panel */ window.site = { message: { remove: function() { $.removebar(); }, custom: function(message, params) { if(!message) return; var params = $.extend({ position: 'top', removebutton: false, color: '#666', message: message, time: 5000, background_color: '#393536' }, params || {}); jQuery(document).ready(function($) { $.bar(params); }); } } }; Phpr.showLoadingIndicator = function() { site.message.custom('Processing...', {background_color: '#f7c809', color: '#000', time: 999999}); }; Phpr.hideLoadingIndicator = function() { site.message.remove(); }; Phpr.response.popupError = function() { site.message.custom(this.html.replace('@AJAX-ERROR@', ''), {background_color: '#c32611', color: '#fff', time: 10000}); };
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /* // Foundation @require frameworks/foundation/modernizr.foundation.js; @require frameworks/foundation/jquery.placeholder.js; @require frameworks/foundation/jquery.foundation.alerts.js; @require frameworks/foundation/jquery.foundation.accordion.js; @require frameworks/foundation/jquery.foundation.buttons.js; @require frameworks/foundation/jquery.foundation.tooltips.js; @require frameworks/foundation/jquery.foundation.forms.js; @require frameworks/foundation/jquery.foundation.tabs.js; @require frameworks/foundation/jquery.foundation.navigation.js; @require frameworks/foundation/jquery.foundation.reveal.js; @require frameworks/foundation/jquery.foundation.orbit.js; @require frameworks/foundation/jquery.offcanvas.js; @require frameworks/foundation/app.js; // Utility @require frameworks/utility/jquery.utility.toggletext.js; @require frameworks/utility/jquery.waterfall.js; // Vendor @require ../vendor/jbar/jquery-bar.js; @require ../vendor/ui/jquery-ui.js; @require ../vendor/date/date.js; @require ../vendor/fileupload/jquery-fileupload.js; @require ../vendor/fileupload/jquery-iframe-transport.js; @require ../vendor/carousel/js/jquery.jcarousel.js; @require ../vendor/stars/jquery-ui-stars.js; @require ../vendor/expander/jquery.expander.js; // Scripts Ahoy! @require ahoy/jquery.validate.js; @require ahoy/jquery.validate.ext.js; @require ahoy/ahoy.validation.js; @require ahoy/ahoy.form.js; @require ahoy/ahoy.post.js; @require ahoy.js; // App @require phpr.js; @require common.js; @require forms.js; @require pages/pages.js; */
JavaScript
var Ahoy_Page = (function(page, $){ page.constructor = $(function() { $('#featured_providers').orbit({ animation: 'horizontal-push', bullets: true, captions: true, directionalNav: false, fluid: true }); $('#banners .sub_banner').click(function(){ window.location = $(this).data('link'); }); }); return page; }(Ahoy_Page || {}, jQuery));
JavaScript
ahoy.page_dashboard = { init: function() { var self = ahoy.page_dashboard; $('#p_dash_offers .sub-nav a').live('click', function(){ var type = $(this).data('filter-type'); self.filter_job_offers(type); }); }, filter_job_offers: function(type) { ahoy.post().action('bluebell:on_dashboard_filter_job_offers').data('filter', type).update('#p_dash_offers', 'dash:offers').send(); } };
JavaScript
/* @require ../behaviors/behavior_upload.js; */ // TODO: Deprecate in favour of behavior ahoy.page_request = { active_step: 'create', init: function() { var self = ahoy.page_request; // Initialize self.style_form(); self.validate_form(); self.bind_required_by(); // Alternative time $('#link_request_alt_time').click(self.click_alt_time); // Remote location $('#location_remote').change(function() { self.click_location_remote(this); }); self.click_location_remote('#location_remote'); // Add photos $('#input_add_photos').behavior(ahoy.behaviors.upload_image_multi, {link_id:'#link_add_photos', param_name:'request_images[]'}); }, style_form: function() { // Bold first word $('#page_request section > label.heading').each(function() { $(this).html($(this).text().replace(/(^\w+|\s+\w+)/,'<strong>$1</strong>')); }); }, // Edit request bind_edit_request: function() { var self = ahoy.page_request; $('#edit_request').click(self.click_edit_request); $('#toggle_login, #toggle_register').click(self.click_account_request); }, // Required by logic bind_required_by: function() { var self = ahoy.page_request; var required_by = $('#page_request section.required_by'); var checked = required_by.find('ul.radio_group label input:checked'); self.click_required_by(checked); required_by.find('label input').change(function() { self.click_required_by(this); }); }, click_required_by: function(element) { var label = $(element).parent(); var required_by = $('#page_request section.required_by'); required_by.find('label').removeClass('selected'); required_by.find('.radio_expand').hide(); label.addClass('selected').next('.radio_expand').show(); }, click_alt_time: function() { $(this).toggleText(); $(this).prev().toggleText(); var container = $('#page_request .firm_date_secondary').toggle(); container.find('select').each(function() { $(this).trigger('change'); }); }, click_location_remote: function(obj) { var checked = $(obj).is(':checked'); var location = $('#request_location'); location.attr('disabled', checked); if (checked) { location.val('').removeClass('error valid').next('.float_error').remove(); } }, validate_form: function(extra_rules, extra_messages) { var options = { messages: ahoy.partial_request_simple_form.validate_messages, rules: ahoy.partial_request_simple_form.validate_rules, submitHandler: ahoy.page_request.submit_form }; if (extra_rules) options.rules = $.extend(true, options.rules, extra_rules); if (extra_messages) options.messages = $.extend(true, options.messages, extra_messages); ahoy.validate.init($('#form_request'), options); }, submit_form: function() { var self = ahoy.page_request; switch (self.active_step) { // Create case 'create': self.check_category(function(result){ $('#request_category_id').val(result.id); $('#request_title').val(result.name); self.display_step('review'); }, function() { self.display_step('assist'); }); break; // Assist case 'assist': self.display_step('review'); break; // Review case 'review': var files = []; $('#panel_photos div.image').each(function(){ files.push($(this).attr('data-image-id')); }); ahoy.post('#form_request').action('bluebell:on_request_submit').data('files', files).send(); break; } return false; }, display_step: function(step_name) { var self = ahoy.page_request; self.active_step = step_name; $('#page_request > section, #page_request > form > section').hide(); switch (step_name) { default: case "create": $('#page_request section.create').show(); break; case "assist": $('#page_request section.assist').show(); self.init_assist(); break; case "review": $('#page_request section.review').show(); ahoy.post($('#form_request')) .action('bluebell:on_request_submit') .data('preview', true) .update('#p_review_form', 'request:review_form') .complete(function(){ self.bind_edit_request(); }, true) .send(); // User not logged in, validate the accounting partial if ($('#p_account').length > 0) self.validate_account_form(); break; } $('html, body').animate({scrollTop:0}, 0); }, check_category: function(success, fail) { ahoy.post($('#request_title')) .action('service:on_search_categories').data('name',$('#request_title').val()) .success(function(raw_data, data){ var result = $.parseJSON(data); var found_category = false; $.each(result, function(k,v){ if (v.parent_id) { // Only allow child categories found_category = true; } }); if (found_category) success(result[0]); else fail(); }) .send(); }, click_edit_request: function() { ahoy.page_request.display_step('create'); }, /** * Account logic */ validate_account_form: function(is_login) { if (is_login) { if (ahoy.partial_site_register_form !== undefined) ahoy.validate.set_rules('#form_request', 'partial_site_register_form', true); if (ahoy.partial_site_login_form !== undefined) ahoy.validate.set_rules('#form_request', 'partial_site_login_form'); } else { if (ahoy.partial_site_login_form !== undefined) ahoy.validate.set_rules('#form_request', 'partial_site_login_form', true); if (ahoy.partial_site_register_form !== undefined) ahoy.validate.set_rules('#form_request', 'partial_site_register_form'); } }, click_account_request: function() { var self = ahoy.page_request; var is_register = $('#title_register').is(':visible'); var ajax = ahoy.post($('#form_request')) .action('core:on_null').success(function(){ $('#title_register, #title_login').toggle(); }) .complete(function(){ self.validate_account_form(is_register); }, true); if (is_register) ajax.update('#p_account', 'site:login_form').send(); else ajax.update('#p_account', 'site:register_form').send(); }, /** * Assist logic */ init_assist: function() { var self = ahoy.page_request; // Assist sub nav $('#page_request section.assist .sub-nav a').click(function() { $(this).parent().siblings().removeClass('active').end().addClass('active'); if ($(this).hasClass('category')) { $('#category_form_select_category').show(); $('#category_form_select_alpha').hide(); } else { $('#category_form_select_category').hide(); $('#category_form_select_alpha').show(); } return false; }); self.populate_categories(); self.validate_assist_form(); // Assist selection $('#select_parent').change(function(){ var parent_id = $(this).val(); $('#select_category').empty(); $('#select_alpha option').each(function() { if ($(this).attr('data-parent-id') == parent_id) $('#select_category').append($(this).clone()); }); }); $('#select_category, #select_alpha').change(function(){ $('#request_category_id').val($(this).val()); $('#request_title').val($(this).children('option:selected').text()); }); }, populate_categories: function() { $('#select_parent, #select_category, #select_alpha').empty(); ahoy.post($('#select_parent')).action('service:on_search_categories').success(function(raw_data, data){ var result = $.parseJSON(data); $.each(result, function(k,v){ if (v.parent_id) $('<option />').val(v.id).text(v.name).attr('data-parent-id',v.parent_id).appendTo($('#select_alpha')); else $('<option />').val(v.id).text(v.name).appendTo($('#select_parent')); }); }).send(); }, validate_assist_form: function() { ahoy.validate.init($('#form_assist'), { rules: { select_category: { required: true }, select_alpha: { required: true } }, submitHandler: ahoy.page_request.submit_form }); } };
JavaScript
/* @require ../frameworks/utility/jquery.gmap3.js; @require ../frameworks/utility/jquery.utility.gmap.js; */ ahoy.page_job_booking = { map: null, address: null, init: function() { var self = ahoy.page_job_booking; // Low priority load $(window).load(self.bind_address_map); // Init others self.bind_question_answers(); self.bind_booking_time(); self.bind_job_cancel(); self.bind_rating_form(); }, bind_question_answers: function() { $('#job_questions span.answer').hide(); $('#job_questions a.question').bind('click', function() { $('#job_questions span.answer').hide(); $(this).next().show(); }) }, bind_address_map: function() { var self = ahoy.page_job_booking; self.map = $('#map_booking_address'); var address = $('#booking_address'); var address_string = address.text(); if (address.length==0 || self.map.length==0) return; self.map.gmap({ start_address: address_string, show_zoom_ui: true, allow_drag: false, allow_scrollwheel: false, alow_dbl_click_zoom: false }).gmap('get_object_from_address_string', address_string, function(address){ self.address = address; self.map .gmap('align_to_address_object', address) .gmap('set_zoom', 9) .gmap('add_marker_from_address_object', address, 'job_tag'); }); // Auto align map to center $(window).bind('resize', function() { self.map.gmap('align_to_address_object', self.address) }); }, // Suggest booking time bind_booking_time: function() { var self = ahoy.page_job_booking; var booking_time_link = $('#link_booking_time_suggest'); var booking_time_form = $('#form_booking_time'); var booking_time_container = $('#booking_time_suggest_container'); booking_time_link.click(function() { booking_time_container.show(); $('#booking_time_time').trigger('change'); }); // Validate ahoy.validate.bind(booking_time_form, 'partial_job_booking_time', function() { return ahoy.post(booking_time_form) .action('bluebell:on_request_booking_time') .update('#p_job_booking_time', 'job:booking_time') .success(function() { self.bind_booking_time(); $.foundation.customForms.appendCustomMarkup(); }) .send(); }); }, // Cancel job bind_job_cancel: function() { ahoy.behavior('#popup_job_cancel', 'popup', { trigger: '#link_job_cancel' }); $('#button_job_cancel').click(function() { var request_id = $(this).data('request-id'); ahoy.post().action('bluebell:on_cancel_booking').data('request_id', request_id).send(); }); }, // Leave a rating bind_rating_form: function() { ahoy.validate.bind($('#form_rating'), 'partial_job_rating_form', function() { ahoy.post('#form_rating').action('service:on_rating_submit').update('#p_job_rating_form', 'job:rating_form').send(); }); } };
JavaScript
/* @require ../behaviors/behavior_upload.js; @require ../behaviors/behavior_portfolio.js; @require ../behaviors/behavior_request_quotes.js; */ ahoy.page_request_manage = { init: function() { var self = ahoy.page_request_manage; // Quotes $('#p_quotes').behavior(ahoy.behaviors.request_quotes); // Init others self.bind_add_description(); self.bind_question_submenu(); self.bind_request_cancel(); self.bind_extend_time(); }, // Add photos bind_add_photos: function() { $('#input_add_photos').behavior(ahoy.behaviors.upload_image_multi, { link_id:'#link_add_photos', param_name:'request_images[]', on_remove: function(obj, file_id) { ahoy.post('#input_add_photos').action('service:on_request_remove_file').data('file_id', file_id).send(); } }); }, // Description // bind_add_description: function() { $('#link_add_description, #link_add_description_cancel').live('click', function(){ $('#panel_add_description').toggle(); $('#link_add_description').toggleText(); }); }, validate_add_description: function(rules, messages) { ahoy.validate.init($('#form_add_description'), { rules: rules, messages: messages, submitHandler: function() { ahoy.post('#form_add_description').action('service:on_request_describe').update('#p_details', 'request:manage_details').send(); } }); }, // Questions // bind_question_submenu: function() { var container = $('#p_questions'); container.find('.answer_form.flagged').hide(); container.find('.sub-nav a').click(function() { var type = $(this).data('filter-type'); container.find('dd').removeClass('active'); $(this).parent().addClass('active'); if (type=="all") container.find('.answer_form').show().end().find('.answer_form.flagged').hide(); else if (type=="unanswered") container.find('.answer_form').hide().end().find('.answer_form.unanswered').show(); else if (type=="flagged") container.find('.answer_form').hide().end().find('.answer_form.flagged').show(); }); }, question_edit_toggle: function(question_id) { var form = $('#form_answer_question_'+question_id); form.find('.view').toggle(); form.find('.edit').toggle(); }, question_flag: function(question_id, remove_flag) { var self = ahoy.page_request_manage; var form = $('#form_answer_question_'+question_id); var ajax = ahoy.post(form).action('service:on_question_flag'); if (remove_flag) ajax.data('remove_flag', true); ajax.update('#p_request_answer_form_'+question_id, 'request:answer_form') .complete(function() { self.question_validate_form(question_id); $('#form_answer_question_'+question_id).parent().hide(); },true); return ajax.send(); }, question_validate_form: function(question_id, status) { var self = ahoy.page_request_manage; var action = (status=="answered") ? 'service:on_answer_update' : 'service:on_answer_submit'; var form = $('#form_answer_question_'+question_id); ahoy.validate.bind(form, 'partial_request_answer_form', function() { return ahoy.post(form) .action(action) .update('#p_request_answer_form_'+question_id, 'request:answer_form') .complete(function() { self.question_validate_form(question_id); },true) .send(); }); }, // Cancel request bind_request_cancel: function() { ahoy.behavior('#popup_request_cancel', 'popup', { trigger: '#link_request_cancel' }); $('#button_request_cancel').click(function() { var request_id = $(this).data('request-id'); ahoy.post().action('service:on_request_cancel').data('request_id', request_id).data('redirect', root_url('dashboard')).send(); }); }, // Extend request time bind_extend_time: function() { var self = ahoy.page_request_manage; $('#link_extend_time').click(function() { var request_id = $(this).data('request-id'); ahoy.post().action('service:on_request_extend_time') .data('request_id', request_id) .update('#p_status_panel', 'request:status_panel') .success(self.bind_extend_time) .send(); }); } };
JavaScript
/* @require ../frameworks/utility/jquery.gmap3.js; @require ../frameworks/utility/jquery.utility.gmap.js; @require ../behaviors/behavior_upload.js; @require ../behaviors/behavior_portfolio.js; @require ../behaviors/behavior_field_editor.js; @require ../behaviors/behavior_provide_hours.js; @require ../behaviors/behavior_provide_radius.js; */ ahoy.page_provide_manage = { init: function() { var self = ahoy.page_provide_manage; // Success popup ahoy.behavior('#popup_profile_success', 'popup', { trigger: '#button_done' }); // Image uploads $('#input_provide_photo').behavior(ahoy.behaviors.upload_image, { link_id: '#link_provide_photo', remove_id: '#link_provide_photo_remove', image_id: '#provide_photo', param_name:'provider_photo', on_success: function(obj, data) { $('#link_provide_photo').hide(); }, on_remove: function() { $('#link_provide_photo').fadeIn(1000); ahoy.post($('#input_provide_photo')).action('service:on_provider_update_photo').data('delete', true).send(); } }); $('#input_provide_logo').behavior(ahoy.behaviors.upload_image, { link_id: '#link_provide_logo', remove_id: '#link_provide_logo_remove', image_id: '#provide_logo', param_name:'provider_logo', on_success: function(obj, data) { $('#link_provide_logo').hide(); }, on_remove: function() { $('#link_provide_logo').fadeIn(1000); $('#provide_logo').hide(); ahoy.post($('#input_provide_logo')).action('service:on_provider_update_logo').data('delete', true).send(); return false; } }); // Init others self.bind_profile_fields(); self.bind_profile_description(); self.bind_profile_testimonials(); self.bind_work_radius(); self.bind_work_hours(); self.bind_portfolio(); self.bind_profile_delete(); }, // Profile fields bind_profile_fields: function() { var self = this; // Save event var save_profile_field = function(object, element, value) { // Check form is valid var form = element.closest('form'); if (form.valid()) { // Save profile field ahoy.post(element).action('bluebell:on_provider_update').send(); } }; // Editing $('#p_profile_form') .behavior(ahoy.behaviors.field_editor, { on_set_field: save_profile_field }) .behavior('apply_validation', [$('#form_provide_details'), 'partial_provide_profile_details']); // Role auto complete ahoy.behavior('#provide_role_name', 'role_select', { on_select: function(obj, value){ $('#provide_role_name').prev('label').text(value); } }); // Select country, populate state ahoy.behavior('#provide_country_id', 'select_country', { state_element_id:'#provide_state_id', after_update: function(obj) { obj.state_element = $('#provide_country_id').parent().next().children().first(); } }); // Marry provide_radius and field_editor functionality $('#profile_details_address').bind('field_editor.field_set', function(e, value) { $('#work_radius_address').val(value).trigger('change'); }); }, // Profile description bind_profile_description: function() { // Popup ahoy.behavior('#popup_profile_description', 'popup', { trigger: '#button_profile_description' }); // Save $('#form_provide_decription').submit(function() { ahoy.post('#form_provide_decription').action('bluebell:on_provider_manage_description').update('#p_provide_description', 'provide:description').send(); $('#popup_profile_description').behavior('close_popup'); return false; }); }, // Testimonials bind_profile_testimonials: function() { // Popup ahoy.behavior('#popup_profile_testimonials', 'popup', { trigger: '#button_profile_testimonials' }); // Save ahoy.validate.bind($('#form_provide_testimonials'), 'partial_provide_testimonials_form', function() { ahoy.post($('#form_provide_testimonials')).action('service:on_testimonial_ask').success(function(){ $('#form_provide_testimonials').hide(); $('#profile_testimonials_success').show(); }).send(); }); // Delete $('#p_provide_testimonials .button_delete_testimonial').live('click', function() { var testimonial_id = $(this).data('testimonial-id'); var provider_id = $(this).data('provider-id'); var confirm = $(this).data('confirm'); ahoy.post().action('service:on_testimonial_remove') .data('testimonial_id', testimonial_id) .data('provider_id', provider_id) .update('#p_provide_testimonials', 'provide:testimonials') .confirm(confirm) .send(); }); }, // Portfolio bind_portfolio: function() { // Popup ahoy.behavior('#popup_profile_portfolio', 'popup', { size: 'expand', trigger: '.button_profile_portfolio', on_close: function() { ahoy.post('#form_provide_portfolio') .action('service:on_refresh_provider_portfolio') .data('is_manage', true) .update('#p_provide_portfolio', 'provide:portfolio') .prepare(function(){ $('#provider_portfolio').behavior('destroy'); }) .send(); } }); // Uploader $('#input_add_photos').behavior(ahoy.behaviors.upload_image_multi, { link_id:'#link_add_photos', param_name:'provider_portfolio[]', on_remove: function(obj, file_id) { ahoy.post('#input_add_photos').action('service:on_provider_update_portfolio').data('file_id', file_id).data('delete', true).send(); } }); }, // Work radius bind_work_radius: function() { // Map $('#p_work_radius_form').provide_radius({ on_complete: function(obj) { $('#provider_service_codes').val('|' + obj.get_nearby_postcodes().join('|') + '|'); }, radius_max: $('#work_radius_max').val(), radius_unit: $('#work_radius_unit').val() }); // Prepopulate map $('#work_radius_address').val($('#profile_details_address label').text()).trigger('change'); // Popup ahoy.behavior('#popup_work_radius', 'popup', { trigger: '#link_work_area', size:'expand' }); // Save $('#form_work_radius').submit(function() { ahoy.post('#form_work_radius').action('bluebell:on_provider_update').send(); $('#popup_work_radius').behavior('close_popup'); return false; }); }, // Work hours bind_work_hours: function() { // Behavior $('#p_work_hours_form').behavior(ahoy.behaviors.provide_hours, { use_general: false }); // Popup ahoy.behavior('#popup_work_hours', 'popup', { trigger: '#link_work_hours', size:'large' }); // Save $('#form_work_hours').submit(function() { ahoy.post('#form_work_hours').action('bluebell:on_provider_update').send(); $('#popup_work_hours').behavior('close_popup'); return false; }); }, // Profile delete bind_profile_delete: function() { ahoy.behavior('#popup_profile_delete', 'popup', { trigger: '#link_delete_profile' }); $('#button_profile_delete').click(function() { var provider_id = $(this).data('provider-id'); ahoy.post().action('service:on_delete_provider').data('provider_id', provider_id).data('redirect', root_url('provide/profiles')).send(); }); } };
JavaScript
/** * Account */ ahoy.page_account = { init: function() { var self = ahoy.page_account; self.bind_work_history(); self.bind_notifications(); }, toggle_edit: function(element) { jQuery(element).parents('.block:first').find('.view:first').slideToggle().next('.edit').slideToggle(); }, bind_country_select: function(element) { element = jQuery(element); var state_field = element.parents('div.form-field:first').next('div.form-field').find('select:first'); ahoy.behavior(element, 'select_country', { state_element_id:state_field, after_update: function(obj) { obj.state_element = element.parents('div.form-field:first').next('div.form-field').find('select:first'); } }); }, filter_history: function(mode, submode, page) { var post_obj = ahoy.post($('#form_work_history')) .action('bluebell:on_account_filter_history') .update('#work_historyTab', 'account:work_history'); if (mode) post_obj = post_obj.data('mode', mode); if (submode) post_obj = post_obj.data('submode', submode); if (page) post_obj= post_obj.data('page', page); post_obj.send(); }, bind_work_history: function() { var self = ahoy.page_account; $('#mode_filter a').live('click', function() { var mode = $(this).data('mode'); self.filter_history(mode, null, null); }); $('#submode_filter_offers a').live('click', function() { var submode = $(this).data('submode'); self.filter_history(null, submode, null); }); $('#p_site_pagination a').live('click', function() { var page = $(this).data('page'); self.filter_history(null, null, page); }); }, bind_notifications: function() { $('#form_user_notifications').submit(function() { ahoy.post($('#form_user_notifications')).action('user:on_preferences_update').send(); return false; }); } };
JavaScript
/* @require ../behaviors/behavior_field_editor.js; */ ahoy.page_pay = { init: function() { var self = ahoy.page_pay; // Invoice field editing ahoy.behavior('#form_invoice_details', 'field_editor', { implode_char: ' ', on_set_field: function() { } }); // Select country, populate state ahoy.behavior('#invoice_billing_country_id', 'select_country', { state_element_id:'#invoice_billing_state_id', after_update: function(obj) { obj.state_element = $('#invoice_billing_country_id').parent().next().children().first(); } }); } };
JavaScript
/* @require ../behaviors/behavior_job_quote.js; */ ahoy.page_job = { init: function() { var self = ahoy.page_job; $('#link_edit_quote').live('click', self.click_edit_quote); $('#link_delete_quote').live('click', self.click_delete_quote); // Init others self.bind_ask_question(); self.bind_request_ignore(); }, // Quote // init_quote_forms: function () { var self = ahoy.page_job; // Styles $(window).load(function() { $('select').trigger('change'); }); // Tabs $(document).foundationTabs({callback:$.foundation.customForms.appendCustomMarkup}); $(document).on('click.fndtn', 'dl.tabs dd a', function (event){ $('form.custom select').trigger('change'); }); // Forms self.bind_quote_flat_rate(); self.bind_quote_onsite(); }, // Flat rate quote bind_quote_flat_rate: function() { if (!$('#p_quote_flat_rate').length) return; // Quote behavior $('#p_quote_flat_rate').behavior(ahoy.behaviors.job_quote, { type: 'flat_rate' }); // Validate ahoy.validate.bind($('#form_quote_flat_rate'), 'partial_job_quote_flat_rate', function() { return ahoy.post($('#form_quote_flat_rate')).action('bluebell:on_quote_submit').update('#p_quote_panel', 'job:quote_summary').send(); }); ahoy.validate.set_rules('#form_quote_flat_rate', 'partial_job_personal_message'); // Message $('#p_personal_message_flat').behavior(ahoy.behaviors.job_quote, { type: 'message' }); }, // On site quote bind_quote_onsite: function() { if (!$('#p_quote_onsite').length) return; // Quote behavior $('#p_quote_onsite').behavior(ahoy.behaviors.job_quote, { type: 'onsite' }); // Validate ahoy.validate.bind($('#form_quote_onsite'), 'partial_job_quote_onsite', function() { return ahoy.post($('#form_quote_onsite')).action('bluebell:on_quote_submit').update('#p_quote_panel', 'job:quote_summary').send(); }); ahoy.validate.set_rules('#form_quote_onsite', 'partial_job_personal_message'); // Message $('#p_personal_message_onsite').behavior(ahoy.behaviors.job_quote, { type: 'message' }); }, // Quote summary // click_edit_quote: function() { return ahoy.post('#form_quote_summary').action('bluebell:on_quote_submit').update('#p_quote_panel', 'job:quote_submit').send(); }, click_delete_quote: function() { return ahoy.post('#form_quote_summary').action('bluebell:on_quote_submit').data('delete', true).update('#p_quote_panel', 'job:quote_submit').send(); }, // Question // bind_ask_question: function() { var self = ahoy.page_job; // Ask a question $('#link_ask_question').click(function() { $(this).hide(); $('#ask_question').show(); }); // Validate ahoy.validate.bind($('#form_ask_question'), 'partial_job_ask_question', function() { return ahoy.post($('#form_ask_question')) .action('service:on_question_submit') .update('#p_ask_question', 'job:ask_question') .complete(function() { self.bind_ask_question(); },true) .send(); }); // Show answers $('#job_questions span.answer').hide(); $('#job_questions a.question').live('click', function() { $('#job_questions span.answer').hide(); $(this).next().show(); }) }, // Ignore request bind_request_ignore: function() { ahoy.behavior('#popup_request_ignore', 'popup', { trigger: '#link_request_ignore' }); $('#button_request_ignore').click(function() { var request_id = $(this).data('request-id'); ahoy.post().action('service:on_request_ignore').data('request_id', request_id).data('redirect', root_url('dashboard')).send(); }); } };
JavaScript
/* @require ../frameworks/utility/jquery.gmap3.js; @require ../frameworks/utility/jquery.utility.gmap.js; @require ../frameworks/utility/jquery.utility.gmap_locator.js; */ ahoy.page_profile = { init: function() { var self = ahoy.page_profile; // Init others self.bind_request_popup(); self.bind_portfolio(); self.bind_other_providers(); }, bind_request_popup: function() { // Popup ahoy.behavior('#popup_contact_provider', 'popup', { trigger: '#button_contact_provider', size:'xlarge' }); ahoy.behavior('#popup_contact_provider_success', 'popup', { size:'xlarge' }); ahoy.validate.bind($('#form_request'), 'partial_request_quick_form', function() { ahoy.post($('#form_request')) .action('bluebell:on_directory_create_request') .success(function() { $('#popup_contact_provider_success').behavior('open_popup'); }) .send(); }); }, bind_portfolio: function() { $('#portfolio_slider').orbit({ bullets: true, bulletThumbs: true, afterLoadComplete: function() { $('.orbit-bullets').addClass('hide-for-small').appendTo($('#portfolio_thumbs')); } // .parent().after($('#portfolio_slider')); } }); }, bind_other_providers: function() { $('#other_providers > ul').addClass('jcarousel-skin-ahoy').jcarousel({scroll:1}); $('#other_providers li').click(function() { var provider_id = $(this).data('id'); if (provider_id) $('#map_other_providers').gmap_locator('focus_location', provider_id); }); $('#map_other_providers').gmap_locator({ container: '#other_providers ul', bubble_id_prefix: '#location_', allow_scrollwheel: false, bubble_on_hover: false, zoom_ui: true }) } };
JavaScript
ahoy.page_messages = { init: function() { var self = ahoy.page_messages; self.bind_message_link(); self.bind_search_form(); self.bind_delete_link(); }, bind_message_link: function() { $('#page_messages .message_link').live('click', function() { window.location = $(this).data('url'); }); }, bind_search_form: function() { $('#form_message_search').submit(function() { return ahoy.post($('#form_message_search')) .action('user:on_messages_search') .update('#p_message_panel', 'messages:message_panel') .send(); }); }, bind_delete_link: function() { $('#page_messages').on('click', '.link_delete', function() { var message_id = $(this).data('message-id'); ahoy.post() .action('user:on_message_remove') .data('message_id', message_id) .update('#p_message_panel', 'messages:message_panel') .send(); }); } }; ahoy.page_message = { init: function() { // Submit reply ahoy.validate.bind($('#form_message_reply'), 'partial_messages_reply_form', function() { return ahoy.post($('#form_message_reply')) .action('bluebell:on_message_send') .update('#p_messages_thread', 'messages:thread') .update('#p_messages_reply_form', 'messages:reply_form') .send(); }); } };
JavaScript
ahoy.page_directory = { init: function() { var self = ahoy.page_directory; // Dress up breadcrumb $('ul.breadcrumbs li:last').addClass('current'); self.bind_request_popup(); self.bind_search_form(); self.bind_request_form(); }, select_letter: function(letter) { return ahoy.post() .action('bluebell:on_directory') .data('letter', letter) .update('#p_directory', 'directory:letter') .send(); }, bind_search_form: function() { var search_form = $('#form_directory_search'); if (search_form.length == 0) return; ahoy.validate.bind(search_form, 'partial_directory_search_form', function() { return ahoy.post(search_form).action('bluebell:on_directory_search').update('#p_directory', 'directory:city').send(); }); }, bind_request_popup: function() { if ($('#popup_request').length == 0) return; ahoy.behavior('#popup_request', 'popup', { trigger: '#button_request_popup', size:'xlarge' }); ahoy.behavior('#popup_request_success', 'popup', { size:'xlarge'}); ahoy.validate.bind($('#form_request'), 'partial_request_quick_form', function() { ahoy.post($('#form_request')) .action('bluebell:on_directory_create_request') .success(function() { $('#popup_request_success').behavior('open_popup'); }) .send(); }); }, bind_request_form: function() { var self = ahoy.page_directory; var validate_extra_options; if ($('#request_role_name').length > 0) { self.bind_role_name(); // Prevent validation and autocomplete conflict validate_extra_options = { onfocusout:self.check_request_role_name }; } ahoy.validate.bind($('#form_request_panel'), 'partial_request_quick_form', function() { ahoy.post($('#form_request_panel')) .action('bluebell:on_directory_create_request') .update('#p_directory_request_panel', 'directory:request_panel') .send(); }, validate_extra_options); }, ignore_role_name_validation: true, bind_role_name: function() { // Role auto complete ahoy.behavior('#request_role_name', 'role_select', { on_select: function() { // Prevent validation and autocomplete conflict self.ignore_role_name_validation = true; setTimeout(function() { self.ignore_role_name_validation = false; }, 0); } }); }, // Prevent validation and autocomplete conflict check_request_role_name: function(element) { if (!$(element).is('#request_role_name') || !ahoy.page_directory.ignore_role_name_validation) { if (!this.checkable(element) && (element.name in this.submitted || !this.optional(element))) { this.element(element); } } } };
JavaScript
/** * Login */ ahoy.page_login = { init: function() { ahoy.validate.bind($('#form_login'), 'partial_site_login_form', function() { return ahoy.post($('#form_login')).action('user:on_login').send(); }); $('#user_login').change(function() { $('#user_password').val(''); }) } }; /** * Register */ ahoy.page_register = { init: function() { ahoy.validate.bind($('#form_register'), 'partial_site_register_form', function() { return ahoy.post($('#form_register')).action('user:on_register').send(); }); } }; /** * Forgot password */ ahoy.page_forgot_pass = { init: function() { var self = ahoy.page_forgot_pass; // Initialize self.validate_form(); }, validate_form: function() { // Validation var on_success = function() { return ahoy.post($('#form_reset_pass')) .action('user:on_password_reset') .success(function(){ $('#reset_pass_form, #reset_pass_success').toggle(); $('#login').val($('#forgot_email').val()); }) .send(); }; var options = { messages: ahoy.page_forgot_password.validate_messages, rules: ahoy.page_forgot_password.validate_rules, submitHandler: on_success }; ahoy.validate.init($('#form_reset_pass'), options); } }; /** * Provide */ ahoy.page_provide = { init: function() { ahoy.validate.bind($('#form_register'), 'partial_site_register_form', function() { return ahoy.post($('#form_register')).action('user:on_register').send(); }); } }; /** * Provide Testimonial */ ahoy.page_provide_testimonial = { init: function() { ahoy.validate.bind($('#form_provide_testimonial_write'), 'partial_provide_write_testimonial_form', function() { return ahoy.post($('#form_provide_testimonial_write')).action('service:on_testimonial_submit') .success(function() { $('#p_provide_testimonial_write_form').hide(); $('#provide_testimonial_write_success').show(); }) .send(); }); } };
JavaScript
/* @require ../frameworks/utility/jquery.gmap3.js; @require ../frameworks/utility/jquery.utility.gmap.js; @require ../behaviors/behavior_upload.js; @require ../behaviors/behavior_provide_hours.js; @require ../behaviors/behavior_provide_radius.js; @require ../behaviors/behavior_field_editor.js; */ ahoy.page_provide_create = { logo_id: null, photo_id: null, init: function() { var self = ahoy.page_provide_create; // Profile field editing ahoy.behavior('#p_profile_form', 'field_editor') .act('apply_validation', [$('#form_provide_create'), 'partial_provide_profile_details', function() { // Success ahoy.post('#form_provide_create').action('bluebell:on_provider_submit') .data('provider_logo', self.logo_id) .data('provider_photo', self.photo_id) .data('redirect', root_url('provide/manage/%s')) .send(); } ]); // Provider work hours $('#p_work_hours_form').behavior(ahoy.behaviors.provide_hours); // Provider work radius $('#p_work_radius_form').provide_radius({ on_complete: function(obj) { $('#provider_service_codes').val('|' + obj.get_nearby_postcodes().join('|') + '|'); }, radius_max: $('#work_radius_max').val(), radius_unit: $('#work_radius_unit').val() }); // Role auto complete ahoy.behavior('#provide_role_name', 'role_select', { on_select: function(obj, value){ $('#provide_role_name').prev('label').text(value); } }); // Select country, populate state ahoy.behavior('#provide_country_id', 'select_country', { state_element_id:'#provide_state_id', after_update: function(obj) { obj.state_element = $('#provide_country_id').parent().next().children().first(); } }); // Marry provide_radius and field_editor functionality $('#profile_details_address').bind('field_editor.field_set', function(e, value) { $('#work_radius_address').val(value).trigger('change'); }); // Add image uploads $('#input_provide_photo').behavior(ahoy.behaviors.upload_image, { link_id: '#link_provide_photo', remove_id: '#link_provide_photo_remove', image_id: '#provide_photo', param_name:'provider_photo', on_success: function(obj, data) { $('#link_provide_photo').hide(); self.photo_id = data.result.id; }, on_remove: function() { $('#link_provide_photo').fadeIn(1000); } }); $('#input_provide_logo').behavior(ahoy.behaviors.upload_image, { link_id: '#link_provide_logo', remove_id: '#link_provide_logo_remove', image_id: '#provide_logo', param_name:'provider_logo', on_success: function(obj, data) { $('#link_provide_logo').hide(); self.logo_id = data.result.id; }, on_remove: function() { $('#link_provide_logo').fadeIn(1000); $('#provide_logo').hide(); return false; } }); } };
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Ahoy module */ var Ahoy = (function(ahoy, $){ ahoy.version = 1.1; return ahoy; }(Ahoy || {}, jQuery)) // Adapter for Ahoy v1.0 backward compatability // var ahoy = Ahoy; ahoy.validate = { }; ahoy.behaviors = { }; ahoy.validate.bind = function(form, code, on_success, extra_options) { extra_options = $.extend(true, ahoy.validate.default_options, extra_options); return ahoy.validation(form, code, extra_options).success(on_success).bind(); } ahoy.validate.add_rule = function(object, code) { return ahoy.form.define_field(code, object); } ahoy.validate.set_rules = function(form, code, is_remove) { if (is_remove) ahoy.validation(form).remove_rules(code); else ahoy.validation(form).add_rules(code); } ahoy.validate.init = function(element, set_options, ignore_defaults) { set_options = $.extend(true, ahoy.validate.default_options, set_options); var obj = ahoy.validation(element, null, set_options); if (ignore_defaults) obj._options = set_options; obj.bind(); }; /** * Behaviors * @deprecated in favour of jQuery.widget * * Usage: * ahoy.behavior('#element', 'behavior_name', { config: 'items' }) * .act('misbehave', [params]); * * ahoy.behavior('#element').act('misbehave'); */ ahoy.behavior = function(element, name, config) { element = $(element); if (!config) config = { }; // Assume this is already bound if (!name) return new ahoy.behavior_object(element); // Behavior exists, so use it if (ahoy.behaviors[name]) { element.behavior(ahoy.behaviors[name], config); return new ahoy.behavior_object(element); } // Behavior does not appear to exist, let's try a lazy load var script_path = 'javascript/behaviors/behavior_%s.js'; var script_file = asset_url(script_path.replace('%s', name)); return $.getScript(script_file, function() { element.behavior(ahoy.behaviors[name], config); }); }; ahoy.behavior_object = function(element) { this._element = element; this.act = function(action, params) { this._element.behavior(action, params); return this; }; }; /** * jquery.behavior JavaScript Library v2.0 * http://rodpetrovic.com/jquery/behavior * * Copyright 2010, Rodoljub Petrović * Licensed under the MIT * http://www.opensource.org/licenses/mit-license.php * * Contributors: * - Matjaž Lipuš * * Date: 2011-05-15 * * // 1. Create behavior: * function BadBehavior(element, config) { * this.misbehave = function () { * alert('Oh behave!'); * } * } * * // 2. Attach behavior: * $('.bad-behavior').behavior(BadBehavior); * * // 3. Use behavior: * $('.bad-behavior').behavior('misbehave'); // alert('Oh behave!') * */ (function ($, undef) { "use strict"; function attach($jq, Behavior, config) { $jq.each(function () { if (!this.behavior) { this.behavior = {}; } $.extend(this.behavior, new Behavior(this, config)); }); } function each($jq, property, attributes) { $jq.each(function () { var behavior = this.behavior; if (behavior && behavior[property] !== undef) { if (typeof behavior[property] === "function") { behavior[property].apply(behavior, attributes || []); } else { behavior[property] = attributes; } } }); } $.fn.behavior = function (a, b) { var type = typeof a; if (type === "function") { attach(this, a, b || {}); return this; } if (type === "string") { each(this, a, b); return this; } return this.get(a || 0).behavior; }; }(jQuery));
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Form Validation * * Overrides the core ahoy.validate default options, * adds inline error placement */ ahoy.validate.default_options = { ignore:":not(:visible, :disabled), .ignore_validate", highlight: function(element, errorClass, validClass) { $(element).removeClass('valid').addClass('error'); }, unhighlight: function(element, errorClass, validClass) { $(element).removeClass('error').addClass('valid'); }, success: function(label) { if (!label.closest('form').hasClass('nice')) label.closest('.form-field').removeClass('error'); label.remove(); }, onkeyup: false, errorClass: 'error', errorElement: 'small', errorPlacement: function(error, element) { var self = ahoy.validate; element.after(error); if (element.closest('form').hasClass('nice')) ahoy.validate.place_label(error, element, {left: 5, top: 8}); else element.closest('.form-field').addClass('error'); }, showErrors: function(errorMap, errorList) { var self = ahoy.validate; this.defaultShowErrors(); setTimeout(self.place_labels, 0); }, submitHandler: function(form) { form.submit(); } }; ahoy.validate.place_label = function(label, element, hard_offset) { var offset = label.offset(); hard_offset = (hard_offset) ? hard_offset : { top:0, left:0 }; offset.top = element.offset().top; offset.left = element.offset().left + (element.outerWidth()+hard_offset.left); label.offset(offset); }; ahoy.validate.place_labels = function() { jQuery('form.nice small.error').each(function() { var label = $(this); if (label.css('position')=="relative") return; var element = $(this).prev(); ahoy.validate.place_label(label, element, {left: 5, top: 8}); }); }; jQuery(window).resize(function(){ ahoy.validate.place_labels(); }); // Poll for dom changes var ahoyform_attributes = { body_height: 0, poll_interval: 1000 }; var ahoyform_poll = setInterval(ahoyform_is_dom_resized, ahoyform_attributes.poll_interval); function ahoyform_is_dom_resized() { $body = jQuery('body'); if(ahoyform_attributes.body_height != $body.height()) { ahoyform_attributes.body_height = $body.height(); jQuery(window).trigger('resize'); } } /** * IE Compatibility */ jQuery(document).ready(function($){ // Alternate placeholder script for IE8 and prior (sad) if ($("html").is(".lt-ie9")) { $("[placeholder]").focus(function() { var input = $(this); if (input.val() == input.attr("placeholder")) { input.val(""); input.removeClass("placeholder"); } }).blur(function() { var input = $(this); if (input.val() == "" || input.val() == input.attr("placeholder")) { input.addClass("placeholder"); input.val(input.attr("placeholder")); } }).blur(); $("[placeholder]").parents("form").submit(function() { $(this).find("[placeholder]").each(function() { var input = $(this); if (input.val() == input.attr("placeholder")) { input.val(""); } }) }); } });
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Provider work hours behavior */ ahoy.behaviors.provide_hours = function(element, config) { var self = this; self.element = element = $(element); var defaults = { specific_container:'#work_hours_specific', general_container:'#work_hours_general', general_select_class: 'general_select', toggle_link:'#link_work_hours', apply_all_link:'#link_apply_all', row_selector:'div.row', use_general: true }; self.config = config = $.extend(true, defaults, config); self.toggle_link = $(self.config.toggle_link); self.apply_all_link = $(self.config.apply_all_link); self.specific = $(self.config.specific_container); self.general = $(self.config.general_container); self.general_select = self.general.find('select.'+self.config.general_select_class); self.general_select_start = self.general.find('select.'+self.config.general_select_class+'_start'); self.general_select_end = self.general.find('select.'+self.config.general_select_class+'_end'); this.init = function() { if (self.config.use_general) { // Toggle link self.toggle_link.click(self.specific_toggle); // Bind general hours self.general_select.change(function() { self.select_general_days($(this).val()); }); self.select_general_days(self.general_select.val()); // Automatically apply all for general time dropdowns self.general_select_start.change(function() { $('#weekday_1').find('select:first').val($(this).val()); self.click_apply_all(); }); self.general_select_end.change(function() { $('#weekday_1').find('select:last').val($(this).val()); self.click_apply_all(); }); } else { self.specific.show(); self.general.hide(); self.validate_times(); } // Apply all self.apply_all_link.click(self.click_apply_all); // Bind specific hours self.check_all_days(); self.specific.find(self.config.row_selector + ' input[type=checkbox]').change(function() { self.check_day($(this).closest(self.config.row_selector)); }); }; this.check_all_days = function() { self.specific.find(self.config.row_selector).each(function() { self.check_day($(this)); }); }; this.check_day = function(row_element) { row_element = $(row_element); var checkbox = row_element.find('input[type=checkbox]'); if (checkbox.is(':checked')) row_element.find('div.hide').hide().end().find('div.show').show(); else { row_element.find('div.hide').show().end().find('div.show').hide().end().find('select').val(0); } }; this.select_general_days = function(value) { switch (value) { case '0': // Mon - Sun $('#weekday_1, #weekday_2, #weekday_3, #weekday_4, #weekday_5, #weekday_6, #weekday_7').find('input[type=checkbox]').attr('checked', true); break; case '1': // Mon - Fri $('#weekday_1, #weekday_2, #weekday_3, #weekday_4, #weekday_5').find('input[type=checkbox]').attr('checked', true); $('#weekday_6, #weekday_7').find('input[type=checkbox]').attr('checked', false); break; case '2': // Mon - Sat $('#weekday_1, #weekday_2, #weekday_3, #weekday_4, #weekday_5, #weekday_6').find('input[type=checkbox]').attr('checked', true); $('#weekday_7').find('input[type=checkbox]').attr('checked', false); break; case '3': // Sat - Sun $('#weekday_6, #weekday_7').find('input[type=checkbox]').attr('checked', true); $('#weekday_1, #weekday_2, #weekday_3, #weekday_4, #weekday_5').find('input[type=checkbox]').attr('checked', false); break; case '4': self.general_select.val(0); self.specific_toggle(); break; } self.check_all_days(); }; this.specific_toggle = function() { self.general.toggle(); self.specific.toggle(); self.toggle_link.toggleText(); }; this.click_apply_all = function() { var start_val = $('#weekday_1').find('select:first').val(); var last_val = $('#weekday_1').find('select:last').val(); self.specific.find(self.config.row_selector).each(function() { $(this).find('select:first:visible').val(start_val); $(this).find('select:last:visible').val(last_val); }); }; this.validate_times = function() { self.specific.find(self.config.row_selector).each(function() { var start = Math.round($(this).find('select:first').val().replace(/:/g, '')); var end = Math.round($(this).find('select:last').val().replace(/:/g, '')); if (start >= end) $(this).find('input[type=checkbox]').attr('checked', false); else $(this).find('input[type=checkbox]').attr('checked', true); }); }; this.init(); };
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Autogrow Textarea behavior * * Usage: ahoy.behavior('#textarea', 'autogrow'); * */ ahoy.behaviors.autogrow = function(element, config) { var self = this; element = $(element); var defaults = { offset: 30 // Height offset }; self.config = config = $.extend(true, defaults, config); this.min_height = element.height(); this.line_height = element.css('line-height'); this.shadow = $('<div></div>'); this.shadow.css({ position: 'absolute', top: -10000, left: -10000, width: element.width(), fontSize: element.css('font-size'), fontFamily: element.css('font-family'), lineHeight: element.css('line-height'), resize: 'none' }).appendTo(document.body); this.update = function () { var val = element.val().replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/&/g, '&amp;').replace(/\n/g, '<br/>'); self.shadow.html(val); $(this).css('height', Math.max(self.shadow.height() + self.config.offset, self.min_height)); }; element.change(self.update).keyup(self.update).keydown(self.update); this.update(); };
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Profile field editing behavior * * Hot swappable label / fields. * * HTML Example: * * <div class="form-field name"> * <!-- The label must come before the div.edit container --> * <?=form_label('Your name', 'name')?> * <div class="edit"><?=form_input('name', '', 'placeholder="Your name please" id="name"')?></div> * </div> * * Usage: * * ahoy.behavior('#form_or_container', 'field_editor'); * */ ahoy.behaviors.field_editor = function(element, config) { var self = this; self.element = element = $(element); var defaults = { edit_selector:'div.edit', // Edit input container field_selector:'div.form-field', // Form field container on_set_field: null, // Callback when field is set, for single field use event: field_editor.field_set implode_char: ', ' // The character to separate multiple inputs }; self.config = config = $.extend(true, defaults, config); this.form = $(config.form_id); this.active_field = null; this.is_loaded = false; this.init = function() { self.reset_profile_fields(); // Bind click label field // returns false to stop clickOutside plugin element.find('label').click(function() { self.click_profile_field(this); return false; }); self.populate_data(); self.is_loaded = true; }; this.populate_data = function() { element.find(config.edit_selector).each(function() { self.set_profile_field($(this)); }); }; this.click_profile_field = function(obj) { // If a field is currently being edited, // set it or prevent other field edits if (self.active_field) { if (self.set_profile_field(self.active_field)===false) return; } // Find the edit container, show, focus and cache var edit = $(obj).hide().parent().find(self.config.edit_selector).show(); edit.find('input:first').focus(); self.active_field = edit; // Use clickOutside plugin for autosave setTimeout(function() { edit.clickOutside(function() { self.set_profile_field(edit); }) }, 1); // Detect keypress events edit.find('input').bind('keypress', function(e){ var code = (e.keyCode ? e.keyCode : e.which); if (code == 13) // ENTER { self.set_profile_field($(this).closest(self.config.edit_selector)); return false; } else if (code == 9) // TAB { var next_field; var field = $(this).closest(self.config.field_selector); // Revert to standard tabbing for fields with multiple inputs if (field.find('input').length > 1) return; self.set_profile_field($(this).closest(self.config.edit_selector)); if (e.shiftKey) next_field = self.dom_shift(field, self.config.field_selector, -1); // Move back else next_field = self.dom_shift(field, self.config.field_selector, 1); // Move forward next_field.find('label').trigger('click'); return false; } }); }; // Find the next / previous field regardless of its DOM position this.dom_shift = function(obj, selector, shift) { var all_fields = element.find(selector); var field_index = all_fields.index(obj); var next_field = all_fields.eq(field_index + shift); return next_field; }; // Hides all fields and shows their labels this.reset_profile_fields = function() { self.element.find('label').each(function() { $(this).show().parent().find(self.config.edit_selector).hide(); }); }; // Determine a friendly value to display, // if we have multiple fields string them together nicely this.get_field_value = function(inputs) { var value = ""; if (inputs.length > 1) { jQuery.each(inputs, function(k,v) { if ($.trim($(this).val()) != "") { if ($(this).is('select')) { value += (k==0) ? $(this).find('option:selected').text() : self.config.implode_char + $(this).find('option:selected').text(); } else { value += (k==0) ? $(this).val() : self.config.implode_char + $(this).val(); } } }); } else value = $.trim(inputs.first().val()); return value; }; // Set a profile field, must return true // If fields do not validate, return false this.set_profile_field = function(obj) { self.reset_profile_fields(); var inputs = obj.find('input, select'); var field = inputs.first(); var label = field.closest('.edit').prev('label'); var value = self.get_field_value(inputs); // Has the field been populated or emptied? // Display value or placeholder for latter if (value != "") label.text(value).addClass('populated'); else label.text(field.attr('placeholder')).removeClass('populated'); // Reset cache variable self.active_field = null; // Cancel clickOutside plugin $('body').unbind('click'); // Events if (self.is_loaded) { obj.trigger('field_editor.field_set', [value]); self.config.on_set_field && self.config.on_set_field(self, obj, value); } // Validates true return true; }; // Apply validation to our fields using an ahoy.validate code // (Implement Wins: Flawless victory) this.apply_validation = function(form, code, on_success) { ahoy.validate.bind(form, code, on_success, { onfocusout: false, // Removed because it looks messy ignore: null, // Do not ignore hidden fields // Binding to the invalid handler here instead // of errorPlacement so we don't conflict invalidHandler: function(form, validator) { var errors = validator.numberOfInvalids(); if (errors) { // Only show the first error var el = validator.errorList[0].element; // Target the label that should perfectly preceed the .edit container var label = $(el).closest('div.edit').prev().trigger('click'); // Trash the other error labels because they are annoying setTimeout(function() { $('small.error').filter(':hidden').remove(); }, 500); } } }); }; this.init(); };
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Provider work hours behavior */ ;(function ($, window, document, undefined) { $.widget("utility.provide_radius", { version: '1.0', options: { radius_max: 100, radius_unit: 'km', map_id: '#work_radius_map', // Map object (see map behavior) address_field_id: '#work_radius_address', // Address field used for geocoding area_list_id: '#work_radius_area_list', // Unordered list to populate with nearby areas on_complete: null // Callback after lookup is complete }, // Internals _nearby_postcodes: [], _country: null, _postcode: null, _radius: 25, _map: null, _address_field: null, _address: null, _latlng: null, _area_list: null, _init: function() { var self = this; this._map = $(this.options.map_id); this._address_field = $(this.options.address_field_id); this._area_list = $(this.options.area_list_id); // Map self._map.gmap({ distance_type: this.options.radius_unit, allow_drag: false, allow_scrollwheel: false, alow_dbl_click_zoom: false }); // Slider self.bind_slider(); // Detect address changes self._address_field.change(function() { self.populate_address($(this).val()); }); }, bind_slider: function() { var self = this; $('#work_radius_slider').slider({ step:5, min:1, max:parseInt(self.options.radius_max)+1, value:20, change:function(event,ui) { if (self._address) { self._radius = (ui.value <= 1) ? 1 : ui.value-1; self._map .gmap('clear_circles') .gmap('show_circle_at_address_object', self._address, self._radius) .gmap('autofit'); $('#work_radius_radius span').text(self._radius); self.find_nearby_areas(self._postcode, self._country, self._radius); } }, slide:function(event,ui) { var radius = (ui.value <= 1) ? 1 : ui.value-1; $('#work_radius_radius span').text(radius); } }); }, populate_address: function(address_string) { var self = this; if ($.trim(address_string)=="") { self.disable_control(); return } self.enable_control(); $.waterfall( function() { var deferred = $.Deferred(); self._map.gmap('get_object_from_address_string', address_string, function(address){ self._address = address; self._latlng = self._map.gmap('get_latlng_from_address_object', self._address); deferred.resolve(); }); return deferred; }, function() { self._map .gmap('align_to_address_object', self._address) .gmap('add_marker_from_address_object', self._address, 'provider_tag') .gmap('show_circle_at_address_object', self._address, self._radius) .gmap('autofit'); self._country = self._map.gmap('get_value_from_address_object', self._address, 'country'); self._postcode = self._map.gmap('get_value_from_address_object', self._address, 'postal_code'); return $.Deferred().resolve(); }, function() { self.find_nearby_areas(self._postcode, self._country, self._radius); return $.Deferred().resolve(); } ); }, find_nearby_areas: function(postcode, country, radius) { var self = this; self._nearby_postcodes = []; // Reset main postal code array var cache = {}; // Cache for duplicates ahoy.post().action('location:on_get_nearby_areas').data({country:country, postcode:postcode, radius:radius, unit:self.options.radius_unit}).success(function(raw, data) { var result = $.parseJSON(data); if (result && result.postalCodes) { self._area_list.empty(); $.each(result.postalCodes, function(key, area){ // Add unique post code to array var duplicate_exists = false; for (var i=0; i < self._nearby_postcodes.length; i++) { if (self._nearby_postcodes[i]==area.postalcode) duplicate_exists = true; } if (!duplicate_exists) self._nearby_postcodes.push(area.postalcode); // Remove duplicates, add to area list if (!cache[area.adminCode1+area.name]) { cache[area.adminCode1+area.name] = true; var item = $('<li />').text(area.name+', '+area.adminCode1).appendTo(self._area_list); } }); } else self._area_list.empty().append($('<li />').text(self._area_list.attr('data-empty-text'))); // End point self.options.on_complete && self.options.on_complete(self); }).send(); }, get_nearby_postcodes: function() { return this._nearby_postcodes; }, disable_control: function() { $('#work_radius_disabled').fadeIn(); $('#work_radius').addClass('disabled'); }, enable_control: function() { $('#work_radius_disabled').fadeOut(); $('#work_radius').removeClass('disabled'); } }) })( jQuery, window, document );
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Request submit behavior */ ahoy.behaviors.request_submit = function(element, config) { var self = this; self.element = element = $(element); // Should be the form tag var defaults = { on_submit: null }; self.config = config = $.extend(true, defaults, config); this.init = function() { self.validate_form(); self.bind_required_by(); // Alternative time $('#link_request_alt_time').click(self.click_alt_time); // Remote location $('#location_remote').change(function() { self.click_location_remote(this); }); self.click_location_remote('#location_remote'); // Add photos $('#input_add_photos').behavior(ahoy.behaviors.upload_image_multi, {link_id:'#link_add_photos', param_name:'request_images[]'}); }; // Required by logic this.bind_required_by = function() { var required_by = element.find('section.required_by'); var checked = required_by.find('ul.radio_group label input:checked'); self.click_required_by(checked); required_by.find('label input').change(function() { self.click_required_by(this); }); }; this.click_required_by = function(element) { var label = $(element).parent(); var required_by = self.element.find('section.required_by'); required_by.find('label').removeClass('selected'); required_by.find('.radio_expand').hide(); label.addClass('selected').next('.radio_expand').show(); }; this.click_alt_time = function() { var container = self.element.find('.firm_date_secondary').toggle(); container.find('select').each(function() { $(this).trigger('change'); }); }; this.click_location_remote = function(obj) { var checked = $(obj).is(':checked'); var location = $('#request_location'); location.attr('disabled', checked); if (checked) { location.val('').removeClass('error valid').next('.float_error').remove(); } }; this.validate_form = function(extra_rules, extra_messages) { var options = { messages: ahoy.partial_request_simple_form.validate_messages, rules: ahoy.partial_request_simple_form.validate_rules, submitHandler: self.submit_form }; if (extra_rules) options.rules = $.extend(true, options.rules, extra_rules); if (extra_messages) options.messages = $.extend(true, options.messages, extra_messages); ahoy.validate.init(self.element, options); }; this.submit_form = function(form) { if (!config.on_submit) return false; self.check_category(function(result){ $('#request_category_id').val(result.id); $('#request_title').val(result.name); return config.on_submit(form, true); }, function() { return config.on_submit(form, false); }); }; this.check_category = function(success, fail) { ahoy.post($('#request_title')) .action('service:on_search_categories').data('name', $('#request_title').val()) .success(function(raw_data, data){ var result = $.parseJSON(data); var found_category = false; $.each(result, function(k,v){ if (v.parent_id) { // Only allow child categories found_category = true; } }); if (found_category) success(result[0]); else fail(); }) .send(); }; this.init(); };
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Upload single image behavior */ ahoy.behaviors.upload_image = function(element, config) { var self = this; element = $(element); var defaults = { link_id: null, remove_id: null, image_id:'#upload_image', param_name: 'image', on_remove: null, on_success: null, allow_reupload:true }; this.config = config = $.extend(true, defaults, config); this.image = $(config.image_id); this.remove = $(config.remove_id); this.init = function() { if (config.link_id) $(config.link_id).click(function() { $(element).trigger('click'); }); self.bind_file_upload(); self.bind_remove_image(); }; this.bind_file_upload = function() { element.fileupload({ dataType: 'json', //url: '', paramName: config.param_name, type: 'POST', done: function (e, data) { var old_src = self.image.attr('src'); self.image.attr('src', data.result.thumb).attr('data-blank-src', old_src).attr('data-image-id', data.result.id).fadeTo(1000, 1); config.on_success && config.on_success(self, data); if (self.config.allow_reupload) self.bind_file_upload(); self.remove.show(); }, add: function(e, data) { self.image.fadeTo(500, 0); data.submit(); }, fail: function(e, data) { alert('Oops! Looks like there was an error uploading your photo, try a different one or send us an email! (' + data.errorThrown + ')') self.image.fadeTo(1000, 1); } }); }; this.bind_remove_image = function() { self.remove.die('click').live('click', function(){ self.remove.hide(); var file_id = self.image.attr('data-image-id'); if (!self.config.on_remove || (self.config.on_remove && (self.config.on_remove(self, file_id))!==false)) { self.image.fadeTo(500, 0, function() { var blank_src = self.image.attr('data-blank-src'); self.image.attr('src', blank_src); self.image.fadeTo(1000, 1); }); } }); }; this.init(); }; /** * Upload multiple images behavior */ ahoy.behaviors.upload_image_multi = function(element, config) { var self = this; element = $(element); var defaults = { link_id: null, panel_id:'#panel_photos', param_name: 'images[]', on_remove: null, on_success: null, allow_reupload:true }; this.config = config = $.extend(true, defaults, config); var panel = $(config.panel_id); this.init = function() { // Bind additional link if (config.link_id) $(config.link_id).unbind('click').click(function() { $(element).trigger('click'); return false; }) self.bind_remove_image(); self.bind_file_upload(); }; this.bind_file_upload = function() { element.fileupload({ dataType: 'json', //url: '', paramName: config.param_name, type: 'POST', done: function (e, data) { panel.find('div.loading:first').removeClass('loading').css('background-image', 'url('+data.result.thumb+')').attr('data-image-id', data.result.id); config.on_success && config.on_success(self, data); if (self.config.allow_reupload) self.bind_file_upload(); }, add: function(e, data) { panel.show().children('ul:first').append('<li><div class="image loading"><a href="javascript:;" class="remove">Remove</a></div></li>'); data.submit(); } }); }; this.bind_remove_image = function() { panel.find('a.remove').die('click').live('click', function(){ var photo = $(this).parent(); $(this).closest('li').fadeOut(function() { $(this).remove() if (panel.find('li').length == 0) panel.hide(); var file_id = photo.attr('data-image-id'); config.on_remove && config.on_remove(self, file_id); }); }); }; this.init(); };
JavaScript
/** * Scripts Ahoy! Software * * Copyright (c) 2012 Scripts Ahoy! (scriptsahoy.com) * All terms, conditions and copyrights as defined * in the Scripts Ahoy! License Agreement * http://www.scriptsahoy.com/license * */ /** * Map Marker behavior (extension of Google Map behavior) * * Usage: * * <script> * $('#map') * .behavior(ahoy.behaviors.map, {allow_drag: true, allow_scroll:false}); * .behavior('use_behavior', [ahoy.behaviors.map_marker, { distance_type: 'km' }]); * .behavior('get_address', ['Pitt St Sydney 2000', { * callback: function(address){ * element.behavior('draw_marker', [address, { marker_id:'address_1', destroy:false } ]); * } * }]); * </script> * */ ahoy.behaviors.map_marker = function(element, config) { var self = this; self.element = element = $(element); var defaults = { distance_type:'km', // Calculate distance in Kilometers (km) or Miles (mi) circle_colour:'#ff0000', // Circle color marker_image: null, // Custom image for marker map_obj: null }; self.config = config = $.extend(true, defaults, config); this.map = config.map_obj; this.marker_manager; this.last_drawn_marker = null; this.marker_counter = 0; this.all_markers = {}; this.init = function() { self.marker_manager = new MarkerManager(self.map); }; this.get_marker = function(marker_id, callback) { if (self.all_markers[marker_id] && callback) callback(self.all_markers[marker_id]); }; this.object_length = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }; this.align_to_markers = function() { if (self.object_length(self.all_markers) <= 0) return; var bounds = new google.maps.LatLngBounds(); jQuery.each(self.all_markers, function(index, marker){ bounds.extend(marker.getPosition()); }); self.map.fitBounds(bounds); var center = bounds.getCenter(); self.map.setCenter(center); }; this.align_to_marker = function(marker_id) { var marker = self.all_markers[marker_id]; self.infobox_content[marker_id] = content; infowindow.open(self.map, marker); }; this.draw_marker = function(address, options) { options = $.extend(true, { destroy: false, // Destroy previous markers min_zoom: 5, // The minimum zoom for displaying marker (hide if far away eg: below 10) max_zoom: null // The maximum zoom for displaying marker (hide if too close eg: above 10) }, options); self.marker_counter++; var center = self.get_center_from_address(address); if (options.destroy && self.last_drawn_marker) self.destroy_markers(); var marker = new google.maps.Marker({ position: center, icon: config.marker_image }); self.last_drawn_marker = marker; if (options.marker_id) self.all_markers[options.marker_id] = marker; else self.all_markers[self.marker_counter] = marker; if (options.infobox_content) self.bind_infobox_content_to_marker(options.infobox_content, options.marker_id); self.marker_manager.addMarker(marker, options.min_zoom, options.max_zoom); if (options.callback) options.callback(self, marker); else return marker; }; this.destroy_markers = function() { self.marker_manager.clearMarkers(); self.all_markers = []; self.infobox_content = []; }; // Events can be: click, mouseover this.bind_event_to_marker = function(event_name, callback, marker_id) { var marker; if (marker_id) marker = self.all_markers[marker_id]; else marker = self.last_drawn_marker; google.maps.event.addListener(marker, event_name, callback); }; // Circles // this.draw_circle = function(address, radius, callback, options) { options = $.extend(true, {destroy:true}, options); var center = self.get_center_from_address(address); var bounds = new google.maps.LatLngBounds(); var circle_coords = Array(); with (Math) { // Set up radians var d; if (self.config.distance_type=="km") d = radius/ 6378.8; else d = radius / 3963.189; var latitude = (PI / 180) * center.lat(); var longitude = (PI / 180) * center.lng(); for (var a = 0; a < 361; a++) { var tc = (PI/180) * a; var y = asin(sin(latitude) * cos(d) + cos(latitude) * sin(d) * cos(tc)); var dlng = atan2(sin(tc) * sin(d) * cos(latitude), cos(d) - sin(latitude) * sin(y)); var x = ((longitude-dlng + PI) % (2 * PI)) - PI; // MOD function var point = new google.maps.LatLng(parseFloat(y * (180 / PI)), parseFloat(x * (180 / PI))); circle_coords.push(point); bounds.extend(point); } if (options.destroy && self.drawn_circle) self.remove_draw_object(self.drawn_circle); var circle = new google.maps.Polygon({ paths: circle_coords, strokeColor: self.config.circle_colour, strokeWeight: 2, strokeOpacity: 1, fillColor: self.config.circle_colour, fillOpacity: 0.4 }); circle.setMap(self.map); self.map.fitBounds(bounds); self.drawn_circle = circle; if (callback) callback(circle); else return circle; } }; // Helpers // this.get_center_from_address = function(address, options) { if (!address) return; options = $.extend(true, {set:0}, options); var set = options.set; if (!set) set = 0; var result = address[set].geometry.location; if (options.callback) options.callback(result); else return result; }; // Object can be: marker, circle this.remove_draw_object = function(object) { object.setMap(null); }; this.init(); }; /** * @name MarkerManager v3 * @version 1.1 * @copyright (c) 2007 Google Inc. * @author Doug Ricket, Bjorn Brala (port to v3), others, * @url http://google-maps-utility-library-v3.googlecode.com/svn/trunk * * @fileoverview Marker manager is an interface between the map and the user, * designed to manage adding and removing many points when the viewport changes. * <br /><br /> * <b>How it Works</b>:<br/> * The MarkerManager places its markers onto a grid, similar to the map tiles. * When the user moves the viewport, it computes which grid cells have * entered or left the viewport, and shows or hides all the markers in those * cells. * (If the users scrolls the viewport beyond the markers that are loaded, * no markers will be visible until the <code>EVENT_moveend</code> * triggers an update.) * In practical consequences, this allows 10,000 markers to be distributed over * a large area, and as long as only 100-200 are visible in any given viewport, * the user will see good performance corresponding to the 100 visible markers, * rather than poor performance corresponding to the total 10,000 markers. * Note that some code is optimized for speed over space, * with the goal of accommodating thousands of markers. */ /* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @name MarkerManagerOptions * @class This class represents optional arguments to the {@link MarkerManager} * constructor. * @property {Number} maxZoom Sets the maximum zoom level monitored by a * marker manager. If not given, the manager assumes the maximum map zoom * level. This value is also used when markers are added to the manager * without the optional {@link maxZoom} parameter. * @property {Number} borderPadding Specifies, in pixels, the extra padding * outside the map's current viewport monitored by a manager. Markers that * fall within this padding are added to the map, even if they are not fully * visible. * @property {Boolean} trackMarkers=false Indicates whether or not a marker * manager should track markers' movements. If you wish to move managed * markers using the {@link setPoint}/{@link setLatLng} methods, * this option should be set to {@link true}. */ /** * Creates a new MarkerManager that will show/hide markers on a map. * * Events: * @event changed (Parameters: shown bounds, shown markers) Notify listeners when the state of what is displayed changes. * @event loaded MarkerManager has succesfully been initialized. * * @constructor * @param {Map} map The map to manage. * @param {Object} opt_opts A container for optional arguments: * {Number} maxZoom The maximum zoom level for which to create tiles. * {Number} borderPadding The width in pixels beyond the map border, * where markers should be display. * {Boolean} trackMarkers Whether or not this manager should track marker * movements. */ function MarkerManager(map, opt_opts) { var me = this; me.map_ = map; me.mapZoom_ = map.getZoom(); me.projectionHelper_ = new ProjectionHelperOverlay(map); google.maps.event.addListener(me.projectionHelper_, 'ready', function () { me.projection_ = this.getProjection(); me.initialize(map, opt_opts); }); } MarkerManager.prototype.initialize = function (map, opt_opts) { var me = this; opt_opts = opt_opts || {}; me.tileSize_ = MarkerManager.DEFAULT_TILE_SIZE_; var mapTypes = map.mapTypes; // Find max zoom level var mapMaxZoom = 1; for (var sType in mapTypes ) { if (typeof map.mapTypes.get(sType) === 'object' && typeof map.mapTypes.get(sType).maxZoom === 'number') { var mapTypeMaxZoom = map.mapTypes.get(sType).maxZoom; if (mapTypeMaxZoom > mapMaxZoom) { mapMaxZoom = mapTypeMaxZoom; } } } me.maxZoom_ = opt_opts.maxZoom || 19; me.trackMarkers_ = opt_opts.trackMarkers; me.show_ = opt_opts.show || true; var padding; if (typeof opt_opts.borderPadding === 'number') { padding = opt_opts.borderPadding; } else { padding = MarkerManager.DEFAULT_BORDER_PADDING_; } // The padding in pixels beyond the viewport, where we will pre-load markers. me.swPadding_ = new google.maps.Size(-padding, padding); me.nePadding_ = new google.maps.Size(padding, -padding); me.borderPadding_ = padding; me.gridWidth_ = {}; me.grid_ = {}; me.grid_[me.maxZoom_] = {}; me.numMarkers_ = {}; me.numMarkers_[me.maxZoom_] = 0; google.maps.event.addListener(map, 'dragend', function () { me.onMapMoveEnd_(); }); google.maps.event.addListener(map, 'idle', function () { me.onMapMoveEnd_(); }); google.maps.event.addListener(map, 'zoom_changed', function () { me.onMapMoveEnd_(); }); /** * This closure provide easy access to the map. * They are used as callbacks, not as methods. * @param GMarker marker Marker to be removed from the map * @private */ me.removeOverlay_ = function (marker) { marker.setMap(null); me.shownMarkers_--; }; /** * This closure provide easy access to the map. * They are used as callbacks, not as methods. * @param GMarker marker Marker to be added to the map * @private */ me.addOverlay_ = function (marker) { if (me.show_) { marker.setMap(me.map_); me.shownMarkers_++; } }; me.resetManager_(); me.shownMarkers_ = 0; me.shownBounds_ = me.getMapGridBounds_(); google.maps.event.trigger(me, 'loaded'); }; /** * Default tile size used for deviding the map into a grid. */ MarkerManager.DEFAULT_TILE_SIZE_ = 1024; /* * How much extra space to show around the map border so * dragging doesn't result in an empty place. */ MarkerManager.DEFAULT_BORDER_PADDING_ = 100; /** * Default tilesize of single tile world. */ MarkerManager.MERCATOR_ZOOM_LEVEL_ZERO_RANGE = 256; /** * Initializes MarkerManager arrays for all zoom levels * Called by constructor and by clearAllMarkers */ MarkerManager.prototype.resetManager_ = function () { var mapWidth = MarkerManager.MERCATOR_ZOOM_LEVEL_ZERO_RANGE; for (var zoom = 0; zoom <= this.maxZoom_; ++zoom) { this.grid_[zoom] = {}; this.numMarkers_[zoom] = 0; this.gridWidth_[zoom] = Math.ceil(mapWidth / this.tileSize_); mapWidth <<= 1; } }; /** * Removes all markers in the manager, and * removes any visible markers from the map. */ MarkerManager.prototype.clearMarkers = function () { this.processAll_(this.shownBounds_, this.removeOverlay_); this.resetManager_(); }; /** * Gets the tile coordinate for a given latlng point. * * @param {LatLng} latlng The geographical point. * @param {Number} zoom The zoom level. * @param {google.maps.Size} padding The padding used to shift the pixel coordinate. * Used for expanding a bounds to include an extra padding * of pixels surrounding the bounds. * @return {GPoint} The point in tile coordinates. * */ MarkerManager.prototype.getTilePoint_ = function (latlng, zoom, padding) { var pixelPoint = this.projectionHelper_.LatLngToPixel(latlng, zoom); var point = new google.maps.Point( Math.floor((pixelPoint.x + padding.width) / this.tileSize_), Math.floor((pixelPoint.y + padding.height) / this.tileSize_) ); return point; }; /** * Finds the appropriate place to add the marker to the grid. * Optimized for speed; does not actually add the marker to the map. * Designed for batch-processing thousands of markers. * * @param {Marker} marker The marker to add. * @param {Number} minZoom The minimum zoom for displaying the marker. * @param {Number} maxZoom The maximum zoom for displaying the marker. */ MarkerManager.prototype.addMarkerBatch_ = function (marker, minZoom, maxZoom) { var me = this; var mPoint = marker.getPosition(); marker.MarkerManager_minZoom = minZoom; // Tracking markers is expensive, so we do this only if the // user explicitly requested it when creating marker manager. if (this.trackMarkers_) { google.maps.event.addListener(marker, 'changed', function (a, b, c) { me.onMarkerMoved_(a, b, c); }); } var gridPoint = this.getTilePoint_(mPoint, maxZoom, new google.maps.Size(0, 0, 0, 0)); for (var zoom = maxZoom; zoom >= minZoom; zoom--) { var cell = this.getGridCellCreate_(gridPoint.x, gridPoint.y, zoom); cell.push(marker); gridPoint.x = gridPoint.x >> 1; gridPoint.y = gridPoint.y >> 1; } }; /** * Returns whether or not the given point is visible in the shown bounds. This * is a helper method that takes care of the corner case, when shownBounds have * negative minX value. * * @param {Point} point a point on a grid. * @return {Boolean} Whether or not the given point is visible in the currently * shown bounds. */ MarkerManager.prototype.isGridPointVisible_ = function (point) { var vertical = this.shownBounds_.minY <= point.y && point.y <= this.shownBounds_.maxY; var minX = this.shownBounds_.minX; var horizontal = minX <= point.x && point.x <= this.shownBounds_.maxX; if (!horizontal && minX < 0) { // Shifts the negative part of the rectangle. As point.x is always less // than grid width, only test shifted minX .. 0 part of the shown bounds. var width = this.gridWidth_[this.shownBounds_.z]; horizontal = minX + width <= point.x && point.x <= width - 1; } return vertical && horizontal; }; /** * Reacts to a notification from a marker that it has moved to a new location. * It scans the grid all all zoom levels and moves the marker from the old grid * location to a new grid location. * * @param {Marker} marker The marker that moved. * @param {LatLng} oldPoint The old position of the marker. * @param {LatLng} newPoint The new position of the marker. */ MarkerManager.prototype.onMarkerMoved_ = function (marker, oldPoint, newPoint) { // NOTE: We do not know the minimum or maximum zoom the marker was // added at, so we start at the absolute maximum. Whenever we successfully // remove a marker at a given zoom, we add it at the new grid coordinates. var zoom = this.maxZoom_; var changed = false; var oldGrid = this.getTilePoint_(oldPoint, zoom, new google.maps.Size(0, 0, 0, 0)); var newGrid = this.getTilePoint_(newPoint, zoom, new google.maps.Size(0, 0, 0, 0)); while (zoom >= 0 && (oldGrid.x !== newGrid.x || oldGrid.y !== newGrid.y)) { var cell = this.getGridCellNoCreate_(oldGrid.x, oldGrid.y, zoom); if (cell) { if (this.removeFromArray_(cell, marker)) { this.getGridCellCreate_(newGrid.x, newGrid.y, zoom).push(marker); } } // For the current zoom we also need to update the map. Markers that no // longer are visible are removed from the map. Markers that moved into // the shown bounds are added to the map. This also lets us keep the count // of visible markers up to date. if (zoom === this.mapZoom_) { if (this.isGridPointVisible_(oldGrid)) { if (!this.isGridPointVisible_(newGrid)) { this.removeOverlay_(marker); changed = true; } } else { if (this.isGridPointVisible_(newGrid)) { this.addOverlay_(marker); changed = true; } } } oldGrid.x = oldGrid.x >> 1; oldGrid.y = oldGrid.y >> 1; newGrid.x = newGrid.x >> 1; newGrid.y = newGrid.y >> 1; --zoom; } if (changed) { this.notifyListeners_(); } }; /** * Removes marker from the manager and from the map * (if it's currently visible). * @param {GMarker} marker The marker to delete. */ MarkerManager.prototype.removeMarker = function (marker) { var zoom = this.maxZoom_; var changed = false; var point = marker.getPosition(); var grid = this.getTilePoint_(point, zoom, new google.maps.Size(0, 0, 0, 0)); while (zoom >= 0) { var cell = this.getGridCellNoCreate_(grid.x, grid.y, zoom); if (cell) { this.removeFromArray_(cell, marker); } // For the current zoom we also need to update the map. Markers that no // longer are visible are removed from the map. This also lets us keep the count // of visible markers up to date. if (zoom === this.mapZoom_) { if (this.isGridPointVisible_(grid)) { this.removeOverlay_(marker); changed = true; } } grid.x = grid.x >> 1; grid.y = grid.y >> 1; --zoom; } if (changed) { this.notifyListeners_(); } this.numMarkers_[marker.MarkerManager_minZoom]--; }; /** * Add many markers at once. * Does not actually update the map, just the internal grid. * * @param {Array of Marker} markers The markers to add. * @param {Number} minZoom The minimum zoom level to display the markers. * @param {Number} opt_maxZoom The maximum zoom level to display the markers. */ MarkerManager.prototype.addMarkers = function (markers, minZoom, opt_maxZoom) { var maxZoom = this.getOptMaxZoom_(opt_maxZoom); for (var i = markers.length - 1; i >= 0; i--) { this.addMarkerBatch_(markers[i], minZoom, maxZoom); } this.numMarkers_[minZoom] += markers.length; }; /** * Returns the value of the optional maximum zoom. This method is defined so * that we have just one place where optional maximum zoom is calculated. * * @param {Number} opt_maxZoom The optinal maximum zoom. * @return The maximum zoom. */ MarkerManager.prototype.getOptMaxZoom_ = function (opt_maxZoom) { return opt_maxZoom || this.maxZoom_; }; /** * Calculates the total number of markers potentially visible at a given * zoom level. * * @param {Number} zoom The zoom level to check. */ MarkerManager.prototype.getMarkerCount = function (zoom) { var total = 0; for (var z = 0; z <= zoom; z++) { total += this.numMarkers_[z]; } return total; }; /** * Returns a marker given latitude, longitude and zoom. If the marker does not * exist, the method will return a new marker. If a new marker is created, * it will NOT be added to the manager. * * @param {Number} lat - the latitude of a marker. * @param {Number} lng - the longitude of a marker. * @param {Number} zoom - the zoom level * @return {GMarker} marker - the marker found at lat and lng */ MarkerManager.prototype.getMarker = function (lat, lng, zoom) { var mPoint = new google.maps.LatLng(lat, lng); var gridPoint = this.getTilePoint_(mPoint, zoom, new google.maps.Size(0, 0, 0, 0)); var marker = new google.maps.Marker({position: mPoint}); var cellArray = this.getGridCellNoCreate_(gridPoint.x, gridPoint.y, zoom); if (cellArray !== undefined) { for (var i = 0; i < cellArray.length; i++) { if (lat === cellArray[i].getPosition().lat() && lng === cellArray[i].getPosition().lng()) { marker = cellArray[i]; } } } return marker; }; /** * Add a single marker to the map. * * @param {Marker} marker The marker to add. * @param {Number} minZoom The minimum zoom level to display the marker. * @param {Number} opt_maxZoom The maximum zoom level to display the marker. */ MarkerManager.prototype.addMarker = function (marker, minZoom, opt_maxZoom) { var maxZoom = this.getOptMaxZoom_(opt_maxZoom); this.addMarkerBatch_(marker, minZoom, maxZoom); var gridPoint = this.getTilePoint_(marker.getPosition(), this.mapZoom_, new google.maps.Size(0, 0, 0, 0)); if (this.isGridPointVisible_(gridPoint) && minZoom <= this.shownBounds_.z && this.shownBounds_.z <= maxZoom) { this.addOverlay_(marker); this.notifyListeners_(); } this.numMarkers_[minZoom]++; }; /** * Helper class to create a bounds of INT ranges. * @param bounds Array.<Object.<string, number>> Bounds object. * @constructor */ function GridBounds(bounds) { // [sw, ne] this.minX = Math.min(bounds[0].x, bounds[1].x); this.maxX = Math.max(bounds[0].x, bounds[1].x); this.minY = Math.min(bounds[0].y, bounds[1].y); this.maxY = Math.max(bounds[0].y, bounds[1].y); } /** * Returns true if this bounds equal the given bounds. * @param {GridBounds} gridBounds GridBounds The bounds to test. * @return {Boolean} This Bounds equals the given GridBounds. */ GridBounds.prototype.equals = function (gridBounds) { if (this.maxX === gridBounds.maxX && this.maxY === gridBounds.maxY && this.minX === gridBounds.minX && this.minY === gridBounds.minY) { return true; } else { return false; } }; /** * Returns true if this bounds (inclusively) contains the given point. * @param {Point} point The point to test. * @return {Boolean} This Bounds contains the given Point. */ GridBounds.prototype.containsPoint = function (point) { var outer = this; return (outer.minX <= point.x && outer.maxX >= point.x && outer.minY <= point.y && outer.maxY >= point.y); }; /** * Get a cell in the grid, creating it first if necessary. * * Optimization candidate * * @param {Number} x The x coordinate of the cell. * @param {Number} y The y coordinate of the cell. * @param {Number} z The z coordinate of the cell. * @return {Array} The cell in the array. */ MarkerManager.prototype.getGridCellCreate_ = function (x, y, z) { var grid = this.grid_[z]; if (x < 0) { x += this.gridWidth_[z]; } var gridCol = grid[x]; if (!gridCol) { gridCol = grid[x] = []; return (gridCol[y] = []); } var gridCell = gridCol[y]; if (!gridCell) { return (gridCol[y] = []); } return gridCell; }; /** * Get a cell in the grid, returning undefined if it does not exist. * * NOTE: Optimized for speed -- otherwise could combine with getGridCellCreate_. * * @param {Number} x The x coordinate of the cell. * @param {Number} y The y coordinate of the cell. * @param {Number} z The z coordinate of the cell. * @return {Array} The cell in the array. */ MarkerManager.prototype.getGridCellNoCreate_ = function (x, y, z) { var grid = this.grid_[z]; if (x < 0) { x += this.gridWidth_[z]; } var gridCol = grid[x]; return gridCol ? gridCol[y] : undefined; }; /** * Turns at geographical bounds into a grid-space bounds. * * @param {LatLngBounds} bounds The geographical bounds. * @param {Number} zoom The zoom level of the bounds. * @param {google.maps.Size} swPadding The padding in pixels to extend beyond the * given bounds. * @param {google.maps.Size} nePadding The padding in pixels to extend beyond the * given bounds. * @return {GridBounds} The bounds in grid space. */ MarkerManager.prototype.getGridBounds_ = function (bounds, zoom, swPadding, nePadding) { zoom = Math.min(zoom, this.maxZoom_); var bl = bounds.getSouthWest(); var tr = bounds.getNorthEast(); var sw = this.getTilePoint_(bl, zoom, swPadding); var ne = this.getTilePoint_(tr, zoom, nePadding); var gw = this.gridWidth_[zoom]; // Crossing the prime meridian requires correction of bounds. if (tr.lng() < bl.lng() || ne.x < sw.x) { sw.x -= gw; } if (ne.x - sw.x + 1 >= gw) { // Computed grid bounds are larger than the world; truncate. sw.x = 0; ne.x = gw - 1; } var gridBounds = new GridBounds([sw, ne]); gridBounds.z = zoom; return gridBounds; }; /** * Gets the grid-space bounds for the current map viewport. * * @return {Bounds} The bounds in grid space. */ MarkerManager.prototype.getMapGridBounds_ = function () { return this.getGridBounds_(this.map_.getBounds(), this.mapZoom_, this.swPadding_, this.nePadding_); }; /** * Event listener for map:movend. * NOTE: Use a timeout so that the user is not blocked * from moving the map. * * Removed this because a a lack of a scopy override/callback function on events. */ MarkerManager.prototype.onMapMoveEnd_ = function () { this.objectSetTimeout_(this, this.updateMarkers_, 0); }; /** * Call a function or evaluate an expression after a specified number of * milliseconds. * * Equivalent to the standard window.setTimeout function, but the given * function executes as a method of this instance. So the function passed to * objectSetTimeout can contain references to this. * objectSetTimeout(this, function () { alert(this.x) }, 1000); * * @param {Object} object The target object. * @param {Function} command The command to run. * @param {Number} milliseconds The delay. * @return {Boolean} Success. */ MarkerManager.prototype.objectSetTimeout_ = function (object, command, milliseconds) { return window.setTimeout(function () { command.call(object); }, milliseconds); }; /** * Is this layer visible? * * Returns visibility setting * * @return {Boolean} Visible */ MarkerManager.prototype.visible = function () { return this.show_ ? true : false; }; /** * Returns true if the manager is hidden. * Otherwise returns false. * @return {Boolean} Hidden */ MarkerManager.prototype.isHidden = function () { return !this.show_; }; /** * Shows the manager if it's currently hidden. */ MarkerManager.prototype.show = function () { this.show_ = true; this.refresh(); }; /** * Hides the manager if it's currently visible */ MarkerManager.prototype.hide = function () { this.show_ = false; this.refresh(); }; /** * Toggles the visibility of the manager. */ MarkerManager.prototype.toggle = function () { this.show_ = !this.show_; this.refresh(); }; /** * Refresh forces the marker-manager into a good state. * <ol> * <li>If never before initialized, shows all the markers.</li> * <li>If previously initialized, removes and re-adds all markers.</li> * </ol> */ MarkerManager.prototype.refresh = function () { if (this.shownMarkers_ > 0) { this.processAll_(this.shownBounds_, this.removeOverlay_); } // An extra check on this.show_ to increase performance (no need to processAll_) if (this.show_) { this.processAll_(this.shownBounds_, this.addOverlay_); } this.notifyListeners_(); }; /** * After the viewport may have changed, add or remove markers as needed. */ MarkerManager.prototype.updateMarkers_ = function () { this.mapZoom_ = this.map_.getZoom(); var newBounds = this.getMapGridBounds_(); // If the move does not include new grid sections, // we have no work to do: if (newBounds.equals(this.shownBounds_) && newBounds.z === this.shownBounds_.z) { return; } if (newBounds.z !== this.shownBounds_.z) { this.processAll_(this.shownBounds_, this.removeOverlay_); if (this.show_) { // performance this.processAll_(newBounds, this.addOverlay_); } } else { // Remove markers: this.rectangleDiff_(this.shownBounds_, newBounds, this.removeCellMarkers_); // Add markers: if (this.show_) { // performance this.rectangleDiff_(newBounds, this.shownBounds_, this.addCellMarkers_); } } this.shownBounds_ = newBounds; this.notifyListeners_(); }; /** * Notify listeners when the state of what is displayed changes. */ MarkerManager.prototype.notifyListeners_ = function () { google.maps.event.trigger(this, 'changed', this.shownBounds_, this.shownMarkers_); }; /** * Process all markers in the bounds provided, using a callback. * * @param {Bounds} bounds The bounds in grid space. * @param {Function} callback The function to call for each marker. */ MarkerManager.prototype.processAll_ = function (bounds, callback) { for (var x = bounds.minX; x <= bounds.maxX; x++) { for (var y = bounds.minY; y <= bounds.maxY; y++) { this.processCellMarkers_(x, y, bounds.z, callback); } } }; /** * Process all markers in the grid cell, using a callback. * * @param {Number} x The x coordinate of the cell. * @param {Number} y The y coordinate of the cell. * @param {Number} z The z coordinate of the cell. * @param {Function} callback The function to call for each marker. */ MarkerManager.prototype.processCellMarkers_ = function (x, y, z, callback) { var cell = this.getGridCellNoCreate_(x, y, z); if (cell) { for (var i = cell.length - 1; i >= 0; i--) { callback(cell[i]); } } }; /** * Remove all markers in a grid cell. * * @param {Number} x The x coordinate of the cell. * @param {Number} y The y coordinate of the cell. * @param {Number} z The z coordinate of the cell. */ MarkerManager.prototype.removeCellMarkers_ = function (x, y, z) { this.processCellMarkers_(x, y, z, this.removeOverlay_); }; /** * Add all markers in a grid cell. * * @param {Number} x The x coordinate of the cell. * @param {Number} y The y coordinate of the cell. * @param {Number} z The z coordinate of the cell. */ MarkerManager.prototype.addCellMarkers_ = function (x, y, z) { this.processCellMarkers_(x, y, z, this.addOverlay_); }; /** * Use the rectangleDiffCoords_ function to process all grid cells * that are in bounds1 but not bounds2, using a callback, and using * the current MarkerManager object as the instance. * * Pass the z parameter to the callback in addition to x and y. * * @param {Bounds} bounds1 The bounds of all points we may process. * @param {Bounds} bounds2 The bounds of points to exclude. * @param {Function} callback The callback function to call * for each grid coordinate (x, y, z). */ MarkerManager.prototype.rectangleDiff_ = function (bounds1, bounds2, callback) { var me = this; me.rectangleDiffCoords_(bounds1, bounds2, function (x, y) { callback.apply(me, [x, y, bounds1.z]); }); }; /** * Calls the function for all points in bounds1, not in bounds2 * * @param {Bounds} bounds1 The bounds of all points we may process. * @param {Bounds} bounds2 The bounds of points to exclude. * @param {Function} callback The callback function to call * for each grid coordinate. */ MarkerManager.prototype.rectangleDiffCoords_ = function (bounds1, bounds2, callback) { var minX1 = bounds1.minX; var minY1 = bounds1.minY; var maxX1 = bounds1.maxX; var maxY1 = bounds1.maxY; var minX2 = bounds2.minX; var minY2 = bounds2.minY; var maxX2 = bounds2.maxX; var maxY2 = bounds2.maxY; var x, y; for (x = minX1; x <= maxX1; x++) { // All x in R1 // All above: for (y = minY1; y <= maxY1 && y < minY2; y++) { // y in R1 above R2 callback(x, y); } // All below: for (y = Math.max(maxY2 + 1, minY1); // y in R1 below R2 y <= maxY1; y++) { callback(x, y); } } for (y = Math.max(minY1, minY2); y <= Math.min(maxY1, maxY2); y++) { // All y in R2 and in R1 // Strictly left: for (x = Math.min(maxX1 + 1, minX2) - 1; x >= minX1; x--) { // x in R1 left of R2 callback(x, y); } // Strictly right: for (x = Math.max(minX1, maxX2 + 1); // x in R1 right of R2 x <= maxX1; x++) { callback(x, y); } } }; /** * Removes value from array. O(N). * * @param {Array} array The array to modify. * @param {any} value The value to remove. * @param {Boolean} opt_notype Flag to disable type checking in equality. * @return {Number} The number of instances of value that were removed. */ MarkerManager.prototype.removeFromArray_ = function (array, value, opt_notype) { var shift = 0; for (var i = 0; i < array.length; ++i) { if (array[i] === value || (opt_notype && array[i] === value)) { array.splice(i--, 1); shift++; } } return shift; }; /** * Projection overlay helper. Helps in calculating * that markers get into the right grid. * @constructor * @param {Map} map The map to manage. **/ function ProjectionHelperOverlay(map) { this.setMap(map); var TILEFACTOR = 8; var TILESIDE = 1 << TILEFACTOR; var RADIUS = 7; this._map = map; this._zoom = -1; this._X0 = this._Y0 = this._X1 = this._Y1 = -1; } ProjectionHelperOverlay.prototype = new google.maps.OverlayView(); /** * Helper function to convert Lng to X * @private * @param {float} lng **/ ProjectionHelperOverlay.prototype.LngToX_ = function (lng) { return (1 + lng / 180); }; /** * Helper function to convert Lat to Y * @private * @param {float} lat **/ ProjectionHelperOverlay.prototype.LatToY_ = function (lat) { var sinofphi = Math.sin(lat * Math.PI / 180); return (1 - 0.5 / Math.PI * Math.log((1 + sinofphi) / (1 - sinofphi))); }; /** * Old school LatLngToPixel * @param {LatLng} latlng google.maps.LatLng object * @param {Number} zoom Zoom level * @return {position} {x: pixelPositionX, y: pixelPositionY} **/ ProjectionHelperOverlay.prototype.LatLngToPixel = function (latlng, zoom) { var map = this._map; var div = this.getProjection().fromLatLngToDivPixel(latlng); var abs = {x: ~~(0.5 + this.LngToX_(latlng.lng()) * (2 << (zoom + 6))), y: ~~(0.5 + this.LatToY_(latlng.lat()) * (2 << (zoom + 6)))}; return abs; }; /** * Draw function only triggers a ready event for * MarkerManager to know projection can proceed to * initialize. */ ProjectionHelperOverlay.prototype.draw = function () { if (!this.ready) { this.ready = true; google.maps.event.trigger(this, 'ready'); } };
JavaScript